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);
PQcancelCreate
creates aPGcancelConn
object, 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 usingPQcancelBlocking
and in a non-blocking manner usingPQcancelStart
. The return value can be passed toPQcancelStatus
to check if thePGcancelConn
object was created successfully. ThePGcancelConn
object is an opaque structure that is not meant to be accessed directly by the application. ThisPGcancelConn
object 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
sslmode
orgssencmode
), 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
PQcancelCreate
returns a non-null pointer, you must callPQcancelFinish
when 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 ofPQcancelBlocking
is 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.
PQcancelStart
PQcancelPoll
#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 ofPQcancelStart
is 1 if the cancellation request could be started and 0 if not. If it was unsuccessful, the error message can be retrieved usingPQcancelErrorMessage
.If
PQcancelStart
succeeds, the next stage is to poll libpq so that it can proceed with the cancel connection sequence. UsePQcancelSocket
to obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same acrossPQcancelPoll
calls.) 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
PQcancelStart
orPQcancelBlocking
, to actually open the socket. This is the connection state right after callingPQcancelCreate
orPQcancelReset
. No connection to the server has been initiated yet at this point. To actually start sending the cancel request usePQcancelStart
orPQcancelBlocking
.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_timeout
connection parameter is ignored when usingPQcancelPoll
; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise,PQcancelStart
followed by aPQcancelPoll
loop 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_OK
andCONNECTION_BAD
. The initial state of aPGcancelConn
that's successfully created usingPQcancelCreate
isCONNECTION_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 untilPQcancelFinish
orPQcancelReset
is called.See the entry for
PQcancelStart
with 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 forPQcancelErrorMessage
andPQcancelSocket
itself).-
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
PGcancelConn
will set a message forPQcancelErrorMessage
if they fail. Note that by libpq convention, a nonemptyPQcancelErrorMessage
result 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 associatedPGcancelConn
handle is passed toPQcancelFinish
. The result string should not be expected to remain the same across operations on thePGcancelConn
structure.PQcancelFinish
#Closes the cancel connection (if it did not finish sending the cancel request yet). Also frees memory used by the
PGcancelConn
object.void PQcancelFinish(PGcancelConn *cancelConn);
Note that even if the cancel attempt fails (as indicated by
PQcancelStatus
), the application should callPQcancelFinish
to free the memory used by thePGcancelConn
object. ThePGcancelConn
pointer must not be used again afterPQcancelFinish
has been called.PQcancelReset
#Resets the
PGcancelConn
so it can be reused for a new cancel connection.void PQcancelReset(PGcancelConn *cancelConn);
If the
PGcancelConn
is currently used to send a cancel request, then this connection is closed. It will then prepare thePGcancelConn
object such that it can be used to send a new cancel request.This can be used to create one
PGcancelConn
for aPGconn
and 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);
PQgetCancel
creates aPGcancel
object given aPGconn
connection object. It will returnNULL
if the givenconn
isNULL
or an invalid connection. ThePGcancel
object is an opaque structure that is not meant to be accessed directly by the application; it can only be passed toPQcancel
orPQfreeCancel
.PQfreeCancel
#Frees a data structure created by
PQgetCancel
.void PQfreeCancel(PGcancel *cancel);
PQfreeCancel
frees a data object previously created byPQgetCancel
.PQcancel
#PQcancel
is 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);
PQcancel
only exists because of backwards compatibility reasons.PQcancelBlocking
should be used instead. The only benefit thatPQcancel
has is that it can be safely invoked from a signal handler, if theerrbuf
is 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
PGcancel
object is read-only as far asPQcancel
is concerned, so it can also be invoked from a thread that is separate from the one manipulating thePGconn
object.The return value of
PQcancel
is 1 if the cancel request was successfully dispatched and 0 if not. If not,errbuf
is filled with an explanatory error message.errbuf
must be a char array of sizeerrbufsize
(the recommended size is 256 bytes).
PQrequestCancel
#PQrequestCancel
is a deprecated and insecure variant ofPQcancelBlocking
.int PQrequestCancel(PGconn *conn);
PQrequestCancel
only exists because of backwards compatibility reasons.PQcancelBlocking
should be used instead. There is no benefit to usingPQrequestCancel
overPQcancelBlocking
.Requests that the server abandon processing of the current command. It operates directly on the
PGconn
object, and in case of failure stores the error message in thePGconn
object (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.