head	1.56;
access;
symbols
	REL9_0_0:1.56
	REL9_1_ALPHA1:1.56
	REL9_0_RC1:1.56
	REL9_0_BETA4:1.56
	REL9_0_STABLE:1.56.0.2
	REL9_0_BETA3:1.56
	REL9_0_BETA2:1.56
	REL7_4_29:1.31.2.2
	REL8_0_25:1.37.4.5
	REL8_1_21:1.44.2.1
	REL8_2_17:1.47.2.2
	REL8_3_11:1.51.2.1
	REL8_4_4:1.52.2.1
	REL9_0_BETA1:1.55
	REL9_0_ALPHA5_BRANCH:1.55.0.2
	REL9_0_ALPHA5:1.55
	REL7_4_28:1.31.2.1
	REL8_0_24:1.37.4.4
	REL8_1_20:1.44
	REL8_2_16:1.47.2.1
	REL8_3_10:1.51
	REL8_4_3:1.52
	REL9_0_ALPHA4:1.53
	REL9_0_ALPHA4_BRANCH:1.53.0.4
	REL8_5_ALPHA3:1.53
	REL8_5_ALPHA3_BRANCH:1.53.0.2
	REL7_4_27:1.31.2.1
	REL8_0_23:1.37.4.4
	REL8_1_19:1.44
	REL8_2_15:1.47.2.1
	REL8_3_9:1.51
	REL8_4_2:1.52
	REL8_5_ALPHA2:1.52
	REL8_5_ALPHA2_BRANCH:1.52.0.6
	REL7_4_26:1.31.2.1
	REL8_0_22:1.37.4.4
	REL8_1_18:1.44
	REL8_2_14:1.47.2.1
	REL8_3_8:1.51
	REL8_4_1:1.52
	REL8_5_ALPHA1:1.52
	REL8_5_ALPHA1_BRANCH:1.52.0.4
	REL8_4_STABLE:1.52.0.2
	REL8_4_0:1.52
	REL8_4_RC2:1.52
	REL8_4_RC1:1.52
	REL8_4_BETA2:1.52
	REL8_4_BETA1:1.52
	REL7_4_25:1.31.2.1
	REL8_0_21:1.37.4.4
	REL8_1_17:1.44
	REL8_2_13:1.47.2.1
	REL8_3_7:1.51
	REL7_4_24:1.31.2.1
	REL8_0_20:1.37.4.4
	REL8_1_16:1.44
	REL8_2_12:1.47.2.1
	REL8_3_6:1.51
	REL7_4_23:1.31.2.1
	REL8_0_19:1.37.4.4
	REL8_1_15:1.44
	REL8_2_11:1.47.2.1
	REL8_3_5:1.51
	REL7_4_22:1.31.2.1
	REL8_0_18:1.37.4.4
	REL8_1_14:1.44
	REL8_2_10:1.47.2.1
	REL8_3_4:1.51
	REL7_4_21:1.31.2.1
	REL8_0_17:1.37.4.4
	REL8_1_13:1.44
	REL8_2_9:1.47.2.1
	REL8_3_3:1.51
	REL7_4_20:1.31.2.1
	REL8_0_16:1.37.4.4
	REL8_1_12:1.44
	REL8_2_8:1.47.2.1
	REL8_3_2:1.51
	REL8_2_7:1.47.2.1
	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.26
	REL7_4_19:1.31.2.1
	REL8_0_15:1.37.4.4
	REL8_1_11:1.44
	REL8_2_6:1.47.2.1
	REL8_3_RC1:1.51
	REL8_3_BETA4:1.51
	REL8_3_BETA3:1.51
	REL8_3_BETA2:1.51
	REL8_3_BETA1:1.51
	REL7_3_20:1.26
	REL7_4_18:1.31.2.1
	REL8_0_14:1.37.4.4
	REL8_1_10:1.44
	REL8_2_5:1.47.2.1
	REL7_3_19:1.26
	REL7_4_17:1.31.2.1
	REL8_0_13:1.37.4.4
	REL8_1_9:1.44
	REL8_2_4:1.47.2.1
	REL8_0_12:1.37.4.4
	REL8_1_8:1.44
	REL8_2_3:1.47.2.1
	REL7_3_18:1.26
	REL7_4_16:1.31.2.1
	REL8_0_11:1.37.4.4
	REL8_1_7:1.44
	REL8_2_2:1.47.2.1
	REL8_0_10:1.37.4.4
	REL8_1_6:1.44
	REL8_2_1:1.47.2.1
	REL7_4_15:1.31.2.1
	REL7_3_17:1.26
	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.44
	REL8_0_9:1.37.4.4
	REL7_4_14:1.31.2.1
	REL7_3_16:1.26
	REL8_2_BETA1:1.47
	REL7_3_15:1.26
	REL7_4_13:1.31.2.1
	REL8_0_8:1.37.4.4
	REL8_1_4:1.44
	REL7_3_14:1.26
	REL7_4_12:1.31.2.1
	REL8_0_7:1.37.4.4
	REL8_1_3:1.44
	REL7_3_13:1.26
	REL7_4_11:1.31.2.1
	REL8_0_6:1.37.4.4
	REL8_1_2:1.44
	REL7_3_12:1.26
	REL7_4_10:1.31.2.1
	REL8_0_5:1.37.4.4
	REL8_1_1:1.44
	REL8_1_STABLE:1.44.0.2
	REL8_1_0:1.44
	REL8_1_0RC1:1.44
	REL8_1_0BETA4:1.44
	REL8_1_0BETA3:1.42
	REL7_3_11:1.26
	REL7_4_9:1.31.2.1
	REL8_0_4:1.37.4.4
	REL8_1_0BETA2:1.42
	REL8_1_0BETA1:1.42
	REL7_2_8:1.21
	REL7_3_10:1.26
	REL7_4_8:1.31.2.1
	REL8_0_3:1.37.4.4
	REL8_0_2:1.37.4.4
	REL7_2_7:1.21
	REL7_3_9:1.26
	REL7_4_7:1.31.2.1
	REL8_0_1:1.37.4.4
	REL8_0_STABLE:1.37.0.4
	REL8_0_0:1.37.0.2
	REL8_0_0RC5:1.37
	REL8_0_0RC4:1.37
	REL8_0_0RC3:1.37
	REL8_0_0RC2:1.36
	REL8_0_0RC1:1.36
	REL8_0_0BETA5:1.36
	REL8_0_0BETA4:1.35
	REL7_4_6:1.31
	REL7_3_8:1.26
	REL7_2_6:1.21
	REL8_0_0BETA3:1.35
	REL8_0_0BETA2:1.35
	REL7_2_5:1.21
	REL7_4_5:1.31
	REL7_3_7:1.26
	REL7_4_4:1.31
	REL8_0_0BETA1:1.35
	REL7_4_3:1.31
	REL7_4_2:1.31
	REL7_3_6:1.26
	REL7_4_1:1.31
	REL7_3_5:1.26
	REL7_4:1.31
	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.28
	WIN32_DEV:1.28.0.2
	REL7_4_BETA1:1.28
	REL7_3_4:1.26
	REL7_3_2:1.26
	REL7_2_4:1.21
	REL7_3_STABLE:1.26.0.2
	REL7_2_3:1.21
	REL7_2_STABLE:1.21.0.2
	REL7_2:1.21
	REL7_2_RC2:1.21
	REL7_2_RC1:1.21
	REL7_2_BETA5:1.20
	REL7_2_BETA4:1.19
	REL7_2_BETA3:1.18
	REL7_2_BETA2:1.17
	REL7_2_BETA1:1.17
	REL7_1_2:1.11
	REL7_1_STABLE:1.11.0.2
	REL7_1_BETA:1.9
	REL7_1_BETA3:1.10
	REL7_1_BETA2:1.10
	REL7_1:1.11
	REL7_0_PATCHES:1.8.0.2
	REL7_0:1.8
	REL6_5_PATCHES:1.7.0.2
	REL6_5:1.7
	REL6_4:1.4.0.2
	release-6-3:1.1;
locks; strict;
comment	@# @;


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

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

1.54
date	2010.02.24.03.33.49;	author momjian;	state Exp;
branches;
next	1.53;

1.53
date	2009.11.05.23.24.22;	author tgl;	state Exp;
branches;
next	1.52;

1.52
date	2008.12.16.03.12.08;	author momjian;	state Exp;
branches
	1.52.2.1;
next	1.51;

1.51
date	2007.02.01.19.10.24;	author momjian;	state Exp;
branches
	1.51.2.1;
next	1.50;

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

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

1.48
date	2006.12.27.16.07.36;	author tgl;	state Exp;
branches;
next	1.47;

1.47
date	2006.09.16.00.30.15;	author momjian;	state Exp;
branches
	1.47.2.1;
next	1.46;

1.46
date	2006.09.02.17.06.52;	author tgl;	state Exp;
branches;
next	1.45;

1.45
date	2006.04.23.03.39.52;	author momjian;	state Exp;
branches;
next	1.44;

1.44
date	2005.10.22.14.44.35;	author alvherre;	state Exp;
branches
	1.44.2.1;
next	1.43;

1.43
date	2005.10.15.20.12.33;	author neilc;	state Exp;
branches;
next	1.42;

1.42
date	2005.05.20.01.37.08;	author neilc;	state Exp;
branches;
next	1.41;

1.41
date	2005.01.29.23.45.36;	author tgl;	state Exp;
branches;
next	1.40;

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

1.39
date	2005.01.22.22.56.36;	author momjian;	state Exp;
branches;
next	1.38;

1.38
date	2005.01.22.22.06.27;	author momjian;	state Exp;
branches;
next	1.37;

1.37
date	2004.12.30.03.13.56;	author tgl;	state Exp;
branches
	1.37.4.1;
next	1.36;

1.36
date	2004.11.15.06.32.14;	author neilc;	state Exp;
branches;
next	1.35;

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

1.34
date	2004.03.09.05.05.40;	author momjian;	state Exp;
branches;
next	1.33;

1.33
date	2003.12.13.23.59.06;	author neilc;	state Exp;
branches;
next	1.32;

1.32
date	2003.11.29.19.51.37;	author pgsql;	state Exp;
branches;
next	1.31;

1.31
date	2003.11.01.01.56.29;	author petere;	state Exp;
branches
	1.31.2.1;
next	1.30;

1.30
date	2003.09.11.21.42.20;	author momjian;	state Exp;
branches;
next	1.29;

1.29
date	2003.08.31.17.32.19;	author petere;	state Exp;
branches;
next	1.28;

1.28
date	2003.04.11.13.22.35;	author petere;	state Exp;
branches
	1.28.2.1;
next	1.27;

1.27
date	2003.02.19.03.13.24;	author momjian;	state Exp;
branches;
next	1.26;

1.26
date	2002.10.19.19.00.47;	author tgl;	state Exp;
branches;
next	1.25;

1.25
date	2002.10.14.22.14.34;	author tgl;	state Exp;
branches;
next	1.24;

1.24
date	2002.09.21.18.32.53;	author petere;	state Exp;
branches;
next	1.23;

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

1.22
date	2002.03.22.19.20.26;	author petere;	state Exp;
branches;
next	1.21;

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

1.20
date	2002.01.07.02.29.13;	author petere;	state Exp;
branches;
next	1.19;

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

1.18
date	2001.11.12.19.19.39;	author petere;	state Exp;
branches;
next	1.17;

1.17
date	2001.09.13.15.55.23;	author petere;	state Exp;
branches;
next	1.16;

1.16
date	2001.09.12.01.22.25;	author ishii;	state Exp;
branches;
next	1.15;

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

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

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

1.12
date	2001.05.12.22.51.35;	author petere;	state Exp;
branches;
next	1.11;

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

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

1.9
date	2000.09.29.20.21.34;	author petere;	state Exp;
branches;
next	1.8;

1.8
date	2000.05.02.20.01.52;	author thomas;	state Exp;
branches;
next	1.7;

1.7
date	99.06.03.16.13.54;	author thomas;	state Exp;
branches;
next	1.6;

1.6
date	98.12.29.02.24.20;	author thomas;	state Exp;
branches;
next	1.5;

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

1.4
date	98.10.25.00.29.00;	author thomas;	state Exp;
branches;
next	1.3;

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

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

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

1.28.2.1
date	2003.09.07.04.36.43;	author momjian;	state Exp;
branches;
next	;

1.31.2.1
date	2005.01.29.23.46.16;	author tgl;	state Exp;
branches;
next	1.31.2.2;

1.31.2.2
date	2010.05.13.19.16.52;	author tgl;	state Exp;
branches;
next	;

1.37.4.1
date	2005.01.22.22.10.10;	author momjian;	state Exp;
branches;
next	1.37.4.2;

1.37.4.2
date	2005.01.22.23.05.49;	author momjian;	state Exp;
branches;
next	1.37.4.3;

1.37.4.3
date	2005.01.23.00.37.23;	author momjian;	state Exp;
branches;
next	1.37.4.4;

1.37.4.4
date	2005.01.29.23.45.53;	author tgl;	state Exp;
branches;
next	1.37.4.5;

1.37.4.5
date	2010.05.13.19.16.45;	author tgl;	state Exp;
branches;
next	;

1.44.2.1
date	2010.05.13.19.16.38;	author tgl;	state Exp;
branches;
next	;

1.47.2.1
date	2006.12.27.16.07.42;	author tgl;	state Exp;
branches;
next	1.47.2.2;

1.47.2.2
date	2010.05.13.19.16.32;	author tgl;	state Exp;
branches;
next	;

1.51.2.1
date	2010.05.13.19.16.27;	author tgl;	state Exp;
branches;
next	;

1.52.2.1
date	2010.05.13.19.16.21;	author tgl;	state Exp;
branches;
next	;


desc
@@


1.56
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.55 2010/02/24 15:54:31 momjian Exp $ -->

<chapter id="rules">
<title>The Rule System</title>

 <indexterm zone="rules">
  <primary>rule</primary>
 </indexterm>

<para>
     This chapter discusses the rule system in
     <productname>PostgreSQL</productname>.  Production rule systems
     are conceptually simple, but there are many subtle points
     involved in actually using them.
</para>

<para>
     Some other database systems define active database rules, which
     are usually stored procedures and triggers.  In
     <productname>PostgreSQL</productname>, these can be implemented
     using functions and triggers as well.
</para>

<para>
     The rule system (more precisely speaking, the query rewrite rule
     system) is totally different from stored procedures and triggers.
     It modifies queries to take rules into consideration, and then
     passes the modified query to the query planner for planning and
     execution.  It is very powerful, and can be used for many things
     such as query language procedures, views, and versions.  The
     theoretical foundations and the power of this rule system are
     also discussed in <xref linkend="STON90b"> and <xref
     linkend="ONG90">.
</para>

<sect1 id="querytree">
<title>The Query Tree</title>

<indexterm zone="querytree">
 <primary>query tree</primary>
</indexterm>

<para>
    To understand how the rule system works it is necessary to know
    when it is invoked and what its input and results are.
</para>

<para>
    The rule system is located between the parser and the planner.
    It takes the output of the parser, one query tree, and the user-defined
    rewrite rules, which are also
    query trees with some extra information, and creates zero or more
    query trees as result. So its input and output are always things
    the parser itself could have produced and thus, anything it sees
    is basically representable as an <acronym>SQL</acronym> statement.
</para>

<para>
    Now what is a query tree? It is an internal representation of an
    <acronym>SQL</acronym> statement where the single parts that it is
    built from are stored separately. These query trees can be shown
    in the server log if you set the configuration parameters
    <varname>debug_print_parse</varname>,
    <varname>debug_print_rewritten</varname>, or
    <varname>debug_print_plan</varname>.  The rule actions are also
    stored as query trees, in the system catalog
    <structname>pg_rewrite</structname>.  They are not formatted like
    the log output, but they contain exactly the same information.
</para>

<para>
    Reading a raw query tree requires some experience.  But since
    <acronym>SQL</acronym> representations of query trees are
    sufficient to understand the rule system, this chapter will not
    teach how to read them.
</para>

<para>
    When reading the <acronym>SQL</acronym> representations of the 
    query trees in this chapter it is necessary to be able to identify
    the parts the statement is broken into when it is in the query tree
    structure. The parts of a query tree are

<variablelist>
    <varlistentry>
    <term>
        the command type
    </term>
    <listitem>
    <para>
        This is a simple value telling which command
        (<command>SELECT</command>, <command>INSERT</command>,
        <command>UPDATE</command>, <command>DELETE</command>) produced
        the query tree.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the range table
    </term>
      <indexterm><primary>range table</></>
    <listitem>
    <para>
        The range table is a list of relations that are used in the query.
        In a <command>SELECT</command> statement these are the relations given after
        the <literal>FROM</literal> key word.
    </para>

    <para>
        Every range table entry identifies a table or view and tells
        by which name it is called in the other parts of the query.
        In the query tree, the range table entries are referenced by
        number rather than by name, so here it doesn't matter if there
        are duplicate names as it would in an <acronym>SQL</acronym>
        statement. This can happen after the range tables of rules
        have been merged in. The examples in this chapter will not have
        this situation.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the result relation
    </term>
    <listitem>
    <para>
        This is an index into the range table that identifies the
        relation where the results of the query go.
    </para>

    <para>
        <command>SELECT</command> queries normally don't have a result
        relation. The special case of a <command>SELECT INTO</command> is
        mostly identical to a <command>CREATE TABLE</command> followed by a
        <literal>INSERT ... SELECT</literal> and is not discussed
        separately here.
    </para>

    <para>
        For <command>INSERT</command>, <command>UPDATE</command>, and
        <command>DELETE</command> commands, the result relation is the table
        (or view!) where the changes are to take effect.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the target list
    </term>
    <indexterm><primary>target list</></>
    <listitem>
    <para>
        The target list is a list of expressions that define the
        result of the query.  In the case of a
        <command>SELECT</command>, these expressions are the ones that
        build the final output of the query.  They correspond to the
        expressions between the key words <command>SELECT</command>
        and <command>FROM</command>.  (<literal>*</literal> is just an
        abbreviation for all the column names of a relation.  It is
        expanded by the parser into the individual columns, so the
        rule system never sees it.)
    </para>

    <para>
        <command>DELETE</command> commands don't need a target list
        because they don't produce any result. In fact, the planner will
        add a special <acronym>CTID</> entry to the empty target list, but
        this is after the rule system and will be discussed later; for the
        rule system, the target list is empty.
    </para>

    <para>
        For <command>INSERT</command> commands, the target list describes
        the new rows that should go into the result relation. It consists of the
        expressions in the <literal>VALUES</> clause or the ones from the
        <command>SELECT</command> clause in <literal>INSERT
        ... SELECT</literal>.  The first step of the rewrite process adds
        target list entries for any columns that were not assigned to by
        the original command but have defaults.  Any remaining columns (with
        neither a given value nor a default) will be filled in by the
        planner with a constant null expression.
    </para>

    <para>
        For <command>UPDATE</command> commands, the target list
        describes the new rows that should replace the old ones. In the
        rule system, it contains just the expressions from the <literal>SET
        column = expression</literal> part of the command.  The planner will handle
        missing columns by inserting expressions that copy the values from
        the old row into the new one. And it will add the special
        <acronym>CTID</> entry just as for <command>DELETE</command>, too.
    </para>

    <para>
        Every entry in the target list contains an expression that can
        be a constant value, a variable pointing to a column of one
        of the relations in the range table, a parameter, or an expression
        tree made of function calls, constants, variables, operators, etc.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the qualification
    </term>
    <listitem>
    <para>
        The query's qualification is an expression much like one of
        those contained in the target list entries. The result value of
        this expression is a Boolean that tells whether the operation
        (<command>INSERT</command>, <command>UPDATE</command>,
        <command>DELETE</command>, or <command>SELECT</command>) for the
        final result row should be executed or not. It corresponds to the <literal>WHERE</> clause
        of an <acronym>SQL</acronym> statement.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the join tree
    </term>
    <listitem>
    <para>
        The query's join tree shows the structure of the <literal>FROM</> clause.
        For a simple query like <literal>SELECT ... FROM a, b, c</literal>, the join tree is just
        a list of the <literal>FROM</> items, because we are allowed to join them in
        any order.  But when <literal>JOIN</> expressions, particularly outer joins,
        are used, we have to join in the order shown by the joins.
        In that case, the join tree shows the structure of the <literal>JOIN</> expressions.  The
        restrictions associated with particular <literal>JOIN</> clauses (from <literal>ON</> or
        <literal>USING</> expressions) are stored as qualification expressions attached
        to those join-tree nodes.  It turns out to be convenient to store
        the top-level <literal>WHERE</> expression as a qualification attached to the
        top-level join-tree item, too.  So really the join tree represents
        both the <literal>FROM</> and <literal>WHERE</> clauses of a <command>SELECT</command>.
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
    <term>
        the others
    </term>
    <listitem>
    <para>
        The other parts of the query tree like the <literal>ORDER BY</>
        clause aren't of interest here. The rule system
        substitutes some entries there while applying rules, but that
        doesn't have much to do with the fundamentals of the rule
        system.
    </para>
    </listitem>
    </varlistentry>

</variablelist>
</para>
</sect1>

<sect1 id="rules-views">
<title>Views and the Rule System</title>

<indexterm zone="rules-views">
 <primary>rule</primary>
 <secondary>and views</secondary>
</indexterm>

<indexterm zone="rules-views">
 <primary>view</>
 <secondary>implementation through rules</>
</indexterm>

<para>
    Views in <productname>PostgreSQL</productname> are implemented
    using the rule system. In fact, there is essentially no difference
    between:

<programlisting>
CREATE VIEW myview AS SELECT * FROM mytab;
</programlisting>
    
    compared against the two commands:

<programlisting>
CREATE TABLE myview (<replaceable>same column list as mytab</replaceable>);
CREATE RULE "_RETURN" AS ON SELECT TO myview DO INSTEAD
    SELECT * FROM mytab;
</programlisting>
    
    because this is exactly what the <command>CREATE VIEW</command>
    command does internally.  This has some side effects. One of them
    is that the information about a view in the
    <productname>PostgreSQL</productname> system catalogs is exactly
    the same as it is for a table. So for the parser, there is
    absolutely no difference between a table and a view. They are the
    same thing: relations.
</para>

<sect2 id="rules-select">
<title>How <command>SELECT</command> Rules Work</title>

<indexterm zone="rules-select">
 <primary>rule</primary>
 <secondary sortas="SELECT">for SELECT</secondary>
</indexterm>

<para>
    Rules <literal>ON SELECT</> are applied to all queries as the last step, even
    if the command given is an <command>INSERT</command>,
    <command>UPDATE</command> or <command>DELETE</command>. And they
    have different semantics from rules on the other command types in that they modify the
    query tree in place instead of creating a new one.  So
    <command>SELECT</command> rules are described first.
</para>

<para>
    Currently, there can be only one action in an <literal>ON SELECT</> rule, and it must
    be an unconditional <command>SELECT</> action that is <literal>INSTEAD</>. This restriction was
    required to make rules safe enough to open them for ordinary users, and
    it restricts <literal>ON SELECT</> rules to act like views.
</para>

<para>
    The examples for this chapter are two join views that do some
    calculations and some more views using them in turn.  One of the
    two first views is customized later by adding rules for
    <command>INSERT</command>, <command>UPDATE</command>, and
    <command>DELETE</command> operations so that the final result will
    be a view that behaves like a real table with some magic
    functionality.  This is not such a simple example to start from and
    this makes things harder to get into. But it's better to have one
    example that covers all the points discussed step by step rather
    than having many different ones that might mix up in mind.
</para>

<para>
For the example, we need a little <literal>min</literal> function that
returns the lower of 2 integer values. We create that as:

<programlisting>
CREATE FUNCTION min(integer, integer) RETURNS integer AS $$
    SELECT CASE WHEN $1 &lt; $2 THEN $1 ELSE $2 END
$$ LANGUAGE SQL STRICT;
</programlisting>
</para>

<para>
    The real tables we need in the first two rule system descriptions
    are these:

<programlisting>
CREATE TABLE shoe_data (
    shoename   text,          -- primary key
    sh_avail   integer,       -- available number of pairs
    slcolor    text,          -- preferred shoelace color
    slminlen   real,          -- minimum shoelace length
    slmaxlen   real,          -- maximum shoelace length
    slunit     text           -- length unit
);

CREATE TABLE shoelace_data (
    sl_name    text,          -- primary key
    sl_avail   integer,       -- available number of pairs
    sl_color   text,          -- shoelace color
    sl_len     real,          -- shoelace length
    sl_unit    text           -- length unit
);

CREATE TABLE unit (
    un_name    text,          -- primary key
    un_fact    real           -- factor to transform to cm
);
</programlisting>

    As you can see, they represent shoe-store data.
</para>

<para>
    The views are created as:

<programlisting>
CREATE VIEW shoe AS
    SELECT sh.shoename,
           sh.sh_avail,
           sh.slcolor,
           sh.slminlen,
           sh.slminlen * un.un_fact AS slminlen_cm,
           sh.slmaxlen,
           sh.slmaxlen * un.un_fact AS slmaxlen_cm,
           sh.slunit
      FROM shoe_data sh, unit un
     WHERE sh.slunit = un.un_name;

CREATE VIEW shoelace AS
    SELECT s.sl_name,
           s.sl_avail,
           s.sl_color,
           s.sl_len,
           s.sl_unit,
           s.sl_len * u.un_fact AS sl_len_cm
      FROM shoelace_data s, unit u
     WHERE s.sl_unit = u.un_name;

CREATE VIEW shoe_ready AS
    SELECT rsh.shoename,
           rsh.sh_avail,
           rsl.sl_name,
           rsl.sl_avail,
           min(rsh.sh_avail, rsl.sl_avail) AS total_avail
      FROM shoe rsh, shoelace rsl
     WHERE rsl.sl_color = rsh.slcolor
       AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
       AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm;
</programlisting>

    The <command>CREATE VIEW</command> command for the
    <literal>shoelace</literal> view (which is the simplest one we
    have) will create a relation <literal>shoelace</> and an entry in
    <structname>pg_rewrite</structname> that tells that there is a
    rewrite rule that must be applied whenever the relation <literal>shoelace</>
    is referenced in a query's range table.  The rule has no rule
    qualification (discussed later, with the non-<command>SELECT</> rules, since
    <command>SELECT</> rules currently cannot have them) and it is <literal>INSTEAD</>. Note
    that rule qualifications are not the same as query qualifications.
    The action of our rule has a query qualification.
    The action of the rule is one query tree that is a copy of the
    <command>SELECT</command> statement in the view creation command.
</para>
    
    <note>
    <para>
    The two extra range
    table entries for <literal>NEW</> and <literal>OLD</> that you can see in
    the <structname>pg_rewrite</structname> entry aren't of interest
    for <command>SELECT</command> rules.
    </para>
    </note>

<para>
    Now we populate <literal>unit</literal>, <literal>shoe_data</literal>
    and <literal>shoelace_data</literal> and run a simple query on a view:

<programlisting>
INSERT INTO unit VALUES ('cm', 1.0);
INSERT INTO unit VALUES ('m', 100.0);
INSERT INTO unit VALUES ('inch', 2.54);

INSERT INTO shoe_data VALUES ('sh1', 2, 'black', 70.0, 90.0, 'cm');
INSERT INTO shoe_data VALUES ('sh2', 0, 'black', 30.0, 40.0, 'inch');
INSERT INTO shoe_data VALUES ('sh3', 4, 'brown', 50.0, 65.0, 'cm');
INSERT INTO shoe_data VALUES ('sh4', 3, 'brown', 40.0, 50.0, 'inch');

