head	2.61;
access;
symbols
	REL7_2_8:2.53
	REL7_2_7:2.53
	REL7_2_6:2.53
	REL7_2_5:2.53
	REL7_2_4:2.53
	REL7_2_3:2.53
	REL7_2_STABLE:2.53.0.2
	REL7_2:2.53
	REL7_2_RC2:2.53
	REL7_2_RC1:2.53
	REL7_2_BETA5:2.53
	REL7_2_BETA4:2.51
	REL7_2_BETA3:2.49
	REL7_2_BETA2:2.45
	REL7_2_BETA1:2.45
	REL7_1_2:2.25
	REL7_1_STABLE:2.25.0.2
	REL7_1_BETA:2.10
	REL7_1_BETA3:2.12
	REL7_1_BETA2:2.12
	REL7_1:2.25
	REL7_0_PATCHES:2.8.0.2
	REL7_0:2.4;
locks; strict;
comment	@# @;


2.61
date	2002.07.30.19.36.13;	author momjian;	state dead;
branches;
next	2.60;

2.60
date	2002.06.24.23.12.06;	author tgl;	state Exp;
branches;
next	2.59;

2.59
date	2002.06.15.19.34.51;	author momjian;	state Exp;
branches;
next	2.58;

2.58
date	2002.05.03.04.11.07;	author tgl;	state Exp;
branches;
next	2.57;

2.57
date	2002.04.09.03.08.25;	author momjian;	state Exp;
branches;
next	2.56;

2.56
date	2002.04.09.02.43.25;	author momjian;	state Exp;
branches;
next	2.55;

2.55
date	2002.04.09.02.31.58;	author momjian;	state Exp;
branches;
next	2.54;

2.54
date	2002.03.22.19.20.18;	author petere;	state Exp;
branches;
next	2.53;

2.53
date	2002.01.07.02.29.13;	author petere;	state Exp;
branches;
next	2.52;

2.52
date	2002.01.02.00.41.26;	author tgl;	state Exp;
branches;
next	2.51;

2.51
date	2001.11.28.04.18.46;	author tgl;	state Exp;
branches;
next	2.50;

2.50
date	2001.11.21.05.53.41;	author thomas;	state Exp;
branches;
next	2.49;

2.49
date	2001.11.16.00.40.11;	author tgl;	state Exp;
branches;
next	2.48;

2.48
date	2001.11.15.23.32.39;	author tgl;	state Exp;
branches;
next	2.47;

2.47
date	2001.11.15.06.25.22;	author tgl;	state Exp;
branches;
next	2.46;

2.46
date	2001.11.08.23.41.12;	author petere;	state Exp;
branches;
next	2.45;

2.45
date	2001.10.13.04.58.35;	author momjian;	state Exp;
branches;
next	2.44;

2.44
date	2001.10.12.23.32.34;	author momjian;	state Exp;
branches;
next	2.43;

2.43
date	2001.10.12.21.19.09;	author momjian;	state Exp;
branches;
next	2.42;

2.42
date	2001.10.09.04.55.11;	author tgl;	state Exp;
branches;
next	2.41;

2.41
date	2001.10.09.04.15.38;	author tgl;	state Exp;
branches;
next	2.40;

2.40
date	2001.09.18.12.08.26;	author petere;	state Exp;
branches;
next	2.39;

2.39
date	2001.09.13.15.55.23;	author petere;	state Exp;
branches;
next	2.38;

2.38
date	2001.09.10.21.58.47;	author petere;	state Exp;
branches;
next	2.37;

2.37
date	2001.09.10.06.35.34;	author ishii;	state Exp;
branches;
next	2.36;

2.36
date	2001.09.10.06.30.43;	author ishii;	state Exp;
branches;
next	2.35;

2.35
date	2001.05.28.19.33.24;	author tgl;	state Exp;
branches;
next	2.34;

2.34
date	2001.05.28.14.58.58;	author petere;	state Exp;
branches;
next	2.33;

2.33
date	2001.05.22.13.52.27;	author momjian;	state Exp;
branches;
next	2.32;

2.32
date	2001.05.17.21.50.16;	author petere;	state Exp;
branches;
next	2.31;

2.31
date	2001.05.12.22.51.35;	author petere;	state Exp;
branches;
next	2.30;

2.30
date	2001.05.11.06.10.44;	author tgl;	state Exp;
branches;
next	2.29;

2.29
date	2001.05.08.02.53.24;	author tgl;	state Exp;
branches;
next	2.28;

2.28
date	2001.05.08.02.26.09;	author momjian;	state Exp;
branches;
next	2.27;

2.27
date	2001.05.08.00.30.41;	author momjian;	state Exp;
branches;
next	2.26;

2.26
date	2001.05.08.00.09.22;	author momjian;	state Exp;
branches;
next	2.25;

2.25
date	2001.03.23.22.07.50;	author tgl;	state Exp;
branches;
next	2.24;

2.24
date	2001.03.17.18.08.14;	author petere;	state Exp;
branches;
next	2.23;

2.23
date	2001.03.17.01.53.22;	author thomas;	state Exp;
branches;
next	2.22;

2.22
date	2001.03.09.19.09.00;	author petere;	state Exp;
branches;
next	2.21;

2.21
date	2001.02.21.17.50.38;	author petere;	state Exp;
branches;
next	2.20;

2.20
date	2001.02.19.19.49.52;	author tgl;	state Exp;
branches;
next	2.19;

2.19
date	2001.02.10.05.32.33;	author tgl;	state Exp;
branches;
next	2.18;

2.18
date	2001.01.20.20.59.29;	author petere;	state Exp;
branches;
next	2.17;

2.17
date	2001.01.18.07.11.36;	author thomas;	state Exp;
branches;
next	2.16;

2.16
date	2001.01.17.22.13.33;	author momjian;	state Exp;
branches;
next	2.15;

2.15
date	2001.01.17.16.34.34;	author momjian;	state Exp;
branches;
next	2.14;

2.14
date	2001.01.13.23.58.55;	author petere;	state Exp;
branches;
next	2.13;

2.13
date	2001.01.09.15.26.16;	author momjian;	state Exp;
branches;
next	2.12;

2.12
date	2001.01.06.12.26.08;	author petere;	state Exp;
branches;
next	2.11;

2.11
date	2000.12.22.18.57.50;	author petere;	state Exp;
branches;
next	2.10;

2.10
date	2000.09.29.20.21.34;	author petere;	state Exp;
branches;
next	2.9;

2.9
date	2000.08.25.15.17.36;	author thomas;	state Exp;
branches;
next	2.8;

2.8
date	2000.05.17.00.15.48;	author momjian;	state Exp;
branches;
next	2.7;

2.7
date	2000.05.16.21.16.12;	author momjian;	state Exp;
branches;
next	2.6;

2.6
date	2000.05.16.19.29.43;	author momjian;	state Exp;
branches;
next	2.5;

2.5
date	2000.05.09.18.27.25;	author momjian;	state Exp;
branches;
next	2.4;

2.4
date	2000.05.02.20.01.52;	author thomas;	state Exp;
branches;
next	2.3;

2.3
date	2000.03.31.06.17.21;	author thomas;	state Exp;
branches;
next	2.2;

2.2
date	2000.03.31.03.27.41;	author thomas;	state Exp;
branches;
next	2.1;

2.1
date	2000.03.30.22.13.30;	author thomas;	state Exp;
branches;
next	;


desc
@@


2.61
log
@Would it be wise to have the plsql.sgml file renamed to plpgsql.sgml?
All of the internal tags are of the latter.

The other thing I noticed is that most of the quick examples in the file
use a para and synopsis.  Is there a reason we're not using <example/> ?

Rod Taylor
@
text
@<!--
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.60 2002/06/24 23:12:06 tgl Exp $
-->

<chapter id="plpgsql"> 
  <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>

 <indexterm zone="plpgsql">
  <primary>PL/pgSQL</primary>
 </indexterm>

 <para>
  <application>PL/pgSQL</application> is a loadable procedural language for the
  <productname>PostgreSQL</productname> database system.
 </para>
   
 <para>
  This package was originally written by Jan Wieck. This
  documentation was in part written 
  by Roberto Mello (<email>rmello@@fslc.usu.edu</email>).
 </para>

  <sect1 id="plpgsql-overview">
   <title>Overview</title>

   <para>
    The design goals of <application>PL/pgSQL</> were to create a loadable procedural
    language that
    <itemizedlist>
     <listitem>
      <para>
       can be used to create functions and trigger procedures,
      </para>
     </listitem>
     <listitem>
      <para>
       adds control structures to the <acronym>SQL</acronym> language,
      </para>
     </listitem>
     <listitem>
      <para>
       can perform complex computations,
      </para>
     </listitem>
     <listitem>
      <para>
       inherits all user defined types, functions and operators,
      </para>
     </listitem>
     <listitem>
      <para>
       can be defined to be trusted by the server,
      </para>
     </listitem>
     <listitem>
      <para>
       is easy to use.
      </para>
     </listitem>
    </itemizedlist>
   </para>
   <para>
    The <application>PL/pgSQL</> call handler parses the function's source text and
    produces an internal binary instruction tree the first time the
    function is called (within any one backend process).  The instruction tree
    fully translates the 
    <application>PL/pgSQL</> statement structure, but individual
    <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> queries
    used in the function are not translated immediately.
   </para>
   <para>
    As each expression and <acronym>SQL</acronym> query is first used
    in the function, the <application>PL/pgSQL</> interpreter creates a
    prepared execution plan (using the <acronym>SPI</acronym> manager's 
    <function>SPI_prepare</function> and
    <function>SPI_saveplan</function> functions).  Subsequent visits
    to that expression or query re-use the prepared plan.  Thus, a function
    with conditional code that contains many statements for which execution
    plans might be required, will only prepare and save those plans
    that are really used during the lifetime of the database
    connection.  This can provide a considerable savings of parsing
    activity.  A disadvantage is that errors in a specific expression
    or query may not be detected until that part of the function is
    reached in execution.
   </para>
  <para>
   Once <application>PL/pgSQL</> has made a query plan for a particular
   query in a function, it will re-use that plan for the life of the
   database connection.  This is usually a win for performance, but it
   can cause some problems if you dynamically
   alter your database schema. For example:

<programlisting>
CREATE FUNCTION populate() RETURNS INTEGER AS '
DECLARE
    -- Declarations
BEGIN
    PERFORM my_function();
