9.28. Триггерные функции
Тогда как в большинстве случаев использование триггеров подразумевает написание пользовательских триггерных функций, в Postgres Pro имеется несколько встроенных триггерных функций, которые можно использовать непосредственно в пользовательских триггерах. Эти функции показаны в Таблице 9.102. (Существуют и другие встроенные триггерные функции, реализующие ограничения внешнего ключа и отложенные ограничения по индексам. Однако они не документированы, так как пользователям не нужно использовать их непосредственно.)
Подробнее о создании триггеров можно узнать в описании CREATE TRIGGER.
Таблица 9.102. Встроенные триггерные функции
Функция Описание Пример использования |
---|
Предотвращает изменения, не меняющие данные. Подробнее об этом рассказывается ниже.
|
Автоматически обновляет содержимое столбца
|
Автоматически обновляет содержимое столбца
|
Функция suppress_redundant_updates_trigger
, применяемая в качестве триггера BEFORE UPDATE
на уровне строк, предотвратит внесение изменений, при которых данные в строке фактически не меняются. Тем самым переопределяется обычное поведение, когда изменение физической строки происходит вне зависимости от того, были ли изменены данные. (Обычное поведение не предполагает сравнения данных, поэтому операции изменения выполняются быстрее, и в ряде случаев именно это поведение желательно.)
В идеале следует избегать операций изменения, которые фактически не меняют данные в записях. Подобные ненужные изменения могут обходиться дорого, особенно когда требуется обновлять множество индексов, к тому же впоследствии базу данных придётся очищать от «мёртвых» строк. Однако выявить такие изменения в клиентском коде бывает сложно, если вообще возможно, а при составлении соответствующих проверочных выражений легко допустить ошибку. В качестве альтернативного решения можно использовать функцию suppress_redundant_updates_trigger
, которая опускает изменения, не меняющие данные. Однако использовать её следует с осторожностью. Данный триггер выполняется для каждой записи довольно быстро, но всё же не мгновенно, так что если большинство затронутых записей фактически изменяется, с этим триггером операция изменения в среднем замедлится.
Функцию suppress_redundant_updates_trigger
можно привязать к таблице так:
CREATE TRIGGER z_min_update BEFORE UPDATE ON tablename FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();
В большинстве случаев этот триггер должен вызываться для каждой строки последним, чтобы он не перекрыл другие триггеры, которым может понадобиться изменить строку. С учётом того, что триггеры вызываются по порядку сортировки их имён, имя для него нужно выбирать таким, чтобы оно было последним среди имён всех триггеров, которые могут быть в таблице. (Из этого соображения выбран префикс «z» в данном примере.)
34.13. 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 obtain a complete preformatted message using PQresultErrorMessage
or PQresultVerboseErrorMessage
.) 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
.