head	1.64;
access;
symbols
	REL9_0_0:1.63.2.1
	REL9_1_ALPHA1:1.64
	REL9_0_RC1:1.63.2.1
	REL9_0_BETA4:1.63
	REL9_0_STABLE:1.63.0.2
	REL9_0_BETA3:1.63
	REL9_0_BETA2:1.63
	REL7_4_29:1.31.2.1
	REL8_0_25:1.39.4.2
	REL8_1_21:1.45
	REL8_2_17:1.47
	REL8_3_11:1.51
	REL8_4_4:1.56
	REL9_0_BETA1:1.63
	REL9_0_ALPHA5_BRANCH:1.62.0.4
	REL9_0_ALPHA5:1.62
	REL7_4_28:1.31.2.1
	REL8_0_24:1.39.4.2
	REL8_1_20:1.45
	REL8_2_16:1.47
	REL8_3_10:1.51
	REL8_4_3:1.56
	REL9_0_ALPHA4:1.62
	REL9_0_ALPHA4_BRANCH:1.62.0.2
	REL8_5_ALPHA3:1.61
	REL8_5_ALPHA3_BRANCH:1.61.0.2
	REL7_4_27:1.31.2.1
	REL8_0_23:1.39.4.2
	REL8_1_19:1.45
	REL8_2_15:1.47
	REL8_3_9:1.51
	REL8_4_2:1.56
	REL8_5_ALPHA2:1.59
	REL8_5_ALPHA2_BRANCH:1.59.0.2
	REL7_4_26:1.31.2.1
	REL8_0_22:1.39.4.2
	REL8_1_18:1.45
	REL8_2_14:1.47
	REL8_3_8:1.51
	REL8_4_1:1.56
	REL8_5_ALPHA1:1.58
	REL8_5_ALPHA1_BRANCH:1.58.0.2
	REL8_4_STABLE:1.56.0.2
	REL8_4_0:1.56
	REL8_4_RC2:1.56
	REL8_4_RC1:1.56
	REL8_4_BETA2:1.55
	REL8_4_BETA1:1.55
	REL7_4_25:1.31.2.1
	REL8_0_21:1.39.4.2
	REL8_1_17:1.45
	REL8_2_13:1.47
	REL8_3_7:1.51
	REL7_4_24:1.31.2.1
	REL8_0_20:1.39.4.2
	REL8_1_16:1.45
	REL8_2_12:1.47
	REL8_3_6:1.51
	REL7_4_23:1.31.2.1
	REL8_0_19:1.39.4.2
	REL8_1_15:1.45
	REL8_2_11:1.47
	REL8_3_5:1.51
	REL7_4_22:1.31.2.1
	REL8_0_18:1.39.4.2
	REL8_1_14:1.45
	REL8_2_10:1.47
	REL8_3_4:1.51
	REL7_4_21:1.31.2.1
	REL8_0_17:1.39.4.2
	REL8_1_13:1.45
	REL8_2_9:1.47
	REL8_3_3:1.51
	REL7_4_20:1.31.2.1
	REL8_0_16:1.39.4.2
	REL8_1_12:1.45
	REL8_2_8:1.47
	REL8_3_2:1.51
	REL8_2_7:1.47
	REL8_3_1:1.51
	REL8_3_STABLE:1.51.0.2
	REL8_3_0:1.51
	REL8_3_RC2:1.51
	REL7_3_21:1.25
	REL7_4_19:1.31.2.1
	REL8_0_15:1.39.4.2
	REL8_1_11:1.45
	REL8_2_6:1.47
	REL8_3_RC1:1.51
	REL8_3_BETA4:1.50
	REL8_3_BETA3:1.50
	REL8_3_BETA2:1.50
	REL8_3_BETA1:1.50
	REL7_3_20:1.25
	REL7_4_18:1.31.2.1
	REL8_0_14:1.39.4.2
	REL8_1_10:1.45
	REL8_2_5:1.47
	REL7_3_19:1.25
	REL7_4_17:1.31.2.1
	REL8_0_13:1.39.4.2
	REL8_1_9:1.45
	REL8_2_4:1.47
	REL8_0_12:1.39.4.2
	REL8_1_8:1.45
	REL8_2_3:1.47
	REL7_3_18:1.25
	REL7_4_16:1.31.2.1
	REL8_0_11:1.39.4.2
	REL8_1_7:1.45
	REL8_2_2:1.47
	REL8_0_10:1.39.4.2
	REL8_1_6:1.45
	REL8_2_1:1.47
	REL7_4_15:1.31.2.1
	REL7_3_17:1.25
	REL8_2_STABLE:1.47.0.2
	REL8_2_0:1.47
	REL8_2_RC1:1.47
	REL8_2_BETA3:1.47
	REL8_2_BETA2:1.47
	REL8_1_5:1.45
	REL8_0_9:1.39.4.2
	REL7_4_14:1.31.2.1
	REL7_3_16:1.25
	REL8_2_BETA1:1.47
	REL7_3_15:1.25
	REL7_4_13:1.31.2.1
	REL8_0_8:1.39.4.2
	REL8_1_4:1.45
	REL7_3_14:1.25
	REL7_4_12:1.31.2.1
	REL8_0_7:1.39.4.2
	REL8_1_3:1.45
	REL7_3_13:1.25
	REL7_4_11:1.31.2.1
	REL8_0_6:1.39.4.2
	REL8_1_2:1.45
	REL7_3_12:1.25
	REL7_4_10:1.31.2.1
	REL8_0_5:1.39.4.2
	REL8_1_1:1.45
	REL8_1_STABLE:1.45.0.2
	REL8_1_0:1.45
	REL8_1_0RC1:1.44
	REL8_1_0BETA4:1.44
	REL8_1_0BETA3:1.42
	REL7_3_11:1.25
	REL7_4_9:1.31.2.1
	REL8_0_4:1.39.4.2
	REL8_1_0BETA2:1.42
	REL8_1_0BETA1:1.42
	REL7_2_8:1.19
	REL7_3_10:1.25
	REL7_4_8:1.31.2.1
	REL8_0_3:1.39.4.2
	REL8_0_2:1.39.4.2
	REL7_2_7:1.19
	REL7_3_9:1.25
	REL7_4_7:1.31.2.1
	REL8_0_1:1.39.4.2
	REL8_0_STABLE:1.39.0.4
	REL8_0_0:1.39.0.2
	REL8_0_0RC5:1.39
	REL8_0_0RC4:1.39
	REL8_0_0RC3:1.39
	REL8_0_0RC2:1.38
	REL8_0_0RC1:1.37
	REL8_0_0BETA5:1.37
	REL8_0_0BETA4:1.36
	REL7_4_6:1.31.2.1
	REL7_3_8:1.25
	REL7_2_6:1.19
	REL8_0_0BETA3:1.36
	REL8_0_0BETA2:1.36
	REL7_2_5:1.19
	REL7_4_5:1.31.2.1
	REL7_3_7:1.25
	REL7_4_4:1.31.2.1
	REL8_0_0BETA1:1.35
	REL7_4_3:1.31.2.1
	REL7_4_2:1.31.2.1
	REL7_3_6:1.25
	REL7_4_1:1.31.2.1
	REL7_3_5:1.25
	REL7_4:1.31.2.1
	REL7_4_RC2:1.31
	REL7_4_STABLE:1.31.0.2
	REL7_4_RC1:1.31
	REL7_4_BETA5:1.30
	REL7_4_BETA4:1.30
	REL7_4_BETA3:1.30
	REL7_4_BETA2:1.29
	WIN32_DEV:1.29.0.2
	REL7_4_BETA1:1.28
	REL7_3_4:1.25
	REL7_3_2:1.25
	REL7_2_4:1.19
	REL7_3_STABLE:1.25.0.2
	REL7_2_3:1.19
	REL7_2_STABLE:1.19.0.2
	REL7_2:1.19
	REL7_2_RC2:1.19
	REL7_2_RC1:1.19
	REL7_2_BETA5:1.19
	REL7_2_BETA4:1.19
	REL7_2_BETA3:1.17
	REL7_2_BETA2:1.16
	REL7_2_BETA1:1.16
	REL7_1_2:1.13
	REL7_1_STABLE:1.13.0.2
	REL7_1_BETA:1.12
	REL7_1_BETA3:1.13
	REL7_1_BETA2:1.13
	REL7_1:1.13
	REL7_0_PATCHES:1.8.0.2
	REL7_0:1.5
	REL6_5_PATCHES:1.3.0.4
	REL6_5:1.3
	REL6_4:1.3.0.2
	release-6-3:1.1;
locks; strict;
comment	@# @;


1.64
date	2010.08.17.04.37.21;	author petere;	state Exp;
branches;
next	1.63;

1.63
date	2010.04.03.07.22.56;	author petere;	state Exp;
branches
	1.63.2.1;
next	1.62;

1.62
date	2010.01.17.22.56.21;	author tgl;	state Exp;
branches;
next	1.61;

1.61
date	2009.11.23.21.41.20;	author petere;	state Exp;
branches;
next	1.60;

1.60
date	2009.11.20.20.38.09;	author tgl;	state Exp;
branches;
next	1.59;

1.59
date	2009.10.14.22.14.21;	author tgl;	state Exp;
branches;
next	1.58;

1.58
date	2009.08.04.22.04.37;	author petere;	state Exp;
branches;
next	1.57;

1.57
date	2009.07.28.02.56.29;	author tgl;	state Exp;
branches;
next	1.56;

1.56
date	2009.05.27.01.18.06;	author tgl;	state Exp;
branches;
next	1.55;

1.55
date	2009.04.07.04.02.41;	author momjian;	state Exp;
branches;
next	1.54;

1.54
date	2009.01.06.16.39.52;	author tgl;	state Exp;
branches;
next	1.53;

1.53
date	2008.12.07.23.46.39;	author alvherre;	state Exp;
branches;
next	1.52;

1.52
date	2008.03.28.00.21.55;	author tgl;	state Exp;
branches;
next	1.51;

1.51
date	2007.12.03.23.49.51;	author tgl;	state Exp;
branches;
next	1.50;

1.50
date	2007.02.14.01.58.56;	author tgl;	state Exp;
branches;
next	1.49;

1.49
date	2007.02.01.00.28.18;	author momjian;	state Exp;
branches;
next	1.48;

1.48
date	2007.01.31.20.56.19;	author momjian;	state Exp;
branches;
next	1.47;

1.47
date	2006.09.16.00.30.16;	author momjian;	state Exp;
branches;
next	1.46;

1.46
date	2006.03.10.19.10.49;	author momjian;	state Exp;
branches;
next	1.45;

1.45
date	2005.11.04.23.14.02;	author petere;	state Exp;
branches;
next	1.44;

1.44
date	2005.10.13.21.09.38;	author tgl;	state Exp;
branches;
next	1.43;

1.43
date	2005.10.13.02.23.12;	author momjian;	state Exp;
branches;
next	1.42;

1.42
date	2005.03.29.00.16.49;	author tgl;	state Exp;
branches;
next	1.41;

1.41
date	2005.01.22.22.56.36;	author momjian;	state Exp;
branches;
next	1.40;

1.40
date	2005.01.22.22.06.27;	author momjian;	state Exp;
branches;
next	1.39;

1.39
date	2004.12.30.03.13.56;	author tgl;	state Exp;
branches
	1.39.4.1;
next	1.38;

1.38
date	2004.12.13.18.05.09;	author petere;	state Exp;
branches;
next	1.37;

1.37
date	2004.10.30.20.52.46;	author tgl;	state Exp;
branches;
next	1.36;

1.36
date	2004.08.13.16.17.19;	author tgl;	state Exp;
branches;
next	1.35;

1.35
date	2004.03.03.22.22.24;	author neilc;	state Exp;
branches;
next	1.34;

1.34
date	2004.01.22.19.50.21;	author neilc;	state Exp;
branches;
next	1.33;

1.33
date	2003.11.29.19.51.38;	author pgsql;	state Exp;
branches;
next	1.32;

1.32
date	2003.11.15.19.46.31;	author tgl;	state Exp;
branches;
next	1.31;

1.31
date	2003.10.22.22.28.10;	author tgl;	state Exp;
branches
	1.31.2.1;
next	1.30;

1.30
date	2003.08.31.17.32.20;	author petere;	state Exp;
branches;
next	1.29;

1.29
date	2003.08.10.01.20.34;	author tgl;	state Exp;
branches
	1.29.2.1;
next	1.28;

1.28
date	2003.04.11.18.41.20;	author petere;	state Exp;
branches;
next	1.27;

1.27
date	2003.03.25.16.15.38;	author petere;	state Exp;
branches;
next	1.26;

1.26
date	2002.11.23.03.59.06;	author momjian;	state Exp;
branches;
next	1.25;

1.25
date	2002.09.21.18.32.54;	author petere;	state Exp;
branches;
next	1.24;

1.24
date	2002.08.22.00.01.40;	author tgl;	state Exp;
branches;
next	1.23;

1.23
date	2002.04.19.16.36.08;	author tgl;	state Exp;
branches;
next	1.22;

1.22
date	2002.04.01.22.36.06;	author tgl;	state Exp;
branches;
next	1.21;

1.21
date	2002.03.22.19.20.32;	author petere;	state Exp;
branches;
next	1.20;

1.20
date	2002.03.06.06.44.33;	author momjian;	state Exp;
branches;
next	1.19;