END;
' LANGUAGE 'plpgsql';
</programlisting>
    If you execute the above function, it will reference the OID for
    <function>my_function()</function> in the query plan produced for
    the PERFORM statement. Later, if you
    drop and re-create <function>my_function()</function>, then
    <function>populate()</function> will not be able to find
    <function>my_function()</function> anymore. You would then have to
    re-create <function>populate()</function>, or at least start a new
    database session so that it will be compiled afresh.
   </para>

   <para>
    Because <application>PL/pgSQL</application> saves execution plans in this way, queries that appear
    directly in a <application>PL/pgSQL</application> function must refer to the same tables and fields
    on every execution; that is, you cannot use a parameter as the name of
    a table or field in a query.  To get around
    this restriction, you can construct dynamic queries using the <application>PL/pgSQL</application>
    EXECUTE statement --- at the price of constructing a new query plan
    on every execution.
   </para>
   <para>
    Except for input/output conversion and calculation functions
    for user defined types, anything that can be defined in C language
    functions can also be done with <application>PL/pgSQL</application>. It is possible to
    create complex conditional computation functions and later use
    them to define operators or use them in functional indexes.
   </para>
  <sect2 id="plpgsql-advantages">
   <title>Advantages of Using PL/pgSQL</title>

   <itemizedlist>
    <listitem>
     <para>
      Better performance (see <xref linkend="plpgsql-advantages-performance">)
     </para>
    </listitem>

    <listitem>
     <para>
      SQL support (see <xref linkend="plpgsql-advantages-sqlsupport">)
     </para>
    </listitem> 

    <listitem>
     <para>
      Portability (see <xref linkend="plpgsql-advantages-portability">)
     </para>
    </listitem>
   </itemizedlist>

   <sect3 id="plpgsql-advantages-performance">
    <title>Better Performance</title>

    <para>
     <acronym>SQL</acronym> is the language <productname>PostgreSQL</> (and
     most other Relational Databases) use as query
     language. It's portable and easy to learn. But every
     <acronym>SQL</acronym> statement must be executed
     individually by the database server.
    </para>

    <para>
     That means that your client application must send each
     query to the database server, wait for it to process it,
     receive the results, do some computation, then send
     other queries to the server. All this incurs inter-process communication
     and may also incur network
     overhead if your client is on a different machine than
     the database server.
    </para>

    <para>
     With <application>PL/pgSQL</application> you can group a block of computation and a
     series of queries <emphasis>inside</emphasis> the
     database server, thus having the power of a procedural
     language and the ease of use of SQL, but saving lots of
     time because you don't have the whole client/server
     communication overhead. This can make for a
     considerable performance increase.
    </para>
   </sect3>

   <sect3 id="plpgsql-advantages-sqlsupport">
    <title>SQL Support</title>

    <para>
     <application>PL/pgSQL</application> adds the power of a procedural language to the
     flexibility and ease of <acronym>SQL</acronym>. With
     <application>PL/pgSQL</application> you can use all the data types, columns, operators
     and functions of SQL.    
    </para>
   </sect3>

   <sect3 id="plpgsql-advantages-portability">
    <title>Portability</title>

    <para>
     Because <application>PL/pgSQL</application> functions run inside <productname>PostgreSQL</>, these
     functions will run on any platform where <productname>PostgreSQL</>
     runs. Thus you can reuse code and have less development costs.
    </para>
   </sect3>
  </sect2>

  <sect2 id="plpgsql-overview-developing-in-plpgsql">
   <title>Developing in <application>PL/pgSQL</application></title>

   <para>
    Developing in <application>PL/pgSQL</application> is pretty straight forward, especially
    if you have developed in other database procedural languages,
    such as Oracle's <application>PL/SQL</application>. Two good ways of developing in
    <application>PL/pgSQL</application> are:

    <itemizedlist>
     <listitem>
      <para>
       Using a text editor and reloading the file with <command>psql</command>
      </para>
     </listitem>

     <listitem>
      <para>
       Using <productname>PostgreSQL</>'s GUI Tool: <application>PgAccess</>
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    One good way to develop in <application>PL/pgSQL</> is to simply use the text
    editor of your choice to create your functions, and in another
    console, use <command>psql</command> (PostgreSQL's interactive monitor) to load
    those functions. If you are doing it this way, it is a good
    idea to write the function using <command>CREATE OR REPLACE
    FUNCTION</command>. That way you can reload the file to update
    the function definition.  For example:
<programlisting>
CREATE OR REPLACE FUNCTION testfunc(INTEGER) RETURNS INTEGER AS '
    ....
end;
' LANGUAGE 'plpgsql';
</programlisting>
   </para>

   <para>
    While running <command>psql</command>, you can load or reload such a
    function definition file with
<programlisting>
    \i filename.sql
</programlisting>
    and then immediately issue SQL commands to test the function.
   </para>

   <para>
    Another good way to develop in <application>PL/pgSQL</> is using
    <productname>PostgreSQL</>'s GUI tool: <application>PgAccess</>. It does some
    nice things for you, like escaping single-quotes, and making
    it easy to recreate and debug functions.
   </para>
  </sect2>
 </sect1>

 <sect1 id="plpgsql-structure">
  <title>Structure of <application>PL/pgSQL</application></title>

    <para>
     <application>PL/pgSQL</application> is a <emphasis>block
     structured</emphasis> language.  The complete text of a function
     definition must be a <firstterm>block</>. A block is defined as:

<synopsis>
<optional> &lt;&lt;label&gt;&gt; </optional>
<optional> DECLARE
    <replaceable>declarations</replaceable> </optional>
BEGIN
    <replaceable>statements</replaceable>
END;
</synopsis>
    </para>

    <para>
     Any <firstterm>statement</> in the statement section of a block
     can be a <firstterm>sub-block</>.  Sub-blocks can be used for
     logical grouping or to localize variables to a small group
     of statements.
    </para>

    <para>
     The variables declared in the declarations section preceding a
     block are initialized to their default values every time the
     block is entered, not only once per function call. For example:
<programlisting>
CREATE FUNCTION somefunc() RETURNS INTEGER AS '
DECLARE
   quantity INTEGER := 30;
BEGIN
   RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 30
   quantity := 50;
   --
   -- Create a sub-block
   --
   DECLARE
      quantity INTEGER := 80;
   BEGIN
      RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 80
   END;

   RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 50

   RETURN quantity;
END;
' LANGUAGE 'plpgsql';
</programlisting>
    </para>

    <para>
     It is important not to confuse the use of BEGIN/END for
     grouping statements in <application>PL/pgSQL</> with the database commands for
     transaction control.  <application>PL/pgSQL</>'s BEGIN/END are only for grouping;
     they do not start or end a transaction.  Functions and trigger procedures
     are always executed within a transaction established by an outer query
     --- they cannot start or commit transactions, since
     <productname>PostgreSQL</productname> does not have nested transactions.
    </para>

   <sect2>
    <title>Lexical Details</title>

    <para>
     Each statement and declaration within a block is terminated
     by a semicolon.
    </para>

    <para>
     All keywords and identifiers can be written in mixed upper- and
     lower-case.  Identifiers are implicitly converted to lower-case
     unless double-quoted.
    </para>

    <para>
     There are two types of comments in <application>PL/pgSQL</>. A double dash <literal>--</literal>
     starts a comment that extends to the end of the line. A <literal>/*</literal>
     starts a block comment that extends to the next occurrence of <literal>*/</literal>.
     Block comments cannot be nested, but double dash comments can be
     enclosed into a block comment and a double dash can hide
     the block comment delimiters <literal>/*</literal> and <literal>*/</literal>.
    </para>
   </sect2>
  </sect1>

  <sect1 id="plpgsql-declarations">
    <title>Declarations</title>

    <para>
     All variables, rows and records used in a block must be declared in the
     declarations section of the block. 
     (The only exception is that the loop variable of a FOR loop iterating
     over a range of integer values is automatically declared as an integer
     variable.)
    </para>

    <para>
     <application>PL/pgSQL</> variables can have any SQL data type, such as
     <type>INTEGER</type>, <type>VARCHAR</type> and
     <type>CHAR</type>.
    </para>

    <para>
     Here are some examples of variable declarations:
<programlisting>
user_id INTEGER;
quantity NUMERIC(5);
url VARCHAR;
myrow tablename%ROWTYPE;
myfield tablename.fieldname%TYPE;
arow RECORD;
</programlisting>
    </para>

    <para>
     The general syntax of a variable declaration is:
<synopsis>
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
</synopsis>
     </para>

     <para>
      The DEFAULT clause, if given, specifies the initial value assigned
      to the variable when the block is entered.  If the DEFAULT clause
      is not given then the variable is initialized to the
     <acronym>SQL</acronym> NULL value. 
     </para>

     <para>
      The CONSTANT option prevents the variable from being assigned to,
      so that its value remains constant for the duration of the block.
      If NOT NULL
      is specified, an assignment of a NULL value results in a run-time
      error. All variables declared as NOT NULL
      must have a non-NULL default value specified.
     </para>

     <para>
      The default value is evaluated every time the block is entered. So,
      for example, assigning '<literal>now</literal>' to a variable of type
      <type>timestamp</type> causes the variable to have the
      time of the current function call, not when the function was
      precompiled.
     </para>

     <para>
      Examples:
<programlisting>
quantity INTEGER DEFAULT 32;
url varchar := ''http://mysite.com'';
user_id CONSTANT INTEGER := 10;
</programlisting>
     </para>

    <sect2 id="plpgsql-declaration-aliases">
     <title>Aliases for Function Parameters</title>

    <para>
<synopsis>
<replaceable>name</replaceable> ALIAS FOR <replaceable>$n</replaceable>;
</synopsis>
    </para>

     <para>
      Parameters passed to functions are named with the identifiers
      <literal>$1</literal>, <literal>$2</literal>,
      etc.  Optionally, aliases can be declared for <literal>$n</literal>
      parameter names for increased readability.  Either the alias or the
      numeric identifier can then be used to refer to the parameter value.
      Some examples:
<programlisting>
CREATE FUNCTION sales_tax(REAL) RETURNS REAL AS '
DECLARE
    subtotal ALIAS FOR $1;
BEGIN
    return subtotal * 0.06;
END;
' LANGUAGE 'plpgsql';


CREATE FUNCTION instr(VARCHAR,INTEGER) RETURNS INTEGER AS '
DECLARE
    v_string ALIAS FOR $1;
    index ALIAS FOR $2;
BEGIN
    -- Some computations here
END;
' LANGUAGE 'plpgsql';


CREATE FUNCTION use_many_fields(tablename) RETURNS TEXT AS '
DECLARE
    in_t ALIAS FOR $1;
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
' LANGUAGE 'plpgsql';
</programlisting>
     </para>
    </sect2>

    <sect2 id="plpgsql-declaration-rowtypes">
     <title>Row Types</title>

    <para>
<synopsis>
<replaceable>name</replaceable> <replaceable>tablename</replaceable><literal>%ROWTYPE</literal>;
</synopsis>
    </para>

   <para>
    A variable of a composite type is called a <firstterm>row</>
    variable (or <firstterm>row-type</> variable).  Such a variable can hold a
    whole row of a SELECT or FOR
    query result, so long as that query's column set matches the declared
    type of the variable.  The individual fields of the row value are
    accessed using the usual dot notation, for example
    <literal>rowvar.field</literal>.
   </para>

   <para>
    Presently, a row variable can only be declared using the
    <literal>%ROWTYPE</literal> notation; although one might expect a
    bare table name to work as a type declaration, it won't be accepted
    within <application>PL/pgSQL</application> functions.
   </para>

   <para>
    Parameters to a function can be
    composite types (complete table rows). In that case, the
    corresponding identifier $n will be a row variable, and fields can
    be selected from it, for example <literal>$1.user_id</literal>.
   </para>

   <para>
    Only the user-defined attributes of a table row are accessible in a
    row-type variable, not OID or other system attributes (because the
    row could be from a view).  The fields of the row type inherit the
    table's field size or precision for data types such as
    <type>char(n)</type>.
<programlisting>
CREATE FUNCTION use_two_tables(tablename) RETURNS TEXT AS '
DECLARE
    in_t ALIAS FOR $1;
    use_t table2name%ROWTYPE;
BEGIN
    SELECT * INTO use_t FROM table2name WHERE ... ;
    RETURN in_t.f1 || use_t.f3 || in_t.f5 || use_t.f7;
END;
' LANGUAGE 'plpgsql';
</programlisting>
   </para>
  </sect2>

    <sect2 id="plpgsql-declaration-records">
     <title>Records</title>

    <para>
<synopsis>
<replaceable>name</replaceable> RECORD;
</synopsis>
    </para>

   <para>
    Record variables are similar to row-type variables, but they have no
    predefined structure.  They take on the actual row structure of the
    row they are assigned during a SELECT or FOR command.  The substructure
    of a record variable can change each time it is assigned to.
    A consequence of this is that until a record variable is first assigned
    to, <emphasis>it has no</> substructure, and any attempt to access a
    field in it will draw a run-time error.
   </para>

   <para>
    Note that <literal>RECORD</> is not a true data type, only a placeholder.
    Thus, for example, one cannot declare a function returning
    <literal>RECORD</>.
   </para>
  </sect2>

    <sect2 id="plpgsql-declaration-attributes">
     <title>Attributes</title>

     <para>
      Using the <type>%TYPE</type> and <type>%ROWTYPE</type>
      attributes, you can declare variables with the same
      data type or structure as another database item (e.g: a
      table field).
     </para>

     <variablelist>
      <varlistentry>
       <term>
        <replaceable>variable</replaceable>%TYPE
       </term>
       <listitem>
        <para>
         <type>%TYPE</type> provides the data type of a
         variable or database column. You can use this to
         declare variables that will hold database
         values. For example, let's say you have a column
         named <type>user_id</type> in your
         <type>users</type> table. To declare a variable with
         the same data type as <structname>users</>.<structfield>user_id</> you write:
<programlisting>
user_id   users.user_id%TYPE;
</programlisting>
        </para>

        <para>
         By using <type>%TYPE</type> you don't need to know
         the data type of the structure you are referencing,
         and most important, if the data type of the
         referenced item changes in the future (e.g: you
         change your table definition of user_id from INTEGER to
         REAL), you may not need to change your function
         definition.
        </para>
       </listitem>
      </varlistentry>

      <varlistentry>
       <term>
        <literal><replaceable>table</replaceable>%ROWTYPE</literal>
       </term>
       <listitem>
        <para>
	 <type>%ROWTYPE</type> provides the composite data type corresponding
	 to a whole row of the specified table.
	 <replaceable>table</replaceable> must be an existing
	 table or view name of the database.
        </para>

<programlisting>
DECLARE
    users_rec users%ROWTYPE;
    user_id users.user_id%TYPE;
BEGIN
    user_id := users_rec.user_id;
    ...

CREATE FUNCTION does_view_exist(INTEGER) RETURNS bool AS '
   DECLARE
        key ALIAS FOR $1;
        table_data cs_materialized_views%ROWTYPE;
   BEGIN
        SELECT INTO table_data * FROM cs_materialized_views
               WHERE sort_key=key;

        IF NOT FOUND THEN
           RETURN false;
        END IF;
        RETURN true;
   END;
' LANGUAGE 'plpgsql';
</programlisting>
       </listitem>
      </varlistentry>
     </variablelist>
    </sect2>

    <sect2 id="plpgsql-declaration-renaming-vars">
     <title>RENAME</title>

     <para>
<synopsis>
RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
</synopsis>

      Using the RENAME declaration you can change the name of a variable,
      record or row. This is primarily useful if NEW or OLD should be
      referenced by another name inside a trigger procedure.  See also ALIAS.
     </para>

     <para>
      Examples:
<programlisting>
RENAME id TO user_id;
RENAME this_var TO that_var;
</programlisting>
     </para>

    <note>
    <para>
     RENAME appears to be broken as of PostgreSQL 7.2.  Fixing this is
     of low priority, since ALIAS covers most of the practical uses of
     RENAME.
    </para>
    </note>

    </sect2>
  </sect1>

  <sect1 id="plpgsql-expressions">
  <title>Expressions</title>

    <para>
     All expressions used in <application>PL/pgSQL</application> statements
     are processed using the server's regular SQL executor. Expressions that
     appear to contain 
     constants may in fact require run-time evaluation
     (e.g. <literal>'now'</literal>  for the 
     <type>timestamp</type> type) so
     it is impossible for the <application>PL/pgSQL</application> parser
     to identify real constant values other than the NULL keyword. All
     expressions are evaluated internally by executing a query
<synopsis>
SELECT <replaceable>expression</replaceable>
</synopsis>
     using the <acronym>SPI</acronym> manager. In the expression, occurrences
     of <application>PL/pgSQL</application> variable 
     identifiers are replaced by parameters and the actual values from
     the variables are passed to the executor in the parameter array.
     This allows the query plan for the SELECT to be prepared just once
     and then re-used for subsequent evaluations.
    </para>

    <para>
     The evaluation done by the <productname>PostgreSQL</productname>
     main parser has some side
     effects on the interpretation of constant values. In detail there
     is a difference between what these two functions do:

<programlisting>
CREATE FUNCTION logfunc1 (TEXT) RETURNS TIMESTAMP AS '
    DECLARE
        logtxt ALIAS FOR $1;
    BEGIN
        INSERT INTO logtable VALUES (logtxt, ''now'');
        RETURN ''now'';
    END;
' LANGUAGE 'plpgsql';
</programlisting>

     and

<programlisting>
CREATE FUNCTION logfunc2 (TEXT) RETURNS TIMESTAMP AS '
    DECLARE
        logtxt ALIAS FOR $1;
        curtime timestamp;
    BEGIN
        curtime := ''now'';
        INSERT INTO logtable VALUES (logtxt, curtime);
        RETURN curtime;
    END;
' LANGUAGE 'plpgsql';
</programlisting>

     In the case of <function>logfunc1()</function>, the 
     <productname>PostgreSQL</productname> main parser knows when 
     preparing the plan for the INSERT, that the string 
     <literal>'now'</literal> should be interpreted as 
     <type>timestamp</type> because the target field of <classname>logtable</classname>
     is of that type. Thus, it will make a constant from it at this
     time and this constant value is then used in all invocations of 
     <function>logfunc1()</function> during the lifetime of the
     backend. Needless to say that this isn't what the
     programmer wanted.
    </para>

    <para>
     In the case of <function>logfunc2()</function>, the 
     <productname>PostgreSQL</productname> main parser does not know
     what type <literal>'now'</literal> should become and therefore 
     it returns a data value of type <type>text</type> containing the string 
     <literal>'now'</literal>. During the ensuing assignment
     to the local variable <varname>curtime</varname>, the
     <application>PL/pgSQL</application> interpreter casts this
     string to the <type>timestamp</type> type by calling the
     <function>text_out()</function> and <function>timestamp_in()</function>
     functions for the conversion.  So, the computed time stamp is updated
     on each execution as the programmer expects.
    </para>

    <para>
     The mutable nature of record variables presents a problem in this
     connection.  When fields of a record variable are used in expressions or
     statements, the data types of the
     fields must not change between calls of one and the same expression,
     since the expression will be planned using the data type that is present
     when the expression is first reached.
     Keep this in mind when writing trigger procedures that handle events
     for more than one table.  (EXECUTE can be used to get around this
     problem when necessary.)
    </para>
  </sect1>

  <sect1 id="plpgsql-statements">
  <title>Basic Statements</title>

   <para>
    In this section and the following ones, we describe all the statement
    types that are explicitly understood by
    <application>PL/pgSQL</application>.
    Anything not recognized as one of these statement types is presumed
    to be an SQL query, and is sent to the main database engine to execute
    (after substitution for any <application>PL/pgSQL</application> variables
    used in the statement).  Thus,
    for example, SQL <command>INSERT</>, <command>UPDATE</>, and
    <command>DELETE</> commands may be considered to be statements of
    <application>PL/pgSQL</application>.  But they are not specifically
    listed here.
   </para>
   
   <sect2 id="plpgsql-statements-assignment">
    <title>Assignment</title>

    <para>
     An assignment of a value to a variable or row/record field is
     written as:
<synopsis>
<replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
</synopsis>
     As explained above, the expression in such a statement is evaluated
     by means of an SQL <command>SELECT</> command sent to the main
     database engine.  The expression must yield a single value.
    </para>

    <para>
     If the expression's result data type doesn't match the variable's
     data type, or the variable has a specific size/precision
     (like <type>char(20)</type>), the result value will be implicitly
     converted by the <application>PL/pgSQL</application> interpreter using
     the result type's output-function and 
     the variable type's input-function. Note that this could potentially
     result in run-time errors generated by the input function, if the
     string form of the result value is not acceptable to the input function.
    </para>

    <para>
     Examples:
<programlisting>
user_id := 20;
tax := subtotal * 0.06;
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-select-into">
    <title>SELECT INTO</title>

    <para>
     The result of a SELECT command yielding multiple columns (but
     only one row) can be assigned to a record variable, row-type
     variable, or list of scalar variables.  This is done by:

<synopsis>
SELECT INTO <replaceable>target</replaceable> <replaceable>expressions</replaceable> FROM ...;
</synopsis>

     where <replaceable>target</replaceable> can be a record variable, a row
     variable, or a comma-separated list of simple variables and
     record/row fields. Note that this is quite different from
     <productname>PostgreSQL</>'s normal interpretation of SELECT INTO, which is that the
     INTO target is a newly created table.  (If you want to create a
     table from a SELECT result inside a <application>PL/pgSQL</application> function, use the
     syntax <command>CREATE TABLE ... AS SELECT</command>.)
    </para>

    <para>
     If a row or a variable list is used as target, the selected values
     must exactly match the structure of the target(s), or a run-time error
     occurs.  When a record variable is the target, it automatically
     configures itself to the row type of the query result columns.
    </para>

    <para>
     Except for the INTO clause, the SELECT statement is the same as a normal
     SQL SELECT query and can use the full power of SELECT.
    </para>

    <para>
     If the SELECT query returns zero rows, NULLs are assigned to the
     target(s).  If the SELECT query returns multiple rows, the first
     row is assigned to the target(s) and the rest are discarded.
     (Note that <quote>the first row</> is not well-defined unless you've
     used ORDER BY.)
    </para>

    <para>
     At present, the INTO clause can appear almost anywhere in the SELECT
     query, but it is recommended to place it immediately after the SELECT
     keyword as depicted above.  Future versions of
     <application>PL/pgSQL</application> may be less forgiving about
     placement of the INTO clause.
    </para>

    <para>
     There is a special variable named FOUND of type
     <type>boolean</type> that can be used immediately after a SELECT
     INTO to check if an assignment had success (that is, at least one
     row was returned by the SELECT).  For example,
  
<programlisting>
SELECT INTO myrec * FROM EMP WHERE empname = myname;
IF NOT FOUND THEN
    RAISE EXCEPTION ''employee % not found'', myname;
END IF;
</programlisting>

     Alternatively, you can use the IS NULL (or ISNULL) conditional to
     test for NULLity of a RECORD/ROW result.  Note that there is no
     way to tell whether any additional rows might have been discarded.
    </para>

    <para>
<programlisting>
DECLARE
    users_rec RECORD;
    full_name varchar;
BEGIN
    SELECT INTO users_rec * FROM users WHERE user_id=3;

    IF users_rec.homepage IS NULL THEN
        -- user entered no homepage, return "http://"

        RETURN ''http://'';
    END IF;
END;
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-perform">
    <title>Executing an expression or query with no result</title>

    <para>
     Sometimes one wishes to evaluate an expression or query but discard
     the result (typically because one is calling a function that has
     useful side-effects but no useful result value).  To do this in
     <application>PL/pgSQL</application>, use the PERFORM statement:

<synopsis>
PERFORM <replaceable>query</replaceable>;
</synopsis>

     This executes a <literal>SELECT</literal>
     <replaceable>query</replaceable> and discards the
     result. <application>PL/pgSQL</application> variables are substituted
     in the query as usual.  Also, the special variable FOUND is set to
     true if the query produced at least one row, or false if it produced
     no rows.
    </para>

    <note>
    <para>
     One might expect that SELECT with no INTO clause would accomplish
     this result, but at present the only accepted way to do it is PERFORM.
    </para>
    </note>

    <para>
     An example:
<programlisting>
PERFORM create_mv(''cs_session_page_requests_mv'', my_query);
</programlisting>
    </para>
   </sect2>
   
   <sect2 id="plpgsql-statements-executing-dyn-queries">
    <title>Executing dynamic queries</title>
    
    <para>
     Oftentimes you will want to generate dynamic queries inside
     your <application>PL/pgSQL</application> functions, that is,
     queries that will involve different tables or different data types
     each time they are executed.  <application>PL/pgSQL</application>'s
     normal attempts to cache plans for queries will not work in such
     scenarios.  To handle this sort of problem, the EXECUTE statement
     is provided:

<synopsis>
EXECUTE <replaceable class="command">query-string</replaceable>;
</synopsis>

     where <replaceable>query-string</replaceable> is an expression
     yielding a string (of type
     <type>text</type>) containing the <replaceable>query</replaceable>
     to be executed.  This string is fed literally to the SQL engine.
    </para>

    <para>
     Note in particular that no substitution of <application>PL/pgSQL</>
     variables is done on the query string.  The values of variables must
     be inserted in the query string as it is constructed.
    </para>

    <para>
    When working with dynamic queries you will have to face
    escaping of single quotes in <application>PL/pgSQL</>. Please refer to the
    table in <xref linkend="plpgsql-porting">
    for a detailed explanation that will save you some effort.
    </para>
     
    <para>
     Unlike all other queries in <application>PL/pgSQL</>, a
     <replaceable>query</replaceable> run by an EXECUTE statement is
     not prepared and saved just once during the life of the server.
     Instead, the <replaceable>query</replaceable> is prepared each
     time the statement is run. The
     <replaceable>query-string</replaceable> can be dynamically
     created within the procedure to perform actions on variable
     tables and fields.
    </para>
  
    <para>
     The results from SELECT queries are discarded by EXECUTE, and
     SELECT INTO is not currently supported within EXECUTE.  So, the
     only way to extract a result from a dynamically-created SELECT is
     to use the FOR-IN-EXECUTE form described later.
    </para>

    <para>
     An example:
<synopsis>
EXECUTE ''UPDATE tbl SET ''
        || quote_ident(fieldname)
        || '' = ''
        || quote_literal(newvalue)
        || '' WHERE ...'';
</synopsis>
    </para>

    <para>
     This example shows use of the functions
     <function>quote_ident</function>(<type>TEXT</type>) and
     <function>quote_literal</function>(<type>TEXT</type>).
     Variables containing field and table identifiers should be
     passed to function <function>quote_ident()</function>.
     Variables containing literal elements of the dynamic query
     string should be passed to
     <function>quote_literal()</function>.  Both take the
     appropriate steps to return the input text enclosed in single
     or double quotes and with any embedded special characters
     properly escaped.
    </para>

    <para>
     Here is a much larger example of a dynamic query and EXECUTE:
<programlisting>
CREATE FUNCTION cs_update_referrer_type_proc() RETURNS INTEGER AS '
DECLARE
    referrer_keys RECORD;  -- Declare a generic record to be used in a FOR
    a_output varchar(4000);
BEGIN 
    a_output := ''CREATE FUNCTION cs_find_referrer_type(varchar,varchar,varchar) 
                  RETURNS VARCHAR AS '''' 
                     DECLARE 
                         v_host ALIAS FOR $1; 
                         v_domain ALIAS FOR $2; 
                         v_url ALIAS FOR $3;
                     BEGIN ''; 

    -- 
    -- Notice how we scan through the results of a query in a FOR loop
    -- using the FOR &lt;record&gt; construct.
    --

    FOR referrer_keys IN SELECT * FROM cs_referrer_keys ORDER BY try_order LOOP
        a_output := a_output || '' IF v_'' || referrer_keys.kind || '' LIKE '''''''''' 
                 || referrer_keys.key_string || '''''''''' THEN RETURN '''''' 
                 || referrer_keys.referrer_type || ''''''; END IF;''; 
    END LOOP; 
  
    a_output := a_output || '' RETURN NULL; END; '''' LANGUAGE ''''plpgsql'''';''; 
 
    -- This works because we are not substituting any variables
    -- Otherwise it would fail. Look at PERFORM for another way to run functions
    
    EXECUTE a_output; 
END; 
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
   </sect2>

   <sect2 id="plpgsql-statements-diagnostics">
    <title>Obtaining result status</title>

    <para>
<synopsis>
GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional> ;
</synopsis>

     This command allows retrieval of system status indicators.  Each
     <replaceable>item</replaceable> is a keyword identifying a state
     value to be assigned to the specified variable (which should be
     of the right data type to receive it).  The currently available
     status items are <varname>ROW_COUNT</>, the number of rows
     processed by the last <acronym>SQL</acronym> query sent down to
     the <acronym>SQL</acronym> engine; and <varname>RESULT_OID</>,
     the OID of the last row inserted by the most recent
     <acronym>SQL</acronym> query.  Note that <varname>RESULT_OID</>
     is only useful after an INSERT query.
    </para>
   </sect2>
  </sect1>

  <sect1 id="plpgsql-control-structures">
   <title>Control Structures</title>

   <para>
    Control structures are probably the most useful (and
    important) part of <application>PL/pgSQL</>. With
    <application>PL/pgSQL</>'s control structures,
    you can manipulate <productname>PostgreSQL</> data in a very
    flexible and powerful way. 
   </para>
   
   <sect2 id="plpgsql-statements-returning">
    <title>Returning from a function</title>

    <para>
<synopsis>
RETURN <replaceable>expression</replaceable>;
</synopsis>

     The function terminates and the value of
     <replaceable>expression</replaceable> will be returned to the
     upper executor.
     The expression's result will be automatically cast into the
     function's return type as described for assignments.
    </para>

    <para>
     The return value of a function cannot be left undefined. If control
     reaches the end of the top-level block of 
     the function without hitting a RETURN statement, a run-time error
     will occur.
    </para>
   </sect2>
    
   <sect2 id="plpgsql-conditionals">
    <title>Conditionals</title>

    <para>
     <function>IF</function> statements let you execute commands based on
      certain conditions.
      <application>PL/pgSQL</> has four forms of IF: IF-THEN, IF-THEN-ELSE,
      IF-THEN-ELSE IF, and IF-THEN-ELSIF-THEN-ELSE.
    </para>

    <sect3>
     <title>IF-THEN</title>

       <para>
<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
END IF;
</synopsis>

        IF-THEN statements are the simplest form of IF. The
        statements between THEN and END IF will be executed if
        the condition is true. Otherwise, they are skipped.

<programlisting>
IF v_user_id &lt;&gt; 0 THEN
    UPDATE users SET email = v_email WHERE user_id = v_user_id;
END IF;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title>IF-THEN-ELSE</title>

       <para>
<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
ELSE
    <replaceable>statements</replaceable>
END IF;
</synopsis>

        IF-THEN-ELSE statements add to IF-THEN by letting you
        specify an alternative set of statements that should be executed if
	the condition evaluates to FALSE.

<programlisting>
IF parentid IS NULL or parentid = ''''
THEN 
    return fullname;
ELSE
    return hp_true_filename(parentid) || ''/'' || fullname;
END IF;


IF v_count > 0 THEN 
    INSERT INTO users_count(count) VALUES(v_count);
    return ''t'';
ELSE 
    return ''f'';
END IF;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title>IF-THEN-ELSE IF</title>

       <para>
        IF statements can be nested, as in the following example:
<programlisting>
IF demo_row.sex = ''m'' THEN
  pretty_sex := ''man'';
ELSE
  IF demo_row.sex = ''f'' THEN
    pretty_sex := ''woman'';
  END IF;
END IF;
</programlisting>
       </para>

       <para>
        When you use this form, you are actually
        nesting an IF statement inside the ELSE part of an outer IF
        statement. Thus you need one END IF statement for each
        nested IF and one for the parent IF-ELSE.
        This is workable but grows tedious when there are many
	alternatives to be checked.
       </para>
     </sect3>

     <sect3>
      <title>IF-THEN-ELSIF-ELSE</title>

       <para>
<synopsis>
IF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
    <replaceable>statements</replaceable>
    ...
</optional>
</optional>
<optional> ELSE
    <replaceable>statements</replaceable> </optional>
END IF;
</synopsis>

        IF-THEN-ELSIF-ELSE provides a more convenient method of checking
	many alternatives in one statement.  Formally it is equivalent
	to nested IF-THEN-ELSE-IF-THEN commands, but only one END IF
	is needed.
       </para>

       <para>
        Here is an example:

<programlisting>
IF number = 0 THEN
    result := ''zero'';
ELSIF number &gt; 0 THEN 
    result := ''positive'';
ELSIF number &lt; 0 THEN
    result := ''negative'';
ELSE
    -- hmm, the only other possibility is that number IS NULL
    result := ''NULL'';
END IF;
</programlisting>
       </para>

       <para>
        The final ELSE section is optional.
       </para>

     </sect3>
   </sect2>

   <sect2 id="plpgsql-control-structures-loops">
    <title>Simple Loops</title>

    <para>
     With the LOOP, EXIT, WHILE and FOR statements, you can arrange
     for your <application>PL/pgSQL</application> function to repeat
     a series of commands.
    </para>

     <sect3>
      <title>LOOP</title>

       <para>
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>

        LOOP defines an unconditional loop that is repeated indefinitely
	until terminated by an EXIT or RETURN statement.
	The optional label can be used by
        EXIT statements in nested loops to specify which level of
        nesting should be terminated.
       </para>
     </sect3>

     <sect3>
      <title>EXIT</title>

       <para>
<synopsis>
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>expression</replaceable> </optional>;
</synopsis>

        If no <replaceable>label</replaceable> is given,
        the innermost loop is terminated and the
        statement following END LOOP is executed next.
        If <replaceable>label</replaceable> is given, it
        must be the label of the current or some outer level of nested loop
        or block. Then the named loop or block is terminated and control
        continues with the statement after the loop's/block's corresponding
        END.
       </para>

       <para>
        If WHEN is present, loop exit occurs only if the specified condition
	is true, otherwise control passes to the statement after EXIT.
       </para>

       <para>
        Examples:
<programlisting>
LOOP
    -- some computations
    IF count > 0 THEN
        EXIT;  -- exit loop
    END IF;
END LOOP;

LOOP
    -- some computations
    EXIT WHEN count > 0;
END LOOP;

BEGIN
    -- some computations
    IF stocks > 100000 THEN
        EXIT;  -- illegal. Can't use EXIT outside of a LOOP
    END IF;
END;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title>WHILE</title>

       <para>
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
WHILE <replaceable>expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>

        The WHILE statement repeats a
        sequence of statements so long as the condition expression
	evaluates to true.  The condition is checked just before
	each entry to the loop body.
       </para>

       <para>
        For example:
<programlisting>
WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
    -- some computations here
END LOOP;

WHILE NOT boolean_expression LOOP
    -- some computations here
END LOOP;
</programlisting>
       </para>
     </sect3>

     <sect3>
      <title>FOR (integer for-loop)</title>

       <para>
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>

        This form of FOR creates a loop that iterates over a range of integer
	values. The variable 
        <replaceable>name</replaceable> is automatically defined as type
        integer and exists only inside the loop. The two expressions giving
        the lower and upper bound of the range are evaluated once when entering
        the loop. The iteration step is normally 1, but is -1 when REVERSE is
	specified.
       </para>

       <para>
        Some examples of integer FOR loops:
<programlisting>
FOR i IN 1..10 LOOP
  -- some expressions here

    RAISE NOTICE ''i is %'',i;
END LOOP;

FOR i IN REVERSE 10..1 LOOP
    -- some expressions here
END LOOP;
</programlisting>
       </para>
     </sect3>
   </sect2>

   <sect2 id="plpgsql-records-iterating">
    <title>Looping Through Query Results</title>

    <para>
     Using a different type of FOR loop, you can iterate through
     the results of a query and manipulate that data
     accordingly. The syntax is:
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>record | row</replaceable> IN <replaceable>select_query</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
     The record or row variable is successively assigned all the rows 
     resulting from the SELECT query and the loop body is executed 
     for each row. Here is an example:
    </para>

    <para>
<programlisting>
CREATE FUNCTION cs_refresh_mviews () RETURNS INTEGER AS '
DECLARE
     mviews RECORD;
BEGIN
     PERFORM cs_log(''Refreshing materialized views...'');

     FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP

         -- Now "mviews" has one record from cs_materialized_views

         PERFORM cs_log(''Refreshing materialized view '' || quote_ident(mviews.mv_name) || ''...'');
         EXECUTE ''TRUNCATE TABLE  '' || quote_ident(mviews.mv_name);
         EXECUTE ''INSERT INTO '' || quote_ident(mviews.mv_name) || '' '' || mviews.mv_query;
     END LOOP;

     PERFORM cs_log(''Done refreshing materialized views.'');
     RETURN 1;
end;
' LANGUAGE 'plpgsql';
</programlisting>

     If the loop is terminated by an EXIT statement, the last
     assigned row value is still accessible after the loop.
    </para>

    <para>
     The FOR-IN-EXECUTE statement is another way to iterate over
     records:
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>record | row</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> LOOP 
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
     This is like the previous form, except that the source SELECT
     statement is specified as a string expression, which is evaluated
     and re-planned on each entry to the FOR loop.  This allows the
     programmer to choose the speed of a pre-planned query or the
     flexibility of a dynamic query, just as with a plain EXECUTE
     statement.
    </para>

    <note>
    <para>
     The <application>PL/pgSQL</> parser presently distinguishes the
     two kinds of FOR loops (integer or record-returning) by checking
     whether the target variable mentioned just after FOR has been
     declared as a record/row variable.  If not, it's presumed to be
     an integer FOR loop.  This can cause rather nonintuitive error
     messages when the true problem is, say, that one has
     misspelled the FOR variable name.
    </para>
    </note>
  </sect2>
  </sect1>

  <sect1 id="plpgsql-cursors">
   <title>Cursors</title>

   <para>
    Rather than executing a whole query at once, it is possible to set
    up a <firstterm>cursor</> that encapsulates the query, and then read
    the query result a few rows at a time. One reason for doing this is
    to avoid memory overrun when the result contains a large number of
    rows. (However, <application>PL/pgSQL</> users don't normally need
    to worry about that, since FOR loops automatically use a cursor
    internally to avoid memory problems.) A more interesting usage is to
    return a reference to a cursor that it has created, allowing the
    caller to read the rows. This provides a way to return row sets
    from functions.
   </para>
   
   <sect2 id="plpgsql-cursor-declarations">
    <title>Declaring Cursor Variables</title>

    <para>
     All access to cursors in <application>PL/pgSQL</> goes through
     cursor variables, which are always of the special data type
     <type>refcursor</>.  One way to create a cursor variable
     is just to declare it as a variable of type <type>refcursor</>.
     Another way is to use the cursor declaration syntax,
     which in general is:
<synopsis>
<replaceable>name</replaceable> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>select_query</replaceable> ;
</synopsis>
     (<literal>FOR</> may be replaced by <literal>IS</> for Oracle
     compatibility.)  <replaceable>arguments</replaceable>, if any,
     are a comma-separated list of <replaceable>name</replaceable>
     <replaceable>datatype</replaceable> pairs that define names to
     be replaced by parameter values in the given query.  The actual
     values to substitute for these names will be specified later,
     when the cursor is opened.
    </para>
    <para>
     Some examples:
<programlisting>
DECLARE
    curs1 refcursor;
    curs2 CURSOR FOR SELECT * from tenk1;
    curs3 CURSOR (key int) IS SELECT * from tenk1 where unique1 = key;
</programlisting>
     All three of these variables have the data type <type>refcursor</>,
     but the first may be used with any query, while the second has
     a fully specified query already <firstterm>bound</> to it, and the last
     has a parameterized query bound to it.  (<literal>key</> will be
     replaced by an integer parameter value when the cursor is opened.)
     The variable <literal>curs1</>
     is said to be <firstterm>unbound</> since it is not bound to
     any particular query.
    </para>
   </sect2>

   <sect2 id="plpgsql-cursor-opening">
    <title>Opening Cursors</title>

    <para>
     Before a cursor can be used to retrieve rows, it must be
     <firstterm>opened</>. (This is the equivalent action to the SQL
     command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
     four forms of the OPEN statement, two of which use unbound cursor
     variables and the other two use bound cursor variables.
    </para>

    <sect3>
     <title>OPEN FOR SELECT</title>

       <para>
<synopsis>
OPEN <replaceable>unbound-cursor</replaceable> FOR SELECT ...;
</synopsis>

        The cursor variable is opened and given the specified query
	to execute.  The cursor cannot be open already, and it must
	have been declared as an unbound cursor (that is, as a simple
	<type>refcursor</> variable).  The SELECT query is treated
	in the same way as other SELECTs in <application>PL/pgSQL</>:
	<application>PL/pgSQL</> variable names are substituted,
	and the query plan is cached for possible re-use.

<programlisting>
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title>OPEN FOR EXECUTE</title>

       <para>
<synopsis>
OPEN <replaceable>unbound-cursor</replaceable> FOR EXECUTE <replaceable class="command">query-string</replaceable>;
</synopsis>

        The cursor variable is opened and given the specified query
	to execute.  The cursor cannot be open already, and it must
	have been declared as an unbound cursor (that is, as a simple
	<type>refcursor</> variable).  The query is specified as a
	string expression in the same way as in the EXECUTE command.
	As usual, this gives flexibility so the query can vary
	from one run to the next.

<programlisting>
OPEN curs1 FOR EXECUTE ''SELECT * FROM '' || quote_ident($1);
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title>OPENing a bound cursor</title>

       <para>
<synopsis>
OPEN <replaceable>bound-cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
</synopsis>

        This form of OPEN is used to open a cursor variable whose query
	was bound to it when it was declared.
	The cursor cannot be open already.  A list of actual argument
	value expressions must appear if and only if the cursor was
	declared to take arguments.  These values will be substituted
	in the query.
	The query plan for a bound cursor is always considered
	cacheable --- there is no equivalent of EXECUTE in this case.

<programlisting>
OPEN curs2;
OPEN curs3(42);
</programlisting>
       </para>
     </sect3>
   </sect2>

   <sect2 id="plpgsql-cursor-using">
    <title>Using Cursors</title>

    <para>
     Once a cursor has been opened, it can be manipulated with the
     statements described here.
    </para>

    <para>
     These manipulations need not occur in the same function that
     opened the cursor to begin with.  You can return a <type>refcursor</>
     value out of a function and let the caller operate on the cursor.
     (Internally, a <type>refcursor</> value is simply the string name
     of a Portal containing the active query for the cursor.  This name
     can be passed around, assigned to other <type>refcursor</> variables,
     and so on, without disturbing the Portal.)
    </para>

    <para>
     All Portals are implicitly closed at transaction end.  Therefore
     a <type>refcursor</> value is useful to reference an open cursor
     only until the end of the transaction.
    </para>

    <sect3>
     <title>FETCH</title>

       <para>
<synopsis>
FETCH <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
</synopsis>

        FETCH retrieves the next row from the cursor into a target,
	which may be a row variable, a record variable, or a comma-separated
	list of simple variables, just like SELECT INTO.  As with
	SELECT INTO, the special variable FOUND may be checked to see
	whether a row was obtained or not.

<programlisting>
FETCH curs1 INTO rowvar;
FETCH curs2 INTO foo,bar,baz;
</programlisting>
       </para>
     </sect3>

    <sect3>
     <title>CLOSE</title>

       <para>
<synopsis>
CLOSE <replaceable>cursor</replaceable>;
</synopsis>

        CLOSE closes the Portal underlying an open cursor.
	This can be used to release resources earlier than end of
	transaction, or to free up the cursor variable to be opened again.

<programlisting>
CLOSE curs1;
</programlisting>
       </para>
     </sect3>
 
    <sect3>
     <title>Returning Cursors</title>

       <para>

        <application>PL/pgSQL</> functions can return cursors to the
        caller. This is used to return multiple rows or columns from the
        function. The function opens the cursor and returns the cursor
        name to the caller. The caller can then FETCH rows from the
        cursor. The cursor can be CLOSEd by the caller, or it will be
        closed automatically when the transaction closes.

       </para>

       <para>
        The cursor name returned by the function can be specified by the
        caller or automatically generated. The following example shows
        how a cursor name can be supplied by the caller:

<programlisting>
CREATE TABLE test (col text);
INSERT INTO test VALUES ('123');

CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
BEGIN
        OPEN $1 FOR SELECT col FROM test;
        RETURN $1;
END;
' LANGUAGE 'plpgsql';

BEGIN;
SELECT reffunc('funccursor');
FETCH ALL IN funccursor;
COMMIT;
</programlisting>
       </para>

       <para>
        The following example uses automatic cursor name generation:
         
<programlisting>
CREATE FUNCTION reffunc2() RETURNS refcursor AS '
DECLARE
        ref refcursor;
BEGIN
        OPEN ref FOR SELECT col FROM test;
        RETURN ref;
END;
' LANGUAGE 'plpgsql';

BEGIN;
SELECT reffunc2();
  
        reffunc2      
  --------------------
   &lt;unnamed cursor 1&gt;
  (1 row)

FETCH ALL IN "&lt;unnamed cursor 1&gt;";
COMMIT;
</programlisting>
       </para>
     </sect3>
   </sect2>
  </sect1>

  <sect1 id="plpgsql-errors-and-messages">
   <title>Errors and Messages</title>

   <para>
    Use the RAISE statement to report messages and raise errors.

<synopsis>
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">variable</replaceable> <optional>...</optional></optional>;
</synopsis>

    Possible levels are DEBUG (write the message into the postmaster log),
    NOTICE (write the message into the postmaster log and forward it to
    the client application) and EXCEPTION (raise an error,
    aborting the transaction).
   </para>

   <para>
    Inside the format string, <literal>%</literal> is replaced by the next
    optional argument's external representation.
    Write <literal>%%</literal> to emit a literal <literal>%</literal>.
    Note that the optional arguments must presently
    be simple variables, not expressions, and the format must be a simple
    string literal.
   </para>

   <!--
   This example should work, but does not:
   	RAISE NOTICE ''Id number '' || key || '' not found!'';
   Put it back when we allow non-string-literal formats.
    -->

   <para>
    Examples:
<programlisting>
RAISE NOTICE ''Calling cs_create_job(%)'',v_job_id;
</programlisting>
    In this example, the value of v_job_id will replace the % in the
    string.
   </para>

   <para>
<programlisting>
RAISE EXCEPTION ''Inexistent ID --> %'',user_id;
</programlisting>
    This will abort the transaction with the given error message.
   </para>

  <sect2 id="plpgsql-exceptions">
   <title>Exceptions</title>

    <para>
     <productname>PostgreSQL</productname> does not have a very smart
     exception handling model. Whenever the parser, planner/optimizer
     or executor decide that a statement cannot be processed any longer,
     the whole transaction gets aborted and the system jumps back
     into the main loop to get the next query from the client application.
    </para>

    <para>
     It is possible to hook into the error mechanism to notice that this
     happens. But currently it is impossible to tell what really
     caused the abort (input/output conversion error, floating-point
     error, parse error). And it is possible that the database backend
     is in an inconsistent state at this point so returning to the upper
     executor or issuing more commands might corrupt the whole database.
    </para>

    <para>
     Thus, the only thing <application>PL/pgSQL</application> currently does when it encounters
     an abort during execution of a function or trigger
     procedure is to write some additional NOTICE level log messages
     telling in which function and where (line number and type of
     statement) this happened.  The error always stops execution of
     the function.
    </para>
  </sect2>
 </sect1>

 <sect1 id="plpgsql-trigger">
  <title>Trigger Procedures</title>

  <para>
   <application>PL/pgSQL</application> can be used to define trigger
   procedures. A trigger procedure is created with the <command>CREATE
   FUNCTION</command> command as a function with no arguments and a return
   type of <type>OPAQUE</type>.  Note that the function must be declared
   with no arguments even if it expects to receive arguments specified
   in <command>CREATE TRIGGER</> --- trigger arguments are passed via
   <varname>TG_ARGV</>, as described below.
  </para>

  <para>
   When a <application>PL/pgSQL</application> function is called as a
   trigger, several special variables are created automatically in the 
   top-level block. They are:
   
   <variablelist>
    <varlistentry>
     <term><varname>NEW</varname></term>
     <listitem>
      <para>
       Data type <type>RECORD</type>; variable holding the new database row for INSERT/UPDATE
       operations in ROW level triggers.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>OLD</varname></term>
     <listitem>
      <para>
       Data type <type>RECORD</type>; variable holding the old database row for UPDATE/DELETE
       operations in ROW level triggers.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_NAME</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; variable that contains the name of the trigger actually
       fired.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_WHEN</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of either 
              <literal>BEFORE</literal> or <literal>AFTER</literal> 
              depending on the trigger's definition.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_LEVEL</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of either 
              <literal>ROW</literal> or <literal>STATEMENT</literal> depending on the
       trigger's definition.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_OP</varname></term>
     <listitem>
      <para>
       Data type <type>text</type>; a string of 
              <literal>INSERT</literal>, <literal>UPDATE</literal> 
              or <literal>DELETE</literal> telling
       for which operation the trigger is fired.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_RELID</varname></term>
     <listitem>
      <para>
       Data type <type>oid</type>; the object ID of the table that caused the
       trigger invocation.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_RELNAME</varname></term>
     <listitem>
      <para>
       Data type <type>name</type>; the name of the table that caused the trigger
       invocation.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_NARGS</varname></term>
     <listitem>
      <para>
       Data type <type>integer</type>; the number of arguments given to the trigger
       procedure in the <command>CREATE TRIGGER</command> statement.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><varname>TG_ARGV[]</varname></term>
     <listitem>
      <para>
       Data type array of <type>text</type>; the arguments from
              the <command>CREATE TRIGGER</command> statement.
       The index counts from 0 and can be given as an expression. Invalid
       indices (&lt; 0 or &gt;= tg_nargs) result in a NULL value.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

   <para>
    A trigger function must return either NULL or a record/row value
    having exactly the structure of the table the trigger was fired for.
    Triggers fired BEFORE may return NULL to signal the trigger manager
    to skip the rest of the operation for this row (ie, subsequent triggers
    are not fired, and the INSERT/UPDATE/DELETE does not occur for this
    row).  If a non-NULL value is returned then the operation proceeds with
    that row value.  Note that returning a row value different from the
    original value of NEW alters the row that will be inserted or updated.
    It is possible to replace single values directly
    in NEW and return that, or to build a complete new record/row to
    return.
   </para>

   <para>
    The return value of a trigger fired AFTER is ignored; it may as well
    always return a NULL value.  But an AFTER trigger can still abort the
    operation by raising an error.
   </para>

   <example>
    <title>A <application>PL/pgSQL</application> Trigger Procedure Example</title>

    <para>
     This example trigger ensures that any time a row is inserted or updated
     in the table, the current user name and time are stamped into the
     row. And it ensures that an employee's name is given and that the
     salary is a positive value.

<programlisting>
CREATE TABLE emp (
    empname text,
    salary integer,
    last_date timestamp,
    last_user text
);

CREATE FUNCTION emp_stamp () RETURNS OPAQUE AS '
    BEGIN
        -- Check that empname and salary are given
        IF NEW.empname ISNULL THEN
            RAISE EXCEPTION ''empname cannot be NULL value'';
        END IF;
        IF NEW.salary ISNULL THEN
            RAISE EXCEPTION ''% cannot have NULL salary'', NEW.empname;
        END IF;

        -- Who works for us when she must pay for?
        IF NEW.salary < 0 THEN
            RAISE EXCEPTION ''% cannot have a negative salary'', NEW.empname;
        END IF;

        -- Remember who changed the payroll when
        NEW.last_date := ''now'';
        NEW.last_user := current_user;
        RETURN NEW;
    END;
' LANGUAGE 'plpgsql';

CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
    FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
</programlisting>
    </para>
   </example>
  </sect1>

  <!-- **** PL/pgSQL Examples **** -->

  <sect1 id="plpgsql-examples">
   <title>Examples</title>

   <para>
    Here are only a few functions to demonstrate how easy it is to
    write <application>PL/pgSQL</>
    functions. For more complex examples the programmer
    might look at the regression test for <application>PL/pgSQL</>.
   </para>

   <para>
    One painful detail in writing functions in <application>PL/pgSQL</application> is the handling
    of single quotes. The function's source text in <command>CREATE FUNCTION</command> must
    be a literal string. Single quotes inside of literal strings must be
    either doubled or quoted with a backslash. We are still looking for
    an elegant alternative. In the meantime, doubling the single quotes
    as in the examples below should be used. Any solution for this
    in future versions of <productname>PostgreSQL</productname> will be
    forward compatible.
   </para>

   <para>
    For a detailed explanation and examples of how to escape single
    quotes in different situations, please see <xref linkend="plpgsql-quote">.
   </para>

   <example>
    <title>A Simple <application>PL/pgSQL</application> Function to Increment an Integer</title>

    <para>
     The following two <application>PL/pgSQL</application> functions are identical to their
     counterparts from the C language function discussion. This
     function receives an <type>integer</type> and increments it by
     one, returning the incremented value.
    </para>

<programlisting>
CREATE FUNCTION add_one (integer) RETURNS INTEGER AS '
    BEGIN
        RETURN $1 + 1;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
   </example>

   <example>
    <title>A Simple <application>PL/pgSQL</application> Function to Concatenate Text</title>

    <para>
     This function receives two <type>text</type> parameters and
     returns the result of concatenating them.
    </para>

<programlisting>
CREATE FUNCTION concat_text (TEXT, TEXT) RETURNS TEXT AS '
    BEGIN
        RETURN $1 || $2;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
   </example>

   <example>
    <title>A <application>PL/pgSQL</application> Function on Composite Type</title>

    <para>
     In this example, we take <literal>EMP</> (a table) and an
     <type>integer</type> as arguments to our function, which returns
     a <type>boolean</type>. If the <structfield>salary</> field of the <structname>EMP</> table is
     <literal>NULL</literal>, we return <literal>f</>. Otherwise we compare with
     that field with the <type>integer</type> passed to the function
     and return the <type>boolean</type> result of the comparison (t
     or f). This is the <application>PL/pgSQL</application> equivalent to the example from the C
     functions.
    </para>

<programlisting>
CREATE FUNCTION c_overpaid (EMP, INTEGER) RETURNS BOOLEAN AS '
    DECLARE
        emprec ALIAS FOR $1;
        sallim ALIAS FOR $2;
    BEGIN
        IF emprec.salary ISNULL THEN
            RETURN ''f'';
        END IF;
        RETURN emprec.salary > sallim;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
   </example>
  </sect1>

  <!-- **** Porting from Oracle PL/SQL **** -->

 <sect1 id="plpgsql-porting">

  <sect1info>
   <date>
    February 2001
   </date>
   <author>
    <firstname>Roberto</firstname>
    <surname>Mello</surname>
    <affiliation>
     <address>
      <email>rmello@@fslc.usu.edu</email>
     </address>
    </affiliation>
   </author>
<!--
  Breaks HTML manifest file
   <legalnotice>
    <para>
     Except for portions of this document quoted from other sources,
     this document is licensed under the BSD License.
    </para>
   </legalnotice>
-->
  </sect1info> 

  <title>Porting from Oracle PL/SQL</title>

  <indexterm zone="plpgsql-porting">
   <primary>Oracle</primary>
  </indexterm>

  <indexterm zone="plpgsql-porting">
   <primary>PL/SQL</primary>
  </indexterm>

  <note>
   <title>Author</title>
   <para>
    Roberto Mello (<email>rmello@@fslc.usu.edu</email>)
   </para>
  </note>

  <para>
   This section explains differences between Oracle's PL/SQL and
   <productname>PostgreSQL</>'s <application>PL/pgSQL</application> languages in the hopes of helping developers
   port applications from Oracle to <productname>PostgreSQL</>.  Most of the code here
   is from the <ulink url="http://www.arsdigita.com">ArsDigita</ulink>
   <ulink url="http://www.arsdigita.com/asj/clickstream">Clickstream
   module</ulink> that I ported to <productname>PostgreSQL</> when I took an
   internship with <ulink url="http://www.openforce.net">OpenForce
   Inc.</ulink> in the Summer of 2000.
  </para>

  <para>
   <application>PL/pgSQL</application> is similar to PL/SQL in many aspects. It is a block
   structured, imperative language (all variables have to be
   declared). PL/SQL has many more features than its <productname>PostgreSQL</>
   counterpart, but <application>PL/pgSQL</application> allows for a great deal of functionality
   and it is being improved constantly.
  </para>

  <sect2>
   <title>Main Differences</title>

   <para>
    Some things you should keep in mind when porting from Oracle to <productname>PostgreSQL</>:

    <itemizedlist>
     <listitem>
      <para>
       No default parameters in <productname>PostgreSQL</>.
      </para>
     </listitem>

     <listitem>
      <para>
       You can overload functions in <productname>PostgreSQL</>. This is often used to work 
       around the lack of default parameters.
      </para>
     </listitem>

     <listitem>
      <para>
       Assignments, loops and conditionals are similar. 
      </para>
     </listitem>

     <listitem>
      <para>
       No need for cursors in <productname>PostgreSQL</>, just put the query in the FOR 
       statement (see example below)
      </para>
     </listitem>

     <listitem>
      <para>
       In <productname>PostgreSQL</> you <emphasis>need</emphasis> to escape single
       quotes. See <xref linkend="plpgsql-quote">.
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <sect3 id="plpgsql-quote">
    <title>Quote Me on That: Escaping Single Quotes</title>

    <para>
     In <productname>PostgreSQL</> you need to escape single quotes inside your
     function definition. This can lead to quite amusing code at
     times, especially if you are creating a function that generates
     other function(s), as in 
     <xref linkend="plpgsql-porting-nastyquote">.  
     One thing to keep in mind
     when escaping lots of single quotes is that, except for the
     beginning/ending quotes, all the others will come in even
     quantity.
    </para>

    <para>
     <xref linkend="plpgsql-quoting-table"> gives the scoop.  (You'll
     love this little chart.)
    </para>

    <table id="plpgsql-quoting-table">
     <title>Single Quotes Escaping Chart</title>

     <tgroup cols="4">
      <thead>
       <row>
        <entry>No. of Quotes</entry>
        <entry>Usage</entry>
        <entry>Example</entry>
        <entry>Result</entry>
       </row>
      </thead>

      <tbody>
       <row>
        <entry>1</entry>
        <entry>To begin/terminate function bodies</entry>
        <entry><programlisting>
CREATE FUNCTION foo() RETURNS INTEGER AS '...'
LANGUAGE 'plpgsql';
</programlisting></entry>
        <entry>as is</entry>
       </row>

       <row>
        <entry>2</entry>
        <entry>In assignments, SELECTs, to delimit strings, etc.</entry>
        <entry><programlisting>
a_output := ''Blah'';
SELECT * FROM users WHERE f_name=''foobar'';
</programlisting></entry>
        <entry><literal>SELECT * FROM users WHERE f_name='foobar';</literal></entry>
       </row>

       <row>
        <entry>4</entry>
        <entry>
         When you need two single quotes in your resulting string
         without terminating that string.
        </entry>
        <entry><programlisting>
a_output := a_output || '' AND name 
    LIKE ''''foobar'''' AND ...''
</programlisting></entry>
        <entry><literal>AND name LIKE 'foobar' AND ...</literal></entry>
       </row>

       <row>
        <entry>6</entry>
        <entry>
         When you want double quotes in your resulting string
         <emphasis>and</emphasis> terminate that string.
        </entry>
        <entry><programlisting>
a_output := a_output || '' AND name 
    LIKE ''''foobar''''''
</programlisting></entry>
        <entry>
         <literal>AND name LIKE 'foobar'</literal>
        </entry>
       </row>

       <row>
        <entry>10</entry>
        <entry>
         When you want two single quotes in the resulting string
         (which accounts for 8 quotes) <emphasis>and</emphasis>
         terminate that string (2 more).  You will probably only need
         that if you were using a function to generate other functions
         (like in <xref linkend="plpgsql-porting-nastyquote">).
        </entry>
        <entry><programlisting>
a_output := a_output || '' if v_'' || 
    referrer_keys.kind || '' like '''''''''' 
    || referrer_keys.key_string || '''''''''' 
    then return ''''''  || referrer_keys.referrer_type 
    || ''''''; end if;''; 
</programlisting></entry>
        <entry>
         <literal>if v_<...> like ''<...>'' then return ''<...>''; end if;</literal>
        </entry>
       </row>
      </tbody>
     </tgroup>
    </table>
   </sect3>
  </sect2>  

  <sect2 id="plpgsql-porting-functions">
   <title>
    Porting Functions
   </title>

   <example>
    <title>
     A Simple Function
    </title>

    <para>
     Here is an Oracle function:
<programlisting>
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name IN varchar, v_version IN varchar)
RETURN varchar IS
BEGIN
    IF v_version IS NULL THEN
        RETURN v_name;
    END IF;
    RETURN v_name || '/' || v_version;
END;
/
SHOW ERRORS;
</programlisting>
    </para>

    <para>
     Let's go through this function and see the differences to <application>PL/pgSQL</>:

     <itemizedlist>
      <listitem>
       <para>
        <productname>PostgreSQL</productname> does not have named
        parameters. You have to explicitly alias them inside your
        function.
       </para>
      </listitem>

      <listitem>
       <para>
        Oracle can have <literal>IN</literal>, <literal>OUT</literal>,
        and <literal>INOUT</literal> parameters passed to functions.
        The <literal>INOUT</literal>, for example, means that the
        parameter will receive a value and return another. <productname>PostgreSQL</>
        only has <quote>IN</quote> parameters and functions can return
        only a single value.
       </para>
      </listitem>

      <listitem>
       <para>
        The <literal>RETURN</literal> key word in the function
        prototype (not the function body) becomes
        <literal>RETURNS</literal> in <productname>PostgreSQL</>.
       </para>
      </listitem>

      <listitem>
       <para>
        On <productname>PostgreSQL</> functions are created using single quotes as
        delimiters, so you have to escape single quotes inside your
        functions (which can be quite annoying at times; see <xref
        linkend="plpgsql-quote">).
       </para>
      </listitem>

      <listitem>
       <para>
        The <literal>/show errors</literal> command does not exist in
        <productname>PostgreSQL</>.
       </para>
      </listitem>
     </itemizedlist>
    </para>

    <para>
     So let's see how this function would look when ported to
     <productname>PostgreSQL</>:

<programlisting>
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(VARCHAR, VARCHAR)
RETURNS VARCHAR AS '
DECLARE
    v_name ALIAS FOR $1;
    v_version ALIAS FOR $2;
BEGIN
    IF v_version IS NULL THEN
        return v_name;
    END IF;
    RETURN v_name || ''/'' || v_version;
END;
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
   </example>
 
   <example id="plpgsql-porting-nastyquote">
    <title>
     A Function that Creates Another Function
    </title>

    <para>
     The following procedure grabs rows from a
     <literal>SELECT</literal> statement and builds a large function
     with the results in <literal>IF</literal> statements, for the
     sake of efficiency. Notice particularly the differences in
     cursors, <literal>FOR</literal> loops, and the need to escape
     single quotes in <productname>PostgreSQL</>.

<programlisting>
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
    CURSOR referrer_keys IS 
        SELECT * FROM cs_referrer_keys 
        ORDER BY try_order;

    a_output VARCHAR(4000); 
BEGIN 
    a_output := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR, v_domain IN VARCHAR, 
v_url IN VARCHAR) RETURN VARCHAR IS BEGIN'; 

    FOR referrer_key IN referrer_keys LOOP 
        a_output := a_output || ' IF v_' || referrer_key.kind || ' LIKE ''' || 
referrer_key.key_string || ''' THEN RETURN ''' || referrer_key.referrer_type || 
'''; END IF;'; 
    END LOOP; 

    a_output := a_output || ' RETURN NULL; END;'; 
    EXECUTE IMMEDIATE a_output; 
END; 
/ 
show errors
</programlisting>
    </para>

    <para>
     Here is how this function would end up in <productname>PostgreSQL</>:

<programlisting>
CREATE FUNCTION cs_update_referrer_type_proc() RETURNS INTEGER AS '
DECLARE
    referrer_keys RECORD;  -- Declare a generic record to be used in a FOR
    a_output varchar(4000);
BEGIN 
    a_output := ''CREATE FUNCTION cs_find_referrer_type(VARCHAR,VARCHAR,VARCHAR) 
                  RETURNS VARCHAR AS '''' 
                     DECLARE 
                         v_host ALIAS FOR $1; 
                         v_domain ALIAS FOR $2; 
                         v_url ALIAS FOR $3;
                     BEGIN ''; 

    -- 
    -- Notice how we scan through the results of a query in a FOR loop
    -- using the FOR &lt;record&gt; construct.
    --

    FOR referrer_keys IN SELECT * FROM cs_referrer_keys ORDER BY try_order LOOP
        a_output := a_output || '' IF v_'' || referrer_keys.kind || '' LIKE '''''''''' 
                 || referrer_keys.key_string || '''''''''' THEN RETURN '''''' 
                 || referrer_keys.referrer_type || ''''''; END IF;''; 
    END LOOP; 
  
    a_output := a_output || '' RETURN NULL; END; '''' LANGUAGE ''''plpgsql'''';''; 
 
    -- This works because we are not substituting any variables
    -- Otherwise it would fail. Look at PERFORM for another way to run functions
    
    EXECUTE a_output; 
END; 
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
   </example>
 
   <example>
    <title>
     A Procedure with a lot of String Manipulation and OUT Parameters
    </title>

    <para>
     The following Oracle PL/SQL procedure is used to parse a URL and
     return several elements (host, path and query). It is an
     procedure because in <application>PL/pgSQL</application> functions only one value can be returned
     (see <xref linkend="plpgsql-porting-procedures">).  In
     <productname>PostgreSQL</>, one way to work around this is to split the procedure
     in three different functions: one to return the host, another for
     the path and another for the query.
    </para>

<programlisting>
CREATE OR REPLACE PROCEDURE cs_parse_url(
    v_url IN VARCHAR,
    v_host OUT VARCHAR,  -- This will be passed back
    v_path OUT VARCHAR,  -- This one too
    v_query OUT VARCHAR) -- And this one
is
    a_pos1 INTEGER;
    a_pos2 INTEGER;
begin
    v_host := NULL;
    v_path := NULL;
    v_query := NULL;
    a_pos1 := instr(v_url, '//'); -- <productname>PostgreSQL</> doesn't have an instr function

    IF a_pos1 = 0 THEN
        RETURN;
    END IF;
    a_pos2 := instr(v_url, '/', a_pos1 + 2);
    IF a_pos2 = 0 THEN
        v_host := substr(v_url, a_pos1 + 2);
        v_path := '/';
        RETURN;
    END IF;

    v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
    a_pos1 := instr(v_url, '?', a_pos2 + 1);

    IF a_pos1 = 0 THEN
        v_path := substr(v_url, a_pos2);
        RETURN;
    END IF;

    v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
    v_query := substr(v_url, a_pos1 + 1);
END;
/
show errors;
</programlisting>

    <para>
     Here is how this procedure could be translated for <productname>PostgreSQL</>:

<programlisting>
CREATE OR REPLACE FUNCTION cs_parse_url_host(VARCHAR) RETURNS VARCHAR AS ' 
DECLARE 
    v_url ALIAS FOR $1; 
    v_host VARCHAR; 
    v_path VARCHAR; 
    a_pos1 INTEGER; 
    a_pos2 INTEGER; 
    a_pos3 INTEGER; 
BEGIN 
    v_host := NULL; 
    a_pos1 := instr(v_url,''//''); 

    IF a_pos1 = 0 THEN 
        RETURN '''';  -- Return a blank
    END IF; 

    a_pos2 := instr(v_url,''/'',a_pos1 + 2); 
    IF a_pos2 = 0 THEN 
        v_host := substr(v_url, a_pos1 + 2); 
        v_path := ''/''; 
        RETURN v_host; 
    END IF; 

    v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2 ); 
    RETURN v_host; 
END; 
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
   </example>

   <note>
    <para>
     <productname>PostgreSQL</> does not have an <function>instr</function> function,
     so you can work around it using a combination of other functions.
     I got tired of doing this and created my own
     <function>instr</function> functions that behave exactly like
     Oracle's (it makes life easier). See the <xref
     linkend="plpgsql-porting-appendix"> for the code.
    </para>
   </note>
  </sect2>

  <sect2 id="plpgsql-porting-procedures">
   <title>
    Procedures
   </title>

   <para>
    Oracle procedures give a little more flexibility to the developer
    because nothing needs to be explicitly returned, but it can be
    through the use of <literal>INOUT</> or <literal>OUT</> parameters.
   </para>

   <para>
    An example:

<programlisting>
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
    a_running_job_count INTEGER;
    PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
BEGIN
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">

    SELECT count(*) INTO a_running_job_count 
    FROM cs_jobs
    WHERE end_stamp IS NULL;

    IF a_running_job_count > 0 THEN
        COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
        raise_application_error(-20000, 'Unable to create a new job: a job is currently running.');
    END IF;

    DELETE FROM cs_active_job;
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);

    BEGIN
        INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
        EXCEPTION WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists<co id="co.plpgsql-porting-exception">
    END;
    COMMIT;
END;
/
show errors
</programlisting>
   </para>

   <para>
    Procedures like this can be easily converted into <productname>PostgreSQL</>
    functions returning an <type>INTEGER</type>. This procedure in
    particular is interesting because it can teach us some things:

    <calloutlist>
     <callout arearefs="co.plpgsql-porting-pragma">
      <para>
       There is no <literal>pragma</literal> statement in <productname>PostgreSQL</>.
      </para>
     </callout>

     <callout arearefs="co.plpgsql-porting-locktable">
      <para>
       If you do a <literal>LOCK TABLE</literal> in <application>PL/pgSQL</>, the lock
       will not be released until the calling transaction is finished.
      </para>
     </callout>

     <callout arearefs="co.plpgsql-porting-commit">
      <para>
       You also cannot have transactions in <application>PL/pgSQL</application> procedures. The
       entire function (and other functions called from therein) is
       executed in a transaction and <productname>PostgreSQL</> rolls back the results if
       something goes wrong. Therefore only one
       <literal>BEGIN</literal> statement is allowed.
      </para>
     </callout>

     <callout arearefs="co.plpgsql-porting-exception">
      <para>
       The exception when would have to be replaced by an
       <literal>IF</literal> statement.
      </para>
     </callout>
    </calloutlist>
   </para>

   <para>
    So let's see one of the ways we could port this procedure to <application>PL/pgSQL</>:

<programlisting>
CREATE OR REPLACE FUNCTION cs_create_job(INTEGER) RETURNS INTEGER AS '
DECLARE
    v_job_id ALIAS FOR $1;
    a_running_job_count INTEGER;
    a_num INTEGER;
    -- PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
    SELECT count(*) INTO a_running_job_count 
    FROM cs_jobs 
    WHERE end_stamp IS NULL;

    IF a_running_job_count > 0
    THEN
        -- COMMIT; -- free lock
        RAISE EXCEPTION ''Unable to create a new job: a job is currently running.'';
    END IF;

    DELETE FROM cs_active_job;
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);

    SELECT count(*) into a_num 
    FROM cs_jobs 
    WHERE job_id=v_job_id;
    IF NOT FOUND THEN  -- If nothing was returned in the last query
        -- This job is not in the table so lets insert it.
        INSERT INTO cs_jobs(job_id, start_stamp) VALUES (v_job_id, sysdate());
        RETURN 1;
    ELSE
        RAISE NOTICE ''Job already running.'';<co id="co.plpgsql-porting-raise">
    END IF;

    RETURN 0;
END;
' LANGUAGE 'plpgsql';
</programlisting>

    <calloutlist>
     <callout arearefs="co.plpgsql-porting-raise">
      <para>
       Notice how you can raise notices (or errors) in <application>PL/pgSQL</>.
      </para>
     </callout>
    </calloutlist>
   </para>
  </sect2>

  <sect2 id="plpgsql-porting-packages">
   <title>
    Packages
   </title>

   <note>
    <para>
     I haven't done much with packages myself, so if there are
     mistakes here, please let me know.
    </para>
   </note>

   <para>
    Packages are a way Oracle gives you to encapsulate PL/SQL
    statements and functions into one entity, like Java classes, where
    you define methods and objects. You can access these
    objects/methods with a <quote><literal>.</literal></quote>
    (dot). Here is an example of an Oracle package from ACS 4 (the
    <ulink url="http://www.arsdigita.com/doc/">ArsDigita Community
    System</ulink>):

<programlisting>
CREATE OR REPLACE PACKAGE BODY acs
AS
  FUNCTION add_user (
    user_id     IN users.user_id%TYPE DEFAULT NULL,
    object_type     IN acs_objects.object_type%TYPE DEFAULT 'user',
    creation_date   IN acs_objects.creation_date%TYPE DEFAULT sysdate,
    creation_user   IN acs_objects.creation_user%TYPE DEFAULT NULL,
    creation_ip     IN acs_objects.creation_ip%TYPE DEFAULT NULL,
  ...
  ) RETURN users.user_id%TYPE
  IS
    v_user_id       users.user_id%TYPE;
    v_rel_id        membership_rels.rel_id%TYPE;
  BEGIN
    v_user_id := acs_user.new (user_id, object_type, creation_date,
                creation_user, creation_ip, email, ...
    RETURN v_user_id;
  END;
END acs;
/
show errors
</programlisting>
   </para>

   <para>
    We port this to <productname>PostgreSQL</> by creating the different objects of
    the Oracle package as functions with a standard naming
    convention. We have to pay attention to some other details, like
    the lack of default parameters in <productname>PostgreSQL</> functions. The above
    package would become something like this:
 
<programlisting>
CREATE FUNCTION acs__add_user(INTEGER,INTEGER,VARCHAR,TIMESTAMP,INTEGER,INTEGER,...)
RETURNS INTEGER AS '
DECLARE
    user_id ALIAS FOR $1;
    object_type ALIAS FOR $2;
    creation_date ALIAS FOR $3;
    creation_user ALIAS FOR $4;
    creation_ip ALIAS FOR $5;
    ...
    v_user_id users.user_id%TYPE;
    v_rel_id membership_rels.rel_id%TYPE;
BEGIN
    v_user_id := acs_user__new(user_id,object_type,creation_date,creation_user,creation_ip, ...);
    ...

    RETURN v_user_id;
END;
' LANGUAGE 'plpgsql';
</programlisting>
   </para>
  </sect2>

  <sect2 id="plpgsql-porting-other">
   <title>
    Other Things to Watch For
   </title>

   <sect3>
    <title>EXECUTE</title>

    <para>
     The <productname>PostgreSQL</> version of <literal>EXECUTE</literal> works
     nicely, but you have to remember to use
     <function>quote_literal(TEXT)</function> and
     <function>quote_string(TEXT)</function> as described in <xref
     linkend="plpgsql-statements-executing-dyn-queries">.  Constructs of the type
     <literal>EXECUTE ''SELECT * from $1'';</literal> will not work
     unless you use these functions.
    </para>
   </sect3>

   <sect3 id="plpgsql-porting-optimization">
    <title>Optimizing <application>PL/pgSQL</application> Functions</title>

    <para>
     <productname>PostgreSQL</> gives you two function creation modifiers to optimize
     execution: <literal>iscachable</literal> (function always returns
     the same result when given the same arguments) and
     <literal>isstrict</literal> (function returns NULL if any
     argument is NULL).  Consult the <command>CREATE
     FUNCTION</command> reference for details.
    </para>

    <para>
     To make use of these optimization attributes, you have to use the
     <literal>WITH</literal> modifier in your <command>CREATE
     FUNCTION</command> statement.  Something like:

<programlisting>
CREATE FUNCTION foo(...) RETURNS INTEGER AS '
...
' LANGUAGE 'plpgsql'
WITH (isstrict, iscachable);
</programlisting>
    </para>
   </sect3>
  </sect2>

  <sect2 id="plpgsql-porting-appendix">
   <title>
    Appendix
   </title>

   <sect3>
    <title>
     Code for my <function>instr</function> functions
    </title>

    <comment>
     This function should probably be integrated into the core.
    </comment>

<programlisting>
--
-- instr functions that mimic Oracle's counterpart
-- Syntax: instr(string1,string2,[n],[m]) where [] denotes optional params.
-- 
-- Searches string1 beginning at the nth character for the mth
-- occurrence of string2. If n is negative, search backwards. If m is
-- not passed, assume 1 (search starts at first character).
--
-- by Roberto Mello (rmello@@fslc.usu.edu)
-- modified by Robert Gaszewski (graszew@@poland.com)
-- Licensed under the GPL v2 or later.
--

CREATE FUNCTION instr(VARCHAR,VARCHAR) RETURNS INTEGER AS '
DECLARE
    pos integer;
BEGIN
    pos:= instr($1,$2,1);
    RETURN pos;
END;
' LANGUAGE 'plpgsql';


CREATE FUNCTION instr(VARCHAR,VARCHAR,INTEGER) RETURNS INTEGER AS '
DECLARE
    string ALIAS FOR $1;
    string_to_search ALIAS FOR $2;
    beg_index ALIAS FOR $3;
    pos integer NOT NULL DEFAULT 0;
    temp_str VARCHAR;
    beg INTEGER;
    length INTEGER;
    ss_length INTEGER;
BEGIN
    IF beg_index > 0 THEN

       temp_str := substring(string FROM beg_index);
       pos := position(string_to_search IN temp_str);

       IF pos = 0 THEN
	         RETURN 0;
	     ELSE
	         RETURN pos + beg_index - 1;
	     END IF;
    ELSE
       ss_length := char_length(string_to_search);
       length := char_length(string);
       beg := length + beg_index - ss_length + 2;

       WHILE beg > 0 LOOP
           temp_str := substring(string FROM beg FOR ss_length);
	         pos := position(string_to_search IN temp_str);

	         IF pos > 0 THEN
		           RETURN beg;
	         END IF;

	         beg := beg - 1;
       END LOOP;
       RETURN 0;
    END IF;
END;
' LANGUAGE 'plpgsql';

--
-- Written by Robert Gaszewski (graszew@@poland.com)
-- Licensed under the GPL v2 or later.
--
CREATE FUNCTION instr(VARCHAR,VARCHAR,INTEGER,INTEGER) RETURNS INTEGER AS '
DECLARE
    string ALIAS FOR $1;
    string_to_search ALIAS FOR $2;
    beg_index ALIAS FOR $3;
    occur_index ALIAS FOR $4;
    pos integer NOT NULL DEFAULT 0;
    occur_number INTEGER NOT NULL DEFAULT 0;
    temp_str VARCHAR;
    beg INTEGER;
    i INTEGER;
    length INTEGER;
    ss_length INTEGER;
BEGIN
    IF beg_index > 0 THEN
        beg := beg_index;
        temp_str := substring(string FROM beg_index);

        FOR i IN 1..occur_index LOOP
            pos := position(string_to_search IN temp_str);

            IF i = 1 THEN
                beg := beg + pos - 1;
            ELSE
                beg := beg + pos;
            END IF;

            temp_str := substring(string FROM beg + 1);
        END LOOP;

        IF pos = 0 THEN
            RETURN 0;
        ELSE
            RETURN beg;
        END IF;
    ELSE
        ss_length := char_length(string_to_search);
        length := char_length(string);
        beg := length + beg_index - ss_length + 2;

        WHILE beg > 0 LOOP
            temp_str := substring(string FROM beg FOR ss_length);
            pos := position(string_to_search IN temp_str);

            IF pos > 0 THEN
                occur_number := occur_number + 1;

                IF occur_number = occur_index THEN
                    RETURN beg;
                END IF;
            END IF;

            beg := beg - 1;
        END LOOP;

        RETURN 0;
    END IF;
END;
' LANGUAGE 'plpgsql';
</programlisting>
   </sect3>
  </sect2>
  
 </sect1>

</chapter>

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


2.60
log
@plpgsql's PERFORM statement now sets FOUND depending on whether any
rows were returned by the performed query.  Per recent pgsql-general
discussion.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.59 2002/06/15 19:34:51 momjian Exp $
@


2.59
log
@On Wed, 2002-05-29 at 01:41, Tom Lane wrote:
>
> > Is it a good idea to provide an example (such as the above), or should I
> > just try and describe the behaviour?
>
> Examples are generally good things ...

OK, the attached documentation patch provides some simple examples of
use of tablename as a parameter, %ROWTYPE and %TYPE.

In the end I decided that the documentation is literally correct, but
hard to follow without any examples explicitly showing the use of a
table name as a parameter.

Andrew McMillan
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.58 2002/05/03 04:11:07 tgl Exp $
d906 3
a908 1
     in the query as usual.
d921 1
a921 5
PERFORM create_mv(''cs_session_page_requests_mv'',''
     SELECT   session_id, page_id, count(*) AS n_hits,
              sum(dwell_time) AS dwell_time, count(dwell_time) AS dwell_count
     FROM     cs_fact_table
     GROUP BY session_id, page_id '');
@


2.58
log
@Remove the last traces of datatypes datetime and timespan.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.57 2002/04/09 03:08:25 momjian Exp $
d374 3
d454 9
d506 11
@


2.57
log
@More cleanups of cursor text.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.56 2002/04/09 02:43:25 momjian Exp $
d2747 1
a2747 1
CREATE FUNCTION acs__add_user(INTEGER,INTEGER,VARCHAR,DATETIME,INTEGER,INTEGER,...)
@


2.56
log
@Fix markup problem with recent change.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.55 2002/04/09 02:31:58 momjian Exp $
d1452 2
a1453 2
    caller to read the rows. This provides one way of returning multiple
    rows and columns from a function.
d1694 1
a1694 1
   &gt;unnamed cursor 1&lt;
d1697 1
a1697 1
FETCH ALL IN "&gt;unnamed cursor 1&lt;";
@


2.55
log
@Update refcursor documentation with examples of how to return pl/pgsql
refcursors.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.54 2002/03/22 19:20:18 petere Exp $
d1694 1
a1694 1
   <unnamed cursor 1>
d1697 1
a1697 1
FETCH ALL IN "<unnamed cursor 1>";
@


2.54
log
@Spell checking and markup additions
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.53 2002/01/07 02:29:13 petere Exp $
d765 1
a765 1
     (as for <type>char(20)</type>), the result value will be implicitly
d883 1
a883 1
     into the query as usual.
d930 1
a930 1
     be inserted into the query string as it is constructed.
d1444 10
a1453 10
    Rather than executing a whole query at once, it is possible to
    set up a <firstterm>cursor</> that encapsulates the query, and
    then read the query result a few rows at a time.  One reason
    for doing this is to avoid memory overrun when the result contains
    a large number of rows.  (However, <application>PL/pgSQL</> users
    don't normally need to worry about that, since FOR loops automatically
    use a cursor internally to avoid memory problems.)  A more interesting
    possibility is that a function can return a reference to a cursor
    that it has set up, allowing the caller to read the rows.  This
    provides one way of returning a row set from a function.
d1501 4
a1504 5
     <firstterm>opened</>.  (This is the equivalent action to
     the SQL command <command>DECLARE CURSOR</>.)
     <application>PL/pgSQL</> has four forms of the OPEN statement,
     two of which are for use with unbound cursor variables
     and the other two for use with bound cursor variables.
d1520 1
a1520 1
	<application>PL/pgSQL</> variable names are substituted for,
d1541 2
a1542 2
	string expression in the same way as for the EXECUTE command.
	As usual, this gives flexibility for the query to vary
d1564 1
a1564 1
	into the query.
d1595 1
a1595 1
     All Portals are implicitly closed at end of transaction.  Therefore
d1610 1
a1610 1
	list of simple variables, just as for SELECT INTO.  As with
d1635 64
@


2.53
log
@Editorial review
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.52 2002/01/02 00:41:26 tgl Exp $
d395 1
a395 1
      is specified, an assignment of a NULL value results in a runtime
d456 1
a456 1
     <title>Rowtypes</title>
d466 1
a466 1
    variable (or <firstterm>rowtype</> variable).  Such a variable can hold a
d490 2
a491 2
    rowtype variable, not OID or other system attributes (because the
    row could be from a view).  The fields of the rowtype inherit the
d507 1
a507 1
    Record variables are similar to rowtype variables, but they have no
d513 1
a513 1
    field in it will draw a runtime error.
d517 1
a517 1
    Note that <literal>RECORD</> is not a true datatype, only a placeholder.
d714 1
a714 1
     functions for the conversion.  So, the computed timestamp is updated
d723 1
a723 1
     since the expression will be planned using the datatype that is present
d769 1
a769 1
     result in runtime errors generated by the input function, if the
d787 1
a787 1
     only one row) can be assigned to a record variable, rowtype
d805 1
a805 1
     must exactly match the structure of the target(s), or a runtime error
d807 1
a807 1
     configures itself to the rowtype of the query result columns.
d911 1
a911 1
     queries that will involve different tables or different datatypes
d1037 1
a1037 1
     the Oid of the last row inserted by the most recent
d1066 1
a1066 1
     The expression's result will be automatically casted into the
d1073 1
a1073 1
     the function without hitting a RETURN statement, a runtime error
d1432 1
a1432 1
     an integer FOR loop.  This can cause rather unintuitive error
d1453 1
a1453 1
    provides one way of returning a rowset from a function.
d1461 1
a1461 1
     cursor variables, which are always of the special datatype
d1485 1
a1485 1
     All three of these variables have the datatype <type>refcursor</>,
@


2.52
log
@Fix incorrect description of rowtype variable declarations.  Eventually
(IMHO) the code should be fixed to do what the documentation formerly
claimed, and then revert this change.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.51 2001/11/28 04:18:46 tgl Exp $
d1703 1
a1703 1
     caused the abort (input/output conversion error, floating point
@


2.51
log
@Reiterate that parsing of plpgsql functions is per-process.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.50 2001/11/21 05:53:41 thomas Exp $
d460 1
a460 1
<replaceable>name</replaceable> <replaceable>table-datatype</replaceable>;
d465 3
a467 3
    A variable declared with a composite type (referenced by the name of
    the table that defines that type) is called a <firstterm>row</>
    variable.  Such a variable can hold a whole row of a SELECT or FOR
d469 1
a469 1
    rowtype of the variable.  The individual fields of the row value are
d475 7
d573 1
a573 3
	 table or view name of the database.  A row variable declared
	 in this way acts the same as a row variable explicitly declared using
	 the same composite (row) datatype.
d624 9
@


2.50
log
@Deprecate 'current' for date/time input.
Fix up references to "PostgreSQL" rather than "Postgres". Was roughly
 evenly split between the two before. ref/ files not yet done.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.49 2001/11/16 00:40:11 tgl Exp $
d65 2
a66 1
    function is called.  The instruction tree fully translates the
@


2.49
log
@Fix silly error in plpgsql example.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.48 2001/11/15 23:32:39 tgl Exp $
d14 1
a14 1
  <productname>Postgres</productname> database system.
d154 1
a154 1
     <acronym>SQL</acronym> is the language PostgreSQL (and
d197 2
a198 2
     Because <application>PL/pgSQL</application> functions run inside PostgreSQL, these
     functions will run on any platform where PostgreSQL
d222 1
a222 1
       Using PostgreSQL's GUI Tool: <application>PgAccess</>
d322 1
a322 1
     <productname>Postgres</productname> does not have nested transactions.
d646 1
a646 1
     The evaluation done by the <productname>Postgres</productname>
d678 1
a678 1
     <productname>Postgres</productname> main parser knows when 
d691 1
a691 1
     <productname>Postgres</productname> main parser does not know
d782 1
a782 1
     Postgres' normal interpretation of SELECT INTO, which is that the
d1678 1
a1678 1
     <productname>Postgres</productname> does not have a very smart
d1917 1
a1917 1
    in future versions of <productname>Postgres</productname> will be
d2039 2
a2040 2
   PostgreSQL's <application>PL/pgSQL</application> languages in the hopes of helping developers
   port applications from Oracle to PostgreSQL.  Most of the code here
d2043 1
a2043 1
   module</ulink> that I ported to PostgreSQL when I took an
d2051 1
a2051 1
   declared). PL/SQL has many more features than its PostgreSQL
d2060 1
a2060 1
    Some things you should keep in mind when porting from Oracle to PostgreSQL:
d2065 1
a2065 1
       No default parameters in PostgreSQL.
d2071 1
a2071 1
       You can overload functions in PostgreSQL. This is often used to work 
d2084 1
a2084 1
       No need for cursors in PostgreSQL, just put the query in the FOR 
d2091 1
a2091 1
       In PostgreSQL you <emphasis>need</emphasis> to escape single
d2102 1
a2102 1
     In PostgreSQL you need to escape single quotes inside your
d2249 1
a2249 1
        parameter will receive a value and return another. PostgreSQL
d2259 1
a2259 1
        <literal>RETURNS</literal> in PostgreSQL.
d2265 1
a2265 1
        On PostgreSQL functions are created using single quotes as
d2275 1
a2275 1
        PostgreSQL.
d2283 1
a2283 1
     PostgreSQL:
d2313 1
a2313 1
     single quotes in PostgreSQL.
d2341 1
a2341 1
     Here is how this function would end up in PostgreSQL:
d2390 1
a2390 1
     PostgreSQL, one way to work around this is to split the procedure
d2408 1
a2408 1
    a_pos1 := instr(v_url, '//'); -- PostgreSQL doesn't have an instr function
d2436 1
a2436 1
     Here is how this procedure could be translated for PostgreSQL:
d2472 1
a2472 1
     PostgreSQL does not have an <function>instr</function> function,
d2527 1
a2527 1
    Procedures like this can be easily converted into PostgreSQL
d2534 1
a2534 1
       There is no <literal>pragma</literal> statement in PostgreSQL.
d2549 1
a2549 1
       executed in a transaction and PostgreSQL rolls back the results if
d2662 1
a2662 1
    We port this to PostgreSQL by creating the different objects of
d2665 1
a2665 1
    the lack of default parameters in PostgreSQL functions. The above
d2700 1
a2700 1
     The PostgreSQL version of <literal>EXECUTE</literal> works
d2714 1
a2714 1
     PostgreSQL gives you two function creation modifiers to optimize
@


2.48
log
@Add documentation for new plpgsql cursor operations.  Also, another
round of editorial effort.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.47 2001/11/15 06:25:22 tgl Exp $
d1187 2
a1189 2
    result := ''positive'';
ELSIF number &gt; 0 THEN 
@


2.47
log
@Significant editorial overhaul of plpgsql documentation.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.46 2001/11/08 23:41:12 petere Exp $
d329 8
a336 2
     All keywords and identifiers can be used in mixed upper and
     lower-case.
d400 1
a400 1
      The default value is evaluated every time the function is called. So,
d417 7
a423 1
     <title>Aliases for Parameters Passed to Functions</title>
d428 4
a431 2
      etc.  Optionally, aliases can be declared for the <literal>$n</literal>
      parameter names for increased readability.  Some examples:
d507 6
d578 1
a578 1
CREATE FUNCTION cs_refresh_one_mv(INTEGER) RETURNS INTEGER AS '
d587 1
a587 2
           RAISE EXCEPTION ''View % not found'', key;
           RETURN 0;
d589 2
a590 9

        -- The mv_name column of cs_materialized_views stores view
        -- names.
 
        EXECUTE ''TRUNCATE TABLE '' || quote_ident(table_data.mv_name);
        EXECUTE ''INSERT INTO '' || quote_ident(table_data.mv_name) || '' '' || table_data.mv_query;

        return 1;
end;
d599 1
a599 3
     <title>
      RENAME
     </title>
d602 4
d607 2
a608 2
      record or row. This is useful if NEW or OLD should be referenced
      by another name inside a trigger procedure.  See also ALIAS.
d612 1
a612 1
      Syntax and examples:
a613 2
RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;

d717 1
a717 1
  <title>Statements</title>
d720 6
a725 5
    This section describes all the statement types that are explicitly
    understood by <application>PL/pgSQL</application>.  Anything not
    recognized as one of these statement types is presumed to be an SQL
    query, and is sent to the main database engine to execute (after
    substitution for any <application>PL/pgSQL</application> variables
d729 2
a730 1
    <application>PL/pgSQL</application>.
d767 2
a768 2
   <sect2 id="plpgsql-query-assignment">
    <title>Query Assignments</title>
d785 1
a785 1
     equivalent syntax <command>CREATE TABLE AS SELECT</command>.)
d796 1
a796 1
     Except for the INTO clause, the SELECT command is the same as a normal
d862 1
a862 1
PERFORM <replaceable>query</replaceable>
d903 1
a903 1
EXECUTE <replaceable class="command">query-string</replaceable>
d1012 1
a1012 1
GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>
d1027 1
d1029 2
a1030 3
   <!-- **** PL/pgSQL Control Structures **** -->

  <sect2 id="plpgsql-control-structures">
a1031 1
   <title>Control Structures</title>
d1040 1
a1040 1
   <sect3 id="plpgsql-statements-returning">
d1045 1
a1045 1
RETURN <replaceable>expression</replaceable>
d1047 1
d1061 1
a1061 1
   </sect3>
d1063 2
a1064 2
   <sect3 id="plpgsql-conditionals">
    <title>Conditional Control: IF statements</title>
d1067 1
a1067 1
	<function>IF</function> statements let you execute commands based on
d1070 1
a1070 1
      IF-THEN-ELSE IF, IF-THEN-ELSIF-THEN-ELSE.
d1073 2
a1074 5
    <variablelist>
     <varlistentry>
      <term>
       IF-THEN
      </term>
a1075 1
      <listitem>
d1077 6
d1093 1
a1093 2
      </listitem>
     </varlistentry>
d1095 2
a1096 4
     <varlistentry>
      <term>
       IF-THEN-ELSE
      </term>
a1097 1
      <listitem>
d1099 8
d1108 2
a1109 2
        specify a group of statements that should be executed if the
        condition evaluates to FALSE.
d1128 1
a1128 2
      </listitem>
     </varlistentry>
d1130 2
a1131 4
     <varlistentry>
      <term>
       IF-THEN-ELSE IF
      </term>
a1132 1
      <listitem>
d1154 1
a1154 2
      </listitem>
     </varlistentry>
d1156 2
a1157 4
     <varlistentry>
      <term>
       IF-THEN-ELSIF-ELSE
      </term>
a1158 1
      <listitem>
d1160 15
d1188 1
a1188 1
    result := ''negative'';
d1192 1
a1192 1
    -- now it seems to be NULL
a1200 2
      </listitem>
     </varlistentry>
d1202 2
d1205 2
a1206 5
    </variablelist>
   </sect3>

   <sect3 id="plpgsql-control-structures-loops">
    <title>Iterative Control: LOOP, WHILE, FOR and EXIT</title>
d1209 1
a1209 1
     With the LOOP, WHILE, FOR and EXIT statements, you can arrange
d1214 2
a1215 5
    <variablelist>
     <varlistentry>
      <term>
       LOOP
      </term>
a1216 1
      <listitem>
d1224 5
a1228 3
        An unconditional loop that must be terminated explicitly
        by an EXIT statement. The optional label can be used by
        EXIT statements of nested loops to specify which level of
d1231 1
a1231 2
      </listitem>
     </varlistentry>
d1233 2
a1234 4
     <varlistentry>
      <term>
       EXIT
      </term>
a1235 1
      <listitem>
d1240 1
d1245 2
a1246 2
        must be the label of the current or an outer level of nested loop
        blocks. Then the named loop or block is terminated and control
d1253 1
a1253 1
	is true.
d1279 1
a1279 2
      </listitem>
     </varlistentry>
d1281 2
a1282 4
     <varlistentry>
      <term>
       WHILE
      </term>
a1283 1
      <listitem>
a1284 4
        With the WHILE statement, you can repeat a
        sequence of statements so long as the condition expression
	evaluates to true.  The condition is checked just before
	each entry to the loop body.
d1291 8
d1310 1
a1310 2
      </listitem>
     </varlistentry>
d1312 2
a1313 4
     <varlistentry>
      <term>
       FOR
      </term>
a1314 1
      <listitem>
a1315 1

d1322 4
a1325 2
        A loop that iterates over a range of integer values. The variable
        <replaceable>name</replaceable> is automatically created as type
d1346 2
a1347 4
      </listitem>
     </varlistentry>
    </variablelist>
   </sect3>
d1349 2
a1350 2
   <sect3 id="plpgsql-records-iterating">
    <title>Iterating Through Records</title>
d1355 1
a1355 1
     accordingly. The syntax is as follows:
d1419 1
a1419 1
     misspelled the FOR variable.
a1421 1
   </sect3>
d1423 202
@


2.46
log
@Fix indexterms
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.45 2001/10/13 04:58:35 momjian Exp $
d65 4
a68 4
    function is called. The produced bytecode is identified
    in the call handler by the object ID of the function. This ensures
    that changing a function by a DROP/CREATE sequence will take effect
    without establishing a new database connection. 
d71 8
a78 9
    For all expressions and <acronym>SQL</acronym> statements used in
    the function, the <application>PL/pgSQL</> bytecode interpreter creates a
    prepared execution plan using the <acronym>SPI</acronym> manager's 
    <function>SPI_prepare()</function> and
    <function>SPI_saveplan()</function> functions. This is done the 
    first time the individual
    statement is processed in the <application>PL/pgSQL</> function. Thus, a function with
    conditional code that contains many statements for which execution
    plans would be required, will only prepare and save those plans
d80 4
a83 1
    connection.
d86 5
a90 2
  This means that you have to be careful about your user-defined
  functions. For example:
d101 3
a103 2
    If you create the above function, it will reference the OID for
    <function>my_function()</function> in its bytecode. Later, if you
d107 2
a108 1
    re-create <function>populate()</function>.
d165 2
a166 2
     other queries to the server. All this incurs inter
     process communication and may also incur network
d177 2
a178 2
     communication overhead. Your application will enjoy a
     considerable performance increase by using <application>PL/pgSQL</application>. 
d232 4
a235 5
    those functions. If you are doing it this way (and if you are
    a <application>PL/pgSQL</> novice or in debugging stage), it is a good idea to 
    always <command>DROP</command> your function before creating it. That way
    when you reload the file, it'll drop your functions and then
    re-create them. For example:
d237 1
a237 2
DROP FUNCTION testfunc(integer);
CREATE FUNCTION testfunc(INTEGER) RETURNS INTEGER AS '
d245 2
a246 4
    When you load the file for the first time,
    <productname>PostgreSQL</> will raise a warning saying this
    function doesn't exist and go on to create it. To load an SQL
    file (e.g., <filename>filename.sql</filename>) into a database named <literal>dbname</literal>, use the command:
d248 1
a248 1
psql -f filename.sql dbname
d250 1
d262 2
a263 9
  <!-- **** PL/pgSQL Description **** -->

  <sect1 id="plpgsql-description">
   <title>Description</title>

   <!-- **** PL/pgSQL structure **** -->

   <sect2>
    <title>Structure of <application>PL/pgSQL</application></title>
d266 3
a268 3
     <application>PL/pgSQL</application> is a <emphasis>block structured</emphasis> language. All
     keywords and identifiers can be used in mixed upper and
     lower-case. A block is defined as:
d271 3
a273 3
<optional>&lt;&lt;label&gt;&gt;</optional>
<optional>DECLARE
    <replaceable>declarations</replaceable></optional>
d281 4
a284 3
     There can be any number of sub-blocks in the statement section
     of a block. Sub-blocks can be used to hide variables from outside a
     block of statements.
a323 1
   </sect2>
d326 6
a331 1
    <title>Comments</title>
d342 1
d344 2
a345 3
   <!-- **** PL/pgSQL Variables and Constants **** -->
   <sect2>
    <title>Variables and Constants</title>
d348 5
a352 4
     All variables, rows and records used in a block or its
     sub-blocks must be declared in the declarations section of a block.
     The exception being the loop variable of a FOR loop iterating over a range
     of integer values. 
d358 1
a358 2
     <type>CHAR</type>. All variables have as default value the
     <acronym>SQL</acronym> NULL value. 
d370 6
a375 2
    <sect3 id="plpgsql-description-default-vars">
     <title>Constants and Variables With Default Values</title>
d378 4
a381 4
      The declarations have the following syntax:
<synopsis>
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>value</replaceable> </optional>;
</synopsis>
d385 3
a387 1
      The value of variables declared as CONSTANT cannot be changed. If NOT NULL
d389 2
a390 3
      error. Since the default value of all variables is the
      <acronym>SQL</acronym> NULL value, all variables declared as NOT NULL
      must also have a default value specified.
d394 2
a395 2
      The default value is evaluated every time the function is called. So
      assigning '<literal>now</literal>' to a variable of type
d397 2
a398 2
      time of the actual function call, not when the function was
      precompiled into its bytecode.
d404 1
a404 1
quantity INTEGER := 32;
a408 1
    </sect3>
d410 2
a411 2
    <sect3 id="plpgsql-description-passed-vars">
     <title>Parameters Passed to Functions</title>
d438 1
a438 1
    </sect3>
d440 56
a495 1
    <sect3 id="plpgsql-description-attributes">
d529 2
a530 2
         change your table definition of user_id to become a
         REAL), you won't need to change your function
d545 3
a547 5
	 table or view name of the database. The fields of the row are
	 accessed in the dot notation. Parameters to a function can be
	 composite types (complete table rows). In that case, the
	 corresponding identifier $n will be a rowtype, and fields can
	 be selected from it, for example <literal>$1.user_id</literal>.
a549 7
        <para>
         Only the user-defined attributes of a table row are accessible in a
	 rowtype variable, not OID or other system attributes (because the
	 row could be from a view).  The fields of the rowtype inherit the
	 table's field sizes or precision for <type>char()</type>
	 etc. data types.
        </para>
d584 1
a584 1
    </sect3>
d586 1
a586 1
    <sect3 id="plpgsql-description-remaning-vars">
d592 3
a594 3
      Using RENAME you can change the name of a variable, record
      or row. This is useful if NEW or OLD should be referenced
      by another name inside a trigger procedure.
d606 2
a607 2
    </sect3>
   </sect2>
d609 2
a610 4
   <!-- **** PL/pgSQL expressions **** -->

   <sect2>
    <title>Expressions</title>
d613 3
a615 2
     All expressions used in <application>PL/pgSQL</application> statements are processed using
     the executor of the server. Expressions that appear to contain
d625 6
a630 5
     using the <acronym>SPI</acronym> manager. In the expression, occurrences of variable
     identifiers are substituted by parameters and the actual values from
     the variables are passed to the executor in the parameter array. All
     expressions used in a <application>PL/pgSQL</application> function are only prepared and
     saved once.  The only exception to this rule is an EXECUTE statement.
d634 1
a634 1
     The type checking done by the <productname>Postgres</productname>
d636 1
a636 1
     effects to the interpretation of constant values. In detail there
d681 4
a684 3
     it returns a data type of <type>text</type> containing the string 
     <literal>'now'</literal>. During the assignment
     to the local variable <varname>curtime</varname>, the <application>PL/pgSQL</application> interpreter casts this
d687 2
a688 1
     functions for the conversion.
d692 6
a697 12
     This type checking done by the <productname>Postgres</productname> main
     parser got implemented after <application>PL/pgSQL</application> was nearly done.
     It is a difference between 6.3 and 6.4 and affects all functions
     using the prepared plan feature of the <acronym>SPI</acronym> manager.
     Using a local
     variable in the above manner is currently the only way in <application>PL/pgSQL</application> to get
     those values interpreted correctly.
    </para>

    <para>
     If record fields are used in expressions or statements, the data types of
     fields should not change between calls of one and the same expression.
d699 2
a700 1
     for more than one table.
d702 1
a702 1
   </sect2>
d704 2
a705 4
   <!-- **** PL/pgSQL statements **** -->

  <sect2>
   <title>Statements</title>
d708 9
a716 3
    Anything not understood by the <application>PL/pgSQL</application> parser as specified below
    will be put into a query and sent down to the database engine
    to execute. The resulting query should not return any data.
d719 1
a719 1
   <sect3 id="plpgsql-statements-assignment">
d721 1
d728 4
d733 9
a741 6
     If the expressions result data type doesn't match the variables
     data type, or the variable has a size/precision that is known
     (as for <type>char(20)</type>), the result value will be implicitly cast by
     the <application>PL/pgSQL</application> bytecode interpreter using the result types output- and
     the variables type input-functions. Note that this could potentially
     result in runtime errors generated by the types input functions.
d744 2
d750 64
a813 1
   </sect3>
d815 4
a818 2
   <sect3 id="plpgsql-statements-calling-other-funcs">
    <title>Calling another function</title>
d821 14
a834 4
     All functions defined in a <productname>Postgres</productname>
     database return a value. Thus, the normal way to call a function
     is to execute a SELECT query or doing an assignment (resulting
     in a <application>PL/pgSQL</application> internal SELECT). 
d836 4
d842 5
a846 3
     But there are cases where someone is not interested in the 
     function's result. In these cases, use the PERFORM
     statement.
d850 5
a854 3
     This executes a <literal>SELECT <replaceable>query</replaceable></literal> over the
     <acronym>SPI manager</acronym> and discards the result. Identifiers like local
     variables are still substituted into parameters.
d856 10
d873 2
a874 1
   </sect3>
d876 1
a876 1
   <sect3 id="plpgsql-statements-executing-dyn-queries">
d880 7
a886 5
     Often times you will want to generate dynamic queries inside
     your <application>PL/pgSQL</application> functions. Or you have functions that will
     generate other functions. <application>PL/pgSQL</application> provides the EXECUTE
     statement for these occasions.
    </para>
a887 1
    <para>
d891 11
a901 3
     where <replaceable>query-string</replaceable> is a string of type
     <type>text</type> containing the <replaceable>query</replaceable>
     to be executed.
d907 1
a907 1
    table available at the <xref linkend="plpgsql-porting">
d926 1
a926 1
     to use the FOR ... EXECUTE form described later.
d950 2
a951 1
     or double quotes and with any embedded special characters.
d967 2
a968 1
                         v_url ALIAS FOR $3; ''; 
d991 1
a991 1
   </sect3>
d993 2
a994 2
   <sect3 id="plpgsql-statements-diagnostics">
    <title>Obtaining other results status</title>
d1012 14
a1025 1
   </sect3>
d1036 3
a1038 4
     upper executor. The return value of a function cannot be
     undefined. If control reaches the end of the top-level block of
     the function without hitting a RETURN statement, a runtime error
     will occur.
d1042 4
a1045 2
     The expressions result will be automatically casted into the
     function's return type as described for assignments.
a1047 13
  </sect2>

   <!-- **** PL/pgSQL Control Structures **** -->

  <sect2 id="plpgsql-description-control-structures">

   <title>Control Structures</title>
   <para>
    Control structures are probably the most useful (and
    important) part of PL/SQL. With <application>PL/pgSQL</>'s control structures,
    you can manipulate <productname>PostgreSQL</> data in a very
    flexible and powerful way. 
   </para>
d1049 1
a1049 1
   <sect3 id="plpgsql-description-conditionals">
d1054 3
a1056 4
      certain conditions. PL/PgSQL has four forms of IF: IF-THEN, IF-THEN-ELSE,
      IF-THEN-ELSE IF, IF-THEN-ELSIF-THEN-ELSE. NOTE: All PL/PgSQL IF statements need
	a corresponding <function>END IF</function> clause. With ELSE-IF statements,
      you need two: one for the first IF and one for the second (ELSE IF).
d1067 1
a1067 1
        IF-THEN statements is the simplest form of an IF. The
d1069 2
a1070 2
        the condition is true. Otherwise, the statements
        following END IF will be executed.
d1087 2
a1088 2
        IF-THEN-ELSE statements adds to IF-THEN by letting you
        specify the statements that should be executed if the
d1090 1
d1108 7
d1116 1
d1118 1
a1118 2
        IF statements can be nested and in the following
        example:
a1128 2
      </listitem>
     </varlistentry>
a1129 6
     <varlistentry>
      <term>
       IF-THEN-ELSE IF
      </term>

      <listitem>
d1131 2
a1132 2
        When you use the <literal>ELSE IF</> statement, you are actually
        nesting an IF statement inside the ELSE
d1135 2
a1136 12
       </para>

       <para>
        For example:
<programlisting>
IF demo_row.sex = ''m'' THEN
   pretty_sex := ''man'';
ELSE IF demo_row.sex = ''f'' THEN
        pretty_sex := ''woman'';
     END IF;
END IF;
</programlisting>
d1148 4
a1151 4
        IF-THEN-ELSIF-ELSE allows you test multiple conditions
        in one statement. Internally it is handled as nested 
        IF-THEN-ELSE-IF-THEN commands. The optional ELSE
        branch is executed when none of the conditions are met.
d1170 4
d1181 1
a1181 1
   <sect3 id="plpgsql-description-control-structures-loops">
d1185 3
a1187 3
     With the LOOP, WHILE, FOR and EXIT statements, you can
     control the flow of execution of your <application>PL/pgSQL</application> program
     iteractively.
d1226 1
a1226 1
        must be the label of the current or an upper level of nested loop
d1228 1
a1228 1
        continues with the statement after the loops/blocks corresponding
d1233 5
d1270 4
a1273 3
        With the WHILE statement, you can loop through a
        sequence of statements as long as the evaluation of
        the condition expression is true.
d1301 1
d1311 3
a1313 2
        the lower and upper bound of the range are evaluated only when entering
        the loop. The iteration step is always 1.
d1317 1
a1317 3
        Some examples of FOR loops (see <xref
        linkend="plpgsql-description-records"> for iterating over
        records in FOR loops):
a1332 105
      </sect3>
   </sect2>

   <!-- **** PL/pgSQL records **** -->

  <sect2 id="plpgsql-description-records">
   <title>Working with RECORDs</title>

   <para>
    Records are similar to rowtypes, but they have no predefined structure.
    They are used in selections and FOR loops to hold one actual
    database row from a SELECT operation.
   </para>

   <sect3 id="plpgsql-description-records-declaration">
    <title>Declaration</title>

    <para>
     One variables of type RECORD can be used for different
     selections. Accessing a record or an attempt to assign
     a value to a record field when there is no actual row in it results
     in a runtime error. They can be declared like this:
    </para>

    <para>
<synopsis>
<replaceable>name</replaceable> RECORD;
</synopsis>
    </para>
   </sect3>

   <sect3 id="plpgsql-description-records-assignment">
    <title>Assignments</title>

    <para>
     An assignment of a complete selection into a record or row can
     be done by:
<synopsis>
SELECT  INTO <replaceable>target</replaceable> <replaceable>expressions</replaceable> FROM ...;
</synopsis>
     <replaceable>target</replaceable> can be a record, a row variable
     or a comma separated list of variables and
     record-/row-fields. Note that this is quite different from
     Postgres' normal interpretation of SELECT INTO, which is that the
     INTO target is a newly created table.  (If you want to create a
     table from a SELECT result inside a <application>PL/pgSQL</application> function, use the
     equivalent syntax <command>CREATE TABLE AS SELECT</command>.)
    </para>

    <para>
     If a row or a variable list is used as target, the selected values
     must exactly match the structure of the target(s) or a runtime error
     occurs. The FROM keyword can be followed by any valid qualification,
     grouping, sorting etc. that can be given for a SELECT statement.
    </para>

    <para>
     Once a record or row has been assigned to a RECORD variable,
     you can use the <literal>.</> (dot) notation to access fields in that
     record:
<programlisting>
DECLARE
    users_rec RECORD;
    full_name varchar;
BEGIN
    SELECT INTO users_rec * FROM users WHERE user_id=3;

  full_name := users_rec.first_name || '' '' || users_rec.last_name;
</programlisting>
    </para>

    <para>
     There is a special variable named FOUND of type
     <type>boolean</type> that can be used immediately after a SELECT
     INTO to check if an assignment had success.
  
<programlisting>
SELECT INTO myrec * FROM EMP WHERE empname = myname;
IF NOT FOUND THEN
    RAISE EXCEPTION ''employee % not found'', myname;
END IF;
</programlisting>

     You can also use the IS NULL (or ISNULL) conditionals to
     test for NULLity of a RECORD/ROW. If the selection returns
     multiple rows, only the first is moved into the target
     fields. All others are silently discarded.
    </para>

    <para>
<programlisting>
DECLARE
    users_rec RECORD;
    full_name varchar;
BEGIN
    SELECT INTO users_rec * FROM users WHERE user_id=3;

    IF users_rec.homepage IS NULL THEN
        -- user entered no homepage, return "http://"

        RETURN ''http://'';
    END IF;
END;
</programlisting>
    </para>
d1335 1
a1335 1
   <sect3 id="plpgsql-description-records-iterating">
d1339 1
a1339 1
     Using a special type of FOR loop, you can iterate through
d1341 1
a1341 1
     accordingly. The syntax is as follow:
d1344 1
a1344 1
FOR <replaceable>record | row</replaceable> IN <replaceable>select_clause</replaceable> LOOP
d1348 3
a1350 3
     The record or row is assigned all the rows 
     resulting from the SELECT clause and the loop body executed 
     for each. Here is an example:
a1357 5

     -- Instead, if you did:
     -- mviews  cs_materialized_views%ROWTYPE;
     -- this record would ONLY be usable for the cs_materialized_views table

d1376 2
a1377 2
     If the loop is terminated with an EXIT statement, the last
     assigned row is still accessible after the loop.
d1381 1
a1381 1
     The FOR-IN EXECUTE statement is another way to iterate over
d1396 12
d1410 1
d1412 2
a1413 2
  <sect2 id="plpgsql-description-aborting-and-messages">
   <title>Aborting and Messages</title>
d1416 1
a1416 2
    Use the RAISE statement to throw messages into the 
    <productname>Postgres</productname> <function>elog</function> mechanism.
d1426 3
d1444 1
a1457 1
  </sect2>   
d1459 2
a1460 4
   <!-- **** PL/pgSQL exceptions **** -->

   <sect2>
    <title>Exceptions</title>
d1484 2
a1485 1
     statement) this happened.
d1487 1
a1487 1
   </sect2>
a1489 3

   <!-- **** PL/pgSQL trigger procedures **** -->

d1494 7
a1500 8
   <application>PL/pgSQL</application> can be used to define trigger procedures. They are created
   with the usual <command>CREATE FUNCTION</command> command as a function with no
   arguments and a return type of <type>OPAQUE</type>.
  </para>

  <para>
   There are some <productname>Postgres</productname> specific details
   in functions used as trigger procedures.
d1504 3
a1506 2
   First they have some special variables created automatically in the 
   top-level blocks declaration section. They are
d1513 2
a1514 2
       Data type <type>RECORD</type>; variable holding the new database row on INSERT/UPDATE
       operations on ROW level triggers.
d1523 2
a1524 2
       Data type <type>RECORD</type>; variable holding the old database row on UPDATE/DELETE
       operations on ROW level triggers.
d1545 1
a1545 1
              depending on the triggers definition.
d1556 1
a1556 1
       triggers definition.
d1568 1
a1568 1
       for which operation the trigger is actually fired.
d1618 10
a1627 8
    Second they must return either NULL or a record/row containing
    exactly the structure of the table the trigger was fired for.
    Triggers fired AFTER might always return a NULL value with no
    effect. Triggers fired BEFORE signal the trigger manager
    to skip the operation for this actual row when returning NULL.
    Otherwise, the returned record/row replaces the inserted/updated
    row in the operation. It is possible to replace single values directly
    in NEW and return that or to build a complete new record/row to
d1631 6
d1641 1
a1641 1
     This trigger ensures, that any time a row is inserted or updated
d1643 1
a1643 1
     row. And it ensures that an employees name is given and that the
d1697 1
a1697 1
    of single quotes. The function's source text on <command>CREATE FUNCTION</command> must
a2022 8
        The <literal>OR REPLACE</literal> clause is not allowed. You
        will have to explicitly drop the function before creating it
        to achieve similar results.
       </para>
      </listitem>

      <listitem>
       <para>
d2067 1
a2067 1
     So let's see how this function would be look like ported to
d2071 1
a2071 2
DROP FUNCTION cs_fmt_browser_version(VARCHAR, VARCHAR);
CREATE FUNCTION cs_fmt_browser_version(VARCHAR, VARCHAR)
d2139 2
a2140 1
                         v_url ALIAS FOR $3; ''; 
d2224 1
a2224 2
DROP FUNCTION cs_parse_url_host(VARCHAR); 
CREATE FUNCTION cs_parse_url_host(VARCHAR) RETURNS VARCHAR AS ' 
d2353 2
a2354 2
DROP FUNCTION cs_create_job(INTEGER);
CREATE FUNCTION cs_create_job(INTEGER) RETURNS INTEGER AS ' DECLARE
a2549 1
DROP FUNCTION instr(varchar,varchar);
a2559 1
DROP FUNCTION instr(VARCHAR,VARCHAR,INTEGER);
a2604 1
DROP FUNCTION instr(VARCHAR,VARCHAR,INTEGER,INTEGER);
@


2.45
log
@More keyword uppercasing.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.44 2001/10/12 23:32:34 momjian Exp $
d1730 1
a1730 1
  <indexterm>
d1734 1
a1734 1
  <indexterm>
@


2.44
log
@Uppercase keywords where appropriate.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.43 2001/10/12 21:19:09 momjian Exp $
d235 1
a235 1
' language 'plpgsql';
d1315 1
a1315 1
' language 'plpgsql';
d2533 1
a2533 1
' language 'plpgsql';
@


2.43
log
@Fix reverse FOR loop to work properly, uppercase cleanup in file.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.42 2001/10/09 04:55:11 tgl Exp $
d712 4
a715 4
     select   session_id, page_id, count(*) as n_hits,
              sum(dwell_time) as dwell_time, count(dwell_time) as dwell_count
     from     cs_fact_table
     group by session_id, page_id '');
d807 4
a810 4
    FOR referrer_keys IN select * from cs_referrer_keys order by try_order LOOP
        a_output := a_output || '' if v_'' || referrer_keys.kind || '' like '''''''''' 
                 || referrer_keys.key_string || '''''''''' then return '''''' 
                 || referrer_keys.referrer_type || ''''''; end if;''; 
d813 1
a813 1
    a_output := a_output || '' return null; end; '''' language ''''plpgsql'''';''; 
d819 1
a819 1
end; 
d1265 1
a1265 1
        return ''http://'';
d1286 1
a1286 1
     resulting from the select clause and the loop body executed 
d1292 1
a1292 1
create function cs_refresh_mviews () returns INTEGER as '
d1313 1
a1313 1
     return 1;
d2033 19
a2051 19
create or replace procedure cs_update_referrer_type_proc is 
    cursor referrer_keys is 
        select * from cs_referrer_keys 
        order by try_order;

    a_output varchar(4000); 
begin 
    a_output := 'create or replace function cs_find_referrer_type(v_host IN varchar, v_domain IN varchar, 
v_url IN varchar) return varchar is begin'; 

    for referrer_key in referrer_keys loop 
        a_output := a_output || ' if v_' || referrer_key.kind || ' like ''' || 
referrer_key.key_string || ''' then return ''' || referrer_key.referrer_type || 
'''; end if;'; 
    end loop; 

    a_output := a_output || ' return null; end;'; 
    execute immediate a_output; 
end; 
d2078 4
a2081 4
    FOR referrer_keys IN select * from cs_referrer_keys order by try_order LOOP
        a_output := a_output || '' if v_'' || referrer_keys.kind || '' like '''''''''' 
                 || referrer_keys.key_string || '''''''''' then return '''''' 
                 || referrer_keys.referrer_type || ''''''; end if;''; 
d2084 1
a2084 1
    a_output := a_output || '' return null; end; '''' language ''''plpgsql'''';''; 
d2090 1
a2090 1
end; 
d2112 5
a2116 5
create or replace procedure cs_parse_url(
    v_url IN varchar,
    v_host OUT varchar,  -- This will be passed back
    v_path OUT varchar,  -- This one too
    v_query OUT varchar) -- And this one
d2118 2
a2119 2
    a_pos1 integer;
    a_pos2 integer;
d2126 3
a2128 3
    if a_pos1 = 0 then
        return;
    end if;
d2130 1
a2130 1
    if a_pos2 = 0 then
d2133 2
a2134 2
        return;
    end if;
d2139 1
a2139 1
    if a_pos1 = 0 then
d2141 2
a2142 2
        return;
    end if;
d2146 1
a2146 1
end;
d2155 3
a2157 3
drop function cs_parse_url_host(VARCHAR); 
create function cs_parse_url_host(VARCHAR) RETURNS VARCHAR AS ' 
declare 
d2159 6
a2164 6
    v_host varchar; 
    v_path varchar; 
    a_pos1 integer; 
    a_pos2 integer; 
    a_pos3 integer; 
begin 
d2168 3
a2170 3
    if a_pos1 = 0 then 
        return '''';  -- Return a blank
    end if; 
d2173 1
a2173 1
    if a_pos2 = 0 then 
d2176 2
a2177 2
        return v_host; 
    end if; 
d2180 3
a2182 3
    return v_host; 
end; 
' language 'plpgsql';
d2214 5
a2218 6
create or replace procedure cs_create_job(v_job_id in integer)
is
    a_running_job_count integer;
    pragma autonomous_transaction;<co id="co.plpgsql-porting-pragma">
begin
    lock table cs_jobs in exclusive mode;<co id="co.plpgsql-porting-locktable">
d2220 3
a2222 2
    select count(*) into a_running_job_count from cs_jobs
    where end_stamp is null;
d2224 2
a2225 2
    if a_running_job_count > 0 then
        commit; -- free lock<co id="co.plpgsql-porting-commit">
d2227 1
a2227 1
    end if;
d2229 2
a2230 2
    delete from cs_active_job;
    insert into cs_active_job(job_id) values(v_job_id);
d2232 6
a2237 6
    begin
        insert into cs_jobs(job_id, start_stamp) values(v_job_id, sysdate);
        exception when dup_val_on_index then null; -- don't worry if it already exists<co id="co.plpgsql-porting-exception">
    end;
    commit;
end;
d2285 2
a2286 2
drop function cs_create_job(INTEGER);
create function cs_create_job(INTEGER) RETURNS INTEGER AS ' DECLARE
d2289 2
a2290 2
    a_num integer;
    -- pragma autonomous_transaction;
d2354 8
a2361 11
create or replace package body acs
as
  function add_user (
    user_id     in users.user_id%TYPE default null,
    object_type     in acs_objects.object_type%TYPE
               default 'user',
    creation_date   in acs_objects.creation_date%TYPE
               default sysdate,
    creation_user   in acs_objects.creation_user%TYPE
               default null,
    creation_ip     in acs_objects.creation_ip%TYPE default null,
d2363 2
a2364 2
  ) return users.user_id%TYPE
  is
d2367 1
a2367 1
  begin
d2369 4
a2372 5
                creation_user, creation_ip, email,
    ...
    return v_user_id;
  end;
end acs;
d2490 1
a2490 1
' language 'plpgsql';
d2500 4
a2503 4
    temp_str varchar;
    beg integer;
    length integer;
    ss_length integer;
a2520 1

d2547 1
a2547 1
    occur_number integer NOT NULL DEFAULT 0;
@


2.42
log
@Correct some errors in plpgsql examples, as reported by Junichi Kobayasi.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.41 2001/10/09 04:15:38 tgl Exp $
d231 2
a232 2
drop function testfunc(integer);
create function testfunc(integer) returns integer as '
d506 1
a506 1
create function cs_refresh_one_mv(integer) returns integer as '
d588 1
a588 1
CREATE FUNCTION logfunc1 (text) RETURNS timestamp AS '
d601 1
a601 1
CREATE FUNCTION logfunc2 (text) RETURNS timestamp AS '
d796 1
a796 1
                  RETURNS varchar AS '''' 
d1157 1
a1157 1
FOR i IN REVERSE 1..10 LOOP
d1292 1
a1292 1
create function cs_refresh_mviews () returns integer as '
d1645 1
a1645 1
CREATE FUNCTION add_one (integer) RETURNS integer AS '
d1662 1
a1662 1
CREATE FUNCTION concat_text (text, text) RETURNS text AS '
d1685 1
a1685 1
CREATE FUNCTION c_overpaid (EMP, integer) RETURNS boolean AS '
d2002 3
a2004 3
DROP FUNCTION cs_fmt_browser_version(varchar, varchar);
CREATE FUNCTION cs_fmt_browser_version(varchar, varchar)
RETURNS varchar AS '
d2061 1
a2061 1
CREATE FUNCTION cs_update_referrer_type_proc() RETURNS integer AS '
d2066 2
a2067 2
    a_output := ''CREATE FUNCTION cs_find_referrer_type(varchar,varchar,varchar) 
                  RETURNS varchar AS '''' 
d2155 2
a2156 2
drop function cs_parse_url_host(varchar); 
create function cs_parse_url_host(varchar) returns varchar as ' 
d2285 4
a2288 4
drop function cs_create_job(integer);
create function cs_create_job(integer) returns integer as ' declare
    v_job_id alias for $1;
    a_running_job_count integer;
d2291 11
a2301 3
begin
    lock table cs_jobs in exclusive mode;
    select count(*) into a_running_job_count from cs_jobs where end_stamp is null;
d2303 2
a2304 7
    if a_running_job_count > 0 then
        -- commit; -- free lock
        raise exception ''Unable to create a new job: a job is currently running.'';
    end if;

    delete from cs_active_job;
    insert into cs_active_job(job_id) values(v_job_id);
d2306 3
a2308 1
    SELECT count(*) into a_num FROM cs_jobs WHERE job_id=v_job_id;
d2311 2
a2312 2
        insert into cs_jobs(job_id, start_stamp) values(v_job_id, sysdate());
        return 1;
d2314 1
a2314 1
        raise NOTICE ''Job already running.'';<co id="co.plpgsql-porting-raise">
d2317 3
a2319 3
    return 0;
end;
' language 'plpgsql';
d2390 2
a2391 2
CREATE FUNCTION acs__add_user(integer,integer,varchar,datetime,integer,integer,...)
RETURNS integer AS '
d2405 1
a2405 1
    return v_user_id;
d2449 1
a2449 1
CREATE FUNCTION foo(...) RETURNS integer AS '
d2487 1
a2487 1
CREATE FUNCTION instr(varchar,varchar) RETURNS integer AS '
d2497 2
a2498 2
DROP FUNCTION instr(varchar,varchar,integer);
CREATE FUNCTION instr(varchar,varchar,integer) RETURNS integer AS '
d2544 2
a2545 2
DROP FUNCTION instr(varchar,varchar,integer,integer);
CREATE FUNCTION instr(varchar,varchar,integer,integer) RETURNS integer AS '
d2553 5
a2557 5
    temp_str varchar;
    beg integer;
    i integer;
    length integer;
    ss_length integer;
d2603 1
a2603 1
' language 'plpgsql';
@


2.41
log
@Change plpgsql to depend on main parser's type-declaration grammar,
rather than having its own somewhat half-baked notion of what a type
declaration looks like.  This is necessary now to ensure that plpgsql
will think a 'timestamp' variable has the same semantics as 'timestamp'
does in the main SQL grammar; and it should avoid divergences in future.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.40 2001/09/18 12:08:26 petere Exp $
d522 2
a523 2
        TRUNCATE TABLE table_data.mv_name;
        INSERT INTO table_data.mv_name || '' '' || table_data.mv_query;
d1154 1
a1154 1
    RAISE NOTICE 'i is %',i;
d1307 3
a1309 3
         PERFORM cs_log(''Refreshing materialized view '' || mview.mv_name || ''...'');
         TRUNCATE TABLE mview.mv_name;
         INSERT INTO mview.mv_name || '' '' || mview.mv_query;
@


2.40
log
@Generate index.html as the root file name of the documentation set,
rather than making index.html a symlink to the autogenerated name.
Fixes fatal problems with tar programs that don't handle symlinks
very well (MacOS X).

(The names user.html, admin.html, etc. are still available as make
targets, but they aren't packaged anymore.)

Use the manifest file that the stylesheets generate as the file list
for packaging.  Put graphics in the right place while building, not
while packaging, so you can actually look at them after building.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.39 2001/09/13 15:55:23 petere Exp $
d232 1
a232 1
create function testfunc(integer) return integer as '
d363 1
a363 1
quantity NUMBER(5);
d440 1
a440 1
      data type or structure of another database item (e.g: a
d515 1
a515 1
           RAISE EXCEPTION ''View '' || key || '' not found'';
d578 1
a578 2
     saved once.  The only exception to this rule is an EXECUTE statement
     if parsing of a query is needed each time it is encountered.
@


2.39
log
@Replace ASCII-quotes with proper markup.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.38 2001/09/10 21:58:47 petere Exp $
d1718 2
a1719 1

d1726 1
@


2.38
log
@Markup and spell-check run over Programmer's Guide (rather incomplete still).
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.37 2001/09/10 06:35:34 ishii Exp $
d742 1
a742 1
    table available at the "Porting from Oracle PL/SQL" chapter
d964 1
a964 1
        When you use the "ELSE IF" statement, you are actually
d1224 1
a1224 1
     you can use the "." (dot) notation to access fields in that
@


2.37
log
@Fix typo.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.36 2001/09/10 06:30:43 ishii Exp $
d6 1
a6 1
  <title>PL/pgSQL - <acronym>SQL</acronym> Procedural Language</title>
d13 1
a13 1
  PL/pgSQL is a loadable procedural language for the
d27 1
a27 1
    The design goals of PL/pgSQL were to create a loadable procedural
d63 1
a63 1
    The PL/pgSQL call handler parses the function's source text and
d72 1
a72 1
    the function, the PL/pgSQL bytecode interpreter creates a
d77 1
a77 1
    statement is processed in the PL/pgSQL function. Thus, a function with
d105 2
a106 2
    Because PL/pgSQL saves execution plans in this way, queries that appear
    directly in a PL/pgSQL function must refer to the same tables and fields
d109 1
a109 1
    this restriction, you can construct dynamic queries using the PL/pgSQL
d116 1
a116 1
    functions can also be done with PL/pgSQL. It is possible to
d165 1
a165 1
     With PL/pgSQL you can group a block of computation and a
d171 1
a171 1
     considerable performance increase by using PL/pgSQL. 
d179 1
a179 1
     PL/pgSQL adds the power of a procedural language to the
d181 1
a181 1
     PL/pgSQL you can use all the datatypes, columns, operators
d190 1
a190 1
     Because PL/pgSQL functions run inside PostgreSQL, these
d198 1
a198 1
   <title>Developing in PL/pgSQL</title>
d201 1
a201 1
    Developing in PL/pgSQL is pretty straight forward, especially
d203 2
a204 2
    such as Oracle's PL/SQL. Two good ways of developing in
    PL/pgSQL are:
d215 1
a215 1
       Using PostgreSQL's GUI Tool: pgaccess
d222 1
a222 1
    One good way to develop in PL/pgSQL is to simply use the text
d226 1
a226 1
    a PL/pgSQL novice or in debugging stage), it is a good idea to 
d243 1
a243 1
    file (filename.sql) into a database named "dbname", use the command:
d250 2
a251 2
    Another good way to develop in PL/pgSQL is using
    <productname>PostgreSQL</>'s GUI tool: pgaccess. It does some
d266 1
a266 1
    <title>Structure of PL/pgSQL</title>
d269 1
a269 1
     PL/pgSQL is a <emphasis>block structured</emphasis> language. All
d319 2
a320 2
     grouping statements in PL/pgSQL with the database commands for
     transaction control.  PL/pgSQL's BEGIN/END are only for grouping;
d332 1
a332 1
     There are two types of comments in PL/pgSQL. A double dash <literal>--</literal>
d353 1
a353 1
     PL/pgSQL variables can have any SQL datatype, such as
d440 1
a440 1
      datatype or structure of another database item (e.g: a
d451 1
a451 1
         <type>%TYPE</type> provides the datatype of a
d457 1
a457 1
         the same datatype as users.user_id you write:
d465 2
a466 2
         the datatype of the structure you are referencing,
         and most important, if the datatype of the
d477 1
a477 1
        <replaceable>table</replaceable>%ROWTYPE
d481 1
a481 1
	 <type>%ROWTYPE</type> provides the composite datatype corresponding
d563 2
a564 2
     All expressions used in PL/pgSQL statements are processed using
     the backend's executor. Expressions that appear to contain
d568 1
a568 1
     it is impossible for the PL/pgSQL parser
d577 1
a577 1
     expressions used in a PL/pgSQL function are only prepared and
d618 1
a618 1
     <type>timestamp</type> because the target field of logtable
d632 2
a633 2
     to the local variable curtime, the PL/pgSQL interpreter casts this
     string to the timestamp type by calling the
d640 1
a640 1
     parser got implemented after PL/pgSQL was nearly done.
d644 1
a644 1
     variable in the above manner is currently the only way in PL/pgSQL to get
d662 1
a662 1
    Anything not understood by the PL/pgSQL parser as specified below
d678 2
a679 2
     (as for <type>char(20)</type>), the result value will be implicitly casted by
     the PL/pgSQL bytecode interpreter using the result types output- and
d697 1
a697 1
     in a PL/pgSQL internal SELECT). 
d725 2
a726 2
     your PL/pgSQL functions. Or you have functions that will
     generate other functions. PL/pgSQL provides the EXECUTE
d741 1
a741 1
    escaping of single quotes in PL/pgSQL. Please refer to the
d747 1
a747 1
     Unlike all other queries in PL/pgSQL, a
d837 1
a837 1
     of the right datatype to receive it).  The currently available
d876 1
a876 1
    important) part of PL/SQL. With PL/pgSQL's control structures,
d1025 2
a1026 2
     control the flow of execution of your PL/pgSQL program
     iteratively.
d1211 1
a1211 1
     table from a SELECT result inside a PL/pgSQL function, use the
d1347 1
a1347 1
    <productname>Postgres</productname> elog mechanism.
d1410 1
a1410 1
     Thus, the only thing PL/pgSQL currently does when it encounters
d1426 1
a1426 1
   PL/pgSQL can be used to define trigger procedures. They are created
d1562 1
a1562 1
    <title>A PL/pgSQL Trigger Procedure Example</title>
d1614 1
a1614 1
    write PL/pgSQL
d1616 1
a1616 1
    might look at the regression test for PL/pgSQL.
d1620 1
a1620 1
    One painful detail in writing functions in PL/pgSQL is the handling
d1636 1
a1636 1
    <title>A Simple PL/pgSQL Function to Increment an Integer</title>
d1639 1
a1639 1
     The following two PL/pgSQL functions are identical to their
d1655 1
a1655 1
    <title>A Simple PL/pgSQL Function to Concatenate Text</title>
d1672 1
a1672 1
    <title>A PL/pgSQL Function on Composite Type</title>
d1675 1
a1675 1
     In this example, we take EMP (a table) and an
d1677 2
a1678 2
     a <type>boolean</type>. If the "salary" field of the EMP table is
     <literal>NULL</literal>, we return "f". Otherwise we compare with
d1681 1
a1681 1
     or f). This is the PL/pgSQL equivalent to the example from the C
d1746 1
a1746 1
   PostgreSQL's PL/pgSQL languages in the hopes of helping developers
d1756 1
a1756 1
   PL/pgSQL is similar to PL/SQL in many aspects. It is a block
d1759 1
a1759 1
   counterpart, but PL/pgSQL allows for a great deal of functionality
d1940 1
a1940 1
     Let's go through this function and see the differences to PL/pgSQL:
d2103 1
a2103 1
     procedure because in PL/pgSQL functions only one value can be returned
d2206 1
a2206 1
    through the use of INOUT or OUT parameters.
d2256 1
a2256 1
       If you do a <literal>LOCK TABLE</literal> in PL/pgSQL, the lock
d2263 1
a2263 1
       You also cannot have transactions in PL/pgSQL procedures. The
d2281 1
a2281 1
    So let's see one of the ways we could port this procedure to PL/pgSQL:
d2319 1
a2319 1
       Notice how you can raise notices (or errors) in PL/pgSQL.
d2426 1
a2426 1
    <title>Optimizing PL/pgSQL Functions</title>
@


2.36
log
@Example program lacks RETURN
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.35 2001/05/28 19:33:24 tgl Exp $
d2003 1
a2003 1
RETRUNS varchar AS '
@


2.35
log
@Cause plpgsql's PERFORM to behave according to its documentation,
which says that PERFORM will execute any SELECT query and discard the
result.  The former implementation would in fact raise an error if the
result contained more than one row or more than one column.

Also, change plpgsql's error-logging mechanism to emit the additional
messages about error location at NOTICE rather than DEBUG level.  This
allows them to be seen by the client without having to dig into the
postmaster log file (which may be nonexistent or inaccessible by the
client).
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.34 2001/05/28 14:58:58 petere Exp $
d310 2
@


2.34
log
@markup fix
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.33 2001/05/22 13:52:27 momjian Exp $
a1404 3
     And even if, at this point the information, that the transaction
     is aborted, is already sent to the client application, so resuming
     operation does not make any sense.
d1410 1
a1410 1
     procedure is to write some additional DEBUG level log messages
@


2.33
log
@ELSEIF PL/PgSQL doc patch.

Klaus Reger
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.32 2001/05/17 21:50:16 petere Exp $
a996 1
       </para>
@


2.32
log
@Change "indices" to "indexes", per OED.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.31 2001/05/12 22:51:35 petere Exp $
d883 5
a887 6
     <function>IF</function> statements let you take action
     according to certain conditions. PL/pgSQL has three forms of
     IF: IF-THEN, IF-THEN-ELSE, IF-THEN-ELSE IF. NOTE: All
     PL/pgSQL IF statements need a corresponding <function>END
     IF</function> statement. In ELSE-IF statements you need two:
     one for the first IF and one for the second (ELSE IF).
d981 35
@


2.31
log
@Add index.  Only some parts of the manual set have index entries so far...
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.30 2001/05/11 06:10:44 tgl Exp $
d118 1
a118 1
    them to define operators or use them in functional indices.
@


2.30
log
@Improve discussion of %TYPE and %ROWTYPE.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.29 2001/05/08 02:53:24 tgl Exp $
d8 4
d1696 8
@


2.29
log
@Further cleanup of RAISE discussion; in particular, remove example
that doesn't actually work.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.27 2001/05/08 00:30:41 momjian Exp $
d399 1
a399 1
     <title>Variables Passed to Functions</title>
d402 1
a402 1
      Variables passed to functions are named with the identifiers
d404 2
a405 1
      etc. (maximum is 16). Some examples:
d441 1
a441 1
        %TYPE
d451 1
a451 1
         the same datatype as users you do:
d453 1
a453 1
user_id users.user_id%TYPE;
d471 1
a471 1
        <replaceable>name</replaceable> <replaceable>table</replaceable>%ROWTYPE;
d475 3
a477 2
         Declares a row with the structure of the given
	 table. <replaceable>table</replaceable> must be an existing
d481 2
a482 2
	 corresponding identifier $n will be a rowtype, but it must be
	 aliased using the ALIAS command described above.
d486 3
a488 3
         Only the user attributes of a table row are accessible in the
	 row, no OID or other system attributes (because the row could
	 be from a view).  The fields of the rowtype inherit the
d495 1
a495 1
  user_id users%TYPE;
@


2.28
log
@Fix raise mention that %% output as %.
@
text
@d1312 3
a1314 5
    Inside the format, <literal>%</literal> is replaced by the next argument's
    external representation. Double <literal>%</literal>'s are output as <literal>%</literal>.
    Possible levels are DEBUG (silently suppressed in production
    running databases), NOTICE (written into the database log and forwarded to
    the client application) and EXCEPTION (written into the database log and
d1316 6
d1324 6
a1331 1
RAISE NOTICE ''Id number '' || key || '' not found!'';
d1334 1
a1334 1
    In this last example, v_job_id will replace the % in the
d1342 1
a1342 1
    This will abort the transaction and write to the database log.
@


2.27
log
@Update RAISE manual concerning % format symbols.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.26 2001/05/08 00:09:22 momjian Exp $
d1313 2
a1314 2
    external representation. Double %'s are left unchanged for internal
    reasons.  Possible levels are DEBUG (silently suppressed in production
@


2.26
log
@Update RAISE mention in manual to take string/variable not format/identifier.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.25 2001/03/23 22:07:50 tgl Exp $
d1309 1
a1309 1
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">string</replaceable>' <optional>, <replaceable class="parameter">variable</replaceable> <optional>...</optional></optional>;
d1312 6
a1317 5
    Inside the format, <literal>%</literal> is used as a placeholder for the
    subsequent comma-separated identifiers. Possible levels are
    DEBUG (silently suppressed in production running databases), NOTICE 
    (written into the database log and forwarded to the client application)
    and EXCEPTION (written into the database log and aborting the transaction).
@


2.25
log
@Doc update from Roberto Mello: improved versions of instr() examples.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.24 2001/03/17 18:08:14 petere Exp $
d1309 1
a1309 1
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">identifier</replaceable> <optional>...</optional></optional>;
@


2.24
log
@Repair.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.23 2001/03/17 01:53:22 thomas Exp $
a2409 7
    <para>
     The third function (that takes 4 parameters) is implemented in
     PL/Tcl but I plan on porting it to PL/pgSQL so in case we want to
     include it in OpenACS we don't need to require PL/Tcl. Plus
     PL/pgSQL should be more efficient.
    </para>

d2420 1
d2424 2
a2425 2
DROP FUNCTION instr(varchar, varchar);
CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS '
d2429 1
a2429 1
    pos:= instr($1, $2, 1);
d2432 45
a2476 1
' LANGUAGE 'plpgsql';
d2478 6
a2483 2
DROP FUNCTION instr(varchar, varchar, integer);
CREATE FUNCTION instr(varchar, varchar, integer) RETURNS integer AS '
d2488 1
d2490 1
a2490 1
    ending integer;
d2493 1
d2495 1
a2495 1
    temp_int integer;
d2498 5
a2502 1
        -- Get substring from 1 to beg_index
d2504 8
a2511 2
        temp_str := substring(string FROM beg_index); 
        pos := position(string_to_search IN temp_str);
d2516 1
a2516 1
            RETURN pos + beg_index - 1;
a2517 1

d2519 1
d2521 1
d2523 3
a2525 11
        IF beg_index = -1 THEN
            ending := length;
            beg := ending;
            temp_int := 1;
        ELSE
            ending := length - abs(beg_index);
            beg := ending;
            temp_int := ending - beg;
        END IF;

        WHILE pos = 0 AND beg &lt;&gt; 1 LOOP
d2527 2
a2528 2
            temp_str := substring(string FROM beg FOR temp_int);
            pos := position(string_to_search IN temp_str);
d2530 4
a2533 1
            -- Keep moving left
a2535 1
            temp_int := (ending - beg) + 1;
a2536 1
    END IF;
a2537 1
    IF pos = 0 THEN
a2538 2
    ELSE
        RETURN beg + 1;
d2541 1
a2541 52
' LANGUAGE 'plpgsql';

--
-- The next one (where all four params are passed) is in PL/Tcl
-- because I had no more patience to do it in PL/pgSQL.
-- It'd probably be faster in PL/pgSQL (that being the reason why
-- I implemented the first two functions in PL/pgSQL) so someday I'll do it.
--

DROP FUNCTION instr(varchar, varchar, integer, integer);
CREATE FUNCTION instr(varchar, varchar, integer, integer) RETURNS integer AS '
    set string1 $1
    set string2 $2
    set n $3
    set m $4

    if { $n > 0 } {
        set pos [string first $string2 $string1 [expr $n -1]]
        if { $pos < 0 } {
            return 0
        } else {
            for { set i 1 } { $i < $m } { incr i } {
                set pos [string first $string2 $string1 [expr $pos + 1]]
                if { $pos < 0 } {
                    return 0
                }
            }
        }
    }

    if { $n < 0 } {
        set pos [string last $string2 $string1 [expr [string length $string1] + $n]]

        if { $pos < 0 } {
            return 0
        } else {
            for { set i 1 } { $i < $m } { incr i } {
                # n is negative so we add
                set pos [string last $string2 $string1 [expr $pos - 1]]
                if { $pos < 0 } {
                    return 0
                }
            }
        }
    }

    if { $pos < 0 } {
        return 0
    } else {
        return [expr $pos + 1]
    }
' LANGUAGE 'pltcl';
@


2.23
log
@New updates from Roberto Mello sent privately today due to email troubles.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.22 2001/03/09 19:09:00 petere Exp $
d6 1
a6 1
  <title>PL/pgSQL - <acronym>SQL<acronym> Procedural Language</title>
d15 2
a16 2
  documentation was re-organized and in part written 
  by Roberto Mello (rmello@@fslc.usu.edu).
d83 1
a83 1
 <programlisting>
d90 8
a97 6
' language 'plpgsql';
 </programlisting>
    If you CREATE the above function, it will reference the ID for
    my_function() in its bytecode. Later, if you DROP and re-CREATE 
  my_function(), populate() will not be able to find my_function()
    anymore. You'll have to re-CREATE populate().
d99 1
d122 1
a122 1
      <xref linkend="plpgsql-advantages-performance">Better performance</xref>
d125 1
d128 1
a128 1
      <xref linkend="plpgsql-advantages-sqlsupport">SQL Support</xref>
d131 1
d134 1
a134 1
      <xref linkend="plpgsql-advantages-portability">Portability</xref>
d141 1
d149 1
d159 1
d170 1
d173 1
d181 1
d184 1
d201 1
d208 1
d216 1
d226 1
a226 3
   </para>
   <para>
 <programlisting>
d232 2
a233 1
 </programlisting>
d235 1
d240 3
d244 1
a245 4
 <programlisting>
psql -f filename.sql dbname
 </programlisting>

d252 1
a252 1
  </sect1>
d265 3
a267 4
   PL/pgSQL is a <emphasis>block structured</emphasis>, case
   insensitive language. All keywords and identifiers can be 
   used in mixed upper- and lower-case. A block is defined as:
  </para>
d269 1
a269 1
 <synopsis>
d276 2
a277 1
 </synopsis>
d284 1
d286 4
a289 5
   The variables declared in the declarations section preceding a
   block are initialized to their default values every time the
   block is entered, not only once per function call. For example:
    </para>
 <programlisting>
d307 3
a309 2
' language 'plpgsql';
 </programlisting>
d344 3
a346 2
  </para>
  <para>
d352 2
a353 1
  <para>
d355 1
a355 2
  </para>
 <programlisting>
d359 2
a360 1
 </programlisting>
d367 3
d371 1
a371 3
 <synopsis>
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>value</replaceable> </optional>;
 </synopsis>
d379 1
d387 1
d390 1
a390 2
     </para>
 <programlisting>
d394 2
a395 1
     </programlisting>
d405 1
a405 2
     </para>
 <programlisting>
d412 1
a412 1
' language 'plpgsql';
d422 3
a424 2
' language 'plpgsql';
     </programlisting>
d451 3
d455 1
a455 3
 <programlisting>
user_id users.user_id%TYPE;
 </programlisting>
d474 7
a480 6
 Declares a row with the structure of the given table. <replaceable>table</replaceable> must be
 an existing table or view name of the database. The fields of the row
 are accessed in the dot notation. Parameters to a function can
 be composite types (complete table rows). In that case, the
 corresponding identifier $n will be a rowtype, but it
 must be aliased using the ALIAS command described above.
d484 5
a488 5
  Only the user
 attributes of a table row are accessible in the row, no OID or other
 system attributes (because the row could be from a view).
 The fields of the rowtype inherit the table's field sizes 
 or precision for <type>char()</type> etc. data types.
d490 1
a490 1
 <programlisting>
d519 2
a520 2
' language 'plpgsql';
        </programlisting>
d530 1
d536 1
d539 1
a539 2
     </para>
 <programlisting>
d544 2
a545 1
     </programlisting>
d563 1
a563 1
 <synopsis>
d565 1
a565 1
 </synopsis>
d573 1
d580 1
a580 1
 <programlisting>
d589 1
a589 1
 </programlisting>
d593 1
a593 1
 <programlisting>
d604 1
a604 1
 </programlisting>
d617 1
d629 1
d639 1
d664 1
a664 1
 <synopsis>
d666 1
a666 1
 </synopsis>
d676 1
a676 1
 <programlisting>
d679 1
a679 1
 </programlisting>
d691 1
d696 1
a696 2
    </para>
 <synopsis>
d698 2
a699 3
 </synopsis>
    <para>
     executes a <literal>SELECT <replaceable>query</replaceable></literal> over the
d703 1
a703 1
 <programlisting>
d709 1
a709 1
 </programlisting>
d721 1
d723 1
a723 1
 <synopsis>
d725 6
a730 5
 </synopsis>
         where <replaceable>query-string</replaceable> is a string of
         type <type>text</type> containing the <replaceable>query</replaceable> to be
         executed.
       </para>
d738 10
a747 10
       <para>
        Unlike all other queries in PL/pgSQL, a
        <replaceable>query</replaceable> run by an EXECUTE statement
        is not prepared and saved just once during the life of the
        server.  Instead, the <replaceable>query</replaceable> is
        prepared each time the statement is run. The
        <replaceable>query-string</replaceable> can be dynamically created
        within the procedure to perform actions on variable tables and
        fields.
       </para>
d749 6
a754 6
       <para>
        The results from SELECT queries are discarded by EXECUTE, and
        SELECT INTO is not currently supported within EXECUTE.  So, the
        only way to extract a result from a dynamically-created SELECT
        is to use the FOR ... EXECUTE form described later.
       </para>
d756 3
a758 3
       <para>
        An example:
 <synopsis>
d764 1
a764 1
 </synopsis>
d766 1
d778 2
a779 1
       </para>
d781 2
a782 2
    Here is a much larger example of a dynamic query and EXECUTE:
 <programlisting>
d813 2
a814 2
' language 'plpgsql';
 </programlisting>
d818 5
a822 4
     <sect3 id="plpgsql-statements-diagnostics">
      <title>Obtaining other results status</title>
       <para>
 <synopsis>
d824 14
a837 12
 </synopsis>
 This command allows retrieval of system status indicators.  Each
 <replaceable>item</replaceable> is a keyword identifying a state
 value to be assigned to the specified variable (which should be of
 the right datatype to receive it).  The currently available status
 items are <varname>ROW_COUNT</>, the number of rows processed by
 the last <acronym>SQL</acronym> query sent down to the <acronym>SQL</acronym> engine; and
 <varname>RESULT_OID</>, the Oid of the last row inserted by the
 most recent <acronym>SQL</acronym> query.  Note that <varname>RESULT_OID</> is only
 useful after an INSERT query.
       </para>
     </sect3>
d843 1
a843 1
 <synopsis>
d845 13
a857 11
 </synopsis>
 The function terminates and the value of <replaceable>expression</replaceable>
 will be returned to the upper executor. The return value of a function
 cannot be undefined. If control reaches the end of the top-level block
 of the function without hitting a RETURN statement, a runtime error
 will occur.
       </para>
       <para>
 The expressions result will be automatically casted into the
 function's return type as described for assignments.
       </para>
d873 1
a873 1
   <sect3 id="plpgsql-description-control-structures-conditionals">
d890 1
d897 1
a897 1
 <programlisting>
d901 1
a901 1
 </programlisting>
d910 1
d916 1
a916 1
 <programlisting>
d931 1
a931 1
        </programlisting>
d933 1
d937 1
a937 1
 <programlisting>
d945 1
a945 1
        </programlisting>
d954 1
d962 1
d965 1
a965 1
 <programlisting>
d972 2
a973 2
 </programlisting>
              </para>
d987 1
d993 1
d996 1
a996 1
 <synopsis>
d1001 1
a1001 1
 </synopsis>
d1014 1
d1017 1
a1017 1
 <synopsis>
d1019 1
a1019 1
 </synopsis>
d1029 1
d1032 1
a1032 1
 <programlisting>
d1051 1
a1051 1
        </programlisting>
d1060 1
d1066 1
a1066 3
       </para>
       <para>
 <synopsis>
d1071 1
a1071 2
 </synopsis>
       <para>
d1073 1
a1073 2
       </para>
 <programlisting>
d1081 1
a1081 1
 </programlisting>
d1090 1
d1093 1
a1093 1
 <synopsis>
d1098 1
a1098 1
 </synopsis>
d1105 1
d1107 4
a1110 3
        Some examples of FOR loops (see <xref linkend="plpgsql-description-records"></xref> for
        iterating over records in FOR loops):
 <programlisting>
d1120 1
a1120 1
 </programlisting>
d1132 1
d1141 1
d1148 1
d1150 1
a1150 1
 <synopsis>
d1152 1
a1152 1
 </synopsis>
d1155 1
d1158 1
d1162 1
a1162 1
 <synopsis>
d1164 8
a1171 7
 </synopsis>
     <replaceable>target</replaceable> can be a record, a row variable or a
     comma separated list of variables and record-/row-fields. Note that
          this is quite different from Postgres' normal interpretation of
          SELECT INTO, which is that the INTO target is a newly created table.
          (If you want to create a table from a SELECT result inside a PL/pgSQL
          function, use the equivalent syntax <command>CREATE TABLE AS SELECT</command>.)
d1173 1
d1180 1
d1185 1
a1185 3
    </para>
    <para>
 <programlisting>
d1193 1
a1193 1
     </programlisting>
d1195 1
d1197 3
a1199 2
     There is a special variable named FOUND of type <type>boolean</type> that can be used
     immediately after a SELECT INTO to check if an assignment had success.
d1201 1
a1201 1
     <programlisting>
d1206 1
a1206 1
 </programlisting>
d1213 1
d1215 1
a1215 1
 <programlisting>
d1228 1
a1228 1
 </programlisting>
d1231 1
d1239 1
a1239 3
    </para>
    <para>
 <synopsis>
d1244 1
a1244 1
 </synopsis>
d1249 1
d1251 1
a1251 1
 <programlisting>
d1276 1
a1276 1
 </programlisting>
d1278 2
a1279 2
          If the loop is terminated with an EXIT statement, 
     the last assigned row is still accessible after the loop.
d1281 5
a1285 6
        <para>
         The FOR-IN EXECUTE statement is another way to iterate over
         records:
        </para>
        <para>
 <synopsis>
d1290 8
a1297 8
 </synopsis>
         This is like the previous form, except that the source SELECT
         statement is specified as a string expression, which is evaluated
         and re-planned on each entry to the FOR loop.  This allows the
         programmer to choose the speed of a pre-planned query or the
         flexibility of a dynamic query, just as with a plain EXECUTE
         statement.
        </para>
d1302 1
a1302 1
      <title>Aborting and Messages</title>
d1308 1
a1308 1
 <synopsis>
d1310 2
a1311 1
 </synopsis>
d1318 1
d1320 1
a1320 1
 <programlisting>
d1323 1
a1323 1
    </programlisting>
d1327 1
d1329 1
a1329 1
 <programlisting>
d1331 1
a1331 1
    </programlisting>
d1348 1
d1360 1
d1375 7
a1381 1
    <title>Trigger Procedures</title>
d1383 8
a1390 15
  <sect2 id="plpgsql-trigger-description">
   <title>Description</title>
   <para>
    PL/pgSQL can be used to define trigger procedures. They are created
    with the usual <command>CREATE FUNCTION</command> command as a function with no
    arguments and a return type of <type>OPAQUE</type>.
   </para>
   <para>
    There are some <productname>Postgres</productname> specific details
    in functions used as trigger procedures.
   </para>
   <para>
    First they have some special variables created automatically in the 
    top-level blocks declaration section. They are
   </para>
d1499 1
a1511 1
  </sect2>
d1522 1
a1522 1
 <programlisting>
d1527 2
a1528 1
    last_user text);
d1554 1
a1554 1
 </programlisting>
d1557 1
a1557 1
   </sect1>
d1581 1
d1584 1
a1584 2
    quotes in different situations, please see <xref linkend="plpgsql-quote"></xref> in
    <xref linkend="plpgsql-porting">Porting From Oracle PL/SQL</xref>.
d1597 1
a1597 1
 <programlisting>
d1603 1
a1603 1
 </programlisting>
d1614 1
a1614 1
 <programlisting>
d1620 1
a1620 1
 </programlisting>
d1627 8
a1634 7
  In this example, we take EMP (a table) and an <type>integer</type> as
  arguments to our function, which returns a <type>boolean</type>. If the
  "salary" field of the EMP table is <literal>NULL</literal>, we return
  "f". Otherwise we compare with that field with the <type>integer</type>
  passed to the function and return the <type>boolean</type> result of the
  comparison (t or f). This is the PL/pgSQL equivalent to the 
    example from the C functions.
d1636 2
a1637 2
    <para>
 <programlisting>
d1649 2
a1650 3
 </programlisting>
    </para>
 </example>
d1743 1
a1743 1
       quotes. See <xref linkend="plpgsql-quote"></xref>.
d1757 1
a1757 1
     <xref linkend="plpgsql-porting-nastyquote">this example</xref>.  
d1765 1
a1765 1
     <xref linkend="plpgsql-quoting-table"></xref> gives the scoop.  (You'll
d1838 1
a1838 1
         (like in <xref linkend="plpgsql-porting-nastyquote"></xref>).
d1927 1
a1927 1
        linkend="plpgsql-quote">this example</xref>).
d2048 1
a2048 1
     (see <xref linkend="plpgsql-porting-procedures"></xref>).  In
d2098 28
a2125 28
 drop function cs_parse_url_host(varchar); 
 create function cs_parse_url_host(varchar) returns varchar as ' 
 declare 
     v_url ALIAS FOR $1; 
     v_host varchar; 
     v_path varchar; 
     a_pos1 integer; 
     a_pos2 integer; 
     a_pos3 integer; 
 begin 
     v_host := NULL; 
     a_pos1 := instr(v_url,''//''); 
   
     if a_pos1 = 0 then 
         return '''';  -- Return a blank
     end if; 
 
     a_pos2 := instr(v_url,''/'',a_pos1 + 2); 
     if a_pos2 = 0 then 
         v_host := substr(v_url, a_pos1 + 2); 
         v_path := ''/''; 
         return v_host; 
     end if; 
 
     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2 ); 
     return v_host; 
 end; 
 ' language 'plpgsql';
