1 <!-- doc/src/sgml/trigger.sgml -->
3 <chapter id=
"triggers">
4 <title>Triggers
</title>
6 <indexterm zone=
"triggers">
7 <primary>trigger
</primary>
11 This chapter provides general information about writing trigger functions.
12 Trigger functions can be written in most of the available procedural
14 <application>PL/pgSQL
</application> (
<xref linkend=
"plpgsql"/>),
15 <application>PL/Tcl
</application> (
<xref linkend=
"pltcl"/>),
16 <application>PL/Perl
</application> (
<xref linkend=
"plperl"/>), and
17 <application>PL/Python
</application> (
<xref linkend=
"plpython"/>).
18 After reading this chapter, you should consult the chapter for
19 your favorite procedural language to find out the language-specific
20 details of writing a trigger in it.
24 It is also possible to write a trigger function in C, although
25 most people find it easier to use one of the procedural languages.
26 It is not currently possible to write a trigger function in the
27 plain SQL function language.
30 <sect1 id=
"trigger-definition">
31 <title>Overview of Trigger Behavior
</title>
34 A trigger is a specification that the database should automatically
35 execute a particular function whenever a certain type of operation is
36 performed. Triggers can be attached to tables (partitioned or not),
37 views, and foreign tables.
41 On tables and foreign tables, triggers can be defined to execute either
42 before or after any
<command>INSERT
</command>,
<command>UPDATE
</command>,
43 or
<command>DELETE
</command> operation, either once per modified row,
44 or once per
<acronym>SQL
</acronym> statement.
45 <command>UPDATE
</command> triggers can moreover be set to fire only if
46 certain columns are mentioned in the
<literal>SET
</literal> clause of
47 the
<command>UPDATE
</command> statement. Triggers can also fire
48 for
<command>TRUNCATE
</command> statements. If a trigger event occurs,
49 the trigger's function is called at the appropriate time to handle the
54 On views, triggers can be defined to execute instead of
55 <command>INSERT
</command>,
<command>UPDATE
</command>, or
56 <command>DELETE
</command> operations.
57 Such
<literal>INSTEAD OF
</literal> triggers
58 are fired once for each row that needs to be modified in the view.
59 It is the responsibility of the
60 trigger's function to perform the necessary modifications to the view's
61 underlying base table(s) and, where appropriate, return the modified
62 row as it will appear in the view. Triggers on views can also be defined
63 to execute once per
<acronym>SQL
</acronym> statement, before or after
64 <command>INSERT
</command>,
<command>UPDATE
</command>, or
65 <command>DELETE
</command> operations.
66 However, such triggers are fired only if there is also
67 an
<literal>INSTEAD OF
</literal> trigger on the view. Otherwise,
68 any statement targeting the view must be rewritten into a statement
69 affecting its underlying base table(s), and then the triggers
70 that will be fired are the ones attached to the base table(s).
74 The trigger function must be defined before the trigger itself can be
75 created. The trigger function must be declared as a
76 function taking no arguments and returning type
<literal>trigger
</literal>.
77 (The trigger function receives its input through a specially-passed
78 <structname>TriggerData
</structname> structure, not in the form of ordinary function
83 Once a suitable trigger function has been created, the trigger is
85 <xref linkend=
"sql-createtrigger"/>.
86 The same trigger function can be used for multiple triggers.
90 <productname>PostgreSQL
</productname> offers both
<firstterm>per-row
</firstterm>
91 triggers and
<firstterm>per-statement
</firstterm> triggers. With a per-row
92 trigger, the trigger function
93 is invoked once for each row that is affected by the statement
94 that fired the trigger. In contrast, a per-statement trigger is
95 invoked only once when an appropriate statement is executed,
96 regardless of the number of rows affected by that statement. In
97 particular, a statement that affects zero rows will still result
98 in the execution of any applicable per-statement triggers. These
99 two types of triggers are sometimes called
<firstterm>row-level
</firstterm>
100 triggers and
<firstterm>statement-level
</firstterm> triggers,
101 respectively. Triggers on
<command>TRUNCATE
</command> may only be
102 defined at statement level, not per-row.
106 Triggers are also classified according to whether they fire
107 <firstterm>before
</firstterm>,
<firstterm>after
</firstterm>, or
108 <firstterm>instead of
</firstterm> the operation. These are referred to
109 as
<literal>BEFORE
</literal> triggers,
<literal>AFTER
</literal> triggers, and
110 <literal>INSTEAD OF
</literal> triggers respectively.
111 Statement-level
<literal>BEFORE
</literal> triggers naturally fire before the
112 statement starts to do anything, while statement-level
<literal>AFTER
</literal>
113 triggers fire at the very end of the statement. These types of
114 triggers may be defined on tables, views, or foreign tables. Row-level
115 <literal>BEFORE
</literal> triggers fire immediately before a particular row is
116 operated on, while row-level
<literal>AFTER
</literal> triggers fire at the end of
117 the statement (but before any statement-level
<literal>AFTER
</literal> triggers).
118 These types of triggers may only be defined on tables and
119 foreign tables, not views.
120 <literal>INSTEAD OF
</literal> triggers may only be
121 defined on views, and only at row level; they fire immediately as each
122 row in the view is identified as needing to be operated on.
126 The execution of an
<literal>AFTER
</literal> trigger can be deferred
127 to the end of the transaction, rather than the end of the statement,
128 if it was defined as a
<firstterm>constraint trigger
</firstterm>.
129 In all cases, a trigger is executed as part of the same transaction as
130 the statement that triggered it, so if either the statement or the
131 trigger causes an error, the effects of both will be rolled back.
135 If an
<command>INSERT
</command> contains an
<literal>ON CONFLICT
136 DO UPDATE
</literal> clause, it is possible for row-level
137 <literal>BEFORE
</literal> <command>INSERT
</command> and then
138 <literal>BEFORE
</literal> <command>UPDATE
</command> triggers
139 to be executed on triggered rows. Such interactions can be
140 complex if the triggers are not idempotent because change made by
141 <literal>BEFORE
</literal> <command>INSERT
</command> triggers will be
142 seen by
<literal>BEFORE
</literal> <command>UPDATE
</command> triggers,
143 including changes to
<varname>EXCLUDED
</varname> columns.
147 Note that statement-level
148 <command>UPDATE
</command> triggers are executed when
<literal>ON
149 CONFLICT DO UPDATE
</literal> is specified, regardless of whether or not
150 any rows were affected by the
<command>UPDATE
</command> (and
151 regardless of whether the alternative
<command>UPDATE
</command>
152 path was ever taken). An
<command>INSERT
</command> with an
153 <literal>ON CONFLICT DO UPDATE
</literal> clause will execute
154 statement-level
<literal>BEFORE
</literal> <command>INSERT
</command>
155 triggers first, then statement-level
<literal>BEFORE
</literal>
156 <command>UPDATE
</command> triggers, followed by statement-level
157 <literal>AFTER
</literal> <command>UPDATE
</command> triggers and finally
158 statement-level
<literal>AFTER
</literal> <command>INSERT
</command>
163 A statement that targets a parent table in an inheritance or partitioning
164 hierarchy does not cause the statement-level triggers of affected child
165 tables to be fired; only the parent table's statement-level triggers are
166 fired. However, row-level triggers of any affected child tables will be
171 If an
<command>UPDATE
</command> on a partitioned table causes a row to move
172 to another partition, it will be performed as a
<command>DELETE
</command>
173 from the original partition followed by an
<command>INSERT
</command> into
174 the new partition. In this case, all row-level
<literal>BEFORE
</literal>
175 <command>UPDATE
</command> triggers and all row-level
176 <literal>BEFORE
</literal> <command>DELETE
</command> triggers are fired on
177 the original partition. Then all row-level
<literal>BEFORE
</literal>
178 <command>INSERT
</command> triggers are fired on the destination partition.
179 The possibility of surprising outcomes should be considered when all these
180 triggers affect the row being moved. As far as
<literal>AFTER ROW
</literal>
181 triggers are concerned,
<literal>AFTER
</literal> <command>DELETE
</command>
182 and
<literal>AFTER
</literal> <command>INSERT
</command> triggers are
183 applied; but
<literal>AFTER
</literal> <command>UPDATE
</command> triggers
184 are not applied because the
<command>UPDATE
</command> has been converted to
185 a
<command>DELETE
</command> and an
<command>INSERT
</command>. As far as
186 statement-level triggers are concerned, none of the
187 <command>DELETE
</command> or
<command>INSERT
</command> triggers are fired,
188 even if row movement occurs; only the
<command>UPDATE
</command> triggers
189 defined on the target table used in the
<command>UPDATE
</command> statement
194 No separate triggers are defined for
<command>MERGE
</command>. Instead,
195 statement-level or row-level
<command>UPDATE
</command>,
196 <command>DELETE
</command>, and
<command>INSERT
</command> triggers are fired
197 depending on (for statement-level triggers) what actions are specified in
198 the
<command>MERGE
</command> query and (for row-level triggers) what
199 actions are performed.
203 While running a
<command>MERGE
</command> command, statement-level
204 <literal>BEFORE
</literal> and
<literal>AFTER
</literal> triggers are
205 fired for events specified in the actions of the
<command>MERGE
</command>
206 command, irrespective of whether or not the action is ultimately performed.
207 This is the same as an
<command>UPDATE
</command> statement that updates
208 no rows, yet statement-level triggers are fired.
209 The row-level triggers are fired only when a row is actually updated,
210 inserted or deleted. So it's perfectly legal that while statement-level
211 triggers are fired for certain types of action, no row-level triggers
212 are fired for the same kind of action.
216 Trigger functions invoked by per-statement triggers should always
217 return
<symbol>NULL
</symbol>. Trigger functions invoked by per-row
218 triggers can return a table row (a value of
219 type
<structname>HeapTuple
</structname>) to the calling executor,
220 if they choose. A row-level trigger fired before an operation has
221 the following choices:
226 It can return
<symbol>NULL
</symbol> to skip the operation for the
227 current row. This instructs the executor to not perform the
228 row-level operation that invoked the trigger (the insertion,
229 modification, or deletion of a particular table row).
235 For row-level
<command>INSERT
</command>
236 and
<command>UPDATE
</command> triggers only, the returned row
237 becomes the row that will be inserted or will replace the row
238 being updated. This allows the trigger function to modify the
239 row being inserted or updated.
244 A row-level
<literal>BEFORE
</literal> trigger that does not intend to cause
245 either of these behaviors must be careful to return as its result the same
246 row that was passed in (that is, the
<varname>NEW
</varname> row
247 for
<command>INSERT
</command> and
<command>UPDATE
</command>
248 triggers, the
<varname>OLD
</varname> row for
249 <command>DELETE
</command> triggers).
253 A row-level
<literal>INSTEAD OF
</literal> trigger should either return
254 <symbol>NULL
</symbol> to indicate that it did not modify any data from
255 the view's underlying base tables, or it should return the view
256 row that was passed in (the
<varname>NEW
</varname> row
257 for
<command>INSERT
</command> and
<command>UPDATE
</command>
258 operations, or the
<varname>OLD
</varname> row for
259 <command>DELETE
</command> operations). A nonnull return value is
260 used to signal that the trigger performed the necessary data
261 modifications in the view. This will cause the count of the number
262 of rows affected by the command to be incremented. For
263 <command>INSERT
</command> and
<command>UPDATE
</command> operations only, the trigger
264 may modify the
<varname>NEW
</varname> row before returning it. This will
265 change the data returned by
266 <command>INSERT RETURNING
</command> or
<command>UPDATE RETURNING
</command>,
267 and is useful when the view will not show exactly the same data
272 The return value is ignored for row-level triggers fired after an
273 operation, and so they can return
<symbol>NULL
</symbol>.
277 Some considerations apply for generated
278 columns.
<indexterm><primary>generated column
</primary><secondary>in
279 triggers
</secondary></indexterm> Stored generated columns are computed after
280 <literal>BEFORE
</literal> triggers and before
<literal>AFTER
</literal>
281 triggers. Therefore, the generated value can be inspected in
282 <literal>AFTER
</literal> triggers. In
<literal>BEFORE
</literal> triggers,
283 the
<literal>OLD
</literal> row contains the old generated value, as one
284 would expect, but the
<literal>NEW
</literal> row does not yet contain the
285 new generated value and should not be accessed. In the C language
286 interface, the content of the column is undefined at this point; a
287 higher-level programming language should prevent access to a stored
288 generated column in the
<literal>NEW
</literal> row in a
289 <literal>BEFORE
</literal> trigger. Changes to the value of a generated
290 column in a
<literal>BEFORE
</literal> trigger are ignored and will be
295 If more than one trigger is defined for the same event on the same
296 relation, the triggers will be fired in alphabetical order by
297 trigger name. In the case of
<literal>BEFORE
</literal> and
298 <literal>INSTEAD OF
</literal> triggers, the possibly-modified row returned by
299 each trigger becomes the input to the next trigger. If any
300 <literal>BEFORE
</literal> or
<literal>INSTEAD OF
</literal> trigger returns
301 <symbol>NULL
</symbol>, the operation is abandoned for that row and subsequent
302 triggers are not fired (for that row).
306 A trigger definition can also specify a Boolean
<literal>WHEN
</literal>
307 condition, which will be tested to see whether the trigger should
308 be fired. In row-level triggers the
<literal>WHEN
</literal> condition can
309 examine the old and/or new values of columns of the row. (Statement-level
310 triggers can also have
<literal>WHEN
</literal> conditions, although the feature
311 is not so useful for them.) In a
<literal>BEFORE
</literal> trigger, the
312 <literal>WHEN
</literal>
313 condition is evaluated just before the function is or would be executed,
314 so using
<literal>WHEN
</literal> is not materially different from testing the
315 same condition at the beginning of the trigger function. However, in
316 an
<literal>AFTER
</literal> trigger, the
<literal>WHEN
</literal> condition is evaluated
317 just after the row update occurs, and it determines whether an event is
318 queued to fire the trigger at the end of statement. So when an
319 <literal>AFTER
</literal> trigger's
320 <literal>WHEN
</literal> condition does not return true, it is not necessary
321 to queue an event nor to re-fetch the row at end of statement. This
322 can result in significant speedups in statements that modify many
323 rows, if the trigger only needs to be fired for a few of the rows.
324 <literal>INSTEAD OF
</literal> triggers do not support
325 <literal>WHEN
</literal> conditions.
329 Typically, row-level
<literal>BEFORE
</literal> triggers are used for checking or
330 modifying the data that will be inserted or updated. For example,
331 a
<literal>BEFORE
</literal> trigger might be used to insert the current time into a
332 <type>timestamp
</type> column, or to check that two elements of the row are
333 consistent. Row-level
<literal>AFTER
</literal> triggers are most sensibly
334 used to propagate the updates to other tables, or make consistency
335 checks against other tables. The reason for this division of labor is
336 that an
<literal>AFTER
</literal> trigger can be certain it is seeing the final
337 value of the row, while a
<literal>BEFORE
</literal> trigger cannot; there might
338 be other
<literal>BEFORE
</literal> triggers firing after it. If you have no
339 specific reason to make a trigger
<literal>BEFORE
</literal> or
340 <literal>AFTER
</literal>, the
<literal>BEFORE
</literal> case is more efficient, since
341 the information about
342 the operation doesn't have to be saved until end of statement.
346 If a trigger function executes SQL commands then these
347 commands might fire triggers again. This is known as cascading
348 triggers. There is no direct limitation on the number of cascade
349 levels. It is possible for cascades to cause a recursive invocation
350 of the same trigger; for example, an
<command>INSERT
</command>
351 trigger might execute a command that inserts an additional row
352 into the same table, causing the
<command>INSERT
</command> trigger
353 to be fired again. It is the trigger programmer's responsibility
354 to avoid infinite recursion in such scenarios.
358 If a foreign key constraint specifies referential actions (that
359 is, cascading updates or deletes), those actions are performed via
360 ordinary SQL update or delete commands on the referencing table.
361 In particular, any triggers that exist on the referencing table
362 will be fired for those changes. If such a trigger modifies or
363 blocks the effect of one of these commands, the end result could
364 be to break referential integrity. It is the trigger programmer's
365 responsibility to avoid that.
370 <primary>trigger
</primary>
371 <secondary>arguments for trigger functions
</secondary>
373 When a trigger is being defined, arguments can be specified for
374 it. The purpose of including arguments in the
375 trigger definition is to allow different triggers with similar
376 requirements to call the same function. As an example, there
377 could be a generalized trigger function that takes as its
378 arguments two column names and puts the current user in one and
379 the current time stamp in the other. Properly written, this
380 trigger function would be independent of the specific table it is
381 triggering on. So the same function could be used for
382 <command>INSERT
</command> events on any table with suitable
383 columns, to automatically track creation of records in a
384 transaction table for example. It could also be used to track
385 last-update events if defined as an
<command>UPDATE
</command>
390 Each programming language that supports triggers has its own method
391 for making the trigger input data available to the trigger function.
392 This input data includes the type of trigger event (e.g.,
393 <command>INSERT
</command> or
<command>UPDATE
</command>) as well as any
394 arguments that were listed in
<command>CREATE TRIGGER
</command>.
395 For a row-level trigger, the input data also includes the
396 <varname>NEW
</varname> row for
<command>INSERT
</command> and
397 <command>UPDATE
</command> triggers, and/or the
<varname>OLD
</varname> row
398 for
<command>UPDATE
</command> and
<command>DELETE
</command> triggers.
402 By default, statement-level triggers do not have any way to examine the
403 individual row(s) modified by the statement. But an
<literal>AFTER
404 STATEMENT
</literal> trigger can request that
<firstterm>transition tables
</firstterm>
405 be created to make the sets of affected rows available to the trigger.
406 <literal>AFTER ROW
</literal> triggers can also request transition tables, so
407 that they can see the total changes in the table as well as the change in
408 the individual row they are currently being fired for. The method for
409 examining the transition tables again depends on the programming language
410 that is being used, but the typical approach is to make the transition
411 tables act like read-only temporary tables that can be accessed by SQL
412 commands issued within the trigger function.
417 <sect1 id=
"trigger-datachanges">
418 <title>Visibility of Data Changes
</title>
421 If you execute SQL commands in your trigger function, and these
422 commands access the table that the trigger is for, then
423 you need to be aware of the data visibility rules, because they determine
424 whether these SQL commands will see the data change that the trigger
425 is fired for. Briefly:
431 Statement-level triggers follow simple visibility rules: none of
432 the changes made by a statement are visible to statement-level
433 <literal>BEFORE
</literal> triggers, whereas all
434 modifications are visible to statement-level
<literal>AFTER
</literal>
441 The data change (insertion, update, or deletion) causing the
442 trigger to fire is naturally
<emphasis>not
</emphasis> visible
443 to SQL commands executed in a row-level
<literal>BEFORE
</literal> trigger,
444 because it hasn't happened yet.
450 However, SQL commands executed in a row-level
<literal>BEFORE
</literal>
451 trigger
<emphasis>will
</emphasis> see the effects of data
452 changes for rows previously processed in the same outer
453 command. This requires caution, since the ordering of these
454 change events is not in general predictable; an SQL command that
455 affects multiple rows can visit the rows in any order.
461 Similarly, a row-level
<literal>INSTEAD OF
</literal> trigger will see the
462 effects of data changes made by previous firings of
<literal>INSTEAD
463 OF
</literal> triggers in the same outer command.
469 When a row-level
<literal>AFTER
</literal> trigger is fired, all data
471 by the outer command are already complete, and are visible to
472 the invoked trigger function.
479 If your trigger function is written in any of the standard procedural
480 languages, then the above statements apply only if the function is
481 declared
<literal>VOLATILE
</literal>. Functions that are declared
482 <literal>STABLE
</literal> or
<literal>IMMUTABLE
</literal> will not see changes made by
483 the calling command in any case.
487 Further information about data visibility rules can be found in
488 <xref linkend=
"spi-visibility"/>. The example in
<xref
489 linkend=
"trigger-example"/> contains a demonstration of these rules.
493 <sect1 id=
"trigger-interface">
494 <title>Writing Trigger Functions in C
</title>
496 <indexterm zone=
"trigger-interface">
497 <primary>trigger
</primary>
498 <secondary>in C
</secondary>
502 <primary>transition tables
</primary>
503 <secondary>referencing from C trigger
</secondary>
507 This section describes the low-level details of the interface to a
508 trigger function. This information is only needed when writing
509 trigger functions in C. If you are using a higher-level language then
510 these details are handled for you. In most cases you should consider
511 using a procedural language before writing your triggers in C. The
512 documentation of each procedural language explains how to write a
513 trigger in that language.
517 Trigger functions must use the
<quote>version
1</quote> function manager
522 When a function is called by the trigger manager, it is not passed
523 any normal arguments, but it is passed a
<quote>context
</quote>
524 pointer pointing to a
<structname>TriggerData
</structname> structure. C
525 functions can check whether they were called from the trigger
526 manager or not by executing the macro:
528 CALLED_AS_TRIGGER(fcinfo)
532 ((fcinfo)-
>context != NULL
&& IsA((fcinfo)-
>context, TriggerData))
534 If this returns true, then it is safe to cast
535 <literal>fcinfo-
>context
</literal> to type
<literal>TriggerData
536 *
</literal> and make use of the pointed-to
537 <structname>TriggerData
</structname> structure. The function must
538 <emphasis>not
</emphasis> alter the
<structname>TriggerData
</structname>
539 structure or any of the data it points to.
543 <structname>struct TriggerData
</structname> is defined in
544 <filename>commands/trigger.h
</filename>:
547 typedef struct TriggerData
550 TriggerEvent tg_event;
551 Relation tg_relation;
552 HeapTuple tg_trigtuple;
553 HeapTuple tg_newtuple;
555 TupleTableSlot *tg_trigslot;
556 TupleTableSlot *tg_newslot;
557 Tuplestorestate *tg_oldtable;
558 Tuplestorestate *tg_newtable;
559 const Bitmapset *tg_updatedcols;
563 where the members are defined as follows:
567 <term><structfield>type
</structfield></term>
570 Always
<literal>T_TriggerData
</literal>.
576 <term><structfield>tg_event
</structfield></term>
579 Describes the event for which the function is called. You can use the
580 following macros to examine
<literal>tg_event
</literal>:
584 <term><literal>TRIGGER_FIRED_BEFORE(tg_event)
</literal></term>
587 Returns true if the trigger fired before the operation.
593 <term><literal>TRIGGER_FIRED_AFTER(tg_event)
</literal></term>
596 Returns true if the trigger fired after the operation.
602 <term><literal>TRIGGER_FIRED_INSTEAD(tg_event)
</literal></term>
605 Returns true if the trigger fired instead of the operation.
611 <term><literal>TRIGGER_FIRED_FOR_ROW(tg_event)
</literal></term>
614 Returns true if the trigger fired for a row-level event.
620 <term><literal>TRIGGER_FIRED_FOR_STATEMENT(tg_event)
</literal></term>
623 Returns true if the trigger fired for a statement-level event.
629 <term><literal>TRIGGER_FIRED_BY_INSERT(tg_event)
</literal></term>
632 Returns true if the trigger was fired by an
<command>INSERT
</command> command.
638 <term><literal>TRIGGER_FIRED_BY_UPDATE(tg_event)
</literal></term>
641 Returns true if the trigger was fired by an
<command>UPDATE
</command> command.
647 <term><literal>TRIGGER_FIRED_BY_DELETE(tg_event)
</literal></term>
650 Returns true if the trigger was fired by a
<command>DELETE
</command> command.
656 <term><literal>TRIGGER_FIRED_BY_TRUNCATE(tg_event)
</literal></term>
659 Returns true if the trigger was fired by a
<command>TRUNCATE
</command> command.
669 <term><structfield>tg_relation
</structfield></term>
672 A pointer to a structure describing the relation that the trigger fired for.
673 Look at
<filename>utils/rel.h
</filename> for details about
674 this structure. The most interesting things are
675 <literal>tg_relation-
>rd_att
</literal> (descriptor of the relation
676 tuples) and
<literal>tg_relation-
>rd_rel-
>relname
</literal>
677 (relation name; the type is not
<type>char*
</type> but
678 <type>NameData
</type>; use
679 <literal>SPI_getrelname(tg_relation)
</literal> to get a
<type>char*
</type> if you
680 need a copy of the name).
686 <term><structfield>tg_trigtuple
</structfield></term>
689 A pointer to the row for which the trigger was fired. This is
690 the row being inserted, updated, or deleted. If this trigger
691 was fired for an
<command>INSERT
</command> or
692 <command>DELETE
</command> then this is what you should return
693 from the function if you don't want to replace the row with
694 a different one (in the case of
<command>INSERT
</command>) or
695 skip the operation. For triggers on foreign tables, values of system
696 columns herein are unspecified.
702 <term><structfield>tg_newtuple
</structfield></term>
705 A pointer to the new version of the row, if the trigger was
706 fired for an
<command>UPDATE
</command>, and
<symbol>NULL
</symbol> if
707 it is for an
<command>INSERT
</command> or a
708 <command>DELETE
</command>. This is what you have to return
709 from the function if the event is an
<command>UPDATE
</command>
710 and you don't want to replace this row by a different one or
711 skip the operation. For triggers on foreign tables, values of system
712 columns herein are unspecified.
718 <term><structfield>tg_trigger
</structfield></term>
721 A pointer to a structure of type
<structname>Trigger
</structname>,
722 defined in
<filename>utils/reltrigger.h
</filename>:
725 typedef struct Trigger
749 where
<structfield>tgname
</structfield> is the trigger's name,
750 <structfield>tgnargs
</structfield> is the number of arguments in
751 <structfield>tgargs
</structfield>, and
<structfield>tgargs
</structfield> is an array of
752 pointers to the arguments specified in the
<command>CREATE
753 TRIGGER
</command> statement. The other members are for internal use
760 <term><structfield>tg_trigslot
</structfield></term>
763 The slot containing
<structfield>tg_trigtuple
</structfield>,
764 or a
<symbol>NULL
</symbol> pointer if there is no such tuple.
770 <term><structfield>tg_newslot
</structfield></term>
773 The slot containing
<structfield>tg_newtuple
</structfield>,
774 or a
<symbol>NULL
</symbol> pointer if there is no such tuple.
780 <term><structfield>tg_oldtable
</structfield></term>
783 A pointer to a structure of type
<structname>Tuplestorestate
</structname>
784 containing zero or more rows in the format specified by
785 <structfield>tg_relation
</structfield>, or a
<symbol>NULL
</symbol> pointer
786 if there is no
<literal>OLD TABLE
</literal> transition relation.
792 <term><structfield>tg_newtable
</structfield></term>
795 A pointer to a structure of type
<structname>Tuplestorestate
</structname>
796 containing zero or more rows in the format specified by
797 <structfield>tg_relation
</structfield>, or a
<symbol>NULL
</symbol> pointer
798 if there is no
<literal>NEW TABLE
</literal> transition relation.
804 <term><structfield>tg_updatedcols
</structfield></term>
807 For
<literal>UPDATE
</literal> triggers, a bitmap set indicating the
808 columns that were updated by the triggering command. Generic trigger
809 functions can use this to optimize actions by not having to deal with
810 columns that were not changed.
814 As an example, to determine whether a column with attribute number
815 <varname>attnum
</varname> (
1-based) is a member of this bitmap set,
816 call
<literal>bms_is_member(attnum -
817 FirstLowInvalidHeapAttributeNumber,
818 trigdata-
>tg_updatedcols))
</literal>.
822 For triggers other than
<literal>UPDATE
</literal> triggers, this will
823 be
<symbol>NULL
</symbol>.
831 To allow queries issued through SPI to reference transition tables, see
832 <xref linkend=
"spi-spi-register-trigger-data"/>.
836 A trigger function must return either a
837 <structname>HeapTuple
</structname> pointer or a
<symbol>NULL
</symbol> pointer
838 (
<emphasis>not
</emphasis> an SQL null value, that is, do not set
<parameter>isNull
</parameter> true).
839 Be careful to return either
840 <structfield>tg_trigtuple
</structfield> or
<structfield>tg_newtuple
</structfield>,
841 as appropriate, if you don't want to modify the row being operated on.
845 <sect1 id=
"trigger-example">
846 <title>A Complete Trigger Example
</title>
849 Here is a very simple example of a trigger function written in C.
850 (Examples of triggers written in procedural languages can be found
851 in the documentation of the procedural languages.)
855 The function
<function>trigf
</function> reports the number of rows in the
856 table
<structname>ttest
</structname> and skips the actual operation if the
857 command attempts to insert a null value into the column
858 <structfield>x
</structfield>. (So the trigger acts as a not-null constraint but
859 doesn't abort the transaction.)
863 First, the table definition:
872 This is the source code of the trigger function:
873 <programlisting><![CDATA[
874 #include
"postgres.h"
876 #include
"executor/spi.h" /* this is what you need to work with SPI */
877 #include
"commands/trigger.h" /* ... triggers ... */
878 #include
"utils/rel.h" /* ... and relations */
882 PG_FUNCTION_INFO_V1(trigf);
885 trigf(PG_FUNCTION_ARGS)
887 TriggerData *trigdata = (TriggerData *) fcinfo-
>context;
891 bool checknull = false;
895 /* make sure it's called as a trigger at all */
896 if (!CALLED_AS_TRIGGER(fcinfo))
897 elog(ERROR,
"trigf: not called by trigger manager");
899 /* tuple to return to executor */
900 if (TRIGGER_FIRED_BY_UPDATE(trigdata-
>tg_event))
901 rettuple = trigdata-
>tg_newtuple;
903 rettuple = trigdata-
>tg_trigtuple;
905 /* check for null values */
906 if (!TRIGGER_FIRED_BY_DELETE(trigdata-
>tg_event)
907 && TRIGGER_FIRED_BEFORE(trigdata-
>tg_event))
910 if (TRIGGER_FIRED_BEFORE(trigdata-
>tg_event))
915 tupdesc = trigdata-
>tg_relation-
>rd_att;
917 /* connect to SPI manager */
920 /* get number of rows in table */
921 ret = SPI_exec(
"SELECT count(*) FROM ttest",
0);
924 elog(ERROR,
"trigf (fired %s): SPI_exec returned %d", when, ret);
926 /* count(*) returns int8, so be careful to convert */
927 i = DatumGetInt64(SPI_getbinval(SPI_tuptable-
>vals[
0],
928 SPI_tuptable-
>tupdesc,
932 elog (INFO,
"trigf (fired %s): there are %d rows in ttest", when, i);
938 SPI_getbinval(rettuple, tupdesc,
1, &isnull);
943 return PointerGetDatum(rettuple);
950 After you have compiled the source code (see
<xref
951 linkend=
"dfunc"/>), declare the function and the triggers:
953 CREATE FUNCTION trigf() RETURNS trigger
954 AS '
<replaceable>filename
</replaceable>'
957 CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest
958 FOR EACH ROW EXECUTE FUNCTION trigf();
960 CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest
961 FOR EACH ROW EXECUTE FUNCTION trigf();
966 Now you can test the operation of the trigger:
968 =
> INSERT INTO ttest VALUES (NULL);
969 INFO: trigf (fired before): there are
0 rows in ttest
972 -- Insertion skipped and AFTER trigger is not fired
974 =
> SELECT * FROM ttest;
979 =
> INSERT INTO ttest VALUES (
1);
980 INFO: trigf (fired before): there are
0 rows in ttest
981 INFO: trigf (fired after ): there are
1 rows in ttest
983 remember what we said about visibility.
985 vac=
> SELECT * FROM ttest;
991 =
> INSERT INTO ttest SELECT x *
2 FROM ttest;
992 INFO: trigf (fired before): there are
1 rows in ttest
993 INFO: trigf (fired after ): there are
2 rows in ttest
995 remember what we said about visibility.
997 =
> SELECT * FROM ttest;
1004 =
> UPDATE ttest SET x = NULL WHERE x =
2;
1005 INFO: trigf (fired before): there are
2 rows in ttest
1007 =
> UPDATE ttest SET x =
4 WHERE x =
2;
1008 INFO: trigf (fired before): there are
2 rows in ttest
1009 INFO: trigf (fired after ): there are
2 rows in ttest
1011 vac=
> SELECT * FROM ttest;
1018 =
> DELETE FROM ttest;
1019 INFO: trigf (fired before): there are
2 rows in ttest
1020 INFO: trigf (fired before): there are
1 rows in ttest
1021 INFO: trigf (fired after ): there are
0 rows in ttest
1022 INFO: trigf (fired after ): there are
0 rows in ttest
1024 remember what we said about visibility.
1026 =
> SELECT * FROM ttest;
1035 There are more complex examples in
1036 <filename>src/test/regress/regress.c
</filename> and
1037 in
<xref linkend=
"contrib-spi"/>.