9.30. Функции событийных триггеров #

Postgres Pro предоставляет следующие вспомогательные функции для получения информации в событийных триггерах.

Подробнее о событийных триггерах можно узнать в Главе 42.

9.30.1. Получение изменений в конце команды #

pg_event_trigger_ddl_commands () → setof record

Функция pg_event_trigger_ddl_commands возвращает список команд DDL, выполняемых в результате действия пользователя. Вызывать её можно только в функции, реализующей событийный триггер ddl_command_end. При попытке вызвать её в любом другом контексте возникнет ошибка. Функция pg_event_trigger_ddl_commands возвращает одну строку для каждой базовой команды; для некоторых команд, записываемых в виде одного предложения SQL, может возвращаться несколько строк. Эта функция возвращает следующие столбцы:

ИмяТипОписание
classidoidOID каталога, к которому относится объект
objidoidOID самого объекта
objsubidintegerИдентификатор подобъекта (например, номер для столбца)
command_tagtextТег команды
object_typetextТип объекта
schema_nametextИмя схемы, к которой относится объект; если объект не относится ни к какой схеме — NULL. В кавычки имя не заключается.
object_identitytextТекстовое представление идентификатора объекта, включающее схему. При необходимости компоненты этого идентификатора заключаются в кавычки.
in_extensionbooleanTrue, если команда является частью скрипта расширения
commandpg_ddl_commandПолное представление команды, во внутреннем формате. Его нельзя вывести непосредственно, но можно передать другим функциям, чтобы получить различные сведения о команде.

9.30.2. Обработка объектов, удалённых командой DDL #

pg_event_trigger_dropped_objects () → setof record

Функция pg_event_trigger_dropped_objects выдаёт список всех объектов, удалённых командой, для которых вызывалось событие sql_drop. При вызове в любом другом контексте происходит ошибка. Эта функция выдаёт следующие столбцы:

ИмяТипОписание
classidoidOID каталога, к которому относился объект
objidoidOID самого объекта
objsubidintegerИдентификатор подобъекта (например, номер для столбца)
originalbooleanTrue, если это один из корневых удаляемых объектов
normalbooleanTrue, если к этому объекту в графе зависимостей привело отношение обычной зависимости
is_temporarybooleanTrue, если объект был временным
object_typetextТип объекта
schema_nametextИмя схемы, к которой относился объект; если объект не относился ни к какой схеме — NULL. В кавычки имя не заключается.
object_nametextИмя объекта, если сочетание схемы и имени позволяет уникально идентифицировать объект; в противном случае — NULL. Имя не заключается в кавычки и не дополняется именем схемы.
object_identitytextТекстовое представление идентификатора объекта, включающее схему. При необходимости компоненты этого идентификатора заключаются в кавычки.
address_namestext[]Массив, который в сочетании с object_type и массивом address_args можно передать функции pg_get_object_address, чтобы воссоздать адрес объекта на удалённом сервере, содержащем одноимённый объект того же рода.
address_argstext[]Дополнение к массиву address_names

Функцию pg_event_trigger_dropped_objects можно использовать в событийном триггере так:

CREATE FUNCTION test_event_trigger_for_drops()
        RETURNS event_trigger LANGUAGE plpgsql AS $$
DECLARE
    obj record;
BEGIN
    FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
    LOOP
        RAISE NOTICE '% dropped object: % %.% %',
                     tg_tag,
                     obj.object_type,
                     obj.schema_name,
                     obj.object_name,
                     obj.object_identity;
    END LOOP;
END;
$$;
CREATE EVENT TRIGGER test_event_trigger_for_drops
   ON sql_drop
   EXECUTE FUNCTION test_event_trigger_for_drops();

9.30.3. Обработка события перезаписи таблицы #

В Таблице 9.112 показаны функции, выдающие информацию о таблице, для которой произошло событие перезаписи таблицы (table_rewrite). При попытке вызвать их в другом контексте возникнет ошибка.

Таблица 9.112. Функции получения информации о перезаписи таблицы

Функция

Описание

pg_event_trigger_table_rewrite_oid () → oid

Выдаёт OID таблицы, которая будет перезаписана.

pg_event_trigger_table_rewrite_reason () → integer

Возвращает код с объяснением причины(причин) перезаписи в виде битовой карты, построенной из следующих значений: 1 (в таблице изменилась характеристика хранения отношений), 2 (в столбце изменилось значение по умолчанию), 4 (у столбца изменился тип данных) и 8 (изменился табличный метод доступа).


Эти функции можно использовать в событийном триггере так:

CREATE FUNCTION test_event_trigger_table_rewrite_oid()
 RETURNS event_trigger
 LANGUAGE plpgsql AS