d2137 1
a2137 1
     linkend="plpgsql-porting-appendix"></xref> for the code.
d2160 1
a2160 1
    pragma autonomous_transaction;<co id="co.plpgsql-porting-pragma"></co>
d2162 1
a2162 1
    lock table cs_jobs in exclusive mode;<co id="co.plpgsql-porting-locktable"></co>
d2168 1
a2168 1
        commit; -- free lock<co id="co.plpgsql-porting-commit"></co>
d2177 1
a2177 1
        exception when dup_val_on_index then null; -- don't worry if it already exists<co id="co.plpgsql-porting-exception"></co>
d2252 1
a2252 1
        raise NOTICE ''Job already running.'';<co id="co.plpgsql-porting-raise"></co>
d2363 1
a2363 1
     linkend="plpgsql-statements"></xref>.  Constructs of the type
d2548 1
a2548 2
 
    </programlisting>
@


2.22
log
@Integrate "Porting from Oracle PL/SQL" HOWTO from Roberto Mello.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.21 2001/02/21 17:50:38 petere Exp $
d5 2
a6 2
 <chapter id="plpgsql">
  <title>PL/pgSQL - <acronym>SQL</acronym> Procedural Language</title>
d8 10
a17 8
  <para>
   PL/pgSQL is a loadable procedural language for the
   <productname>Postgres</productname> database system.
  </para>

  <para>
   This package was originally written by Jan Wieck.
  </para>
