2010-09-20 22:08:53 +02:00
|
|
|
<!-- doc/src/sgml/trigger.sgml -->
|
2001-12-04 03:07:11 +01:00
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<chapter id="triggers">
|
|
|
|
<title>Triggers</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="triggers">
|
|
|
|
<primary>trigger</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2005-10-13 23:09:38 +02:00
|
|
|
This chapter provides general information about writing trigger functions.
|
|
|
|
Trigger functions can be written in most of the available procedural
|
|
|
|
languages, including
|
2017-11-23 15:39:47 +01:00
|
|
|
<application>PL/pgSQL</application> (<xref linkend="plpgsql"/>),
|
|
|
|
<application>PL/Tcl</application> (<xref linkend="pltcl"/>),
|
|
|
|
<application>PL/Perl</application> (<xref linkend="plperl"/>), and
|
|
|
|
<application>PL/Python</application> (<xref linkend="plpython"/>).
|
2005-10-13 23:09:38 +02:00
|
|
|
After reading this chapter, you should consult the chapter for
|
|
|
|
your favorite procedural language to find out the language-specific
|
|
|
|
details of writing a trigger in it.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
It is also possible to write a trigger function in C, although
|
|
|
|
most people find it easier to use one of the procedural languages.
|
|
|
|
It is not currently possible to write a trigger function in the
|
|
|
|
plain SQL function language.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
2002-04-19 18:36:08 +02:00
|
|
|
<sect1 id="trigger-definition">
|
2003-10-23 00:28:10 +02:00
|
|
|
<title>Overview of Trigger Behavior</title>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
<para>
|
2005-10-13 23:09:38 +02:00
|
|
|
A trigger is a specification that the database should automatically
|
|
|
|
execute a particular function whenever a certain type of operation is
|
2017-05-01 14:23:01 +02:00
|
|
|
performed. Triggers can be attached to tables (partitioned or not),
|
|
|
|
views, and foreign tables.
|
2010-10-10 19:43:33 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2014-03-23 07:16:34 +01:00
|
|
|
On tables and foreign tables, triggers can be defined to execute either
|
|
|
|
before or after any <command>INSERT</command>, <command>UPDATE</command>,
|
|
|
|
or <command>DELETE</command> operation, either once per modified row,
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
or once per <acronym>SQL</acronym> statement.
|
|
|
|
<command>UPDATE</command> triggers can moreover be set to fire only if
|
|
|
|
certain columns are mentioned in the <literal>SET</literal> clause of
|
|
|
|
the <command>UPDATE</command> statement. Triggers can also fire
|
|
|
|
for <command>TRUNCATE</command> statements. If a trigger event occurs,
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
the trigger's function is called at the appropriate time to handle the
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
event.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
<para>
|
|
|
|
On views, triggers can be defined to execute instead of
|
|
|
|
<command>INSERT</command>, <command>UPDATE</command>, or
|
2018-03-18 20:10:28 +01:00
|
|
|
<command>DELETE</command> operations.
|
|
|
|
Such <literal>INSTEAD OF</literal> triggers
|
2010-10-10 19:43:33 +02:00
|
|
|
are fired once for each row that needs to be modified in the view.
|
|
|
|
It is the responsibility of the
|
2018-03-18 20:10:28 +01:00
|
|
|
trigger's function to perform the necessary modifications to the view's
|
|
|
|
underlying base table(s) and, where appropriate, return the modified
|
2010-10-10 19:43:33 +02:00
|
|
|
row as it will appear in the view. Triggers on views can also be defined
|
|
|
|
to execute once per <acronym>SQL</acronym> statement, before or after
|
|
|
|
<command>INSERT</command>, <command>UPDATE</command>, or
|
|
|
|
<command>DELETE</command> operations.
|
2018-03-18 20:10:28 +01:00
|
|
|
However, such triggers are fired only if there is also
|
|
|
|
an <literal>INSTEAD OF</literal> trigger on the view. Otherwise,
|
|
|
|
any statement targeting the view must be rewritten into a statement
|
|
|
|
affecting its underlying base table(s), and then the triggers
|
|
|
|
that will be fired are the ones attached to the base table(s).
|
2010-10-10 19:43:33 +02:00
|
|
|
</para>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2002-04-19 18:36:08 +02:00
|
|
|
The trigger function must be defined before the trigger itself can be
|
2008-03-28 01:21:56 +01:00
|
|
|
created. The trigger function must be declared as a
|
2017-10-09 03:44:17 +02:00
|
|
|
function taking no arguments and returning type <literal>trigger</literal>.
|
2003-10-23 00:28:10 +02:00
|
|
|
(The trigger function receives its input through a specially-passed
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>TriggerData</structname> structure, not in the form of ordinary function
|
2003-10-23 00:28:10 +02:00
|
|
|
arguments.)
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-10-23 00:28:10 +02:00
|
|
|
Once a suitable trigger function has been created, the trigger is
|
|
|
|
established with
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="sql-createtrigger"/>.
|
2003-10-23 00:28:10 +02:00
|
|
|
The same trigger function can be used for multiple triggers.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
<productname>PostgreSQL</productname> offers both <firstterm>per-row</firstterm>
|
|
|
|
triggers and <firstterm>per-statement</firstterm> triggers. With a per-row
|
2005-10-13 23:09:38 +02:00
|
|
|
trigger, the trigger function
|
|
|
|
is invoked once for each row that is affected by the statement
|
2004-01-22 20:50:21 +01:00
|
|
|
that fired the trigger. In contrast, a per-statement trigger is
|
|
|
|
invoked only once when an appropriate statement is executed,
|
|
|
|
regardless of the number of rows affected by that statement. In
|
|
|
|
particular, a statement that affects zero rows will still result
|
|
|
|
in the execution of any applicable per-statement triggers. These
|
2017-10-09 03:44:17 +02:00
|
|
|
two types of triggers are sometimes called <firstterm>row-level</firstterm>
|
|
|
|
triggers and <firstterm>statement-level</firstterm> triggers,
|
2008-03-28 01:21:56 +01:00
|
|
|
respectively. Triggers on <command>TRUNCATE</command> may only be
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
defined at statement level, not per-row.
|
2004-01-22 20:50:21 +01:00
|
|
|
</para>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<para>
|
2010-10-10 19:43:33 +02:00
|
|
|
Triggers are also classified according to whether they fire
|
2017-10-09 03:44:17 +02:00
|
|
|
<firstterm>before</firstterm>, <firstterm>after</firstterm>, or
|
|
|
|
<firstterm>instead of</firstterm> the operation. These are referred to
|
|
|
|
as <literal>BEFORE</literal> triggers, <literal>AFTER</literal> triggers, and
|
|
|
|
<literal>INSTEAD OF</literal> triggers respectively.
|
|
|
|
Statement-level <literal>BEFORE</literal> triggers naturally fire before the
|
|
|
|
statement starts to do anything, while statement-level <literal>AFTER</literal>
|
2010-10-10 19:43:33 +02:00
|
|
|
triggers fire at the very end of the statement. These types of
|
2017-05-01 14:23:01 +02:00
|
|
|
triggers may be defined on tables, views, or foreign tables. Row-level
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>BEFORE</literal> triggers fire immediately before a particular row is
|
|
|
|
operated on, while row-level <literal>AFTER</literal> triggers fire at the end of
|
|
|
|
the statement (but before any statement-level <literal>AFTER</literal> triggers).
|
2020-02-26 23:57:14 +01:00
|
|
|
These types of triggers may only be defined on tables and
|
2020-03-18 22:58:05 +01:00
|
|
|
foreign tables, not views.
|
2020-02-26 23:57:14 +01:00
|
|
|
<literal>INSTEAD OF</literal> triggers may only be
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
defined on views, and only at row level; they fire immediately as each
|
|
|
|
row in the view is identified as needing to be operated on.
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
|
2021-09-01 23:24:59 +02:00
|
|
|
<para>
|
|
|
|
The execution of an <literal>AFTER</literal> trigger can be deferred
|
|
|
|
to the end of the transaction, rather than the end of the statement,
|
|
|
|
if it was defined as a <firstterm>constraint trigger</firstterm>.
|
|
|
|
In all cases, a trigger is executed as part of the same transaction as
|
|
|
|
the statement that triggered it, so if either the statement or the
|
|
|
|
trigger causes an error, the effects of both will be rolled back.
|
|
|
|
</para>
|
|
|
|
|
2017-05-10 05:49:20 +02:00
|
|
|
<para>
|
2017-05-10 05:57:52 +02:00
|
|
|
A statement that targets a parent table in an inheritance or partitioning
|
2017-05-10 05:49:20 +02:00
|
|
|
hierarchy does not cause the statement-level triggers of affected child
|
|
|
|
tables to be fired; only the parent table's statement-level triggers are
|
|
|
|
fired. However, row-level triggers of any affected child tables will be
|
|
|
|
fired.
|
|
|
|
</para>
|
|
|
|
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
<para>
|
|
|
|
If an <command>INSERT</command> contains an <literal>ON CONFLICT
|
2017-10-09 03:44:17 +02:00
|
|
|
DO UPDATE</literal> clause, it is possible that the effects of
|
|
|
|
row-level <literal>BEFORE</literal> <command>INSERT</command> triggers and
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
row-level <literal>BEFORE</literal> <command>UPDATE</command> triggers can
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
both be applied in a way that is apparent from the final state of
|
2017-10-09 03:44:17 +02:00
|
|
|
the updated row, if an <varname>EXCLUDED</varname> column is referenced.
|
|
|
|
There need not be an <varname>EXCLUDED</varname> column reference for
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
both sets of row-level <literal>BEFORE</literal> triggers to execute,
|
|
|
|
though. The
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
possibility of surprising outcomes should be considered when there
|
2017-10-09 03:44:17 +02:00
|
|
|
are both <literal>BEFORE</literal> <command>INSERT</command> and
|
|
|
|
<literal>BEFORE</literal> <command>UPDATE</command> row-level triggers
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
that change a row being inserted/updated (this can be
|
|
|
|
problematic even if the modifications are more or less equivalent, if
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
they're not also idempotent). Note that statement-level
|
|
|
|
<command>UPDATE</command> triggers are executed when <literal>ON
|
2017-10-09 03:44:17 +02:00
|
|
|
CONFLICT DO UPDATE</literal> is specified, regardless of whether or not
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
any rows were affected by the <command>UPDATE</command> (and
|
|
|
|
regardless of whether the alternative <command>UPDATE</command>
|
|
|
|
path was ever taken). An <command>INSERT</command> with an
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>ON CONFLICT DO UPDATE</literal> clause will execute
|
|
|
|
statement-level <literal>BEFORE</literal> <command>INSERT</command>
|
|
|
|
triggers first, then statement-level <literal>BEFORE</literal>
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
<command>UPDATE</command> triggers, followed by statement-level
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>AFTER</literal> <command>UPDATE</command> triggers and finally
|
|
|
|
statement-level <literal>AFTER</literal> <command>INSERT</command>
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
triggers.
|
|
|
|
</para>
|
|
|
|
|
Allow UPDATE to move rows between partitions.
When an UPDATE causes a row to no longer match the partition
constraint, try to move it to a different partition where it does
match the partition constraint. In essence, the UPDATE is split into
a DELETE from the old partition and an INSERT into the new one. This
can lead to surprising behavior in concurrency scenarios because
EvalPlanQual rechecks won't work as they normally did; the known
problems are documented. (There is a pending patch to improve the
situation further, but it needs more review.)
Amit Khandekar, reviewed and tested by Amit Langote, David Rowley,
Rajkumar Raghuwanshi, Dilip Kumar, Amul Sul, Thomas Munro, Álvaro
Herrera, Amit Kapila, and me. A few final revisions by me.
Discussion: http://postgr.es/m/CAJ3gD9do9o2ccQ7j7+tSgiE1REY65XRiMb=yJO3u3QhyP8EEPQ@mail.gmail.com
2018-01-19 21:33:06 +01:00
|
|
|
<para>
|
|
|
|
If an <command>UPDATE</command> on a partitioned table causes a row to move
|
|
|
|
to another partition, it will be performed as a <command>DELETE</command>
|
|
|
|
from the original partition followed by an <command>INSERT</command> into
|
|
|
|
the new partition. In this case, all row-level <literal>BEFORE</literal>
|
|
|
|
<command>UPDATE</command> triggers and all row-level
|
|
|
|
<literal>BEFORE</literal> <command>DELETE</command> triggers are fired on
|
|
|
|
the original partition. Then all row-level <literal>BEFORE</literal>
|
|
|
|
<command>INSERT</command> triggers are fired on the destination partition.
|
|
|
|
The possibility of surprising outcomes should be considered when all these
|
|
|
|
triggers affect the row being moved. As far as <literal>AFTER ROW</literal>
|
|
|
|
triggers are concerned, <literal>AFTER</literal> <command>DELETE</command>
|
|
|
|
and <literal>AFTER</literal> <command>INSERT</command> triggers are
|
|
|
|
applied; but <literal>AFTER</literal> <command>UPDATE</command> triggers
|
|
|
|
are not applied because the <command>UPDATE</command> has been converted to
|
|
|
|
a <command>DELETE</command> and an <command>INSERT</command>. As far as
|
|
|
|
statement-level triggers are concerned, none of the
|
|
|
|
<command>DELETE</command> or <command>INSERT</command> triggers are fired,
|
|
|
|
even if row movement occurs; only the <command>UPDATE</command> triggers
|
|
|
|
defined on the target table used in the <command>UPDATE</command> statement
|
|
|
|
will be fired.
|
|
|
|
</para>
|
|
|
|
|
2022-03-28 16:45:58 +02:00
|
|
|
<para>
|
|
|
|
No separate triggers are defined for <command>MERGE</command>. Instead,
|
|
|
|
statement-level or row-level <command>UPDATE</command>,
|
|
|
|
<command>DELETE</command>, and <command>INSERT</command> triggers are fired
|
|
|
|
depending on (for statement-level triggers) what actions are specified in
|
|
|
|
the <command>MERGE</command> query and (for row-level triggers) what
|
|
|
|
actions are performed.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
While running a <command>MERGE</command> command, statement-level
|
|
|
|
<literal>BEFORE</literal> and <literal>AFTER</literal> triggers are
|
|
|
|
fired for events specified in the actions of the <command>MERGE</command>
|
|
|
|
command, irrespective of whether or not the action is ultimately performed.
|
|
|
|
This is the same as an <command>UPDATE</command> statement that updates
|
|
|
|
no rows, yet statement-level triggers are fired.
|
|
|
|
The row-level triggers are fired only when a row is actually updated,
|
|
|
|
inserted or deleted. So it's perfectly legal that while statement-level
|
|
|
|
triggers are fired for certain types of action, no row-level triggers
|
|
|
|
are fired for the same kind of action.
|
|
|
|
</para>
|
|
|
|
|
2004-01-22 20:50:21 +01:00
|
|
|
<para>
|
|
|
|
Trigger functions invoked by per-statement triggers should always
|
|
|
|
return <symbol>NULL</symbol>. Trigger functions invoked by per-row
|
|
|
|
triggers can return a table row (a value of
|
|
|
|
type <structname>HeapTuple</structname>) to the calling executor,
|
|
|
|
if they choose. A row-level trigger fired before an operation has
|
|
|
|
the following choices:
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
It can return <symbol>NULL</symbol> to skip the operation for the
|
2004-01-22 20:50:21 +01:00
|
|
|
current row. This instructs the executor to not perform the
|
2010-10-10 19:43:33 +02:00
|
|
|
row-level operation that invoked the trigger (the insertion,
|
|
|
|
modification, or deletion of a particular table row).
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-01-22 20:50:21 +01:00
|
|
|
For row-level <command>INSERT</command>
|
|
|
|
and <command>UPDATE</command> triggers only, the returned row
|
|
|
|
becomes the row that will be inserted or will replace the row
|
|
|
|
being updated. This allows the trigger function to modify the
|
|
|
|
row being inserted or updated.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
2002-04-19 18:36:08 +02:00
|
|
|
|
2017-10-09 03:44:17 +02:00
|
|
|
A row-level <literal>BEFORE</literal> trigger that does not intend to cause
|
2010-10-10 19:43:33 +02:00
|
|
|
either of these behaviors must be careful to return as its result the same
|
2004-01-22 20:50:21 +01:00
|
|
|
row that was passed in (that is, the <varname>NEW</varname> row
|
|
|
|
for <command>INSERT</command> and <command>UPDATE</command>
|
|
|
|
triggers, the <varname>OLD</varname> row for
|
2003-11-15 20:46:31 +01:00
|
|
|
<command>DELETE</command> triggers).
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
A row-level <literal>INSTEAD OF</literal> trigger should either return
|
|
|
|
<symbol>NULL</symbol> to indicate that it did not modify any data from
|
2010-10-10 19:43:33 +02:00
|
|
|
the view's underlying base tables, or it should return the view
|
|
|
|
row that was passed in (the <varname>NEW</varname> row
|
|
|
|
for <command>INSERT</command> and <command>UPDATE</command>
|
|
|
|
operations, or the <varname>OLD</varname> row for
|
|
|
|
<command>DELETE</command> operations). A nonnull return value is
|
|
|
|
used to signal that the trigger performed the necessary data
|
|
|
|
modifications in the view. This will cause the count of the number
|
|
|
|
of rows affected by the command to be incremented. For
|
2019-11-07 21:50:00 +01:00
|
|
|
<command>INSERT</command> and <command>UPDATE</command> operations only, the trigger
|
2017-10-09 03:44:17 +02:00
|
|
|
may modify the <varname>NEW</varname> row before returning it. This will
|
2010-10-10 19:43:33 +02:00
|
|
|
change the data returned by
|
2017-10-09 03:44:17 +02:00
|
|
|
<command>INSERT RETURNING</command> or <command>UPDATE RETURNING</command>,
|
2010-10-10 19:43:33 +02:00
|
|
|
and is useful when the view will not show exactly the same data
|
|
|
|
that was provided.
|
|
|
|
</para>
|
|
|
|
|
2003-10-23 00:28:10 +02:00
|
|
|
<para>
|
2004-01-22 20:50:21 +01:00
|
|
|
The return value is ignored for row-level triggers fired after an
|
2017-10-09 03:44:17 +02:00
|
|
|
operation, and so they can return <symbol>NULL</symbol>.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
2019-03-30 08:13:09 +01:00
|
|
|
<para>
|
|
|
|
Some considerations apply for generated
|
|
|
|
columns.<indexterm><primary>generated column</primary><secondary>in
|
|
|
|
triggers</secondary></indexterm> Stored generated columns are computed after
|
|
|
|
<literal>BEFORE</literal> triggers and before <literal>AFTER</literal>
|
|
|
|
triggers. Therefore, the generated value can be inspected in
|
|
|
|
<literal>AFTER</literal> triggers. In <literal>BEFORE</literal> triggers,
|
|
|
|
the <literal>OLD</literal> row contains the old generated value, as one
|
|
|
|
would expect, but the <literal>NEW</literal> row does not yet contain the
|
|
|
|
new generated value and should not be accessed. In the C language
|
|
|
|
interface, the content of the column is undefined at this point; a
|
|
|
|
higher-level programming language should prevent access to a stored
|
|
|
|
generated column in the <literal>NEW</literal> row in a
|
|
|
|
<literal>BEFORE</literal> trigger. Changes to the value of a generated
|
|
|
|
column in a <literal>BEFORE</literal> trigger are ignored and will be
|
|
|
|
overwritten.
|
|
|
|
</para>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2002-09-21 20:32:54 +02:00
|
|
|
If more than one trigger is defined for the same event on the same
|
2004-01-22 20:50:21 +01:00
|
|
|
relation, the triggers will be fired in alphabetical order by
|
2017-10-09 03:44:17 +02:00
|
|
|
trigger name. In the case of <literal>BEFORE</literal> and
|
|
|
|
<literal>INSTEAD OF</literal> triggers, the possibly-modified row returned by
|
2010-10-10 19:43:33 +02:00
|
|
|
each trigger becomes the input to the next trigger. If any
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>BEFORE</literal> or <literal>INSTEAD OF</literal> trigger returns
|
|
|
|
<symbol>NULL</symbol>, the operation is abandoned for that row and subsequent
|
2010-10-10 19:43:33 +02:00
|
|
|
triggers are not fired (for that row).
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
A trigger definition can also specify a Boolean <literal>WHEN</literal>
|
2009-11-20 21:38:12 +01:00
|
|
|
condition, which will be tested to see whether the trigger should
|
2017-10-09 03:44:17 +02:00
|
|
|
be fired. In row-level triggers the <literal>WHEN</literal> condition can
|
2009-11-20 21:38:12 +01:00
|
|
|
examine the old and/or new values of columns of the row. (Statement-level
|
2017-10-09 03:44:17 +02:00
|
|
|
triggers can also have <literal>WHEN</literal> conditions, although the feature
|
|
|
|
is not so useful for them.) In a <literal>BEFORE</literal> trigger, the
|
|
|
|
<literal>WHEN</literal>
|
2009-11-20 21:38:12 +01:00
|
|
|
condition is evaluated just before the function is or would be executed,
|
2017-10-09 03:44:17 +02:00
|
|
|
so using <literal>WHEN</literal> is not materially different from testing the
|
2009-11-20 21:38:12 +01:00
|
|
|
same condition at the beginning of the trigger function. However, in
|
2017-10-09 03:44:17 +02:00
|
|
|
an <literal>AFTER</literal> trigger, the <literal>WHEN</literal> condition is evaluated
|
2010-10-10 19:43:33 +02:00
|
|
|
just after the row update occurs, and it determines whether an event is
|
|
|
|
queued to fire the trigger at the end of statement. So when an
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>AFTER</literal> trigger's
|
|
|
|
<literal>WHEN</literal> condition does not return true, it is not necessary
|
2009-11-20 21:38:12 +01:00
|
|
|
to queue an event nor to re-fetch the row at end of statement. This
|
|
|
|
can result in significant speedups in statements that modify many
|
|
|
|
rows, if the trigger only needs to be fired for a few of the rows.
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>INSTEAD OF</literal> triggers do not support
|
|
|
|
<literal>WHEN</literal> conditions.
|
2009-11-20 21:38:12 +01:00
|
|
|
</para>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Typically, row-level <literal>BEFORE</literal> triggers are used for checking or
|
2004-12-30 04:13:56 +01:00
|
|
|
modifying the data that will be inserted or updated. For example,
|
2017-10-09 03:44:17 +02:00
|
|
|
a <literal>BEFORE</literal> trigger might be used to insert the current time into a
|
2005-11-05 00:14:02 +01:00
|
|
|
<type>timestamp</type> column, or to check that two elements of the row are
|
2017-10-09 03:44:17 +02:00
|
|
|
consistent. Row-level <literal>AFTER</literal> triggers are most sensibly
|
2004-12-30 04:13:56 +01:00
|
|
|
used to propagate the updates to other tables, or make consistency
|
|
|
|
checks against other tables. The reason for this division of labor is
|
2017-10-09 03:44:17 +02:00
|
|
|
that an <literal>AFTER</literal> trigger can be certain it is seeing the final
|
|
|
|
value of the row, while a <literal>BEFORE</literal> trigger cannot; there might
|
|
|
|
be other <literal>BEFORE</literal> triggers firing after it. If you have no
|
|
|
|
specific reason to make a trigger <literal>BEFORE</literal> or
|
|
|
|
<literal>AFTER</literal>, the <literal>BEFORE</literal> case is more efficient, since
|
2010-10-10 19:43:33 +02:00
|
|
|
the information about
|
2004-12-30 04:13:56 +01:00
|
|
|
the operation doesn't have to be saved until end of statement.
|
|
|
|
</para>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2003-10-23 00:28:10 +02:00
|
|
|
If a trigger function executes SQL commands then these
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
commands might fire triggers again. This is known as cascading
|
2002-11-23 04:59:09 +01:00
|
|
|
triggers. There is no direct limitation on the number of cascade
|
2003-04-11 20:41:20 +02:00
|
|
|
levels. It is possible for cascades to cause a recursive invocation
|
|
|
|
of the same trigger; for example, an <command>INSERT</command>
|
|
|
|
trigger might execute a command that inserts an additional row
|
2002-11-23 04:59:09 +01:00
|
|
|
into the same table, causing the <command>INSERT</command> trigger
|
|
|
|
to be fired again. It is the trigger programmer's responsibility
|
|
|
|
to avoid infinite recursion in such scenarios.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
2002-11-23 04:59:09 +01:00
|
|
|
|
|
|
|
<para>
|
2011-04-08 17:36:05 +02:00
|
|
|
<indexterm>
|
2017-10-09 03:44:17 +02:00
|
|
|
<primary>trigger</primary>
|
|
|
|
<secondary>arguments for trigger functions</secondary>
|
2011-04-08 17:36:05 +02:00
|
|
|
</indexterm>
|
2003-04-11 20:41:20 +02:00
|
|
|
When a trigger is being defined, arguments can be specified for
|
2011-04-08 17:36:05 +02:00
|
|
|
it. The purpose of including arguments in the
|
2003-08-31 19:32:24 +02:00
|
|
|
trigger definition is to allow different triggers with similar
|
|
|
|
requirements to call the same function. As an example, there
|
|
|
|
could be a generalized trigger function that takes as its
|
|
|
|
arguments two column names and puts the current user in one and
|
|
|
|
the current time stamp in the other. Properly written, this
|
|
|
|
trigger function would be independent of the specific table it is
|
|
|
|
triggering on. So the same function could be used for
|
|
|
|
<command>INSERT</command> events on any table with suitable
|
|
|
|
columns, to automatically track creation of records in a
|
|
|
|
transaction table for example. It could also be used to track
|
|
|
|
last-update events if defined as an <command>UPDATE</command>
|
|
|
|
trigger.
|
2002-11-23 04:59:09 +01:00
|
|
|
</para>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<para>
|
|
|
|
Each programming language that supports triggers has its own method
|
|
|
|
for making the trigger input data available to the trigger function.
|
|
|
|
This input data includes the type of trigger event (e.g.,
|
|
|
|
<command>INSERT</command> or <command>UPDATE</command>) as well as any
|
2017-10-09 03:44:17 +02:00
|
|
|
arguments that were listed in <command>CREATE TRIGGER</command>.
|
2004-12-30 04:13:56 +01:00
|
|
|
For a row-level trigger, the input data also includes the
|
|
|
|
<varname>NEW</varname> row for <command>INSERT</command> and
|
|
|
|
<command>UPDATE</command> triggers, and/or the <varname>OLD</varname> row
|
|
|
|
for <command>UPDATE</command> and <command>DELETE</command> triggers.
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
By default, statement-level triggers do not have any way to examine the
|
|
|
|
individual row(s) modified by the statement. But an <literal>AFTER
|
2017-10-09 03:44:17 +02:00
|
|
|
STATEMENT</literal> trigger can request that <firstterm>transition tables</firstterm>
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
be created to make the sets of affected rows available to the trigger.
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>AFTER ROW</literal> triggers can also request transition tables, so
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
that they can see the total changes in the table as well as the change in
|
2017-09-16 21:31:26 +02:00
|
|
|
the individual row they are currently being fired for. The method for
|
Fix SQL-spec incompatibilities in new transition table feature.
The standard says that all changes of the same kind (insert, update, or
delete) caused in one table by a single SQL statement should be reported
in a single transition table; and by that, they mean to include foreign key
enforcement actions cascading from the statement's direct effects. It's
also reasonable to conclude that if the standard had wCTEs, they would say
that effects of wCTEs applying to the same table as each other or the outer
statement should be merged into one transition table. We weren't doing it
like that.
Hence, arrange to merge tuples from multiple update actions into a single
transition table as much as we can. There is a problem, which is that if
the firing of FK enforcement triggers and after-row triggers with
transition tables is interspersed, we might need to report more tuples
after some triggers have already seen the transition table. It seems like
a bad idea for the transition table to be mutable between trigger calls.
There's no good way around this without a major redesign of the FK logic,
so for now, resolve it by opening a new transition table each time this
happens.
Also, ensure that AFTER STATEMENT triggers fire just once per statement,
or once per transition table when we're forced to make more than one.
Previous versions of Postgres have allowed each FK enforcement query
to cause an additional firing of the AFTER STATEMENT triggers for the
referencing table, but that's certainly not per spec. (We're still
doing multiple firings of BEFORE STATEMENT triggers, though; is that
something worth changing?)
Also, forbid using transition tables with column-specific UPDATE triggers.
The spec requires such transition tables to show only the tuples for which
the UPDATE trigger would have fired, which means maintaining multiple
transition tables or else somehow filtering the contents at readout.
Maybe someday we'll bother to support that option, but it looks like a
lot of trouble for a marginal feature.
The transition tables are now managed by the AfterTriggers data structures,
rather than being directly the responsibility of ModifyTable nodes. This
removes a subtransaction-lifespan memory leak introduced by my previous
band-aid patch 3c4359521.
In passing, refactor the AfterTriggers data structures to reduce the
management overhead for them, by using arrays of structs rather than
several parallel arrays for per-query-level and per-subtransaction state.
I failed to resist the temptation to do some copy-editing on the SGML
docs about triggers, above and beyond merely documenting the effects
of this patch.
Back-patch to v10, because we don't want the semantics of transition
tables to change post-release.
Patch by me, with help and review from Thomas Munro.
Discussion: https://postgr.es/m/20170909064853.25630.12825@wrigleys.postgresql.org
2017-09-16 19:20:32 +02:00
|
|
|
examining the transition tables again depends on the programming language
|
2017-09-16 21:31:26 +02:00
|
|
|
that is being used, but the typical approach is to make the transition
|
|
|
|
tables act like read-only temporary tables that can be accessed by SQL
|
|
|
|
commands issued within the trigger function.
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
</sect1>
|
|
|
|
|
2003-10-23 00:28:10 +02:00
|
|
|
<sect1 id="trigger-datachanges">
|
|
|
|
<title>Visibility of Data Changes</title>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
If you execute SQL commands in your trigger function, and these
|
|
|
|
commands access the table that the trigger is for, then
|
|
|
|
you need to be aware of the data visibility rules, because they determine
|
|
|
|
whether these SQL commands will see the data change that the trigger
|
|
|
|
is fired for. Briefly:
|
|
|
|
|
|
|
|
<itemizedlist>
|
2004-01-22 20:50:21 +01:00
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Statement-level triggers follow simple visibility rules: none of
|
|
|
|
the changes made by a statement are visible to statement-level
|
2016-04-29 19:03:58 +02:00
|
|
|
<literal>BEFORE</literal> triggers, whereas all
|
2017-10-09 03:44:17 +02:00
|
|
|
modifications are visible to statement-level <literal>AFTER</literal>
|
2010-10-10 19:43:33 +02:00
|
|
|
triggers.
|
2004-01-22 20:50:21 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2003-10-23 00:28:10 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-01-22 20:50:21 +01:00
|
|
|
The data change (insertion, update, or deletion) causing the
|
|
|
|
trigger to fire is naturally <emphasis>not</emphasis> visible
|
2017-10-09 03:44:17 +02:00
|
|
|
to SQL commands executed in a row-level <literal>BEFORE</literal> trigger,
|
2010-10-10 19:43:33 +02:00
|
|
|
because it hasn't happened yet.
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
However, SQL commands executed in a row-level <literal>BEFORE</literal>
|
2004-01-22 20:50:21 +01:00
|
|
|
trigger <emphasis>will</emphasis> see the effects of data
|
|
|
|
changes for rows previously processed in the same outer
|
|
|
|
command. This requires caution, since the ordering of these
|
2021-06-11 03:38:04 +02:00
|
|
|
change events is not in general predictable; an SQL command that
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
affects multiple rows can visit the rows in any order.
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Similarly, a row-level <literal>INSTEAD OF</literal> trigger will see the
|
2010-10-10 19:43:33 +02:00
|
|
|
effects of data changes made by previous firings of <literal>INSTEAD
|
2017-10-09 03:44:17 +02:00
|
|
|
OF</literal> triggers in the same outer command.
|
2010-10-10 19:43:33 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
When a row-level <literal>AFTER</literal> trigger is fired, all data
|
2010-10-10 19:43:33 +02:00
|
|
|
changes made
|
2004-01-22 20:50:21 +01:00
|
|
|
by the outer command are already complete, and are visible to
|
|
|
|
the invoked trigger function.
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
2009-05-27 03:18:06 +02:00
|
|
|
<para>
|
|
|
|
If your trigger function is written in any of the standard procedural
|
|
|
|
languages, then the above statements apply only if the function is
|
2017-10-09 03:44:17 +02:00
|
|
|
declared <literal>VOLATILE</literal>. Functions that are declared
|
|
|
|
<literal>STABLE</literal> or <literal>IMMUTABLE</literal> will not see changes made by
|
2009-05-27 03:18:06 +02:00
|
|
|
the calling command in any case.
|
|
|
|
</para>
|
|
|
|
|
2003-10-23 00:28:10 +02:00
|
|
|
<para>
|
|
|
|
Further information about data visibility rules can be found in
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="spi-visibility"/>. The example in <xref
|
|
|
|
linkend="trigger-example"/> contains a demonstration of these rules.
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
</sect1>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2003-10-23 00:28:10 +02:00
|
|
|
<sect1 id="trigger-interface">
|
|
|
|
<title>Writing Trigger Functions in C</title>
|
|
|
|
|
|
|
|
<indexterm zone="trigger-interface">
|
2003-08-31 19:32:24 +02:00
|
|
|
<primary>trigger</primary>
|
|
|
|
<secondary>in C</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2017-04-05 01:36:39 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>transition tables</primary>
|
|
|
|
<secondary>referencing from C trigger</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2000-05-29 03:59:17 +02:00
|
|
|
This section describes the low-level details of the interface to a
|
2005-10-13 23:09:38 +02:00
|
|
|
trigger function. This information is only needed when writing
|
|
|
|
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 triggers in C. The
|
|
|
|
documentation of each procedural language explains how to write a
|
|
|
|
trigger in that language.
|
2003-10-23 00:28:10 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
Trigger functions must use the <quote>version 1</quote> function manager
|
2003-10-23 00:28:10 +02:00
|
|
|
interface.
|
2000-05-29 03:59:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2002-11-23 04:59:09 +01:00
|
|
|
When a function is called by the trigger manager, it is not passed
|
2017-10-09 03:44:17 +02:00
|
|
|
any normal arguments, but it is passed a <quote>context</quote>
|
|
|
|
pointer pointing to a <structname>TriggerData</structname> structure. C
|
2002-11-23 04:59:09 +01:00
|
|
|
functions can check whether they were called from the trigger
|
2007-02-01 01:28:19 +01:00
|
|
|
manager or not by executing the macro:
|
2003-04-11 20:41:20 +02:00
|
|
|
<programlisting>
|
|
|
|
CALLED_AS_TRIGGER(fcinfo)
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
which expands to:
|
2002-09-21 20:32:54 +02:00
|
|
|
<programlisting>
|
2007-12-04 00:49:51 +01:00
|
|
|
((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))
|
2002-09-21 20:32:54 +02:00
|
|
|
</programlisting>
|
2002-11-23 04:59:09 +01:00
|
|
|
If this returns true, then it is safe to cast
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>fcinfo->context</literal> to type <literal>TriggerData
|
2002-11-23 04:59:09 +01:00
|
|
|
*</literal> and make use of the pointed-to
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>TriggerData</structname> structure. The function must
|
|
|
|
<emphasis>not</emphasis> alter the <structname>TriggerData</structname>
|
2000-05-29 03:59:17 +02:00
|
|
|
structure or any of the data it points to.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2002-03-22 20:20:45 +01:00
|
|
|
<structname>struct TriggerData</structname> is defined in
|
|
|
|
<filename>commands/trigger.h</filename>:
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2002-03-22 20:20:45 +01:00
|
|
|
<programlisting>
|
1998-03-01 09:16:16 +01:00
|
|
|
typedef struct TriggerData
|
|
|
|
{
|
2017-04-05 01:36:39 +02:00
|
|
|
NodeTag type;
|
|
|
|
TriggerEvent tg_event;
|
|
|
|
Relation tg_relation;
|
|
|
|
HeapTuple tg_trigtuple;
|
|
|
|
HeapTuple tg_newtuple;
|
|
|
|
Trigger *tg_trigger;
|
2019-12-10 10:00:30 +01:00
|
|
|
TupleTableSlot *tg_trigslot;
|
|
|
|
TupleTableSlot *tg_newslot;
|
2017-04-05 01:36:39 +02:00
|
|
|
Tuplestorestate *tg_oldtable;
|
|
|
|
Tuplestorestate *tg_newtable;
|
2020-03-09 09:22:22 +01:00
|
|
|
const Bitmapset *tg_updatedcols;
|
1998-03-01 09:16:16 +01:00
|
|
|
} TriggerData;
|
2002-03-22 20:20:45 +01:00
|
|
|
</programlisting>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
where the members are defined as follows:
|
|
|
|
|
|
|
|
<variablelist>
|
2000-05-29 03:59:17 +02:00
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>type</structfield></term>
|
2000-05-29 03:59:17 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2003-04-11 20:41:20 +02:00
|
|
|
Always <literal>T_TriggerData</literal>.
|
2000-05-29 03:59:17 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_event</structfield></term>
|
2000-05-02 22:02:03 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
Describes the event for which the function is called. You can use the
|
2004-12-30 04:13:56 +01:00
|
|
|
following macros to examine <literal>tg_event</literal>:
|
|
|
|
|
|
|
|
<variablelist>
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_BEFORE(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger fired before the operation.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_AFTER(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger fired after the operation.
|
2010-10-10 19:43:33 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_INSTEAD(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger fired instead of the operation.
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_FOR_ROW(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger fired for a row-level event.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_FOR_STATEMENT(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger fired for a statement-level event.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_BY_INSERT(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger was fired by an <command>INSERT</command> command.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_BY_UPDATE(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger was fired by an <command>UPDATE</command> command.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_BY_DELETE(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger was fired by a <command>DELETE</command> command.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2008-03-28 01:21:56 +01:00
|
|
|
|
|
|
|
<varlistentry>
|
|
|
|
<term><literal>TRIGGER_FIRED_BY_TRUNCATE(tg_event)</literal></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Returns true if the trigger was fired by a <command>TRUNCATE</command> command.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2004-12-30 04:13:56 +01:00
|
|
|
</variablelist>
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_relation</structfield></term>
|
2000-05-02 22:02:03 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
A pointer to a structure describing the relation that the trigger fired for.
|
2017-10-09 03:44:17 +02:00
|
|
|
Look at <filename>utils/rel.h</filename> for details about
|
2004-12-30 04:13:56 +01:00
|
|
|
this structure. The most interesting things are
|
2017-10-09 03:44:17 +02:00
|
|
|
<literal>tg_relation->rd_att</literal> (descriptor of the relation
|
|
|
|
tuples) and <literal>tg_relation->rd_rel->relname</literal>
|
|
|
|
(relation name; the type is not <type>char*</type> but
|
|
|
|
<type>NameData</type>; use
|
|
|
|
<literal>SPI_getrelname(tg_relation)</literal> to get a <type>char*</type> if you
|
2004-12-30 04:13:56 +01:00
|
|
|
need a copy of the name).
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_trigtuple</structfield></term>
|
2000-05-02 22:02:03 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
A pointer to the row for which the trigger was fired. This is
|
|
|
|
the row being inserted, updated, or deleted. If this trigger
|
|
|
|
was fired for an <command>INSERT</command> or
|
|
|
|
<command>DELETE</command> then this is what you should return
|
|
|
|
from the function if you don't want to replace the row with
|
|
|
|
a different one (in the case of <command>INSERT</command>) or
|
2014-03-23 07:16:34 +01:00
|
|
|
skip the operation. For triggers on foreign tables, values of system
|
|
|
|
columns herein are unspecified.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_newtuple</structfield></term>
|
2000-05-02 22:02:03 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
A pointer to the new version of the row, if the trigger was
|
2017-10-09 03:44:17 +02:00
|
|
|
fired for an <command>UPDATE</command>, and <symbol>NULL</symbol> if
|
2004-12-30 04:13:56 +01:00
|
|
|
it is for an <command>INSERT</command> or a
|
|
|
|
<command>DELETE</command>. This is what you have to return
|
|
|
|
from the function if the event is an <command>UPDATE</command>
|
|
|
|
and you don't want to replace this row by a different one or
|
2014-03-23 07:16:34 +01:00
|
|
|
skip the operation. For triggers on foreign tables, values of system
|
|
|
|
columns herein are unspecified.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_trigger</structfield></term>
|
2000-05-02 22:02:03 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
A pointer to a structure of type <structname>Trigger</structname>,
|
|
|
|
defined in <filename>utils/reltrigger.h</filename>:
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2002-09-21 20:32:54 +02:00
|
|
|
<programlisting>
|
1998-03-01 09:16:16 +01:00
|
|
|
typedef struct Trigger
|
|
|
|
{
|
2000-01-11 06:37:11 +01:00
|
|
|
Oid tgoid;
|
|
|
|
char *tgname;
|
|
|
|
Oid tgfoid;
|
|
|
|
int16 tgtype;
|
2012-03-20 17:14:16 +01:00
|
|
|
char tgenabled;
|
2010-01-17 23:56:23 +01:00
|
|
|
bool tgisinternal;
|
2002-04-02 00:36:13 +02:00
|
|
|
Oid tgconstrrelid;
|
2009-07-28 04:56:31 +02:00
|
|
|
Oid tgconstrindid;
|
2007-02-14 02:58:58 +01:00
|
|
|
Oid tgconstraint;
|
2000-01-11 06:37:11 +01:00
|
|
|
bool tgdeferrable;
|
|
|
|
bool tginitdeferred;
|
|
|
|
int16 tgnargs;
|
2005-03-29 02:17:27 +02:00
|
|
|
int16 tgnattr;
|
|
|
|
int16 *tgattr;
|
2000-01-11 06:37:11 +01:00
|
|
|
char **tgargs;
|
2009-11-20 21:38:12 +01:00
|
|
|
char *tgqual;
|
2017-04-05 01:36:39 +02:00
|
|
|
char *tgoldtable;
|
|
|
|
char *tgnewtable;
|
1998-03-01 09:16:16 +01:00
|
|
|
} Trigger;
|
2002-09-21 20:32:54 +02:00
|
|
|
</programlisting>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2017-10-09 03:44:17 +02:00
|
|
|
where <structfield>tgname</structfield> is the trigger's name,
|
|
|
|
<structfield>tgnargs</structfield> is the number of arguments in
|
|
|
|
<structfield>tgargs</structfield>, and <structfield>tgargs</structfield> is an array of
|
2002-11-23 04:59:09 +01:00
|
|
|
pointers to the arguments specified in the <command>CREATE
|
2003-04-11 20:41:20 +02:00
|
|
|
TRIGGER</command> statement. The other members are for internal use
|
2002-11-23 04:59:09 +01:00
|
|
|
only.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2004-10-30 22:53:06 +02:00
|
|
|
|
|
|
|
<varlistentry>
|
2019-12-10 10:00:30 +01:00
|
|
|
<term><structfield>tg_trigslot</structfield></term>
|
2004-10-30 22:53:06 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2019-12-10 10:00:30 +01:00
|
|
|
The slot containing <structfield>tg_trigtuple</structfield>,
|
|
|
|
or a <symbol>NULL</symbol> pointer if there is no such tuple.
|
2004-10-30 22:53:06 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2019-12-10 10:00:30 +01:00
|
|
|
<term><structfield>tg_newslot</structfield></term>
|
2004-10-30 22:53:06 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2019-12-10 10:00:30 +01:00
|
|
|
The slot containing <structfield>tg_newtuple</structfield>,
|
|
|
|
or a <symbol>NULL</symbol> pointer if there is no such tuple.
|
2004-10-30 22:53:06 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2017-04-05 01:36:39 +02:00
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_oldtable</structfield></term>
|
2017-04-05 01:36:39 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A pointer to a structure of type <structname>Tuplestorestate</structname>
|
|
|
|
containing zero or more rows in the format specified by
|
2017-10-09 03:44:17 +02:00
|
|
|
<structfield>tg_relation</structfield>, or a <symbol>NULL</symbol> pointer
|
2017-04-05 01:36:39 +02:00
|
|
|
if there is no <literal>OLD TABLE</literal> transition relation.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
|
|
|
<varlistentry>
|
2017-10-09 03:44:17 +02:00
|
|
|
<term><structfield>tg_newtable</structfield></term>
|
2017-04-05 01:36:39 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A pointer to a structure of type <structname>Tuplestorestate</structname>
|
|
|
|
containing zero or more rows in the format specified by
|
2017-10-09 03:44:17 +02:00
|
|
|
<structfield>tg_relation</structfield>, or a <symbol>NULL</symbol> pointer
|
2017-04-05 01:36:39 +02:00
|
|
|
if there is no <literal>NEW TABLE</literal> transition relation.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
|
|
|
|
2020-03-09 09:22:22 +01:00
|
|
|
<varlistentry>
|
|
|
|
<term><structfield>tg_updatedcols</structfield></term>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
For <literal>UPDATE</literal> triggers, a bitmap set indicating the
|
|
|
|
columns that were updated by the triggering command. Generic trigger
|
|
|
|
functions can use this to optimize actions by not having to deal with
|
|
|
|
columns that were not changed.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
As an example, to determine whether a column with attribute number
|
|
|
|
<varname>attnum</varname> (1-based) is a member of this bitmap set,
|
|
|
|
call <literal>bms_is_member(attnum -
|
|
|
|
FirstLowInvalidHeapAttributeNumber,
|
|
|
|
trigdata->tg_updatedcols))</literal>.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
For triggers other than <literal>UPDATE</literal> triggers, this will
|
|
|
|
be <symbol>NULL</symbol>.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</varlistentry>
|
2000-05-02 22:02:03 +02:00
|
|
|
</variablelist>
|
|
|
|
</para>
|
|
|
|
|
2017-04-05 01:36:39 +02:00
|
|
|
<para>
|
|
|
|
To allow queries issued through SPI to reference transition tables, see
|
2017-11-23 15:39:47 +01:00
|
|
|
<xref linkend="spi-spi-register-trigger-data"/>.
|
2017-04-05 01:36:39 +02:00
|
|
|
</para>
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2004-08-13 18:17:19 +02:00
|
|
|
A trigger function must return either a
|
2017-10-09 03:44:17 +02:00
|
|
|
<structname>HeapTuple</structname> pointer or a <symbol>NULL</symbol> pointer
|
|
|
|
(<emphasis>not</emphasis> an SQL null value, that is, do not set <parameter>isNull</parameter> true).
|
2004-08-13 18:17:19 +02:00
|
|
|
Be careful to return either
|
2017-10-09 03:44:17 +02:00
|
|
|
<structfield>tg_trigtuple</structfield> or <structfield>tg_newtuple</structfield>,
|
2003-10-23 00:28:10 +02:00
|
|
|
as appropriate, if you don't want to modify the row being operated on.
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
<sect1 id="trigger-example">
|
2009-08-05 00:04:37 +02:00
|
|
|
<title>A Complete Trigger Example</title>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
<para>
|
2003-04-11 20:41:20 +02:00
|
|
|
Here is a very simple example of a trigger function written in C.
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
(Examples of triggers written in procedural languages can be found
|
2003-10-23 00:28:10 +02:00
|
|
|
in the documentation of the procedural languages.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2017-10-09 03:44:17 +02:00
|
|
|
The function <function>trigf</function> reports the number of rows in the
|
|
|
|
table <structname>ttest</structname> and skips the actual operation if the
|
2003-04-11 20:41:20 +02:00
|
|
|
command attempts to insert a null value into the column
|
2017-10-09 03:44:17 +02:00
|
|
|
<structfield>x</structfield>. (So the trigger acts as a not-null constraint but
|
2003-04-11 20:41:20 +02:00
|
|
|
doesn't abort the transaction.)
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-04-11 20:41:20 +02:00
|
|
|
First, the table definition:
|
|
|
|
<programlisting>
|
|
|
|
CREATE TABLE ttest (
|
|
|
|
x integer
|
|
|
|
);
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
<para>
|
|
|
|
This is the source code of the trigger function:
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2003-04-11 20:41:20 +02:00
|
|
|
#include "postgres.h"
|
2017-02-02 22:49:46 +01:00
|
|
|
#include "fmgr.h"
|
2002-09-21 20:32:54 +02:00
|
|
|
#include "executor/spi.h" /* this is what you need to work with SPI */
|
2012-03-20 20:50:18 +01:00
|
|
|
#include "commands/trigger.h" /* ... triggers ... */
|
|
|
|
#include "utils/rel.h" /* ... and relations */
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2009-11-23 22:41:20 +01:00
|
|
|
PG_MODULE_MAGIC;
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(trigf);
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
Datum
|
|
|
|
trigf(PG_FUNCTION_ARGS)
|
1998-03-01 09:16:16 +01:00
|
|
|
{
|
2008-12-08 00:46:39 +01:00
|
|
|
TriggerData *trigdata = (TriggerData *) fcinfo->context;
|
2002-09-21 20:32:54 +02:00
|
|
|
TupleDesc tupdesc;
|
|
|
|
HeapTuple rettuple;
|
|
|
|
char *when;
|
|
|
|
bool checknull = false;
|
|
|
|
bool isnull;
|
|
|
|
int ret, i;
|
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
/* make sure it's called as a trigger at all */
|
2002-09-21 20:32:54 +02:00
|
|
|
if (!CALLED_AS_TRIGGER(fcinfo))
|
2003-04-11 20:41:20 +02:00
|
|
|
elog(ERROR, "trigf: not called by trigger manager");
|
2002-09-21 20:32:54 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
/* tuple to return to executor */
|
2008-12-08 00:46:39 +01:00
|
|
|
if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
|
|
|
|
rettuple = trigdata->tg_newtuple;
|
2002-09-21 20:32:54 +02:00
|
|
|
else
|
2008-12-08 00:46:39 +01:00
|
|
|
rettuple = trigdata->tg_trigtuple;
|
2002-09-21 20:32:54 +02:00
|
|
|
|
|
|
|
/* check for null values */
|
2008-12-08 00:46:39 +01:00
|
|
|
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)
|
|
|
|
&& TRIGGER_FIRED_BEFORE(trigdata->tg_event))
|
2002-09-21 20:32:54 +02:00
|
|
|
checknull = true;
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
|
2002-09-21 20:32:54 +02:00
|
|
|
when = "before";
|
|
|
|
else
|
|
|
|
when = "after ";
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
tupdesc = trigdata->tg_relation->rd_att;
|
2002-09-21 20:32:54 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
/* connect to SPI manager */
|
2008-12-08 00:46:39 +01:00
|
|
|
if ((ret = SPI_connect()) < 0)
|
2009-01-06 17:39:52 +01:00
|
|
|
elog(ERROR, "trigf (fired %s): SPI_connect returned %d", when, ret);
|
2002-09-21 20:32:54 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
/* get number of rows in table */
|
2002-09-21 20:32:54 +02:00
|
|
|
ret = SPI_exec("SELECT count(*) FROM ttest", 0);
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
if (ret < 0)
|
2009-01-06 17:39:52 +01:00
|
|
|
elog(ERROR, "trigf (fired %s): SPI_exec returned %d", when, ret);
|
2002-09-21 20:32:54 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
/* count(*) returns int8, so be careful to convert */
|
2008-12-08 00:46:39 +01:00
|
|
|
i = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
|
|
|
|
SPI_tuptable->tupdesc,
|
2003-04-11 20:41:20 +02:00
|
|
|
1,
|
2008-12-08 00:46:39 +01:00
|
|
|
&isnull));
|
2002-09-21 20:32:54 +02:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
elog (INFO, "trigf (fired %s): there are %d rows in ttest", when, i);
|
2002-09-21 20:32:54 +02:00
|
|
|
|
|
|
|
SPI_finish();
|
|
|
|
|
|
|
|
if (checknull)
|
|
|
|
{
|
2008-12-08 00:46:39 +01:00
|
|
|
SPI_getbinval(rettuple, tupdesc, 1, &isnull);
|
2002-09-21 20:32:54 +02:00
|
|
|
if (isnull)
|
|
|
|
rettuple = NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
return PointerGetDatum(rettuple);
|
1998-03-01 09:16:16 +01:00
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2002-09-21 20:32:54 +02:00
|
|
|
</programlisting>
|
2000-05-02 22:02:03 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
<para>
|
2009-04-07 06:02:41 +02:00
|
|
|
After you have compiled the source code (see <xref
|
2017-11-23 15:39:47 +01:00
|
|
|
linkend="dfunc"/>), declare the function and the triggers:
|
2002-09-21 20:32:54 +02:00
|
|
|
<programlisting>
|
2003-04-11 20:41:20 +02:00
|
|
|
CREATE FUNCTION trigf() RETURNS trigger
|
2017-10-09 03:44:17 +02:00
|
|
|
AS '<replaceable>filename</replaceable>'
|
2003-04-11 20:41:20 +02:00
|
|
|
LANGUAGE C;
|
|
|
|
|
2008-03-28 01:21:56 +01:00
|
|
|
CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest
|
2018-08-15 23:08:34 +02:00
|
|
|
FOR EACH ROW EXECUTE FUNCTION trigf();
|
2000-08-25 01:59:38 +02:00
|
|
|
|
2008-03-28 01:21:56 +01:00
|
|
|
CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest
|
2018-08-15 23:08:34 +02:00
|
|
|
FOR EACH ROW EXECUTE FUNCTION trigf();
|
2002-09-21 20:32:54 +02:00
|
|
|
</programlisting>
|
2003-04-11 20:41:20 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2003-04-11 20:41:20 +02:00
|
|
|
<para>
|
|
|
|
Now you can test the operation of the trigger:
|
|
|
|
<screen>
|
2005-01-22 23:56:36 +01:00
|
|
|
=> INSERT INTO ttest VALUES (NULL);
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 0 rows in ttest
|
1998-03-01 09:16:16 +01:00
|
|
|
INSERT 0 0
|
|
|
|
|
|
|
|
-- Insertion skipped and AFTER trigger is not fired
|
|
|
|
|
2005-01-22 23:56:36 +01:00
|
|
|
=> SELECT * FROM ttest;
|
2002-09-21 20:32:54 +02:00
|
|
|
x
|
|
|
|
---
|
1998-03-01 09:16:16 +01:00
|
|
|
(0 rows)
|
|
|
|
|
2005-01-22 23:56:36 +01:00
|
|
|
=> INSERT INTO ttest VALUES (1);
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 0 rows in ttest
|
|
|
|
INFO: trigf (fired after ): there are 1 rows in ttest
|
1998-03-01 09:16:16 +01:00
|
|
|
^^^^^^^^
|
|
|
|
remember what we said about visibility.
|
|
|
|
INSERT 167793 1
|
2005-01-22 23:56:36 +01:00
|
|
|
vac=> SELECT * FROM ttest;
|
2002-09-21 20:32:54 +02:00
|
|
|
x
|
|
|
|
---
|
|
|
|
1
|
1998-03-01 09:16:16 +01:00
|
|
|
(1 row)
|
|
|
|
|
2005-01-22 23:56:36 +01:00
|
|
|
=> INSERT INTO ttest SELECT x * 2 FROM ttest;
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 1 rows in ttest
|
|
|
|
INFO: trigf (fired after ): there are 2 rows in ttest
|
|
|
|
^^^^^^
|
1998-03-01 09:16:16 +01:00
|
|
|
remember what we said about visibility.
|
|
|
|
INSERT 167794 1
|
2005-01-22 23:56:36 +01:00
|
|
|
=> SELECT * FROM ttest;
|
2002-09-21 20:32:54 +02:00
|
|
|
x
|
|
|
|
---
|
|
|
|
1
|
|
|
|
2
|
1998-03-01 09:16:16 +01:00
|
|
|
(2 rows)
|
|
|
|
|
2005-01-22 23:56:36 +01:00
|
|
|
=> UPDATE ttest SET x = NULL WHERE x = 2;
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 2 rows in ttest
|
1998-03-01 09:16:16 +01:00
|
|
|
UPDATE 0
|
2005-01-22 23:56:36 +01:00
|
|
|
=> UPDATE ttest SET x = 4 WHERE x = 2;
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 2 rows in ttest
|
|
|
|
INFO: trigf (fired after ): there are 2 rows in ttest
|
1998-03-01 09:16:16 +01:00
|
|
|
UPDATE 1
|
2005-01-22 23:56:36 +01:00
|
|
|
vac=> SELECT * FROM ttest;
|
2002-09-21 20:32:54 +02:00
|
|
|
x
|
|
|
|
---
|
|
|
|
1
|
|
|
|
4
|
1998-03-01 09:16:16 +01:00
|
|
|
(2 rows)
|
|
|
|
|
2005-01-22 23:56:36 +01:00
|
|
|
=> DELETE FROM ttest;
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired before): there are 2 rows in ttest
|
|
|
|
INFO: trigf (fired before): there are 1 rows in ttest
|
2005-10-13 04:23:12 +02:00
|
|
|
INFO: trigf (fired after ): there are 0 rows in ttest
|
2003-04-11 20:41:20 +02:00
|
|
|
INFO: trigf (fired after ): there are 0 rows in ttest
|
|
|
|
^^^^^^
|
1998-03-01 09:16:16 +01:00
|
|
|
remember what we said about visibility.
|
|
|
|
DELETE 2
|
2005-01-22 23:56:36 +01:00
|
|
|
=> SELECT * FROM ttest;
|
2002-09-21 20:32:54 +02:00
|
|
|
x
|
|
|
|
---
|
1998-03-01 09:16:16 +01:00
|
|
|
(0 rows)
|
2003-04-11 20:41:20 +02:00
|
|
|
</screen>
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
</para>
|
2003-04-11 20:41:20 +02:00
|
|
|
|
|
|
|
<para>
|
|
|
|
There are more complex examples in
|
|
|
|
<filename>src/test/regress/regress.c</filename> and
|
2017-11-23 15:39:47 +01:00
|
|
|
in <xref linkend="contrib-spi"/>.
|
2003-04-11 20:41:20 +02:00
|
|
|
</para>
|
2000-05-02 22:02:03 +02:00
|
|
|
</sect1>
|
|
|
|
</chapter>
|