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

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

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

9.29.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.29.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.29.3. Обработка события перезаписи таблицы

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

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

Функция

Описание

pg_event_trigger_table_rewrite_oid () → oid

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

pg_event_trigger_table_rewrite_reason () → integer

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


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

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();

48.46. pg_statistic

The catalog pg_statistic stores statistical data about the contents of the database. Entries are created by ANALYZE and subsequently used by the query planner. Note that all the statistical data is inherently approximate, even assuming that it is up-to-date.

Normally there is one entry, with stainherit = false, for each table column that has been analyzed. If the table has inheritance children, a second entry with stainherit = true is also created. This row represents the column's statistics over the inheritance tree, i.e., statistics for the data you'd see with SELECT column FROM table*, whereas the stainherit = false row represents the results of SELECT column FROM ONLY table.

pg_statistic also stores statistical data about the values of index expressions. These are described as if they were actual data columns; in particular, starelid references the index. No entry is made for an ordinary non-expression index column, however, since it would be redundant with the entry for the underlying table column. Currently, entries for index expressions always have stainherit = false.

Since different kinds of statistics might be appropriate for different kinds of data, pg_statistic is designed not to assume very much about what sort of statistics it stores. Only extremely general statistics (such as nullness) are given dedicated columns in pg_statistic. Everything else is stored in slots, which are groups of associated columns whose content is identified by a code number in one of the slot's columns. For more information see src/include/catalog/pg_statistic.h.

pg_statistic should not be readable by the public, since even statistical information about a table's contents might be considered sensitive. (Example: minimum and maximum values of a salary column might be quite interesting.) pg_stats is a publicly readable view on pg_statistic that only exposes information about those tables that are readable by the current user.

Table 48.46. pg_statistic Columns

NameTypeReferencesDescription
starelidoidpg_class.oidThe table or index that the described column belongs to
staattnumint2pg_attribute.attnumThe number of the described column
stainheritbool If true, the stats include inheritance child columns, not just the values in the specified relation
stanullfracfloat4 The fraction of the column's entries that are null
stawidthint4 The average stored width, in bytes, of nonnull entries
stadistinctfloat4 The number of distinct nonnull data values in the column. A value greater than zero is the actual number of distinct values. A value less than zero is the negative of a multiplier for the number of rows in the table; for example, a column in which about 80% of the values are nonnull and each nonnull value appears about twice on average could be represented by stadistinct = -0.4. A zero value means the number of distinct values is unknown.
stakindNint2  A code number indicating the kind of statistics stored in the Nth slot of the pg_statistic row.
staopNoidpg_operator.oid An operator used to derive the statistics stored in the Nth slot. For example, a histogram slot would show the < operator that defines the sort order of the data.
stanumbersNfloat4[]  Numerical statistics of the appropriate kind for the Nth slot, or null if the slot kind does not involve numerical values
stavaluesNanyarray  Column data values of the appropriate kind for the Nth slot, or null if the slot kind does not store any data values. Each array's element values are actually of the specific column's data type, or a related type such as an array's element type, so there is no way to define these columns' type more specifically than anyarray.