d69 4
a72 2
    prepared execution plan using the <acronym>SPI</acronym> manager's <function>SPI_prepare()</function> and
    <function>SPI_saveplan()</function> functions. This is done the first time the individual
d79 18
d113 124
d250 4
a253 5
     The PL/pgSQL language is case insensitive. All keywords and
     identifiers can be used in mixed upper- and lower-case.
    </para>
    <para>
     PL/pgSQL is a block oriented language. A block is defined as
d255 1
a255 1
<synopsis>
d262 1
a262 2
</synopsis>
    </para>
d267 6
a272 4
     block of statements. The variables
     declared in the declarations section preceding a block are
     initialized to their default values every time the block is entered,
     not only once per function call.
d274 20
d319 1
a319 2
   <!-- **** PL/pgSQL declarations **** -->

d321 1
a321 1
    <title>Declarations</title>
d325 9
a333 5
     sub-blocks must be declared in the declarations section of a block,
     except for the loop variable of a FOR-loop iterating over a range
     of integer values. Parameters given to a PL/pgSQL function are
     automatically declared with the usual identifiers <literal>$1</literal>, <literal>$2</literal>, etc.
     The declarations have the following syntax:
d335 58
a392 1
    <variablelist>
a393 24
     <varlistentry>
      <term>
<replaceable>name</replaceable> <optional> CONSTANT </optional>
<replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> DEFAULT | :=
	<replaceable>value</replaceable> </optional>;
      </term>
      <listitem>
       <para>
	Declares a variable of the specified base type. If the variable
	is declared as CONSTANT, the value cannot be changed. If NOT NULL
	is specified, an assignment of a NULL value results in a runtime
	error. Since the default value of all variables is the
	<acronym>SQL</acronym> NULL value, all variables declared as NOT NULL
	must also have a default value specified.
       </para>
       <para>
	The default value is evaluated every time the block is entered. So
	assigning <literal>'now'</literal> to a variable of type
	<type>timestamp</type> causes the variable to have the
	time of the actual function call, not when the function was
	precompiled into its bytecode.
       </para>
      </listitem>
     </varlistentry>
