| Документация по PostgreSQL 9.4.1 | |||
|---|---|---|---|
| Пред. | Уровень выше | Глава 41. PL/Tcl — процедурный язык Tcl | След. |
41.6. Процедуры триггеров на PL/Tcl
На PL/Tcl можно написать триггерные процедуры. PostgreSQL требует, чтобы процедура, которая будет вызываться как триггерная, была объявлена как функция без аргументов и возвращала тип trigger.
Информация от менеджера триггеров передаётся в тело процедуры в следующих переменных:
- $TG_name
Имя триггера из оператора CREATE TRIGGER.
- $TG_relid
Идентификатор объекта таблицы, для которой будет вызываться триггерная процедура.
- $TG_table_name
Имя таблицы, для которой будет вызываться триггерная процедура.
- $TG_table_schema
Схема таблицы, для которой будет вызываться триггерная процедура.
- $TG_relatts
Список языка Tcl, содержащий имена колонок таблицы. В начало списка добавлен пустой элемент, поэтому при поиске в этом списке имени колонки с помощью стандартной в Tcl команды
lsearchбудет возвращён номер элемента, начиная с 1, так же, как нумеруются колонки в PostgreSQL. (В позициях удалённых колонок также содержатся пустые элементы, так что нумерация следующих за ними атрибутов не нарушается.)- $TG_when
Строка BEFORE, AFTER или INSTEAD OF, в зависимости от типа события триггера.
- $TG_level
Строка ROW или STATEMENT, в зависимости от уровня события триггера.
- $TG_op
Строка INSERT, UPDATE, DELETE или TRUNCATE, в зависимости от действия события триггера.
- $NEW
Ассоциативный массив, содержащий значения новой строки таблицы для действий INSERT или UPDATE, либо пустой массив для DELETE. Индексами в массиве являются имена колонок. Колонки со значениями NULL в нём отсутствуют. Для триггеров уровня оператора этот массив не определяется.
- $OLD
Ассоциативный массив, содержащий значения старой строки таблицы для действий UPDATE или DELETE, либо пустой массив для INSERT. Индексами в массиве являются имена колонок. Колонки со значениями NULL в нём отсутствуют. Для триггеров уровня оператора этот массив не определяется.
- $args
Список на языке Tcl аргументов процедуры, заданных в операторе CREATE TRIGGER. Эти аргументы также доступны под обозначениями $1 ... $n в теле процедуры.
Возвращаемым значением триггерной процедуры может быть строка OK или SKIP, либо список, в виде, возвращаемом командой языка Tcl array get. Если возвращается значение OK, операция (INSERT/UPDATE/DELETE), которая привела к срабатыванию триггера, выполняется нормально. Значение SKIP указывает менеджеру триггеров просто пропустить эту операцию с текущей строкой данных. Если возвращается список, через него PL/Tcl передаёт менеджеру триггеров изменённую строку. Это имеет смысл только для триггеров уровня строки с порядком BEFORE команд INSERT и UPDATE, в которых вместо заданной в $NEW будет записываться изменённая строка; либо с порядком INSTEAD OF команд INSERT или UPDATE, в которых возвращаемая строка задействована в INSERT RETURNING или UPDATE RETURNING. Для других типов триггеров возвращаемое значение игнорируется.
Следующий небольшой пример показывает триггерную процедуру, которая ведёт в таблице целочисленный счётчик числа изменений, выполненных в строке. Для новых строк счётчик инициализируется нулевым значением, а затем увеличивается на единицу при каждом изменении.
CREATE FUNCTION trigfunc_modcount() RETURNS trigger AS $$
switch $TG_op {
INSERT {
set NEW($1) 0
}
UPDATE {
set NEW($1) $OLD($1)
incr NEW($1)
}
default {
return OK
}
}
return [array get NEW]
$$ LANGUAGE pltcl;
CREATE TABLE mytab (num integer, description text, modcnt integer);
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');Заметьте, что сама триггерная процедура не знает имени колонки; оно передаётся в аргументах триггера. Это позволяет применять эту триггерную процедуру для различных таблиц.
| Пред. | Начало | След. |
| Обращение к базе данных из PL/Tcl | Уровень выше | Процедуры событийных триггеров в PL/Tcl |
| PostgreSQL 9.4.1 Documentation | |||
|---|---|---|---|
| Prev | Up | Chapter 41. PL/Tcl - Tcl Procedural Language | Next |
41.6. Trigger Procedures in PL/Tcl
Trigger procedures can be written in PL/Tcl. PostgreSQL requires that a procedure that is to be called as a trigger must be declared as a function with no arguments and a return type of trigger.
The information from the trigger manager is passed to the procedure body in the following variables:
- $TG_name
The name of the trigger from the CREATE TRIGGER statement.
- $TG_relid
The object ID of the table that caused the trigger procedure to be invoked.
- $TG_table_name
The name of the table that caused the trigger procedure to be invoked.
- $TG_table_schema
The schema of the table that caused the trigger procedure to be invoked.
- $TG_relatts
A Tcl list of the table column names, prefixed with an empty list element. So looking up a column name in the list with Tcl's
lsearchcommand returns the element's number starting with 1 for the first column, the same way the columns are customarily numbered in PostgreSQL. (Empty list elements also appear in the positions of columns that have been dropped, so that the attribute numbering is correct for columns to their right.)- $TG_when
The string BEFORE, AFTER, or INSTEAD OF, depending on the type of trigger event.
- $TG_level
The string ROW or STATEMENT depending on the type of trigger event.
- $TG_op
The string INSERT, UPDATE, DELETE, or TRUNCATE depending on the type of trigger event.
- $NEW
An associative array containing the values of the new table row for INSERT or UPDATE actions, or empty for DELETE. The array is indexed by column name. Columns that are null will not appear in the array. This is not set for statement-level triggers.
- $OLD
An associative array containing the values of the old table row for UPDATE or DELETE actions, or empty for INSERT. The array is indexed by column name. Columns that are null will not appear in the array. This is not set for statement-level triggers.
- $args
A Tcl list of the arguments to the procedure as given in the CREATE TRIGGER statement. These arguments are also accessible as $1 ... $n in the procedure body.
The return value from a trigger procedure can be one of the strings OK or SKIP, or a list as returned by the array get Tcl command. If the return value is OK, the operation (INSERT/UPDATE/DELETE) that fired the trigger will proceed normally. SKIP tells the trigger manager to silently suppress the operation for this row. If a list is returned, it tells PL/Tcl to return a modified row to the trigger manager. This is only meaningful for row-level BEFORE INSERT or UPDATE triggers for which the modified row will be inserted instead of the one given in $NEW; or for row-level INSTEAD OF INSERT or UPDATE triggers where the returned row is used to support INSERT RETURNING and UPDATE RETURNING commands. The return value is ignored for other types of triggers.
Here's a little example trigger procedure that forces an integer value in a table to keep track of the number of updates that are performed on the row. For new rows inserted, the value is initialized to 0 and then incremented on every update operation.
CREATE FUNCTION trigfunc_modcount() RETURNS trigger AS $$
switch $TG_op {
INSERT {
set NEW($1) 0
}
UPDATE {
set NEW($1) $OLD($1)
incr NEW($1)
}
default {
return OK
}
}
return [array get NEW]
$$ LANGUAGE pltcl;
CREATE TABLE mytab (num integer, description text, modcnt integer);
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');Notice that the trigger procedure itself does not know the column name; that's supplied from the trigger arguments. This lets the trigger procedure be reused with different tables.