33.7. Отмена запросов в процессе выполнения
Клиентское приложение может запросить отмену команды, которая ещё обрабатывается сервером, используя функции, описанные в этом разделе.
PQgetCancel
Создаёт структуру данных, содержащую информацию, необходимую для отмены команды, запущенной через конкретное подключение к базе данных.
PGcancel *PQgetCancel(PGconn *conn);
Функция
PQgetCancel
создаёт объектPGcancel
, получив объектPGconn
, описывающий подключение. Она возвратитNULL
, если параметрconn
равенNULL
или представляет недействительное подключение. ОбъектPGcancel
является непрозрачной структурой, которая не предназначена для того, чтобы приложение обращалось к ней напрямую; её можно только передавать функцииPQcancel
илиPQfreeCancel
.PQfreeCancel
Освобождает память, занимаемую структурой данных, созданной функцией
PQgetCancel
.void PQfreeCancel(PGcancel *cancel);
PQfreeCancel
освобождает память, занимаемую объектом, предварительно созданным функциейPQgetCancel
.PQcancel
Требует, чтобы сервер прекратил обработку текущей команды.
int PQcancel(PGcancel *cancel, char *errbuf, int errbufsize);
Возвращаемое значение равно 1, если запрос на отмену был успешно отправлен, и 0 в противном случае. В случае неудачной отправки
errbuf
заполняется пояснительным сообщением об ошибке.errbuf
должен быть массивом символов, имеющим размерerrbufsize
(рекомендуемый размер составляет 256 байт).Успешная отправка ещё не является гарантией того, что запрос будет иметь какой-то эффект. Если отмена сработала, текущая команда завершится досрочно и возвратит в качестве результата ошибку. Если же отмена не получится (например, потому, что сервер уже завершил обработку команды), тогда вообще не будет видимого результата.
PQcancel
можно безопасно вызывать из обработчика сигнала, еслиerrbuf
является локальной переменной в обработчике сигнала. ОбъектPGcancel
доступен только в режиме чтения, пока речь идёт о функцииPQcancel
, поэтому её можно также вызывать из потока, отдельного от того, который управляет объектомPGconn
.
PQrequestCancel
PQrequestCancel
является устаревшим аналогом функцииPQcancel
.int PQrequestCancel(PGconn *conn);
Выдаёт запрос на то, чтобы сервер прекратил обработку текущей команды. Функция работает напрямую с объектом
PGconn
и в случае сбоя сохраняет сообщение об ошибке в объектеPGconn
(откуда его можно извлечь с помощьюPQerrorMessage
). Хотя функциональность та же самая, этот подход небезопасен для многопоточных программ или обработчиков сигналов, поскольку перезапись сообщения об ошибке, хранящегося в объектеPGconn
, может помешать ходу операции, выполняемой через данное подключение.
33.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.
PQgetCancel
Creates a data structure containing the information needed to cancel a command issued through a particular database connection.
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
Requests 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,
errbuf
is filled with an explanatory error message.errbuf
must 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.
PQcancel
can safely be invoked from a signal handler, if theerrbuf
is a local variable in the signal handler. ThePGcancel
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.
PQrequestCancel
PQrequestCancel
is a deprecated variant ofPQcancel
.int PQrequestCancel(PGconn *conn);
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.