d395 10
a404 22
     <varlistentry>
      <term>
<replaceable>name</replaceable> <replaceable>table</replaceable>%ROWTYPE;
      </term>
      <listitem>
       <para>
	Declares a row with the structure of the given table. <replaceable>table</replaceable> must be
	an existing table or view name of the database. The fields of the row
	are accessed in the dot notation. Parameters to a function can
	be composite types (complete table rows). In that case, the
	corresponding identifier $n will be a rowtype, but it
	must be aliased using the ALIAS command described below. Only the user
	attributes of a table row are accessible in the row, no Oid or other
	system attributes (because the row could be from a view and view rows
	don't have useful system attributes).
       </para>
       <para>
	The fields of the rowtype inherit the table's field sizes 
	or precision for <type>char()</type> etc. data types.
       </para>
      </listitem>
     </varlistentry>
d406 2
a407 21
     <varlistentry>
      <term>
<replaceable>name</replaceable> RECORD;
      </term>
      <listitem>
       <para>
	Records are similar to rowtypes, but they have no predefined structure.
	They are used in selections and FOR loops to hold one actual
	database row from a SELECT operation. One and the same record can be
	used in different selections. Accessing a record or an attempt to assign
	a value to a record field when there is no actual row in it results
	in a runtime error.
       </para>
       <para>
	The NEW and OLD rows in a trigger are given to the procedure as
	records. This is necessary because in <productname>Postgres</productname>
	one and the same trigger procedure can handle trigger events for
	different tables.
       </para>
      </listitem>
     </varlistentry>
d409 65
a473 16
     <varlistentry>
      <term>
<replaceable>name</replaceable> ALIAS FOR $n;
      </term>
      <listitem>
       <para>
	For better readability of the code it is possible to define an alias
	for a positional parameter to a function.
       </para>
       <para>
	This aliasing is required for composite types given as arguments to
	a function. The dot notation $1.salary as in <acronym>SQL</acronym> functions is not
	allowed in PL/pgSQL.
       </para>
      </listitem>
     </varlistentry>
d475 12
a486 12
     <varlistentry>
      <term>
RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
      </term>
      <listitem>
       <para>
	Change the name of a variable, record or row. This is useful
	if NEW or OLD should be referenced by another name inside a 
	trigger procedure.
       </para>
      </listitem>
     </varlistentry>
d488 5
a492 2
    </variablelist>
   </sect2>
d494 23
a516 4
   <!-- **** PL/pgSQL data types **** -->

   <sect2>
    <title>Data Types</title>
d518 4
a521 49
    <para>
     The type of a variable can be any of the existing base types of
     the database. <replaceable>type</replaceable> in the declarations
     section above is defined as:
    </para>
    <para>
     <itemizedlist>
      <listitem>
       <para>
	<productname>Postgres</productname>-basetype
       </para>
      </listitem>
      <listitem>
       <para>
	<replaceable>variable</replaceable>%TYPE
       </para>
      </listitem>
      <listitem>
       <para>
	<replaceable>table.field</replaceable>%TYPE
       </para>
      </listitem>
     </itemizedlist>
    </para>
    <para>
     <replaceable>variable</replaceable> is the name of a variable,
     previously declared in the 
     same function, that is visible at this point.
    </para>
    <para>
     <replaceable>table</replaceable> is the name of an existing table
     or view where <replaceable>field</replaceable> is the name of
     an attribute.
    </para>
    <para>
     Using the <replaceable>table.field</replaceable>%TYPE
     causes PL/pgSQL to look up the attributes definitions at the
     first call to the function during the lifetime of a backend.
     Suppose we have a table with a <type>char(20)</type> attribute and some PL/pgSQL functions
     that deal with its content in local variables. Now someone
     decides that <type>char(20)</type> is not enough, dumps the table, drops it,
     recreates it now with the attribute in question defined as
     <type>char(40)</type> and restores the data. Hah - he forgot about the
     functions. The computations inside them will truncate the values
     to 20 characters. But if they are defined using the
     <replaceable>table.field</replaceable>%TYPE
     declarations, they will automagically handle the size change or
     if the new table schema defines the attribute as <type>text</type> type.
    </para>
d532 2
a533 1
     constants may in fact require runtime evaluation (e.g., <literal>'now'</literal> for the
d538 1
a538 1
<synopsis>
d540 1
a540 1
</synopsis>
d552 1
a552 1
     is a difference between what the two functions
d554 1
a554 1
<programlisting>
d563 1
a563 1
</programlisting>
d567 1
a567 1
<programlisting>
d578 1
a578 1
</programlisting>
d580 7
a586 7
     do. In the case of <function>logfunc1()</function>, the
     <productname>Postgres</productname> main parser knows when
     preparing the plan for the INSERT, that the string
     <literal>'now'</literal> should be interpreted as
     <type>timestamp</type> because the target field of logtable is of
     that type. Thus, it will make a constant from it at this time and
     this constant value is then used in all invocations of
d588 2
a589 2
     backend. Needless to say that this isn't what the programmer
     wanted.
d592 5
a596 4
     In the case of <function>logfunc2()</function>, the <productname>Postgres</productname> 
     main parser does not know
     what type <literal>'now'</literal> should become and therefore it returns a data type of
     <type>text</type> containing the string <literal>'now'</literal>. During the assignment
d598 2
a599 1
     string to the timestamp type by calling the <function>text_out()</function> and <function>timestamp_in()</function>
d621 2
a622 2
   <sect2 id="plpgsql-statements">
    <title>Statements</title>
d624 8
d633 12
a644 3
     Anything not understood by the PL/pgSQL parser as specified below
     will be put into a query and sent down to the database engine
     to execute. The resulting query should not return any data.
d647 5
a651 40
    <variablelist>

     <varlistentry>
      <term>Assignment</term>
      <listitem>
       <para>
	An assignment of a value to a variable or row/record field is
	written as
<synopsis>
<replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
</synopsis>
	If the expressions result data type doesn't match the variables
	data type, or the variable has a size/precision that is known
	(as for <type>char(20)</type>), the result value will be implicitly cast by
	the PL/pgSQL bytecode interpreter using the result types output- and
	the variables type input-functions. Note that this could potentially
	result in runtime errors generated by the types input functions.
       </para>
       <para>
	An assignment of a complete selection into a record or row can
	be done by
<synopsis>
SELECT  INTO <replaceable>target</replaceable> <replaceable>expressions</replaceable> FROM ...;
</synopsis>
	<replaceable>target</replaceable> can be a record, a row variable or a
	comma separated list of variables and record-/row-fields.  Note that
	this is quite different from Postgres' normal interpretation of
	SELECT INTO, which is that the INTO target is a newly created table.
	(If you want to create a table from a SELECT result inside a PL/pgSQL
	function, use the equivalent syntax CREATE TABLE AS SELECT.)
       </para>
       <para>
	if a row or a variable list is used as target, the selected values
	must exactly match the structure of the target(s) or a runtime error
	occurs. The FROM keyword can be followed by any valid qualification,
	grouping, sorting etc. that can be given for a SELECT statement.
       </para>
       <para>
	There is a special variable named FOUND of type <type>boolean</type> that can be used
	immediately after a SELECT INTO to check if an assignment had success.
d653 2
a654 6
<programlisting>
SELECT INTO myrec * FROM EMP WHERE empname = myname;
IF NOT FOUND THEN
    RAISE EXCEPTION ''employee % not found'', myname;
END IF;
</programlisting>
d656 12
a667 16
	If the selection returns multiple rows, only the first is moved
	into the target fields. All others are silently discarded.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>Calling another function</term>
      <listitem>
       <para>
	All functions defined in a <productname>Postgres</productname>
	database return a value. Thus, the normal way to call a function
	is to execute a SELECT query or doing an assignment (resulting
	in a PL/pgSQL internal SELECT). But there are cases where someone
	is not interested in the function's result.
<synopsis>
d669 26
a694 13
</synopsis>
	executes a <literal>SELECT <replaceable>query</replaceable></literal> over the
	<acronym>SPI</acronym> manager and discards the result. Identifiers like local
	variables are still substituted into parameters.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>Executing dynamic queries</term>
      <listitem>
       <para>
<synopsis>
d696 4
a699 4
</synopsis>
       where <replaceable>query-string</replaceable> is a string of
       type <type>text</type> containing the <replaceable>query</replaceable> to be
       executed.
d701 7
a707 1
	    
d718 1
a718 1

d720 4
a723 4
	The results from SELECT queries are discarded by EXECUTE, and
	SELECT INTO is not currently supported within EXECUTE.  So, the
	only way to extract a result from a dynamically-created SELECT
	is to use the FOR ... EXECUTE form described later.
d728 1
a728 1
<programlisting>
d734 51
a784 15
</programlisting>
        This example shows use of the functions
        <function>quote_ident</function>(<type>TEXT</type>) and
        <function>quote_literal</function>(<type>TEXT</type>).
        Variables containing field and table identifiers should be
        passed to function <function>quote_ident()</function>.
        Variables containing literal elements of the dynamic query
        string should be passed to
        <function>quote_literal()</function>.  Both take the
        appropriate steps to return the input text enclosed in single
        or double quotes and with any embedded special characters
        properly escaped.
       </para>
      </listitem>
     </varlistentry>
d786 2
a787 3
     <varlistentry>
      <term>Obtaining other results status</term>
      <listitem>
d789 1
a789 1
<synopsis>
d791 10
a800 10
</synopsis>
	This command allows retrieval of system status indicators.  Each
	<replaceable>item</replaceable> is a keyword identifying a state
	value to be assigned to the specified variable (which should be of
	the right datatype to receive it).  The currently available status
	items are <varname>ROW_COUNT</>, the number of rows processed by
	the last <acronym>SQL</acronym> query sent down to the <acronym>SQL</acronym> engine; and
	<varname>RESULT_OID</>, the Oid of the last row inserted by the
	most recent <acronym>SQL</acronym> query.  Note that <varname>RESULT_OID</> is only
	useful after an INSERT query.
d802 4
a805 2
      </listitem>
     </varlistentry>
d807 2
a808 5
     <varlistentry>
      <term>Returning from the function</term>
      <listitem>
       <para>
<synopsis>
d810 6
a815 6
</synopsis>
	The function terminates and the value of <replaceable>expression</replaceable>
	will be returned to the upper executor. The return value of a function
	cannot be undefined. If control reaches the end of the top-level block
	of the function without hitting a RETURN statement, a runtime error
	will occur.
d818 2
a819 2
	The expressions result will be automatically casted into the
	function's return type as described for assignments.
d821 26
a846 2
      </listitem>
     </varlistentry>
d848 1
d850 3
a852 1
      <term>Aborting and messages</term>
d855 9
a863 11
	As indicated in the above examples there is a RAISE statement that
	can throw messages into the <productname>Postgres</productname>
	elog mechanism.
<synopsis>
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">identifier</replaceable> <optional>...</optional></optional>;
</synopsis>
	Inside the format, <literal>%</literal> is used as a placeholder for the
	subsequent comma-separated identifiers. Possible levels are
	DEBUG (silently suppressed in production running databases), NOTICE 
	(written into the database log and forwarded to the client application)
	and EXCEPTION (written into the database log and aborting the transaction).
d869 3
a871 1
      <term>Conditionals</term>
d874 30
a903 5
<synopsis>
IF <replaceable>expression</replaceable> THEN
    <replaceable>statements</replaceable>
<optional>ELSE
    <replaceable>statements</replaceable></optional>
d905 1
a905 3
</synopsis>
	The <replaceable>expression</replaceable> must return a value that
	is of type <type>boolean</type> or can be casted to a <type>boolean</type>.
d912 1
a912 1
Loops
d916 4
a919 63
	There are multiple types of loops.
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
	An unconditional loop that must be terminated explicitly
	by an EXIT statement. The optional label can be used by
	EXIT statements of nested loops to specify which level of
	nesting should be terminated.
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
WHILE <replaceable>expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
	A conditional loop that is executed as long as the evaluation
	of <replaceable>expression</replaceable> is true.
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
	A loop that iterates over a range of integer values. The variable
	<replaceable>name</replaceable> is automatically created as type
	integer and exists only inside the loop. The two expressions giving
	the lower and upper bound of the range are evaluated only when entering
	the loop. The iteration step is always 1.
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>record | row</replaceable> IN <replaceable>select_clause</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
	The record or row is assigned all the rows resulting from the select
	clause and the loop body is executed for each row. If the loop is
	terminated with an EXIT statement, the last assigned row is still
	accessible after the loop.
<synopsis>
<optional>&lt;&lt;label&gt;&gt;</optional>
FOR <replaceable>record | row</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> LOOP
    <replaceable>statements</replaceable>
END LOOP;
</synopsis>
	This is like the previous form, except that the source SELECT
	statement is specified as a string expression, which is evaluated
	and re-planned on each entry to the FOR loop.  This allows the
	programmer to choose the speed of a pre-planned query or the
	flexibility of a dynamic query, just as with a plain EXECUTE
	statement.
<synopsis>
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>expression</replaceable> </optional>;
</synopsis>
	If no <replaceable>label</replaceable> given,
	the innermost loop is terminated and the
	statement following END LOOP is executed next.
	If <replaceable>label</replaceable> is given, it
	must be the label of the current or an upper level of nested loop
	blocks. Then the named loop or block is terminated and control
	continues with the statement after the loops/blocks corresponding
	END.
d921 11
a933 1

d935 1
d937 2
a938 6
   </sect2>

   <!-- **** PL/pgSQL trigger procedures **** -->

   <sect2>
    <title>Trigger Procedures</title>
d941 3
a943 7
     PL/pgSQL can be used to define trigger procedures. They are created
     with the usual CREATE FUNCTION command as a function with no
     arguments and a return type of OPAQUE.
    </para>
    <para>
     There are some <productname>Postgres</productname> specific details
     in functions used as trigger procedures.
a944 5
    <para>
     First they have some special variables created automatically in the 
     top-level blocks declaration section. They are
    </para>

d947 3
a949 1
      <term><varname>NEW</varname></term>
d952 10
a961 2
	Data type RECORD; variable holding the new database row on INSERT/UPDATE
	operations on ROW level triggers.
d967 3
a969 1
      <term><varname>OLD</varname></term>
d972 11
a982 2
	Data type RECORD; variable holding the old database row on UPDATE/DELETE
	operations on ROW level triggers.
d984 14
a997 2
      </listitem>
     </varlistentry>
d999 7
a1005 6
     <varlistentry>
      <term><varname>TG_NAME</varname></term>
      <listitem>
       <para>
	Data type <type>name</type>; variable that contains the name of the trigger actually
	fired.
d1011 3
a1013 1
      <term><varname>TG_WHEN</varname></term>
d1016 3
a1018 2
	Data type <type>text</type>; a string of either <literal>'BEFORE'</literal> or <literal>'AFTER'</literal> depending on the
	triggers definition.
a1019 6
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><varname>TG_LEVEL</varname></term>
      <listitem>
d1021 8
a1028 2
	Data type <type>text</type>; a string of either <literal>'ROW'</literal> or <literal>'STATEMENT'</literal> depending on the
	triggers definition.
d1030 4
a1033 2
      </listitem>
     </varlistentry>
d1035 4
a1038 6
     <varlistentry>
      <term><varname>TG_OP</varname></term>
      <listitem>
       <para>
	Data type <type>text</type>; a string of <literal>'INSERT'</literal>, <literal>'UPDATE'</literal>, or <literal>'DELETE'</literal> telling
	for which operation the trigger is actually fired.
d1044 3
a1046 1
      <term><varname>TG_RELID</varname></term>
d1049 11
a1059 2
	Data type oid; the object ID of the table that caused the
	trigger invocation.
a1060 6
      </listitem>
     </varlistentry>

     <varlistentry>
      <term><varname>TG_RELNAME</varname></term>
      <listitem>
d1062 5
a1066 5
	Data type name; the name of the table that caused the trigger
	invocation.
       </para>
      </listitem>
     </varlistentry>
d1068 2
a1069 9
     <varlistentry>
      <term><varname>TG_NARGS</varname></term>
      <listitem>
       <para>
	Data type integer; the number of arguments given to the trigger
	procedure in the CREATE TRIGGER statement.
       </para>
      </listitem>
     </varlistentry>
d1071 4
a1074 7
     <varlistentry>
      <term><varname>TG_ARGV[]</varname></term>
      <listitem>
       <para>
	Data type array of <type>text</type>; the arguments from the CREATE TRIGGER statement.
	The index counts from 0 and can be given as an expression. Invalid
	indices (&lt; 0 or &gt;= tg_nargs) result in a NULL value.
d1079 12
d1092 8
d1101 3
a1103 9
     Second they must return either NULL or a record/row containing
     exactly the structure of the table the trigger was fired for.
     Triggers fired AFTER might always return a NULL value with no
     effect. Triggers fired BEFORE signal the trigger manager
     to skip the operation for this actual row when returning NULL.
     Otherwise, the returned record/row replaces the inserted/updated
     row in the operation. It is possible to replace single values directly
     in NEW and return that or to build a complete new record/row to
     return.
d1105 173
a1277 1
   </sect2>
d1310 2
a1311 1
  </sect1>
d1313 1
a1313 1
  <!-- **** PL/pgSQL Examples **** -->
d1315 2
a1316 2
  <sect1 id="plpgsql-examples">
   <title>Examples</title>
d1318 7
d1326 2
a1327 3
    Here are only a few functions to demonstrate how easy it is to write PL/pgSQL
    functions. For more complex examples the programmer
    might look at the regression test for PL/pgSQL.
a1328 1

d1330 2
a1331 8
    One painful detail in writing functions in PL/pgSQL is the handling
    of single quotes. The function's source text in the <command>CREATE FUNCTION</command> command must
    be a literal string. Single quotes inside of literal strings must be
    either doubled or quoted with a backslash. We are still looking for
    an elegant alternative. In the meantime, doubling the single quotes
    as in the examples below should be used. Any solution for this
    in future versions of <productname>Postgres</productname> will be
    forward compatible.
d1333 11
d1345 19
a1363 2
   <example>
    <title>A Simple PL/pgSQL Functions</title>
d1365 10
a1374 3
    <para>
     The following two PL/pgSQL functions are identical to their
     counterparts from the C language function discussion.
d1376 10
a1385 7
<programlisting>
CREATE FUNCTION add_one (integer) RETURNS integer AS '
    BEGIN
        RETURN $1 + 1;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
d1387 11
a1397 8
<programlisting>
CREATE FUNCTION concat_text (text, text) RETURNS text AS '
    BEGIN
        RETURN $1 || $2;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
d1399 9
a1407 1
   </example>
d1409 9
a1417 2
   <example>
    <title>A PL/pgSQL Function on a Composite Type</title>
d1419 9
a1427 3
    <para>
     Again, this is the PL/pgSQL equivalent to the example from
     the C functions.
d1429 12
a1440 14
<programlisting>
CREATE FUNCTION c_overpaid (EMP, integer) RETURNS boolean AS '
    DECLARE
        emprec ALIAS FOR $1;
        sallim ALIAS FOR $2;
    BEGIN
        IF emprec.salary ISNULL THEN
            RETURN ''f'';
        END IF;
        RETURN emprec.salary > sallim;
    END;
' LANGUAGE 'plpgsql';
</programlisting>
    </para>
d1442 12
a1453 1
   </example>
d1456 1
a1456 1
    <title>A PL/pgSQL Trigger Procedure</title>
d1459 1
a1459 1
     This trigger ensures that any time a row is inserted or updated
d1464 1
a1464 1
<programlisting>
d1495 41
a1535 1
</programlisting>
d1537 8
d1546 46
d1594 2
d1684 1
a1684 1
       quotes. See <xref linkend="plpgsql-quote">.
d1697 3
a1699 2
     other function(s), as in <xref
     linkend="plpgsql-porting-nastyquote">.  One thing to keep in mind
d1706 1
a1706 1
     <xref linkend="plpgsql-quoting-table"> gives the scoop.  (You'll
d1779 1
a1779 1
         (like in <xref linkend="plpgsql-porting-nastyquote">).
d1868 1
a1868 1
        linkend="plpgsql-quote">).
d1988 2
a1989 2
     procedure because in functions only one value can be returned
     (see <xref linkend="plpgsql-porting-procedures">).  In
d2078 1
a2078 1
     linkend="plpgsql-porting-appendix"> for the code.
d2101 1
a2101 1
    pragma autonomous_transaction;<co id="co.plpgsql-porting-pragma">
d2103 1
a2103 1
    lock table cs_jobs in exclusive mode;<co id="co.plpgsql-porting-locktable">
d2109 1
a2109 1
        commit; -- free lock<co id="co.plpgsql-porting-commit">
d2118 1
a2118 1
        exception when dup_val_on_index then null; -- don't worry if it already exists<co id="co.plpgsql-porting-exception">
d2193 1
a2193 1
        raise NOTICE ''Job already running.'';<co id="co.plpgsql-porting-raise">
d2304 1
a2304 1
     linkend="plpgsql-statements">.  Constructs of the type
d2318 2
a2319 2
     argument is NULL).  Consult the <literal>CREATE
     FUNCTION</literal> reference for details.
d2324 2
a2325 2
     <literal>WITH</literal> modifier in your <literal>CREATE
     FUNCTION</literal> statement.  Something like:
@


2.21
log
@Fix markup.  (A <keyword> isn't what it is in SQL.)  Add jungle of more
markup. ;-)
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.20 2001/02/19 19:49:52 tgl Exp $
d5 1
a5 1
 <chapter id="plsql">
d17 1
a17 1
  <sect1 id="plsql-overview">
d421 1
a421 1
   <sect2>
d994 901
a1894 1
 </chapter>
@


2.20
log
@Change plpgsql's GET DIAGNOSTICS statement to use SQL99-compatible
syntax.  Fix the RESULT_OID case, which never worked.  Add documentation.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.19 2001/02/10 05:32:33 tgl Exp $
d6 1
a6 1
  <title>PL/pgSQL - SQL Procedural Language</title>
d67 2
a68 2
    prepared execution plan using the SPI manager's SPI_prepare() and
    SPI_saveplan() functions. This is done the first time the individual
d110 4
a113 4
     <programlisting>
[&lt;&lt;label&gt;&gt;]
[DECLARE
    <replaceable>declarations</replaceable>]
d117 1
a117 1
     </programlisting>
d144 3
a146 3
     There are two types of comments in PL/pgSQL. A double dash '--'
     starts a comment that extends to the end of the line. A '/*'
     starts a block comment that extends to the next occurrence of '*/'.
d149 1
a149 1
     the block comment delimiters '/*' and '*/'.
d163 1
a163 1
     automatically declared with the usual identifiers $n.
d170 3
a172 3
<replaceable>name</replaceable> [ CONSTANT ]
<replaceable>type</replaceable> [ NOT NULL ] [ DEFAULT | :=
	<replaceable>value</replaceable> ];
d185 1
a185 1
	assigning '<replaceable>now</replaceable>' to a variable of type
d211 1
a211 1
	or precision for char() etc. data types.
d249 1
a249 1
	a function. The dot notation $1.salary as in SQL functions is not
d314 1
a314 1
     Suppose we have a table with a char(20) attribute and some PL/pgSQL functions
d316 1
a316 1
     decides that char(20) isn't enough, dumps the table, drops it,
d318 1
a318 1
     char(40) and restores the data. Ha - he forgot about the
d323 1
a323 1
     if the new table schema defines the attribute as text type.
d335 1
a335 1
     constants may in fact require run-time evaluation (e.g. 'now' for the
d340 4
a343 4
     <programlisting>
      SELECT <replaceable>expression</replaceable>
     </programlisting>
     using the SPI manager. In the expression, occurrences of variable
d356 1
a356 1
     <programlisting>
d365 1
a365 1
     </programlisting>
d369 1
a369 1
     <programlisting>
d380 1
a380 1
     </programlisting>
d382 10
a391 8
     do. In the case of logfunc1(), the <productname>Postgres</productname>
     main parser
     knows when preparing the plan for the INSERT, that the string 'now'
     should be interpreted as <type>timestamp</type> because the target field of logtable
     is of that type. Thus, it will make a constant from it at this time
     and this constant value is then used in all invocations of logfunc1()
     during the lifetime of the backend. Needless to say that this isn't what the
     programmer wanted.
d394 1
a394 1
     In the case of logfunc2(), the <productname>Postgres</productname> 
d396 2
a397 2
     what type 'now' should become and therefore it returns a data type of
     text containing the string 'now'. During the assignment
d399 1
a399 1
     string to the timestamp type by calling the text_out() and timestamp_in()
d406 1
a406 1
     using the prepared plan feature of the SPI manager.
d438 3
a440 3
	<programlisting>
	 <replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
	</programlisting>
d443 1
a443 1
	(as for char(20)), the result value will be implicitly casted by
d451 1
a451 1
	<programlisting>
d453 1
a453 1
	</programlisting>
d468 1
a468 1
	There is a special variable named FOUND of type bool that can be used
d471 1
a471 1
	<programlisting>
d476 1
a476 1
	</programlisting>
d493 1
a493 1
	<programlisting>
d495 3
a497 3
	</programlisting>
	executes a 'SELECT <replaceable>query</replaceable>' over the
	SPI manager and discards the result. Identifiers like local
d506 7
a512 8
       <cmdsynopsis>
        <command>EXECUTE</command>
        <arg choice="req"><replaceable class="command">query-string</replaceable></arg>
       </cmdsynopsis>
	   
	   <para>
       where <replaceable>query-string</replaceable> is a string
	   of type TEXT containing the <replaceable>query</replaceable> to be executed.
d561 3
a563 3
	<programlisting>
GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> [ , ... ]
	</programlisting>
d568 4
a571 4
	items are <keyword>ROW_COUNT</>, the number of rows processed by
	the last SQL query sent down to the SQL engine; and
	<keyword>RESULT_OID</>, the Oid of the last row inserted by the
	most recent SQL query.  Note that <keyword>RESULT_OID</> is only
d581 1
a581 1
	<programlisting>
d583 1
a583 1
	</programlisting>
d604 4
a607 4
	<programlisting>
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' [, <replaceable class="parameter">identifier</replaceable> [...]];
	</programlisting>
	Inside the format, "<literal>%</literal>" is used as a placeholder for the
d620 1
a620 1
	<programlisting>
d623 2
a624 2
[ELSE
    <replaceable>statements</replaceable>]
d626 1
a626 1
	</programlisting>
d628 1
a628 1
	is a boolean or can be casted into a boolean.
d640 2
a641 2
	<programlisting>
[&lt;&lt;label&gt;&gt;]
d645 1
a645 1
	</programlisting>
d650 2
a651 2
	<programlisting>
[&lt;&lt;label&gt;&gt;]
d655 1
a655 1
	</programlisting>
d658 3
a660 3
	<programlisting>
[&lt;&lt;label&gt;&gt;]
FOR <replaceable>name</replaceable> IN [ REVERSE ] <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
d663 1
a663 1
	</programlisting>
d669 2
a670 2
	<programlisting>
[&lt;&lt;label&gt;&gt;]
d674 1
a674 1
	</programlisting>
d679 2
a680 2
	<programlisting>
[&lt;&lt;label&gt;&gt;]
d684 1
a684 1
	</programlisting>
d691 3
a693 3
	<programlisting>
EXIT [ <replaceable>label</replaceable> ] [ WHEN <replaceable>expression</replaceable> ];
	</programlisting>
d731 1
a731 1
      <term>NEW</term>
d741 1
a741 1
      <term>OLD</term>
d751 1
a751 1
      <term>TG_NAME</term>
d754 1
a754 1
	Data type name; variable that contains the name of the trigger actually
d761 1
a761 1
      <term>TG_WHEN</term>
d764 1
a764 1
	Data type text; a string of either 'BEFORE' or 'AFTER' depending on the
d771 1
a771 1
      <term>TG_LEVEL</term>
d774 1
a774 1
	Data type text; a string of either 'ROW' or 'STATEMENT' depending on the
d781 1
a781 1
      <term>TG_OP</term>
d784 1
a784 1
	Data type text; a string of 'INSERT', 'UPDATE' or 'DELETE' telling
d791 1
a791 1
      <term>TG_RELID</term>
d801 1
a801 1
      <term>TG_RELNAME</term>
d811 1
a811 1
      <term>TG_NARGS</term>
d821 1
a821 1
      <term>TG_ARGV[]</term>
d824 1
a824 1
	Data type array of text; the arguments from the CREATE TRIGGER statement.
d884 2
a885 2
    Here are only a few functions to demonstrate how easy PL/pgSQL
    functions can be written. For more complex examples the programmer
d890 2
a891 2
    One painful detail of writing functions in PL/pgSQL is the handling
    of single quotes. The function's source text on CREATE FUNCTION must
d897 1
a897 1
    upward compatible.
d900 2
a901 2
   <sect2>
    <title>Some Simple PL/pgSQL Functions</title>
d907 1
a907 1
     <programlisting>
d913 1
a913 1
    </programlisting>
d915 1
a915 1
    <programlisting>
d921 1
a921 1
     </programlisting>
d924 1
a924 1
   </sect2>
d926 2
a927 2
   <sect2>
    <title>PL/pgSQL Function on Composite Type</title>
d930 2
a931 2
     Again it is the PL/pgSQL equivalent to the example from
     The C functions.
d933 2
a934 2
     <programlisting>
CREATE FUNCTION c_overpaid (EMP, integer) RETURNS bool AS '
d945 1
a945 1
     </programlisting>
d948 1
a948 1
   </sect2>
d950 2
a951 2
   <sect2>
    <title>PL/pgSQL Trigger Procedure</title>
d954 1
a954 1
     This trigger ensures, that any time a row is inserted or updated
d959 1
a959 1
     <programlisting>
d990 1
a990 1
     </programlisting>
d992 1
a992 1
   </sect2>
@


2.19
log
@Fix documentation of EXECUTE, add documentation of FOR ... EXECUTE.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.18 2001/01/20 20:59:29 petere Exp $
d105 1
a105 1
     identifiers can be used in mixed upper- and lowercase.
d184 1
a184 1
	The default value is evaluated every time the function is called. So
d206 1
a206 1
	system attributes (hence the row could be from a view and view rows
d314 1
a314 1
     Have a table with a char(20) attribute and some PL/pgSQL functions
d552 20
@


2.18
log
@Replace some oldish, non-SQL'ish elements with more standard forms. (cast
syntax, type names, function names, etc.)
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.17 2001/01/18 07:11:36 thomas Exp $
d57 2
a58 2
    The PL/pgSQL call handler parses the functions source text and
    produces an internal binary instruction tree on the first time the
d60 1
a60 1
    in the call handler by the object ID of the function. This ensures,
d67 2
a68 2
    prepared execution plan using the SPI managers SPI_prepare() and
    SPI_saveplan() functions. This is done the first time, the individual
d72 1
a72 1
    that are really used during the entire lifetime of the database
d76 10
a85 1
    Except for input-/output-conversion and calculation functions
d130 7
a136 5
     It is important not to misunderstand the meaning of BEGIN/END for
     grouping statements in PL/pgSQL and the database commands for
     transaction control. Functions and trigger procedures cannot
     start or commit transactions and <productname>Postgres</productname>
     does not have nested transactions.
d160 2
a161 2
     sub-blocks must be declared in the declarations section of a block
     except for the loop variable of a FOR loop iterating over a range
d453 5
a457 1
	comma separated list of variables and record-/row-fields.
d524 1
a524 1
		
d526 4
a529 2
		The results from SELECT queries are discarded by EXECUTE unless
		SELECT INTO is used to save the results into a table.
d551 1
a551 1
        intact.
d607 1
a607 1
	at least can be casted into a boolean type.
d655 15
a669 3
	clause and the statements executed for each. If the loop is terminated
	with an EXIT statement, the last assigned row is still accessible 
	after the loop.
@


2.17
log
@Replace contraction with long form. Cosmetic only.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.16 2001/01/17 22:13:33 momjian Exp $
d173 1
a173 1
	The default value is evaluated ever time the function is called. So
d175 1
a175 1
	<replaceable>datetime</replaceable> causes the variable to have the
d325 1
a325 1
     datetime type) so
d346 1
a346 1
CREATE FUNCTION logfunc1 (text) RETURNS datetime AS '
d359 1
a359 1
CREATE FUNCTION logfunc2 (text) RETURNS datetime AS '
d362 1
a362 1
        curtime datetime;
d374 1
a374 1
     should be interpreted as datetime because the target field of logtable
d386 1
a386 1
     string to the datetime type by calling the text_out() and datetime_in()
d858 1
a858 1
CREATE FUNCTION add_one (int4) RETURNS int4 AS '
d884 1
a884 1
CREATE FUNCTION c_overpaid (EMP, int4) RETURNS bool AS '
d912 3
a914 3
    salary int4,
    last_date datetime,
    last_user name);