$$
BEGIN
  RAISE NOTICE 'rewriting table % for reason %',
                pg_event_trigger_table_rewrite_oid()::regclass,
                pg_event_trigger_table_rewrite_reason();
END;
$$;

CREATE EVENT TRIGGER test_table_rewrite_oid
                  ON table_rewrite
   EXECUTE FUNCTION test_event_trigger_table_rewrite_oid();

9.30. Event Trigger Functions #

Postgres Pro provides these helper functions to retrieve information from event triggers.

For more information about event triggers, see Chapter 42.

9.30.1. Capturing Changes at Command End #

pg_event_trigger_ddl_commands () → setof record

pg_event_trigger_ddl_commands returns a list of DDL commands executed by each user action, when invoked in a function attached to a ddl_command_end event trigger. If called in any other context, an error is raised. pg_event_trigger_ddl_commands returns one row for each base command executed; some commands that are a single SQL sentence may return more than one row. This function returns the following columns:

NameTypeDescription
classidoidOID of catalog the object belongs in
objidoidOID of the object itself
objsubidintegerSub-object ID (e.g., attribute number for a column)
command_tagtextCommand tag
object_typetextType of the object
schema_nametext Name of the schema the object belongs in, if any; otherwise NULL. No quoting is applied.
object_identitytext Text rendering of the object identity, schema-qualified. Each identifier included in the identity is quoted if necessary.
in_extensionbooleanTrue if the command is part of an extension script
commandpg_ddl_command A complete representation of the command, in internal format. This cannot be output directly, but it can be passed to other functions to obtain different pieces of information about the command.

9.30.2. Processing Objects Dropped by a DDL Command #

pg_event_trigger_dropped_objects () → setof record

pg_event_trigger_dropped_objects returns a list of all objects dropped by the command in whose sql_drop event it is called. If called in any other context, an error is raised. This function returns the following columns:

NameTypeDescription
classidoidOID of catalog the object belonged in
objidoidOID of the object itself
objsubidintegerSub-object ID (e.g., attribute number for a column)
originalbooleanTrue if this was one of the root object(s) of the deletion
normalboolean True if there was a normal dependency relationship in the dependency graph leading to this object
is_temporaryboolean True if this was a temporary object
object_typetextType of the object
schema_nametext Name of the schema the object belonged in, if any; otherwise NULL. No quoting is applied.
object_nametext Name of the object, if the combination of schema and name can be used as a unique identifier for the object; otherwise NULL. No quoting is applied, and name is never schema-qualified.
object_identitytext Text rendering of the object identity, schema-qualified. Each identifier included in the identity is quoted if necessary.
address_namestext[] An array that, together with object_type and address_args, can be used by the pg_get_object_address function to recreate the object address in a remote server containing an identically named object of the same kind.
address_argstext[] Complement for address_names

The pg_event_trigger_dropped_objects function can be used in an event trigger like this:

CREATE FUNCTION test_event_trigger_for_drops()
        RETURNS event_trigger LANGUAGE plpgsql AS $$
DECLARE
    obj record;
BEGIN
    FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
    LOOP
        RAISE NOTICE '% dropped object: % %.% %',
                     tg_tag,
                     obj.object_type,
                     obj.schema_name,
                     obj.object_name,
                     obj.object_identity;
    END LOOP;
END;
$$;
CREATE EVENT TRIGGER test_event_trigger_for_drops
   ON sql_drop
   EXECUTE FUNCTION test_event_trigger_for_drops();

9.30.3. Handling a Table Rewrite Event #

The functions shown in Table 9.112 provide information about a table for which a table_rewrite event has just been called. If called in any other context, an error is raised.

Table 9.112. Table Rewrite Information Functions

Function

Description

pg_event_trigger_table_rewrite_oid () → oid

Returns the OID of the table about to be rewritten.

pg_event_trigger_table_rewrite_reason () → integer

Returns a code explaining the reason(s) for rewriting. The value is a bitmap built from the following values: 1 (the table has changed its persistence), 2 (default value of a column has changed), 4 (a column has a new data type) and 8 (the table access method has changed).


These functions can be used in an event trigger like this:

CREATE FUNCTION test_event_trigger_table_rewrite_oid()
 RETURNS event_trigger
 LANGUAGE plpgsql AS
$$
BEGIN
  RAISE NOTICE 'rewriting table % for reason %',
                pg_event_trigger_table_rewrite_oid()::regclass,
                pg_event_trigger_table_rewrite_reason();
END;
$$;

CREATE EVENT TRIGGER test_table_rewrite_oid
                  ON table_rewrite
   EXECUTE FUNCTION test_event_trigger_table_rewrite_oid();

FAQ