Asynchronous Query Processing

The PQexec function is adequate for submitting queries in simple synchronous applications. However, it has a couple of major deficiencies:

Older programs that used this functionality as well as PQputline and PQputnbytes could block waiting to send data to the backend. To address that issue, the function PQsetnonblocking was added.

Old applications can neglect to use PQsetnonblocking and get the older potentially blocking behavior. Newer programs can use PQsetnonblocking to achieve a completely non-blocking connection to the backend.

Asynchronous Query Functions

PQsocket

PQsocket obtains the file descriptor number for the backend connection socket. A valid descriptor will be >= 0; a result of -1 indicates that no backend connection is currently open.
int PQsocket(const PGconn *conn);
Use PQsocket to obtain the backend socket descriptor in preparation for executing select(). This allows an application using a blocking connection to wait for either backend responses or other conditions. If the result of select() indicates that data can be read from the backend socket, then PQconsumeInput should be called to read the data; after which, PQisBusy, PQgetResult, and/or PQnotifies can be used to process the response.

Non-blocking connections (that have used PQsetnonblocking) should not use select until PQflush has returned 0 indicating that there is no buffered data waiting to be sent to the backend.

A typical frontend using these functions will have a main loop that uses select() to wait for all the conditions that it must respond to. One of the conditions will be input available from the backend, which in select's terms is readable data on the file descriptor identified by PQsocket. When the main loop detects input ready, it should call PQconsumeInput to read the input. It can then call PQisBusy, followed by PQgetResult if PQisBusy returns false (0). It can also call PQnotifies to detect NOTIFY messages (see the Section called Asynchronous Notification).

A frontend that uses PQsendQuery/PQgetResult can also attempt to cancel a query that is still being processed by the backend.