d933 1
a933 1
        NEW.last_user := getpgusername();
@


2.16
log
@Functions -> Function's
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.15 2001/01/17 16:34:34 momjian Exp $
d475 1
a475 1
	isn't interested in the function's result.
@


2.15
log
@There are misprints in postgres doc., in :
Chapter 10. PL/pgSQL - SQL Procedural Language (c40914117.htm)

Statements
...
(resulting in a PL/pgSQL internal SELECT).
But there are cases where someone isn't interested int
-----------------------------------------(have to be)-->
But there are cases where someone isn't interested in
     the functions result.

 RAISE level format''
--(have to be)-->
 RAISE level 'format'
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.14 2001/01/13 23:58:55 petere Exp $
d475 1
a475 1
	isn't interested in the functions result.
d554 1
a554 1
	functions return type as described for assignments.
d841 1
a841 1
    of single quotes. The functions source text on CREATE FUNCTION must
@


2.14
log
@Terminology cleanup: class -> table, instance -> row, attribute -> column,
etc.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.13 2001/01/09 15:26:16 momjian Exp $
d475 1
a475 1
	isn't interested int the functions result.
d567 1
a567 1
RAISE <replaceable class="parameter">level</replaceable> <replaceable class="parameter">format</replaceable>'' [, <replaceable class="parameter">identifier</replaceable> [...]];
@