INSERT INTO shoelace_data VALUES ('sl1', 5, 'black', 80.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl2', 6, 'black', 100.0, 'cm');
INSERT INTO shoelace_data VALUES ('sl3', 0, 'black', 35.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl4', 8, 'black', 40.0 , 'inch');
INSERT INTO shoelace_data VALUES ('sl5', 4, 'brown', 1.0 , 'm');
INSERT INTO shoelace_data VALUES ('sl6', 0, 'brown', 0.9 , 'm');
INSERT INTO shoelace_data VALUES ('sl7', 7, 'brown', 60 , 'cm');
INSERT INTO shoelace_data VALUES ('sl8', 1, 'brown', 40 , 'inch');

SELECT * FROM shoelace;

 sl_name   | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
-----------+----------+----------+--------+---------+-----------
 sl1       |        5 | black    |     80 | cm      |        80
 sl2       |        6 | black    |    100 | cm      |       100
 sl7       |        7 | brown    |     60 | cm      |        60
 sl3       |        0 | black    |     35 | inch    |      88.9
 sl4       |        8 | black    |     40 | inch    |     101.6
 sl8       |        1 | brown    |     40 | inch    |     101.6
 sl5       |        4 | brown    |      1 | m       |       100
 sl6       |        0 | brown    |    0.9 | m       |        90
(8 rows)
</programlisting>
   </para>

   <para>
    This is the simplest <command>SELECT</command> you can do on our
    views, so we take this opportunity to explain the basics of view
    rules.  The <literal>SELECT * FROM shoelace</literal> was
    interpreted by the parser and produced the query tree:

<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
       shoelace.sl_color, shoelace.sl_len,
       shoelace.sl_unit, shoelace.sl_len_cm
  FROM shoelace shoelace;
</programlisting>

    and this is given to the rule system. The rule system walks through the
    range table and checks if there are rules
    for any relation. When processing the range table entry for
    <literal>shoelace</literal> (the only one up to now) it finds the
    <literal>_RETURN</literal> rule with the query tree:

<programlisting>
SELECT s.sl_name, s.sl_avail,
       s.sl_color, s.sl_len, s.sl_unit,
       s.sl_len * u.un_fact AS sl_len_cm
  FROM shoelace old, shoelace new,
       shoelace_data s, unit u
 WHERE s.sl_unit = u.un_name;
</programlisting>
</para>

<para>
    To expand the view, the rewriter simply creates a subquery range-table
    entry containing the rule's action query tree, and substitutes this
    range table entry for the original one that referenced the view.  The 
    resulting rewritten query tree is almost the same as if you had typed:

<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
       shoelace.sl_color, shoelace.sl_len,
       shoelace.sl_unit, shoelace.sl_len_cm
  FROM (SELECT s.sl_name,
               s.sl_avail,
               s.sl_color,
               s.sl_len,
               s.sl_unit,
               s.sl_len * u.un_fact AS sl_len_cm
          FROM shoelace_data s, unit u
         WHERE s.sl_unit = u.un_name) shoelace;
</programlisting>

     There is one difference however: the subquery's range table has two
     extra entries <literal>shoelace old</> and <literal>shoelace new</>.  These entries don't
     participate directly in the query, since they aren't referenced by
     the subquery's join tree or target list.  The rewriter uses them
     to store the access privilege check information that was originally present
     in the range-table entry that referenced the view.  In this way, the
     executor will still check that the user has proper privileges to access
     the view, even though there's no direct use of the view in the rewritten
     query.
</para>

<para>
    That was the first rule applied.  The rule system will continue checking
    the remaining range-table entries in the top query (in this example there
    are no more), and it will recursively check the range-table entries in
    the added subquery to see if any of them reference views.  (But it
    won't expand <literal>old</> or <literal>new</> &mdash; otherwise we'd have infinite recursion!)
    In this example, there are no rewrite rules for <literal>shoelace_data</> or <literal>unit</>,
    so rewriting is complete and the above is the final result given to
    the planner.
</para>

<para>
    Now we want to write a query that finds out for which shoes currently in the store
    we have the matching shoelaces (color and length) and where the
    total number of exactly matching pairs is greater or equal to two.

<programlisting>
SELECT * FROM shoe_ready WHERE total_avail &gt;= 2;

 shoename | sh_avail | sl_name | sl_avail | total_avail
----------+----------+---------+----------+-------------
 sh1      |        2 | sl1     |        5 |           2
 sh3      |        4 | sl7     |        7 |           4
(2 rows)
</programlisting>
</para>

<para>
    The output of the parser this time is the query tree:

<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
       shoe_ready.sl_name, shoe_ready.sl_avail,
       shoe_ready.total_avail
  FROM shoe_ready shoe_ready
 WHERE shoe_ready.total_avail &gt;= 2;
</programlisting>

    The first rule applied will be the one for the 
    <literal>shoe_ready</literal> view and it results in the
    query tree:

<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
       shoe_ready.sl_name, shoe_ready.sl_avail,
       shoe_ready.total_avail
  FROM (SELECT rsh.shoename,
               rsh.sh_avail,
               rsl.sl_name,
               rsl.sl_avail,
               min(rsh.sh_avail, rsl.sl_avail) AS total_avail
          FROM shoe rsh, shoelace rsl
         WHERE rsl.sl_color = rsh.slcolor
           AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
           AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail &gt;= 2;
</programlisting>

    Similarly, the rules for <literal>shoe</literal> and
    <literal>shoelace</literal> are substituted into the range table of
    the subquery, leading to a three-level final query tree:

<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
       shoe_ready.sl_name, shoe_ready.sl_avail,
       shoe_ready.total_avail
  FROM (SELECT rsh.shoename,
               rsh.sh_avail,
               rsl.sl_name,
               rsl.sl_avail,
               min(rsh.sh_avail, rsl.sl_avail) AS total_avail
          FROM (SELECT sh.shoename,
                       sh.sh_avail,
                       sh.slcolor,
                       sh.slminlen,
                       sh.slminlen * un.un_fact AS slminlen_cm,
                       sh.slmaxlen,
                       sh.slmaxlen * un.un_fact AS slmaxlen_cm,
                       sh.slunit
                  FROM shoe_data sh, unit un
                 WHERE sh.slunit = un.un_name) rsh,
               (SELECT s.sl_name,
                       s.sl_avail,
                       s.sl_color,
                       s.sl_len,
                       s.sl_unit,
                       s.sl_len * u.un_fact AS sl_len_cm
                  FROM shoelace_data s, unit u
                 WHERE s.sl_unit = u.un_name) rsl
         WHERE rsl.sl_color = rsh.slcolor
           AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
           AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail &gt; 2;
</programlisting>
   </para>

   <para>
    It turns out that the planner will collapse this tree into a
    two-level query tree: the bottommost <command>SELECT</command>
    commands will be <quote>pulled up</quote> into the middle
    <command>SELECT</command> since there's no need to process them
    separately.  But the middle <command>SELECT</command> will remain
    separate from the top, because it contains aggregate functions.
    If we pulled those up it would change the behavior of the topmost
    <command>SELECT</command>, which we don't want.  However,
    collapsing the query tree is an optimization that the rewrite
    system doesn't have to concern itself with.
   </para>
</sect2>

<sect2>
<title>View Rules in Non-<command>SELECT</command> Statements</title>

<para>
    Two details of the query tree aren't touched in the description of
    view rules above. These are the command type and the result relation.
    In fact, view rules don't need this information.
</para>

<para>
    There are only a few differences between a query tree for a
    <command>SELECT</command> and one for any other
    command. Obviously, they have a different command type and for a
    command other than a <command>SELECT</command>, the result
    relation points to the range-table entry where the result should
    go.  Everything else is absolutely the same.  So having two tables
    <literal>t1</> and <literal>t2</> with columns <literal>a</> and
    <literal>b</>, the query trees for the two statements:

<programlisting>
SELECT t2.b FROM t1, t2 WHERE t1.a = t2.a;

UPDATE t1 SET b = t2.b FROM t2 WHERE t1.a = t2.a;
</programlisting>

    are nearly identical.  In particular:

    <itemizedlist>
        <listitem>
        <para>
            The range tables contain entries for the tables <literal>t1</> and <literal>t2</>.
        </para>
        </listitem>

        <listitem>
        <para>
            The target lists contain one variable that points to column
            <literal>b</> of the range table entry for table <literal>t2</>.
        </para>
        </listitem>

        <listitem>
        <para>
            The qualification expressions compare the columns <literal>a</> of both
            range-table entries for equality.
        </para>
        </listitem>

        <listitem>
        <para>
            The join trees show a simple join between <literal>t1</> and <literal>t2</>.
        </para>
        </listitem>
    </itemizedlist>
   </para>

   <para>
    The consequence is, that both query trees result in similar
    execution plans: They are both joins over the two tables. For the
    <command>UPDATE</command> the missing columns from <literal>t1</> are added to
    the target list by the planner and the final query tree will read
    as:

<programlisting>
UPDATE t1 SET a = t1.a, b = t2.b FROM t2 WHERE t1.a = t2.a;
</programlisting>

    and thus the executor run over the join will produce exactly the
    same result set as a:

<programlisting>
SELECT t1.a, t2.b FROM t1, t2 WHERE t1.a = t2.a;
</programlisting>
    
    will do. But there is a little problem in
    <command>UPDATE</command>: The executor does not care what the
    results from the join it is doing are meant for. It just produces
    a result set of rows. The difference that one is a
    <command>SELECT</command> command and the other is an
    <command>UPDATE</command> is handled in the caller of the
    executor. The caller still knows (looking at the query tree) that
    this is an <command>UPDATE</command>, and it knows that this
    result should go into table <literal>t1</>. But which of the rows that are
    there has to be replaced by the new row?
</para>

<para>
    To resolve this problem, another entry is added to the target list
    in <command>UPDATE</command> (and also in
    <command>DELETE</command>) statements: the current tuple ID
    (<acronym>CTID</>).<indexterm><primary>CTID</></>
    This is a system column containing the
    file block number and position in the block for the row. Knowing
    the table, the <acronym>CTID</> can be used to retrieve the
    original row of <literal>t1</> to be updated.  After adding the
    <acronym>CTID</> to the target list, the query actually looks like:

<programlisting>
SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;
</programlisting>
    
    Now another detail of <productname>PostgreSQL</productname> enters
    the stage. Old table rows aren't overwritten, and this
    is why <command>ROLLBACK</command> is fast. In an <command>UPDATE</command>,
    the new result row is inserted into the table (after stripping the
    <acronym>CTID</>) and in the row header of the old row, which the
    <acronym>CTID</> pointed to, the <literal>cmax</> and
    <literal>xmax</> entries are set to the current command counter
    and current transaction ID. Thus the old row is hidden, and after
    the transaction commits the vacuum cleaner can really remove it.
</para>

<para>
    Knowing all that, we can simply apply view rules in absolutely
    the same way to any command. There is no difference.
</para>
</sect2>

<sect2>
<title>The Power of Views in <productname>PostgreSQL</productname></title>

<para>
    The above demonstrates how the rule system incorporates view
    definitions into the original query tree. In the second example, a
    simple <command>SELECT</command> from one view created a final
    query tree that is a join of 4 tables (<literal>unit</> was used twice with
    different names).
</para>

<para>
    The benefit of implementing views with the rule system is,
    that the planner has all
    the information about which tables have to be scanned plus the
    relationships between these tables plus the restrictive
    qualifications from the views plus the qualifications from
    the original query
    in one single query tree. And this is still the situation
    when the original query is already a join over views.
    The planner has to decide which is
    the best path to execute the query, and the more information
    the planner has, the better this decision can be. And
    the rule system as implemented in <productname>PostgreSQL</productname>
    ensures, that this is all information available about the query
    up to that point.
</para>
</sect2>

<sect2 id="rules-views-update">
<title>Updating a View</title>

<para>
    What happens if a view is named as the target relation for an
    <command>INSERT</command>, <command>UPDATE</command>, or
    <command>DELETE</command>?  After doing the substitutions
    described above, we will have a query tree in which the result
    relation points at a subquery range-table entry.  This will not
    work, so the rewriter throws an error if it sees it has produced
    such a thing.
</para>

<para>
    To change this, we can define rules that modify the behavior of
    these kinds of commands. This is the topic of the next section.
</para>
</sect2>

</sect1>

<sect1 id="rules-update">
<title>Rules on <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</></title>

<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="INSERT">for INSERT</secondary>
</indexterm>

<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="UPDATE">for UPDATE</secondary>
</indexterm>

<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="DELETE">for DELETE</secondary>
</indexterm>

<para>
    Rules that are defined on <command>INSERT</>, <command>UPDATE</>,
    and <command>DELETE</> are significantly different from the view rules
    described in the previous section. First, their <command>CREATE
    RULE</command> command allows more:

    <itemizedlist>
        <listitem>
        <para>
            They are allowed to have no action.
        </para>
        </listitem>

        <listitem>
        <para>
            They can have multiple actions.
        </para>
        </listitem>

        <listitem>
        <para>
            They can be <literal>INSTEAD</> or <literal>ALSO</> (the default).
        </para>
        </listitem>

        <listitem>
        <para>
            The pseudorelations <literal>NEW</> and <literal>OLD</> become useful.
        </para>
        </listitem>

        <listitem>
        <para>
            They can have rule qualifications.
        </para>
        </listitem>
    </itemizedlist>

    Second, they don't modify the query tree in place. Instead they
    create zero or more new query trees and can throw away the
    original one.
</para>

<sect2>
<title>How Update Rules Work</title>

<para>
    Keep the syntax:

<programlisting>
CREATE [ OR REPLACE ] RULE <replaceable class="parameter">name</replaceable> AS ON <replaceable class="parameter">event</replaceable>
    TO <replaceable class="parameter">table</replaceable> [ WHERE <replaceable class="parameter">condition</replaceable> ]
    DO [ ALSO | INSTEAD ] { NOTHING | <replaceable class="parameter">command</replaceable> | ( <replaceable class="parameter">command</replaceable> ; <replaceable class="parameter">command</replaceable> ... ) }
</programlisting>

    in mind.
    In the following, <firstterm>update rules</> means rules that are defined
    on <command>INSERT</>, <command>UPDATE</>, or <command>DELETE</>.
</para>

<para>
    Update rules get applied by the rule system when the result
    relation and the command type of a query tree are equal to the
    object and event given in the <command>CREATE RULE</command> command.
    For update rules, the rule system creates a list of query trees.
    Initially the query-tree list is empty.
    There can be zero (<literal>NOTHING</> key word), one, or multiple actions.
    To simplify, we will look at a rule with one action. This rule
    can have a qualification or not and it can be <literal>INSTEAD</> or
    <literal>ALSO</> (the default).
</para>

<para>
    What is a rule qualification? It is a restriction that tells
    when the actions of the rule should be done and when not. This
    qualification can only reference the pseudorelations <literal>NEW</> and/or <literal>OLD</>,
    which basically represent the relation that was given as object (but with a
    special meaning).
</para>

   <para>
    So we have three cases that produce the following query trees for
    a one-action rule.

    <variablelist>
     <varlistentry>
      <term>No qualification, with either <literal>ALSO</> or
      <literal>INSTEAD</></term>
      <listitem>
       <para>
        the query tree from the rule action with the original query
        tree's qualification added
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>Qualification given and <literal>ALSO</></term>
      <listitem>
       <para>
        the query tree from the rule action with the rule
        qualification and the original query tree's qualification
        added
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>Qualification given and <literal>INSTEAD</></term>
      <listitem>
       <para>
        the query tree from the rule action with the rule
        qualification and the original query tree's qualification; and
        the original query tree with the negated rule qualification
        added
       </para>
      </listitem>
     </varlistentry>
    </variablelist>

    Finally, if the rule is <literal>ALSO</>, the unchanged original query tree is
    added to the list. Since only qualified <literal>INSTEAD</> rules already add the
    original query tree, we end up with either one or two output query trees
    for a rule with one action.
</para>

<para>
    For <literal>ON INSERT</> rules, the original query (if not suppressed by <literal>INSTEAD</>)
    is done before any actions added by rules.  This allows the actions to
    see the inserted row(s).  But for <literal>ON UPDATE</> and <literal>ON
    DELETE</> rules, the original query is done after the actions added by rules.
    This ensures that the actions can see the to-be-updated or to-be-deleted
    rows; otherwise, the actions might do nothing because they find no rows
    matching their qualifications.
</para>

<para>
    The query trees generated from rule actions are thrown into the
    rewrite system again, and maybe more rules get applied resulting
    in more or less query trees.
    So a rule's actions must have either a different
    command type or a different result relation than the rule itself is
    on, otherwise this recursive process will end up in an infinite loop.
    (Recursive expansion of a rule will be detected and reported as an
    error.)
</para>

<para>
    The query trees found in the actions of the
    <structname>pg_rewrite</structname> system catalog are only
    templates. Since they can reference the range-table entries for
    <literal>NEW</> and <literal>OLD</>, some substitutions have to be made before they can be
    used. For any reference to <literal>NEW</>, the target list of the original
    query is searched for a corresponding entry. If found, that
    entry's expression replaces the reference. Otherwise, <literal>NEW</> means the
    same as <literal>OLD</> (for an <command>UPDATE</command>) or is replaced by
    a null value (for an <command>INSERT</command>). Any reference to <literal>OLD</> is
    replaced by a reference to the range-table entry that is the
    result relation.
</para>

<para>
    After the system is done applying update rules, it applies view rules to the
    produced query tree(s).  Views cannot insert new update actions so
    there is no need to apply update rules to the output of view rewriting.
</para>

<sect3>
<title>A First Rule Step by Step</title>

<para>
    Say we want to trace changes to the <literal>sl_avail</> column in the
    <literal>shoelace_data</literal> relation. So we set up a log table
    and a rule that conditionally writes a log entry when an
    <command>UPDATE</command> is performed on
    <literal>shoelace_data</literal>.

<programlisting>
CREATE TABLE shoelace_log (
    sl_name    text,          -- shoelace changed
    sl_avail   integer,       -- new available value
    log_who    text,          -- who did it
    log_when   timestamp      -- when
);

CREATE RULE log_shoelace AS ON UPDATE TO shoelace_data
    WHERE NEW.sl_avail &lt;&gt; OLD.sl_avail
    DO INSERT INTO shoelace_log VALUES (
                                    NEW.sl_name,
                                    NEW.sl_avail,
                                    current_user,
                                    current_timestamp
                                );
</programlisting>
</para>

<para>
    Now someone does:

<programlisting>
UPDATE shoelace_data SET sl_avail = 6 WHERE sl_name = 'sl7';
</programlisting>

    and we look at the log table:

<programlisting>
SELECT * FROM shoelace_log;

 sl_name | sl_avail | log_who | log_when                        
---------+----------+---------+----------------------------------
 sl7     |        6 | Al      | Tue Oct 20 16:14:45 1998 MET DST
(1 row)
</programlisting>
   </para>

   <para>
    That's what we expected. What happened in the background is the following.
    The parser created the query tree:

<programlisting>
UPDATE shoelace_data SET sl_avail = 6
  FROM shoelace_data shoelace_data
 WHERE shoelace_data.sl_name = 'sl7';
</programlisting>

    There is a rule <literal>log_shoelace</literal> that is <literal>ON UPDATE</> with the rule
    qualification expression:

<programlisting>
NEW.sl_avail &lt;&gt; OLD.sl_avail
</programlisting>

    and the action:

<programlisting>
INSERT INTO shoelace_log VALUES (
       new.sl_name, new.sl_avail,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old;
</programlisting>

    (This looks a little strange since you cannot normally write
    <literal>INSERT ... VALUES ... FROM</>.  The <literal>FROM</>
    clause here is just to indicate that there are range-table entries
    in the query tree for <literal>new</> and <literal>old</>.
    These are needed so that they can be referenced by variables in
    the <command>INSERT</command> command's query tree.)
</para>

<para>
    The rule is a qualified <literal>ALSO</> rule, so the rule system
    has to return two query trees: the modified rule action and the original
    query tree. In step 1, the range table of the original query is
    incorporated into the rule's action query tree. This results in:

<programlisting>
INSERT INTO shoelace_log VALUES (
       new.sl_name, new.sl_avail,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old,
       <emphasis>shoelace_data shoelace_data</emphasis>;
</programlisting>

    In step 2, the rule qualification is added to it, so the result set
    is restricted to rows where <literal>sl_avail</> changes:

<programlisting>
INSERT INTO shoelace_log VALUES (
       new.sl_name, new.sl_avail,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old,
       shoelace_data shoelace_data
 <emphasis>WHERE new.sl_avail &lt;&gt; old.sl_avail</emphasis>;
</programlisting>

    (This looks even stranger, since <literal>INSERT ... VALUES</> doesn't have
    a <literal>WHERE</> clause either, but the planner and executor will have no
    difficulty with it.  They need to support this same functionality
    anyway for <literal>INSERT ... SELECT</>.)
   </para>

   <para>
    In step 3, the original query tree's qualification is added,
    restricting the result set further to only the rows that would have been touched
    by the original query:

<programlisting>
INSERT INTO shoelace_log VALUES (
       new.sl_name, new.sl_avail,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old,
       shoelace_data shoelace_data
 WHERE new.sl_avail &lt;&gt; old.sl_avail
   <emphasis>AND shoelace_data.sl_name = 'sl7'</emphasis>;
</programlisting>
   </para>

   <para>
    Step 4 replaces references to <literal>NEW</> by the target list entries from the
    original query tree or by the matching variable references
    from the result relation:

<programlisting>
INSERT INTO shoelace_log VALUES (
       <emphasis>shoelace_data.sl_name</emphasis>, <emphasis>6</emphasis>,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old,
       shoelace_data shoelace_data
 WHERE <emphasis>6</emphasis> &lt;&gt; old.sl_avail
   AND shoelace_data.sl_name = 'sl7';
</programlisting>

   </para>

   <para>
    Step 5 changes <literal>OLD</> references into result relation references:

<programlisting>
INSERT INTO shoelace_log VALUES (
       shoelace_data.sl_name, 6,
       current_user, current_timestamp )
  FROM shoelace_data new, shoelace_data old,
       shoelace_data shoelace_data
 WHERE 6 &lt;&gt; <emphasis>shoelace_data.sl_avail</emphasis>
   AND shoelace_data.sl_name = 'sl7';
</programlisting>
   </para>

   <para>
    That's it.  Since the rule is <literal>ALSO</>, we also output the
    original query tree.  In short, the output from the rule system
    is a list of two query trees that correspond to these statements:

<programlisting>
INSERT INTO shoelace_log VALUES (
       shoelace_data.sl_name, 6,
       current_user, current_timestamp )
  FROM shoelace_data
 WHERE 6 &lt;&gt; shoelace_data.sl_avail
   AND shoelace_data.sl_name = 'sl7';

UPDATE shoelace_data SET sl_avail = 6
 WHERE sl_name = 'sl7';
</programlisting>

    These are executed in this order, and that is exactly what
    the rule was meant to do.
   </para>

   <para>
    The substitutions and the added qualifications
    ensure that, if the original query would be, say:

<programlisting>
UPDATE shoelace_data SET sl_color = 'green'
 WHERE sl_name = 'sl7';
</programlisting>

    no log entry would get written.  In that case, the original query
    tree does not contain a target list entry for
    <literal>sl_avail</>, so <literal>NEW.sl_avail</> will get
    replaced by <literal>shoelace_data.sl_avail</>.  Thus, the extra
    command generated by the rule is:

<programlisting>
INSERT INTO shoelace_log VALUES (
       shoelace_data.sl_name, <emphasis>shoelace_data.sl_avail</emphasis>,
       current_user, current_timestamp )
  FROM shoelace_data
 WHERE <emphasis>shoelace_data.sl_avail</emphasis> &lt;&gt; shoelace_data.sl_avail
   AND shoelace_data.sl_name = 'sl7';
</programlisting>

    and that qualification will never be true.
   </para>

   <para>
    It will also work if the original query modifies multiple rows. So
    if someone issued the command:

<programlisting>
UPDATE shoelace_data SET sl_avail = 0
 WHERE sl_color = 'black';
</programlisting>

    four rows in fact get updated (<literal>sl1</>, <literal>sl2</>, <literal>sl3</>, and <literal>sl4</>).
    But <literal>sl3</> already has <literal>sl_avail = 0</>.   In this case, the original
    query trees qualification is different and that results
    in the extra query tree:

<programlisting>
INSERT INTO shoelace_log
SELECT shoelace_data.sl_name, 0,
       current_user, current_timestamp
  FROM shoelace_data
 WHERE 0 &lt;&gt; shoelace_data.sl_avail
   AND <emphasis>shoelace_data.sl_color = 'black'</emphasis>;
</programlisting>

    being generated by the rule.  This query tree will surely insert
    three new log entries. And that's absolutely correct.
</para>

<para>
    Here we can see why it is important that the original query tree
    is executed last.  If the <command>UPDATE</command> had been
    executed first, all the rows would have already been set to zero, so the
    logging <command>INSERT</command> would not find any row where
    <literal>0 &lt;&gt; shoelace_data.sl_avail</literal>.
</para>
</sect3>

</sect2>

<sect2 id="rules-update-views">
<title>Cooperation with Views</title>

<indexterm zone="rules-update-views"><primary>view</><secondary>updating</></>

<para>
    A simple way to protect view relations from the mentioned
    possibility that someone can try to run <command>INSERT</command>,
    <command>UPDATE</command>, or <command>DELETE</command> on them is
    to let those query trees get thrown away.  So we could create the rules:

<programlisting>
CREATE RULE shoe_ins_protect AS ON INSERT TO shoe
    DO INSTEAD NOTHING;
CREATE RULE shoe_upd_protect AS ON UPDATE TO shoe
    DO INSTEAD NOTHING;
CREATE RULE shoe_del_protect AS ON DELETE TO shoe
    DO INSTEAD NOTHING;
</programlisting>

    If someone now tries to do any of these operations on the view
    relation <literal>shoe</literal>, the rule system will
    apply these rules. Since the rules have
    no actions and are <literal>INSTEAD</>, the resulting list of
    query trees will be empty and the whole query will become
    nothing because there is nothing left to be optimized or
    executed after the rule system is done with it.
</para>

<para>
    A more sophisticated way to use the rule system is to
    create rules that rewrite the query tree into one that
    does the right operation on the real tables. To do that
    on the <literal>shoelace</literal> view, we create
    the following rules:

<programlisting>
CREATE RULE shoelace_ins AS ON INSERT TO shoelace
    DO INSTEAD
    INSERT INTO shoelace_data VALUES (
           NEW.sl_name,
           NEW.sl_avail,
           NEW.sl_color,
           NEW.sl_len,
           NEW.sl_unit
    );

CREATE RULE shoelace_upd AS ON UPDATE TO shoelace
    DO INSTEAD
    UPDATE shoelace_data
       SET sl_name = NEW.sl_name,
           sl_avail = NEW.sl_avail,
           sl_color = NEW.sl_color,
           sl_len = NEW.sl_len,
           sl_unit = NEW.sl_unit
     WHERE sl_name = OLD.sl_name;

CREATE RULE shoelace_del AS ON DELETE TO shoelace
    DO INSTEAD
    DELETE FROM shoelace_data
     WHERE sl_name = OLD.sl_name;
</programlisting>
   </para>

   <para>
    If you want to support <literal>RETURNING</> queries on the view,
    you need to make the rules include <literal>RETURNING</> clauses that
    compute the view rows.  This is usually pretty trivial for views on a
    single table, but it's a bit tedious for join views such as
    <literal>shoelace</literal>.  An example for the insert case is:

<programlisting>
CREATE RULE shoelace_ins AS ON INSERT TO shoelace
    DO INSTEAD
    INSERT INTO shoelace_data VALUES (
           NEW.sl_name,
           NEW.sl_avail,
           NEW.sl_color,
           NEW.sl_len,
           NEW.sl_unit
    )
    RETURNING
           shoelace_data.*,
           (SELECT shoelace_data.sl_len * u.un_fact
            FROM unit u WHERE shoelace_data.sl_unit = u.un_name);
</programlisting>

    Note that this one rule supports both <command>INSERT</> and
    <command>INSERT RETURNING</> queries on the view &mdash; the
    <literal>RETURNING</> clause is simply ignored for <command>INSERT</>.
   </para>

   <para>
    Now assume that once in a while, a pack of shoelaces arrives at
    the shop and a big parts list along with it.  But you don't want
    to manually update the <literal>shoelace</literal> view every
    time.  Instead we setup two little tables: one where you can
    insert the items from the part list, and one with a special
    trick. The creation commands for these are:

<programlisting>
CREATE TABLE shoelace_arrive (
    arr_name    text,
    arr_quant   integer
);

CREATE TABLE shoelace_ok (
    ok_name     text,
    ok_quant    integer
);

CREATE RULE shoelace_ok_ins AS ON INSERT TO shoelace_ok
    DO INSTEAD
    UPDATE shoelace
       SET sl_avail = sl_avail + NEW.ok_quant
     WHERE sl_name = NEW.ok_name;
</programlisting>

    Now you can fill the table <literal>shoelace_arrive</literal> with
    the data from the parts list:

<programlisting>
SELECT * FROM shoelace_arrive;

 arr_name | arr_quant
----------+-----------
 sl3      |        10
 sl6      |        20
 sl8      |        20
(3 rows)
</programlisting>

    Take a quick look at the current data:
    
<programlisting>
SELECT * FROM shoelace;

 sl_name  | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
----------+----------+----------+--------+---------+-----------
 sl1      |        5 | black    |     80 | cm      |        80
 sl2      |        6 | black    |    100 | cm      |       100
 sl7      |        6 | brown    |     60 | cm      |        60
 sl3      |        0 | black    |     35 | inch    |      88.9
 sl4      |        8 | black    |     40 | inch    |     101.6
 sl8      |        1 | brown    |     40 | inch    |     101.6
 sl5      |        4 | brown    |      1 | m       |       100
 sl6      |        0 | brown    |    0.9 | m       |        90
(8 rows)
</programlisting>

    Now move the arrived shoelaces in:

<programlisting>
INSERT INTO shoelace_ok SELECT * FROM shoelace_arrive;
</programlisting>

    and check the results:

<programlisting>
SELECT * FROM shoelace ORDER BY sl_name;

 sl_name  | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
----------+----------+----------+--------+---------+-----------
 sl1      |        5 | black    |     80 | cm      |        80
 sl2      |        6 | black    |    100 | cm      |       100
 sl7      |        6 | brown    |     60 | cm      |        60
 sl4      |        8 | black    |     40 | inch    |     101.6
 sl3      |       10 | black    |     35 | inch    |      88.9
 sl8      |       21 | brown    |     40 | inch    |     101.6
 sl5      |        4 | brown    |      1 | m       |       100
 sl6      |       20 | brown    |    0.9 | m       |        90
(8 rows)

SELECT * FROM shoelace_log;

 sl_name | sl_avail | log_who| log_when                        
---------+----------+--------+----------------------------------
 sl7     |        6 | Al     | Tue Oct 20 19:14:45 1998 MET DST
 sl3     |       10 | Al     | Tue Oct 20 19:25:16 1998 MET DST
 sl6     |       20 | Al     | Tue Oct 20 19:25:16 1998 MET DST
 sl8     |       21 | Al     | Tue Oct 20 19:25:16 1998 MET DST
(4 rows)
</programlisting>
   </para>

   <para>
    It's a long way from the one <literal>INSERT ... SELECT</literal>
    to these results. And the description of the query-tree
    transformation will be the last in this chapter.  First, there is
    the parser's output:

<programlisting>
INSERT INTO shoelace_ok
SELECT shoelace_arrive.arr_name, shoelace_arrive.arr_quant
  FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok;
</programlisting>

    Now the first rule <literal>shoelace_ok_ins</literal> is applied and turns this
    into:

<programlisting>
UPDATE shoelace
   SET sl_avail = shoelace.sl_avail + shoelace_arrive.arr_quant
  FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
       shoelace_ok old, shoelace_ok new,
       shoelace shoelace
 WHERE shoelace.sl_name = shoelace_arrive.arr_name;
</programlisting>

    and throws away the original <command>INSERT</command> on
    <literal>shoelace_ok</literal>.  This rewritten query is passed to
    the rule system again, and the second applied rule
    <literal>shoelace_upd</literal> produces:

<programlisting>
UPDATE shoelace_data
   SET sl_name = shoelace.sl_name,
       sl_avail = shoelace.sl_avail + shoelace_arrive.arr_quant,
       sl_color = shoelace.sl_color,
       sl_len = shoelace.sl_len,
       sl_unit = shoelace.sl_unit
  FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
       shoelace_ok old, shoelace_ok new,
       shoelace shoelace, shoelace old,
       shoelace new, shoelace_data shoelace_data
 WHERE shoelace.sl_name = shoelace_arrive.arr_name
   AND shoelace_data.sl_name = shoelace.sl_name;
</programlisting>

    Again it's an <literal>INSTEAD</> rule and the previous query tree is trashed.
    Note that this query still uses the view <literal>shoelace</literal>.
    But the rule system isn't finished with this step, so it continues
    and applies the <literal>_RETURN</literal> rule on it, and we get:

<programlisting>
UPDATE shoelace_data
   SET sl_name = s.sl_name,
       sl_avail = s.sl_avail + shoelace_arrive.arr_quant,
       sl_color = s.sl_color,
       sl_len = s.sl_len,
       sl_unit = s.sl_unit
  FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
       shoelace_ok old, shoelace_ok new,
       shoelace shoelace, shoelace old,
       shoelace new, shoelace_data shoelace_data,
       shoelace old, shoelace new,
       shoelace_data s, unit u
 WHERE s.sl_name = shoelace_arrive.arr_name
   AND shoelace_data.sl_name = s.sl_name;
</programlisting>

    Finally, the rule <literal>log_shoelace</literal> gets applied,
    producing the extra query tree:

<programlisting>
INSERT INTO shoelace_log
SELECT s.sl_name,
       s.sl_avail + shoelace_arrive.arr_quant,
       current_user,
       current_timestamp
  FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
       shoelace_ok old, shoelace_ok new,
       shoelace shoelace, shoelace old,
       shoelace new, shoelace_data shoelace_data,
       shoelace old, shoelace new,
       shoelace_data s, unit u,
       shoelace_data old, shoelace_data new
       shoelace_log shoelace_log
 WHERE s.sl_name = shoelace_arrive.arr_name
   AND shoelace_data.sl_name = s.sl_name
   AND (s.sl_avail + shoelace_arrive.arr_quant) &lt;&gt; s.sl_avail;
</programlisting>
    
    After that the rule system runs out of rules and returns the 
    generated query trees.
   </para>

   <para>
    So we end up with two final query trees that are equivalent to the
    <acronym>SQL</acronym> statements:

<programlisting>
INSERT INTO shoelace_log
SELECT s.sl_name,
       s.sl_avail + shoelace_arrive.arr_quant,
       current_user,
       current_timestamp
  FROM shoelace_arrive shoelace_arrive, shoelace_data shoelace_data,
       shoelace_data s
 WHERE s.sl_name = shoelace_arrive.arr_name
   AND shoelace_data.sl_name = s.sl_name
   AND s.sl_avail + shoelace_arrive.arr_quant &lt;&gt; s.sl_avail;
           
UPDATE shoelace_data
   SET sl_avail = shoelace_data.sl_avail + shoelace_arrive.arr_quant
  FROM shoelace_arrive shoelace_arrive,
       shoelace_data shoelace_data,
       shoelace_data s
 WHERE s.sl_name = shoelace_arrive.sl_name
   AND shoelace_data.sl_name = s.sl_name;
</programlisting>

    The result is that data coming from one relation inserted into another,
    changed into updates on a third, changed into updating
    a fourth plus logging that final update in a fifth
    gets reduced into two queries.
</para>

<para>
    There is a little detail that's a bit ugly. Looking at the two
    queries, it turns out that the <literal>shoelace_data</literal>
    relation appears twice in the range table where it could
    definitely be reduced to one. The planner does not handle it and
    so the execution plan for the rule systems output of the
    <command>INSERT</command> will be

<literallayout class="monospaced">
Nested Loop
  -&gt;  Merge Join
        -&gt;  Seq Scan
              -&gt;  Sort
                    -&gt;  Seq Scan on s
        -&gt;  Seq Scan
              -&gt;  Sort
                    -&gt;  Seq Scan on shoelace_arrive
  -&gt;  Seq Scan on shoelace_data
</literallayout>

    while omitting the extra range table entry would result in a

<literallayout class="monospaced">
Merge Join
  -&gt;  Seq Scan
        -&gt;  Sort
              -&gt;  Seq Scan on s
  -&gt;  Seq Scan
        -&gt;  Sort
              -&gt;  Seq Scan on shoelace_arrive
</literallayout>

    which produces exactly the same entries in the log table.  Thus,
    the rule system caused one extra scan on the table
    <literal>shoelace_data</literal> that is absolutely not
    necessary. And the same redundant scan is done once more in the
    <command>UPDATE</command>. But it was a really hard job to make
    that all possible at all.
</para>

<para>
    Now we make a final demonstration of the
    <productname>PostgreSQL</productname> rule system and its power.
    Say you add some shoelaces with extraordinary colors to your
    database:

<programlisting>
INSERT INTO shoelace VALUES ('sl9', 0, 'pink', 35.0, 'inch', 0.0);
INSERT INTO shoelace VALUES ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0);
</programlisting>

    We would like to make a view to check which
    <literal>shoelace</literal> entries do not fit any shoe in color.
    The view for this is:

<programlisting>
CREATE VIEW shoelace_mismatch AS
    SELECT * FROM shoelace WHERE NOT EXISTS
        (SELECT shoename FROM shoe WHERE slcolor = sl_color);
</programlisting>

    Its output is:

<programlisting>
SELECT * FROM shoelace_mismatch;

 sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
---------+----------+----------+--------+---------+-----------
 sl9     |        0 | pink     |     35 | inch    |      88.9
 sl10    |     1000 | magenta  |     40 | inch    |     101.6
</programlisting>
   </para>

   <para>
    Now we want to set it up so that mismatching shoelaces that are
    not in stock are deleted from the database.
    To make it a little harder for <productname>PostgreSQL</productname>,
    we don't delete it directly. Instead we create one more view:

<programlisting>
CREATE VIEW shoelace_can_delete AS
    SELECT * FROM shoelace_mismatch WHERE sl_avail = 0;
</programlisting>

    and do it this way:

<programlisting>
DELETE FROM shoelace WHERE EXISTS
    (SELECT * FROM shoelace_can_delete
             WHERE sl_name = shoelace.sl_name);
</programlisting>

    <foreignphrase>Voil&agrave;</foreignphrase>:

<programlisting>
SELECT * FROM shoelace;

 sl_name | sl_avail | sl_color | sl_len | sl_unit | sl_len_cm
---------+----------+----------+--------+---------+-----------
 sl1     |        5 | black    |     80 | cm      |        80
 sl2     |        6 | black    |    100 | cm      |       100
 sl7     |        6 | brown    |     60 | cm      |        60
 sl4     |        8 | black    |     40 | inch    |     101.6
 sl3     |       10 | black    |     35 | inch    |      88.9
 sl8     |       21 | brown    |     40 | inch    |     101.6
 sl10    |     1000 | magenta  |     40 | inch    |     101.6
 sl5     |        4 | brown    |      1 | m       |       100
 sl6     |       20 | brown    |    0.9 | m       |        90
(9 rows)
</programlisting>
   </para>

   <para>
    A <command>DELETE</command> on a view, with a subquery qualification that
    in total uses 4 nesting/joined views, where one of them
    itself has a subquery qualification containing a view
    and where calculated view columns are used,
    gets rewritten into 
    one single query tree that deletes the requested data
    from a real table.
</para>

<para>
    There are probably only a few situations out in the real world
    where such a construct is necessary. But it makes you feel
    comfortable that it works.
</para>
</sect2>

</sect1>

<sect1 id="rules-privileges">
<title>Rules and Privileges</title>

<indexterm zone="rules-privileges">
 <primary>privilege</primary>
 <secondary sortas="Regeln">with rules</secondary>
</indexterm>

<indexterm zone="rules-privileges">
 <primary>privilege</primary>
 <secondary sortas="Sichten">with views</secondary>
</indexterm>

<para>
    Due to rewriting of queries by the <productname>PostgreSQL</productname>
    rule system, other tables/views than those used in the original
    query get accessed. When update rules are used, this can include write access
    to tables.
</para>

<para>
    Rewrite rules don't have a separate owner. The owner of
    a relation (table or view) is automatically the owner of the
    rewrite rules that are defined for it.
    The <productname>PostgreSQL</productname> rule system changes the
    behavior of the default access control system. Relations that
    are used due to rules get checked against the
    privileges of the rule owner, not the user invoking the rule.
    This means that a user only needs the required privileges
    for the tables/views that he names explicitly in his queries.
</para>

<para>
    For example: A user has a list of phone numbers where some of
    them are private, the others are of interest for the secretary of the office.
    He can construct the following:

<programlisting>
CREATE TABLE phone_data (person text, phone text, private boolean);
CREATE VIEW phone_number AS
    SELECT person, phone FROM phone_data WHERE NOT private;
GRANT SELECT ON phone_number TO secretary;
</programlisting>
    
    Nobody except him (and the database superusers) can access the
    <literal>phone_data</> table. But because of the <command>GRANT</>,
    the secretary can run a <command>SELECT</command> on the
    <literal>phone_number</> view. The rule system will rewrite the
    <command>SELECT</command> from <literal>phone_number</> into a
    <command>SELECT</command> from <literal>phone_data</> and add the
    qualification that only entries where <literal>private</> is false
    are wanted. Since the user is the owner of
    <literal>phone_number</> and therefore the owner of the rule, the
    read access to <literal>phone_data</> is now checked against his
    privileges and the query is permitted. The check for accessing
    <literal>phone_number</> is also performed, but this is done
    against the invoking user, so nobody but the user and the
    secretary can use it.
</para>

<para>
    The privileges are checked rule by rule. So the secretary is for now the
    only one who can see the public phone numbers. But the secretary can setup
    another view and grant access to that to the public. Then, anyone
    can see the <literal>phone_number</> data through the secretary's view.
    What the secretary cannot do is to create a view that directly
    accesses <literal>phone_data</>.  (Actually he can, but it will not work since
    every access will be denied during the permission checks.)
    And as soon as the user will notice, that the secretary opened
    his <literal>phone_number</> view, he can revoke his access. Immediately, any
    access to the secretary's view would fail.
</para>

<para>
    One might think that this rule-by-rule checking is a security
    hole, but in fact it isn't.   But if it did not work this way, the secretary
    could set up a table with the same columns as <literal>phone_number</> and
    copy the data to there once per day. Then it's his own data and
    he can grant access to everyone he wants. A
    <command>GRANT</command> command means, <quote>I trust you</quote>.
    If someone you trust does the thing above, it's time to
    think it over and then use <command>REVOKE</command>.
</para>

<para>
    This mechanism also works for update rules. In the examples of
    the previous section, the owner of the tables in the example
    database could grant the privileges <literal>SELECT</>,
    <literal>INSERT</>, <literal>UPDATE</>, and <literal>DELETE</> on
    the <literal>shoelace</> view to someone else, but only
    <literal>SELECT</> on <literal>shoelace_log</>. The rule action to
    write log entries will still be executed successfully, and that
    other user could see the log entries.  But he cannot create fake
    entries, nor could he manipulate or remove existing ones.
</para>
</sect1>

<sect1 id="rules-status">
<title>Rules and Command Status</title>

<para>
    The <productname>PostgreSQL</productname> server returns a command
    status string, such as <literal>INSERT 149592 1</>, for each
    command it receives.  This is simple enough when there are no rules
    involved, but what happens when the query is rewritten by rules?
</para>

<para>
    Rules affect the command status as follows:

    <itemizedlist>
     <listitem>
      <para>
       If there is no unconditional <literal>INSTEAD</> rule for the query, then
       the originally given query will be executed, and its command
       status will be returned as usual.  (But note that if there were
       any conditional <literal>INSTEAD</> rules, the negation of their qualifications
       will have been added to the original query.  This might reduce the
       number of rows it processes, and if so the reported status will
       be affected.)
      </para>
     </listitem>

     <listitem>
      <para>
       If there is any unconditional <literal>INSTEAD</> rule for the query, then
       the original query will not be executed at all.  In this case,
       the server will return the command status for the last query
       that was inserted by an <literal>INSTEAD</> rule (conditional or
       unconditional) and is of the same command type
       (<command>INSERT</command>, <command>UPDATE</command>, or
       <command>DELETE</command>) as the original query.  If no query
       meeting those requirements is added by any rule, then the
       returned command status shows the original query type and
       zeroes for the row-count and OID fields.
      </para>
     </listitem>
    </itemizedlist>

    (This system was established in <productname>PostgreSQL</> 7.3.
    In versions before that, the command status might show different
    results when rules exist.)
</para>

<para>
    The programmer can ensure that any desired <literal>INSTEAD</> rule is the one
    that sets the command status in the second case, by giving it the
    alphabetically last rule name among the active rules, so that it
    gets applied last.
</para>
</sect1>

<sect1 id="rules-triggers">
<title>Rules versus Triggers</title>

<indexterm zone="rules-triggers">
 <primary>rule</primary>
 <secondary sortas="Trigger">compared with triggers</secondary>
</indexterm>

<indexterm zone="rules-triggers">
 <primary>trigger</primary>
 <secondary sortas="Regeln">compared with rules</secondary>
</indexterm>

<para>
    Many things that can be done using triggers can also be
    implemented using the <productname>PostgreSQL</productname>
    rule system.  One of the things that cannot be implemented by
    rules are some kinds of constraints, especially foreign keys. It is possible
    to place a qualified rule that rewrites a command to <literal>NOTHING</>
    if the value of a column does not appear in another table.
    But then the data is silently thrown away and that's
    not a good idea. If checks for valid values are required,
    and in the case of an invalid value an error message should
    be generated, it must be done by a trigger.
</para>

<para>
    On the other hand, a trigger cannot be created on views because
    there is no real data in a view relation;  however INSERT, UPDATE,
    and DELETE rules can be created on views.
</para>

<para>
    For the things that can be implemented by both, which is best
    depends on the usage of the database.
    A trigger is fired for any affected row once. A rule manipulates
    the query or generates an additional query. So if many
    rows are affected in one statement, a rule issuing one extra
    command is likely to be faster than a trigger that is
    called for every single row and must execute its operations
    many times.  However, the trigger approach is conceptually far
    simpler than the rule approach, and is easier for novices to get right.
</para>

<para>
    Here we show an example of how the choice of rules versus triggers
    plays out in one situation.  There are two tables:

<programlisting>
CREATE TABLE computer (
    hostname        text,    -- indexed
    manufacturer    text     -- indexed
);

CREATE TABLE software (
    software        text,    -- indexed
    hostname        text     -- indexed
);
</programlisting>

    Both tables have many thousands of rows and the indexes on
    <structfield>hostname</> are unique.  The rule or trigger should
    implement a constraint that deletes rows from <literal>software</>
    that reference a deleted computer.  The trigger would use this command:

<programlisting>
DELETE FROM software WHERE hostname = $1;
</programlisting>

    Since the trigger is called for each individual row deleted from
    <literal>computer</>, it can prepare and save the plan for this
    command and pass the <structfield>hostname</> value in the
    parameter.  The rule would be written as:

<programlisting>
CREATE RULE computer_del AS ON DELETE TO computer
    DO DELETE FROM software WHERE hostname = OLD.hostname;
</programlisting>
   </para>

   <para>
    Now we look at different types of deletes. In the case of a:
    
<programlisting>
DELETE FROM computer WHERE hostname = 'mypc.local.net';
</programlisting>

    the table <literal>computer</> is scanned by index (fast), and the
    command issued by the trigger would also use an index scan (also fast).
    The extra command from the rule would be:

<programlisting>
DELETE FROM software WHERE computer.hostname = 'mypc.local.net'
                       AND software.hostname = computer.hostname;
</programlisting>

    Since there are appropriate indexes setup, the planner
    will create a plan of

<literallayout class="monospaced">
Nestloop
  -&gt;  Index Scan using comp_hostidx on computer
  -&gt;  Index Scan using soft_hostidx on software
</literallayout>

    So there would be not that much difference in speed between
    the trigger and the rule implementation.
   </para>

   <para>
    With the next delete we want to get rid of all the 2000 computers
    where the <structfield>hostname</> starts with
    <literal>old</>. There are two possible commands to do that. One
    is:

<programlisting>
DELETE FROM computer WHERE hostname &gt;= 'old'
                       AND hostname &lt;  'ole'
</programlisting>

    The command added by the rule will be:

<programlisting>
DELETE FROM software WHERE computer.hostname &gt;= 'old' AND computer.hostname &lt; 'ole'
                       AND software.hostname = computer.hostname;
</programlisting>

    with the plan

<literallayout class="monospaced">
Hash Join
  -&gt;  Seq Scan on software
  -&gt;  Hash
    -&gt;  Index Scan using comp_hostidx on computer
</literallayout>

    The other possible command is:

<programlisting>
DELETE FROM computer WHERE hostname ~ '^old';
</programlisting>

    which results in the following executing plan for the command
    added by the rule:

<literallayout class="monospaced">
Nestloop
  -&gt;  Index Scan using comp_hostidx on computer
  -&gt;  Index Scan using soft_hostidx on software
</literallayout>

    This shows, that the planner does not realize that the
    qualification for <structfield>hostname</> in
    <literal>computer</> could also be used for an index scan on
    <literal>software</> when there are multiple qualification
    expressions combined with <literal>AND</>, which is what it does
    in the regular-expression version of the command. The trigger will
    get invoked once for each of the 2000 old computers that have to be
    deleted, and that will result in one index scan over
    <literal>computer</> and 2000 index scans over
    <literal>software</>. The rule implementation will do it with two
    commands that use indexes.  And it depends on the overall size of
    the table <literal>software</> whether the rule will still be faster in the
    sequential scan situation. 2000 command executions from the trigger over the SPI
    manager take some time, even if all the index blocks will soon be in the cache.
</para>

<para>
    The last command we look at is:

<programlisting>
DELETE FROM computer WHERE manufacturer = 'bim';
</programlisting>

    Again this could result in many rows to be deleted from
    <literal>computer</>. So the trigger will again run many commands
    through the executor.  The command generated by the rule will be:

<programlisting>
DELETE FROM software WHERE computer.manufacturer = 'bim'
                       AND software.hostname = computer.hostname;
</programlisting>

    The plan for that command will again be the nested loop over two
    index scans, only using a different index on <literal>computer</>:

<programlisting>
Nestloop
  -&gt;  Index Scan using comp_manufidx on computer
  -&gt;  Index Scan using soft_hostidx on software
</programlisting>

    In any of these cases, the extra commands from the rule system
    will be more or less independent from the number of affected rows
    in a command.
</para>

<![IGNORE[
<!-- What's happening with this?  If it doesn't come back, remove this section. -->
<para>
    Another situation is cases on <command>UPDATE</command> where it depends on the
    change of an attribute if an action should be performed or
    not. The only way to
    create a rule as in the shoelace_log example is to do it with
    a rule qualification. That results in an extra query that is
    performed always, even if the attribute of interest cannot
    change at all because it does not appear in the target list
    of the initial query. When this is enabled again, it will be
    one more advantage of rules over triggers. Optimization of
    a trigger must fail by definition in this case, because the
    fact that its actions will only be done when a specific attribute
    is updated is hidden in its functionality. The definition of
    a trigger only allows to specify it on row level, so whenever a
    row is touched, the trigger must be called to make its
    decision. The rule system will know it by looking up the
    target list and will suppress the additional query completely
    if the attribute isn't touched. So the rule, qualified or not,
    will only do its scans if there ever could be something to do.
</para>
]]>

<para>
    The summary is, rules will only be significantly slower than
    triggers if their actions result in large and badly qualified
    joins, a situation where the planner fails.
</para>
</sect1>

</chapter>
@


1.55
log
@Revert removal of pre-7.4 documenation behavior mentions.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.53 2009/11/05 23:24:22 tgl Exp $ -->
d1653 1
a1653 1
    <foreignphrase>Voilà</foreignphrase>:
@


1.54
log
@Remove pre-7.4 documentaiton mentions, now that 8.0 is the oldest
supported release.
@
text
@d1831 3
@


1.53
log
@Don't treat NEW and OLD as reserved words anymore.  For the purposes of rules
it works just as well to have them be ordinary identifiers, and this gets rid
of a number of ugly special cases.  Plus we aren't interfering with non-rule
usage of these names.

catversion bump because the names change internally in stored rules.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.52 2008/12/16 03:12:08 momjian Exp $ -->
a1830 3
    (This system was established in <productname>PostgreSQL</> 7.3.
    In versions before that, the command status might show different
    results when rules exist.)
@


1.52
log
@Fix wording of section comparing triggers and rules;  old wording as
confusing.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.51 2007/02/01 19:10:24 momjian Exp $ -->
d438 1
a438 2
    table entries for <literal>NEW</> and <literal>OLD</> (named <literal>*NEW*</> and <literal>*OLD*</> for
    historical reasons in the printed query tree) you can see in
d506 1
a506 1
  FROM shoelace *OLD*, shoelace *NEW*,
d533 1
a533 1
     extra entries <literal>shoelace *OLD*</> and <literal>shoelace *NEW*</>.  These entries don't
d548 1
a548 1
    won't expand <literal>*OLD*</> or <literal>*NEW*</> &mdash; otherwise we'd have infinite recursion!)
d1075 1
a1075 1
       *NEW*.sl_name, *NEW*.sl_avail,
d1077 1
a1077 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*;
d1083 1
a1083 1
    in the query tree for <literal>*NEW*</> and <literal>*OLD*</>.
d1096 1
a1096 1
       *NEW*.sl_name, *NEW*.sl_avail,
d1098 1
a1098 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*,
d1107 1
a1107 1
       *NEW*.sl_name, *NEW*.sl_avail,
d1109 1
a1109 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*,
d1111 1
a1111 1
 <emphasis>WHERE *NEW*.sl_avail &lt;&gt; *OLD*.sl_avail</emphasis>;
d1127 1
a1127 1
       *NEW*.sl_name, *NEW*.sl_avail,
d1129 1
a1129 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*,
d1131 1
a1131 1
 WHERE *NEW*.sl_avail &lt;&gt; *OLD*.sl_avail
d1145 1
a1145 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*,
d1147 1
a1147 1
 WHERE <emphasis>6</emphasis> &lt;&gt; *OLD*.sl_avail
d1160 1
a1160 1
  FROM shoelace_data *NEW*, shoelace_data *OLD*,
d1457 1
a1457 1
       shoelace_ok *OLD*, shoelace_ok *NEW*,
d1475 3
a1477 3
       shoelace_ok *OLD*, shoelace_ok *NEW*,
       shoelace shoelace, shoelace *OLD*,
       shoelace *NEW*, shoelace_data shoelace_data
d1495 4
a1498 4
       shoelace_ok *OLD*, shoelace_ok *NEW*,
       shoelace shoelace, shoelace *OLD*,
       shoelace *NEW*, shoelace_data shoelace_data,
       shoelace *OLD*, shoelace *NEW*,
d1514 4
a1517 4
       shoelace_ok *OLD*, shoelace_ok *NEW*,
       shoelace shoelace, shoelace *OLD*,
       shoelace *NEW*, shoelace_data shoelace_data,
       shoelace *OLD*, shoelace *NEW*,
d1519 1
a1519 1
       shoelace_data *OLD*, shoelace_data *NEW*
@


1.52.2.1
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.52 2008/12/16 03:12:08 momjian Exp $ -->
d1654 1
a1654 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.51
log
@Wording cleanup for error messages.  Also change can't -> cannot.

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".
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.50 2007/02/01 00:28:18 momjian Exp $ -->
d1872 3
a1874 7
    On the other hand, a trigger that is fired on
    <command>INSERT</command> on a view can do the same as a rule: put
    the data somewhere else and suppress the insert in the view. But
    it cannot do the same thing on <command>UPDATE</command> or
    <command>DELETE</command>, because there is no real data in the
    view relation that could be scanned, and thus the trigger would
    never get called. Only a rule will help.
@


1.51.2.1
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.51 2007/02/01 19:10:24 momjian Exp $ -->
d1654 1
a1654 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.50
log
@Consistenly use colons before '<programlisting>' blocks, where
appropriate.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.49 2007/01/31 20:56:18 momjian Exp $ -->
d1081 1
a1081 1
    (This looks a little strange since you can't normally write
@


1.49
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/rules.sgml,v 1.48 2006/12/27 16:07:36 tgl Exp $ -->
d281 1
a281 1
    between
d287 1
a287 1
    compared against the two commands
d343 1
a343 1
returns the lower of 2 integer values. We create that as
d384 1
a384 1
    The views are created as
d488 1
a488 1
    interpreted by the parser and produced the query tree
d501 1
a501 1
    <literal>_RETURN</literal> rule with the query tree
d517 1
a517 1
    resulting rewritten query tree is almost the same as if you had typed
d572 1
a572 1
    The output of the parser this time is the query tree
d584 1
a584 1
    query tree
d671 1
a671 1
    <literal>b</>, the query trees for the two statements
d715 1
a715 1
    as
d722 1
a722 1
    same result set as a
d749 1
a749 1
    <acronym>CTID</> to the target list, the query actually looks like
d887 1
a887 1
    Keep the syntax
d1057 1
a1057 1
    The parser created the query tree
d1066 1
a1066 1
    qualification expression
d1072 1
a1072 1
    and the action
d1191 1
a1191 1
    ensure that, if the original query would be, say,
d1202 1
a1202 1
    command generated by the rule is
d1218 1
a1218 1
    if someone issued the command
d1228 1
a1228 1
    in the extra query tree
d1263 1
a1263 1
    to let those query trees get thrown away.  So we could create the rules
d1323 1
a1323 1
    <literal>shoelace</literal>.  An example for the insert case is
d1443 1
a1443 1
    the parser's output
d1452 1
a1452 1
    into
d1466 1
a1466 1
    <literal>shoelace_upd</literal> produces
d1486 1
a1486 1
    and applies the <literal>_RETURN</literal> rule on it, and we get
d1506 1
a1506 1
    producing the extra query tree
d1533 1
a1533 1
    <acronym>SQL</acronym> statements
d1615 1
a1615 1
    The view for this is
d1623 1
a1623 1
    Its output is
d1639 1
a1639 1
    we don't delete it directly. Instead we create one more view
d1921 1
a1921 1
    parameter.  The rule would be written as
d1930 1
a1930 1
    Now we look at different types of deletes. In the case of a 
d1938 1
a1938 1
    The extra command from the rule would be
d1962 1
a1962 1
    is
d1969 1
a1969 1
    The command added by the rule will be
d1985 1
a1985 1
    The other possible command is
d2017 1
a2017 1
    The last command we look at is
d2025 1
a2025 1
    through the executor.  The command generated by the rule will be
@


1.48
log
@Use FROM clause in example UPDATE commands where appropriate.  Also
remove long-obsolete statement that there isn't a check for infinite
recursion in view rules.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.47 2006/09/16 00:30:15 momjian Exp $ -->
d1810 1
a1810 1
       will have been added to the original query.  This may reduce the
@


1.47
log
@Remove emacs info from footer of SGML files.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.46 2006/09/02 17:06:52 tgl Exp $ -->
a651 15

   <note>
    <para>
    There is currently no recursion stopping mechanism for view rules
    in the rule system (only for the other kinds of rules).  This
    doesn't hurt much, because the only way to push this into an
    endless loop (bloating up the server process until it reaches the memory
    limit) is to create tables and then setup the view rules by hand
    with <command>CREATE RULE</command> in such a way, that one
    selects from the other that selects from the one.  This could
    never happen if <command>CREATE VIEW</command> is used because for
    the first <command>CREATE VIEW</command>, the second relation does
    not exist and thus the first view cannot select from the second.
    </para>
   </note>
d676 1
a676 1
UPDATE t1 SET b = t2.b WHERE t1.a = t2.a;
d718 1
a718 1
UPDATE t1 SET a = t1.a, b = t2.b WHERE t1.a = t2.a;
d744 2
a745 1
    (<acronym>CTID</>).<indexterm><primary>CTID</></>  This is a system column containing the
d748 2
a749 2
    original row of <literal>t1</> to be updated.  After adding the <acronym>CTID</>
    to the target list, the query actually looks like
d763 1
a763 2
    the transaction committed the vacuum cleaner can really move it
    out.
@


1.47.2.1
log
@Use FROM clause in example UPDATE commands where appropriate.  Also
remove long-obsolete statement that there isn't a check for infinite
recursion in view rules.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.47 2006/09/16 00:30:15 momjian Exp $ -->
d652 15
d691 1
a691 1
UPDATE t1 SET b = t2.b FROM t2 WHERE t1.a = t2.a;
d733 1
a733 1
UPDATE t1 SET a = t1.a, b = t2.b FROM t2 WHERE t1.a = t2.a;
d759 1
a759 2
    (<acronym>CTID</>).<indexterm><primary>CTID</></>
    This is a system column containing the
d762 2
a763 2
    original row of <literal>t1</> to be updated.  After adding the
    <acronym>CTID</> to the target list, the query actually looks like
d777 2
a778 1
    the transaction commits the vacuum cleaner can really remove it.
@


1.47.2.2
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.47.2.1 2006/12/27 16:07:42 tgl Exp $ -->
d1654 1
a1654 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.46
log
@Apply a simple solution to the problem of making INSERT/UPDATE/DELETE
RETURNING play nice with views/rules.  To wit, have the rule rewriter
rewrite any RETURNING clause found in a rule to produce what the rule's
triggering query asked for in its RETURNING clause, in particular drop
the RETURNING clause if no RETURNING in the triggering query.  This
leaves the responsibility for knowing how to produce the view's output
columns on the rule author, without requiring any fundamental changes
in rule semantics such as adding new rule event types would do.  The
initial implementation constrains things to ensure that there is
exactly one, unconditionally invoked RETURNING clause among the rules
for an event --- later we might be able to relax that, but for a post
feature freeze fix it seems better to minimize how much invention we do.
Per gripe from Jaime Casanova.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.45 2006/04/23 03:39:52 momjian Exp $ -->
a2092 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
@Removes or minimizes some documentation mentions of backward
compatibility for release 7.2 and earlier.  I have not altered any
mentions of release 7.3 or later.  The release notes were not modified,
so the changes are still documented, just not in the main docs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.44 2005/10/22 14:44:35 alvherre Exp $ -->
d876 1
a876 1
            They can be <literal>INSTEAD</> or <literal>ALSO</> (default).
d923 2
a924 1
    can have a qualification or not and it can be <literal>INSTEAD</> or <literal>ALSO</> (default).
d936 1
a936 1
    So we have four cases that produce the following query trees for
d941 2
a942 11
      <term>No qualification and <literal>ALSO</></term>
      <listitem>
       <para>
        the query tree from the rule action with the original query
        tree's qualification added
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>No qualification but <literal>INSTEAD</></term>
d1278 1
a1278 1
    to let those query trees get thrown away.  So we create the rules
d1334 28
@


1.44
log
@Fix typo.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.43 2005/10/15 20:12:33 neilc Exp $ -->
d2046 1
a2046 4
    not. In <productname>PostgreSQL</productname> version 6.4, the
    attribute specification for rule events is disabled (it will have
    its comeback latest in 6.5, maybe earlier 
    - stay tuned). So for now the only way to
@


1.44.2.1
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.44 2005/10/22 14:44:35 alvherre Exp $ -->
d1649 1
a1649 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.43
log
@Fix assorted typos in the documentation, and use American spelling
rather than British. Patch from Michael Fuhr.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.42 2005/05/20 01:37:08 neilc Exp $ -->
d556 1
a556 1
    No we want to write a query that finds out for which shoes currently in the store
@


1.42
log
@Make the CREATE RULE syntax description in rules.sgml more consistent
with the syntax description in the CREATE RULE reference page. From
Kris Jurka.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.41 2005/01/29 23:45:36 tgl Exp $ -->
d2015 1
a2015 1
DELETE FROM computer WHERE manufacurer = 'bim';
d2023 1
a2023 1
DELETE FROM software WHERE computer.manufacurer = 'bim'
@


1.41
log
@We haven't had a fixed limit on rule recursion depth since 7.3 ...
but the documentation still said so.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.40 2005/01/23 00:30:18 momjian Exp $ -->
d905 3
a907 3
CREATE RULE <replaceable>rule_name</> AS ON <replaceable>event</>
    TO <replaceable>object</> [WHERE <replaceable>rule_qualification</>]
    DO [ALSO|INSTEAD] [<replaceable>action</> | (<replaceable>actions</>) | NOTHING];
@


1.40
log
@Add tools/find_gt_lt to find < and > in SGML source.

Lowercase some uppercase tags so tools is more reliable at finding
problems.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.39 2005/01/22 22:56:36 momjian Exp $ -->
d1003 5
a1007 6
    So the query trees in the rule actions must have either a different command type
    or a different result relation, otherwise, this recursive process will end up in a loop.
    There is a fixed recursion limit of currently 100 iterations.
    If after 100 iterations there are still update rules to apply, the
    rule system assumes a loop over multiple rule definitions and reports
    an error.
@


1.39
log
@More < and > cleanups converted to ampersands.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.38 2005/01/22 22:06:27 momjian Exp $ -->
d3 2
a4 2
<Chapter Id="rules">
<Title>The Rule System</Title>
d10 1
a10 1
<Para>
d15 1
a15 1
</Para>
d17 1
a17 1
<Para>
d22 1
a22 1
</Para>
d24 1
a24 1
<Para>
d36 2
a37 2
<Sect1 id="querytree">
<Title>The Query Tree</Title>
d43 1
a43 1
<Para>
d46 1
a46 1
</Para>
d48 1
a48 1
<Para>
d55 2
a56 2
    is basically representable as an <Acronym>SQL</Acronym> statement.
</Para>
d58 1
a58 1
<Para>
d60 1
a60 1
    <Acronym>SQL</Acronym> statement where the single parts that it is
d69 1
a69 1
</Para>
d71 1
a71 1
<Para>
d73 1
a73 1
    <Acronym>SQL</Acronym> representations of query trees are
d76 1
a76 1
</Para>
d78 2
a79 2
<Para>
    When reading the <Acronym>SQL</Acronym> representations of the 
d84 3
a86 3
<VariableList>
    <VarListEntry>
    <Term>
d88 3
a90 3
    </Term>
    <ListItem>
    <Para>
d95 3
a97 3
    </Para>
    </ListItem>
    </VarListEntry>
d99 2
a100 2
    <VarListEntry>
    <Term>
d102 1
a102 1
    </Term>
d104 2
a105 2
    <ListItem>
    <Para>
d109 1
a109 1
    </Para>
d111 1
a111 1
    <Para>
d116 1
a116 1
        are duplicate names as it would in an <Acronym>SQL</Acronym>
d120 3
a122 3
    </Para>
    </ListItem>
    </VarListEntry>
d124 2
a125 2
    <VarListEntry>
    <Term>
d127 3
a129 3
    </Term>
    <ListItem>
    <Para>
d132 1
a132 1
    </Para>
d134 1
a134 1
    <Para>
d140 1
a140 1
    </Para>
d142 1
a142 1
    <Para>
d146 3
a148 3
    </Para>
    </ListItem>
    </VarListEntry>
d150 2
a151 2
    <VarListEntry>
    <Term>
d153 1
a153 1
    </Term>
d155 2
a156 2
    <ListItem>
    <Para>
d166 1
a166 1
    </Para>
d168 1
a168 1
    <Para>
d174 1
a174 1
    </Para>
d176 1
a176 1
    <Para>
d186 1
a186 1
    </Para>
d188 1
a188 1
    <Para>
d196 1
a196 1
    </Para>
d198 1
a198 1
    <Para>
d203 3
a205 3
    </Para>
    </ListItem>
    </VarListEntry>
d207 2
a208 2
    <VarListEntry>
    <Term>
d210 3
a212 3
    </Term>
    <ListItem>
    <Para>
d219 4
a222 4
        of an <Acronym>SQL</Acronym> statement.
    </Para>
    </ListItem>
    </VarListEntry>
d224 2
a225 2
    <VarListEntry>
    <Term>
d227 3
a229 3
    </Term>
    <ListItem>
    <Para>
d242 3
a244 3
    </Para>
    </ListItem>
    </VarListEntry>
d246 2
a247 2
    <VarListEntry>
    <Term>
d249 3
a251 3
    </Term>
    <ListItem>
    <Para>
d257 3
a259 3
    </Para>
    </ListItem>
    </VarListEntry>
d261 1
a261 1
</VariableList>
d263 1
a263 1
</Sect1>
d265 2
a266 2
<Sect1 id="rules-views">
<Title>Views and the Rule System</Title>
d278 2
a279 2
<Para>
    Views in <ProductName>PostgreSQL</ProductName> are implemented
d283 1
a283 1
<ProgramListing>
d285 1
a285 1
</ProgramListing>
d289 2
a290 2
<ProgramListing>
CREATE TABLE myview (<Replaceable>same column list as mytab</Replaceable>);
d293 1
a293 1
</ProgramListing>
d298 1
a298 1
    <ProductName>PostgreSQL</ProductName> system catalogs is exactly
d302 1
a302 1
</Para>
d304 2
a305 2
<Sect2 id="rules-select">
<Title>How <command>SELECT</command> Rules Work</Title>
d312 1
a312 1
<Para>
d319 1
a319 1
</Para>
d321 1
a321 1
<Para>
d326 1
a326 1
</Para>
d328 1
a328 1
<Para>
d339 1
a339 1
</Para>
d341 1
a341 1
<Para>
d345 1
a345 1
<ProgramListing>
d349 2
a350 2
</ProgramListing>
</Para>
d352 1
a352 1
<Para>
d356 1
a356 1
<ProgramListing>
d378 1
a378 1
</ProgramListing>
d381 1
a381 1
</Para>
d383 1
a383 1
<Para>
d386 1
a386 1
<ProgramListing>
d419 1
a419 1
</ProgramListing>
d433 1
a433 1
</Para>
d435 2
a436 2
    <Note>
    <Para>
d442 2
a443 2
    </Para>
    </Note>
d445 1
a445 1
<Para>
d449 1
a449 1
<ProgramListing>
d481 1
a481 1
</ProgramListing>
d490 1
a490 1
<ProgramListing>
d495 1
a495 1
</ProgramListing>
d503 1
a503 1
<ProgramListing>
d510 2
a511 2
</ProgramListing>
</Para>
d513 1
a513 1
<Para>
d519 1
a519 1
<ProgramListing>
d531 1
a531 1
</ProgramListing>
d542 1
a542 1
</Para>
d544 1
a544 1
<Para>
d553 1
a553 1
</Para>
d555 1
a555 1
<Para>
d560 1
a560 1
<ProgramListing>
d568 2
a569 2
</ProgramListing>
</Para>
d571 1
a571 1
<Para>
d574 1
a574 1
<ProgramListing>
d580 1
a580 1
</ProgramListing>
d586 1
a586 1
<ProgramListing>
d600 1
a600 1
</ProgramListing>
d606 1
a606 1
<ProgramListing>
d637 1
a637 1
</ProgramListing>
d653 2
a654 2
   <Note>
    <Para>
d665 3
a667 3
    </Para>
   </Note>
</Sect2>
d669 2
a670 2
<Sect2>
<Title>View Rules in Non-<command>SELECT</command> Statements</Title>
d672 1
a672 1
<Para>
d676 1
a676 1
</Para>
d678 1
a678 1
<Para>
d688 1
a688 1
<ProgramListing>
d692 1
a692 1
</ProgramListing>
d696 3
a698 3
    <ItemizedList>
        <ListItem>
        <Para>
d700 2
a701 2
        </Para>
        </ListItem>
d703 2
a704 2
        <ListItem>
        <Para>
d707 2
a708 2
        </Para>
        </ListItem>
d710 2
a711 2
        <ListItem>
        <Para>
d714 2
a715 2
        </Para>
        </ListItem>
d717 2
a718 2
        <ListItem>
        <Para>
d720 3
a722 3
        </Para>
        </ListItem>
    </ItemizedList>
d732 1
a732 1
<ProgramListing>
d734 1
a734 1
</ProgramListing>
d739 1
a739 1
<ProgramListing>
d741 1
a741 1
</ProgramListing>
d753 1
a753 1
</Para>
d755 1
a755 1
<Para>
d765 1
a765 1
<ProgramListing>
d767 1
a767 1
</ProgramListing>
d769 1
a769 1
    Now another detail of <ProductName>PostgreSQL</ProductName> enters
d779 1
a779 1
</Para>
d781 1
a781 1
<Para>
d784 2
a785 2
</Para>
</Sect2>
d787 2
a788 2
<Sect2>
<Title>The Power of Views in <ProductName>PostgreSQL</ProductName></Title>
d790 1
a790 1
<Para>
d796 1
a796 1
</Para>
d798 1
a798 1
<Para>
d810 1
a810 1
    the rule system as implemented in <ProductName>PostgreSQL</ProductName>
d813 2
a814 2
</Para>
</Sect2>
d816 2
a817 2
<Sect2 id="rules-views-update">
<Title>Updating a View</Title>
d819 1
a819 1
<Para>
d827 1
a827 1
</Para>
d829 1
a829 1
<Para>
d832 2
a833 2
</Para>
</Sect2>
d835 1
a835 1
</Sect1>
d837 2
a838 2
<Sect1 id="rules-update">
<Title>Rules on <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</></Title>
d855 1
a855 1
<Para>
d861 3
a863 3
    <ItemizedList>
        <ListItem>
        <Para>
d865 2
a866 2
        </Para>
        </ListItem>
d868 2
a869 2
        <ListItem>
        <Para>
d871 2
a872 2
        </Para>
        </ListItem>
d874 2
a875 2
        <ListItem>
        <Para>
d877 2
a878 2
        </Para>
        </ListItem>
d880 2
a881 2
        <ListItem>
        <Para>
d883 2
a884 2
        </Para>
        </ListItem>
d886 2
a887 2
        <ListItem>
        <Para>
d889 3
a891 3
        </Para>
        </ListItem>
    </ItemizedList>
d896 1
a896 1
</Para>
d898 2
a899 2
<Sect2>
<Title>How Update Rules Work</Title>
d901 1
a901 1
<Para>
d904 1
a904 1
<ProgramListing>
d908 1
a908 1
</ProgramListing>
d913 1
a913 1
</Para>
d915 1
a915 1
<Para>
d924 1
a924 1
</Para>
d926 1
a926 1
<Para>
d932 1
a932 1
</Para>
d987 1
a987 1
</Para>
d989 1
a989 1
<Para>
d997 1
a997 1
</Para>
d999 1
a999 1
<Para>
d1009 1
a1009 1
</Para>
d1011 1
a1011 1
<Para>
d1023 1
a1023 1
</Para>
d1025 1
a1025 1
<Para>
d1029 1
a1029 1
</Para>
d1031 2
a1032 2
<Sect3>
<Title>A First Rule Step by Step</Title>
d1034 1
a1034 1
<Para>
d1041 1
a1041 1
<ProgramListing>
d1057 2
a1058 2
</ProgramListing>
</Para>
d1060 1
a1060 1
<Para>
d1063 1
a1063 1
<ProgramListing>
d1065 1
a1065 1
</ProgramListing>
d1069 1
a1069 1
<ProgramListing>
d1076 1
a1076 1
</ProgramListing>
d1083 1
a1083 1
<ProgramListing>
d1087 1
a1087 1
</ProgramListing>
d1092 1
a1092 1
<ProgramListing>
d1094 1
a1094 1
</ProgramListing>
d1098 1
a1098 1
<ProgramListing>
d1103 1
a1103 1
</ProgramListing>
d1111 1
a1111 1
</Para>
d1113 1
a1113 1
<Para>
d1119 1
a1119 1
<ProgramListing>
d1125 1
a1125 1
</ProgramListing>
d1130 1
a1130 1
<ProgramListing>
d1137 1
a1137 1
</ProgramListing>
d1150 1
a1150 1
<ProgramListing>
d1158 1
a1158 1
</ProgramListing>
d1166 1
a1166 1
<ProgramListing>
d1174 1
a1174 1
</ProgramListing>
d1181 1
a1181 1
<ProgramListing>
d1189 1
a1189 1
</ProgramListing>
d1197 1
a1197 1
<ProgramListing>
d1207 1
a1207 1
</ProgramListing>
d1217 1
a1217 1
<ProgramListing>
d1220 1
a1220 1
</ProgramListing>
d1228 1
a1228 1
<ProgramListing>
d1235 1
a1235 1
</ProgramListing>
d1244 1
a1244 1
<ProgramListing>
d1247 1
a1247 1
</ProgramListing>
d1254 1
a1254 1
<ProgramListing>
d1261 1
a1261 1
</ProgramListing>
d1265 1
a1265 1
</Para>
d1267 1
a1267 1
<Para>
d1273 2
a1274 2
</Para>
</Sect3>
d1276 1
a1276 1
</Sect2>
d1278 2
a1279 2
<Sect2 id="rules-update-views">
<Title>Cooperation with Views</Title>
d1283 1
a1283 1
<Para>
d1289 1
a1289 1
<ProgramListing>
d1296 1
a1296 1
</ProgramListing>
d1305 1
a1305 1
</Para>
d1307 1
a1307 1
<Para>
d1314 1
a1314 1
<ProgramListing>
d1339 1
a1339 1
</ProgramListing>
d1350 1
a1350 1
<ProgramListing>
d1366 1
a1366 1
</ProgramListing>
d1371 1
a1371 1
<ProgramListing>
d1380 1
a1380 1
</ProgramListing>
d1384 1
a1384 1
<ProgramListing>
d1398 1
a1398 1
</ProgramListing>
d1402 1
a1402 1
<ProgramListing>
d1404 1
a1404 1
</ProgramListing>
d1408 1
a1408 1
<ProgramListing>
d1432 1
a1432 1
</ProgramListing>
d1441 1
a1441 1
<ProgramListing>
d1445 1
a1445 1
</ProgramListing>
d1450 1
a1450 1
<ProgramListing>
d1457 1
a1457 1
</ProgramListing>
d1464 1
a1464 1
<ProgramListing>
d1477 1
a1477 1
</ProgramListing>
d1484 1
a1484 1
<ProgramListing>
d1499 1
a1499 1
</ProgramListing>
d1504 1
a1504 1
<ProgramListing>
d1521 1
a1521 1
</ProgramListing>
d1529 1
a1529 1
    <Acronym>SQL</Acronym> statements
d1531 1
a1531 1
<ProgramListing>
d1550 1
a1550 1
</ProgramListing>
d1556 1
a1556 1
</Para>
d1558 1
a1558 1
<Para>
d1596 1
a1596 1
</Para>
d1598 1
a1598 1
<Para>
d1600 1
a1600 1
    <ProductName>PostgreSQL</ProductName> rule system and its power.
d1604 1
a1604 1
<ProgramListing>
d1607 1
a1607 1
</ProgramListing>
d1613 1
a1613 1
<ProgramListing>
d1617 1
a1617 1
</ProgramListing>
d1621 1
a1621 1
<ProgramListing>
d1628 1
a1628 1
</ProgramListing>
d1634 1
a1634 1
    To make it a little harder for <ProductName>PostgreSQL</ProductName>,
d1637 1
a1637 1
<ProgramListing>
d1640 1
a1640 1
</ProgramListing>
d1644 1
a1644 1
<ProgramListing>
d1648 1
a1648 1
</ProgramListing>
d1652 1
a1652 1
<ProgramListing>
d1667 1
a1667 1
</ProgramListing>
d1678 1
a1678 1
</Para>
d1680 1
a1680 1
<Para>
d1684 2
a1685 2
</Para>
</Sect2>
d1687 1
a1687 1
</Sect1>
d1689 2
a1690 2
<Sect1 id="rules-privileges">
<Title>Rules and Privileges</Title>
d1702 2
a1703 2
<Para>
    Due to rewriting of queries by the <ProductName>PostgreSQL</ProductName>
d1707 1
a1707 1
</Para>
d1709 1
a1709 1
<Para>
d1713 1
a1713 1
    The <ProductName>PostgreSQL</ProductName> rule system changes the
d1719 1
a1719 1
</Para>
d1721 1
a1721 1
<Para>
d1726 1
a1726 1
<ProgramListing>
d1731 1
a1731 1
</ProgramListing>
d1747 1
a1747 1
</Para>
d1749 1
a1749 1
<Para>
d1760 1
a1760 1
</Para>
d1762 1
a1762 1
<Para>
d1771 1
a1771 1
</Para>
d1773 1
a1773 1
<Para>
d1783 2
a1784 2
</Para>
</Sect1>
d1786 2
a1787 2
<Sect1 id="rules-status">
<Title>Rules and Command Status</Title>
d1789 2
a1790 2
<Para>
    The <ProductName>PostgreSQL</ProductName> server returns a command
d1794 1
a1794 1
</Para>
d1796 1
a1796 1
<Para>
d1831 1
a1831 1
</Para>
d1833 1
a1833 1
<Para>
d1838 2
a1839 2
</Para>
</Sect1>
d1841 2
a1842 2
<Sect1 id="rules-triggers">
<Title>Rules versus Triggers</Title>
d1854 1
a1854 1
<Para>
d1856 1
a1856 1
    implemented using the <ProductName>PostgreSQL</ProductName>
d1865 1
a1865 1
</Para>
d1867 1
a1867 1
<Para>
d1875 1
a1875 1
</Para>
d1877 1
a1877 1
<Para>
d1887 1
a1887 1
</Para>
d1889 1
a1889 1
<Para>
d1893 1
a1893 1
<ProgramListing>
d1903 1
a1903 1
</ProgramListing>
d1910 1
a1910 1
<ProgramListing>
d1912 1
a1912 1
</ProgramListing>
d1919 1
a1919 1
<ProgramListing>
d1922 1
a1922 1
</ProgramListing>
d1928 1
a1928 1
<ProgramListing>
d1930 1
a1930 1
</ProgramListing>
d1936 1
a1936 1
<ProgramListing>
d1939 1
a1939 1
</ProgramListing>
d1960 1
a1960 1
<ProgramListing>
d1963 1
a1963 1
</ProgramListing>
d1967 1
a1967 1
<ProgramListing>
d1970 1
a1970 1
</ProgramListing>
d1983 1
a1983 1
<ProgramListing>
d1985 1
a1985 1
</ProgramListing>
d2010 1
a2010 1
</Para>
d2012 1
a2012 1
<Para>
d2015 1
a2015 1
<ProgramListing>
d2017 1
a2017 1
</ProgramListing>
d2023 1
a2023 1
<ProgramListing>
d2026 1
a2026 1
</ProgramListing>
d2031 1
a2031 1
<ProgramListing>
d2035 1
a2035 1
</ProgramListing>
d2040 1
a2040 1
</Para>
d2044 1
a2044 1
<Para>
d2047 1
a2047 1
    not. In <ProductName>PostgreSQL</ProductName> version 6.4, the
d2066 1
a2066 1
</Para>
d2069 1
a2069 1
<Para>
d2073 2
a2074 2
</Para>
</Sect1>
d2076 1
a2076 1
</Chapter>
@


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

HEAD and 8.0.X.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.37 2004/12/30 03:13:56 tgl Exp $ -->
d347 1
a347 1
    SELECT CASE WHEN $1 < $2 THEN $1 ELSE $2 END
d417 2
a418 2
       AND rsl.sl_len_cm >= rsh.slminlen_cm
       AND rsl.sl_len_cm <= rsh.slmaxlen_cm;
d561 1
a561 1
SELECT * FROM shoe_ready WHERE total_avail >= 2;
d579 1
a579 1
 WHERE shoe_ready.total_avail >= 2;
d597 3
a599 3
           AND rsl.sl_len_cm >= rsh.slminlen_cm
           AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail >= 2;
d634 3
a636 3
           AND rsl.sl_len_cm >= rsh.slminlen_cm
           AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail > 2;
d1961 2
a1962 2
DELETE FROM computer WHERE hostname >= 'old'
                       AND hostname <  'ole'
d1968 1
a1968 1
DELETE FROM software WHERE computer.hostname >= 'old' AND computer.hostname < 'ole'
@


1.37
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
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.36 2004/11/15 06:32:14 neilc Exp $ -->
d1568 8
a1575 8
  ->  Merge Join
        ->  Seq Scan
              ->  Sort
                    ->  Seq Scan on s
        ->  Seq Scan
              ->  Sort
                    ->  Seq Scan on shoelace_arrive
  ->  Seq Scan on shoelace_data
d1582 6
a1587 6
  ->  Seq Scan
        ->  Sort
              ->  Seq Scan on s
  ->  Seq Scan
        ->  Sort
              ->  Seq Scan on shoelace_arrive
d1946 2
a1947 2
  ->  Index Scan using comp_hostidx on computer
  ->  Index Scan using soft_hostidx on software
d1976 3
a1978 3
  ->  Seq Scan on software
  ->  Hash
    ->  Index Scan using comp_hostidx on computer
d1992 2
a1993 2
  ->  Index Scan using comp_hostidx on computer
  ->  Index Scan using soft_hostidx on software
d2033 2
a2034 2
  ->  Index Scan using comp_manufidx on computer
  ->  Index Scan using soft_hostidx on software
@


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

HEAD and 8.0.X.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.37 2004/12/30 03:13:56 tgl Exp $ -->
d1568 8
a1575 8
  -&gt;  Merge Join
        -&gt;  Seq Scan
              -&gt;  Sort
                    -&gt;  Seq Scan on s
        -&gt;  Seq Scan
              -&gt;  Sort
                    -&gt;  Seq Scan on shoelace_arrive
  -&gt;  Seq Scan on shoelace_data
d1582 6
a1587 6
  -&gt;  Seq Scan
        -&gt;  Sort
              -&gt;  Seq Scan on s
  -&gt;  Seq Scan
        -&gt;  Sort
              -&gt;  Seq Scan on shoelace_arrive
d1946 2
a1947 2
  -&gt;  Index Scan using comp_hostidx on computer
  -&gt;  Index Scan using soft_hostidx on software
d1976 3
a1978 3
  -&gt;  Seq Scan on software
  -&gt;  Hash
    -&gt;  Index Scan using comp_hostidx on computer
d1992 2
a1993 2
  -&gt;  Index Scan using comp_hostidx on computer
  -&gt;  Index Scan using soft_hostidx on software
d2033 2
a2034 2
  -&gt;  Index Scan using comp_manufidx on computer
  -&gt;  Index Scan using soft_hostidx on software
@


1.37.4.2
log
@More < and > cleanups converted to ampersands.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.37.4.1 2005/01/22 22:10:10 momjian Exp $ -->
d347 1
a347 1
    SELECT CASE WHEN $1 &lt; $2 THEN $1 ELSE $2 END
d417 2
a418 2
       AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
       AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm;
d561 1
a561 1
SELECT * FROM shoe_ready WHERE total_avail &gt;= 2;
d579 1
a579 1
 WHERE shoe_ready.total_avail &gt;= 2;
d597 3
a599 3
           AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
           AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail &gt;= 2;
d634 3
a636 3
           AND rsl.sl_len_cm &gt;= rsh.slminlen_cm
           AND rsl.sl_len_cm &lt;= rsh.slmaxlen_cm) shoe_ready
 WHERE shoe_ready.total_avail &gt; 2;
d1961 2
a1962 2
DELETE FROM computer WHERE hostname &gt;= 'old'
                       AND hostname &lt;  'ole'
d1968 1
a1968 1
DELETE FROM software WHERE computer.hostname &gt;= 'old' AND computer.hostname &lt; 'ole'
@


1.37.4.3
log
@Add tools/find_gt_lt to find < and > in SGML source.

Lowercase some uppercase tags so tools is more reliable at finding
problems.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.37.4.2 2005/01/22 23:05:49 momjian Exp $ -->
d3 2
a4 2
<chapter id="rules">
<title>The Rule System</title>
d10 1
a10 1
<para>
d15 1
a15 1
</para>
d17 1
a17 1
<para>
d22 1
a22 1
</para>
d24 1
a24 1
<para>
d36 2
a37 2
<sect1 id="querytree">
<title>The Query Tree</title>
d43 1
a43 1
<para>
d46 1
a46 1
</para>
d48 1
a48 1
<para>
d55 2
a56 2
    is basically representable as an <acronym>SQL</acronym> statement.
</para>
d58 1
a58 1
<para>
d60 1
a60 1
    <acronym>SQL</acronym> statement where the single parts that it is
d69 1
a69 1
</para>
d71 1
a71 1
<para>
d73 1
a73 1
    <acronym>SQL</acronym> representations of query trees are
d76 1
a76 1
</para>
d78 2
a79 2
<para>
    When reading the <acronym>SQL</acronym> representations of the 
d84 3
a86 3
<variablelist>
    <varlistentry>
    <term>
d88 3
a90 3
    </term>
    <listitem>
    <para>
d95 3
a97 3
    </para>
    </listitem>
    </varlistentry>
d99 2
a100 2
    <varlistentry>
    <term>
d102 1
a102 1
    </term>
d104 2
a105 2
    <listitem>
    <para>
d109 1
a109 1
    </para>
d111 1
a111 1
    <para>
d116 1
a116 1
        are duplicate names as it would in an <acronym>SQL</acronym>
d120 3
a122 3
    </para>
    </listitem>
    </varlistentry>
d124 2
a125 2
    <varlistentry>
    <term>
d127 3
a129 3
    </term>
    <listitem>
    <para>
d132 1
a132 1
    </para>
d134 1
a134 1
    <para>
d140 1
a140 1
    </para>
d142 1
a142 1
    <para>
d146 3
a148 3
    </para>
    </listitem>
    </varlistentry>
d150 2
a151 2
    <varlistentry>
    <term>
d153 1
a153 1
    </term>
d155 2
a156 2
    <listitem>
    <para>
d166 1
a166 1
    </para>
d168 1
a168 1
    <para>
d174 1
a174 1
    </para>
d176 1
a176 1
    <para>
d186 1
a186 1
    </para>
d188 1
a188 1
    <para>
d196 1
a196 1
    </para>
d198 1
a198 1
    <para>
d203 3
a205 3
    </para>
    </listitem>
    </varlistentry>
d207 2
a208 2
    <varlistentry>
    <term>
d210 3
a212 3
    </term>
    <listitem>
    <para>
d219 4
a222 4
        of an <acronym>SQL</acronym> statement.
    </para>
    </listitem>
    </varlistentry>
d224 2
a225 2
    <varlistentry>
    <term>
d227 3
a229 3
    </term>
    <listitem>
    <para>
d242 3
a244 3
    </para>
    </listitem>
    </varlistentry>
d246 2
a247 2
    <varlistentry>
    <term>
d249 3
a251 3
    </term>
    <listitem>
    <para>
d257 3
a259 3
    </para>
    </listitem>
    </varlistentry>
d261 1
a261 1
</variablelist>
d263 1
a263 1
</sect1>
d265 2
a266 2
<sect1 id="rules-views">
<title>Views and the Rule System</title>
d278 2
a279 2
<para>
    Views in <productname>PostgreSQL</productname> are implemented
d283 1
a283 1
<programlisting>
d285 1
a285 1
</programlisting>
d289 2
a290 2
<programlisting>
CREATE TABLE myview (<replaceable>same column list as mytab</replaceable>);
d293 1
a293 1
</programlisting>
d298 1
a298 1
    <productname>PostgreSQL</productname> system catalogs is exactly
d302 1
a302 1
</para>
d304 2
a305 2
<sect2 id="rules-select">
<title>How <command>SELECT</command> Rules Work</title>
d312 1
a312 1
<para>
d319 1
a319 1
</para>
d321 1
a321 1
<para>
d326 1
a326 1
</para>
d328 1
a328 1
<para>
d339 1
a339 1
</para>
d341 1
a341 1
<para>
d345 1
a345 1
<programlisting>
d349 2
a350 2
</programlisting>
</para>
d352 1
a352 1
<para>
d356 1
a356 1
<programlisting>
d378 1
a378 1
</programlisting>
d381 1
a381 1
</para>
d383 1
a383 1
<para>
d386 1
a386 1
<programlisting>
d419 1
a419 1
</programlisting>
d433 1
a433 1
</para>
d435 2
a436 2
    <note>
    <para>
d442 2
a443 2
    </para>
    </note>
d445 1
a445 1
<para>
d449 1
a449 1
<programlisting>
d481 1
a481 1
</programlisting>
d490 1
a490 1
<programlisting>
d495 1
a495 1
</programlisting>
d503 1
a503 1
<programlisting>
d510 2
a511 2
</programlisting>
</para>
d513 1
a513 1
<para>
d519 1
a519 1
<programlisting>
d531 1
a531 1
</programlisting>
d542 1
a542 1
</para>
d544 1
a544 1
<para>
d553 1
a553 1
</para>
d555 1
a555 1
<para>
d560 1
a560 1
<programlisting>
d568 2
a569 2
</programlisting>
</para>
d571 1
a571 1
<para>
d574 1
a574 1
<programlisting>
d580 1
a580 1
</programlisting>
d586 1
a586 1
<programlisting>
d600 1
a600 1
</programlisting>
d606 1
a606 1
<programlisting>
d637 1
a637 1
</programlisting>
d653 2
a654 2
   <note>
    <para>
d665 3
a667 3
    </para>
   </note>
</sect2>
d669 2
a670 2
<sect2>
<title>View Rules in Non-<command>SELECT</command> Statements</title>
d672 1
a672 1
<para>
d676 1
a676 1
</para>
d678 1
a678 1
<para>
d688 1
a688 1
<programlisting>
d692 1
a692 1
</programlisting>
d696 3
a698 3
    <itemizedlist>
        <listitem>
        <para>
d700 2
a701 2
        </para>
        </listitem>
d703 2
a704 2
        <listitem>
        <para>
d707 2
a708 2
        </para>
        </listitem>
d710 2
a711 2
        <listitem>
        <para>
d714 2
a715 2
        </para>
        </listitem>
d717 2
a718 2
        <listitem>
        <para>
d720 3
a722 3
        </para>
        </listitem>
    </itemizedlist>
d732 1
a732 1
<programlisting>
d734 1
a734 1
</programlisting>
d739 1
a739 1
<programlisting>
d741 1
a741 1
</programlisting>
d753 1
a753 1
</para>
d755 1
a755 1
<para>
d765 1
a765 1
<programlisting>
d767 1
a767 1
</programlisting>
d769 1
a769 1
    Now another detail of <productname>PostgreSQL</productname> enters
d779 1
a779 1
</para>
d781 1
a781 1
<para>
d784 2
a785 2
</para>
</sect2>
d787 2
a788 2
<sect2>
<title>The Power of Views in <productname>PostgreSQL</productname></title>
d790 1
a790 1
<para>
d796 1
a796 1
</para>
d798 1
a798 1
<para>
d810 1
a810 1
    the rule system as implemented in <productname>PostgreSQL</productname>
d813 2
a814 2
</para>
</sect2>
d816 2
a817 2
<sect2 id="rules-views-update">
<title>Updating a View</title>
d819 1
a819 1
<para>
d827 1
a827 1
</para>
d829 1
a829 1
<para>
d832 2
a833 2
</para>
</sect2>
d835 1
a835 1
</sect1>
d837 2
a838 2
<sect1 id="rules-update">
<title>Rules on <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</></title>
d855 1
a855 1
<para>
d861 3
a863 3
    <itemizedlist>
        <listitem>
        <para>
d865 2
a866 2
        </para>
        </listitem>
d868 2
a869 2
        <listitem>
        <para>
d871 2
a872 2
        </para>
        </listitem>
d874 2
a875 2
        <listitem>
        <para>
d877 2
a878 2
        </para>
        </listitem>
d880 2
a881 2
        <listitem>
        <para>
d883 2
a884 2
        </para>
        </listitem>
d886 2
a887 2
        <listitem>
        <para>
d889 3
a891 3
        </para>
        </listitem>
    </itemizedlist>
d896 1
a896 1
</para>
d898 2
a899 2
<sect2>
<title>How Update Rules Work</title>
d901 1
a901 1
<para>
d904 1
a904 1
<programlisting>
d908 1
a908 1
</programlisting>
d913 1
a913 1
</para>
d915 1
a915 1
<para>
d924 1
a924 1
</para>
d926 1
a926 1
<para>
d932 1
a932 1
</para>
d987 1
a987 1
</para>
d989 1
a989 1
<para>
d997 1
a997 1
</para>
d999 1
a999 1
<para>
d1009 1
a1009 1
</para>
d1011 1
a1011 1
<para>
d1023 1
a1023 1
</para>
d1025 1
a1025 1
<para>
d1029 1
a1029 1
</para>
d1031 2
a1032 2
<sect3>
<title>A First Rule Step by Step</title>
d1034 1
a1034 1
<para>
d1041 1
a1041 1
<programlisting>
d1057 2
a1058 2
</programlisting>
</para>
d1060 1
a1060 1
<para>
d1063 1
a1063 1
<programlisting>
d1065 1
a1065 1
</programlisting>
d1069 1
a1069 1
<programlisting>
d1076 1
a1076 1
</programlisting>
d1083 1
a1083 1
<programlisting>
d1087 1
a1087 1
</programlisting>
d1092 1
a1092 1
<programlisting>
d1094 1
a1094 1
</programlisting>
d1098 1
a1098 1
<programlisting>
d1103 1
a1103 1
</programlisting>
d1111 1
a1111 1
</para>
d1113 1
a1113 1
<para>
d1119 1
a1119 1
<programlisting>
d1125 1
a1125 1
</programlisting>
d1130 1
a1130 1
<programlisting>
d1137 1
a1137 1
</programlisting>
d1150 1
a1150 1
<programlisting>
d1158 1
a1158 1
</programlisting>
d1166 1
a1166 1
<programlisting>
d1174 1
a1174 1
</programlisting>
d1181 1
a1181 1
<programlisting>
d1189 1
a1189 1
</programlisting>
d1197 1
a1197 1
<programlisting>
d1207 1
a1207 1
</programlisting>
d1217 1
a1217 1
<programlisting>
d1220 1
a1220 1
</programlisting>
d1228 1
a1228 1
<programlisting>
d1235 1
a1235 1
</programlisting>
d1244 1
a1244 1
<programlisting>
d1247 1
a1247 1
</programlisting>
d1254 1
a1254 1
<programlisting>
d1261 1
a1261 1
</programlisting>
d1265 1
a1265 1
</para>
d1267 1
a1267 1
<para>
d1273 2
a1274 2
</para>
</sect3>
d1276 1
a1276 1
</sect2>
d1278 2
a1279 2
<sect2 id="rules-update-views">
<title>Cooperation with Views</title>
d1283 1
a1283 1
<para>
d1289 1
a1289 1
<programlisting>
d1296 1
a1296 1
</programlisting>
d1305 1
a1305 1
</para>
d1307 1
a1307 1
<para>
d1314 1
a1314 1
<programlisting>
d1339 1
a1339 1
</programlisting>
d1350 1
a1350 1
<programlisting>
d1366 1
a1366 1
</programlisting>
d1371 1
a1371 1
<programlisting>
d1380 1
a1380 1
</programlisting>
d1384 1
a1384 1
<programlisting>
d1398 1
a1398 1
</programlisting>
d1402 1
a1402 1
<programlisting>
d1404 1
a1404 1
</programlisting>
d1408 1
a1408 1
<programlisting>
d1432 1
a1432 1
</programlisting>
d1441 1
a1441 1
<programlisting>
d1445 1
a1445 1
</programlisting>
d1450 1
a1450 1
<programlisting>
d1457 1
a1457 1
</programlisting>
d1464 1
a1464 1
<programlisting>
d1477 1
a1477 1
</programlisting>
d1484 1
a1484 1
<programlisting>
d1499 1
a1499 1
</programlisting>
d1504 1
a1504 1
<programlisting>
d1521 1
a1521 1
</programlisting>
d1529 1
a1529 1
    <acronym>SQL</acronym> statements
d1531 1
a1531 1
<programlisting>
d1550 1
a1550 1
</programlisting>
d1556 1
a1556 1
</para>
d1558 1
a1558 1
<para>
d1596 1
a1596 1
</para>
d1598 1
a1598 1
<para>
d1600 1
a1600 1
    <productname>PostgreSQL</productname> rule system and its power.
d1604 1
a1604 1
<programlisting>
d1607 1
a1607 1
</programlisting>
d1613 1
a1613 1
<programlisting>
d1617 1
a1617 1
</programlisting>
d1621 1
a1621 1
<programlisting>
d1628 1
a1628 1
</programlisting>
d1634 1
a1634 1
    To make it a little harder for <productname>PostgreSQL</productname>,
d1637 1
a1637 1
<programlisting>
d1640 1
a1640 1
</programlisting>
d1644 1
a1644 1
<programlisting>
d1648 1
a1648 1
</programlisting>
d1652 1
a1652 1
<programlisting>
d1667 1
a1667 1
</programlisting>
d1678 1
a1678 1
</para>
d1680 1
a1680 1
<para>
d1684 2
a1685 2
</para>
</sect2>
d1687 1
a1687 1
</sect1>
d1689 2
a1690 2
<sect1 id="rules-privileges">
<title>Rules and Privileges</title>
d1702 2
a1703 2
<para>
    Due to rewriting of queries by the <productname>PostgreSQL</productname>
d1707 1
a1707 1
</para>
d1709 1
a1709 1
<para>
d1713 1
a1713 1
    The <productname>PostgreSQL</productname> rule system changes the
d1719 1
a1719 1
</para>
d1721 1
a1721 1
<para>
d1726 1
a1726 1
<programlisting>
d1731 1
a1731 1
</programlisting>
d1747 1
a1747 1
</para>
d1749 1
a1749 1
<para>
d1760 1
a1760 1
</para>
d1762 1
a1762 1
<para>
d1771 1
a1771 1
</para>
d1773 1
a1773 1
<para>
d1783 2
a1784 2
</para>
</sect1>
d1786 2
a1787 2
<sect1 id="rules-status">
<title>Rules and Command Status</title>
d1789 2
a1790 2
<para>
    The <productname>PostgreSQL</productname> server returns a command
d1794 1
a1794 1
</para>
d1796 1
a1796 1
<para>
d1831 1
a1831 1
</para>
d1833 1
a1833 1
<para>
d1838 2
a1839 2
</para>
</sect1>
d1841 2
a1842 2
<sect1 id="rules-triggers">
<title>Rules versus Triggers</title>
d1854 1
a1854 1
<para>
d1856 1
a1856 1
    implemented using the <productname>PostgreSQL</productname>
d1865 1
a1865 1
</para>
d1867 1
a1867 1
<para>
d1875 1
a1875 1
</para>
d1877 1
a1877 1
<para>
d1887 1
a1887 1
</para>
d1889 1
a1889 1
<para>
d1893 1
a1893 1
<programlisting>
d1903 1
a1903 1
</programlisting>
d1910 1
a1910 1
<programlisting>
d1912 1
a1912 1
</programlisting>
d1919 1
a1919 1
<programlisting>
d1922 1
a1922 1
</programlisting>
d1928 1
a1928 1
<programlisting>
d1930 1
a1930 1
</programlisting>
d1936 1
a1936 1
<programlisting>
d1939 1
a1939 1
</programlisting>
d1960 1
a1960 1
<programlisting>
d1963 1
a1963 1
</programlisting>
d1967 1
a1967 1
<programlisting>
d1970 1
a1970 1
</programlisting>
d1983 1
a1983 1
<programlisting>
d1985 1
a1985 1
</programlisting>
d2010 1
a2010 1
</para>
d2012 1
a2012 1
<para>
d2015 1
a2015 1
<programlisting>
d2017 1
a2017 1
</programlisting>
d2023 1
a2023 1
<programlisting>
d2026 1
a2026 1
</programlisting>
d2031 1
a2031 1
<programlisting>
d2035 1
a2035 1
</programlisting>
d2040 1
a2040 1
</para>
d2044 1
a2044 1
<para>
d2047 1
a2047 1
    not. In <productname>PostgreSQL</productname> version 6.4, the
d2066 1
a2066 1
</para>
d2069 1
a2069 1
<para>
d2073 2
a2074 2
</para>
</sect1>
d2076 1
a2076 1
</chapter>
@


1.37.4.4
log
@We haven't had a fixed limit on rule recursion depth since 7.3 ...
but the documentation still said so.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.40 2005/01/23 00:30:18 momjian Exp $ -->
d1003 6
a1008 5
    So a rule's actions must have either a different
    command type or a different result relation than the rule itself is
    on, otherwise this recursive process will end up in an infinite loop.
    (Recursive expansion of a rule will be detected and reported as an
    error.)
@


1.37.4.5
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.37.4.4 2005/01/29 23:45:53 tgl Exp $ -->
d1649 1
a1649 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.36
log
@Replace "--" and "---" with "&mdash;" as appropriate, for better-looking
output.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.35 2004/05/16 23:22:07 neilc Exp $ -->
d107 2
a108 2
	In a <command>SELECT</command> statement these are the relations given after
	the <literal>FROM</literal> key word.
d113 7
a119 7
	by which name it is called in the other parts of the query.
	In the query tree, the range table entries are referenced by
	number rather than by name, so here it doesn't matter if there
	are duplicate names as it would in an <Acronym>SQL</Acronym>
	statement. This can happen after the range tables of rules
	have been merged in. The examples in this chapter will not have
	this situation.
d131 1
a131 1
	relation where the results of the query go.
d135 5
a139 5
	<command>SELECT</command> queries normally don't have a result
	relation. The special case of a <command>SELECT INTO</command> is
	mostly identical to a <command>CREATE TABLE</command> followed by a
	<literal>INSERT ... SELECT</literal> and is not discussed
	separately here.
d144 2
a145 2
	<command>DELETE</command> commands, the result relation is the table
	(or view!) where the changes take effect.
d170 4
a173 4
	because they don't produce any result. In fact, the planner will
	add a special <acronym>CTID</> entry to the empty target list, but
	this is after the rule system and will be discussed later; for the
	rule system, the target list is empty.
d178 8
a185 8
	the new rows that should go into the result relation. It consists of the
	expressions in the <literal>VALUES</> clause or the ones from the
	<command>SELECT</command> clause in <literal>INSERT
	... SELECT</literal>.  The first step of the rewrite process adds
	target list entries for any columns that were not assigned to by
	the original command but have defaults.  Any remaining columns (with
	neither a given value nor a default) will be filled in by the
	planner with a constant null expression.
d190 6
a195 6
	describes the new rows that should replace the old ones. In the
	rule system, it contains just the expressions from the <literal>SET
	column = expression</literal> part of the command.  The planner will handle
	missing columns by inserting expressions that copy the values from
	the old row into the new one. And it will add the special
	<acronym>CTID</> entry just as for <command>DELETE</command>, too.
d200 3
a202 3
	be a constant value, a variable pointing to a column of one
	of the relations in the range table, a parameter, or an expression
	tree made of function calls, constants, variables, operators, etc.
d214 6
a219 6
	those contained in the target list entries. The result value of
	this expression is a Boolean that tells whether the operation
	(<command>INSERT</command>, <command>UPDATE</command>,
	<command>DELETE</command>, or <command>SELECT</command>) for the
	final result row should be executed or not. It corresponds to the <literal>WHERE</> clause
	of an <Acronym>SQL</Acronym> statement.
d231 11
a241 11
	For a simple query like <literal>SELECT ... FROM a, b, c</literal>, the join tree is just
	a list of the <literal>FROM</> items, because we are allowed to join them in
	any order.  But when <literal>JOIN</> expressions, particularly outer joins,
	are used, we have to join in the order shown by the joins.
	In that case, the join tree shows the structure of the <literal>JOIN</> expressions.  The
	restrictions associated with particular <literal>JOIN</> clauses (from <literal>ON</> or
	<literal>USING</> expressions) are stored as qualification expressions attached
	to those join-tree nodes.  It turns out to be convenient to store
	the top-level <literal>WHERE</> expression as a qualification attached to the
	top-level join-tree item, too.  So really the join tree represents
	both the <literal>FROM</> and <literal>WHERE</> clauses of a <command>SELECT</command>.
d253 4
a256 4
	clause aren't of interest here. The rule system
	substitutes some entries there while applying rules, but that
	doesn't have much to do with the fundamentals of the rule
	system.
d325 1
a325 1
    it restricts <literal>ON SELECT</> rules to real view rules.
d698 3
a700 3
	<Para>
	    The range tables contain entries for the tables <literal>t1</> and <literal>t2</>.
	</Para>
d704 4
a707 4
	<Para>
	    The target lists contain one variable that points to column
	    <literal>b</> of the range table entry for table <literal>t2</>.
	</Para>
d711 4
a714 4
	<Para>
	    The qualification expressions compare the columns <literal>a</> of both
	    range-table entries for equality.
	</Para>
d718 3
a720 3
	<Para>
	    The join trees show a simple join between <literal>t1</> and <literal>t2</>.
	</Para>
d863 4
a866 4
	<Para>
	    They are allowed to have no action.
	</Para>
	</ListItem>
d869 4
a872 4
	<Para>
	    They can have multiple actions.
	</Para>
	</ListItem>
d875 4
a878 4
	<Para>
	    They can be <literal>INSTEAD</> or <literal>ALSO</> (default).
	</Para>
	</ListItem>
d881 4
a884 4
	<Para>
	    The pseudorelations <literal>NEW</> and <literal>OLD</> become useful.
	</Para>
	</ListItem>
d887 4
a890 4
	<Para>
	    They can have rule qualifications.
	</Para>
	</ListItem>
d1878 2
a1879 2
    For the things that can be implemented by both,
    it depends on the usage of the database, which is the best.
d1881 1
a1881 1
    the query tree or generates an additional one. So if many
d1883 1
a1883 1
    command would usually do a better job than a trigger that is
d1885 2
a1886 1
    many times.
@


1.35
log
@Add documentation for the new "dollar quoting" feature, and update existing
examples to use dollar quoting when appropriate. Original patch from David
Fetter, additional work and editorializing by Neil Conway.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/rules.sgml,v 1.34 2004/03/09 05:05:40 momjian Exp $ -->
d549 1
a549 1
    won't expand <literal>*OLD*</> or <literal>*NEW*</> --- otherwise we'd have infinite recursion!)
@


1.34
log
@Add ALSO keyword to CREATE RULE.

Fabien COELHO
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/rules.sgml,v 1.33 2003/12/13 23:59:06 neilc Exp $ -->
d346 1
a346 1
CREATE FUNCTION min(integer, integer) RETURNS integer AS '
d348 1
a348 1
' LANGUAGE SQL STRICT;
@


1.33
log
@This patch makes some SGML markup more consistent and makes a small
improvement to the SSL auth docs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/rules.sgml,v 1.32 2003/11/29 19:51:37 pgsql Exp $ -->
d876 1
a876 1
	    They can be <literal>INSTEAD</> or not.
d907 1
a907 1
    DO [INSTEAD] [<replaceable>action</> | (<replaceable>actions</>) | NOTHING];
d923 1
a923 1
    can have a qualification or not and it can be <literal>INSTEAD</> or not.
d940 1
a940 1
      <term>No qualification and not <literal>INSTEAD</></term>
d960 1
a960 1
      <term>Qualification given and not <literal>INSTEAD</></term>
d983 1
a983 1
    Finally, if the rule is not <literal>INSTEAD</>, the unchanged original query tree is
d1114 1
a1114 1
    The rule is a qualified non-<literal>INSTEAD</> rule, so the rule system
d1193 1
a1193 1
    That's it.  Since the rule is not <literal>INSTEAD</>, we also output the
@


1.32
log
@
$Header: -> $PostgreSQL Changes ...
@
text
@d1 1
a1 1
<!-- $PostgreSQL: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.31 2003/11/01 01:56:29 petere Exp $ -->
d1828 3
a1830 3
    (This system was established in PostgreSQL 7.3.  In versions
    before that, the command status might show different results when
    rules exist.)
@


1.31
log
@Spell checking, consistent terminology.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.30 2003/09/11 21:42:20 momjian Exp $ -->
@


1.31.2.1
log
@We haven't had a fixed limit on rule recursion depth since 7.3 ...
but the documentation still said so.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.31 2003/11/01 01:56:29 petere Exp $ -->
d1003 6
a1008 5
    So a rule's actions must have either a different
    command type or a different result relation than the rule itself is
    on, otherwise this recursive process will end up in an infinite loop.
    (Recursive expansion of a rule will be detected and reported as an
    error.)
@


1.31.2.2
log
@Use an entity instead of non-ASCII letter.  Thom Brown
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.31.2.1 2005/01/29 23:46:16 tgl Exp $ -->
d1649 1
a1649 1
    <foreignphrase>Voil&agrave;</foreignphrase>:
@


1.30
log
@This patch fixes a few missed GUC variables that were still upper case,
makes a few more small improvements to runtime.sgml, and makes some SGML
conventions more consistent.

Neil Conway
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.29 2003/08/31 17:32:19 petere Exp $ -->
d773 1
a773 1
    <acronym>CTID</>) and in the tuple header of the old row, which the
@


1.29
log
@Add/edit index entries.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.28 2003/04/11 13:22:35 petere Exp $ -->
d11 4
a14 4
     This chapter discusses the rule system in PostgreSQL.
     Production rule systems are conceptually simple, but
     there are many subtle points involved in actually using
     them.
d19 3
a21 2
     are usually stored procedures and triggers.  In PostgreSQL, these
     can be implemented using functions and triggers as well.
@


1.28
log
@Revision
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.27 2003/02/19 03:13:24 momjian Exp $ -->
d7 1
a7 1
  <primary>rules</primary>
d38 4
d153 1
d266 10
a275 1
<indexterm zone="rules-views"><primary>rules</><secondary>and views</></>
d303 1
a303 1
<Sect2>
d306 5
d758 1
a758 1
    (<acronym>CTID</>).  This is a system column containing the
d839 15
d1280 1
a1280 1
<indexterm zone="rules-update-views"><primary>views</><secondary>updating</></>
d1691 10
d1842 10
@


1.28.2.1
log
@Update this branch to match CVS head, includes WIN32 improvements.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.29 2003/08/31 17:32:19 petere Exp $ -->
d7 1
a7 1
  <primary>rule</primary>
a37 4
<indexterm zone="querytree">
 <primary>query tree</primary>
</indexterm>

a148 1
    <indexterm><primary>target list</></>
d261 1
a261 10

<indexterm zone="rules-views">
 <primary>rule</primary>
 <secondary>and views</secondary>
</indexterm>

<indexterm zone="rules-views">
 <primary>view</>
 <secondary>implementation through rules</>
</indexterm>
d289 1
a289 1
<Sect2 id="rules-select">
a291 5
<indexterm zone="rules-select">
 <primary>rule</primary>
 <secondary sortas="SELECT">for SELECT</secondary>
</indexterm>

d739 1
a739 1
    (<acronym>CTID</>).<indexterm><primary>CTID</></>  This is a system column containing the
a819 15
<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="INSERT">for INSERT</secondary>
</indexterm>

<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="UPDATE">for UPDATE</secondary>
</indexterm>

<indexterm zone="rules-update">
 <primary>rule</primary>
 <secondary sortas="DELETE">for DELETE</secondary>
</indexterm>

d1246 1
a1246 1
<indexterm zone="rules-update-views"><primary>view</><secondary>updating</></>
a1656 10
<indexterm zone="rules-privileges">
 <primary>privilege</primary>
 <secondary sortas="Regeln">with rules</secondary>
</indexterm>

<indexterm zone="rules-privileges">
 <primary>privilege</primary>
 <secondary sortas="Sichten">with views</secondary>
</indexterm>

a1797 10

<indexterm zone="rules-triggers">
 <primary>rule</primary>
 <secondary sortas="Trigger">compared with triggers</secondary>
</indexterm>

<indexterm zone="rules-triggers">
 <primary>trigger</primary>
 <secondary sortas="Regeln">compared with rules</secondary>
</indexterm>
@


1.27
log
@This patch includes more SGML markup fixes as well as a few minor
additions to the docs.

Neil Conway
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.26 2002/10/19 19:00:47 tgl Exp $ -->
a9 10
   <note>
    <title>Author</title>
    <para>
     Written by Jan Wieck.  Updates for 7.1 by Tom Lane.
    </para>
   </note>

   <sect1 id="rules-intro">
    <title>Introduction</title>

d11 1
d14 1
a14 4
     them. Some of these points and
     the theoretical foundations of the <ProductName>PostgreSQL</ProductName>
     rule system can be found in
<XRef LinkEnd="STON90b">.
d18 3
a20 3
     Some other database systems define active database rules. These
     are usually stored procedures and triggers and are implemented
     in <ProductName>PostgreSQL</ProductName> as functions and triggers.
d24 9
a32 11
     The query rewrite rule system (the <firstterm>rule system</> from now on) 
     is totally different from stored procedures and triggers.
     It modifies  queries  to
     take rules into consideration, and then passes the modified 
     query to the query planner for planning and execution.   It
     is  very powerful, and can be used for many things such
     as query language procedures, views, and versions.  The
     power  of  this  rule system is discussed in 
<XRef LinkEnd="ONG90">
 as well as
<XRef LinkEnd="STON90b">.
a34 2
  </sect1>

d36 1
a36 1
<Title>What is a Query Tree?</Title>
d44 4
a47 4
    The rule system is located between the query parser and the planner.
    It takes the output of the parser, one query tree, and the rewrite
    rules from the <structname>pg_rewrite</structname> catalog, which are
    query trees too with some extra information, and creates zero or many
d55 9
a63 7
    <Acronym>SQL</Acronym> statement where the single parts that built
    it are stored separately. These query trees are visible when starting
    the <ProductName>PostgreSQL</ProductName> backend with debug level 4
    and typing queries into the interactive backend interface. The rule
    actions in the <structname>pg_rewrite</structname> system catalog are
    also stored as query trees. They are not formatted like the debug
    output, but they contain exactly the same information.
d67 1
a67 5
    Reading a query tree requires some experience and it was a hard
    time when I started to work on the rule system. I can remember
    that I was standing at the coffee machine and I saw the cup
    in a target list, water and coffee powder in a range table and all
    the buttons in a qualification expression. Since 
d69 2
a70 4
    sufficient to understand the rule system, this document will
    not teach how to read them. It might help to learn
    it and the naming conventions are required in the later following
    descriptions.
a72 3
<Sect2>
<Title>The Parts of a Query tree</Title>

d75 1
a75 1
    query trees in this document it is necessary to be able to identify
d89 1
a89 1
        the parse tree.
d103 1
a103 1
	the FROM keyword.
d109 2
a110 2
	In the query tree the range table entries are referenced by
	index rather than by name, so here it doesn't matter if there
d113 1
a113 1
	have been merged in. The examples in this document will not have
d132 2
a133 2
	mostly identical to a <command>CREATE TABLE</command>,
	<literal>INSERT ... SELECT</literal> sequence and is not discussed
d138 2
a139 2
        On <command>INSERT</command>, <command>UPDATE</command> and
	<command>DELETE</command> queries the result relation is the table
d152 8
a159 7
	result of the query. In the case of a <command>SELECT</command>,
	the expressions are what builds the final output of the
	query. They are the expressions between the
	<command>SELECT</command> and the FROM keywords.
	(<literal>*</literal> is just an abbreviation for all the
	attribute names of a relation.  It is expanded by the parser into
	the individual attributes, so the rule system never sees it.)
d163 5
a167 5
        <command>DELETE</command> queries don't need a target list
	because they don't produce any result. In fact the planner will
	add a special <acronym>CTID</> entry to the empty target list. But
	this is after the rule system and will be discussed later. For the
	rule system the target list is empty.
d171 3
a173 3
        In <command>INSERT</command> queries the target list describes
	the new rows that should go into the result relation. It is the
	expressions in the VALUES clause or the ones from the
d177 1
a177 1
	the original query and have defaults.  Any remaining columns (with
d179 1
a179 1
	planner with a constant NULL expression.
d183 1
a183 1
        In <command>UPDATE</command> queries, the target list
d185 2
a186 2
	rule system, it contains just the expressions from the SET
	attribute = expression part of the query.  The planner will handle
d189 1
a189 1
	<acronym>CTID</> entry just as for <command>DELETE</command> too.
d194 1
a194 1
	be a constant value, a variable pointing to an attribute of one
d196 1
a196 1
	tree made of function calls, constants, variables, operators etc.
d209 1
a209 1
	this expression is a Boolean that tells if the operation
d211 2
a212 2
	<command>DELETE</command> or <command>SELECT</command>) for the
	final result row should be executed or not. It is the WHERE clause
d224 12
a235 12
        The query's join tree shows the structure of the FROM clause.
	For a simple query like SELECT FROM a, b, c the join tree is just
	a list of the FROM items, because we are allowed to join them in
	any order.  But when JOIN expressions --- particularly outer joins
	--- are used, we have to join in the order shown by the joins.
	The join tree shows the structure of the JOIN expressions.  The
	restrictions associated with particular JOIN clauses (from ON or
	USING expressions) are stored as qualification expressions attached
	to those join tree nodes.  It turns out to be convenient to store
	the top-level WHERE expression as a qualification attached to the
	top-level join tree item, too.  So really the join tree represents
	both the FROM and WHERE clauses of a <command>SELECT</command>.
d246 1
a246 1
        The other parts of the query tree like the ORDER BY 
d248 1
a248 1
	substitutes entries there while applying rules, but that
a256 1
</Sect2>
a262 3
<Sect2>
<Title>Implementation of Views in <ProductName>PostgreSQL</ProductName></Title>

d265 1
a265 1
    using the rule system. In fact there is essentially no difference
d275 1
a275 1
CREATE TABLE myview (<Replaceable>same attribute list as for mytab</Replaceable>);
d284 1
a284 1
    the same as it is for a table. So for the query parser, there is
d286 1
a286 1
    same thing - relations. That is the important one for now.
a287 1
</Sect2>
d293 1
a293 1
    Rules ON SELECT are applied to all queries as the last step, even
d296 2
a297 2
    have different semantics from the others in that they modify the
    parse tree in place instead of creating a new one.  So
d302 4
a305 4
    Currently, there can be only one action in an ON SELECT rule, and it must
    be an unconditional SELECT action that is INSTEAD. This restriction was
    required to make rules safe enough to open them for ordinary users and
    it restricts rules ON SELECT to real view rules.
d309 1
a309 1
    The examples for this document are two join views that do some
d312 1
a312 1
    <command>INSERT</command>, <command>UPDATE</command> and
d315 1
a315 1
    functionality.  It is not such a simple example to start from and
d322 2
a323 5
    The database needed to play with the examples is named <literal>al_bundy</literal>.
    You'll see soon why this is the database name. And it needs the
    procedural language <application>PL/pgSQL</> installed, because
    we need a little min() function returning the lower of 2
    integer values. We create that as
d327 2
a328 7
    BEGIN
        IF $1 < $2 THEN
            RETURN $1;
        END IF;
        RETURN $2;
    END;
' LANGUAGE plpgsql;
d338 6
a343 6
    shoename   char(10),      -- primary key
    sh_avail   integer,       -- available # of pairs
    slcolor    char(10),      -- preferred shoelace color
    slminlen   float,         -- miminum shoelace length
    slmaxlen   float,         -- maximum shoelace length
    slunit     char(8)        -- length unit
d347 5
a351 5
    sl_name    char(10),      -- primary key
    sl_avail   integer,       -- available # of pairs
    sl_color   char(10),      -- shoelace color
    sl_len     float,         -- shoelace length
    sl_unit    char(8)        -- length unit
d355 2
a356 2
    un_name    char(8),       -- the primary key
    un_fact    float          -- factor to transform to cm
d360 1
a360 4
    I think most of us wear shoes and can realize that this is
    really useful data. Well there are shoes out in the world
    that don't require shoelaces, but this doesn't make Al's
    life easier and so we ignore it.
d403 1
a403 1
    have) will create a relation shoelace and an entry in
d405 1
a405 1
    rewrite rule that must be applied whenever the relation shoelace
d407 6
a412 4
    qualification (discussed later, with the non SELECT rules, since
    SELECT rules currently cannot have them) and it is INSTEAD. Note
    that rule qualifications are not the same as query qualifications!
    The rule's action has a query qualification.
a413 4

<Para>
    The rule's action is one query tree that is a copy of the
    <command>SELECT</command> statement in the view creation command.
a415 1
    <Title>Note</Title>
d418 1
a418 1
    table entries for NEW and OLD (named *NEW* and *CURRENT* for
d421 1
a421 1
    for SELECT rules.
d425 1
d427 1
a427 2
    and <literal>shoelace_data</literal> and Al types the first 
    <command>SELECT</command> in his life:
d430 30
a459 41
al_bundy=> INSERT INTO unit VALUES ('cm', 1.0);
al_bundy=> INSERT INTO unit VALUES ('m', 100.0);
al_bundy=> INSERT INTO unit VALUES ('inch', 2.54);
al_bundy=> 
al_bundy=> INSERT INTO shoe_data VALUES 
al_bundy->     ('sh1', 2, 'black', 70.0, 90.0, 'cm');
al_bundy=> INSERT INTO shoe_data VALUES 
al_bundy->     ('sh2', 0, 'black', 30.0, 40.0, 'inch');
al_bundy=> INSERT INTO shoe_data VALUES 
al_bundy->     ('sh3', 4, 'brown', 50.0, 65.0, 'cm');
al_bundy=> INSERT INTO shoe_data VALUES 
al_bundy->     ('sh4', 3, 'brown', 40.0, 50.0, 'inch');
al_bundy=> 
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl1', 5, 'black', 80.0, 'cm');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl2', 6, 'black', 100.0, 'cm');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl3', 0, 'black', 35.0 , 'inch');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl4', 8, 'black', 40.0 , 'inch');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl5', 4, 'brown', 1.0 , 'm');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl6', 0, 'brown', 0.9 , 'm');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl7', 7, 'brown', 60 , 'cm');
al_bundy=> INSERT INTO shoelace_data VALUES 
al_bundy->     ('sl8', 1, 'brown', 40 , 'inch');
al_bundy=> 
al_bundy=> SELECT * FROM shoelace;
sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
----------+--------+----------+------+--------+---------
sl1       |       5|black     |    80|cm      |       80
sl2       |       6|black     |   100|cm      |      100
sl7       |       7|brown     |    60|cm      |       60
sl3       |       0|black     |    35|inch    |     88.9
sl4       |       8|black     |    40|inch    |    101.6
sl8       |       1|brown     |    40|inch    |    101.6
sl5       |       4|brown     |     1|m       |      100
sl6       |       0|brown     |   0.9|m       |       90
d462 1
d464 2
a465 1
    It's the simplest <command>SELECT</command> Al can do on our
d468 1
a468 1
    interpreted by the parser and produced the parse tree
d478 1
a478 1
    range table and checks if there are rules in <structname>pg_rewrite</structname>
d481 1
a481 1
    <literal>_RETURN</literal> rule with the parse tree
d484 1
a484 1
<emphasis>SELECT s.sl_name, s.sl_avail,
d486 1
a486 1
       float8mul(s.sl_len, u.un_fact) AS sl_len_cm
d489 1
a489 1
 WHERE bpchareq(s.sl_unit, u.un_name);</emphasis>
a490 4

    Note that the parser changed the calculation and qualification into
    calls to the appropriate functions. But
    in fact this changes nothing.
d494 2
a495 2
    To expand the view, the rewriter simply creates a subselect range-table
    entry containing the rule's action parse tree, and substitutes this
d497 1
a497 1
    resulting rewritten parse tree is almost the same as if Al had typed
d513 2
a514 2
     There is one difference however: the sub-query's range table has two
     extra entries shoelace *OLD*, shoelace *NEW*.  These entries don't
d516 2
a517 2
     the sub-query's join tree or target list.  The rewriter uses them
     to store the access permission check info that was originally present
d519 1
a519 1
     executor will still check that the user has proper permissions to access
d528 3
a530 3
    the added sub-query to see if any of them reference views.  (But it
    won't expand *OLD* or *NEW* --- otherwise we'd have infinite recursion!)
    In this example, there are no rewrite rules for shoelace_data or unit,
d536 2
a537 10
    Now we face Al with the problem that the Blues Brothers appear
    in his shop and
    want to buy some new shoes, and as the Blues Brothers are,
    they want to wear the same shoes. And they want to wear them
    immediately, so they need shoelaces too.
</Para>

<Para>
    Al needs to know for which shoes currently in the store
    he has the matching shoelaces (color and size) and where the
a538 1
    We teach him what to do and he asks his database:
d541 6
a546 5
al_bundy=> SELECT * FROM shoe_ready WHERE total_avail >= 2;
shoename  |sh_avail|sl_name   |sl_avail|total_avail
----------+--------+----------+--------+-----------
sh1       |       2|sl1       |       5|          2
sh3       |       4|sl7       |       7|          4
a548 4

    Al is a shoe guru and so he knows that only shoes of type sh1
    would fit (shoelace sl7 is brown and shoes that need brown shoelaces
    aren't shoes the Blues Brothers would ever wear).
d552 1
a552 1
    The output of the parser this time is the parse tree
d559 1
a559 1
 WHERE int4ge(shoe_ready.total_avail, 2);
d564 1
a564 1
    parse tree
d579 1
a579 1
 WHERE int4ge(shoe_ready.total_avail, 2);
d584 1
a584 1
    the sub-query, leading to a three-level final query tree:
d616 1
a616 1
 WHERE int4ge(shoe_ready.total_avail, 2);
d618 1
d620 12
a631 8
    It turns out that the planner will collapse this tree into a two-level
    query tree: the bottommost selects will be <quote>pulled up</quote> into the middle
    select since there's no need to process them separately.  But the
    middle select will remain separate from the top, because it contains
    aggregate functions.  If we pulled those up it would change the behavior
    of the topmost select, which we don't want.  However, collapsing the
    query tree is an optimization that the rewrite system doesn't
    have to concern itself with.
d633 1
a633 2
    <Note>
    <Title>Note</Title>
d638 1
a638 1
    endless loop (blowing up the backend until it reaches the memory
d646 1
a646 3
    </Note>
</Para>

d650 1
a650 1
<Title>View Rules in Non-SELECT Statements</Title>
d653 1
a653 1
    Two details of the parse tree aren't touched in the description of
d659 8
a666 7
    There are only a few differences between a parse tree for a
    <command>SELECT</command> and one for any other command. Obviously
    they have another command type and this time the result relation
    points to the range table entry where the result should
    go. Everything else is absolutely the same.  So having two tables
    t1 and t2 with attributes a and b, the parse trees for the two
    statements
d674 1
a674 1
    are nearly identical.
d679 1
a679 1
	    The range tables contain entries for the tables t1 and t2.
d685 2
a686 2
	    The target lists contain one variable that points to attribute
	    b of the range table entry for table t2.
d692 2
a693 2
	    The qualification expressions compare the attributes a of both
	    ranges for equality.
d699 1
a699 1
	    The join trees show a simple join between t1 and t2.
d703 1
d705 5
a709 4
    The consequence is, that both parse trees result in similar
    execution plans. They are both joins over the two tables. For the
    <command>UPDATE</command> the missing columns from t1 are added to
    the target list by the planner and the final parse tree will read
d724 1
a724 1
    <command>UPDATE</command>. The executor does not care what the
d729 3
a731 3
    executor. The caller still knows (looking at the parse tree) that
    this is an <command>UPDATE</command>, and he knows that this
    result should go into table t1. But which of the rows that are
d739 1
a739 1
    (<acronym>CTID</>).  This is a system attribute containing the
d742 1
a742 1
    original t1 row to be updated.  After adding the <acronym>CTID</>
d750 5
a754 5
    the stage. At this moment, table rows aren't overwritten and this
    is why ABORT TRANSACTION is fast. In an <command>UPDATE</command>,
    the new result row is inserted into the table (after stripping
    <acronym>CTID</>) and in the tuple header of the row that
    <acronym>CTID</> pointed to the <literal>cmax</> and
d756 1
a756 1
    and current transaction ID. Thus the old row is hidden and after
d772 1
a772 1
    definitions into the original parse tree. In the second example a
d774 1
a774 1
    parse tree that is a join of 4 tables (unit is used twice with
a777 3
<Sect3>
<Title>Benefits</Title>

d785 1
a785 1
    in one single parse tree. And this is still the situation
d787 2
a788 2
    Now the planner has to decide which is
    the best path to execute the query. The more information
d792 1
a792 1
    up to now.
a793 1
</Sect3>
d797 1
a797 2
<Title>What about updating a view?</Title>
<indexterm zone="rules-views-update"><primary>views</><secondary>updating</></>
d804 1
a804 1
    relation points at a subquery range table entry.  This will not
d810 2
a811 3
    To change this we can define rules that modify the behavior of
    non-<command>SELECT</command> queries. This is the topic of the
    next section.
d817 2
a818 5
<Sect1 id="rules-insert">
<Title>Rules on INSERT, UPDATE and DELETE</Title>

<Sect2>
<Title>Differences from View Rules</Title>
d821 4
a824 4
    Rules that are defined ON INSERT, UPDATE and DELETE are totally
    different from the view rules described in the previous
    section. First, their <command>CREATE RULE</command> command
    allows more:
d829 1
a829 1
	    They can have no action.
d841 1
a841 1
	    The keyword INSTEAD is optional.
d847 1
a847 1
	    The pseudo relations NEW and OLD become useful.
d858 2
a859 2
    Second, they don't modify the parse tree in place. Instead they
    create zero or many new parse trees and can throw away the
d862 1
a862 1
</sect2>
d864 1
a864 1
<Title>How These Rules Work</Title>
d870 3
a872 3
CREATE RULE rule_name AS ON event
    TO object [WHERE rule_qualification]
    DO [INSTEAD] [action | (actions) | NOTHING];
d877 1
a877 1
    ON INSERT, UPDATE or DELETE.
d882 1
a882 1
    relation and the command type of a parse tree are equal to the
d884 5
a888 5
    For update rules, the rule system creates a list of parse trees.
    Initially the parse tree list is empty.
    There can be zero (NOTHING keyword), one or multiple actions.
    To simplify, we look at a rule with one action. This rule
    can have a qualification or not and it can be INSTEAD or not.
d894 2
a895 2
    qualification can only reference the NEW and/or OLD pseudo relations
    which are basically the relation given as object (but with a
d899 2
a900 2
<Para>
    So we have four cases that produce the following parse trees for
a901 45
</Para>
<Para>
    <ItemizedList>
    <ListItem>
    <Para>
        No qualification and not INSTEAD:
        <ItemizedList>
	    <ListItem>
	    <Para>
	        The parse tree from the rule action where the
		original parse tree's qualification has been added.
	    </Para>
	    </ListItem>
	</ItemizedList>
    </Para>
    </ListItem>

    <ListItem>
    <Para>
        No qualification but INSTEAD:
        <ItemizedList>
	    <ListItem>
	    <Para>
	        The parse tree from the rule action where the
		original parse tree's qualification has been added.
	    </Para>
	    </ListItem>
	</ItemizedList>
    </Para>
    </ListItem>

    <ListItem>
    <Para>
        Qualification given and not INSTEAD:
        <ItemizedList>
	    <ListItem>
	    <Para>
	        The parse tree from the rule action where the rule
		qualification and the original parse tree's 
		qualification have been added.
	    </Para>
	    </ListItem>
	</ItemizedList>
    </Para>
    </ListItem>
d903 48
a950 27
    <ListItem>
    <Para>
        Qualification given and INSTEAD:
        <ItemizedList>
	    <ListItem>
	    <Para>
	        The parse tree from the rule action where the rule
		qualification and the original parse tree's 
		qualification have been added.
	    </Para>
	    </ListItem>

	    <ListItem>
	    <Para>
	        The original parse tree where the negated rule
		qualification has been added.
	    </Para>
	    </ListItem>
	</ItemizedList>
    </Para>
    </ListItem>
    </ItemizedList>
</para>
<Para>
    Finally, if the rule is not INSTEAD, the unchanged original parse tree is
    added to the list. Since only qualified INSTEAD rules already add the
    original parse tree, we end up with either one or two output parse trees
d955 1
a955 1
    For ON INSERT rules, the original query (if not suppressed by INSTEAD)
d957 2
a958 2
    see the inserted row(s).  But for ON UPDATE and ON
    DELETE rules, the original query is done after the actions added by rules.
d965 7
a971 7
    The parse trees generated from rule actions are thrown into the
    rewrite system again and maybe more rules get applied resulting
    in more or less parse trees.
    So the parse trees in the rule actions must have either another command type
    or another result relation. Otherwise this recursive process will end up in a loop.
    There is a compiled-in recursion limit of currently 100 iterations.
    If after 100 iterations there are still update rules to apply the
d977 1
a977 1
    The parse trees found in the actions of the
d980 2
a981 2
    NEW and OLD, some substitutions have to be made before they can be
    used. For any reference to NEW, the target list of the original
d983 4
a986 4
    entry's expression replaces the reference. Otherwise NEW means the
    same as OLD (for an <command>UPDATE</command>) or is replaced by
    NULL (for an <command>INSERT</command>). Any reference to OLD is
    replaced by a reference to the range-table entry which is the
d991 2
a992 2
    After we are done applying update rules, we apply view rules to the
    produced parse tree(s).  Views cannot insert new update actions so
d1000 2
a1001 2
    We want to trace changes to the sl_avail column in the
    <literal>shoelace_data</literal> relation. So we setup a log table
d1008 1
a1008 1
    sl_name    char(10),      -- shoelace changed
d1015 1
a1015 1
    WHERE NEW.sl_avail != OLD.sl_avail
d1026 1
a1026 1
    Now Al does
d1029 1
a1029 2
al_bundy=> UPDATE shoelace_data SET sl_avail = 6                       
al_bundy->     WHERE sl_name = 'sl7';
d1032 1
a1032 1
    and we look at the log table.
d1035 5
a1039 4
al_bundy=> SELECT * FROM shoelace_log;
sl_name   |sl_avail|log_who|log_when                        
----------+--------+-------+--------------------------------
sl7       |       6|Al     |Tue Oct 20 16:14:45 1998 MET DST
d1042 1
d1044 1
d1046 1
a1046 3
    The parser created the parse tree (this time the parts of the original
    parse tree are highlighted because the base of operations is the
    rule action for update rules).
d1049 1
a1049 1
<emphasis>UPDATE shoelace_data SET sl_avail = 6
d1051 1
a1051 1
 WHERE bpchareq(shoelace_data.sl_name, 'sl7');</emphasis>
d1054 1
a1054 1
    There is a rule <literal>log_shoelace</literal> that is ON UPDATE with the rule
d1058 1
a1058 1
int4ne(NEW.sl_avail, OLD.sl_avail)
d1061 1
a1061 1
    and one action
d1064 1
a1064 1
INSERT INTO shoelace_log VALUES(
d1066 1
a1066 1
       current_user, current_timestamp)
d1070 6
a1075 5
    This is a little strange-looking since you can't normally write
    INSERT ... VALUES ... FROM.  The FROM clause here is just to indicate
    that there are range-table entries in the parse tree for *NEW* and *OLD*.
    These are needed so that they can be referenced by variables in the
    <command>INSERT</command> command's query tree.
d1079 4
a1082 4
    The rule is a qualified non-INSTEAD rule, so the rule system
    has to return two parse trees: the modified rule action and the original
    parse tree. In the first step the range table of the original query is
    incorporated into the rule's action parse tree. This results in
d1085 1
a1085 1
INSERT INTO shoelace_log VALUES(
d1087 1
a1087 1
       current_user, current_timestamp)
d1092 2
a1093 2
    In step 2 the rule qualification is added to it, so the result set
    is restricted to rows where sl_avail changes.
d1096 1
a1096 1
INSERT INTO shoelace_log VALUES(
d1098 1
a1098 1
       current_user, current_timestamp)
d1101 1
a1101 1
 <emphasis>WHERE int4ne(*NEW*.sl_avail, *OLD*.sl_avail)</emphasis>;
d1104 2
a1105 2
    This is even stranger-looking, since INSERT ... VALUES doesn't have
    a WHERE clause either, but the planner and executor will have no
d1107 1
a1107 1
    anyway for INSERT ... SELECT.
d1111 3
a1113 3
    In step 3 the original parse tree's qualification is added,
    restricting the result set further to only the rows touched
    by the original parse tree.
d1116 1
a1116 1
INSERT INTO shoelace_log VALUES(
d1118 1
a1118 1
       current_user, current_timestamp)
d1121 2
a1122 2
 WHERE int4ne(*NEW*.sl_avail, *OLD*.sl_avail)
   <emphasis>AND bpchareq(shoelace_data.sl_name, 'sl7')</emphasis>;
d1124 1
d1126 4
a1129 3
    Step 4 replaces NEW references by the target list entries from the
    original parse tree or by the matching variable references
    from the result relation.
d1132 1
a1132 1
INSERT INTO shoelace_log VALUES(
d1134 1
a1134 1
       current_user, current_timestamp)
d1137 2
a1138 2
 WHERE int4ne(<emphasis>6</emphasis>, *OLD*.sl_avail)
   AND bpchareq(shoelace_data.sl_name, 'sl7');
d1141 4
a1144 1
    Step 5 changes OLD references into result relation references.
d1147 1
a1147 1
INSERT INTO shoelace_log VALUES(
d1149 1
a1149 1
       current_user, current_timestamp)
d1152 2
a1153 2
 WHERE int4ne(6, <emphasis>shoelace_data.sl_avail</emphasis>)
   AND bpchareq(shoelace_data.sl_name, 'sl7');
d1155 1
d1157 4
a1160 3
    That's it.  Since the rule is not INSTEAD, we also output the
    original parse tree.  In short, the output from the rule system
    is a list of two parse trees that are the same as the statements:
d1163 1
a1163 1
INSERT INTO shoelace_log VALUES(
d1165 1
a1165 1
       current_user, current_timestamp)
d1167 1
a1167 1
 WHERE 6 != shoelace_data.sl_avail
d1174 7
a1180 3
    These are executed in this order and that is exactly what
    the rule defines. The substitutions and the qualifications
    added ensure that if the original query would be, say,
d1187 5
a1191 4
    no log entry would get written.  This
    time the original parse tree does not contain a target list
    entry for sl_avail, so NEW.sl_avail will get replaced by
    shoelace_data.sl_avail resulting in the extra query
d1194 1
a1194 1
INSERT INTO shoelace_log VALUES(
d1196 1
a1196 1
       current_user, current_timestamp)
d1198 1
a1198 1
 WHERE <emphasis>shoelace_data.sl_avail</emphasis> != shoelace_data.sl_avail
d1202 6
a1207 3
    and that qualification will never be true. It will also
    work if the original query modifies multiple rows. So if Al
    would issue the command
d1214 4
a1217 4
    four rows in fact get updated (sl1, sl2, sl3 and sl4).
    But sl3 already has sl_avail = 0. This time, the original
    parse trees qualification is different and that results
    in the extra parse tree
d1220 2
a1221 2
INSERT INTO shoelace_log SELECT
       shoelace_data.sl_name, 0,
d1224 1
a1224 1
 WHERE 0 != shoelace_data.sl_avail
d1228 2
a1229 2
    This parse tree will surely insert three new log entries. And
    that's absolutely correct.
d1233 5
a1237 5
    Here we can see why it is important that the original parse tree
    is executed last.  If the <command>UPDATE</command> would have
    been executed first, all the rows are already set to zero, so the
    logging <command>INSERT</command> would not find any row where 0
    != shoelace_data.sl_avail.
d1243 1
a1243 1
<Sect2>
d1246 2
d1250 3
a1252 3
    possibility that someone can try to <command>INSERT</command>,
    <command>UPDATE</command> and <command>DELETE</command> on them is
    to let those parse trees get thrown away. We create the rules
d1263 1
a1263 1
    If Al now tries to do any of these operations on the view
d1265 3
a1267 3
    apply the rules. Since the rules have
    no actions and are INSTEAD, the resulting list of
    parse trees will be empty and the whole query will become
d1274 1
a1274 1
    create rules that rewrite the parse tree into one that
d1287 2
a1288 1
           NEW.sl_unit);
d1292 2
a1293 2
    UPDATE shoelace_data SET
           sl_name = NEW.sl_name,
d1305 1
d1307 7
a1313 6
    Now there is a pack of shoelaces arriving in Al's shop and it has
    a big part list. Al is not that good in calculating and so
    we don't want him to manually update the shoelace view.
    Instead we setup two little tables, one where he can
    insert the items from the part list and one with a special
    trick. The create commands for these are:
d1317 1
a1317 1
    arr_name    char(10),
d1322 1
a1322 1
    ok_name     char(10),
d1328 2
a1329 2
    UPDATE shoelace SET
           sl_avail = sl_avail + NEW.ok_quant
d1333 2
a1334 1
    Now Al can sit down and do whatever until
d1337 7
a1343 6
al_bundy=> SELECT * FROM shoelace_arrive;
arr_name  |arr_quant
----------+---------
sl3       |       10
sl6       |       20
sl8       |       20
d1347 1
a1347 2
    is exactly what's on the part list. We take a quick look
    at the current data,
d1350 12
a1361 11
al_bundy=> SELECT * FROM shoelace;
sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
----------+--------+----------+------+--------+---------
sl1       |       5|black     |    80|cm      |       80
sl2       |       6|black     |   100|cm      |      100
sl7       |       6|brown     |    60|cm      |       60
sl3       |       0|black     |    35|inch    |     88.9
sl4       |       8|black     |    40|inch    |    101.6
sl8       |       1|brown     |    40|inch    |    101.6
sl5       |       4|brown     |     1|m       |      100
sl6       |       0|brown     |   0.9|m       |       90
d1365 1
a1365 1
    move the arrived shoelaces in
d1368 1
a1368 1
al_bundy=> INSERT INTO shoelace_ok SELECT * FROM shoelace_arrive;
d1371 1
a1371 1
    and check the results
d1374 12
a1385 11
al_bundy=> SELECT * FROM shoelace ORDER BY sl_name;
sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
----------+--------+----------+------+--------+---------
sl1       |       5|black     |    80|cm      |       80
sl2       |       6|black     |   100|cm      |      100
sl7       |       6|brown     |    60|cm      |       60
sl4       |       8|black     |    40|inch    |    101.6
sl3       |      10|black     |    35|inch    |     88.9
sl8       |      21|brown     |    40|inch    |    101.6
sl5       |       4|brown     |     1|m       |      100
sl6       |      20|brown     |   0.9|m       |       90
d1388 8
a1395 7
al_bundy=> SELECT * FROM shoelace_log;
sl_name   |sl_avail|log_who|log_when                        
----------+--------+-------+--------------------------------
sl7       |       6|Al     |Tue Oct 20 19:14:45 1998 MET DST
sl3       |      10|Al     |Tue Oct 20 19:25:16 1998 MET DST
sl6       |      20|Al     |Tue Oct 20 19:25:16 1998 MET DST
sl8       |      21|Al     |Tue Oct 20 19:25:16 1998 MET DST
d1398 1
d1400 5
a1404 3
    It's a long way from the one INSERT ... SELECT to these
    results. And its description will be the last in this
    document (but not the last example :-). First there was the parser's output
d1407 2
a1408 2
INSERT INTO shoelace_ok SELECT
       shoelace_arrive.arr_name, shoelace_arrive.arr_quant
d1412 1
a1412 1
    Now the first rule <literal>shoelace_ok_ins</literal> is applied and turns it
d1416 2
a1417 2
UPDATE shoelace SET
       sl_avail = int4pl(shoelace.sl_avail, shoelace_arrive.arr_quant)
d1421 1
a1421 1
 WHERE bpchareq(shoelace.sl_name, showlace_arrive.arr_name);
d1426 2
a1427 2
    the rule system again and the second applied rule
    <literal>shoelace_upd</literal> produced
d1430 3
a1432 3
UPDATE shoelace_data SET
       sl_name = shoelace.sl_name,
       sl_avail = int4pl(shoelace.sl_avail, shoelace_arrive.arr_quant),
d1439 3
a1441 3
       shoelace *NEW*, shoelace_data showlace_data
 WHERE bpchareq(shoelace.sl_name, showlace_arrive.arr_name)
   AND bpchareq(shoelace_data.sl_name, shoelace.sl_name);
d1444 1
a1444 1
    Again it's an INSTEAD rule and the previous parse tree is trashed.
d1446 2
a1447 2
    But the rule system isn't finished with this loop so it continues
    and applies the <literal>_RETURN</literal> rule on it and we get
d1450 3
a1452 3
UPDATE shoelace_data SET
       sl_name = s.sl_name,
       sl_avail = int4pl(s.sl_avail, shoelace_arrive.arr_quant),
d1459 1
a1459 1
       shoelace *NEW*, shoelace_data showlace_data,
d1462 2
a1463 2
 WHERE bpchareq(s.sl_name, showlace_arrive.arr_name)
   AND bpchareq(shoelace_data.sl_name, s.sl_name);
d1466 2
a1467 4
    Again an update rule has been applied and so the wheel
    turns on and we are in rewrite round 3. This time rule
    <literal>log_shoelace</literal> gets applied, producing the extra
    parse tree
d1470 3
a1472 3
INSERT INTO shoelace_log SELECT
       s.sl_name,
       int4pl(s.sl_avail, shoelace_arrive.arr_quant),
d1478 1
a1478 1
       shoelace *NEW*, shoelace_data showlace_data,
d1483 3
a1485 3
 WHERE bpchareq(s.sl_name,  showlace_arrive.arr_name)
   AND bpchareq(shoelace_data.sl_name, s.sl_name);
   AND int4ne(int4pl(s.sl_avail, shoelace_arrive.arr_quant), s.sl_avail);
d1489 5
a1493 2
    generated parse trees.
    So we end up with two final parse trees that are equal to the
d1497 2
a1498 2
INSERT INTO shoelace_log SELECT
       s.sl_name,
d1506 1
a1506 1
   AND s.sl_avail + shoelace_arrive.arr_quant != s.sl_avail;
d1508 2
a1509 2
UPDATE shoelace_data SET
       sl_avail = shoelace_data.sl_avail + shoelace_arrive.arr_quant
d1525 1
a1525 1
    queries turns out, that the <literal>shoelace_data</literal>
d1531 1
a1531 1
<ProgramListing>
d1541 1
a1541 1
</ProgramListing>
d1545 1
a1545 1
<ProgramListing>
d1553 1
a1553 1
</ProgramListing>
d1555 4
a1558 4
    that totally produces the same entries in the log relation.  Thus,
    the rule system caused one extra scan on the
    <literal>shoelace_data</literal> relation that is absolutely not
    necessary. And the same obsolete scan is done once more in the
d1564 4
a1567 21
    A final demonstration of the <ProductName>PostgreSQL</ProductName>
    rule system and its power. There is a cute blonde that
    sells shoelaces. And what Al could never realize, she's not
    only cute, she's smart too - a little too smart. Thus, it
    happens from time to time that Al orders shoelaces that
    are absolutely not sellable. This time he ordered 1000 pairs
    of magenta shoelaces and since another kind is currently not
    available but he committed to buy some, he also prepared
    his database for pink ones.

<ProgramListing>
al_bundy=> INSERT INTO shoelace VALUES 
al_bundy->     ('sl9', 0, 'pink', 35.0, 'inch', 0.0);
al_bundy=> INSERT INTO shoelace VALUES 
al_bundy->     ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0);
</ProgramListing>

    Since this happens often, we must lookup for shoelace entries,
    that fit for absolutely no shoe sometimes. We could do that in
    a complicated statement every time, or we can setup a view
    for it. The view for this is
d1570 10
a1579 1
CREATE VIEW shoelace_obsolete AS
d1587 6
a1592 5
al_bundy=> SELECT * FROM shoelace_obsolete;
sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
----------+--------+----------+------+--------+---------
sl9       |       0|pink      |    35|inch    |     88.9
sl10      |    1000|magenta   |    40|inch    |    101.6
d1594 1
d1596 3
a1598 2
    For the 1000 magenta shoelaces we must debit Al before we can
    throw 'em away, but that's another problem. The pink entry we delete.
d1603 2
a1604 2
CREATE VIEW shoelace_candelete AS
    SELECT * FROM shoelace_obsolete WHERE sl_avail = 0;
d1611 1
a1611 1
    (SELECT * FROM shoelace_candelete
d1618 13
a1630 12
al_bundy=> SELECT * FROM shoelace;
sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
----------+--------+----------+------+--------+---------
sl1       |       5|black     |    80|cm      |       80
sl2       |       6|black     |   100|cm      |      100
sl7       |       6|brown     |    60|cm      |       60
sl4       |       8|black     |    40|inch    |    101.6
sl3       |      10|black     |    35|inch    |     88.9
sl8       |      21|brown     |    40|inch    |    101.6
sl10      |    1000|magenta   |    40|inch    |    101.6
sl5       |       4|brown     |     1|m       |      100
sl6       |      20|brown     |   0.9|m       |       90
d1633 1
d1635 2
a1636 1
    A DELETE on a view, with a subselect qualification that
d1638 1
a1638 1
    itself has a subselect qualification containing a view
d1641 1
a1641 1
    one single parse tree that deletes the requested data
d1646 3
a1648 3
    I think there are only a few situations out in the real
    world, where such a construct is necessary. But
    it makes me feel comfortable that it works.
a1649 8

    <formalpara>
    <Title>The truth is:</Title>
    <Para>
    Doing this I found one more bug while writing this document.
    But after fixing that I was a little amazed that it works at all.
    </Para>
    </formalpara>
d1654 2
a1655 2
<Sect1 id="rules-permissions">
<Title>Rules and Permissions</Title>
d1660 1
a1660 1
    query get accessed. Using update rules, this can include write access
d1671 3
a1673 3
    permissions of the rule owner, not the user invoking the rule.
    This means, that a user does only need the required permissions
    for the tables/views he names in his queries. 
d1682 1
a1682 1
CREATE TABLE phone_data (person text, phone text, private bool);
d1689 13
a1701 11
    phone_data table. But due to the GRANT, the secretary can
    <command>SELECT</command> from the phone_number view. The rule
    system will rewrite the <command>SELECT</command> from
    phone_number into a <command>SELECT</command> from phone_data and
    add the qualification that only entries where private is false are
    wanted. Since the user is the owner of phone_number, the read
    access to phone_data is now checked against his permissions and
    the query is considered granted. The check for accessing
    phone_number is also performed, but this is done against the
    invoking user, so nobody but the user and the secretary can use
    it.
d1705 1
a1705 1
    The permissions are checked rule by rule. So the secretary is for now the
d1707 2
a1708 2
    another view and grant access to that to public. Then, anyone
    can see the phone_number data through the secretaries view.
d1710 2
a1711 2
    accesses phone_data (actually he can, but it will not work since
    every access aborts the transaction during the permission checks).
d1713 2
a1714 2
    his phone_number view, he can REVOKE his access. Immediately any
    access to the secretaries view will fail.
d1718 3
a1720 3
    Someone might think that this rule by rule checking is a security
    hole, but in fact it isn't. If this would not work, the secretary
    could setup a table with the same columns as phone_number and
d1723 1
a1723 1
    <command>GRANT</command> means <quote>I trust you</quote>.
d1725 1
a1725 1
    think it over and then <command>REVOKE</command>.
d1729 9
a1737 16
    This mechanism does also work for update rules. In the examples
    of the previous section, the owner of the tables in Al's database
    could GRANT SELECT, INSERT, UPDATE and DELETE on the shoelace view to al.
    But only SELECT on shoelace_log. The rule action to write log entries
    will still be executed successfully. And Al could see the log entries.
    But he cannot create fake entries, nor could he manipulate or remove
    existing ones.

    <Note>
    <Title>Warning</Title>
    <Para>
    GRANT ALL currently includes RULE permission. This means the granted
    user could drop the rule, do the changes and reinstall it. I think
    this should get changed quickly.
    </Para>
    </Note>
d1747 1
a1747 1
    query it receives.  This is simple enough when there are no rules
d1752 1
a1752 2
    As of <ProductName>PostgreSQL</ProductName> 7.3, rules affect the
    command status as follows:
d1754 1
a1754 1
    <orderedlist>
d1757 1
a1757 1
       If there is no unconditional INSTEAD rule for the query, then
d1760 1
a1760 1
       any conditional INSTEAD rules, the negation of their qualifications
d1769 1
a1769 1
       If there is any unconditional INSTEAD rule for the query, then
d1772 2
a1773 2
       that was inserted by an INSTEAD rule (conditional or
       unconditional) and is of the same type
d1778 1
a1778 1
       zeroes for the tuple-count and OID fields.
d1781 5
a1785 1
    </orderedlist>
d1789 1
a1789 1
    The programmer can ensure that any desired INSTEAD rule is the one
d1792 1
a1792 1
    fires last.
d1802 3
a1804 3
    rule system. What currently cannot be implemented by
    rules are some kinds of constraints. It is possible,
    to place a qualified rule that rewrites a query to NOTHING
d1809 1
a1809 1
    be generated, it must be done by a trigger for now.
d1813 2
a1814 2
    On the other hand a trigger that is fired on
    <command>INSERT</command> on a view can do the same as a rule, put
d1818 1
a1818 1
    view relation that could be scanned and thus the trigger would
d1825 2
a1826 2
    A trigger is fired for any row affected once. A rule manipulates
    the parse tree or generates an additional one. So if many
d1828 3
a1830 3
    query would usually do a better job than a trigger that is
    called for any single row and must execute his operations
    this many times.
d1834 2
a1835 1
    For example: There are two tables
d1849 4
a1852 7
    Both tables have many
    thousands of rows and the index on <structfield>hostname</> is unique.
    The <structfield>hostname</> column contains the full qualified domain
    name of the computer. The rule/trigger should constraint
    delete rows from software that reference the deleted host.
    Since the trigger is called for each individual row
    deleted from computer, it can use the statement
d1858 4
a1861 2
    in a prepared and saved plan and pass the <structfield>hostname</> in
    the parameter. The rule would be written as
d1867 1
d1869 1
d1876 3
a1878 3
    the table computer is scanned by index (fast) and the
    query issued by the trigger would also be an index scan (fast too).
    The extra query from the rule would be a
d1888 1
a1888 1
<ProgramListing>
d1892 1
a1892 1
</ProgramListing>
d1895 8
a1902 3
    the trigger and the rule implementation. With the next delete
    we want to get rid of all the 2000 computers where the <structfield>hostname</> starts
    with 'old'. There are two possible queries to do that. One is
d1909 1
a1909 1
    Where the plan for the rule query will be a 
d1912 7
d1923 1
a1923 1
</ProgramListing>
d1925 1
a1925 1
    The other possible query is a
d1931 2
a1932 1
    with the execution plan
d1934 1
a1934 1
<ProgramListing>
d1938 1
a1938 1
</ProgramListing>
d1941 13
a1953 13
    qualification for the <structfield>hostname</> on computer could also be
    used for an index scan on software when there are
    multiple qualification expressions combined with AND, what
    he does in the regexp version of the query. The trigger will
    get invoked once for any of the 2000 old computers that
    have to be deleted and that will result in one index scan
    over computer and 2000 index scans for the software. The
    rule implementation will do it with two queries over indexes.
    And it depends on the overall size of the software table if
    the rule will still be faster in the sequential scan situation. 2000
    query executions over the SPI manager take some time, even
    if all the index blocks to look them up will soon appear in
    the cache.
d1957 1
a1957 1
    The last query we look at is a
d1964 2
a1965 3
    computer. So the trigger will again fire many queries into
    the executor. But the rule plan will again be the nested loop over
    two index scans. Only using another index on computer:
d1968 2
a1969 3
Nestloop
  ->  Index Scan using comp_manufidx on computer
  ->  Index Scan using soft_hostidx on software
d1972 2
a1973 1
    resulting from the rules query
d1976 3
a1978 2
DELETE FROM software WHERE computer.manufacurer = 'bim'
                       AND software.hostname = computer.hostname;
d1981 3
a1983 3
    In any of these cases, the extra queries from the rule system will be
    more or less independent from the number of affected rows
    in a query. 
d1986 2
d2011 1
d2014 3
a2016 5
    Rules will only be significantly slower than triggers if
    their actions result in large and bad qualified joins, a situation
    where the planner fails. They are a big hammer.
    Using a big hammer without caution can cause big damage. But
    used with the right touch, they can hit any nail on the head.
@


1.26
log
@Fix rewrite code so that rules are in fact executed in order by name,
rather than being reordered according to INSTEAD attribute for
implementation convenience.
Also, increase compiled-in recursion depth limit from 10 to 100 rewrite
cycles.  10 seems pretty marginal for situations where multiple rules
exist for the same query.  There was a complaint about this recently,
so I'm going to bump it up.  (Perhaps we should make the limit a GUC
parameter, but that's too close to being a new feature to do in beta.)
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.25 2002/10/14 22:14:34 tgl Exp $ -->
d62 1
a62 1
    rules from the <FileName>pg_rewrite</FileName> catalog, which are
d75 1
a75 1
    actions in the <FileName>pg_rewrite</FileName> system catalog are
d110 3
a112 1
	(SELECT, INSERT, UPDATE, DELETE) produced the parse tree.
d125 1
a125 1
	In a SELECT statement these are the relations given after
d153 5
a157 5
	SELECT queries
	normally don't have a result relation. The special case
	of a SELECT INTO is mostly identical to a CREATE TABLE,
	INSERT ... SELECT sequence and is not discussed separately
	here.
d161 3
a163 2
        On INSERT, UPDATE and DELETE queries the result relation
	is the table (or view!) where the changes take effect.
d174 8
a181 7
        The target list is a list of expressions that define the result
	of the query. In the case of a SELECT, the expressions are what
	builds the final output of the query. They are the expressions
	between the SELECT and the FROM keywords.  (* is just an
	abbreviation for all the attribute names of a relation.  It is
	expanded by the parser into the individual attributes, so the
	rule system never sees it.)
d185 5
a189 5
        DELETE queries don't need a target list because they don't
	produce any result. In fact the planner will add a special <acronym>CTID</>
	entry to the empty target list. But this is after the rule
	system and will be discussed later. For the rule system the
	target list is empty.
d193 8
a200 7
        In INSERT queries the target list describes the new rows that
	should go into the result relation. It is the expressions in the VALUES
	clause or the ones from the SELECT clause in INSERT ... SELECT.
	The first step of the rewrite process adds target list entries
	for any columns that were not assigned to by the original query
	and have defaults.  Any remaining columns (with neither a given
	value nor a default) will be filled in by the
d205 7
a211 6
        In UPDATE queries, the target list describes the new rows that should
	replace the old ones. In the rule system, it contains just the
	expressions from the SET attribute = expression part of the query.
	The planner will handle missing columns by inserting expressions that
	copy the values from the old row into the new one. And it will add
	the special <acronym>CTID</> entry just as for DELETE too.
d229 7
a235 6
        The query's qualification is an expression much like one of those
	contained in the target list entries. The result value of this
	expression is a Boolean that tells if the operation
	(INSERT, UPDATE, DELETE or SELECT) for the final result row should be
	executed or not. It is the WHERE clause of an
	<Acronym>SQL</Acronym> statement.
d257 1
a257 1
	both the FROM and WHERE clauses of a SELECT.
d306 7
a312 7
    because this is exactly what the CREATE VIEW command does internally.
    This has some side effects. One of them is that
    the information about a view in the <ProductName>PostgreSQL</ProductName>
    system catalogs is exactly the same as it is for a table. So for the
    query parser, there is absolutely no difference between
    a table and a view. They are the same thing - relations. That is the
    important one for now.
d317 1
a317 1
<Title>How SELECT Rules Work</Title>
d320 6
a325 6
    Rules ON SELECT are applied to all queries as the
    last step, even if the command
    given is an INSERT, UPDATE or DELETE. And they have different
    semantics from the others in that they modify the parse tree in
    place instead of creating a new one.
    So SELECT rules are described first.
d336 10
a345 9
    The examples for this document are two join views that do some calculations
    and some more views using them in turn.
    One of the two first views is customized later by adding rules for
    INSERT, UPDATE and DELETE operations so that the final result will
    be a view that behaves like a real table with some magic functionality.
    It is not such a simple example to start from and this makes things
    harder to get into. But it's better to have one example that covers
    all the points discussed step by step rather than having many
    different ones that might mix up in mind.
d439 10
a448 10
    The CREATE VIEW command for the <Filename>shoelace</Filename> 
    view (which is the simplest one we have)
    will create a relation shoelace and an entry 
    in <FileName>pg_rewrite</FileName>
    that tells that there is a rewrite rule that must be applied
    whenever the relation shoelace is referenced in a query's range table.
    The rule has no rule qualification (discussed later, with the
    non SELECT rules, since SELECT rules currently cannot have them) and
    it is INSTEAD. Note that rule qualifications are not the same as
    query qualifications! The rule's action has a query qualification.
d453 1
a453 1
    SELECT statement in the view creation command.
d461 1
a461 1
    the <Filename>pg_rewrite</Filename> entry aren't of interest
d466 3
a468 3
    Now we populate <Filename>unit</Filename>, <Filename>shoe_data</Filename>
    and <Filename>shoelace_data</Filename> and Al types the first 
    SELECT in his life:
d515 4
a518 4
    It's the simplest SELECT Al can do on our views, so we take this
    to explain the basics of view rules.
    The <literal>SELECT * FROM shoelace</literal> was interpreted by the parser and
    produced the parse tree
d528 1
a528 1
    range table and checks if there are rules in <Filename>pg_rewrite</Filename>
d530 1
a530 1
    <Filename>shoelace</Filename> (the only one up to now) it finds the
d629 1
a629 1
    <Filename>shoe_ready</Filename> view and it results in the
d648 2
a649 2
    Similarly, the rules for <Filename>shoe</Filename> and
    <Filename>shoelace</Filename> are substituted into the range table of
d697 10
a706 11
    There is currently no recursion stopping mechanism for view
    rules in the rule system (only for the other kinds of rules).
    This doesn't hurt much, because the only way to push this
    into an endless loop (blowing up the
    backend until it reaches the memory limit)
    is to create tables and then setup the
    view rules by hand with CREATE RULE in such a way, that
    one selects from the other that selects from the one.
    This could never happen if CREATE VIEW is used because
    for the first CREATE VIEW, the second relation does not exist
    and thus the first view cannot select from the second.
d723 7
a729 6
    There are only a few differences between a parse tree for a SELECT
    and one for any other command. Obviously they have another command type
    and this time the result relation points to the range table entry where
    the result should go. Everything else is absolutely the same. 
    So having two tables t1 and t2 with attributes
    a and b, the parse trees for the two statements
d767 5
a771 4
    The consequence is, that both parse trees result in similar execution
    plans. They are both joins over the two tables. For the UPDATE
    the missing columns from t1 are added to the target list by the planner 
    and the final parse tree will read as
d784 10
a793 8
    will do. But there is a little problem in UPDATE. The executor does
    not care what the results from the join it is doing are meant
    for. It just produces a result set of rows. The difference that one
    is a SELECT command and the other is an UPDATE is handled in the
    caller of the executor. The caller still knows (looking at the
    parse tree) that this is an UPDATE, and he knows that this result
    should go into table t1. But which of the rows that are there
    has to be replaced by the new row?
d798 7
a804 5
    in UPDATE (and also in DELETE) statements: the current tuple ID (<acronym>CTID</>).
    This is a system attribute containing the file
    block number and position in the block for the row. Knowing the table,
    the <acronym>CTID</> can be used to retrieve the original t1 row to be updated.
    After adding the <acronym>CTID</> to the target list, the query actually looks like
d812 8
a819 7
    is why ABORT TRANSACTION is fast. In an UPDATE, the new result row
    is inserted into the table (after stripping <acronym>CTID</>) and
    in the tuple header of the row that <acronym>CTID</> pointed to
    the <literal>cmax</> and <literal>xmax</> entries are set to the
    current command counter and current transaction ID. Thus the old
    row is hidden and after the transaction committed the vacuum
    cleaner can really move it out.
d832 5
a836 4
    The above demonstrates how the rule system incorporates
    view definitions into the original parse tree. In the second example
    a simple SELECT from one view created a final parse tree that is
    a join of 4 tables (unit is used twice with different names).
d866 7
a872 5
    What happens if a view is named as the target relation for an INSERT,
    UPDATE, or DELETE?  After doing the substitutions described above,
    we will have a query tree in which the result relation points at a
    subquery range table entry.  This will not work, so the rewriter throws
    an error if it sees it has produced such a thing.
d876 3
a878 2
    To change this we can define rules that modify the behavior
    of non-SELECT queries. This is the topic of the next section.
d891 4
a894 4
    Rules that are defined ON INSERT, UPDATE and DELETE are
    totally different from the view rules described
    in the previous section. First, their CREATE RULE
    command allows more:
d953 1
a953 1
    object and event given in the CREATE RULE command.
d1071 11
a1081 9
    The parse trees found in the actions of the <Filename>pg_rewrite</Filename>
    system catalog are only templates. Since they can reference the
    range-table entries for NEW and OLD, some substitutions have to be made
    before they can be used. For any reference to NEW, the target list of
    the original query is searched for a corresponding entry. If found,
    that entry's expression replaces the reference. Otherwise
    NEW means the same as OLD (for an UPDATE) or is replaced by NULL
    (for an INSERT). Any reference to OLD is replaced by a
    reference to the range-table entry which is the result relation.
d1095 4
a1098 3
    <Filename>shoelace_data</Filename> relation. So we setup a
    log table and a rule that conditionally writes a log entry when
    an UPDATE is performed on <Filename>shoelace_data</Filename>.
d1168 1
a1168 1
    INSERT command's query tree.
d1311 5
a1315 5
    Here we can see why it is important that the original parse tree is
    executed last.
    If the UPDATE would have been executed first, all the rows
    are already set to zero, so the logging INSERT
    would not find any row where 0 != shoelace_data.sl_avail.
d1326 3
a1328 3
    possibility that someone can try to INSERT, UPDATE and DELETE
    on them is to let those parse trees get
    thrown away. We create the rules
d1340 1
a1340 1
    relation <Filename>shoe</Filename>, the rule system will
d1352 1
a1352 1
    on the <Filename>shoelace</Filename> view, we create
d1490 4
a1493 3
    and throws away the original INSERT on <Filename>shoelace_ok</Filename>.
    This rewritten query is passed to the rule system again and
    the second applied rule <literal>shoelace_upd</literal> produced
d1511 1
a1511 1
    Note that this query still uses the view <Filename>shoelace</Filename>.
d1589 6
a1594 5
    There is a little detail that's a bit ugly. Looking at
    the two queries turns out, that the <Filename>shoelace_data</Filename>
    relation appears twice in the range table where it could definitely
    be reduced to one. The planner does not handle it and so the
    execution plan for the rule systems output of the INSERT will be
d1620 6
a1625 6
    that totally produces the same entries in the log relation.
    Thus, the rule system caused one extra scan on the
    <Filename>shoelace_data</Filename> relation that is
    absolutely not necessary. And the same obsolete scan
    is done once more in the UPDATE. But it was a really hard
    job to make that all possible at all.
d1764 11
a1774 9
    phone_data table. But due to the GRANT, the secretary can SELECT from the
    phone_number view. The rule system will rewrite
    the SELECT from phone_number into a SELECT from phone_data and add the qualification
    that only entries where private is false are wanted. Since the
    user is the owner of phone_number, the read access to phone_data
    is now checked against his permissions and the query is considered
    granted. The check for accessing phone_number is also performed,
    but this is done against the invoking user, so nobody but the user and the
    secretary can use it.
d1795 2
a1796 1
    he can grant access to everyone he wants. A GRANT means <quote>I trust you</quote>.
d1798 1
a1798 1
    think it over and then REVOKE.
d1852 8
a1859 6
       the server will return the command status for the last query that
       was inserted by an INSTEAD rule (conditional or unconditional)
       and is of the same type (INSERT, UPDATE, or DELETE) as the original
       query.  If no query meeting those requirements is added by any
       rule, then the returned command status shows the original query
       type and zeroes for the tuple-count and OID fields.
d1890 7
a1896 7
    On the other hand a trigger that is fired on INSERT 
    on a view can do the same as a rule, put the data somewhere
    else and suppress the insert in the view. But it cannot
    do the same thing on UPDATE or DELETE, because there is
    no real data in the view relation that could be scanned
    and thus the trigger would never get called. Only a rule
    will help.
d2049 1
a2049 1
    Another situation is cases on UPDATE where it depends on the
@


1.25
log
@Adjust handling of command status strings in the presence of rules,
as per recent pghackers discussions.  initdb forced due to change in
fields of stored Query nodes.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.24 2002/09/21 18:32:53 petere Exp $ -->
d1046 2
a1047 2
    There is a compiled in recursion limit of currently 10 iterations.
    If after 10 iterations there are still update rules to apply the
@


1.24
log
@Add more appropriate markup.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/rules.sgml,v 1.23 2002/04/19 23:13:53 tgl Exp $ -->
d192 4
a195 1
	Missing columns of the result relation will be filled in by the
d203 1
a203 1
	The planner will add missing columns by inserting expressions that
d284 2
a285 2
    using the rule system. In fact there is absolutely no difference
    between a
d1139 1
a1139 1
       current_user, current_timestamp
d1159 1
a1159 1
       current_user, current_timestamp
d1170 1
a1170 1
       current_user, current_timestamp
d1180 1
d1182 1
d1190 1
a1190 1
       current_user, current_timestamp
d1197 2
a1198 2
    Step 4 substitutes NEW references by the target list entries from the
    original parse tree or with the matching variable references
d1204 1
a1204 1
       current_user, current_timestamp
d1216 1
a1216 1
       current_user, current_timestamp
d1230 1
a1230 1
       current_user, current_timestamp
a1324 12

    <Note>
    <Title>Note</Title>
    <Para>
    This way might irritate frontend applications because
    absolutely nothing happened on the database and thus, the
    backend will not return anything for the query. Not
    even a <symbol>PGRES_EMPTY_QUERY</symbol> will be available in <application>libpq</>.
    In <application>psql</application>, nothing happens. This might change in the future.
    </Para>
    </Note>

d1512 1
a1512 1
    <literal>log_shoelace</literal> gets applied what produces the extra
d1644 1
a1644 1
    For the 1000 magenta shoelaces we must debt Al before we can
d1792 50
@


1.23
log
@Change naming rule for ON SELECT rules of views: they're all just
_RETURN now, since there's no need to keep 'em unique anymore.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.22 2002/03/22 19:20:26 petere Exp $ -->
d182 1
a182 1
	produce any result. In fact the planner will add a special CTID
d202 1
a202 1
	the special CTID entry just as for DELETE too.
d784 1
a784 1
    in UPDATE (and also in DELETE) statements: the current tuple ID (CTID).
d787 2
a788 2
    the CTID can be used to retrieve the original t1 row to be updated.
    After adding the CTID to the target list, the query actually looks like
d794 9
a802 8
    Now another detail of <ProductName>PostgreSQL</ProductName> enters the
    stage. At this moment, table rows aren't overwritten and this is why
    ABORT TRANSACTION is fast. In an UPDATE, the new result row is inserted
    into the table (after stripping CTID) and in the tuple header of the row 
    that CTID pointed to the cmax and xmax entries are set to the current
    command counter and current transaction ID. Thus the old row is hidden
    and after the transaction committed the vacuum cleaner can really move
    it out.
@


1.22
log
@Spell checking and markup additions
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.21 2002/01/20 22:19:56 petere Exp $ -->
d292 1
a292 1
CREATE RULE "_RETmyview" AS ON SELECT TO myview DO INSTEAD
d520 1
a520 1
    rule <literal>_RETshoelace</literal> with the parse tree
d1497 1
a1497 1
    and applies the rule <literal>_RETshoelace</literal> on it and we get
@


1.21
log
@Spell-check and markup police
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.20 2002/01/07 02:29:13 petere Exp $ -->
d1143 1
a1143 1
    INSERT command's querytree.
@


1.20
log
@Editorial review
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.19 2001/11/21 06:09:45 thomas Exp $ -->
d285 1
a285 1
    CREATE VIEW myview AS SELECT * FROM mytab;
d291 3
a293 3
    CREATE TABLE myview (<Replaceable>same attribute list as for mytab</Replaceable>);
    CREATE RULE "_RETmyview" AS ON SELECT TO myview DO INSTEAD
        SELECT * FROM mytab;
d345 8
a352 8
    CREATE FUNCTION min(integer, integer) RETURNS integer AS
        'BEGIN
            IF $1 < $2 THEN
                RETURN $1;
            END IF;
            RETURN $2;
        END;'
    LANGUAGE 'plpgsql';
d361 21
a381 21
    CREATE TABLE shoe_data (
        shoename   char(10),      -- primary key
        sh_avail   integer,       -- available # of pairs
        slcolor    char(10),      -- preferred shoelace color
        slminlen   float,         -- miminum shoelace length
        slmaxlen   float,         -- maximum shoelace length
        slunit     char(8)        -- length unit
    );

    CREATE TABLE shoelace_data (
        sl_name    char(10),      -- primary key
        sl_avail   integer,       -- available # of pairs
        sl_color   char(10),      -- shoelace color
        sl_len     float,         -- shoelace length
        sl_unit    char(8)        -- length unit
    );

    CREATE TABLE unit (
        un_name    char(8),       -- the primary key
        un_fact    float          -- factor to transform to cm
    );
d394 32
a425 32
    CREATE VIEW shoe AS
        SELECT sh.shoename,
               sh.sh_avail,
               sh.slcolor,
               sh.slminlen,
               sh.slminlen * un.un_fact AS slminlen_cm,
               sh.slmaxlen,
               sh.slmaxlen * un.un_fact AS slmaxlen_cm,
               sh.slunit
          FROM shoe_data sh, unit un
         WHERE sh.slunit = un.un_name;

    CREATE VIEW shoelace AS
        SELECT s.sl_name,
               s.sl_avail,
               s.sl_color,
               s.sl_len,
               s.sl_unit,
               s.sl_len * u.un_fact AS sl_len_cm
          FROM shoelace_data s, unit u
         WHERE s.sl_unit = u.un_name;

    CREATE VIEW shoe_ready AS
        SELECT rsh.shoename,
               rsh.sh_avail,
               rsl.sl_name,
               rsl.sl_avail,
               min(rsh.sh_avail, rsl.sl_avail) AS total_avail
          FROM shoe rsh, shoelace rsl
         WHERE rsl.sl_color = rsh.slcolor
           AND rsl.sl_len_cm >= rsh.slminlen_cm
           AND rsl.sl_len_cm <= rsh.slmaxlen_cm;
d460 42
a501 42
    al_bundy=> INSERT INTO unit VALUES ('cm', 1.0);
    al_bundy=> INSERT INTO unit VALUES ('m', 100.0);
    al_bundy=> INSERT INTO unit VALUES ('inch', 2.54);
    al_bundy=> 
    al_bundy=> INSERT INTO shoe_data VALUES 
    al_bundy->     ('sh1', 2, 'black', 70.0, 90.0, 'cm');
    al_bundy=> INSERT INTO shoe_data VALUES 
    al_bundy->     ('sh2', 0, 'black', 30.0, 40.0, 'inch');
    al_bundy=> INSERT INTO shoe_data VALUES 
    al_bundy->     ('sh3', 4, 'brown', 50.0, 65.0, 'cm');
    al_bundy=> INSERT INTO shoe_data VALUES 
    al_bundy->     ('sh4', 3, 'brown', 40.0, 50.0, 'inch');
    al_bundy=> 
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl1', 5, 'black', 80.0, 'cm');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl2', 6, 'black', 100.0, 'cm');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl3', 0, 'black', 35.0 , 'inch');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl4', 8, 'black', 40.0 , 'inch');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl5', 4, 'brown', 1.0 , 'm');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl6', 0, 'brown', 0.9 , 'm');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl7', 7, 'brown', 60 , 'cm');
    al_bundy=> INSERT INTO shoelace_data VALUES 
    al_bundy->     ('sl8', 1, 'brown', 40 , 'inch');
    al_bundy=> 
    al_bundy=> SELECT * FROM shoelace;
    sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
    ----------+--------+----------+------+--------+---------
    sl1       |       5|black     |    80|cm      |       80
    sl2       |       6|black     |   100|cm      |      100
    sl7       |       7|brown     |    60|cm      |       60
    sl3       |       0|black     |    35|inch    |     88.9
    sl4       |       8|black     |    40|inch    |    101.6
    sl8       |       1|brown     |    40|inch    |    101.6
    sl5       |       4|brown     |     1|m       |      100
    sl6       |       0|brown     |   0.9|m       |       90
    (8 rows)
d507 1
a507 1
    produced the parsetree
d510 4
a513 4
    SELECT shoelace.sl_name, shoelace.sl_avail,
           shoelace.sl_color, shoelace.sl_len,
           shoelace.sl_unit, shoelace.sl_len_cm
      FROM shoelace shoelace;
d523 6
a528 6
    <FirstTerm>SELECT s.sl_name, s.sl_avail,
           s.sl_color, s.sl_len, s.sl_unit,
           float8mul(s.sl_len, u.un_fact) AS sl_len_cm
      FROM shoelace *OLD*, shoelace *NEW*,
           shoelace_data s, unit u
     WHERE bpchareq(s.sl_unit, u.un_name);</FirstTerm>
d537 2
a538 2
    To expand the view, the rewriter simply creates a subselect rangetable
    entry containing the rule's action parsetree, and substitutes this
d543 11
a553 11
    SELECT shoelace.sl_name, shoelace.sl_avail,
           shoelace.sl_color, shoelace.sl_len,
           shoelace.sl_unit, shoelace.sl_len_cm
      FROM (SELECT s.sl_name,
                   s.sl_avail,
                   s.sl_color,
                   s.sl_len,
                   s.sl_unit,
                   s.sl_len * u.un_fact AS sl_len_cm
              FROM shoelace_data s, unit u
             WHERE s.sl_unit = u.un_name) shoelace;
d561 1
a561 1
     in the rangetable entry that referenced the view.  In this way, the
d569 2
a570 2
    the remaining rangetable entries in the top query (in this example there
    are no more), and it will recursively check the rangetable entries in
d593 6
a598 6
    al_bundy=> SELECT * FROM shoe_ready WHERE total_avail >= 2;
    shoename  |sh_avail|sl_name   |sl_avail|total_avail
    ----------+--------+----------+--------+-----------
    sh1       |       2|sl1       |       5|          2
    sh3       |       4|sl7       |       7|          4
    (2 rows)
d610 5
a614 5
    SELECT shoe_ready.shoename, shoe_ready.sh_avail,
           shoe_ready.sl_name, shoe_ready.sl_avail,
           shoe_ready.total_avail
      FROM shoe_ready shoe_ready
     WHERE int4ge(shoe_ready.total_avail, 2);
d622 13
a634 13
    SELECT shoe_ready.shoename, shoe_ready.sh_avail,
           shoe_ready.sl_name, shoe_ready.sl_avail,
           shoe_ready.total_avail
      FROM (SELECT rsh.shoename,
                   rsh.sh_avail,
                   rsl.sl_name,
                   rsl.sl_avail,
                   min(rsh.sh_avail, rsl.sl_avail) AS total_avail
              FROM shoe rsh, shoelace rsl
             WHERE rsl.sl_color = rsh.slcolor
               AND rsl.sl_len_cm >= rsh.slminlen_cm
               AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
     WHERE int4ge(shoe_ready.total_avail, 2);
d642 30
a671 30
    SELECT shoe_ready.shoename, shoe_ready.sh_avail,
           shoe_ready.sl_name, shoe_ready.sl_avail,
           shoe_ready.total_avail
      FROM (SELECT rsh.shoename,
                   rsh.sh_avail,
                   rsl.sl_name,
                   rsl.sl_avail,
                   min(rsh.sh_avail, rsl.sl_avail) AS total_avail
              FROM (SELECT sh.shoename,
                           sh.sh_avail,
                           sh.slcolor,
                           sh.slminlen,
                           sh.slminlen * un.un_fact AS slminlen_cm,
                           sh.slmaxlen,
                           sh.slmaxlen * un.un_fact AS slmaxlen_cm,
                           sh.slunit
                      FROM shoe_data sh, unit un
                     WHERE sh.slunit = un.un_name) rsh,
                   (SELECT s.sl_name,
                           s.sl_avail,
                           s.sl_color,
                           s.sl_len,
                           s.sl_unit,
                           s.sl_len * u.un_fact AS sl_len_cm
                      FROM shoelace_data s, unit u
                     WHERE s.sl_unit = u.un_name) rsl
             WHERE rsl.sl_color = rsh.slcolor
               AND rsl.sl_len_cm >= rsh.slminlen_cm
               AND rsl.sl_len_cm <= rsh.slmaxlen_cm) shoe_ready
     WHERE int4ge(shoe_ready.total_avail, 2);
d721 1
a721 1
    SELECT t2.b FROM t1, t2 WHERE t1.a = t2.a;
d723 1
a723 1
    UPDATE t1 SET b = t2.b WHERE t1.a = t2.a;
d762 1
a762 1
    UPDATE t1 SET a = t1.a, b = t2.b WHERE t1.a = t2.a;
d769 1
a769 1
    SELECT t1.a, t2.b FROM t1, t2 WHERE t1.a = t2.a;
d784 1
a784 1
    in UPDATE (and also in DELETE) statements: the current tuple ID (ctid).
d787 2
a788 2
    the ctid can be used to retrieve the original t1 row to be updated.
    After adding the ctid to the target list, the query actually looks like
d791 1
a791 1
    SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;
d797 2
a798 2
    into the table (after stripping ctid) and in the tuple header of the row 
    that ctid pointed to the cmax and xmax entries are set to the current
d918 3
a920 3
    CREATE RULE rule_name AS ON event
        TO object [WHERE rule_qualification]
        DO [INSTEAD] [action | (actions) | NOTHING];
d1049 1
a1049 1
    The parsetrees found in the actions of the <Filename>pg_rewrite</Filename>
d1051 2
a1052 2
    rangetable entries for NEW and OLD, some substitutions have to be made
    before they can be used. For any reference to NEW, the targetlist of
d1057 1
a1057 1
    reference to the rangetable entry which is the resultrelation.
d1062 1
a1062 1
    produced parsetree(s).  Views cannot insert new update actions so
d1076 15
a1090 15
    CREATE TABLE shoelace_log (
        sl_name    char(10),      -- shoelace changed
        sl_avail   integer,       -- new available value
        log_who    text,          -- who did it
        log_when   timestamp      -- when
    );

    CREATE RULE log_shoelace AS ON UPDATE TO shoelace_data
        WHERE NEW.sl_avail != OLD.sl_avail
        DO INSERT INTO shoelace_log VALUES (
                                        NEW.sl_name,
                                        NEW.sl_avail,
                                        current_user,
                                        current_timestamp
                                    );
d1098 2
a1099 2
    al_bundy=> UPDATE shoelace_data SET sl_avail = 6                       
    al_bundy->     WHERE sl_name = 'sl7';
d1102 1
a1102 1
    and we look at the logtable.
d1105 5
a1109 5
    al_bundy=> SELECT * FROM shoelace_log;
    sl_name   |sl_avail|log_who|log_when                        
    ----------+--------+-------+--------------------------------
    sl7       |       6|Al     |Tue Oct 20 16:14:45 1998 MET DST
    (1 row)
d1113 2
a1114 2
    The parser created the parsetree (this time the parts of the original
    parsetree are highlighted because the base of operations is the
d1118 3
a1120 3
    <FirstTerm>UPDATE shoelace_data SET sl_avail = 6
      FROM shoelace_data shoelace_data
     WHERE bpchareq(shoelace_data.sl_name, 'sl7');</FirstTerm>
d1127 1
a1127 1
    int4ne(NEW.sl_avail, OLD.sl_avail)
d1133 4
a1136 4
    INSERT INTO shoelace_log VALUES(
           *NEW*.sl_name, *NEW*.sl_avail,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*;
d1141 1
a1141 1
    that there are rangetable entries in the parsetree for *NEW* and *OLD*.
d1149 1
a1149 1
    parsetree. In the first step the range table of the original query is
d1153 5
a1157 5
    INSERT INTO shoelace_log VALUES(
           *NEW*.sl_name, *NEW*.sl_avail,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           <FirstTerm>shoelace_data shoelace_data</FirstTerm>;
d1164 6
a1169 6
    INSERT INTO shoelace_log VALUES(
           *NEW*.sl_name, *NEW*.sl_avail,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           shoelace_data shoelace_data
     <FirstTerm>WHERE int4ne(*NEW*.sl_avail, *OLD*.sl_avail)</FirstTerm>;
d1182 7
a1188 7
    INSERT INTO shoelace_log VALUES(
           *NEW*.sl_name, *NEW*.sl_avail,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           shoelace_data shoelace_data
     WHERE int4ne(*NEW*.sl_avail, *OLD*.sl_avail)
       <FirstTerm>AND bpchareq(shoelace_data.sl_name, 'sl7')</FirstTerm>;
d1196 7
a1202 7
    INSERT INTO shoelace_log VALUES(
           <FirstTerm>shoelace_data.sl_name</FirstTerm>, <FirstTerm>6</FirstTerm>,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           shoelace_data shoelace_data
     WHERE int4ne(<FirstTerm>6</FirstTerm>, *OLD*.sl_avail)
       AND bpchareq(shoelace_data.sl_name, 'sl7');
d1208 7
a1214 7
    INSERT INTO shoelace_log VALUES(
           shoelace_data.sl_name, 6,
           current_user, current_timestamp
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           shoelace_data shoelace_data
     WHERE int4ne(6, <FirstTerm>shoelace_data.sl_avail</FirstTerm>)
       AND bpchareq(shoelace_data.sl_name, 'sl7');
d1222 6
a1227 6
    INSERT INTO shoelace_log VALUES(
           shoelace_data.sl_name, 6,
           current_user, current_timestamp
      FROM shoelace_data
     WHERE 6 != shoelace_data.sl_avail
       AND shoelace_data.sl_name = 'sl7';
d1229 2
a1230 2
    UPDATE shoelace_data SET sl_avail = 6
     WHERE sl_name = 'sl7';
d1238 2
a1239 2
    UPDATE shoelace_data SET sl_color = 'green'
     WHERE sl_name = 'sl7';
d1248 6
a1253 6
    INSERT INTO shoelace_log VALUES(
           shoelace_data.sl_name, <FirstTerm>shoelace_data.sl_avail</FirstTerm>,
           current_user, current_timestamp)
      FROM shoelace_data
     WHERE <FirstTerm>shoelace_data.sl_avail</FirstTerm> != shoelace_data.sl_avail
       AND shoelace_data.sl_name = 'sl7';
d1261 2
a1262 2
    UPDATE shoelace_data SET sl_avail = 0
     WHERE sl_color = 'black';
d1271 6
a1276 6
    INSERT INTO shoelace_log SELECT
           shoelace_data.sl_name, 0,
           current_user, current_timestamp
      FROM shoelace_data
     WHERE 0 != shoelace_data.sl_avail
       AND <FirstTerm>shoelace_data.sl_color = 'black'</FirstTerm>;
d1304 6
a1309 6
    CREATE RULE shoe_ins_protect AS ON INSERT TO shoe
        DO INSTEAD NOTHING;
    CREATE RULE shoe_upd_protect AS ON UPDATE TO shoe
        DO INSTEAD NOTHING;
    CREATE RULE shoe_del_protect AS ON DELETE TO shoe
        DO INSTEAD NOTHING;
d1341 23
a1363 23
    CREATE RULE shoelace_ins AS ON INSERT TO shoelace
        DO INSTEAD
        INSERT INTO shoelace_data VALUES (
               NEW.sl_name,
               NEW.sl_avail,
               NEW.sl_color,
               NEW.sl_len,
               NEW.sl_unit);

    CREATE RULE shoelace_upd AS ON UPDATE TO shoelace
        DO INSTEAD
        UPDATE shoelace_data SET
               sl_name = NEW.sl_name,
               sl_avail = NEW.sl_avail,
               sl_color = NEW.sl_color,
               sl_len = NEW.sl_len,
               sl_unit = NEW.sl_unit
         WHERE sl_name = OLD.sl_name;

    CREATE RULE shoelace_del AS ON DELETE TO shoelace
        DO INSTEAD
        DELETE FROM shoelace_data
         WHERE sl_name = OLD.sl_name;
d1374 15
a1388 15
    CREATE TABLE shoelace_arrive (
        arr_name    char(10),
        arr_quant   integer
    );

    CREATE TABLE shoelace_ok (
        ok_name     char(10),
        ok_quant    integer
    );

    CREATE RULE shoelace_ok_ins AS ON INSERT TO shoelace_ok
        DO INSTEAD
        UPDATE shoelace SET
               sl_avail = sl_avail + NEW.ok_quant
         WHERE sl_name = NEW.ok_name;
d1394 7
a1400 7
    al_bundy=> SELECT * FROM shoelace_arrive;
    arr_name  |arr_quant
    ----------+---------
    sl3       |       10
    sl6       |       20
    sl8       |       20
    (3 rows)
d1407 12
a1418 12
    al_bundy=> SELECT * FROM shoelace;
    sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
    ----------+--------+----------+------+--------+---------
    sl1       |       5|black     |    80|cm      |       80
    sl2       |       6|black     |   100|cm      |      100
    sl7       |       6|brown     |    60|cm      |       60
    sl3       |       0|black     |    35|inch    |     88.9
    sl4       |       8|black     |    40|inch    |    101.6
    sl8       |       1|brown     |    40|inch    |    101.6
    sl5       |       4|brown     |     1|m       |      100
    sl6       |       0|brown     |   0.9|m       |       90
    (8 rows)
d1424 1
a1424 1
    al_bundy=> INSERT INTO shoelace_ok SELECT * FROM shoelace_arrive;
d1430 21
a1450 21
    al_bundy=> SELECT * FROM shoelace ORDER BY sl_name;
    sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
    ----------+--------+----------+------+--------+---------
    sl1       |       5|black     |    80|cm      |       80
    sl2       |       6|black     |   100|cm      |      100
    sl7       |       6|brown     |    60|cm      |       60
    sl4       |       8|black     |    40|inch    |    101.6
    sl3       |      10|black     |    35|inch    |     88.9
    sl8       |      21|brown     |    40|inch    |    101.6
    sl5       |       4|brown     |     1|m       |      100
    sl6       |      20|brown     |   0.9|m       |       90
    (8 rows)

    al_bundy=> SELECT * FROM shoelace_log;
    sl_name   |sl_avail|log_who|log_when                        
    ----------+--------+-------+--------------------------------
    sl7       |       6|Al     |Tue Oct 20 19:14:45 1998 MET DST
    sl3       |      10|Al     |Tue Oct 20 19:25:16 1998 MET DST
    sl6       |      20|Al     |Tue Oct 20 19:25:16 1998 MET DST
    sl8       |      21|Al     |Tue Oct 20 19:25:16 1998 MET DST
    (4 rows)
d1458 3
a1460 3
    INSERT INTO shoelace_ok SELECT
           shoelace_arrive.arr_name, shoelace_arrive.arr_quant
      FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok;
d1467 6
a1472 6
    UPDATE shoelace SET
           sl_avail = int4pl(shoelace.sl_avail, shoelace_arrive.arr_quant)
      FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
           shoelace_ok *OLD*, shoelace_ok *NEW*,
           shoelace shoelace
     WHERE bpchareq(shoelace.sl_name, showlace_arrive.arr_name);
d1480 12
a1491 12
    UPDATE shoelace_data SET
           sl_name = shoelace.sl_name,
           sl_avail = int4pl(shoelace.sl_avail, shoelace_arrive.arr_quant),
           sl_color = shoelace.sl_color,
           sl_len = shoelace.sl_len,
           sl_unit = shoelace.sl_unit
      FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
           shoelace_ok *OLD*, shoelace_ok *NEW*,
           shoelace shoelace, shoelace *OLD*,
           shoelace *NEW*, shoelace_data showlace_data
     WHERE bpchareq(shoelace.sl_name, showlace_arrive.arr_name)
       AND bpchareq(shoelace_data.sl_name, shoelace.sl_name);
d1500 14
a1513 14
    UPDATE shoelace_data SET
           sl_name = s.sl_name,
           sl_avail = int4pl(s.sl_avail, shoelace_arrive.arr_quant),
           sl_color = s.sl_color,
           sl_len = s.sl_len,
           sl_unit = s.sl_unit
      FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
           shoelace_ok *OLD*, shoelace_ok *NEW*,
           shoelace shoelace, shoelace *OLD*,
           shoelace *NEW*, shoelace_data showlace_data,
           shoelace *OLD*, shoelace *NEW*,
           shoelace_data s, unit u
     WHERE bpchareq(s.sl_name, showlace_arrive.arr_name)
       AND bpchareq(shoelace_data.sl_name, s.sl_name);
d1522 16
a1537 17
    INSERT INTO shoelace_log SELECT
           s.sl_name,
           int4pl(s.sl_avail, shoelace_arrive.arr_quant),
           current_user,
           current_timestamp
      FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok,
           shoelace_ok *OLD*, shoelace_ok *NEW*,
           shoelace shoelace, shoelace *OLD*,
           shoelace *NEW*, shoelace_data showlace_data,
           shoelace *OLD*, shoelace *NEW*,
           shoelace_data s, unit u,
           shoelace_data *OLD*, shoelace_data *NEW*
           shoelace_log shoelace_log
     WHERE bpchareq(s.sl_name,  showlace_arrive.arr_name)
       AND bpchareq(shoelace_data.sl_name, s.sl_name);
       AND int4ne(int4pl(s.sl_avail, shoelace_arrive.arr_quant),
                                                    s.sl_avail);
d1546 10
a1555 10
    INSERT INTO shoelace_log SELECT
           s.sl_name,
           s.sl_avail + shoelace_arrive.arr_quant,
           current_user,
           current_timestamp
      FROM shoelace_arrive shoelace_arrive, shoelace_data shoelace_data,
           shoelace_data s
     WHERE s.sl_name = shoelace_arrive.arr_name
       AND shoelace_data.sl_name = s.sl_name
       AND s.sl_avail + shoelace_arrive.arr_quant != s.sl_avail;
d1557 7
a1563 7
    UPDATE shoelace_data SET
           sl_avail = shoelace_data.sl_avail + shoelace_arrive.arr_quant
     FROM shoelace_arrive shoelace_arrive,
          shoelace_data shoelace_data,
          shoelace_data s
    WHERE s.sl_name = shoelace_arrive.sl_name
      AND shoelace_data.sl_name = s.sl_name;
d1623 4
a1626 4
    al_bundy=> INSERT INTO shoelace VALUES 
    al_bundy->     ('sl9', 0, 'pink', 35.0, 'inch', 0.0);
    al_bundy=> INSERT INTO shoelace VALUES 
    al_bundy->     ('sl10', 1000, 'magenta', 40.0, 'inch', 0.0);
d1635 3
a1637 3
    CREATE VIEW shoelace_obsolete AS
        SELECT * FROM shoelace WHERE NOT EXISTS
            (SELECT shoename FROM shoe WHERE slcolor = sl_color);
d1643 5
a1647 5
    al_bundy=> SELECT * FROM shoelace_obsolete;
    sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
    ----------+--------+----------+------+--------+---------
    sl9       |       0|pink      |    35|inch    |     88.9
    sl10      |    1000|magenta   |    40|inch    |    101.6
d1656 2
a1657 2
    CREATE VIEW shoelace_candelete AS
        SELECT * FROM shoelace_obsolete WHERE sl_avail = 0;
d1663 21
a1683 21
    DELETE FROM shoelace WHERE EXISTS
        (SELECT * FROM shoelace_candelete
                 WHERE sl_name = shoelace.sl_name);
</ProgramListing>

    Voilà:

<ProgramListing>
    al_bundy=> SELECT * FROM shoelace;
    sl_name   |sl_avail|sl_color  |sl_len|sl_unit |sl_len_cm
    ----------+--------+----------+------+--------+---------
    sl1       |       5|black     |    80|cm      |       80
    sl2       |       6|black     |   100|cm      |      100
    sl7       |       6|brown     |    60|cm      |       60
    sl4       |       8|black     |    40|inch    |    101.6
    sl3       |      10|black     |    35|inch    |     88.9
    sl8       |      21|brown     |    40|inch    |    101.6
    sl10      |    1000|magenta   |    40|inch    |    101.6
    sl5       |       4|brown     |     1|m       |      100
    sl6       |      20|brown     |   0.9|m       |       90
    (9 rows)
d1740 4
a1743 4
    CREATE TABLE phone_data (person text, phone text, private bool);
    CREATE VIEW phone_number AS
        SELECT person, phone FROM phone_data WHERE NOT private;
    GRANT SELECT ON phone_number TO secretary;
d1842 9
a1850 9
    CREATE TABLE computer (
        hostname        text,    -- indexed
	manufacturer    text     -- indexed
    );

    CREATE TABLE software (
        software        text,    -- indexed
        hostname        text     -- indexed
    );
d1862 1
a1862 1
    DELETE FROM software WHERE hostname = $1;
d1869 2
a1870 2
    CREATE RULE computer_del AS ON DELETE TO computer
        DO DELETE FROM software WHERE hostname = OLD.hostname;
d1876 1
a1876 1
    DELETE FROM computer WHERE hostname = 'mypc.local.net';
d1884 2
a1885 2
    DELETE FROM software WHERE computer.hostname = 'mypc.local.net'
                           AND software.hostname = computer.hostname;
d1892 3
a1894 3
    Nestloop
      ->  Index Scan using comp_hostidx on computer
      ->  Index Scan using soft_hostidx on software
d1903 2
a1904 2
    DELETE FROM computer WHERE hostname >= 'old'
                           AND hostname <  'ole'
d1910 4
a1913 4
    Hash Join
      ->  Seq Scan on software
      ->  Hash
	    ->  Index Scan using comp_hostidx on computer
d1919 1
a1919 1
    DELETE FROM computer WHERE hostname ~ '^old';
d1925 3
a1927 3
    Nestloop
      ->  Index Scan using comp_hostidx on computer
      ->  Index Scan using soft_hostidx on software
d1950 1
a1950 1
    DELETE FROM computer WHERE manufacurer = 'bim';
d1959 3
a1961 3
    Nestloop
      ->  Index Scan using comp_manufidx on computer
      ->  Index Scan using soft_hostidx on software
d1967 2
a1968 2
    DELETE FROM software WHERE computer.manufacurer = 'bim'
                           AND software.hostname = computer.hostname;
@


1.19
log
@Deprecate 'current' date/time constant.
Purge "Postgres" in favor of "PostgreSQL" in docs. ref/ not yet done.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.18 2001/11/12 19:19:39 petere Exp $ -->
d17 3
d48 3
@


1.18
log
@Add some more index entries.
@
text
@d1 1
a1 1
<!-- $Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.17 2001/09/13 15:55:23 petere Exp $ -->
d21 1
a21 1
     the theoretical foundations of the <ProductName>Postgres</ProductName>
d29 1
a29 1
     in <ProductName>Postgres</ProductName> as functions and triggers.
d67 1
a67 1
    the <ProductName>Postgres</ProductName> backend with debug level 4
d271 1
a271 1
<Title>Implementation of Views in <ProductName>Postgres</ProductName></Title>
d274 1
a274 1
    Views in <ProductName>Postgres</ProductName> are implemented
d292 1
a292 1
    the information about a view in the <ProductName>Postgres</ProductName>
d788 1
a788 1
    Now another detail of <ProductName>Postgres</ProductName> enters the
d805 1
a805 1
<Title>The Power of Views in <ProductName>Postgres</ProductName></Title>
d829 1
a829 1
    the rule system as implemented in <ProductName>Postgres</ProductName>
d1607 1
a1607 1
    A final demonstration of the <ProductName>Postgres</ProductName>
d1647 1
a1647 1
    To make it a little harder for <ProductName>Postgres</ProductName>,
d1711 1
a1711 1
    Due to rewriting of queries by the <ProductName>Postgres</ProductName>
d1721 1
a1721 1
    The <ProductName>Postgres</ProductName> rule system changes the
d1801 1
a1801 1
    implemented using the <ProductName>Postgres</ProductName>
d1974 1
a1974 1
    not. In <ProductName>Postgres</ProductName> version 6.4, the
@


1.17
log
@Replace ASCII-quotes with proper markup.
@
text
@d1 1
a1 1
<!-- $Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.16 2001/09/12 01:22:25 ishii Exp $ -->
d4 1
a4 1
<Title>The <ProductName>Postgres</ProductName> Rule System</Title>
d23 1
a23 1
[<XRef LinkEnd="STON90b" EndTerm="STON90b">].
d41 1
a41 1
[<XRef LinkEnd="ONG90" EndTerm="ONG90">]
d43 1
a43 1
[<XRef LinkEnd="STON90b" EndTerm="STON90b">].
d113 1
d268 1
d836 1
a836 1
<Sect2>
d838 1
d1694 1
d1696 2
a1697 2
    <Note>
    <Title>The truth is</Title>
d1702 1
a1702 2
    </Note>
</Para>
@


1.16
log
@Fix typo.
@
text
@d1 1
a1 1
<!-- $Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.15 2001/09/10 21:58:47 petere Exp $ -->
d33 1
a33 1
     The query rewrite rule system (the "rule system" from now on) 
d498 1
a498 1
    The 'SELECT * FROM shoelace' was interpreted by the parser and
d667 1
a667 1
    query tree: the bottommost selects will be "pulled up" into the middle
d915 1
a915 1
    In the following, "update rules" means rules that are defined
d1114 1
a1114 1
    There is a rule 'log_shoelace' that is ON UPDATE with the rule
d1454 1
a1454 1
    Now the first rule 'shoelace_ok_ins' is applied and turns it
d1768 1
a1768 1
    he can grant access to everyone he wants. A GRANT means "I trust you".
@


1.15
log
@Markup and spell-check run over Programmer's Guide (rather incomplete still).
@
text
@d1 1
a1 1
<!-- $Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/rules.sgml,v 1.14 2001/07/09 23:50:32 tgl Exp $ -->
d1398 1
a1398 1
    al_bundy=> SELECT * FROM shoelace ORDER BY sl_name;
d1835 1
a1835 1
        hostname        text     -- indexed
@


1.14
log
@Fix rule rewriter so that new ordering of ON INSERT actions applies
in cases of qualified rules as well as unqualified ones.  Tweak rules
test to avoid cluttering output with dummy SELECT results.  Update
documentation to match code.
@
text
@d1 1
a1 1
<!-- $Header$ -->
d46 1
a46 1
<Title>What is a Querytree?</Title>
d55 1
a55 1
    It takes the output of the parser, one querytree, and the rewrite
d57 2
a58 2
    querytrees too with some extra information, and creates zero or many
    querytrees as result. So its input and output are always things
d64 1
a64 1
    Now what is a querytree? It is an internal representation of an
d66 2
a67 2
    it are stored separately. These querytrees are visible when starting
    the <ProductName>Postgres</ProductName> backend with debuglevel 4
d70 1
a70 1
    also stored as querytrees. They are not formatted like the debug
d75 1
a75 1
    Reading a querytree requires some experience and it was a hard
d78 1
a78 1
    in a targetlist, water and coffee powder in a rangetable and all
d80 1
a80 1
    <Acronym>SQL</Acronym> representations of querytrees are
d88 1
a88 1
<Title>The Parts of a Querytree</Title>
d92 3
a94 4
    querytrees in this document it is necessary to be able to identify
    the parts the statement is broken into when it is in the querytree
    structure. The parts of a querytree are
</Para>
a95 1
<Para>
d99 1
a99 1
        the commandtype
d104 1
a104 1
	(SELECT, INSERT, UPDATE, DELETE) produced the parsetree.
d111 1
a111 1
        the rangetable
d115 1
a115 1
        The rangetable is a list of relations that are used in the query.
d121 1
a121 1
        Every rangetable entry identifies a table or view and tells
d123 1
a123 1
	In the querytree the rangetable entries are referenced by
d126 1
a126 1
	statement. This can happen after the rangetables of rules
d135 1
a135 1
        the resultrelation
d139 1
a139 1
        This is an index into the rangetable that identifies the
d152 1
a152 1
        On INSERT, UPDATE and DELETE queries the resultrelation
d160 1
a160 1
        the targetlist
d164 1
a164 1
        The targetlist is a list of expressions that define the result
d174 1
a174 1
        DELETE queries don't need a targetlist because they don't
d176 1
a176 1
	entry to the empty targetlist. But this is after the rule
d178 1
a178 1
	targetlist is empty.
d182 2
a183 2
        In INSERT queries the targetlist describes the new rows that
	should go into the resultrelation. It is the expressions in the VALUES
d185 1
a185 1
	Missing columns of the resultrelation will be filled in by the
d190 1
a190 1
        In UPDATE queries, the targetlist describes the new rows that should
d199 1
a199 1
        Every entry in the targetlist contains an expression that can
d201 1
a201 1
	of the relations in the rangetable, a parameter, or an expression
d214 2
a215 2
	contained in the targetlist entries. The result value of this
	expression is a boolean that tells if the operation
d233 1
a233 1
	--- are used, we have to join in the order shown by the JOINs.
d251 1
a251 1
        The other parts of the querytree like the ORDER BY 
d305 1
a305 1
    semantics from the others in that they modify the parsetree in
d330 1
a330 1
    The database needed to play with the examples is named al_bundy.
d332 1
a332 1
    procedural language PL/pgSQL installed, because
d425 1
a425 1
    whenever the relation shoelace is referenced in a query's rangetable.
d433 1
a433 1
    The rule's action is one querytree that is a copy of the
d441 1
a441 1
    historical reasons in the printed querytree) you can see in
d509 2
a510 2
    rangetable and checks if there are rules in <Filename>pg_rewrite</Filename>
    for any relation. When processing the rangetable entry for
d512 1
a512 1
    rule '_RETshoelace' with the parsetree
d531 2
a532 2
    rangetable entry for the original one that referenced the view.  The 
    resulting rewritten parsetree is almost the same as if Al had typed
d548 1
a548 1
     There is one difference however: the sub-query's rangetable has two
d551 1
a551 1
     the sub-query's join tree or targetlist.  The rewriter uses them
d599 1
a599 1
    The output of the parser this time is the parsetree
d611 1
a611 1
    parsetree
d630 2
a631 2
    <Filename>shoelace</Filename> are substituted into the rangetable of
    the sub-query, leading to a three-level final querytree:
d667 1
a667 1
    querytree: the bottommost selects will be "pulled up" into the middle
d699 2
a700 2
    Two details of the parsetree aren't touched in the description of
    view rules above. These are the commandtype and the resultrelation.
d705 3
a707 3
    There are only a few differences between a parsetree for a SELECT
    and one for any other command. Obviously they have another commandtype
    and this time the resultrelation points to the rangetable entry where
d710 1
a710 1
    a and b, the parsetrees for the two statements
d723 1
a723 1
	    The rangetables contain entries for the tables t1 and t2.
d729 2
a730 2
	    The targetlists contain one variable that points to attribute
	    b of the rangetable entry for table t2.
d743 1
a743 1
	    The jointrees show a simple join between t1 and t2.
d748 1
a748 1
    The consequence is, that both parsetrees result in similar execution
d750 2
a751 2
    the missing columns from t1 are added to the targetlist by the planner 
    and the final parsetree will read as
d769 1
a769 1
    parsetree) that this is an UPDATE, and he knows that this result
d775 1
a775 1
    To resolve this problem, another entry is added to the targetlist
d780 1
a780 1
    After adding the ctid to the targetlist, the query actually looks like
d792 1
a792 1
    and after the transaction commited the vacuum cleaner can really move
d807 2
a808 2
    view definitions into the original parsetree. In the second example
    a simple SELECT from one view created a final parsetree that is
d822 1
a822 1
    in one single parsetree. And this is still the situation
d840 2
a841 2
    we will have a querytree in which the resultrelation points at a
    subquery rangetable entry.  This will not work, so the rewriter throws
d846 1
a846 1
    To change this we can define rules that modify the behaviour
d897 2
a898 2
    Second, they don't modify the parsetree in place. Instead they
    create zero or many new parsetrees and can throw away the
d921 1
a921 1
    relation and the commandtype of a parsetree are equal to the
d923 2
a924 2
    For update rules, the rule system creates a list of parsetrees.
    Initially the parsetree list is empty.
d939 1
a939 1
    So we have four cases that produce the following parsetrees for
d950 2
a951 2
	        The parsetree from the rule action where the
		original parsetree's qualification has been added.
d964 2
a965 2
	        The parsetree from the rule action where the
		original parsetree's qualification has been added.
d978 2
a979 2
	        The parsetree from the rule action where the rule
		qualification and the original parsetree's 
d993 2
a994 2
	        The parsetree from the rule action where the rule
		qualification and the original parsetree's 
d1001 1
a1001 1
	        The original parsetree where the negated rule
d1011 1
a1011 1
    Finally, if the rule is not INSTEAD, the unchanged original parsetree is
d1013 1
a1013 1
    original parsetree, we end up with either one or two output parsetrees
d1028 1
a1028 1
    The parsetrees generated from rule actions are thrown into the
d1030 3
a1032 3
    in more or less parsetrees.
    So the parsetrees in the rule actions must have either another commandtype
    or another resultrelation. Otherwise this recursive process will end up in a loop.
d1139 3
a1141 3
    has to return two parsetrees: the modified rule action and the original
    parsetree. In the first step the rangetable of the original query is
    incorporated into the rule's action parsetree. This results in
d1168 3
a1170 3
    In step 3 the original parsetree's qualification is added,
    restricting the resultset further to only the rows touched
    by the original parsetree.
d1182 2
a1183 2
    Step 4 substitutes NEW references by the targetlist entries from the
    original parsetree or with the matching variable references
d1196 1
a1196 1
    Step 5 changes OLD references into resultrelation references.
d1209 2
a1210 2
    original parsetree.  In short, the output from the rule system
    is a list of two parsetrees that are the same as the statements:
d1234 1
a1234 1
    time the original parsetree does not contain a targetlist
d1258 2
a1259 2
    parsetrees qualification is different and that results
    in the extra parsetree
d1270 1
a1270 1
    This parsetree will surely insert three new log entries. And
d1275 1
a1275 1
    Here we can see why it is important that the original parsetree is
d1291 1
a1291 1
    on them is to let those parsetrees get
d1307 1
a1307 1
    parsetrees will be empty and the whole query will become
d1317 2
a1318 2
    even a PGRES_EMPTY_QUERY will be available in libpq.
    In psql, nothing happens. This might change in the future.
d1326 1
a1326 1
    create rules that rewrite the parsetree into one that
d1358 1
a1358 1
    a big partlist. Al is not that good in calculating and so
d1361 1
a1361 1
    insert the items from the partlist and one with a special
d1446 1
a1446 1
    document (but not the last example :-). First there was the parsers output
d1468 1
a1468 1
    the second applied rule 'shoelace_upd' produced
d1485 1
a1485 1
    Again it's an INSTEAD rule and the previous parsetree is trashed.
d1488 1
a1488 1
    and applies the rule '_RETshoelace' on it and we get
d1509 2
a1510 2
    'log_shoelace' gets applied what produces the extra
    parsetree
d1533 2
a1534 2
    generated parsetrees.
    So we end up with two final parsetrees that are equal to the
d1567 1
a1567 1
    relation appears twice in the rangetable where it could definitely
d1583 1
a1583 1
    while omitting the extra rangetable entry would result in a
d1660 1
a1660 1
    Voila:
d1683 1
a1683 1
    one single parsetree that deletes the requested data
d1719 1
a1719 1
    behaviour of the default access control system. Relations that
d1823 1
a1823 1
    the parsetree or generates an additional one. So if many
d1846 2
a1847 2
    thousands of rows and the index on hostname is unique.
    The hostname column contains the full qualified domain
d1857 1
a1857 1
    in a prepared and saved plan and pass the hostname in
d1891 1
a1891 1
    we want to get rid of all the 2000 computers where the hostname starts
d1923 1
a1923 1
    qualification for the hostname on computer could also be
d1932 1
a1932 1
    the rule will still be faster in the seqscan situation. 2000
d1947 2
a1948 2
    the executor. But the rule plan will again be the Nestloop over
    two IndexScan's. Only using another index on computer:
d1978 1
a1978 1
    change at all because it does not appear in the targetlist
d1987 1
a1987 1
    targetlist and will suppress the additional query completely
@


1.13
log
@Change "indices" to "indexes", per OED.
@
text
@d1 2
d1020 10
d1037 2
a1038 2
    rule system assumes a loop over multiple rule definitions and aborts the
    transaction.
d1277 2
a1278 4
    It is important, that the original parsetree is executed last.
    The <ProductName>Postgres</ProductName> "traffic cop" does
    a command counter increment between the execution of the two
    parsetrees so the second one can see changes made by the first.
@


1.12
log
@Add index.  Only some parts of the manual set have index entries so far...
@
text
@d1872 1
a1872 1
    Since there are appropriate indices setup, the planner
d1922 1
a1922 1
    rule implementation will do it with two queries over indices.
@


1.11
log
@Replace some oldish, non-SQL'ish elements with more standard forms. (cast
syntax, type names, function names, etc.)
@
text
@d4 4
@


1.10
log
@Revise SELECT reference page for outer joins, subselect in FROM,
ISO-compliant UNION/INTERSECT/EXCEPT.  Revise discussion of rule
rewriter to reflect new subselect-in-FROM implementation of views.
Miscellaneous other cleanups.
@
text
@d1056 2
a1057 2
        log_who    name,          -- who did it
        log_when   datetime       -- when
d1065 2
a1066 2
                                        getpgusername(),
                                        'now'::text
a1068 11

    One interesting detail is the casting of 'now' in the rules
    INSERT action to type text. Without that, the parser would see
    at CREATE RULE time, that the target type in <Filename>shoelace_log</Filename>
    is a datetime and tries to make a constant from it - with success.
    So a constant datetime value would be stored in the rule action
    and all log entries would have the time of the CREATE RULE statement.
    Not exactly what we want. The casting causes the parser to
    construct a datetime('now'::text) expression and this will be 
    evaluated when the rule is executed.  (Another way to do this is to
    use the function now() instead of a literal constant.)
d1112 1
a1112 1
           getpgusername(), datetime('now'::text))
d1132 1
a1132 1
           getpgusername(), datetime('now'::text))
d1143 1
a1143 1
           getpgusername(), datetime('now'::text))
d1161 1
a1161 1
           getpgusername(), datetime('now'::text))
d1175 1
a1175 1
           getpgusername(), datetime('now'::text))
d1187 1
a1187 1
           getpgusername(), datetime('now'::text))
d1201 1
a1201 1
           getpgusername(), datetime('now'::text))
d1227 1
a1227 1
           getpgusername(), 'now')
d1250 1
a1250 1
           getpgusername(), 'now'
d1504 2
a1505 2
           getpgusername(),
           datetime('now'::text)
d1529 2
a1530 2
           getpgusername(),
           'now'
@


1.9
log
@Add `id' attributes to all `chapter' and `sect1' tags, to generate useful
names for the HTML files (e.g., not x4856.htm).
@
text
@d4 7
d31 1
a31 1
     query to the query optimizer for  execution.   It
d44 1
a44 1
    when it is invoked and what it's input and results are.
d48 1
a48 1
    The rule system is located between the query parser and the optimizer.
d52 1
a52 1
    querytrees as result. So it's input and output are always things
d111 2
a112 2
        The rangtable is a list of relations that are used in the query.
	In a SELECT statement that are the relations given after
d163 4
a166 2
	between the SELECT and the FROM keywords (* is just an
	abbreviation for all the attribute names of a relation). 
d171 1
a171 1
	produce any result. In fact the optimizer will add a special
d179 4
a182 4
	should go into the resultrelation. Missing columns of the 
	resultrelation will be added by the optimizer with a constant
	NULL expression. It is the expressions in the VALUES clause
	or the ones from the SELECT clause on INSERT ... SELECT.
d186 6
a191 6
        On UPDATE queries, it describes the new rows that should
	replace the old ones. Here now the optimizer will add missing
	columns by inserting expressions that put the values from the
	old rows into the new one. And it will add the special entry
	like for DELETE too. It is the expressions from the
	SET attribute = expression part of the query.
d197 1
a197 1
	of the relations in the rangetable, a parameter or an expression
d209 1
a209 1
        The queries qualification is an expression much like one of those
d221 22
d248 1
a248 1
	clause arent of interest here. The rule system
d251 1
a251 2
	system. GROUP BY is a special thing when it appears in
        a view definition and still needs to be documented.
d288 1
a288 1
    query parsers, there is absolutely no difference between
d307 3
a309 3
    Currently, there could be only one action and it must be a
    SELECT action that is INSTEAD. This restriction was required
    to make rules safe enough to open them for ordinary users and
d314 1
a314 1
    The example for this document are two join views that do some calculations
d326 1
a326 1
    The database needed to play on the examples is named al_bundy.
d345 1
a345 1
    The real tables we need in the first two rule system descripitons
d421 3
a423 3
    whenever the relation shoelace is referenced in a queries rangetable.
    The rule has no rule qualification (discussed in the
    non SELECT rules since SELECT rules currently cannot have them) and
d425 1
a425 1
    query qualifications! The rules action has a qualification.
d429 1
a429 1
    The rules action is one querytree that is an exact copy of the
d522 7
a528 2
    The first step in rewriting is merging the two rangetables. The resulting
    parsetree then reads
d534 20
a553 4
      FROM shoelace shoelace, <FirstTerm>shoelace *OLD*</FirstTerm>,
           <FirstTerm>shoelace *NEW*</FirstTerm>, <FirstTerm>shoelace_data s</FirstTerm>,
           <FirstTerm>unit u</FirstTerm>;
</ProgramListing>
d555 9
a563 55
    In step 2 it adds the qualification from the rule action to the
    parsetree resulting in

<ProgramListing>
    SELECT shoelace.sl_name, shoelace.sl_avail,
           shoelace.sl_color, shoelace.sl_len,
           shoelace.sl_unit, shoelace.sl_len_cm
      FROM shoelace shoelace, shoelace *OLD*,
           shoelace *NEW*, shoelace_data s,
           unit u
     <FirstTerm>WHERE bpchareq(s.sl_unit, u.un_name)</FirstTerm>;
</ProgramListing>

    And in step 3 it replaces all the variables in the parsetree, that
    reference the rangetable entry (the one for
    <Filename>shoelace</Filename> that is currently processed)
    by the corresponding targetlist expressions
    from the rule action. This results in the final query

<ProgramListing>
    SELECT <FirstTerm>s.sl_name</FirstTerm>, <FirstTerm>s.sl_avail</FirstTerm>, 
           <FirstTerm>s.sl_color</FirstTerm>, <FirstTerm>s.sl_len</FirstTerm>, 
           <FirstTerm>s.sl_unit</FirstTerm>, <FirstTerm>float8mul(s.sl_len, u.un_fact)</FirstTerm> AS sl_len_cm
      FROM shoelace shoelace, shoelace *OLD*,
           shoelace *NEW*, shoelace_data s,
           unit u
     WHERE bpchareq(s.sl_unit, u.un_name);
</ProgramListing>

    Turning this back into a real <Acronym>SQL</Acronym> statement a human
    user would type reads

<ProgramListing>
    SELECT s.sl_name, s.sl_avail,
           s.sl_color, s.sl_len,
           s.sl_unit, s.sl_len * u.un_fact AS sl_len_cm
      FROM shoelace_data s, unit u
     WHERE s.sl_unit = u.un_name;
</ProgramListing>

    That was the first rule applied. While this was done, the rangetable has
    grown. So the rule system continues checking the range table entries.
    The next one is number 2 (shoelace *OLD*).
    Relation <Filename>shoelace</Filename>
    has a rule, but this rangetable entry isn't referenced
    in any of the variables of the parsetree, so it is ignored. Since all the
    remaining rangetable entries either have no rules in
    <Filename>pg_rewrite</Filename> or aren't referenced,
    it reaches the end of the rangetable.
    Rewriting is complete and the above is the final result given into
    the optimizer.
    The optimizer ignores the extra rangetable entries that aren't
    referenced by variables in the parsetree and the plan produced
    by the planner/optimizer would be exactly the same as if Al had typed
    the above SELECT query instead of the view selection.
d578 1
a578 1
    We theach him how to do and he asks his database:
d605 2
a606 2
    The first rule applied will be that one for the 
    <Filename>shoe_ready</Filename> relation and it results in the
d610 60
a669 89
    SELECT <FirstTerm>rsh.shoename</FirstTerm>, <FirstTerm>rsh.sh_avail</FirstTerm>,
           <FirstTerm>rsl.sl_name</FirstTerm>, <FirstTerm>rsl.sl_avail</FirstTerm>,
           <FirstTerm>min(rsh.sh_avail, rsl.sl_avail) AS total_avail</FirstTerm>
      FROM shoe_ready shoe_ready, <FirstTerm>shoe_ready *OLD*</FirstTerm>,
           <FirstTerm>shoe_ready *NEW*</FirstTerm>, <FirstTerm>shoe rsh</FirstTerm>,
           <FirstTerm>shoelace rsl</FirstTerm>
     WHERE int4ge(<FirstTerm>min(rsh.sh_avail, rsl.sl_avail)</FirstTerm>, 2)
       <FirstTerm>AND (bpchareq(rsl.sl_color, rsh.slcolor)
            AND float8ge(rsl.sl_len_cm, rsh.slminlen_cm)
            AND float8le(rsl.sl_len_cm, rsh.slmaxlen_cm)
           )</FirstTerm>;
</ProgramListing>

    In reality the AND clauses in the qualification will be
    operator nodes of type AND with a left and right expression. But
    that makes it lesser readable as it already is, and there are more
    rules to apply. So I only put them into some parantheses to group
    them into logical units in the order they where added and we continue
    with the rule for relation
    <Filename>shoe</Filename> as it is the next rangetable entry
    that is referenced and has a rule. The result of applying it is

<ProgramListing>
    SELECT <FirstTerm>sh.shoename</FirstTerm>, <FirstTerm>sh.sh_avail</FirstTerm>,
           rsl.sl_name, rsl.sl_avail,
           min(<FirstTerm>sh.sh_avail</FirstTerm>, rsl.sl_avail) AS total_avail,
      FROM shoe_ready shoe_ready, shoe_ready *OLD*,
           shoe_ready *NEW*, shoe rsh,
           shoelace rsl, <FirstTerm>shoe *OLD*</FirstTerm>,
           <FirstTerm>shoe *NEW*</FirstTerm>, <FirstTerm>shoe_data sh</FirstTerm>,
           <FirstTerm>unit un</FirstTerm>
     WHERE (int4ge(min(<FirstTerm>sh.sh_avail</FirstTerm>, rsl.sl_avail), 2)
            AND (bpchareq(rsl.sl_color, <FirstTerm>sh.slcolor</FirstTerm>)
                 AND float8ge(rsl.sl_len_cm, 
                              <FirstTerm>float8mul(sh.slminlen, un.un_fact)</FirstTerm>)
                 AND float8le(rsl.sl_len_cm, 
                              <FirstTerm>float8mul(sh.slmaxlen, un.un_fact)</FirstTerm>)
                )
           )
       <FirstTerm>AND bpchareq(sh.slunit, un.un_name)</FirstTerm>;
</ProgramListing>

    And finally we apply the already well known rule for
    <Filename>shoelace</Filename> (this time on a parsetree that is
    a little more complex) and get

<ProgramListing>
    SELECT sh.shoename, sh.sh_avail,
           <FirstTerm>s.sl_name</FirstTerm>, <FirstTerm>s.sl_avail</FirstTerm>,
           min(sh.sh_avail, <FirstTerm>s.sl_avail</FirstTerm>) AS total_avail
      FROM shoe_ready shoe_ready, shoe_ready *OLD*,
           shoe_ready *NEW*, shoe rsh,
           shoelace rsl, shoe *OLD*,
           shoe *NEW*, shoe_data sh,
           unit un, <FirstTerm>shoelace *OLD*</FirstTerm>,
           <FirstTerm>shoelace *NEW*</FirstTerm>, <FirstTerm>shoelace_data s</FirstTerm>,
           <FirstTerm>unit u</FirstTerm>
     WHERE (    (int4ge(min(sh.sh_avail, <FirstTerm>s.sl_avail</FirstTerm>), 2)
                 AND (bpchareq(<FirstTerm>s.sl_color</FirstTerm>, sh.slcolor)
                      AND float8ge(<FirstTerm>float8mul(s.sl_len, u.un_fact)</FirstTerm>, 
                                   float8mul(sh.slminlen, un.un_fact))
                      AND float8le(<FirstTerm>float8mul(s.sl_len, u.un_fact)</FirstTerm>, 
                                   float8mul(sh.slmaxlen, un.un_fact))
                     )
                )
            AND bpchareq(sh.slunit, un.un_name)
           )
       <FirstTerm>AND bpchareq(s.sl_unit, u.un_name)</FirstTerm>;
</ProgramListing>

    Again we reduce it to a real <Acronym>SQL</Acronym> statement
    that is equivalent to the final output of the rule system:

<ProgramListing>
    SELECT sh.shoename, sh.sh_avail,
           s.sl_name, s.sl_avail,
           min(sh.sh_avail, s.sl_avail) AS total_avail
      FROM shoe_data sh, shoelace_data s, unit u, unit un
     WHERE min(sh.sh_avail, s.sl_avail) >= 2
       AND s.sl_color = sh.slcolor
       AND s.sl_len * u.un_fact >= sh.slminlen * un.un_fact
       AND s.sl_len * u.un_fact <= sh.slmaxlen * un.un_fact
       AND sh.sl_unit = un.un_name
       AND s.sl_unit = u.un_name;
</ProgramListing>

    Recursive processing of rules rewrote one SELECT from a view
    into a parsetree, that is equivalent to exactly that what Al
    had to type if there would be no views at all.
d675 1
a675 1
    rules in the rule system (only for the other rules).
d683 1
a683 1
    on the first CREATE VIEW, the second relation does not exist
d697 1
a697 1
    In fact, view rules don't need these informations.
d704 1
a704 1
    the result should go. Anything else is absolutely the same. 
d736 6
d746 1
a746 1
    the missing columns from t1 are added to the targetlist by the optimizer 
d766 2
a767 4
    should go into table t1. But which of the 666 rows that are there
    has to be replaced by the new row? The plan executed is a join
    with a qualification that potentially could produce any number of
    rows between 0 and 666 in unknown order.
d772 5
a776 7
    in UPDATE and DELETE statements. The current tuple ID (ctid). This
    is a system attribute with a special feature. It contains the
    block and position in the block for the row. Knowing the table,
    the ctid can be used to find one specific row in a 1.5GB sized table
    containing millions of rows by fetching one single data block.
    After adding the ctid to the targetlist, the final result set
    could be defined as
d793 1
a793 1
    Knowing that all, we can simply apply view rules in absolutely
d813 1
a813 1
    that the optimizer has all
d820 1
a820 1
    Now the optimizer has to decide which is
d822 1
a822 1
    the optimizer has, the better this decision can be. And
a827 71

<Sect3>
<Title>Concerns</Title>

<Para>
    There was a long time where the <ProductName>Postgres</ProductName> 
    rule system was considered broken. The use of rules was not
    recommended and the only part working was view rules. And also
    these view rules gave problems because the rule system wasn't able
    to apply them properly on statements other than a SELECT (for
    example an UPDATE
    that used data from a view didn't work).
</Para>

<Para>
    During that time, development moved on and many features were
    added to the parser and optimizer. The rule system got more and more
    out of sync with their capabilities and it became harder and harder
    to start fixing it. Thus, no one did.
</Para>

<Para>
    For 6.4, someone locked the door, took a deep breath and shuffled
    that damned thing up. What came out was a rule system with the
    capabilities described in this document. But there are still some
    constructs not handled and some where it fails due to 
    things that are currently not
    supported by the <ProductName>Postgres</ProductName> query
    optimizer.

    <ItemizedList>
        <ListItem>
	<Para>
	    Views with aggregate columns have bad problems. Aggregate
	    expressions in qualifications must be used in subselects.
	    Currently it is not possible to do a join of two views,
	    each having an aggregate column, and compare the two aggregate values
	    in the qualification. In the meantime it is possible to
	    put these aggregate expressions into functions with
	    the appropriate arguments and use
	    them in the view definition.
	</Para>
        </ListItem>

        <ListItem>
	<Para>
	    Views of unions are currently not supported. Well it's easy
	    to rewrite a simple SELECT into a union. But it is a little
	    difficult if the view is part of a join doing an update.
	</Para>
        </ListItem>

        <ListItem>
	<Para>
	    ORDER BY clauses in view definitions aren't supported.
	</Para>
        </ListItem>

        <ListItem>
	<Para>
	    DISTINCT isn't supported in view definitions.
	</Para>
        </ListItem>
    </ItemizedList>

    There is no good reason why the optimizer should not
    handle parsetree constructs that the parser could never produce
    due to limitations in the <Acronym>SQL</Acronym> syntax.
    The author hopes that these items disappear in the future.
</Para>
</Sect3>
d831 1
a831 1
<Title>Implementation Side Effects</Title>
d834 5
a838 39
    Using the described rule system to implement views has a funny
    side effect. The following does not seem to work:

<ProgramListing>
    al_bundy=> INSERT INTO shoe (shoename, sh_avail, slcolor)
    al_bundy->     VALUES ('sh5', 0, 'black');
    INSERT 20128 1
    al_bundy=> SELECT shoename, sh_avail, slcolor FROM shoe_data;
    shoename  |sh_avail|slcolor   
    ----------+--------+----------
    sh1       |       2|black     
    sh3       |       4|brown     
    sh2       |       0|black     
    sh4       |       3|brown     
    (4 rows)
</ProgramListing>

    The interesting thing is that the return code for INSERT gave
    us an object ID and told that 1 row has been inserted.
    But it doesn't appear in <Filename>shoe_data</Filename>.
    Looking into the database
    directory we can see, that the database file for the
    view relation <Filename>shoe</Filename> seems now to have
    a data block. And that is definitely the case.
</Para>

<Para>
    We can also issue a DELETE and if it does not have
    a qualification, it tells us that rows have been deleted
    and the next vacuum run will reset the file to zero size.
</Para>

<Para>
    The reason for that behaviour is, that the parsetree for the
    INSERT does not reference the <Filename>shoe</Filename> relation
    in any variable. The targetlist contains only constant values.
    So there is no rule to apply and it goes
    down unchanged into execution and the row is inserted. And
    so for the DELETE.
d853 1
a853 1
<Title>Differences to View Rules</Title>
d947 1
a947 1
		original parsetrees qualification has been added.
d961 1
a961 1
		original parsetrees qualification has been added.
d975 1
a975 1
		qualification and the original parsetrees 
d990 1
a990 1
		qualification and the original parsetrees 
d1009 1
a1009 1
    original parsetree, we end up with a total maximum of two parsetrees
d1031 3
a1033 2
    that entries expression is placed into the reference. Otherwise
    NEW means the same as OLD. Any reference to OLD is replaced by a
d1037 6
d1049 2
a1050 2
    log table and a rule that writes us entries every time
    and UPDATE is performed on <Filename>shoelace_data</Filename>.
d1076 4
a1079 3
    Not exactly what we want. The casting causes that the parser
    constructs a datetime('now'::text) from it and this will be 
    evaluated when the rule is executed.
d1121 1
a1121 1
    INSERT INTO shoelace_log SELECT 
d1123 2
a1124 3
           getpgusername(), datetime('now'::text)
      FROM shoelace_data *NEW*, shoelace_data *OLD*,
           shoelace_log shoelace_log;
d1127 5
a1131 13
    Don't trust the output of the pg_rules system view. It specially
    handles the situation that there are only references to NEW
    and OLD in the INSERT and outputs the VALUES format of INSERT.
    In fact there is no difference between an INSERT ... VALUES
    and an INSERT ... SELECT on parsetree level. They both have
    rangetables, targetlists and maybe qualifications etc. The
    optimizer later decides, if to create an execution plan of
    type result, seqscan, indexscan, join or whatever for that
    parsetree. If there are no references to
    rangetable entries leftin the parsetree , it becomes
    a result execution plan
    (the INSERT ... VALUES version). The rule action above can
    truely result in both variants.
d1136 1
a1136 1
    has to return two parsetrees. The modified rule action and the original
d1138 1
a1138 1
    incorporated into the rules action parsetree. This results in
d1141 5
a1145 5
    INSERT INTO shoelace_log SELECT 
           *NEW*.sl_name, *NEW*.sl_avai,
           getpgusername(), datetime('now'::text)
      FROM <FirstTerm>shoelace_data shoelace_data</FirstTerm>, shoelace_data *NEW*,
           shoelace_data *OLD*, shoelace_log shoelace_log;
d1152 5
a1156 5
    INSERT INTO shoelace_log SELECT 
           *NEW*.sl_name, *NEW*.sl_avai,
           getpgusername(), datetime('now'::text)
      FROM shoelace_data shoelace_data, shoelace_data *NEW*,
           shoelace_data *OLD*, shoelace_log shoelace_log
d1160 6
a1165 1
    In step 3 the original parsetrees qualification is added,
d1170 5
a1174 5
    INSERT INTO shoelace_log SELECT 
           *NEW*.sl_name, *NEW*.sl_avai,
           getpgusername(), datetime('now'::text)
      FROM shoelace_data shoelace_data, shoelace_data *NEW*,
           shoelace_data *OLD*, shoelace_log shoelace_log
d1184 1
a1184 1
    INSERT INTO shoelace_log SELECT 
d1186 3
a1188 3
           getpgusername(), datetime('now'::text)
      FROM shoelace_data shoelace_data, shoelace_data *NEW*,
           shoelace_data *OLD*, shoelace_log shoelace_log
d1193 1
a1193 1
    Step 5 replaces OLD references into resultrelation references.
d1196 1
a1196 1
    INSERT INTO shoelace_log SELECT 
d1198 3
a1200 3
           getpgusername(), datetime('now'::text)
      FROM shoelace_data shoelace_data, shoelace_data *NEW*,
           shoelace_data *OLD*, shoelace_log shoelace_log
d1205 2
a1206 1
    That's it. So reduced to the max the return from the rule system
d1210 1
a1210 1
    INSERT INTO shoelace_log SELECT
d1212 1
a1212 1
           getpgusername(), 'now'
d1222 2
a1223 2
    the rule defines. The subtitutions and the qualifications
    added ensure, that if the original query would be an
d1230 1
a1230 1
    No log entry would get written because due to the fact that this
d1232 1
a1232 1
    entry for sl_avail, NEW.sl_avail will get replaced by
d1236 1
a1236 1
    INSERT INTO shoelace_log SELECT
d1238 1
a1238 1
           getpgusername(), 'now'
d1244 1
a1244 3
    and that qualification will never be true. Since the is no
    difference on parsetree level between an INSERT ... SELECT,
    and an INSERT ... VALUES, it will also
d1289 2
a1290 2
    possibility that someone can INSERT, UPDATE and DELETE
    invisible data on them is to let those parsetrees get
d1313 1
a1313 1
    This fact might irritate frontend applications because
d1316 1
a1316 1
    even a PGRES_EMPTY_QUERY or so will be available in libpq.
d1361 1
a1361 1
    trick. The create commands for anything are:
d1393 1
a1393 1
    is exactly that what's on the part list. We take a quick look
d1444 1
a1444 1
    results. And it's description will be the last in this
d1485 1
a1485 1
    Note that this query sill uses the view <Filename>shoelace</Filename>
d1567 1
a1567 1
    be reduced to one. The optimizer does not handle it and so the
d1604 1
a1604 1
    rule system and it's power. There is a cute blonde that
d1631 1
a1631 1
    It's output is
d1719 2
a1720 2
    are used due to rules get checked during the rewrite against the
    permissions of the relation owner, the rule is defined on.
d1744 3
a1746 2
    granted. The check for accessing phone_number is still performed,
    so nobody than the secretary can use it.
d1777 1
a1777 1
    will still be executed successfull. And Al could see the log entries.
d1879 1
a1879 1
    Since there are appropriate indices setup, the optimizer
d1921 1
a1921 1
    This shows, that the optimizer does not realize that the
d1972 1
a1972 1
    it's comeback latest in 6.5, maybe earlier 
d1981 2
a1982 2
    fact that it's actions will only be done when a specific attribute
    is updated is hidden in it's functionality. The definition of
d1984 1
a1984 1
    row is touched, the trigger must be called to make it's
d1992 1
a1992 1
    Rules will only be significant slower than triggers if
d1994 1
a1994 1
    where the optimizer fails. They are a big hammer.
@


1.8
log
@Fixups in content and markup for 7.0 release.
@
text
@d32 1
a32 1
<Sect1>
d231 1
a231 1
<Sect1>
d976 1
a976 1
<Sect1>
d1827 1
a1827 1
<Sect1>
d1915 1
a1915 1
<Sect1>
@


1.7
log
@Minor markup fixes.
@
text
@d857 3
a859 3
    recommended and the only part working where view rules. And also
    these view rules made problems because the rule system wasn't able
    to apply them properly on other statements than a SELECT (for
d865 1
a865 1
    During that time, development moved on and many features where
d868 1
a868 1
    to start fixing it. Thus, noone did.
d2091 1
a2091 1
    Another situation are cases on UPDATE where it depends on the
d2099 1
a2099 1
    performed allways, even if the attribute of interest cannot
d2111 1
a2111 1
    will only do it's scan's if there ever could be something to do.
d2124 17
@


1.6
log
@Clean up to ensure tag completion as required by the newest versions
 of Norm's Modular Style Sheets and jade/docbook.
From Vince Vielhaber <vev@@michvhf.com>.
@
text
@d1674 2
a1675 1
     FROM shoelace_arrive shoelace_arrive, shoelace_data shoelace_data,
@


1.5
log
@Fix typos in rules.sgml.
Add Emacs configuration block to postgres.sgml.
@
text
@d31 1
a31 1

d227 1
d1024 1
a1024 1

d1132 1
a1132 1

@


1.4
log
@Small adjustments in markup getting ready for hardcopy release.
Jan did a nice job of initial markup so it was pretty easy!
@
text
@d172 1
a172 1
	NULL expression. It are the expressions in the VALUES clause
d181 1
a181 1
	like for DELETE too. It are the expressions from the
@


1.3
log
@Add id field to chapter and book tags to allow output file names
 to be meaningful.
@
text
@d5 1
a5 1
     Production  rule  systems  are conceptually simple, but
d7 11
a17 9
     them.  Consequently, we will not attempt to explain the
     actual syntax and operation of the <ProductName>Postgres</ProductName> rule system
     here.  Instead, you should read 
[<XRef LinkEnd="STON90b" EndTerm="STON90b">] to understand
     some of these points and the theoretical foundations of
     the  <ProductName>Postgres</ProductName>  rule  system before trying to use rules.
     The discussion in this section is intended  to  provide
     an  overview  of the <ProductName>Postgres</ProductName> rule system and point the
     user at helpful references and examples.
d19 4
a22 1
     The "query rewrite" rule  system  modifies  queries  to
d31 7
d40 190
d231 491
a721 1
<Title>The Goodness of Rules</Title>
a722 2
<Note>
<title>Editor's Note</title>
d724 63
a786 6
This information resulted from an exchange of e-mail on 1998-02-20/22 between
<ULink url="mailto:jwieck@@debis.com">Jan Wieck</ULink>,
<ULink url="mailto:Andreas.Zeugswetter@@telecom.at">Andreas Zeugswetter</ULink>,
and
<ULink url="mailto:vadim@@sable.krasnoyarsk.su">Vadim B. Mikheev</ULink>
on the subject.
a787 1
</Note>
d790 9
d800 1
a800 2
From: Zeugswetter Andreas SARZ
To: Jan Wieck
d802 10
d814 160
a973 5
Since we have so little documentation on the rules, I think we should save
every 
little word describing them, so could you simply put the following into a
rules.readme 
(undigested is still better than not adding it)
d976 64
a1039 1
<Title>Rewrite Rules versus Triggers</Title>
d1042 642
a1683 2
> > Why I like the rewrite system is:
The benefits of the rewrite rules system include:
a1684 62
<VariableList>
<VarListEntry>
<Term>
Select Rewrite Possible
</Term>
<ListItem>
<Para>
A select trigger would be no good, due to optimizer concerns.
 
<Para>
Exactly that's what is done if you create  a  view.  Postgres
creates  a  regular  table  (look  at  pg_class  and into the
database directory) and then sets up a relation level instead
rewrite rule on select.
</ListItem>
</VarListEntry>

<VarListEntry>
<Term>
Dumb Client Possible
</Term>
<ListItem>
<Para>
The client can be really dumb, like MS Access or some other
standard ODBC tool
which does not know anything about funcs procs and the like
(even without using passthrough).

<Para>
The  client  must not know why and how and where the
data is left and coming from. But that's true in any case - a
trigger  for each row on insert can do anything different and
push the data wherever it wants.
</ListItem>
</VarListEntry>

<VarListEntry>
<Term>
Rewrite rules are more powerful than views
</Term>
<ListItem>
<Para>
Views are only one special rule case in Postgres.
</ListItem>
</VarListEntry>

<VarListEntry>
<Term>
Optimizer Used
</Term>
<ListItem>
<Para>
It allows the optimizer to get involved (this is where triggers
fail per definition).
</ListItem>
</VarListEntry>

<VarListEntry>
<Term>
Simple to use
</Term>
<ListItem>
d1686 120
a1805 2
Once understood it is very easy to use;
easier than triggers with <Acronym>C</Acronym> stored procedures at least.
a1806 3
</ListItem>
</VarListEntry>
</VariableList>
d1809 15
a1823 105
Optimizing again and again. If the rules aren't instead,  the
querytree  get's  additional queries for every rule appended.
Have a table field that references an entry in another  table
and  this entry should have a refcount. So on update you must
decrease the refcount from the old ref and increase it on the
new.   You  create  two  rules so the UPDATE will result in 1
scan and 2 nestloops with scans inside - really optimized  if
the  referenced value doesn't change.  And don't think that a
rule qual of NEW != CURRENT might help - that will result  in
2 mergejoins where the scanned tuples are compared.

<Note>
<Para>
I fought that like a windmill, I guess it would be better to kill the
CURRENT keyword
with this meaning alltogether, since it only has the same meaning as the
tablename itself.
I have already crossed it out of my mind and don't miss anything.
</Para>
</Note>

I think there should instead be an OLD and NEW keyword
like in triggers:
<ProgramListing>
referencing old as <replaceable class="parameter">oldname</replaceable> new as <replaceable class="parameter">newname</replaceable>
</ProgramListing>
that only reference the tuples in memory.

<Para>
BTW,  this  sample  doesn't  work currently because the rules
queries are appended at the end of the  querytree,  thus  the
decrement  scan  having  the  same qual will not find the old
tuple    at    all    because    it's    already     outdated
(command_counter_increment  between  processing the queries).
Referencing CURRENT in a rule is not what most  people  think
it is.

<Para>
The old 4.2 postgres had a second, instance level rule system
(prs2 stubs) that fired the rules actions when  actually  the
old  tuple and the new projected tuple where handy. There you
could have made also things like 'UPDATE NEW SET a = 4'  that
really   modified  the  in  memory  tuple  in  the  executors
expression context. Who the hell removed all that? It was  so
nice :-(

<Note>
<Title>Editor's Note</Title>
<Para>
This feature was removed by Jolly et. al. prior to v1.0.x.
</Para>
</Note>

<Para>
Absolutely !    I did cry up when that was done, but nobody responded :-(
Well to be honest Vadim did respond with the trigger code, which made me
feel comfortable again.

<Para>
A  really  simple to write trigger can compare old != new and
only if send down the other two queries. This time they  wont
be  nestloops,  they  are  simple  scans. And the trigger can
arrange that the queries it uses  are  only  parsed  on  it's
first  of  all  calls and store the generated execution plans
permanently for quick execution (look at SPI_prepare).

<Para>
For the stored C procedures you're  totally  right.  I  don't
like  the  C functions because it requires postgres superuser
rights to develop them and thus I created  PL/Tcl  where  joe
user  can  hack  around without having complete access to the
whole database (look at src/pl/tcl). And  someday  after  6.3
release  I'll really start on a plain PL/pgSQL implementation
that would give a  normal  user  the  opportunity  to  create
functions and triggers on a high level. There is light at the
end of the tunnel - hope that it isn't the coming train :-)

<Para>
I guess if triggers could also trigger simple select statements, I could
do
most of what I want using triggers except of course the select stuff.
But as I said I like the rules system very much, especially after your
recent
fixes Jan :-) So please stick to supporting all 3: triggers, views and
rules. Wow :-)

<Para>
Well - a trigger cannot build a view. The relation underlying
the view doesn't contain any tuples and a select trigger will
never be fired.  As long as there is no possibility to return
tuple  sets  from  non-SQL  functions.  But  a trigger can do
things like the pg_hide_passwd stuff much more powerful.  You
could  define  the trigger so that it checks if the user is a
superuser and overwrite the passwd value  only  in  the  case
where  he/she isn't. If fired at the right place it would too
work for things like the copy command etc.

<Para>
We must stay with all 3 features. And I will take a  look  at
the  INSERT  ...  SELECT  view problem really soon as it is a
rule system problem that breaks views. But this is  only  the
SELECT  rewriting part of the rule system which I really like
(optimizable). The other areas (insert,  update,  delete)  of
the  rule  system are dangerous and I really think a powerful
PL/pgSQL language could make them obsolete.
d1826 8
a1833 1
<Title>Summary from Andreas</Title>
d1836 33
a1868 1
Ok, to sum it up:
a1869 2
<ItemizedList Mark="bullet">
<ListItem>
d1871 10
a1880 1
We need and want the select part of the rewrite rules.
a1881 1
</ListItem>
a1882 1
<ListItem>
d1884 8
a1891 5
For the insert/update/delete rules the old instance rules system
	    was much more appropriate. TODO: dig up the old code
	    and merge it with the current trigger Implementation;
		    it must be pretty much the wanted functionality (it
supported SQL).
a1892 2
<Note>
<Title>Vadim's Note</Title>
d1894 16
a1909 4
Old instance rules system was removed by Jolly & Andrew and so
it never supported SQL. I hope that Jan will give us PL/pgSQL soon
and it will be used for triggers, without changing current trigger 
implementation...
d1911 4
a1914 1
</Note>
d1916 11
a1927 1
</ListItem>
a1928 1
<ListItem>
d1930 8
a1937 3
The CURRENT keyword in the i/u/d rewrite rules is stupid
and should be disabled
		   destroyed and burned in hell.
a1938 2
<Note>
<Title>Vadim's Note</Title>
d1940 8
a1947 2
Agreed, if standard hasn't it. I know that OLD & NEW are in standard,
for triggers atleast.
a1948 1
</Note>
d1950 106
a2056 1
</ListItem>
a2057 1
<ListItem>
d2059 11
a2069 4
To stick to the mainstream we should enhance the trigger
syntax,
		    and forget the rule stuff for i/u/d
		
d2071 3
a2073 5
		create trigger passwd_utr
		..........
		referencing old as o new as n
		  for each row (statement, statement, statement, procedure,
		...... all PL/pgSQL syntax allowed );
a2074 1
with a syntax to modify the new tuple in memory.
d2076 12
a2087 2
<Note>
<Title>Vadim's Note</Title>
d2089 21
a2109 3
Yes. Statement level triggers give the same functionality as rewrite 
i/u/d rules. We could let them to return something special to skip 
user' i/u/d itself, isn't it the same as INSTEAD ?
a2110 1
</Note>
d2112 6
d2119 1
a2119 2
</ListItem>
</ItemizedList>
@


1.2
log
@Include e-mail exchange between Jan and Andreas to start info on rules.
@
text
@d1 1
a1 1
<Chapter>
@


1.1
log
@SGML source for new documentation.
@
text
@d10 1
a10 1
<XRef LinkEnd="STON90b" EndTerm="[STON90b]"> to understand
d23 1
a23 1
<XRef LinkEnd="ONG90" EndTerm="[ONG90]">
d25 1
a25 1
<XRef LinkEnd="STON90b" EndTerm="[STON90b]">.
d27 291
@
