43.3. Триггерные функции событий на языке C #
В этом разделе описываются низкоуровневые детали интерфейса для событийных триггерных функций. Эта информация необходима только при разработке событийных триггерных функций событий на языке C. При использовании языка более высокого уровня эти детали не видны. В большинстве случаев стоит рассмотреть возможность использования процедурного языка, прежде чем начать разрабатывать событийные триггеры на C. В документации по каждому процедурному языку объясняется, как создавать событийные триггеры на этом языке.
Триггерные функции событий должны использовать «version 1» интерфейса диспетчера функций.
Когда функция вызывается диспетчером триггеров событий, ей не передаются обычные аргументы, но передаётся указатель «context», ссылающийся на структуру EventTriggerData. Функции на C могут проверить вызваны ли они диспетчером триггеров событий или нет выполнив макрос:
CALLED_AS_EVENT_TRIGGER(fcinfo)
который разворачивается в:
EventTriggerData Если возвращается истина, то fcinfo->context можно безопасно привести к типу EventTriggerData * и использовать указатель на структуру EventTriggerData. Функция не должна изменять структуру EventTriggerData или любые данные, которые на неё указывают.
struct EventTriggerData определена в commands/event_trigger.h:
typedef struct EventTriggerData
{
NodeTag type;
const char *event; /* имя события */
Node *parsetree; /* дерево разбора */
CommandTag tag; /* тег команды */
} EventTriggerData;со следующими членами структуры:
typeВсегда
T_EventTriggerData.eventОписывает событие, для которого вызывается функция. Возможные значения:
"ddl_command_start","ddl_command_end","sql_drop","table_rewrite". Суть этих событий описывается в Разделе 43.1.parsetreeУказатель на дерево разбора команды. Детали можно посмотреть в исходном коде Postgres Pro. Структура дерева разбора может быть изменена без предупреждений.
tagТег команды, для которой сработал триггер события. Например
"CREATE FUNCTION".
Функция триггера события должна возвращать указатель NULL (но не SQL значение null, то есть не нужно устанавливать isNull в истину).
43.3. Writing Event Trigger Functions in C #
This section describes the low-level details of the interface to an event trigger function. This information is only needed when writing event trigger functions in C. If you are using a higher-level language then these details are handled for you. In most cases you should consider using a procedural language before writing your event triggers in C. The documentation of each procedural language explains how to write an event trigger in that language.
Event trigger functions must use the “version 1” function manager interface.
When a function is called by the event trigger manager, it is not passed any normal arguments, but it is passed a “context” pointer pointing to a EventTriggerData structure. C functions can check whether they were called from the event trigger manager or not by executing the macro:
CALLED_AS_EVENT_TRIGGER(fcinfo)
which expands to:
((fcinfo)->context != NULL && IsA((fcinfo)->context, EventTriggerData))
If this returns true, then it is safe to cast fcinfo->context to type EventTriggerData * and make use of the pointed-to EventTriggerData structure. The function must not alter the EventTriggerData structure or any of the data it points to.
struct EventTriggerData is defined in commands/event_trigger.h:
typedef struct EventTriggerData
{
NodeTag type;
const char *event; /* event name */
Node *parsetree; /* parse tree */
CommandTag tag; /* command tag */
} EventTriggerData;
where the members are defined as follows:
typeAlways
T_EventTriggerData.eventDescribes the event for which the function is called, one of
"ddl_command_start","ddl_command_end","sql_drop","table_rewrite". See Section 43.1 for the meaning of these events.parsetreeA pointer to the parse tree of the command. Check the Postgres Pro source code for details. The parse tree structure is subject to change without notice.
tagThe command tag associated with the event for which the event trigger is run, for example
"CREATE FUNCTION".
An event trigger function must return a NULL pointer (not an SQL null value, that is, do not set isNull true).