36.7. Отмена запросов в процессе выполнения #

36.7.1. Функции для отправки запросов отмены #

PQcancelCreate #

Готовит соединение для отправки запросов отмены.

PGcancelConn *PQcancelCreate(PGconn *conn);

Функция PQcancelCreate создаёт объект PGcancelConn, однако отправка запросов отмены не начинается сразу. Запрос отмены можно отправить через это соединение блокирующим способом, используя PQcancelBlocking, и неблокирующим, используя PQcancelStart. Полученное значение можно передать через PQcancelStatus для проверки, что объект PGcancelConn создан успешно. Объект PGcancelConn является непрозрачной структурой, которая не предполагает доступ напрямую через приложение. Этот объект PGcancelConn можно использовать для потокобезопасной отмены запроса, который выполняется на исходном соединении.

При настройке соединения для отправки запроса отмены переиспользуются многие параметры соединения исходного клиента. Важно помнить, что если исходное соединение требует шифрования соединения и/или проверки целевого узла (через sslmode или gssencmode), то соединение для запроса отмены создаётся с такими же требованиями. Любые параметры соединения, используемые только во время или сразу же после аутентификации клиента, игнорируются, поскольку запросы отмены не требуют аутентификации, а соединение закрывается сразу после отправки запроса отмены.

Заметьте, что если функция PQconnectStart возвращает ненулевой указатель, то, закончив его использование, вы должны вызвать PQcancelFinish, чтобы освободить полученную структуру и все связанные с ней блоки памяти. Это нужно сделать, даже если попытка подключения не последует или окажется неуспешной.

PQcancelBlocking #

Требует, чтобы сервер прекратил обработку текущей команды блокирующим способом.

int PQcancelBlocking(PGcancelConn *cancelConn);

Запрос отправляется по заданному соединению PGcancelConn, которое необходимо создать функцией PQcancelCreate. PQcancelBlocking возвращает 1, если запрос отмены успешно отправлен, и 0 в противном случае. В случае неудачи сообщение об ошибке можно получить с помощью функции PQcancelErrorMessage .

Успешная отправка отмены ещё не является гарантией того, что запрос будет иметь какой-то эффект. Если отмена сработала, текущая команда завершится досрочно и возвратит в качестве результата ошибку. Если же отмена не получится (например, потому, что сервер уже завершил обработку команды), тогда видимого результата не будет вовсе.

PQcancelStart
PQcancelPoll #

Выдаёт запрос на то, чтобы сервер прерывал выполнение текущей команды неблокирующим способом.

int PQcancelStart(PGcancelConn *cancelConn);

PostgresPollingStatusType PQcancelPoll(PGcancelConn *cancelConn);

Запрос отправляется по заданному соединению PGcancelConn, которое необходимо создать функцией PQcancelCreate. PQcancelStart возвращает 1, если запрос отмены может быть отправлен, и 0 в противном случае. В случае неудачи сообщение об ошибке можно получить с помощью функции PQcancelErrorMessage .

Если вызов PQcancelStart оказался успешным, нужно опросить libpq для продолжения процедуры подключения. Вызовите PQcancelSocket для получения дескриптора нижележащего сокета, через который устанавливается соединение с базой данных. (Внимание: этот сокет может меняться от вызова к вызову PQcancelPoll.) Организуйте цикл таким образом: если PQcancelPoll(cancelConn) при последнем вызове возвращает PGRES_POLLING_READING, ожидайте, пока сокет не окажется готовым для чтения (это покажет функция select(), poll() или подобная системная функция). Затем снова вызовите PQcancelPoll(cancelConn). Если же PQcancelPoll(cancelConn) при последнем вызове возвратила PGRES_POLLING_WRITING, дождитесь готовности сокета к записи, а затем снова вызовите PQcancelPoll(cancelConn). На первой итерации, то есть когда вы ещё не вызывали PQcancelPoll(cancelConn), реализуйте то же поведение, что и после получения PGRES_POLLING_WRITING. Продолжайте этот цикл, пока PQcancelPoll(cancelConn) не выдаст значение PGRES_POLLING_FAILED, сигнализирующее об ошибке при установлении соединения, или PGRES_POLLING_OK, показывающее, что соединение установлено успешно.

Успешная отправка отмены ещё не является гарантией того, что запрос будет иметь какой-то эффект. Если отмена сработала, текущая команда завершится досрочно и возвратит в качестве результата ошибку. Если же отмена не получится (например, потому, что сервер уже завершил обработку команды), тогда видимого результата не будет вовсе.