1.19
date	2001.12.04.02.07.11;	author tgl;	state Exp;
branches;
next	1.18;

1.18
date	2001.11.21.06.09.45;	author thomas;	state Exp;
branches;
next	1.17;

1.17
date	2001.11.19.03.58.23;	author tgl;	state Exp;
branches;
next	1.16;

1.16
date	2001.10.12.23.32.34;	author momjian;	state Exp;
branches;
next	1.15;

1.15
date	2001.09.13.15.55.23;	author petere;	state Exp;
branches;
next	1.14;

1.14
date	2001.06.01.02.41.35;	author tgl;	state Exp;
branches;
next	1.13;

1.13
date	2000.12.22.18.57.50;	author petere;	state Exp;
branches;
next	1.12;

1.12
date	2000.11.20.20.36.46;	author tgl;	state Exp;
branches;
next	1.11;

1.11
date	2000.09.29.20.21.34;	author petere;	state Exp;
branches;
next	1.10;

1.10
date	2000.08.24.23.59.38;	author tgl;	state Exp;
branches;
next	1.9;

1.9
date	2000.05.29.01.59.05;	author tgl;	state Exp;
branches;
next	1.8;

1.8
date	2000.05.18.14.24.32;	author momjian;	state Exp;
branches;
next	1.7;

1.7
date	2000.05.17.18.30.02;	author momjian;	state Exp;
branches;
next	1.6;

1.6
date	2000.05.17.17.44.13;	author momjian;	state Exp;
branches;
next	1.5;

1.5
date	2000.05.02.20.01.53;	author thomas;	state Exp;
branches;
next	1.4;

1.4
date	2000.01.11.05.37.11;	author tgl;	state Exp;
branches;
next	1.3;

1.3
date	98.10.30.19.37.14;	author thomas;	state Exp;
branches;
next	1.2;

1.2
date	98.07.29.06.50.03;	author thomas;	state Exp;
branches;
next	1.1;

1.1
date	98.03.01.08.16.13;	author thomas;	state Exp;
branches;
next	;

1.29.2.1
date	2003.09.07.04.36.44;	author momjian;	state Exp;
branches;
next	;

1.31.2.1
date	2003.11.15.19.46.36;	author tgl;	state Exp;
branches;
next	;

1.39.4.1
date	2005.01.22.22.10.10;	author momjian;	state Exp;
branches;
next	1.39.4.2;

1.39.4.2
date	2005.01.22.23.05.50;	author momjian;	state Exp;
branches;
next	;

1.63.2.1
date	2010.08.17.04.37.19;	author petere;	state Exp;
branches;
next	;


desc
@@


1.64
log
@Spell and markup checking
@
text
@<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.63 2010/04/03 07:22:56 petere Exp $ -->

 <chapter id="triggers">
  <title>Triggers</title>

  <indexterm zone="triggers">
   <primary>trigger</primary>
  </indexterm>

  <para>
   This chapter provides general information about writing trigger functions.
   Trigger functions can be written in most of the available procedural
   languages, including
   <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">).
   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.
  </para>

  <sect1 id="trigger-definition">
   <title>Overview of Trigger Behavior</title>

   <para>
    A trigger is a specification that the database should automatically
    execute a particular function whenever a certain type of operation is
    performed.  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,
    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, the trigger's function is called at the
    appropriate time to handle the event.
   </para>

   <para>
    The trigger function must be defined before the trigger itself can be
    created.  The trigger function must be declared as a
    function taking no arguments and returning type <literal>trigger</>.
    (The trigger function receives its input through a specially-passed
    <structname>TriggerData</> structure, not in the form of ordinary function
    arguments.)
   </para>

   <para>
    Once a suitable trigger function has been created, the trigger is
    established with
    <xref linkend="sql-createtrigger">.
    The same trigger function can be used for multiple triggers.
   </para>

   <para>
    <productname>PostgreSQL</productname> offers both <firstterm>per-row</>
    triggers and <firstterm>per-statement</> triggers.  With a per-row
    trigger, the trigger function
    is invoked once for each row that is affected by the statement
    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
    two types of triggers are sometimes called <firstterm>row-level</>
    triggers and <firstterm>statement-level</> triggers,
    respectively. Triggers on <command>TRUNCATE</command> may only be
    defined at statement-level.
   </para>

   <para>
    Triggers are also classified as <firstterm>before</> triggers and
    <firstterm>after</> triggers.
    Statement-level before triggers naturally fire before the
    statement starts to do anything, while statement-level after
    triggers fire at the very end of the statement.  Row-level before
    triggers fire immediately before a particular row is operated on,
    while row-level after triggers fire at the end of the statement
    (but before any statement-level after triggers).
   </para>

   <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:

    <itemizedlist>
     <listitem>
      <para>
       It can return <symbol>NULL</> to skip the operation for the
       current row. This instructs the executor to not perform the
       row-level operation that invoked the trigger (the insertion or
       modification of a particular table row).
      </para>
     </listitem>

     <listitem>
      <para>
       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.
      </para>
     </listitem>
    </itemizedlist>

    A row-level before trigger that does not intend to cause either of
    these behaviors must be careful to return as its result the same
    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
    <command>DELETE</command> triggers).
   </para>

   <para>
    The return value is ignored for row-level triggers fired after an
    operation, and so they can return <symbol>NULL</>.
   </para>

   <para>
    If more than one trigger is defined for the same event on the same
    relation, the triggers will be fired in alphabetical order by
    trigger name.  In the case of before triggers, the
    possibly-modified row returned by each trigger becomes the input
    to the next trigger.  If any before trigger returns
    <symbol>NULL</>, the operation is abandoned for that row and subsequent
    triggers are not fired.
   </para>

   <para>
    A trigger definition can also specify a Boolean <literal>WHEN</>
    condition, which will be tested to see whether the trigger should
    be fired.  In row-level triggers the <literal>WHEN</> condition can
    examine the old and/or new values of columns of the row.  (Statement-level
    triggers can also have <literal>WHEN</> conditions, although the feature
    is not so useful for them.)  In a before trigger, the <literal>WHEN</>
    condition is evaluated just before the function is or would be executed,
    so using <literal>WHEN</> is not materially different from testing the
    same condition at the beginning of the trigger function.  However, in
    an after trigger, the <literal>WHEN</> condition is evaluated 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 after trigger's
    <literal>WHEN</> condition does not return true, it is not necessary
    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.
   </para>

   <para>
    Typically, row before triggers are used for checking or
    modifying the data that will be inserted or updated.  For example,
    a before trigger might be used to insert the current time into a
    <type>timestamp</type> column, or to check that two elements of the row are
    consistent. Row after triggers are most sensibly
    used to propagate the updates to other tables, or make consistency
    checks against other tables.  The reason for this division of labor is
    that an after trigger can be certain it is seeing the final value of the
    row, while a before trigger cannot; there might be other before triggers
    firing after it.  If you have no specific reason to make a trigger before
    or after, the before case is more efficient, since the information about
    the operation doesn't have to be saved until end of statement.
   </para>

   <para>
    If a trigger function executes SQL commands then these
    commands might fire triggers again. This is known as cascading
    triggers.  There is no direct limitation on the number of cascade
    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
    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.
   </para>

   <para>
    When a trigger is being defined, arguments can be specified for
    it.<indexterm><primary>trigger</><secondary>arguments for trigger
    functions</></indexterm> The purpose of including arguments in the
    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.
   </para>

   <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
    arguments that were listed in <command>CREATE TRIGGER</>.
    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.
    Statement-level triggers do not currently have any way to examine the
    individual row(s) modified by the statement.
   </para>

  </sect1>

  <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>

     <listitem>
      <para>
       Statement-level triggers follow simple visibility rules: none of
       the changes made by a statement are visible to statement-level
       triggers that are invoked before the statement, whereas all
       modifications are visible to statement-level after triggers.
      </para>
     </listitem>

     <listitem>
      <para>
       The data change (insertion, update, or deletion) causing the
       trigger to fire is naturally <emphasis>not</emphasis> visible
       to SQL commands executed in a row-level before trigger, because
       it hasn't happened yet.
      </para>
     </listitem>

     <listitem>
      <para>
       However, SQL commands executed in a row-level before
       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
       change events is not in general predictable; a SQL command that
       affects multiple rows can visit the rows in any order.
      </para>
     </listitem>

     <listitem>
      <para>
       When a row-level after trigger is fired, all data changes made
       by the outer command are already complete, and are visible to
       the invoked trigger function.
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    If your trigger function is written in any of the standard procedural
    languages, then the above statements apply only if the function is
    declared <literal>VOLATILE</>.  Functions that are declared
    <literal>STABLE</> or <literal>IMMUTABLE</> will not see changes made by
    the calling command in any case.
   </para>

   <para>
    Further information about data visibility rules can be found in
    <xref linkend="spi-visibility">.  The example in <xref
    linkend="trigger-example"> contains a demonstration of these rules.
   </para>
  </sect1>

  <sect1 id="trigger-interface">
   <title>Writing Trigger Functions in C</title>

   <indexterm zone="trigger-interface">
    <primary>trigger</primary>
    <secondary>in C</secondary>
   </indexterm>

   <para>
    This section describes the low-level details of the interface to a
    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.
   </para>

   <para>
    Trigger functions must use the <quote>version 1</> function manager
    interface.
   </para>

   <para>
    When a function is called by the trigger manager, it is not passed
    any normal arguments, but it is passed a <quote>context</>
    pointer pointing to a <structname>TriggerData</> structure.  C
    functions can check whether they were called from the trigger
    manager or not by executing the macro:
<programlisting>
CALLED_AS_TRIGGER(fcinfo)
</programlisting>
    which expands to:
<programlisting>
((fcinfo)-&gt;context != NULL &amp;&amp; IsA((fcinfo)-&gt;context, TriggerData))
</programlisting>
    If this returns true, then it is safe to cast
    <literal>fcinfo-&gt;context</> to type <literal>TriggerData
    *</literal> and make use of the pointed-to
    <structname>TriggerData</> structure.  The function must
    <emphasis>not</emphasis> alter the <structname>TriggerData</>
    structure or any of the data it points to.
   </para>

   <para>
    <structname>struct TriggerData</structname> is defined in
    <filename>commands/trigger.h</filename>:

<programlisting>
typedef struct TriggerData
{
    NodeTag       type;
    TriggerEvent  tg_event;
    Relation      tg_relation;
    HeapTuple     tg_trigtuple;
    HeapTuple     tg_newtuple;
    Trigger      *tg_trigger;
    Buffer        tg_trigtuplebuf;
    Buffer        tg_newtuplebuf;
} TriggerData;
</programlisting>

    where the members are defined as follows:

    <variablelist>
     <varlistentry>
      <term><structfield>type</></term>
      <listitem>
       <para>
        Always <literal>T_TriggerData</literal>.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_event</></term>
      <listitem>
       <para>
        Describes the event for which the function is called. You can use the
        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.
           </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>

         <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>
        </variablelist>
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_relation</></term>
      <listitem>
       <para>
        A pointer to a structure describing the relation that the trigger fired for.
        Look at <filename>utils/rel.h</> for details about
        this structure.  The most interesting things are
        <literal>tg_relation-&gt;rd_att</> (descriptor of the relation
        tuples) and <literal>tg_relation-&gt;rd_rel-&gt;relname</>
        (relation name; the type is not <type>char*</> but
        <type>NameData</>; use
        <literal>SPI_getrelname(tg_relation)</> to get a <type>char*</> if you
        need a copy of the name).
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_trigtuple</></term>
      <listitem>
       <para>
        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
        skip the operation.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_newtuple</></term>
      <listitem>
       <para>
        A pointer to the new version of the row, if the trigger was
        fired for an <command>UPDATE</command>, and <symbol>NULL</> if
        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
        skip the operation.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_trigger</></term>
      <listitem>
       <para>
        A pointer to a structure of type <structname>Trigger</>,
        defined in <filename>utils/rel.h</>:

