31.12. Обработка замечаний
Сообщения с замечаниями и предупреждениями, выдаваемые сервером, не возвращаются функциями, выполняющими запросы, так как они не свидетельствуют об ошибке в запросе. Вместо этого они передаются функции обработки замечаний и после завершения этой функции выполнение продолжается как обычно. Стандартная функция обработки замечаний выводит сообщение в stderr
, но приложение может переопределить это поведение, предоставив собственный обработчик.
По историческим причинам обработка замечаний выполняется на двух уровнях, приёмником замечаний и обработчиком замечаний. По умолчанию приёмник замечаний форматирует замечание и передаёт сформированную строку обработчику замечаний для вывода. Однако приложения, которые реализуют свой приёмник замечаний, обычно просто игнорируют слой обработчика и выполняют все действия в коде приёмника.
Функция PQsetNoticeReceiver
устанавливает или возвращает текущий приёмник замечаний для объекта соединения. Подобным образом, PQsetNoticeProcessor
устанавливает или возвращает текущий обработчик замечаний.
typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res); PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg); typedef void (*PQnoticeProcessor) (void *arg, const char *message); PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg);
Каждая из этих функций возвращает указатель на ранее установленный приёмник или обработчик замечаний и устанавливает новый указатель. Если ей передаётся нулевой указатель, она ничего не делает, только возвращает текущий указатель.
Когда сообщение с замечанием или предупреждением поступает от сервера, либо выдаётся самой библиотекой libpq, вызывается функция приёмника замечания. Сообщение передаётся ей в виде состояния PGRES_NONFATAL_ERROR
объекта PGresult
. (Это позволяет приёмнику извлечь из него отдельные поля, используя PQresultErrorField
, либо получить полное подготовленное сообщение, вызвав PQresultErrorMessage
.) Ей также передаётся тот же неопределённый указатель, что был передан функции PQsetNoticeReceiver
. (Этот указатель может пригодиться для обращения к внутреннему состоянию приложения при необходимости.)
Стандартный приёмник замечаний просто извлекает сообщение (вызывая PQresultErrorMessage
) и передаёт его обработчику замечаний.
Обработчик замечаний отвечает за обработку сообщения с замечанием или предупреждением в текстовом виде. Ему передаётся строка с текстом сообщения (включающая завершающий символ новой строки) и неопределённый указатель, который был передан функции PQsetNoticeProcessor
. (Этот указатель может пригодиться для обращения к внутреннему состоянию приложения при необходимости.)
Стандартный обработчик замечаний прост:
static void defaultNoticeProcessor(void *arg, const char *message) { fprintf(stderr, "%s", message); }
Установив приёмник или обработчик замечаний, вы можете ожидать, что эта функция будет вызываться, пока будут существовать объект PGconn
или объекты PGresult
, созданные с ней. Когда создаётся PGresult
, указатели текущих обработчиков замечаний, установленные в PGconn
, копируются в PGresult
для возможного использования функциями вроде PQgetvalue
.
31.12. Notice Processing
Notice and warning messages generated by the server are not returned by the query execution functions, since they do not imply failure of the query. Instead they are passed to a notice handling function, and execution continues normally after the handler returns. The default notice handling function prints the message on stderr
, but the application can override this behavior by supplying its own handling function.
For historical reasons, there are two levels of notice handling, called the notice receiver and notice processor. The default behavior is for the notice receiver to format the notice and pass a string to the notice processor for printing. However, an application that chooses to provide its own notice receiver will typically ignore the notice processor layer and just do all the work in the notice receiver.
The function PQsetNoticeReceiver
sets or examines the current notice receiver for a connection object. Similarly, PQsetNoticeProcessor
sets or examines the current notice processor.
typedef void (*PQnoticeReceiver) (void *arg, const PGresult *res); PQnoticeReceiver PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg); typedef void (*PQnoticeProcessor) (void *arg, const char *message); PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg);
Each of these functions returns the previous notice receiver or processor function pointer, and sets the new value. If you supply a null function pointer, no action is taken, but the current pointer is returned.
When a notice or warning message is received from the server, or generated internally by libpq, the notice receiver function is called. It is passed the message in the form of a PGRES_NONFATAL_ERROR
PGresult
. (This allows the receiver to extract individual fields using PQresultErrorField
, or the complete preformatted message using PQresultErrorMessage
.) The same void pointer passed to PQsetNoticeReceiver
is also passed. (This pointer can be used to access application-specific state if needed.)
The default notice receiver simply extracts the message (using PQresultErrorMessage
) and passes it to the notice processor.
The notice processor is responsible for handling a notice or warning message given in text form. It is passed the string text of the message (including a trailing newline), plus a void pointer that is the same one passed to PQsetNoticeProcessor
. (This pointer can be used to access application-specific state if needed.)
The default notice processor is simply:
static void defaultNoticeProcessor(void *arg, const char *message) { fprintf(stderr, "%s", message); }
Once you have set a notice receiver or processor, you should expect that that function could be called as long as either the PGconn
object or PGresult
objects made from it exist. At creation of a PGresult
, the PGconn
's current notice handling pointers are copied into the PGresult
for possible use by functions like PQgetvalue
.