В любое время в процессе подключения его состояние можно проверить, вызвав PQcancelStatus. Если этот вызов возвратит CONNECTION_BAD, значит, процедура отмены завершилась сбоем; если вызов возвратит CONNECTION_OK, значит, запрос отмены успешно отправлен. Оба эти состояния можно определить на основе возвращаемого значения функции PQcancelPoll, описанной выше. Другие состояния могут также иметь место в течение (и только в течение) асинхронной процедуры подключения. Они показывают текущую стадию процедуры подключения и могут быть полезны, например, для предоставления обратной связи пользователю. Вот эти состояния:

CONNECTION_ALLOCATED #

Ожидание, когда вызов функции PQcancelStart или PQcancelBlocking фактически откроет сокет. Это этап соединения сразу после вызова PQcancelCreate или PQcancelReset, на котором соединение с сервером ещё не инициализировано. Чтобы фактически начать отправку запроса отмены, используйте PQcancelStart или PQcancelBlocking.

CONNECTION_STARTED #

Ожидание, пока соединение будет установлено.

CONNECTION_MADE #

Соединение установлено; ожидание отправки.

CONNECTION_AWAITING_RESPONSE #

Ожидание ответа от сервера.

CONNECTION_SSL_STARTUP #

Согласование SSL-шифрования.

CONNECTION_GSS_STARTUP #

Согласование GSS-шифрования.

Заметьте, что, хотя эти константы и сохранятся (для поддержания совместимости), приложение никогда не должно полагаться на то, что они появятся в каком-то конкретном порядке или вообще появятся, а также на то, что состояние всегда примет одно из этих документированных значений. Приложение может сделать что-то наподобие:

switch(PQcancelStatus(conn))
{
        case CONNECTION_STARTED:
            feedback = "Подключение...";
            break;

        case CONNECTION_MADE:
            feedback = "Подключён к серверу...";
            break;
.
.
.
        default:
            feedback = "Подключение...";
}

Параметр подключения connect_timeout игнорируется, когда используется PQcancelPoll; именно приложение отвечает за принятие решения о том, является ли истекшее время чрезмерным. В противном случае вызов PQcancelStart с последующим вызовом PQcancelPoll в цикле будут эквивалентны вызову PQcancelBlocking.

PQcancelStatus #

Возвращает состояние подключения для отмены.

ConnStatusType PQcancelStatus(const PGcancelConn *cancelConn);

Статус может принимать одно из ряда значений. Однако только три из них видны извне процедуры асинхронной отмены: CONNECTION_ALLOCATED, CONNECTION_OK и CONNECTION_BAD. Изначальное состояние подключения PGcancelConn, успешно созданного через PQcancelCreate, — CONNECTION_ALLOCATED. Успешно отправленный запрос отмены имеет статус CONNECTION_OK. О неудачной попытке отмены сигнализирует статус CONNECTION_BAD. Обычно статус OK остаётся таковым до вызова PQcancelFinish или PQcancelReset.

О других кодах состояния, которые могут выдать эти функции, можно узнать в описании PQcancelStart.

Успешная отправка отмены ещё не является гарантией того, что запрос будет иметь какой-то эффект. Если отмена сработала, текущая команда завершится досрочно и возвратит в качестве результата ошибку. Если же отмена не получится (например, потому, что сервер уже завершил обработку команды), тогда видимого результата не будет вовсе.

PQcancelSocket #

Получает номер файлового дескриптора для сокета отмены соединения с сервером.

int PQcancelSocket(const PGcancelConn *cancelConn);

Действительный дескриптор будет больше или равен 0; значение -1 показывает, что в данный момент не открыто ни одного соединения с сервером. Значение может измениться в результате вызова любой функции в этом разделе в PGcancelConn (кроме PQcancelErrorMessage и самой PQcancelSocket).

PQcancelErrorMessage #

Возвращает сообщение об ошибке, наиболее недавно сгенерированное операцией отмены соединения.

char *PQcancelErrorMessage(const PGcancelConn *cancelconn);

Почти все функции библиотеки libpq, принимающие PGcancelConn, в случае сбоя сформируют сообщение для PQcancelErrorMessage . Обратите внимание, что по соглашениям, принятым в libpq, непустой результат функции PQcancelErrorMessage может состоять из нескольких строк и будет включать завершающий символ новой строки. Вызывающая функция не должна освобождать память, на которую указывает возвращаемое значение, напрямую. Она будет освобождена, когда связанный с ней дескриптор PGcancelConn будет передан функции PQcancelFinish. Не стоит ожидать, что результирующая строка останется той же самой при выполнении нескольких операций со структурой PGcancelConn.