<programlisting>
typedef struct Trigger
{
    Oid         tgoid;
    char       *tgname;
    Oid         tgfoid;
    int16       tgtype;
    bool        tgenabled;
    bool        tgisinternal;
    Oid         tgconstrrelid;
    Oid         tgconstrindid;
    Oid         tgconstraint;
    bool        tgdeferrable;
    bool        tginitdeferred;
    int16       tgnargs;
    int16       tgnattr;
    int16      *tgattr;
    char      **tgargs;
    char       *tgqual;
} Trigger;
</programlisting>

       where <structfield>tgname</> is the trigger's name,
       <structfield>tgnargs</> is the number of arguments in
       <structfield>tgargs</>, and <structfield>tgargs</> is an array of
       pointers to the arguments specified in the <command>CREATE
       TRIGGER</command> statement. The other members are for internal use
       only.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_trigtuplebuf</></term>
      <listitem>
       <para>
        The buffer containing <structfield>tg_trigtuple</structfield>, or <symbol>InvalidBuffer</symbol> if there
        is no such tuple or it is not stored in a disk buffer.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><structfield>tg_newtuplebuf</></term>
      <listitem>
       <para>
        The buffer containing <structfield>tg_newtuple</structfield>, or <symbol>InvalidBuffer</symbol> if there
        is no such tuple or it is not stored in a disk buffer.
       </para>
      </listitem>
     </varlistentry>

    </variablelist>
   </para>

   <para>
    A trigger function must return either a
    <structname>HeapTuple</> pointer or a <symbol>NULL</> pointer
    (<emphasis>not</> an SQL null value, that is, do not set <parameter>isNull</parameter> true).
    Be careful to return either
    <structfield>tg_trigtuple</> or <structfield>tg_newtuple</>,
    as appropriate, if you don't want to modify the row being operated on.
   </para>
  </sect1>

  <sect1 id="trigger-example">
   <title>A Complete Trigger Example</title>

   <para>
    Here is a very simple example of a trigger function written in C.
    (Examples of triggers written in procedural languages can be found
    in the documentation of the procedural languages.)
   </para>

   <para>
    The function <function>trigf</> reports the number of rows in the
    table <structname>ttest</> and skips the actual operation if the
    command attempts to insert a null value into the column
    <structfield>x</>. (So the trigger acts as a not-null constraint but
    doesn't abort the transaction.)
   </para>

   <para>
    First, the table definition:
<programlisting>
CREATE TABLE ttest (
    x integer
);
</programlisting>
   </para>

   <para>
    This is the source code of the trigger function:
<programlisting><![CDATA[
#include "postgres.h"
#include "executor/spi.h"       /* this is what you need to work with SPI */
#include "commands/trigger.h"   /* ... and triggers */

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

extern Datum trigf(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(trigf);

Datum
trigf(PG_FUNCTION_ARGS)
{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    TupleDesc   tupdesc;
    HeapTuple   rettuple;
    char       *when;
    bool        checknull = false;
    bool        isnull;
    int         ret, i;

    /* make sure it's called as a trigger at all */
    if (!CALLED_AS_TRIGGER(fcinfo))
        elog(ERROR, "trigf: not called by trigger manager");

    /* tuple to return to executor */
    if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        rettuple = trigdata->tg_newtuple;
    else
        rettuple = trigdata->tg_trigtuple;

    /* check for null values */
    if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)
        && TRIGGER_FIRED_BEFORE(trigdata->tg_event))
        checknull = true;

    if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
        when = "before";
    else
        when = "after ";

    tupdesc = trigdata->tg_relation->rd_att;

    /* connect to SPI manager */
    if ((ret = SPI_connect()) < 0)
        elog(ERROR, "trigf (fired %s): SPI_connect returned %d", when, ret);

    /* get number of rows in table */
    ret = SPI_exec("SELECT count(*) FROM ttest", 0);

    if (ret < 0)
        elog(ERROR, "trigf (fired %s): SPI_exec returned %d", when, ret);

    /* count(*) returns int8, so be careful to convert */
    i = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
                                    SPI_tuptable->tupdesc,
                                    1,
                                    &isnull));

    elog (INFO, "trigf (fired %s): there are %d rows in ttest", when, i);

    SPI_finish();

    if (checknull)
    {
        SPI_getbinval(rettuple, tupdesc, 1, &isnull);
        if (isnull)
            rettuple = NULL;
    }

    return PointerGetDatum(rettuple);
}
]]>
</programlisting>
   </para>

   <para>
    After you have compiled the source code (see <xref
    linkend="dfunc">), declare the function and the triggers:
<programlisting>
CREATE FUNCTION trigf() RETURNS trigger
    AS '<replaceable>filename</>'
    LANGUAGE C;

CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest
    FOR EACH ROW EXECUTE PROCEDURE trigf();

CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest
    FOR EACH ROW EXECUTE PROCEDURE trigf();
</programlisting>
   </para>

   <para>
    Now you can test the operation of the trigger:
<screen>
=&gt; INSERT INTO ttest VALUES (NULL);
INFO:  trigf (fired before): there are 0 rows in ttest
INSERT 0 0

-- Insertion skipped and AFTER trigger is not fired

=&gt; SELECT * FROM ttest;
 x
---
(0 rows)

=&gt; INSERT INTO ttest VALUES (1);
INFO:  trigf (fired before): there are 0 rows in ttest
INFO:  trigf (fired after ): there are 1 rows in ttest
                                       ^^^^^^^^
                             remember what we said about visibility.
INSERT 167793 1
vac=&gt; SELECT * FROM ttest;
 x
---
 1
(1 row)

=&gt; INSERT INTO ttest SELECT x * 2 FROM ttest;
INFO:  trigf (fired before): there are 1 rows in ttest
INFO:  trigf (fired after ): there are 2 rows in ttest
                                       ^^^^^^
                             remember what we said about visibility.
INSERT 167794 1
=&gt; SELECT * FROM ttest;
 x
---
 1
 2
(2 rows)

=&gt; UPDATE ttest SET x = NULL WHERE x = 2;
INFO:  trigf (fired before): there are 2 rows in ttest
UPDATE 0
=&gt; UPDATE ttest SET x = 4 WHERE x = 2;
INFO:  trigf (fired before): there are 2 rows in ttest
INFO:  trigf (fired after ): there are 2 rows in ttest
UPDATE 1
vac=&gt; SELECT * FROM ttest;
 x
---
 1
 4
(2 rows)

=&gt; DELETE FROM ttest;
INFO:  trigf (fired before): there are 2 rows in ttest
INFO:  trigf (fired before): there are 1 rows in ttest
INFO:  trigf (fired after ): there are 0 rows in ttest
INFO:  trigf (fired after ): there are 0 rows in ttest
                                       ^^^^^^
                             remember what we said about visibility.
DELETE 2
=&gt; SELECT * FROM ttest;
 x
---
(0 rows)
</screen>

   </para>

   <para>
    There are more complex examples in
    <filename>src/test/regress/regress.c</filename> and
    in <filename>contrib/spi</filename>.
   </para>
  </sect1>
 </chapter>
@


1.63
log
@Remove unnecessary xref endterm attributes and title ids

The endterm attribute is mainly useful when the toolchain does not support
automatic link target text generation for a particular situation.  In  the
past, this was required by the man page tools for all reference page links,
but that is no longer the case, and it now actually gets in the way of
proper automatic link text generation.  The only remaining use cases are
currently xrefs to refsects.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.62 2010/01/17 22:56:21 tgl Exp $ -->
d144 1
a144 1
    A trigger definition can also specify a boolean <literal>WHEN</>
@


1.63.2.1
log
@Spell and markup checking
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.63 2010/04/03 07:22:56 petere Exp $ -->
d144 1
a144 1
    A trigger definition can also specify a Boolean <literal>WHEN</>
@


1.62
log
@Improve the handling of SET CONSTRAINTS commands by having them search
pg_constraint before searching pg_trigger.  This allows saner handling of
corner cases; in particular we now say "constraint is not deferrable"
rather than "constraint does not exist" when the command is applied to
a constraint that's inherently non-deferrable.  Per a gripe several months
ago from hubert depesz lubaczewski.

To make this work without breaking user-defined constraint triggers,
we have to add entries for them to pg_constraint.  However, in return
we can remove the pgconstrname column from pg_constraint, which represents
a fairly sizable space savings.  I also replaced the tgisconstraint column
with tgisinternal; the old meaning of tgisconstraint can now be had by
testing for nonzero tgconstraint, while there is no other way to get
the old meaning of nonzero tgconstraint, namely that the trigger was
internally generated rather than being user-created.

In passing, fix an old misstatement in the docs and comments, namely that
pg_trigger.tgdeferrable is exactly redundant with pg_constraint.condeferrable.
Actually, we mark RI action triggers as nondeferrable even when they belong to
a nominally deferrable FK constraint.  The SET CONSTRAINTS code now relies on
that instead of hard-coding a list of exception OIDs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.61 2009/11/23 21:41:20 petere Exp $ -->
d60 1
a60 1
    <xref linkend="sql-createtrigger" endterm="sql-createtrigger-title">.
@


1.61
log
@Add PG_MODULE_MAGIC and some missing include files to examples

Author: Euler Taveira de Oliveira <euler@@timbira.com>
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.60 2009/11/20 20:38:09 tgl Exp $ -->
d509 1
a509 1
    bool        tgisconstraint;
@


1.60
log
@Add a WHEN clause to CREATE TRIGGER, allowing a boolean expression to be
checked to determine whether the trigger should be fired.

For BEFORE triggers this is mostly a matter of spec compliance; but for AFTER
triggers it can provide a noticeable performance improvement, since queuing of
a deferred trigger event and re-fetching of the row(s) at end of statement can
be short-circuited if the trigger does not need to be fired.

Takahiro Itagaki, reviewed by KaiGai Kohei.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.59 2009/10/14 22:14:21 tgl Exp $ -->
d599 4
@


1.59
log
@Support SQL-compliant triggers on columns, ie fire only if certain columns
are named in the UPDATE's SET list.

Note: the schema of pg_trigger has not actually changed; we've just started
to use a column that was there all along.  catversion bumped anyway so that
this commit is included in the history of potentially interesting changes
to system catalog contents.

Itagaki Takahiro
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.58 2009/08/04 22:04:37 petere Exp $ -->
d144 19
d519 1
@


1.58
log
@Use DocBook XSL stylesheets for man page building

This switches the man page building process to use the DocBook XSL stylesheet
toolchain.  The previous targets for Docbook2X are removed. configure has been
updated to look for the new tools.  The Documentation appendix contains the
new build instructions.  There are also a few isolated tweaks in the
documentation to improve places that came out strangely in the man pages.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.57 2009/07/28 02:56:29 tgl Exp $ -->
d39 7
a45 4
    or once per <acronym>SQL</acronym> statement.  Triggers can also fire
    for <command>TRUNCATE</command> statements.  If a trigger event occurs,
    the trigger's function is called at the appropriate time to handle the
    event.
@


1.57
log
@Add system catalog columns pg_constraint.conindid and pg_trigger.tgconstrindid.

conindid is the index supporting a constraint.  We can use this not only for
unique/primary-key constraints, but also foreign-key constraints, which
depend on the unique index that constrains the referenced columns.
tgconstrindid is just copied from the constraint's conindid field, or is
zero for triggers not associated with constraints.

This is mainly intended as infrastructure for upcoming patches, but it has
some virtue in itself, since it exposes a relationship that you formerly
had to grovel in pg_depend to determine.  I simplified one information_schema
view accordingly.  (There is a pg_dump query that could also use conindid,
but I left it alone because it wasn't clear it'd get any faster.)
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.56 2009/05/27 01:18:06 tgl Exp $ -->
d544 1
a544 1
   <title>A Complete Example</title>
@


1.56
log
@Improve documentation about function volatility: mention the snapshot
visibility effects in a couple of places where people are likely to look
for it.  Per discussion of recent question from Karl Nack.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.55 2009/04/07 04:02:41 momjian Exp $ -->
d489 1
d501 1
a501 1
       <structfield>tgnargs</> is number of arguments in
@


1.55
log
@Add doc link to section about how to compile triggers.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.54 2009/01/06 16:39:52 tgl Exp $ -->
d253 8
@


1.54
log
@Change a couple of ill-advised uses of INFO elog level to WARNINGs; in
particular this allows EmitWarningsOnPlaceholders messages to show up in the
postmaster log by default.  Update elog.h comment to make it clearer what INFO
is for, and fix one example in the SGML docs that was misusing it.  Per my
gripe of yesterday.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.53 2008/12/07 23:46:39 alvherre Exp $ -->
d638 2
a639 2
    After you have compiled the source code, declare the function and
    the triggers:
@


1.53
log
@Desultorily enclose programlisting tags in CDATA, to get rid of some obnoxious
SGML-escaping.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.52 2008/03/28 00:21:55 tgl Exp $ -->
d606 1
a606 1
        elog(INFO, "trigf (fired %s): SPI_connect returned %d", when, ret);
d612 1
a612 1
        elog(NOTICE, "trigf (fired %s): SPI_exec returned %d", when, ret);
@


1.52
log
@Support statement-level ON TRUNCATE triggers.  Simon Riggs
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.51 2007/12/03 23:49:51 tgl Exp $ -->
d562 1
a562 1
<programlisting>
d574 1
a574 1
    TriggerData *trigdata = (TriggerData *) fcinfo-&gt;context;
d587 2
a588 2
    if (TRIGGER_FIRED_BY_UPDATE(trigdata-&gt;tg_event))
        rettuple = trigdata-&gt;tg_newtuple;
d590 1
a590 1
        rettuple = trigdata-&gt;tg_trigtuple;
d593 2
a594 2
    if (!TRIGGER_FIRED_BY_DELETE(trigdata-&gt;tg_event)
        &amp;&amp; TRIGGER_FIRED_BEFORE(trigdata-&gt;tg_event))
d597 1
a597 1
    if (TRIGGER_FIRED_BEFORE(trigdata-&gt;tg_event))
d602 1
a602 1
    tupdesc = trigdata-&gt;tg_relation-&gt;rd_att;
d605 1
a605 1
    if ((ret = SPI_connect()) &lt; 0)
d611 1
a611 1
    if (ret &lt; 0)
d615 2
a616 2
    i = DatumGetInt64(SPI_getbinval(SPI_tuptable-&gt;vals[0],
                                    SPI_tuptable-&gt;tupdesc,
d618 1
a618 1
                                    &amp;isnull));
d626 1
a626 1
        SPI_getbinval(rettuple, tupdesc, 1, &amp;isnull);
d633 1
@