2.13
log
@A patch for doc/src/sgml/plsql.sgml to add a little more info about PL/pgSQL
EXECUTE.

--
-------- Robert B. Easter
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.12 2001/01/06 12:26:08 petere Exp $
d184 1
a184 1
<replaceable>name</replaceable> <replaceable>class</replaceable>%ROWTYPE;
d188 2
a189 2
	Declares a row with the structure of the given class. Class must be
	an existing table- or view name of the database. The fields of the row
d284 1
a284 1
	<replaceable>class.field</replaceable>%TYPE
d295 1
a295 1
     <replaceable>class</replaceable> is the name of an existing table
d300 1
a300 1
     Using the <replaceable>class.field</replaceable>%TYPE
d310 1
a310 1
     <replaceable>class.field</replaceable>%TYPE
@


2.12
log
@EXECUTE documentation, from "Robert B. Easter" <reaster@@comptechnews.com>.
I threw in spell check run over the whole file.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.11 2000/12/22 18:57:50 petere Exp $
d491 1
a491 1
        <arg choice="req"><replaceable class="command">query</replaceable></arg>
d493 6
a498 1

d504 2
a505 2
        prepared each time the statement is run. This allows the
        <replaceable>query</replaceable> to be dynamically created
d508 5
@


2.11
log
@Replace incorrect uses of 'which' with 'that'.  (so-called "wicked which")
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.10 2000/09/29 20:21:34 petere Exp $
d58 2
a59 2
    produces an internal binary instruction tree on the first time, the
    function is called by a backend. The produced bytecode is identified