PQcancelFinish #

Закрывает соединение для отмены (если отправка запроса отмены ещё не завершена). Также освобождает память, используемую объектом PGcancelConn.

void PQcancelFinish(PGcancelConn *cancelConn);

Обратите внимание, что даже если попытка отмены потерпела неудачу (как показывает PQcancelStatus), приложение все равно должно вызвать PQcancelFinish, чтобы освободить память, используемую объектом PGcancelConn. Указатель PGcancelConn не должен использоваться повторно после того, как была вызвана функция PQcancelFinish.

PQcancelReset #

Переустанавливает PGcancelConn в целях повторного использования для нового соединения для отмены.

void PQcancelReset(PGcancelConn *cancelConn);

Если PGcancelConn используется для отправки запроса отмены, соединение закрывается. Позже будет подготовлен объект PGcancelConn, чтобы через него можно было отправить новый запрос отмены.

Это можно использовать для создания PGcancelConn для PGconn и многократно его переиспользовать на протяжении работы исходного PGconn.

36.7.2. Устаревшие функции для отправки запросов отмены #

Через данные функции раньше отправлялись запросы отмены. Хотя эти функции всё ещё работают, они признаны устаревшими, поскольку отправляют запросы отмены незашифрованными, даже если в исходном соединении указано требование шифрования sslmode или gssencmode. По этой причине крайне не рекомендуется использовать их в новом коде, а так же лучше изменить существующий код и вписать в него новые функции.

PQgetCancel #

Создаёт структуру данных, содержащую информацию, необходимую для отмены команды, запущенной через PQcancel.

PGcancel *PQgetCancel(PGconn *conn);

Функция PQgetCancel создаёт объект PGcancel, получив объект PGconn, описывающий подключение. Она возвратит NULL, если параметр conn равен NULL или представляет недействительное подключение. Объект PGcancel является непрозрачной структурой, которая не предназначена для того, чтобы приложение обращалось к ней напрямую; её можно только передавать функции PQcancel или PQfreeCancel.

PQfreeCancel #

Освобождает память, занимаемую структурой данных, созданной функцией PQgetCancel.

void PQfreeCancel(PGcancel *cancel);

PQfreeCancel освобождает память, занимаемую объектом, предварительно созданным функцией PQgetCancel.

PQcancel #

PQcancel является устаревшим и небезопасным аналогом функции PQcancelBlocking, но её можно безопасно использовать в рамках обработчика сигналов.

int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);

Функция PQcancel существует только в целях обратной совместимости. Вместо неё необходимо использовать PQcancelBlocking. Единственное преимущество PQcancel состоит в том, что её можно безопасно вызывать из обработчика сигнала, если errbuf является локальной переменной в таком обработчике. Однако это преимущество не исключает проблем с безопасностью, связанных с этой функцией, и не является весомой причиной для её использования.

Объект PGcancel доступен только в режиме чтения, пока речь идёт о функции PQcancel, поэтому её можно также вызывать из потока, отдельного от того, который управляет объектом PGconn.

Возвращаемое функцией PQcancel значение равно 1, если запрос на отмену был успешно отправлен, и 0 в противном случае. В случае неудачной отправки errbuf заполняется пояснительным сообщением об ошибке. errbuf должен быть массивом символов, имеющим размер errbufsize (рекомендуемый размер составляет 256 байт).

PQrequestCancel #

PQrequestCancel является устаревшим и небезопасным аналогом функции PQcancelBlocking.

int PQrequestCancel(PGconn *conn);

Функция PQrequestCancel существует только в целях обратной совместимости. Вместо неё необходимо использовать PQcancelBlocking. Нет никаких преимуществ использования PQrequestCancel вместо PQcancelBlocking.

Выдаёт запрос на то, чтобы сервер прекратил обработку текущей команды. Функция работает напрямую с объектом PGconn и в случае сбоя сохраняет сообщение об ошибке в объекте PGconn (откуда его можно извлечь с помощью PQerrorMessage ). Хотя функциональность та же самая, этот подход небезопасен для многопоточных программ или обработчиков сигналов, поскольку перезапись сообщения об ошибке, хранящегося в объекте PGconn, может помешать ходу операции, выполняемой через данное подключение.

36.7. Canceling Queries in Progress #