1.51
log
@Entity-ify a passel of & < > characters.  Per gripe from Devrim.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.50 2007/02/14 01:58:56 tgl Exp $ -->
d39 4
a42 3
    or once per <acronym>SQL</acronym> statement.
    If a trigger event occurs, the trigger's function is called
    at the appropriate time to handle the event.
d47 1
a47 1
    created.  The trigger function must be declared as a 
d73 2
a74 1
    respectively.
d403 9
d644 1
a644 1
CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest 
d647 1
a647 1
CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest 
@


1.50
log
@Fix up foreign-key mechanism so that there is a sound semantic basis for the
equality checks it applies, instead of a random dependence on whatever
operators might be named "=".  The equality operators will now be selected
from the opfamily of the unique index that the FK constraint depends on to
enforce uniqueness of the referenced columns; therefore they are certain to be
consistent with that index's notion of equality.  Among other things this
should fix the problem noted awhile back that pg_dump may fail for foreign-key
constraints on user-defined types when the required operators aren't in the
search path.  This also means that the former warning condition about "foreign
key constraint will require costly sequential scans" is gone: if the
comparison condition isn't indexable then we'll reject the constraint
entirely. All per past discussions.

Along the way, make the RI triggers look into pg_constraint for their
information, instead of using pg_trigger.tgargs; and get rid of the always
error-prone fixed-size string buffers in ri_triggers.c in favor of building up
the RI queries in StringInfo buffers.

initdb forced due to columns added to pg_constraint and pg_trigger.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.49 2007/02/01 00:28:18 momjian Exp $ -->
d291 1
a291 1
((fcinfo)-&gt;context != NULL && IsA((fcinfo)-&gt;context, TriggerData))
d583 1
a583 1
        && TRIGGER_FIRED_BEFORE(trigdata-&gt;tg_event))
@


1.49
log
@Consistenly use colons before '<programlisting>' blocks, where
appropriate.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.48 2007/01/31 20:56:19 momjian Exp $ -->
d470 1
@


1.48
log
@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.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.47 2006/09/16 00:30:16 momjian Exp $ -->
d285 1
a285 1
    manager or not by executing the macro
d289 1
a289 1
    which expands to
@


1.47
log
@Remove emacs info from footer of SGML files.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.46 2006/03/10 19:10:49 momjian Exp $ -->
d125 1
a125 1
    operation, and so they may as well return <symbol>NULL</>.
d155 1
a155 1
    commands may fire triggers again. This is known as cascading
d236 1
a236 1
       affects multiple rows may visit the rows in any order.
d335 1
a335 1
        Describes the event for which the function is called. You may use the
d527 1
a527 1
    (Examples of triggers written in procedural languages may be found
@


1.46
log
@Make $PostgreSQL CVS tags consistent for SGML files.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/advanced.sgml,v 1.49 2005/04/09 03:52:43 momjian Exp $ -->
a715 17

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->
@


1.45
log
@Spellchecking run, final cleanups
@
text
@d1 1
a1 3
<!--
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.44 2005/10/13 21:09:38 tgl Exp $
-->
@


1.44
log
@Adjust the discussion of triggers to more clearly guide people in the
direction of writing triggers in a procedural language, rather than C.
Per discussion.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.43 2005/10/13 02:23:12 momjian Exp $
d144 1
a144 1
    timestamp column, or to check that two elements of the row are
@


1.43
log
@Update trigger demo to reflect new trigger ordering.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.42 2005/03/29 00:16:49 tgl Exp $
d13 17
a29 4
   This chapter describes how to write trigger functions.  Trigger
   functions can be written in C or in some of the available procedural
   languages.  It is not currently possible to write a SQL-language
   trigger function.
d36 3
a38 1
    A trigger can be defined to execute before or after an
d63 4
a66 3
    There are two types of triggers: per-row triggers and
    per-statement triggers. In a per-row trigger, the trigger function
    is invoked once for every row that is affected by the statement
d72 2
a73 2
    two types of triggers are sometimes called <quote>row-level
    triggers</quote> and <quote>statement-level triggers</quote>,
d78 5
a82 3
    Statement-level <quote>before</> triggers naturally fire before the
    statement starts to do anything, while statement-level <quote>after</>
    triggers fire at the very end of the statement.  Row-level <quote>before</>
d84 2
a85 2
    while row-level <quote>after</> triggers fire at the end of the statement
    (but before any statement-level <quote>after</> triggers).
d136 1
a136 1
    <symbol>NULL</>, the operation is abandoned and subsequent
d269 6
a274 5
    trigger function.  This information is only needed when writing a
    trigger function in C.  If you are using a higher-level
    language then these details are handled for you.  The documentation
    of each procedural language explains how to write a trigger in that
    language.
@


1.42
log
@Convert oidvector and int2vector into variable-length arrays.  This
change saves a great deal of space in pg_proc and its primary index,
and it eliminates the former requirement that INDEX_MAX_KEYS and
FUNC_MAX_ARGS have the same value.  INDEX_MAX_KEYS is still embedded
in the on-disk representation (because it affects index tuple header
size), but FUNC_MAX_ARGS is not.  I believe it would now be possible
to increase FUNC_MAX_ARGS at little cost, but haven't experimented yet.
There are still a lot of vestigial references to FUNC_MAX_ARGS, which
I will clean up in a separate pass.  However, getting rid of it
altogether would require changing the FunctionCallInfoData struct,
and I'm not sure I want to buy into that.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.41 2005/01/22 22:56:36 momjian Exp $
a677 1
INFO:  trigf (fired after ): there are 1 rows in ttest
d680 1
@


1.41
log
@More < and > cleanups converted to ampersands.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.40 2005/01/22 22:06:27 momjian Exp $
d456 2
a457 1
    int16       tgattr[FUNC_MAX_ARGS];
@


1.40
log
@Change -> and <- to use proper ampersand markups.

HEAD and 8.0.X.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.39 2004/12/30 03:13:56 tgl Exp $
d575 1
a575 1
    if ((ret = SPI_connect()) < 0)
d581 1
a581 1
    if (ret < 0)
d625 1
a625 1
=> INSERT INTO ttest VALUES (NULL);
d631 1
a631 1
=> SELECT * FROM ttest;
d636 1
a636 1
=> INSERT INTO ttest VALUES (1);
d642 1
a642 1
vac=> SELECT * FROM ttest;
d648 1
a648 1
=> INSERT INTO ttest SELECT x * 2 FROM ttest;
d654 1
a654 1
=> SELECT * FROM ttest;
d661 1
a661 1
=> UPDATE ttest SET x = NULL WHERE x = 2;
d664 1
a664 1
=> UPDATE ttest SET x = 4 WHERE x = 2;
d668 1
a668 1
vac=> SELECT * FROM ttest;
d675 1
a675 1
=> DELETE FROM ttest;
d683 1
a683 1
=> SELECT * FROM ttest;
@


1.39
log
@More updates and copy-editing.  Rearrange order of sections a little bit
to put more widely useful info before less widely useful info.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.38 2004/12/13 18:05:09 petere Exp $
d274 1
a274 1
((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))
d277 1
a277 1
    <literal>fcinfo->context</> to type <literal>TriggerData
d396 2
a397 2
        <literal>tg_relation->rd_att</> (descriptor of the relation
        tuples) and <literal>tg_relation->rd_rel->relname</>
d544 1
a544 1
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
d557 2
a558 2
    if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        rettuple = trigdata->tg_newtuple;
d560 1
a560 1
        rettuple = trigdata->tg_trigtuple;
d563 2
a564 2
    if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)
        && TRIGGER_FIRED_BEFORE(trigdata->tg_event))
d567 1
a567 1
    if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
d572 1
a572 1
    tupdesc = trigdata->tg_relation->rd_att;
d585 2
a586 2
    i = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
                                    SPI_tuptable->tupdesc,
@


1.39.4.1
log
@Change -> and <- to use proper ampersand markups.

HEAD and 8.0.X.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.39 2004/12/30 03:13:56 tgl Exp $
d274 1
a274 1
((fcinfo)-&gt;context != NULL && IsA((fcinfo)-&gt;context, TriggerData))
d277 1
a277 1
    <literal>fcinfo-&gt;context</> to type <literal>TriggerData
d396 2
a397 2
        <literal>tg_relation-&gt;rd_att</> (descriptor of the relation
        tuples) and <literal>tg_relation-&gt;rd_rel-&gt;relname</>
d544 1
a544 1
    TriggerData *trigdata = (TriggerData *) fcinfo-&gt;context;
d557 2
a558 2
    if (TRIGGER_FIRED_BY_UPDATE(trigdata-&gt;tg_event))
        rettuple = trigdata-&gt;tg_newtuple;
d560 1
a560 1
        rettuple = trigdata-&gt;tg_trigtuple;
d563 2
a564 2
    if (!TRIGGER_FIRED_BY_DELETE(trigdata-&gt;tg_event)
        && TRIGGER_FIRED_BEFORE(trigdata-&gt;tg_event))
d567 1
a567 1
    if (TRIGGER_FIRED_BEFORE(trigdata-&gt;tg_event))
d572 1
a572 1
    tupdesc = trigdata-&gt;tg_relation-&gt;rd_att;