d112 2
a113 2
     There can be any number of subblocks in the statement section
     of a block. Subblocks can be used to hide variables from outside a
d135 1
a135 1
     starts a block comment that extends to the next occurence of '*/'.
d148 2
a149 2
     All variables, rows and records used in a block or it's
     subblocks must be declared in the declarations section of a block
d177 1
a177 1
	precompiled into it's bytecode.
d189 1
a189 1
	an existing table- or viewname of the database. The fields of the row
d199 1
a199 1
	The fields of the rowtype inherit the tables fieldsizes 
d266 1
a266 1
     The type of a varible can be any of the existing basetypes of
d301 1
a301 1
     causes PL/pgSQL to lookup the attributes definitions at the
d304 1
a304 1
     that deal with it's content in local variables. Now someone
d308 1
a308 1
     funcitons. The computations inside them will truncate the values
d323 1
a323 1
     the backends executor. Expressions that appear to contain
d332 1
a332 1
     using the SPI manager. In the expression, occurences of variable
d336 2
a337 1
     saved once.
d383 1
a383 1
     what type 'now' should become and therefor it returns a datatype of
d471 1
a471 1
	All functions defined in a <productname>Prostgres</productname>
d487 43
d538 1
a538 1
	cannot be undefined. If control reaches the end of the toplevel block
d666 1
a666 1
     toplevel blocks declaration section. They are
d674 1
a674 1
	Datatype RECORD; variable holding the new database row on INSERT/UPDATE
d684 1
a684 1
	Datatype RECORD; variable holding the old database row on UPDATE/DELETE
d694 1
a694 1
	Datatype name; variable that contains the name of the trigger actually
d704 1
a704 1
	Datatype text; a string of either 'BEFORE' or 'AFTER' depending on the
d714 1
a714 1
	Datatype text; a string of either 'ROW' or 'STATEMENT' depending on the
d724 1
a724 1
	Datatype text; a string of 'INSERT', 'UPDATE' or 'DELETE' telling
d734 1
a734 1
	Datatype oid; the object ID of the table that caused the
d744 1
a744 1
	Datatype name; the name of the table that caused the trigger
d754 1
a754 1
	Datatype integer; the number of arguments given to the trigger
d764 1
a764 1
	Datatype array of text; the arguments from the CREATE TRIGGER statement.
d795 1
a795 1
     into the mainloop to get the next query from the client application.
d799 1
a799 1
     happens. But currently it's impossible to tell what really
d834 1
a834 1
    an elegant alternative. In the meantime, doubling the single qoutes
d895 1
a895 1
     in the table, the current username and time are stamped into the
@


2.10
log
@Add `id' attributes to all `chapter' and `sect1' tags, to generate useful
names for the HTML files (e.g., not x4856.htm).
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.9 2000/08/25 15:17:36 thomas Exp $
d323 1
a323 1
     the backends executor. Expressions which appear to contain
@


2.9
log
@Fix typos and inconsistancies found by He Weiping
 (aka Henry) <laser@@zhangmai.com.cn>.
Fix new problems in insert.sgml and create_function.sgml which kept jade
 from completing.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.8 2000/05/17 00:15:48 momjian Exp $
d5 1
a5 1
 <chapter>
d17 1
a17 1
  <sect1>
d86 1
a86 1
  <sect1>
d776 1
a776 1
  <sect1>
@


2.8
log
@Change plpgsql example from SELECT * INTO rec to SELECT INTO rec *.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.7 2000/05/16 21:16:12 momjian Exp $
d160 1
a160 1
<replaceable>type</replaceable>> [ NOT NULL ] [ DEFAULT | :=
@


2.7
log
@Fix typo
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.6 2000/05/16 19:29:43 momjian Exp $
d438 1
a438 1
SELECT <replaceable>expressions</replaceable> INTO <replaceable>target</replaceable> FROM ...;
d454 1
a454 1
SELECT * INTO myrec FROM EMP WHERE empname = myname;
@


2.6
log
@Cleanup plpgsql man page typo
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.5 2000/05/09 18:27:25 momjian Exp $
d302 1
a302 1
     first call to the funciton during the lifetime of a backend.
@


2.5
log
@Add single quote.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.4 2000/05/02 20:01:52 thomas Exp $
d160 1
a160 1
<replaceable>>typ</replaceable>> [ NOT NULL ] [ DEFAULT | :=
@


2.4
log
@Fixups in content and markup for 7.0 release.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.3 2000/03/31 06:17:21 thomas Exp $
d862 1
a862 1
CREATE FUNCTION emp_stamp () RETURNS OPAQUE AS
@


2.3
log
@Use a uniform chapter title for all of the procedural languages.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plsql.sgml,v 2.2 2000/03/31 03:27:41 thomas Exp $
d515 1
a515 1
	Inside the format, <quote>%</quote> is used as a placeholder for the
@


2.2
log
@Minor markup changes. Refer to (".../catalog") in the emacs hints.
@
text
@d2 1
a2 1
$Header$
d6 1
a6 1
  <title>PL/pgSQL</title>
@


2.1
log
@Split off language-specific docs to their own chapters.
Add PL/perl docs from Mark Hollomon.
Put language-specific docs into the User's Guide, and move the rest
 to the Programmer's Guide.
@
text
@d1 4
d904 1
a904 1
sgml-local-catalogs:("/usr/lib/sgml/CATALOG")
@
