32.7. Canceling Queries in Progress #
32.7.1. Functions for Sending Cancel Requests #
PQcancelCreate#Prepares a connection over which a cancel request can be sent.
PGcancelConn *PQcancelCreate(PGconn *conn);
PQcancelCreatecreates aPGcancelConnobject, but it won't instantly start sending a cancel request over this connection. A cancel request can be sent over this connection in a blocking manner usingPQcancelBlockingand in a non-blocking manner usingPQcancelStart. The return value can be passed toPQcancelStatusto check if thePGcancelConnobject was created successfully. ThePGcancelConnobject is an opaque structure that is not meant to be accessed directly by the application. ThisPGcancelConnobject can be used to cancel the query that's running on the original connection in a thread-safe way.Many connection parameters of the original client will be reused when setting up the connection for the cancel request. Importantly, if the original connection requires encryption of the connection and/or verification of the target host (using
sslmodeorgssencmode), then the connection for the cancel request is made with these same requirements. Any connection options that are only used during authentication or after authentication of the client are ignored though, because cancellation requests do not require authentication and the connection is closed right after the cancellation request is submitted.Note that when
PQcancelCreatereturns a non-null pointer, you must callPQcancelFinishwhen you are finished with it, in order to dispose of the structure and any associated memory blocks. This must be done even if the cancel request failed or was abandoned.PQcancelBlocking#Requests that the server abandons processing of the current command in a blocking manner.
int PQcancelBlocking(PGcancelConn *cancelConn);
The request is made over the given
PGcancelConn, which needs to be created withPQcancelCreate. The return value ofPQcancelBlockingis 1 if the cancel request was successfully dispatched and 0 if not. If it was unsuccessful, the error message can be retrieved usingPQcancelErrorMessage.Successful dispatch of the cancellation is no guarantee that the request will have any effect, however. If the cancellation is effective, the command being canceled 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.
PQcancelStartPQcancelPoll#Requests that the server abandons processing of the current command in a non-blocking manner.
int PQcancelStart(PGcancelConn *cancelConn); PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);
The request is made over the given
PGcancelConn, which needs to be created withPQcancelCreate. The return value ofPQcancelStartis 1 if the cancellation request could be started and 0 if not. If it was unsuccessful, the error message can be retrieved usingPQcancelErrorMessage.If
PQcancelStartsucceeds, the next stage is to poll libpq so that it can proceed with the cancel connection sequence. UsePQcancelSocketto obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same acrossPQcancelPollcalls.) Loop thus: IfPQcancelPoll(cancelConn)last returnedPGRES_POLLING_READING, wait until the socket is ready to read (as indicated byselect(),poll(), or similar system function). Then callPQcancelPoll(cancelConn)again. Conversely, ifPQcancelPoll(cancelConn)last returnedPGRES_POLLING_WRITING, wait until the socket is ready to write, then callPQcancelPoll(cancelConn)again. On the first iteration, i.e., if you have yet to callPQcancelPoll(cancelConn), behave as if it last returnedPGRES_POLLING_WRITING. Continue this loop untilPQcancelPoll(cancelConn)returnsPGRES_POLLING_FAILED, indicating the connection procedure has failed, orPGRES_POLLING_OK, indicating cancel request was successfully dispatched.Successful dispatch of the cancellation is no guarantee that the request will have any effect, however. If the cancellation is effective, the command being canceled 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.
At any time during connection, the status of the connection can be checked by calling
PQcancelStatus. If this call returnsCONNECTION_BAD, then the cancel procedure has failed; if the call returnsCONNECTION_OK, then cancel request was successfully dispatched. Both of these states are equally detectable from the return value ofPQcancelPoll, described above. Other states might also occur during (and only during) an asynchronous connection procedure. These indicate the current stage of the connection procedure and might be useful to provide feedback to the user for example. These statuses are:CONNECTION_ALLOCATED#Waiting for a call to
PQcancelStartorPQcancelBlocking, to actually open the socket. This is the connection state right after callingPQcancelCreateorPQcancelReset. No connection to the server has been initiated yet at this point. To actually start sending the cancel request usePQcancelStartorPQcancelBlocking.CONNECTION_STARTED#Waiting for connection to be made.
CONNECTION_MADE#Connection OK; waiting to send.
CONNECTION_AWAITING_RESPONSE#Waiting for a response from the server.
CONNECTION_SSL_STARTUP#Negotiating SSL encryption.
CONNECTION_GSS_STARTUP#Negotiating GSS encryption.
Note that, although these constants will remain (in order to maintain compatibility), an application should never rely upon these occurring in a particular order, or at all, or on the status always being one of these documented values. An application might do something like this:
switch(PQcancelStatus(conn)) { case CONNECTION_STARTED: feedback = "Connecting..."; break; case CONNECTION_MADE: feedback = "Connected to server..."; break; . . . default: feedback = "Connecting..."; }The
connect_timeoutconnection parameter is ignored when usingPQcancelPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise,PQcancelStartfollowed by aPQcancelPollloop is equivalent toPQcancelBlocking.PQcancelStatus#Returns the status of the cancel connection.
ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);
The status can be one of a number of values. However, only three of these are seen outside of an asynchronous cancel procedure:
CONNECTION_ALLOCATED,CONNECTION_OKandCONNECTION_BAD. The initial state of aPGcancelConnthat's successfully created usingPQcancelCreateisCONNECTION_ALLOCATED. A cancel request that was successfully dispatched has the statusCONNECTION_OK. A failed cancel attempt is signaled by statusCONNECTION_BAD. An OK status will remain so untilPQcancelFinishorPQcancelResetis called.See the entry for
PQcancelStartwith regards to other status codes that might be returned.Successful dispatch of the cancellation is no guarantee that the request will have any effect, however. If the cancellation is effective, the command being canceled 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.
PQcancelSocket#Obtains the file descriptor number of the cancel connection socket to the server.
int PQcancelSocket(const PGcancelConn *cancelConn);
A valid descriptor will be greater than or equal to 0; a result of -1 indicates that no server connection is currently open. This might change as a result of calling any of the functions in this section on the
PGcancelConn(except forPQcancelErrorMessageandPQcancelSocketitself).-
PQcancelErrorMessage# Returns the error message most recently generated by an operation on the cancel connection.
char *PQcancelErrorMessage(const PGcancelConn *cancelconn);
Nearly all libpq functions that take a
PGcancelConnwill set a message forPQcancelErrorMessageif they fail. Note that by libpq convention, a nonemptyPQcancelErrorMessageresult can consist of multiple lines, and will include a trailing newline. The caller should not free the result directly. It will be freed when the associatedPGcancelConnhandle is passed toPQcancelFinish. The result string should not be expected to remain the same across operations on thePGcancelConnstructure.PQcancelFinish#Closes the cancel connection (if it did not finish sending the cancel request yet). Also frees memory used by the
PGcancelConnobject.void PQcancelFinish(PGcancelConn *cancelConn);
Note that even if the cancel attempt fails (as indicated by
PQcancelStatus), the application should callPQcancelFinishto free the memory used by thePGcancelConnobject. ThePGcancelConnpointer must not be used again afterPQcancelFinishhas been called.PQcancelReset#Resets the
PGcancelConnso it can be reused for a new cancel connection.void PQcancelReset(PGcancelConn *cancelConn);
If the
PGcancelConnis currently used to send a cancel request, then this connection is closed. It will then prepare thePGcancelConnobject such that it can be used to send a new cancel request.This can be used to create one
PGcancelConnfor aPGconnand reuse it multiple times throughout the lifetime of the originalPGconn.
32.7.2. Obsolete Functions for Sending Cancel Requests #
These functions represent older methods of sending cancel requests. Although they still work, they are deprecated due to not sending the cancel requests in an encrypted manner, even when the original connection specified sslmode or gssencmode to require encryption. Thus these older methods are heavily discouraged from being used in new code, and it is recommended to change existing code to use the new functions instead.
PQgetCancel#Creates a data structure containing the information needed to cancel a command using
PQcancel.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.PQfreeCancel#Frees a data structure created by
PQgetCancel.void PQfreeCancel(PGcancel *cancel);
PQfreeCancelfrees a data object previously created byPQgetCancel.PQcancel#PQcancelis a deprecated and insecure variant ofPQcancelBlocking, but one that can be used safely from within a signal handler.int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
PQcancelonly exists because of backwards compatibility reasons.PQcancelBlockingshould be used instead. The only benefit thatPQcancelhas is that it can be safely invoked from a signal handler, if theerrbufis a local variable in the signal handler. However, this is generally not considered a big enough benefit to be worth the security issues that this function has.The
PGcancelobject is read-only as far asPQcancelis concerned, so it can also be invoked from a thread that is separate from the one manipulating thePGconnobject.The return value of
PQcancelis 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).
PQrequestCancel#PQrequestCancelis a deprecated and insecure variant ofPQcancelBlocking.int PQrequestCancel(PGconn *conn);
PQrequestCancelonly exists because of backwards compatibility reasons.PQcancelBlockingshould be used instead. There is no benefit to usingPQrequestCanceloverPQcancelBlocking.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.