d585 2
a586 2
    i = DatumGetInt64(SPI_getbinval(SPI_tuptable-&gt;vals[0],
                                    SPI_tuptable-&gt;tupdesc,
@


1.39.4.2
log
@More < and > cleanups converted to ampersands.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.39.4.1 2005/01/22 22:10:10 momjian Exp $
d575 1
a575 1
    if ((ret = SPI_connect()) &lt; 0)
d581 1
a581 1
    if (ret &lt; 0)
d625 1
a625 1
=&gt; INSERT INTO ttest VALUES (NULL);
d631 1
a631 1
=&gt; SELECT * FROM ttest;
d636 1
a636 1
=&gt; INSERT INTO ttest VALUES (1);
d642 1
a642 1
vac=&gt; SELECT * FROM ttest;
d648 1
a648 1
=&gt; INSERT INTO ttest SELECT x * 2 FROM ttest;
d654 1
a654 1
=&gt; SELECT * FROM ttest;
d661 1
a661 1
=&gt; UPDATE ttest SET x = NULL WHERE x = 2;
d664 1
a664 1
=&gt; UPDATE ttest SET x = 4 WHERE x = 2;
d668 1
a668 1
vac=&gt; SELECT * FROM ttest;
d675 1
a675 1
=&gt; DELETE FROM ttest;
d683 1
a683 1
=&gt; SELECT * FROM ttest;
@


1.38
log
@Spell checker run
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.37 2004/10/30 20:52:46 tgl Exp $
d62 9
d123 15
d167 14
d318 2
a319 2
	Describes the event for which the function is called. You may use the
	following macros to examine <literal>tg_event</literal>:
d321 64
a384 64
	<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.
	   </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>
	</variablelist>
d393 9
a401 9
	A pointer to a structure describing the relation that the trigger fired for.
	Look at <filename>utils/rel.h</> for details about
	this structure.  The most interesting things are
	<literal>tg_relation->rd_att</> (descriptor of the relation
	tuples) and <literal>tg_relation->rd_rel->relname</>
	(relation name; the type is not <type>char*</> but
	<type>NameData</>; use
	<literal>SPI_getrelname(tg_relation)</> to get a <type>char*</> if you
	need a copy of the name).
d410 7
a416 7
	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
	to from the function if you don't want to replace the row with
	a different one (in the case of <command>INSERT</command>) or
	skip the operation.
d425 7
a431 7
	A pointer to the new version of the row, if the trigger was
	fired for an <command>UPDATE</command>, and <symbol>NULL</> if
	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
	skip the operation.
d440 2
a441 2
	A pointer to a structure of type <structname>Trigger</>,
	defined in <filename>utils/rel.h</>:
@


1.37
log
@I found a corner case in which it is possible for RI_FKey_check's call
of HeapTupleSatisfiesItself() to trigger a hint-bit update on the tuple:
if the row was updated or deleted by a subtransaction of my own transaction
that was later rolled back.  This cannot occur in pre-8.0 of course, so
the hint-bit patch applied a couple weeks ago is OK for existing releases.
But for 8.0 it seems we had better fix things so that RI_FKey_check can
pass the correct buffer number to HeapTupleSatisfiesItself.  Accordingly,
add fields to the TriggerData struct to carry the buffer ID(s) for the
old and new tuple(s).  There are other possible solutions but this one
seems cleanest; it will allow other AFTER-trigger functions to safely
do tqual.c calls if they want to.  Put new fields at end of struct so
that there is no API breakage.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.36 2004/08/13 16:17:19 tgl Exp $
d437 1
a437 1
        The buffer containing tg_trigtuple, or InvalidBuffer if there
d447 1
a447 1
        The buffer containing tg_newtuple, or InvalidBuffer if there
d459 1
a459 1
    (<emphasis>not</> a SQL NULL, that is, do not set isNull true).
@


1.36
log
@Clarify trigger function return convention, per Thomas Hallgren.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/trigger.sgml,v 1.35 2004/03/03 22:22:24 neilc Exp $
d259 2
d432 21
@


1.35
log
@Add a few more cross-references where appropriate, add more text about
the FROM clause and an example to the UPDATE reference page, and make
a few other SGML tweaks.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/trigger.sgml,v 1.34 2004/01/22 19:50:21 neilc Exp $
d434 4
a437 2
    A trigger function must return either <symbol>NULL</> or a
    <structname>HeapTuple</> pointer.  Be careful to return either
@


1.34
log
@Minor improvements to the trigger documentation, and a few SGML fixes.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/trigger.sgml,v 1.33 2003/11/29 19:51:38 pgsql Exp $
d452 1
a452 1
    table <literal>ttest</> and skips the actual operation if the
d454 1
a454 1
    <literal>x</>. (So the trigger acts as a not-null constraint but
@


1.33
log
@
$Header: -> $PostgreSQL Changes ...
@
text
@d2 1
a2 1
$PostgreSQL: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.32 2003/11/15 19:46:31 tgl Exp $
d48 20
a67 3
    Trigger functions return a table row (a value of type
    <structname>HeapTuple</>) to the calling executor.
    A trigger fired before an operation has the following choices:
d72 4
a75 3
       It can return a <symbol>NULL</> pointer to skip the operation
       for the current row (and so the row will not be
       inserted/updated/deleted).
d81 5
a85 5
       For <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.
d90 5
a94 4
    A before trigger that does not intend to cause either of these
    behaviors must be careful to return as its result the same row that was
    passed in (that is, the NEW row for <command>INSERT</command> and
    <command>UPDATE</command> triggers, the OLD row for
d99 2
a100 3
    The return
    value is ignored for triggers fired after an operation, and so
    they may as well return <symbol>NULL</>.
d105 6
a110 5
    relation, the triggers will be fired in alphabetical order by trigger
    name.  In the case of before triggers, the possibly-modified row
    returned by each trigger becomes the input to the next trigger.
    If any before trigger returns a <symbol>NULL</> pointer, the
    operation is abandoned and subsequent triggers are not fired.
d156 10
d168 4
a171 4
       The data change (insertion, update, or deletion) causing the trigger
       to fire is naturally
       <emphasis>not</emphasis> visible to SQL commands executed in a
       before trigger, because it hasn't happened yet.
d177 6
a182 6
       However, SQL commands executed in a before 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 change events
       is not in general predictable; a SQL command that affects
       multiple rows may visit the rows in any order.
d188 3
a190 2
       When an after trigger is fired, all data changes made by the outer
       command are already complete, and are visible to executed SQL commands.
@


1.32
log
@Minor wording improvement suggested by a comment in the interactive docs.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.31 2003/10/22 22:28:10 tgl Exp $
@


1.31
log
@Move docs about index cost estimation functions and writing a procedural
language handler to the 'Internals' area, per my proposal of yesterday.
Clean up the trigger documentation a bit.  Push SPI chapter to the end
of its part, and reorder the Internals chapters into what seems a more
sensible order (at the moment anyway).
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.30 2003/08/31 17:32:20 petere Exp $
d74 3
a76 1
    passed in.
@


1.31.2.1
log
@Minor wording improvement suggested by a comment in the interactive docs.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.31 2003/10/22 22:28:10 tgl Exp $
d74 1
a74 3
    passed in (that is, the NEW row for <command>INSERT</command> and
    <command>UPDATE</command> triggers, the OLD row for
    <command>DELETE</command> triggers).
@


1.30
log
@Add/edit index entries.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.29 2003/08/10 01:20:34 tgl Exp $
d13 4
a16 11
   This chapter describes how to write trigger functions.  In
   particular, it describes the C-language interface for trigger
   functions.  The trigger interfaces in most procedural languages
   work analogously.  (Trigger functions cannot be written in SQL.)
  </para>

  <para>
   A trigger function can execute before or after a
   <command>INSERT</command>, <command>UPDATE</command>, or
   <command>DELETE</command>, either once per modified row, or once
   per <acronym>SQL</acronym> statement.
d20 1
a20 1
   <title>Trigger Definition</title>
d23 6
a28 4
    If a trigger event occurs, the trigger manager is called by the
    executor.  It sets up an information structure of type
    <structname>TriggerData</> (described below) and calls the trigger
    function to handle the event.
d35 3
a37 4
    (The trigger function receives its input through a <structname>TriggerData</>
    structure, not in the form of ordinary function arguments.)
    If the function is written in C, it must use the <quote>version 1</>
    function manager interface.
d41 2
a42 1
    The syntax for creating triggers is described in
d44 1
d48 3
a50 4
    Trigger functions return a value of type <structname>HeapTuple</>,
    which represents a table row, to the calling executor.  The return
    value is ignored for triggers fired after an operation, but a
    triggers fired before an operation has the following choices:
d73 8
a80 2
    behaviors must be careful to return the same row that was passed
    in as the new row (see below).
d85 1
a85 1
    relation, the triggers will be fired in alphabetical order by
d93 1
a93 1
    If a trigger function executes SQL commands (using SPI) then these
d124 46
a169 2
  <sect1 id="trigger-manager">
   <title>Interaction with the Trigger Manager</title>
d171 4
a174 1
   <indexterm zone="trigger-manager">
d183 8
a190 1
    language then these details are handled for you.
a399 40
  </sect1>

  <sect1 id="trigger-datachanges">
   <title>Visibility of Data Changes</title>

   <para>
    If you are using the SPI interface to execute SQL commands in your
    trigger functions written in C (or you are using a different
    language and execute SQL commands in some way, which internally
    goes through SPI as well), be sure to read <xref
    linkend="spi-visibility"> so that you know which data is visible
    at which point during the execution of a trigger.  For triggers,
    the most important consequences of the data visibility rules are:

    <itemizedlist>
     <listitem>
      <para>
       The row being inserted (<structfield>tg_trigtuple</>) is
       <emphasis>not</emphasis> visible to SQL commands executed in a
       before trigger.
      </para>
     </listitem>

     <listitem>
      <para>
       The row being inserted (<structfield>tg_trigtuple</>)
       <emphasis>is</emphasis> visible to SQL commands executed in an
       after trigger (because it was just inserted).
      </para>
     </listitem>

     <listitem>
      <para>
       A just-inserted row is visible to all SQL commands executed
       within any trigger that is fired later in the execution of the
       outer command (e.g., for the next row).
      </para>
     </listitem>
    </itemizedlist>
   </para>
d402 4
a405 1
    The next section contains a demonstration of these rules applied.
d414 5
@


1.29
log
@Make various links point to specific places instead of entire parts
(doubtless these are hangovers from the old separate-books days).
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.28 2003/04/11 18:41:20 petere Exp $
d8 4
d105 14
a118 12
    it.  The purpose of including arguments in the 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.
d125 5
@


1.29.2.1
log
@Update this branch to match CVS head, includes WIN32 improvements.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.30 2003/08/31 17:32:20 petere Exp $
a7 4
  <indexterm zone="triggers">
   <primary>trigger</primary>
  </indexterm>

d101 12
a112 14
    it.<indexterm><primary>trigger</><secondary>arguments for trigger
    functions</></indexterm> The purpose of including arguments in the
    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.
a118 5

   <indexterm zone="trigger-manager">
    <primary>trigger</primary>
    <secondary>in C</secondary>
   </indexterm>
@


1.28
log
@Revision
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.27 2003/03/25 16:15:38 petere Exp $
d43 2
a44 1
    The syntax for creating triggers is described in <xref linkend="reference">.
@


1.27
log
@Merge documentation into one book.  (Build with "make html".)  Replace
vague cross-references with real links.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.26 2002/11/23 03:59:06 momjian Exp $
d9 11
a19 9
   <productname>PostgreSQL</productname> has various server-side
   function interfaces. Server-side functions can be written in
   <acronym>SQL</acronym>, C, or any defined procedural
   language. Trigger functions can be written in C and most procedural
   languages, but not in <acronym>SQL</acronym>. Both per-row and
   per-statement triggers are supported. A trigger procedure can
   execute BEFORE or AFTER a <command>INSERT</command>,
   <command>DELETE</command> or <command>UPDATE</command>, either once
   per modified row, or once per <acronym>SQL</acronym> statement.
d26 4
a29 4
    If a trigger event occurs, the trigger manager (called by the
    Executor) sets up a <structname>TriggerData</> information
    structure (described below) and calls the trigger function to
    handle the event.
d47 4
a50 3
    Trigger functions return a <structname>HeapTuple</> to the calling
    executor.  The return value is ignored for triggers fired AFTER an
    operation, but it allows BEFORE triggers to:
d55 2
a56 2
       Return a <symbol>NULL</> pointer to skip the operation for the
       current tuple (and so the tuple will not be
d64 2
a65 2
       triggers only, the returned tuple becomes the tuple which will
       be inserted or will replace the tuple being updated.  This
d72 3
a74 8
    A BEFORE trigger that does not intend to cause either of these behaviors
    must be careful to return the same NEW tuple it is passed.
   </para>

   <para>
    Note that there is no initialization performed by the
    <command>CREATE TRIGGER</command> handler.  This may be changed in
    the future.
d80 1
a80 1
    name.  In the case of BEFORE triggers, the possibly-modified tuple
d82 2
a83 2
    If any BEFORE trigger returns <symbol>NULL</>, the operation is
    abandoned and subsequent triggers are not fired.
d87 2
a88 2
    If a trigger function executes SQL-queries (using SPI) then these
    queries may fire triggers again. This is known as cascading
d90 3
a92 3
    levels.  It is possible for cascades to cause recursive invocation
    of the same trigger --- for example, an <command>INSERT</command>
    trigger might execute a query that inserts an additional tuple
d99 13
a111 14
	When a trigger is defined, a number of arguments can be
	specified. The purpose of including arguments in the 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 field 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
	fields, 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.
d122 1
a122 1
    trigger function in C.  If you are using a higher-level function
a125 9
    <note>
     <para>
      The interface described here applies for
      <productname>PostgreSQL</productname> 7.1 and later.
      Earlier versions passed the <structname>TriggerData</> pointer in a global
      variable <varname>CurrentTriggerData</>.
     </para>
    </note>

d128 1
a128 1
    any normal parameters, but it is passed a <quote>context</>
d132 4
a135 1
    <literal>CALLED_AS_TRIGGER(fcinfo)</literal>, which expands to
d170 1
a170 1
        Always <literal>T_TriggerData</literal> if this is a trigger event.
d179 1
a179 1
	describes the event for which the function is called. You may use the
d184 1
a184 1
	  <term>TRIGGER_FIRED_BEFORE(tg_event)</term>
d187 1
a187 1
	    returns TRUE if trigger fired BEFORE.
d193 1
a193 1
	  <term>TRIGGER_FIRED_AFTER(tg_event)</term>
d196 1
a196 1
	    Returns TRUE if trigger fired AFTER.
d202 1
a202 1
	  <term>TRIGGER_FIRED_FOR_ROW(event)</term>
d205 1
a205 1
	    Returns TRUE if trigger fired for a ROW-level event.
d211 1
a211 1
	  <term>TRIGGER_FIRED_FOR_STATEMENT(event)</term>
d214 1
a214 1
	    Returns TRUE if trigger fired for STATEMENT-level event.
d220 1
a220 1
	  <term>TRIGGER_FIRED_BY_INSERT(event)</term>
d223 1
a223 1
	    Returns TRUE if trigger fired by <command>INSERT</command>.
d229 1
a229 1
	  <term>TRIGGER_FIRED_BY_DELETE(event)</term>
d232 1
a232 1
	    Returns TRUE if trigger fired by <command>DELETE</command>.
d238 1
a238 1
	  <term>TRIGGER_FIRED_BY_UPDATE(event)</term>
d241 1
a241 1
	    Returns TRUE if trigger fired by <command>UPDATE</command>.
d254 2
a255 2
	is a pointer to structure describing the triggered
	relation. Look at <filename>utils/rel.h</> for details about
d259 3
a261 3
	(relation's name. This is not <type>char*</>, but
	<type>NameData</>.  Use
	<literal>SPI_getrelname(tg_relation)</> to get <type>char*</> if you
d271 7
a277 9
	is a pointer to the tuple for which the trigger is fired. This is
	the tuple being inserted (if <command>INSERT</command>), deleted
	(if <command>DELETE</command>) or updated (if
	<command>UPDATE</command>).  If this trigger was fired for an
	<command>INSERT</command> or <command>DELETE</command> then this
	is what you should return to the Executor if you don't want to
	replace the tuple with a different one (in the case of
	<command>INSERT</command>) or skip the operation (in the case of
	<command>DELETE</command>).
d286 7
a292 6
	is a pointer to the new version of tuple if
	<command>UPDATE</command> and <symbol>NULL</> if this is for an
	<command>INSERT</command> or a <command>DELETE</command>. This is
	what you are to return to Executor if <command>UPDATE</command>
	and you don't want to replace this tuple with another one or skip
	the operation.
d301 2
a302 1
	is pointer to structure <structname>Trigger</> defined in <filename>utils/rel.h</>:
d324 1
a324 1
       <structfield>tgargs</>, <structfield>tgargs</> is an array of
d326 1
a326 1
       TRIGGER</command> statement. Other members are for internal use
d339 7
a345 3
    <productname>PostgreSQL</productname> data changes visibility rule: during a query execution, data
    changes made by the query itself (via SQL-function, SPI-function, triggers)
    are invisible to the query scan.  For example, in query
d347 8
a354 3
<programlisting>
INSERT INTO a SELECT * FROM a;
</programlisting>
d356 7
a362 4
    tuples inserted are invisible for SELECT scan.  In effect, this
    duplicates the database table within itself (subject to unique index
    rules, of course) without recursing.
   </para>
d364 8
a371 10
   <para>
    But keep in mind this notice about visibility in the SPI documentation:

    <blockquote>
     <para>
Changes made by query Q are visible by queries that are started after
query Q, no matter whether they are started inside Q (during the
execution of Q) or after Q is done.
     </para>
    </blockquote>
d375 1
a375 4
    This is true for triggers as well so, though a tuple being inserted
    (<structfield>tg_trigtuple</>) is not visible to queries in a BEFORE trigger, this tuple
    (just inserted) is visible to queries in an AFTER trigger, and to queries
    in BEFORE/AFTER triggers fired after this!
d379 2
a380 2
  <sect1 id="trigger-examples">
   <title>Examples</title>
d383 6
a388 3
    There are more complex examples in
    <filename>src/test/regress/regress.c</filename> and
    in <filename>contrib/spi</filename>.
d392 7
a398 6
    Here is a very simple example of trigger usage.  Function
    <function>trigf</> reports the number of tuples in the triggered
    relation <literal>ttest</> and skips the operation if the query
    attempts to insert a null value into x (i.e - it acts as a
    <literal>NOT NULL</literal> constraint but doesn't abort the
    transaction).
d400 2
d403 1
d405 1
a405 1
#include "commands/trigger.h"   /* -"- and triggers */
d422 1
a422 1
    /* Make sure trigdata is pointing at what I expect */
d424 1
a424 1
        elog(ERROR, "trigf: not fired by trigger manager");
d426 1
a426 1
    /* tuple to return to Executor */
d444 1
a444 1
    /* Connect to SPI manager */
d448 1
a448 1
    /* Get number of tuples in relation */
d454 5
a458 5
    /* count(*) returns int8 as of PG 7.2, so be careful to convert */
    i = (int) DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
                                          SPI_tuptable->tupdesc,
                                          1,
                                          &amp;isnull));
d460 1
a460 1
    elog (NOTICE, "trigf (fired %s): there are %d tuples in ttest", when, i);
d466 1
a466 1
        (void) SPI_getbinval(rettuple, tupdesc, 1, &amp;isnull);
d477 6
a482 1
    Now, compile and create the trigger function:
d484 2
a485 3
<programlisting>
CREATE FUNCTION trigf () RETURNS TRIGGER AS 
'...path_to_so' LANGUAGE C;
d487 2
a488 1
CREATE TABLE ttest (x int4);
d490 1
d492 5
a496 9
<programlisting>
vac=> CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest 
FOR EACH ROW EXECUTE PROCEDURE trigf();
CREATE
vac=> CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest 
FOR EACH ROW EXECUTE PROCEDURE trigf();
CREATE
vac=> INSERT INTO ttest VALUES (NULL);
WARNING:  trigf (fired before): there are 0 tuples in ttest
d501 1
a501 1
vac=> SELECT * FROM ttest;
d506 3
a508 3
vac=> INSERT INTO ttest VALUES (1);
INFO:  trigf (fired before): there are 0 tuples in ttest
INFO:  trigf (fired after ): there are 1 tuples in ttest
d518 4
a521 4
vac=> INSERT INTO ttest SELECT x * 2 FROM ttest;
INFO:  trigf (fired before): there are 1 tuples in ttest
INFO:  trigf (fired after ): there are 2 tuples in ttest
                                       ^^^^^^^^
d524 1
a524 1
vac=> SELECT * FROM ttest;
d531 2
a532 2
vac=> UPDATE ttest SET x = NULL WHERE x = 2;
INFO:  trigf (fired before): there are 2 tuples in ttest
d534 3
a536 3
vac=> UPDATE ttest SET x = 4 WHERE x = 2;
INFO:  trigf (fired before): there are 2 tuples in ttest
INFO:  trigf (fired after ): there are 2 tuples in ttest
d545 6
a550 6
vac=> DELETE FROM ttest;
INFO:  trigf (fired before): there are 2 tuples in ttest
INFO:  trigf (fired after ): there are 1 tuples in ttest
INFO:  trigf (fired before): there are 1 tuples in ttest
INFO:  trigf (fired after ): there are 0 tuples in ttest
                                       ^^^^^^^^
d553 1
a553 1
vac=> SELECT * FROM ttest;
d557 3
a559 1
</programlisting>
d561 4
@


1.26
log
@This patch implements FOR EACH STATEMENT triggers, per my email to
-hackers a couple days ago.

Notes/caveats:

        - added regression tests for the new functionality, all
          regression tests pass on my machine

        - added pg_dump support

        - updated PL/PgSQL to support per-statement triggers; didn't
          look at the other procedural languages.

        - there's (even) more code duplication in trigger.c than there
          was previously. Any suggestions on how to refactor the
          ExecXXXTriggers() functions to reuse more code would be
          welcome -- I took a brief look at it, but couldn't see an
          easy way to do it (there are several subtly-different
          versions of the code in question)

        - updated the documentation. I also took the liberty of
          removing a big chunk of duplicated syntax documentation in
          the Programmer's Guide on triggers, and moving that
          information to the CREATE TRIGGER reference page.

        - I also included some spelling fixes and similar small
          cleanups I noticed while making the changes. If you'd like
          me to split those into a separate patch, let me know.

Neil Conway
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.25 2002/09/21 18:32:54 petere Exp $
d41 1
a41 1
    The syntax for creating triggers is described in &cite-reference;.
@


1.25
log
@Add more appropriate markup.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.24 2002/08/22 00:01:40 tgl Exp $
d10 8
a17 6
   function interfaces. Server-side functions can be written in SQL,
   C, or any defined procedural language. Trigger functions can be
   written in C and most procedural languages, but not in SQL. Note that
   statement-level trigger events are not supported in the current
   version. You can currently specify BEFORE or AFTER on INSERT,
   DELETE or UPDATE of a tuple as a trigger event.
d24 4
a27 3
    If a trigger event occurs, the trigger manager (called by the Executor)
    sets up a <structname>TriggerData</> information structure (described below) and calls
    the trigger function to handle the event.
d41 1
a41 104
    The syntax for creating triggers is:

<programlisting>
CREATE TRIGGER <replaceable>trigger</replaceable> [ BEFORE | AFTER ] [ INSERT | DELETE | UPDATE [ OR ... ] ]
    ON <replaceable>relation</replaceable> FOR EACH [ ROW | STATEMENT ]
    EXECUTE PROCEDURE <replaceable>procedure</replaceable>
     (<replaceable>args</replaceable>);
</programlisting>

    where the arguments are:

    <variablelist>
     <varlistentry>
      <term>
       <replaceable>trigger</replaceable>
      </term>
      <listitem>
       <para>
        The trigger must have a name distinct from all other triggers on
	the same table.  The name is needed
	if you ever have to delete the trigger.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>BEFORE</term>
      <term>AFTER</term>
      <listitem>
       <para>
	Determines whether the function is called before or after
	the event.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>INSERT</term>
      <term>DELETE</term>
      <term>UPDATE</term>
      <listitem>
       <para>
	The next element of the command determines what event(s) will trigger
	the function.  Multiple events can be specified separated by OR.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><replaceable>relation</replaceable></term>
      <listitem>
       <para>
	The relation name indicates which table the event applies to.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>ROW</term>
      <term>STATEMENT</term>
      <listitem>
       <para>
	The FOR EACH clause determines whether the trigger is fired for each
	affected row or before (or after) the entire statement has completed.
	Currently only the ROW case is supported.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><replaceable>procedure</replaceable></term>
      <listitem>
       <para>
	The procedure name is the function to be called.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><replaceable>args</replaceable></term>
      <listitem>
       <para>
	The arguments passed to the function in the <structname>TriggerData</> structure.
	This is either empty or a list of one or more simple literal
	constants (which will be passed to the function as strings).
       </para>

       <para>
	The purpose of including arguments in the 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 field 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 INSERT events on any table with suitable fields,
	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 UPDATE trigger.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
d45 3
a47 3
    Trigger functions return a <structname>HeapTuple</> to the calling executor.  The return
    value is ignored for triggers fired AFTER an operation,
    but it allows BEFORE triggers to:
d60 4
a63 3
       For INSERT and UPDATE triggers only, the returned tuple becomes the
       tuple which will be inserted or will replace the tuple being updated.
       This allows the trigger function to modify the row being inserted or
d74 3
a76 2
    Note that there is no initialization performed by the CREATE TRIGGER
    handler.  This may be changed in the future.
d89 9
a97 8
    If a trigger function executes SQL-queries (using SPI) then these queries
    may fire triggers again. This is known as cascading triggers.  There is no
    direct limitation on the number of cascade levels.  It is possible for
    cascades to cause recursive invocation of the same trigger --- for
    example, an INSERT trigger might execute a query that inserts an
    additional tuple into the same table, causing the INSERT trigger to be
    fired again.  It is the trigger programmer's
    responsibility to avoid infinite recursion in such scenarios.
d99 18
d139 5
a143 4
    When a function is called by the trigger manager, it is not passed any
    normal parameters, but it is passed a <quote>context</> pointer pointing to a
    <structname>TriggerData</> structure.  C functions can check whether they were called
    from the trigger manager or not by executing the macro
d148 5
a152 4
    If this returns true, then it is safe to cast <literal>fcinfo->context</> to type
    <literal>TriggerData *</literal> and make use of the pointed-to
    <structname>TriggerData</> structure.
    The function must <emphasis>not</emphasis> alter the <structname>TriggerData</>
d214 1
a214 2
	    Returns TRUE if trigger fired for
	    a ROW-level event.
d223 1
a223 2
	    Returns TRUE if trigger fired for
	    STATEMENT-level event.
d232 1
a232 1
	    Returns TRUE if trigger fired by INSERT.
d241 1
a241 1
	    Returns TRUE if trigger fired by DELETE.
d250 1
a250 1
	    Returns TRUE if trigger fired by UPDATE.
d280 9
a288 5
	is a pointer to the tuple for which the trigger is fired. This is the tuple
	being inserted (if INSERT), deleted (if DELETE) or updated (if UPDATE).
	If INSERT/DELETE then this is what you are to return to Executor if 
	you don't want to replace tuple with another one (INSERT) or skip the
	operation.
d297 5
a301 3
	is a pointer to the new version of tuple if UPDATE and <symbol>NULL</> if this is
	for an INSERT or a DELETE. This is what you are to return to Executor if
	UPDATE and you don't want to replace this tuple with another one or skip
d334 3
a336 2
       pointers to the arguments specified in the CREATE TRIGGER
       statement. Other members are for internal use only.
d391 6
a396 4
    Here is a very simple example of trigger usage.  Function <function>trigf</> reports
    the number of tuples in the triggered relation <literal>ttest</> and skips the
    operation if the query attempts to insert a null value into x (i.e - it acts as a
    not-null constraint but doesn't abort the transaction).
@


1.24
log
@Add a bunch of pseudo-types to replace the behavior formerly associated
with OPAQUE, as per recent pghackers discussion.  I still want to do some
more work on the 'cstring' pseudo-type, but I'm going to commit the bulk
of the changes now before the tree starts shifting under me ...
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/trigger.sgml,v 1.23 2002/04/19 16:36:08 tgl Exp $
d9 7
a15 6
   <productname>PostgreSQL</productname> has various server-side function
   interfaces. Server-side functions can be written in SQL, PL/pgSQL,
   Tcl, or C. Trigger functions can be written in any of these
   languages except SQL. Note that statement-level trigger events are not
   supported in the current version. You can currently specify BEFORE or
   AFTER on INSERT, DELETE or UPDATE of a tuple as a trigger event.
d23 1
a23 1
    sets up a TriggerData information structure (described below) and calls
d31 1
a31 1
    (The trigger function receives its input through a TriggerData
d40 1
a40 1
    <programlisting>
d45 1
a45 1
    </programlisting>
d120 1
a120 1
	The arguments passed to the function in the TriggerData structure.
d131 1
a131 1
	current user in one and the current timestamp in the other.
d145 1
a145 1
    Trigger functions return a HeapTuple to the calling Executor.  The return
d152 3
a154 2
       Return NULL to skip the operation for the current tuple (and so the
       tuple will not be inserted/updated/deleted).
d178 6
a183 6
    If more than one trigger
    is defined for the same event on the same relation, the triggers will
    be fired in alphabetical order by name.  In the case of BEFORE triggers,
    the possibly-modified tuple returned by each trigger becomes the input
    to the next trigger.  If any BEFORE trigger returns NULL, the operation
    is abandoned and subsequent triggers are not fired.
d212 2
a213 2
      Earlier versions passed the TriggerData pointer in a global
      variable CurrentTriggerData.
d220 1
a220 1
    TriggerData structure.  C functions can check whether they were called
d223 4
a226 4
    <programlisting>
        ((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))
    </programlisting>
    If this returns TRUE, then it is safe to cast fcinfo->context to type
d228 2
a229 2
    TriggerData structure.
    The function must <emphasis>not</emphasis> alter the TriggerData
d253 1
a253 1
      <term>type</term>
d262 1
a262 1
      <term>tg_event</term>
d339 1
a339 1
      <term>tg_relation</term>
d342 9
a350 6
	is a pointer to structure describing the triggered relation. Look at
	src/include/utils/rel.h for details about this structure.  The most
	interesting things are tg_relation->rd_att (descriptor of the relation
	tuples) and tg_relation->rd_rel->relname (relation's name. This is not
	char*, but NameData.  Use SPI_getrelname(tg_relation) to get char* if
	you need a copy of name).
d356 1
a356 1
      <term>tg_trigtuple</term>
d369 1
a369 1
      <term>tg_newtuple</term>
d372 1
a372 1
	is a pointer to the new version of tuple if UPDATE and NULL if this is
d381 1
a381 1
      <term>tg_trigger</term>
d384 1
a384 1
	is pointer to structure Trigger defined in src/include/utils/rel.h:
d386 1
a386 1
	<programlisting>
d402 1
a402 1
	</programlisting>
d404 5
a408 4
	where
	tgname is the trigger's name, tgnargs is number of arguments in tgargs,
	tgargs is an array of pointers to the arguments specified in the CREATE
	TRIGGER statement. Other members are for internal use only.
d424 1
a424 1
    <programlisting>
d426 1
a426 1
    </programlisting>
d447 1
a447 1
    (tg_trigtuple) is not visible to queries in a BEFORE trigger, this tuple
d463 8
a470 8
    Here is a very simple example of trigger usage.  Function trigf reports
    the number of tuples in the triggered relation ttest and skips the
    operation if the query attempts to insert NULL into x (i.e - it acts as a
    NOT NULL constraint but doesn't abort the transaction).

    <programlisting>
#include "executor/spi.h"	/* this is what you need to work with SPI */
#include "commands/trigger.h"	/* -"- and triggers */
d479 56
a534 56
	TriggerData    *trigdata = (TriggerData *) fcinfo->context;
	TupleDesc	tupdesc;
	HeapTuple	rettuple;
	char		*when;
	bool		checknull = false;
	bool		isnull;
	int		ret, i;

	/* Make sure trigdata is pointing at what I expect */
	if (!CALLED_AS_TRIGGER(fcinfo))
		elog(ERROR, "trigf: not fired by trigger manager");
	
	/* tuple to return to Executor */
	if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
		rettuple = trigdata->tg_newtuple;
	else
		rettuple = trigdata->tg_trigtuple;
	
	/* check for NULLs ? */
	if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event) &&
		TRIGGER_FIRED_BEFORE(trigdata->tg_event))
		checknull = true;
	
	if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
		when = "before";
	else
		when = "after ";
	
	tupdesc = trigdata->tg_relation->rd_att;
	
	/* Connect to SPI manager */
	if ((ret = SPI_connect()) < 0)
		elog(INFO, "trigf (fired %s): SPI_connect returned %d", when, ret);
	
	/* Get number of tuples in relation */
	ret = SPI_exec("SELECT count(*) FROM ttest", 0);
	
	if (ret < 0)
		elog(NOTICE, "trigf (fired %s): SPI_exec returned %d", when, ret);

	/* count(*) returns int8 as of PG 7.2, so be careful to convert */
	i = (int) DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
					      SPI_tuptable->tupdesc,
					      1,
					      &amp;isnull));
	
	elog (NOTICE, "trigf (fired %s): there are %d tuples in ttest", when, i);
	
	SPI_finish();
	
	if (checknull)
	{
		(void) SPI_getbinval(rettuple, tupdesc, 1, &amp;isnull);
		if (isnull)
			rettuple = NULL;
	}
d536 1
a536 1
	return PointerGetDatum(rettuple);
d538 1
a538 1
    </programlisting>
d544 1
a544 1
    <programlisting>
d546 1
a546 1
'...path_to_so' LANGUAGE 'C';
d549 1
a549 1
    </programlisting>
d551 1
a551 1
    <programlisting>
d565 2
a566 2
x
-
d576 3
a578 3
x
-
1
d588 4
a591 4
x
-
1
2
d594 1
a594 1
vac=> UPDATE ttest SET x = null WHERE x = 2;
d602 4
a605 4
x
-
1
4
d617 2
a618 2
x
-
d620 1
a620 1
    </programlisting>
@


1.23
log
@pg_trigger's index on tgrelid is replaced by a unique index on
(tgrelid, tgname).  This provides an additional check on trigger name
uniqueness per-table (which was already enforced by the code anyway).
With this change, RelationBuildTriggers will read the triggers in
order by tgname, since it's scanning using this index.  Since a
predictable trigger ordering has been requested for some time, document
this behavior as a feature.  Also document that rules fire in name
order, since yesterday's changes to pg_rewrite indexing cause that too.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/trigger.sgml,v 1.22 2002/04/01 22:36:06 tgl Exp $
d29 1
a29 1
    function taking no arguments and returning type <literal>opaque</>.
d539 1
a539 1
CREATE FUNCTION trigf () RETURNS OPAQUE AS 
@


1.22
log
@Add tgconstrrelid to stored Trigger structures, make RI trigger functions
depend on this rather than the trigger argument strings to locate the
other relation to test.  This makes RI triggers function properly in
the presence of schemas and temp tables.  Along the way, fix bogus lack
of locking in RI triggers, handle quoting of names fully correctly,
compute required sizes of query buffers with some semblance of accuracy.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/trigger.sgml,v 1.21 2002/03/22 19:20:32 petere Exp $
d17 2
a18 2
  <sect1 id="trigger-create">
   <title>Trigger Creation</title>
d27 7
a33 3
    The trigger function must be defined before the trigger is created as a
    function taking no arguments and returning opaque.  If the function is
    written in C, it must use the <quote>version 1</> function manager interface.
d37 1
a37 1
    The syntax for creating triggers is as follows:
d55 3
a57 3
	The name of the trigger is
	used if you ever have to delete the trigger.
	It is used as an argument to the <command>DROP TRIGGER</command> command.
d79 1
a79 1
	The next element of the command determines on what event(s) will trigger
d89 1
a89 1
	The relation name determines which table the event applies to.
d101 1
d110 1
a110 1
	The procedure name is the function called.
d120 2
a121 2
	The purpose of passing arguments to the function is to allow different
	triggers with similar requirements to call the same function.
d125 12
a136 12
	Also, <replaceable>procedure</replaceable>
	may be used for triggering different relations (these
	functions are named as <firstterm>general trigger functions</>).
       </para>

       <para>
	As example of using both features above, there could be a general
	function that takes as its arguments two field names and puts the current
	user in one and the current timestamp in the other. This allows triggers to
	be written on INSERT events to automatically track creation of records in a
	transaction table for example. It could also be used as a <quote>last updated</>
	function if used in an UPDATE event.
d144 2
a145 2
    Trigger functions return HeapTuple to the calling Executor.  This
    is ignored for triggers fired after an INSERT, DELETE or UPDATE operation
d158 4
a161 3
       Return a pointer to another tuple (INSERT and UPDATE only) which will
       be inserted (as the new version of the updated tuple if UPDATE) instead
       of original tuple.
d165 3
d172 1
a172 3
    handler.  This will be changed in the future.  Also, if more than one trigger
    is defined for the same event on the same relation, the order of trigger
    firing is unpredictable. This may be changed in the future.
d176 6
a181 3
    If a trigger function executes SQL-queries (using SPI) then these queries
    may fire triggers again. This is known as cascading triggers.  There is no
    explicit limitation on the number of cascade levels.
d185 8
a192 5
    If a trigger is fired by INSERT and inserts a new tuple in the same
    relation then this trigger will be fired again.  Currently, there is nothing
    provided for synchronization (etc) of these cases but this may change.  At
    the moment, there is function funny_dup17() in the regress tests which uses
    some techniques to stop recursion (cascading) on itself...
d342 1
a342 1
	interest things are tg_relation->rd_att (descriptor of the relation
@


1.21
log
@Spell checking and markup additions
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/trigger.sgml,v 1.20 2002/03/06 06:44:33 momjian Exp $
d377 1
@


1.20
log
@Update docs for new INFO, NOTICE, WARNING elog() levels.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/trigger.sgml,v 1.19 2001/12/04 02:07:11 tgl Exp $
d10 3
a12 3
   interfaces. Server-side functions can be written in SQL, PLPGSQL,
   TCL, or C. Trigger functions can be written in any of these
   languages except SQL. Note that STATEMENT-level trigger events are not
d219 2
a220 1
    struct TriggerData is defined in src/include/commands/trigger.h:
d222 1
a222 1
    <programlisting>
d232 1
a232 1
    </programlisting>
@


1.19
log
@Fix trigger example for PG 7.2 change: count(*) now returns int8.
@
text
@d2 1
a2 1
$Header$
d490 1
a490 1
		elog(NOTICE, "trigf (fired %s): SPI_connect returned %d", when, ret);
d538 1
a538 1
NOTICE:trigf (fired before): there are 0 tuples in ttest
d549 2
a550 2
NOTICE:trigf (fired before): there are 0 tuples in ttest
NOTICE:trigf (fired after ): there are 1 tuples in ttest
d561 2
a562 2
NOTICE:trigf (fired before): there are 1 tuples in ttest
NOTICE:trigf (fired after ): there are 2 tuples in ttest
d574 1
a574 1
NOTICE:trigf (fired before): there are 2 tuples in ttest
d577 2
a578 2
NOTICE:trigf (fired before): there are 2 tuples in ttest
NOTICE:trigf (fired after ): there are 2 tuples in ttest
d588 4
a591 4
NOTICE:trigf (fired before): there are 2 tuples in ttest
NOTICE:trigf (fired after ): there are 1 tuples in ttest
NOTICE:trigf (fired before): there are 1 tuples in ttest
NOTICE:trigf (fired after ): there are 0 tuples in ttest
@


1.18
log
@Deprecate 'current' date/time constant.
Purge "Postgres" in favor of "PostgreSQL" in docs. ref/ not yet done.
@
text
@d1 4
d458 1
a458 1
	TriggerData *trigdata = (TriggerData *) fcinfo->context;
d497 6
a502 2
	
	i = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &amp;isnull);
d510 1
a510 1
		i = SPI_getbinval(rettuple, tupdesc, 1, &amp;isnull);
@


1.17
log
@A bunch of small doco updates motivated by scanning the comments on
the interactive docs.
@
text
@d5 1
a5 1
   <productname>Postgres</productname> has various server-side function
d192 1
a192 1
      <productname>Postgres</productname> 7.1 and later.
d395 1
a395 1
    <productname>Postgres</productname> data changes visibility rule: during a query execution, data
@


1.16
log
@Uppercase keywords where appropriate.
@
text
@d23 1
a23 1
    The trigger function must be created before the trigger is created as a
@


1.15
log
@Replace ASCII-quotes with proper markup.
@
text
@d489 1
a489 1
	ret = SPI_exec("select count(*) from ttest", 0);
d516 2
a517 2
create function trigf () returns opaque as 
'...path_to_so' language 'C';
d519 1
a519 1
create table ttest (x int4);
d523 2
a524 2
vac=> create trigger tbefore before insert or update or delete on ttest 
for each row execute procedure trigf();
d526 2
a527 2
vac=> create trigger tafter after insert or update or delete on ttest 
for each row execute procedure trigf();
d529 1
a529 1
vac=> insert into ttest values (null);
d535 1
a535 1
vac=> select * from ttest;
d540 1
a540 1
vac=> insert into ttest values (1);
d546 1
a546 1
vac=> select * from ttest;
d552 1
a552 1
vac=> insert into ttest select x * 2 from ttest;
d558 1
a558 1
vac=> select * from ttest;
d565 1
a565 1
vac=> update ttest set x = null where x = 2;
d568 1
a568 1
vac=> update ttest set x = 4 where x = 2;
d572 1
a572 1
vac=> select * from ttest;
d579 1
a579 1
vac=> delete from ttest;
d587 1
a587 1
vac=> select * from ttest;
@


1.14
log
@Clean up some minor problems exposed by further thought about Panon's bug
report on old-style functions invoked by RI triggers.  We had a number of
other places that were being sloppy about which memory context FmgrInfo
subsidiary data will be allocated in.  Turns out none of them actually
cause a problem in 7.1, but this is for arcane reasons such as the fact
that old-style triggers aren't supported anyway.  To avoid getting burnt
later, I've restructured the trigger support so that we don't keep trigger
FmgrInfo structs in relcache memory.  Some other related cleanups too:
it's not really necessary to call fmgr_info at all while setting up
the index support info in relcache entries, because those ScanKeyEntry
structs are never used to invoke the functions.  This should speed up
relcache initialization a tiny bit.
@
text
@d25 1
a25 1
    written in C, it must use the "version 1" function manager interface.
d118 1
a118 1
	functions are named as "general trigger functions").
d126 1
a126 1
	transaction table for example. It could also be used as a "last updated"
d200 1
a200 1
    normal parameters, but it is passed a "context" pointer pointing to a
@


1.13
log
@Replace incorrect uses of 'which' with 'that'.  (so-called "wicked which")
@
text
@a368 1
    FmgrInfo    tgfunc;
@


1.12
log
@Revise handling of oldstyle/newstyle functions per recent discussions
in pghackers list.  Support for oldstyle internal functions is gone
(no longer needed, since conversion is complete) and pg_language entry
'internal' now implies newstyle call convention.  pg_language entry
'newC' is gone; both old and newstyle dynamically loaded C functions
are now called language 'C'.  A newstyle function must be identified
by an associated info routine.  See src/backend/utils/fmgr/README.
@
text
@d414 1
a414 1
Changes made by query Q are visible by queries which are started after
@


1.11
log
@Add `id' attributes to all `chapter' and `sect1' tags, to generate useful
names for the HTML files (e.g., not x4856.htm).
@
text
@d25 1
a25 1
    written in C, it must follow the "new style" function manager interface.
d450 2
d518 1
a518 1
'...path_to_so' language 'newC';
@


1.10
log
@Documentation updates to reflect TOAST and new-style fmgr.
@
text
@d13 1
a13 1
  <sect1>
d179 1
a179 1
  <sect1>
d392 1
a392 1
  <sect1>
d429 1
a429 1
  <sect1>
@


1.9
log
@Second round of fmgr changes: triggers are now invoked in new style,
CurrentTriggerData is history.
@
text
@d512 1
a512 2
    Now, compile and 
    create table ttest (x int4):
d516 3
a518 1
'...path_to_so' language 'c';
@


1.8
log
@Fix WARN->NOTICE in docs.  Change libpgeasy connection parameters to use
PQconnectdb() style connections.
@
text
@d18 2
a19 2
    initializes the global structure TriggerData *CurrentTriggerData (described
    below) and calls the trigger function to handle the event.
d24 2
a25 1
    function taking no arguments and returns opaque.
d110 1
a110 1
	The arguments passed to the function in the CurrentTriggerData structure.
d183 29
a211 5
    As mentioned above, when function is called by the trigger manager,
    structure TriggerData *CurrentTriggerData is NOT NULL and initialized.  So
    it is better to check CurrentTriggerData against being NULL at the start
    and set it to NULL just after fetching the information to prevent calls to
    a trigger function not from the trigger manager.
d220 1
d233 9
d448 1
a448 1
HeapTuple		trigf(void);
d450 2
a451 2
HeapTuple
trigf()
d453 1
d461 3
a463 2
	if (!CurrentTriggerData)
		elog(NOTICE, "trigf: triggers are not initialized");
d466 2
a467 2
	if (TRIGGER_FIRED_BY_UPDATE(CurrentTriggerData->tg_event))
		rettuple = CurrentTriggerData->tg_newtuple;
d469 1
a469 1
		rettuple = CurrentTriggerData->tg_trigtuple;
d472 2
a473 2
	if (!TRIGGER_FIRED_BY_DELETE(CurrentTriggerData->tg_event) &&
		TRIGGER_FIRED_BEFORE(CurrentTriggerData->tg_event))
d476 1
a476 1
	if (TRIGGER_FIRED_BEFORE(CurrentTriggerData->tg_event))
d481 1
a481 2
	tupdesc = CurrentTriggerData->tg_relation->rd_att;
	CurrentTriggerData = NULL;
d506 1
a506 1
	return (rettuple);
@


1.7
log
@Update trigger.sgml
@
text
@d426 1
a426 1
		elog(WARN, "trigf: triggers are not initialized");
d449 1
a449 1
		elog(WARN, "trigf (fired %s): SPI_connect returned %d", when, ret);
d455 1
a455 1
		elog(WARN, "trigf (fired %s): SPI_exec returned %d", when, ret);
@


1.6
log
@Clean up trigger sgml docs.
@
text
@d8 3
a10 3
   languages. Note that STATEMENT-level trigger events are not supported
   in the current version. You can currently specify BEFORE or AFTER on
   INSERT, DELETE or UPDATE of a tuple as a trigger event.
@


1.5
log
@Fixups in content and markup for 7.0 release.
@
text
@d5 6
a10 7
   <productname>Postgres</productname> has various client interfaces
   such as Perl, Tcl, Python and C, as well as three
   <firstterm>Procedural Languages</firstterm>
   (PL).  It is also possible
   to call C functions as trigger actions.  Note that STATEMENT-level trigger
   events are not supported in the current version.  You can currently specify
   BEFORE or AFTER on INSERT, DELETE or UPDATE of a tuple as a trigger event.
d100 1
a100 1
	The procedure name is the C function called.
@


1.4
log
@Update struct Trigger definition.
@
text
@d1 2
a2 2
<Chapter Id="triggers">
<Title>Triggers</Title>
d4 185
a188 127
<Para>
<ProductName>Postgres</ProductName> has various client interfaces
such as Perl, Tcl, Python and C, as well as two
<FirstTerm>Procedural Languages</FirstTerm>
(PL).  It is also possible
to call C functions as trigger actions.  Note that STATEMENT-level trigger
events are not supported in the current version.  You can currently specify
BEFORE or AFTER on INSERT, DELETE or UPDATE of a tuple as a trigger event.
</Para>

<Sect1>
<Title>Trigger Creation</Title>

<Para>
   If a trigger event occurs, the trigger manager (called by the Executor)
initializes the global structure TriggerData *CurrentTriggerData (described
below) and calls the trigger function to handle the event.
</Para>

<Para>
   The trigger function must be created before the trigger is created as a
function taking no arguments and returns opaque.
</Para>

<Para>
   The syntax for creating triggers is as follows:

<ProgramListing>
   CREATE TRIGGER &lt;trigger name&gt; &lt;BEFORE|AFTER&gt; &lt;INSERT|DELETE|UPDATE&gt;
       ON &lt;relation name&gt; FOR EACH &lt;ROW|STATEMENT&gt;
       EXECUTE PROCEDURE &lt;procedure name&gt; (&lt;function args&gt;);
</ProgramListing>
</Para>

<Para>
   The name of the trigger is used if you ever have to delete the trigger.
It is used as an argument to the DROP TRIGGER command.
</Para>

<Para>
   The next word determines whether the function is called before or after
the event.
</Para>

<Para>
   The next element of the command determines on what event(s) will trigger
the function.  Multiple events can be specified separated by OR.
</Para>

<Para>
   The relation name determines which table the event applies to.
</Para>

<Para>
   The FOR EACH statement determines whether the trigger is fired for each
affected row or before (or after) the entire statement has completed.
</Para>

<Para>
   The procedure name is the C function called.
</Para>

<Para>
   The args are passed to the function in the CurrentTriggerData structure.
The purpose of passing arguments to the function is to allow different
triggers with similar requirements to call the same function.
</Para>

<Para>
   Also, function may be used for triggering different relations (these
functions are named as "general trigger functions").
</Para>

<Para>
   As example of using both features above, there could be a general
function that takes as its arguments two field names and puts the current
user in one and the current timestamp in the other. This allows triggers to
be written on INSERT events to automatically track creation of records in a
transaction table for example. It could also be used as a "last updated"
function if used in an UPDATE event.
</Para>

<Para>
   Trigger functions return HeapTuple to the calling Executor.  This
is ignored for triggers fired after an INSERT, DELETE or UPDATE operation
but it allows BEFORE triggers to:

   - return NULL to skip the operation for the current tuple (and so the
     tuple will not be inserted/updated/deleted);
   - return a pointer to another tuple (INSERT and UPDATE only) which will
     be inserted (as the new version of the updated tuple if UPDATE) instead
     of original tuple.
</Para>

<Para>
   Note, that there is no initialization performed by the CREATE TRIGGER
handler.  This will be changed in the future.  Also, if more than one trigger
is defined for the same event on the same relation, the order of trigger
firing is unpredictable. This may be changed in the future.
</Para>

<Para>
   If a trigger function executes SQL-queries (using SPI) then these queries
may fire triggers again. This is known as cascading triggers.  There is no
explicit limitation on the number of cascade levels.
</Para>

<Para>
   If a trigger is fired by INSERT and inserts a new tuple in the same
relation then this trigger will be fired again.  Currently, there is nothing
provided for synchronization (etc) of these cases but this may change.  At
the moment, there is function funny_dup17() in the regress tests which uses
some techniques to stop recursion (cascading) on itself...
</Para>

</Sect1>

<Sect1>
<Title>Interaction with the Trigger Manager</Title>

<Para>
   As mentioned above, when function is called by the trigger manager,
structure TriggerData *CurrentTriggerData is NOT NULL and initialized.  So
it is better to check CurrentTriggerData against being NULL at the start
and set it to NULL just after fetching the information to prevent calls to
a trigger function not from the trigger manager.
</Para>
d190 2
a191 2
<Para>
   struct TriggerData is defined in src/include/commands/trigger.h:
d193 1
a193 1
<ProgramListing>
d196 5
a200 5
	TriggerEvent	tg_event;
	Relation	tg_relation;
	HeapTuple	tg_trigtuple;
	HeapTuple	tg_newtuple;
	Trigger		*tg_trigger;
d202 1
a202 1
</ProgramListing>
d204 1
a204 35
<ProgramListing>
tg_event 
   describes event for which the function is called. You may use the
   following macros to examine tg_event:

   TRIGGER_FIRED_BEFORE(event) returns TRUE if trigger fired BEFORE;
   TRIGGER_FIRED_AFTER(event) returns TRUE if trigger fired AFTER;
   TRIGGER_FIRED_FOR_ROW(event) returns TRUE if trigger fired for
                                ROW-level event;
   TRIGGER_FIRED_FOR_STATEMENT(event) returns TRUE if trigger fired for
                                STATEMENT-level event;
   TRIGGER_FIRED_BY_INSERT(event) returns TRUE if trigger fired by INSERT;
   TRIGGER_FIRED_BY_DELETE(event) returns TRUE if trigger fired by DELETE;
   TRIGGER_FIRED_BY_UPDATE(event) returns TRUE if trigger fired by UPDATE.

tg_relation
   is pointer to structure describing the triggered relation. Look at
   src/include/utils/rel.h for details about this structure.  The most
   interest things are tg_relation->rd_att (descriptor of the relation
   tuples) and tg_relation->rd_rel->relname (relation's name. This is not
   char*, but NameData.  Use SPI_getrelname(tg_relation) to get char* if
   you need a copy of name).

tg_trigtuple
   is a pointer to the tuple for which the trigger is fired. This is the tuple
   being inserted (if INSERT), deleted (if DELETE) or updated (if UPDATE).
   If INSERT/DELETE then this is what you are to return to Executor if 
   you don't want to replace tuple with another one (INSERT) or skip the
   operation.

tg_newtuple
   is a pointer to the new version of tuple if UPDATE and NULL if this is
   for an INSERT or a DELETE. This is what you are to return to Executor if
   UPDATE and you don't want to replace this tuple with another one or skip
   the operation.
d206 122
a327 2
tg_trigger
   is pointer to structure Trigger defined in src/include/utils/rel.h:
d329 1
d345 1
d347 62
a408 55
   tgname is the trigger's name, tgnargs is number of arguments in tgargs,
   tgargs is an array of pointers to the arguments specified in the CREATE
   TRIGGER statement. Other members are for internal use only.
</ProgramListing>
</Para>
</Sect1>

<Sect1>
<Title>Visibility of Data Changes</Title>

<Para>
   <ProductName>Postgres</ProductName> data changes visibility rule: during a query execution, data
changes made by the query itself (via SQL-function, SPI-function, triggers)
are invisible to the query scan.  For example, in query

<ProgramListing>
   INSERT INTO a SELECT * FROM a
</ProgramListing>

   tuples inserted are invisible for SELECT' scan.  In effect, this
duplicates the database table within itself (subject to unique index
rules, of course) without recursing.
</Para>

<Para>
   But keep in mind this notice about visibility in the SPI documentation:

<ProgramListing>
   Changes made by query Q are visible by queries which are started after
   query Q, no matter whether they are started inside Q (during the
   execution of Q) or after Q is done.
</ProgramListing>
</Para>

<Para>
   This is true for triggers as well so, though a tuple being inserted
(tg_trigtuple) is not visible to queries in a BEFORE trigger, this tuple
(just inserted) is visible to queries in an AFTER trigger, and to queries
in BEFORE/AFTER triggers fired after this!
</Para>
</Sect1>

<Sect1>
<Title>Examples</Title>

<Para>
   There are more complex examples in in src/test/regress/regress.c and
in contrib/spi.
</Para>

<Para>
   Here is a very simple example of trigger usage.  Function trigf reports
the number of tuples in the triggered relation ttest and skips the
operation if the query attempts to insert NULL into x (i.e - it acts as a
NOT NULL constraint but doesn't abort the transaction).
d410 1
a410 1
<ProgramListing>
d473 2
a474 2
</ProgramListing>
</Para>
d476 5
a480 3
<Para>
   Now, compile and 
create table ttest (x int4);
d483 1
d485 1
a485 1
<ProgramListing>
d554 1
a554 1
</ProgramListing>
d556 20
a575 3
</Para>
</Sect1>
</Chapter>
@


1.3
log
@Minor editing and markup changes as a result of preparing the Postscript
 documentation for v6.4.
Bigger updates to the installation instructions (install and config).
@
text
@d187 12
a198 7
	char		*tgname;
	Oid		tgfoid;
	func_ptr	tgfunc;
	int16		tgtype;
	int16		tgnargs;
	int16		tgattr[8];
	char		**tgargs;
@


1.2
log
@Add id field to chapter and book tags to allow output file names
 to be meaningful.
@
text
@d5 4
a8 3
   While the current version of <ProductName>Postgres</ProductName> has various client interfaces
such as Perl, Tcl, Python and C, it lacks an actual <FirstTerm>Procedural Language</FirstTerm>
(PL).  We hope to have a proper PL one day.  In the meantime it is possible
@


1.1
log
@SGML source for new documentation.
@
text
@d1 1
a1 1
<Chapter>
@