36.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 a PGcancelConn 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 using PQcancelBlocking and in a non-blocking manner using PQcancelStart. The return value can be passed to PQcancelStatus to check if the PGcancelConn object was created successfully. The PGcancelConn object is an opaque structure that is not meant to be accessed directly by the application. This PGcancelConn 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 or gssencmode), 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 call PQcancelFinish 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 with PQcancelCreate. The return value of PQcancelBlocking is 1 if the cancel request was successfully dispatched and 0 if not. If it was unsuccessful, the error message can be retrieved using PQcancelErrorMessage .

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 with PQcancelCreate. The return value of PQcancelStart is 1 if the cancellation request could be started and 0 if not. If it was unsuccessful, the error message can be retrieved using PQcancelErrorMessage .

If PQcancelStart succeeds, the next stage is to poll libpq so that it can proceed with the cancel connection sequence. Use PQcancelSocket to obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same across PQcancelPoll calls.) Loop thus: If PQcancelPoll(cancelConn) last returned PGRES_POLLING_READING, wait until the socket is ready to read (as indicated by select(), poll(), or similar system function). Then call PQcancelPoll(cancelConn) again. Conversely, if PQcancelPoll(cancelConn) last returned PGRES_POLLING_WRITING, wait until the socket is ready to write, then call PQcancelPoll(cancelConn) again. On the first iteration, i.e., if you have yet to call PQcancelPoll(cancelConn), behave as if it last returned PGRES_POLLING_WRITING. Continue this loop until PQcancelPoll(cancelConn) returns PGRES_POLLING_FAILED, indicating the connection procedure has failed, or PGRES_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 returns CONNECTION_BAD, then the cancel procedure has failed; if the call returns CONNECTION_OK, then cancel request was successfully dispatched. Both of these states are equally detectable from the return value of PQcancelPoll, 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 or PQcancelBlocking, to actually open the socket. This is the connection state right after calling PQcancelCreate or PQcancelReset. No connection to the server has been initiated yet at this point. To actually start sending the cancel request use PQcancelStart or PQcancelBlocking.

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 using PQcancelPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, PQcancelStart followed by a PQcancelPoll loop is equivalent to PQcancelBlocking.

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 and CONNECTION_BAD. The initial state of a PGcancelConn that's successfully created using PQcancelCreate is CONNECTION_ALLOCATED. A cancel request that was successfully dispatched has the status CONNECTION_OK. A failed cancel attempt is signaled by status CONNECTION_BAD. An OK status will remain so until PQcancelFinish or PQcancelReset 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 for PQcancelErrorMessage and PQcancelSocket 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 for PQcancelErrorMessage if they fail. Note that by libpq convention, a nonempty PQcancelErrorMessage 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 associated PGcancelConn handle is passed to PQcancelFinish. The result string should not be expected to remain the same across operations on the PGcancelConn 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 call PQcancelFinish to free the memory used by the PGcancelConn object. The PGcancelConn pointer must not be used again after PQcancelFinish 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 the PGcancelConn object such that it can be used to send a new cancel request.

This can be used to create one PGcancelConn for a PGconn and reuse it multiple times throughout the lifetime of the original PGconn.

36.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 a PGcancel object given a PGconn connection object. It will return NULL if the given conn is NULL or an invalid connection. The PGcancel object is an opaque structure that is not meant to be accessed directly by the application; it can only be passed to PQcancel or PQfreeCancel.

PQfreeCancel #

Frees a data structure created by PQgetCancel.

void PQfreeCancel(PGcancel *cancel);

PQfreeCancel frees a data object previously created by PQgetCancel.

PQcancel #

PQcancel is a deprecated and insecure variant of PQcancelBlocking, 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 that PQcancel has is that it can be safely invoked from a signal handler, if the errbuf 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 as PQcancel is concerned, so it can also be invoked from a thread that is separate from the one manipulating the PGconn 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 size errbufsize (the recommended size is 256 bytes).

PQrequestCancel #

PQrequestCancel is a deprecated and insecure variant of PQcancelBlocking.

int PQrequestCancel(PGconn *conn);

PQrequestCancel only exists because of backwards compatibility reasons. PQcancelBlocking should be used instead. There is no benefit to using PQrequestCancel over PQcancelBlocking.

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 the PGconn object (whence it can be retrieved by PQerrorMessage ). Although the functionality is the same, this approach is not safe within multiple-thread programs or signal handlers, since it is possible that overwriting the PGconn's error message will mess up the operation currently in progress on the connection.

FAQ