34.7. Canceling Queries in Progress
A client application can request cancellation of a command that is still being processed by the server, using the functions described in this section.
PQgetCancelCreates a data structure containing the information needed to cancel a command issued through a particular database connection.
PGcancel *PQgetCancel(PGconn *conn);
PQgetCancelcreates aPGcancelobject given aPGconnconnection object. It will returnNULLif the givenconnisNULLor an invalid connection. ThePGcancelobject is an opaque structure that is not meant to be accessed directly by the application; it can only be passed toPQcancelorPQfreeCancel.PQfreeCancelFrees a data structure created by
PQgetCancel.void PQfreeCancel(PGcancel *cancel);
PQfreeCancelfrees a data object previously created byPQgetCancel.PQcancelRequests that the server abandon processing of the current command.
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
The return value is 1 if the cancel request was successfully dispatched and 0 if not. If not,
errbufis filled with an explanatory error message.errbufmust be a char array of sizeerrbufsize(the recommended size is 256 bytes).Successful dispatch is no guarantee that the request will have any effect, however. If the cancellation is effective, the current command will terminate early and return an error result. If the cancellation fails (say, because the server was already done processing the command), then there will be no visible result at all.
PQcancelcan safely be invoked from a signal handler, if theerrbufis a local variable in the signal handler. ThePGcancelobject is read-only as far asPQcancelis concerned, so it can also be invoked from a thread that is separate from the one manipulating thePGconnobject.
PQrequestCancelPQrequestCancelis a deprecated variant ofPQcancel.int PQrequestCancel(PGconn *conn);
Requests that the server abandon processing of the current command. It operates directly on the
PGconnobject, and in case of failure stores the error message in thePGconnobject (whence it can be retrieved byPQerrorMessage). Although the functionality is the same, this approach is not safe within multiple-thread programs or signal handlers, since it is possible that overwriting thePGconn's error message will mess up the operation currently in progress on the connection.