]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpgsql.sgml
This patch makes a minor cleanup to the implementation of PERFORM in
[postgresql] / doc / src / sgml / plpgsql.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/plpgsql.sgml,v 1.9 2002/11/10 00:35:58 momjian Exp $
3 -->
4
5 <chapter id="plpgsql"> 
6   <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
7
8  <indexterm zone="plpgsql">
9   <primary>PL/pgSQL</primary>
10  </indexterm>
11
12  <para>
13   <application>PL/pgSQL</application> is a loadable procedural language for the
14   <productname>PostgreSQL</productname> database system.
15  </para>
16    
17  <para>
18   This package was originally written by Jan Wieck. This
19   documentation was in part written 
20   by Roberto Mello (<email>rmello@fslc.usu.edu</email>).
21  </para>
22
23   <sect1 id="plpgsql-overview">
24    <title>Overview</title>
25
26    <para>
27     The design goals of <application>PL/pgSQL</> were to create a loadable procedural
28     language that
29     <itemizedlist>
30      <listitem>
31       <para>
32        can be used to create functions and trigger procedures,
33       </para>
34      </listitem>
35      <listitem>
36       <para>
37        adds control structures to the <acronym>SQL</acronym> language,
38       </para>
39      </listitem>
40      <listitem>
41       <para>
42        can perform complex computations,
43       </para>
44      </listitem>
45      <listitem>
46       <para>
47        inherits all user defined types, functions and operators,
48       </para>
49      </listitem>
50      <listitem>
51       <para>
52        can be defined to be trusted by the server,
53       </para>
54      </listitem>
55      <listitem>
56       <para>
57        is easy to use.
58       </para>
59      </listitem>
60     </itemizedlist>
61    </para>
62    <para>
63     The <application>PL/pgSQL</> call handler parses the function's source text and
64     produces an internal binary instruction tree the first time the
65     function is called (within any one backend process).  The instruction tree
66     fully translates the 
67     <application>PL/pgSQL</> statement structure, but individual
68     <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> queries
69     used in the function are not translated immediately.
70    </para>
71    <para>
72     As each expression and <acronym>SQL</acronym> query is first used
73         in the function, the <application>PL/pgSQL</> interpreter creates
74         a prepared execution plan (using the <acronym>SPI</acronym>
75         manager's <function>SPI_prepare</function> and
76         <function>SPI_saveplan</function> functions).  Subsequent visits
77         to that expression or query re-use the prepared plan.  Thus, a
78         function with conditional code that contains many statements for
79         which execution plans might be required will only prepare and save
80         those plans that are really used during the lifetime of the
81         database connection.  This can substantially reduce the total
82         amount of time required to parse, and generate query plans for the
83         statements in a procedural language function. A disadvantage is
84         that errors in a specific expression or query may not be detected
85         until that part of the function is reached in execution.
86    </para>
87   <para>
88    Once <application>PL/pgSQL</> has made a query plan for a particular
89    query in a function, it will re-use that plan for the life of the
90    database connection.  This is usually a win for performance, but it
91    can cause some problems if you dynamically
92    alter your database schema. For example:
93
94 <programlisting>
95 CREATE FUNCTION populate() RETURNS INTEGER AS '
96 DECLARE
97     -- Declarations
98 BEGIN
99     PERFORM my_function();
100 END;
101 ' LANGUAGE 'plpgsql';
102 </programlisting>
103     If you execute the above function, it will reference the OID for
104     <function>my_function()</function> in the query plan produced for
105     the <command>PERFORM</command> statement. Later, if you
106     drop and re-create <function>my_function()</function>, then
107     <function>populate()</function> will not be able to find
108     <function>my_function()</function> anymore. You would then have to
109     re-create <function>populate()</function>, or at least start a new
110     database session so that it will be compiled afresh.
111    </para>
112
113    <para>
114     Because <application>PL/pgSQL</application> saves execution plans
115         in this way, queries that appear directly in a
116         <application>PL/pgSQL</application> function must refer to the
117         same tables and fields on every execution; that is, you cannot use
118         a parameter as the name of a table or field in a query.  To get
119         around this restriction, you can construct dynamic queries using
120         the <application>PL/pgSQL</application> <command>EXECUTE</command>
121         statement --- at the price of constructing a new query plan on
122         every execution.
123    </para>
124
125    <note>
126         <para>
127          The <application>PL/pgSQL</application>
128          <command>EXECUTE</command> statement is not related to the
129          <command>EXECUTE</command> statement supported by the
130          <productname>PostgreSQL</productname> backend. The backend
131          <command>EXECUTE</command> statement cannot be used within
132          <application>PL/pgSQL</> functions (and is not needed).
133         </para>
134    </note>
135
136    <para>
137     Except for input/output conversion and calculation functions
138     for user defined types, anything that can be defined in C language
139     functions can also be done with <application>PL/pgSQL</application>. It is possible to
140     create complex conditional computation functions and later use
141     them to define operators or use them in functional indexes.
142    </para>
143   <sect2 id="plpgsql-advantages">
144    <title>Advantages of Using <application>PL/pgSQL</application></title>
145
146    <itemizedlist>
147     <listitem>
148      <para>
149       Better performance (see <xref linkend="plpgsql-advantages-performance">)
150      </para>
151     </listitem>
152
153     <listitem>
154      <para>
155       SQL support (see <xref linkend="plpgsql-advantages-sqlsupport">)
156      </para>
157     </listitem> 
158
159     <listitem>
160      <para>
161       Portability (see <xref linkend="plpgsql-advantages-portability">)
162      </para>
163     </listitem>
164    </itemizedlist>
165
166    <sect3 id="plpgsql-advantages-performance">
167     <title>Better Performance</title>
168
169     <para>
170           <acronym>SQL</acronym> is the language
171           <productname>PostgreSQL</> (and most other relational databases)
172           use as query language. It's portable and easy to learn. But
173           every <acronym>SQL</acronym> statement must be executed
174           individually by the database server.
175     </para>
176
177     <para>
178      That means that your client application must send each query to
179      the database server, wait for it to process it, receive the
180      results, do some computation, then send other queries to the
181      server. All this incurs inter-process communication and may also
182      incur network overhead if your client is on a different machine
183      than the database server.
184     </para>
185
186     <para>
187      With <application>PL/pgSQL</application> you can group a block of computation and a
188      series of queries <emphasis>inside</emphasis> the
189      database server, thus having the power of a procedural
190      language and the ease of use of SQL, but saving lots of
191      time because you don't have the whole client/server
192      communication overhead. This can make for a
193      considerable performance increase.
194     </para>
195    </sect3>
196
197    <sect3 id="plpgsql-advantages-sqlsupport">
198     <title>SQL Support</title>
199
200     <para>
201      <application>PL/pgSQL</application> adds the power of a procedural language to the
202      flexibility and ease of <acronym>SQL</acronym>. With
203      <application>PL/pgSQL</application> you can use all the data types, columns, operators
204      and functions of SQL.    
205     </para>
206    </sect3>
207
208    <sect3 id="plpgsql-advantages-portability">
209     <title>Portability</title>
210
211     <para>
212           Because <application>PL/pgSQL</application> functions run inside
213           <productname>PostgreSQL</>, these functions will run on any
214           platform where <productname>PostgreSQL</> runs. Thus you can
215           reuse code and reduce development costs.
216     </para>
217    </sect3>
218   </sect2>
219
220   <sect2 id="plpgsql-overview-developing-in-plpgsql">
221    <title>Developing in <application>PL/pgSQL</application></title>
222
223    <para>
224     Developing in <application>PL/pgSQL</application> is pretty straight forward, especially
225     if you have developed in other database procedural languages,
226     such as Oracle's <application>PL/SQL</application>. Two good ways of developing in
227     <application>PL/pgSQL</application> are:
228
229     <itemizedlist>
230      <listitem>
231       <para>
232        Using a text editor and reloading the file with <command>psql</command>
233       </para>
234      </listitem>
235
236      <listitem>
237       <para>
238        Using <productname>PostgreSQL</>'s GUI Tool: <application>PgAccess</>
239       </para>
240      </listitem>
241     </itemizedlist>
242    </para>
243
244    <para>
245          One good way to develop in <application>PL/pgSQL</> is to simply
246          use the text editor of your choice to create your functions, and
247          in another window, use <command>psql</command>
248          (<productname>PostgreSQL</>'s interactive monitor) to load those
249          functions. If you are doing it this way, it is a good idea to
250          write the function using <command>CREATE OR REPLACE
251          FUNCTION</>. That way you can reload the file to update the
252          function definition.  For example:
253 <programlisting>
254 CREATE OR REPLACE FUNCTION testfunc(INTEGER) RETURNS INTEGER AS '
255           ....
256 end;
257 ' LANGUAGE 'plpgsql';
258 </programlisting>
259    </para>
260
261    <para>
262     While running <command>psql</command>, you can load or reload such a
263     function definition file with
264 <programlisting>
265     \i filename.sql
266 </programlisting>
267     and then immediately issue SQL commands to test the function.
268    </para>
269
270    <para>
271     Another good way to develop in <application>PL/pgSQL</> is using
272     <productname>PostgreSQL</>'s GUI tool: <application>PgAccess</>. It does some
273     nice things for you, like escaping single-quotes, and making
274     it easy to recreate and debug functions.
275    </para>
276   </sect2>
277  </sect1>
278
279  <sect1 id="plpgsql-structure">
280   <title>Structure of <application>PL/pgSQL</application></title>
281
282     <para>
283      <application>PL/pgSQL</application> is a <emphasis>block
284      structured</emphasis> language.  The complete text of a function
285      definition must be a <firstterm>block</>. A block is defined as:
286
287 <synopsis>
288 <optional> &lt;&lt;label&gt;&gt; </optional>
289 <optional> DECLARE
290     <replaceable>declarations</replaceable> </optional>
291 BEGIN
292     <replaceable>statements</replaceable>
293 END;
294 </synopsis>
295     </para>
296
297     <para>
298      Any <firstterm>statement</> in the statement section of a block
299      can be a <firstterm>sub-block</>.  Sub-blocks can be used for
300      logical grouping or to localize variables to a small group
301      of statements.
302     </para>
303
304     <para>
305      The variables declared in the declarations section preceding a
306      block are initialized to their default values every time the
307      block is entered, not only once per function call. For example:
308 <programlisting>
309 CREATE FUNCTION somefunc() RETURNS INTEGER AS '
310 DECLARE
311    quantity INTEGER := 30;
312 BEGIN
313    RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 30
314    quantity := 50;
315    --
316    -- Create a sub-block
317    --
318    DECLARE
319       quantity INTEGER := 80;
320    BEGIN
321       RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 80
322    END;
323
324    RAISE NOTICE ''Quantity here is %'',quantity;  -- Quantity here is 50
325
326    RETURN quantity;
327 END;
328 ' LANGUAGE 'plpgsql';
329 </programlisting>
330     </para>
331
332     <para>
333      It is important not to confuse the use of BEGIN/END for
334      grouping statements in <application>PL/pgSQL</> with the database commands for
335      transaction control.  <application>PL/pgSQL</>'s BEGIN/END are only for grouping;
336      they do not start or end a transaction.  Functions and trigger procedures
337      are always executed within a transaction established by an outer query
338      --- they cannot start or commit transactions, since
339      <productname>PostgreSQL</productname> does not have nested transactions.
340     </para>
341
342    <sect2>
343     <title>Lexical Details</title>
344
345     <para>
346      Each statement and declaration within a block is terminated
347      by a semicolon.
348     </para>
349
350     <para>
351      All keywords and identifiers can be written in mixed upper- and
352      lower-case.  Identifiers are implicitly converted to lower-case
353      unless double-quoted.
354     </para>
355
356     <para>
357      There are two types of comments in <application>PL/pgSQL</>. A double dash <literal>--</literal>
358      starts a comment that extends to the end of the line. A <literal>/*</literal>
359      starts a block comment that extends to the next occurrence of <literal>*/</literal>.
360      Block comments cannot be nested, but double dash comments can be
361      enclosed into a block comment and a double dash can hide
362      the block comment delimiters <literal>/*</literal> and <literal>*/</literal>.
363     </para>
364    </sect2>
365   </sect1>
366
367   <sect1 id="plpgsql-declarations">
368     <title>Declarations</title>
369
370     <para>
371      All variables, rows and records used in a block must be declared in the
372      declarations section of the block. 
373      (The only exception is that the loop variable of a FOR loop iterating
374      over a range of integer values is automatically declared as an integer
375      variable.)
376     </para>
377
378     <para>
379      <application>PL/pgSQL</> variables can have any SQL data type, such as
380      <type>INTEGER</type>, <type>VARCHAR</type> and
381      <type>CHAR</type>.
382     </para>
383
384     <para>
385      Here are some examples of variable declarations:
386 <programlisting>
387 user_id INTEGER;
388 quantity NUMERIC(5);
389 url VARCHAR;
390 myrow tablename%ROWTYPE;
391 myfield tablename.fieldname%TYPE;
392 arow RECORD;
393 </programlisting>
394     </para>
395
396     <para>
397      The general syntax of a variable declaration is:
398 <synopsis>
399 <replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
400 </synopsis>
401      </para>
402
403      <para>
404       The DEFAULT clause, if given, specifies the initial value assigned
405       to the variable when the block is entered.  If the DEFAULT clause
406       is not given then the variable is initialized to the
407      <acronym>SQL</acronym> NULL value. 
408      </para>
409
410      <para>
411       The CONSTANT option prevents the variable from being assigned to,
412       so that its value remains constant for the duration of the block.
413       If NOT NULL
414       is specified, an assignment of a NULL value results in a run-time
415       error. All variables declared as NOT NULL
416       must have a non-NULL default value specified.
417      </para>
418
419      <para>
420       The default value is evaluated every time the block is entered. So,
421       for example, assigning '<literal>now</literal>' to a variable of type
422       <type>timestamp</type> causes the variable to have the
423       time of the current function call, not when the function was
424       precompiled.
425      </para>
426
427      <para>
428       Examples:
429 <programlisting>
430 quantity INTEGER DEFAULT 32;
431 url varchar := ''http://mysite.com'';
432 user_id CONSTANT INTEGER := 10;
433 </programlisting>
434      </para>
435
436     <sect2 id="plpgsql-declaration-aliases">
437      <title>Aliases for Function Parameters</title>
438
439     <para>
440 <synopsis>
441 <replaceable>name</replaceable> ALIAS FOR <replaceable>$n</replaceable>;
442 </synopsis>
443     </para>
444
445      <para>
446       Parameters passed to functions are named with the identifiers
447       <literal>$1</literal>, <literal>$2</literal>,
448       etc.  Optionally, aliases can be declared for <literal>$n</literal>
449       parameter names for increased readability.  Either the alias or the
450       numeric identifier can then be used to refer to the parameter value.
451       Some examples:
452 <programlisting>
453 CREATE FUNCTION sales_tax(REAL) RETURNS REAL AS '
454 DECLARE
455     subtotal ALIAS FOR $1;
456 BEGIN
457     return subtotal * 0.06;
458 END;
459 ' LANGUAGE 'plpgsql';
460
461
462 CREATE FUNCTION instr(VARCHAR,INTEGER) RETURNS INTEGER AS '
463 DECLARE
464     v_string ALIAS FOR $1;
465     index ALIAS FOR $2;
466 BEGIN
467     -- Some computations here
468 END;
469 ' LANGUAGE 'plpgsql';
470
471
472 CREATE FUNCTION use_many_fields(tablename) RETURNS TEXT AS '
473 DECLARE
474     in_t ALIAS FOR $1;
475 BEGIN
476     RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
477 END;
478 ' LANGUAGE 'plpgsql';
479 </programlisting>
480      </para>
481     </sect2>
482
483     <sect2 id="plpgsql-declaration-rowtypes">
484      <title>Row Types</title>
485
486     <para>
487 <synopsis>
488 <replaceable>name</replaceable> <replaceable>tablename</replaceable><literal>%ROWTYPE</literal>;
489 </synopsis>
490     </para>
491
492    <para>
493     A variable of a composite type is called a <firstterm>row</>
494     variable (or <firstterm>row-type</> variable).  Such a variable can hold a
495     whole row of a SELECT or FOR
496     query result, so long as that query's column set matches the declared
497     type of the variable.  The individual fields of the row value are
498     accessed using the usual dot notation, for example
499     <literal>rowvar.field</literal>.
500    </para>
501
502    <para>
503     Presently, a row variable can only be declared using the
504     <literal>%ROWTYPE</literal> notation; although one might expect a
505     bare table name to work as a type declaration, it won't be accepted
506     within <application>PL/pgSQL</application> functions.
507    </para>
508
509    <para>
510     Parameters to a function can be
511     composite types (complete table rows). In that case, the
512     corresponding identifier $n will be a row variable, and fields can
513     be selected from it, for example <literal>$1.user_id</literal>.
514    </para>
515
516    <para>
517     Only the user-defined attributes of a table row are accessible in a
518     row-type variable, not OID or other system attributes (because the
519     row could be from a view).  The fields of the row type inherit the
520     table's field size or precision for data types such as
521     <type>char(n)</type>.
522 <programlisting>
523 CREATE FUNCTION use_two_tables(tablename) RETURNS TEXT AS '
524 DECLARE
525     in_t ALIAS FOR $1;
526     use_t table2name%ROWTYPE;
527 BEGIN
528     SELECT * INTO use_t FROM table2name WHERE ... ;
529     RETURN in_t.f1 || use_t.f3 || in_t.f5 || use_t.f7;
530 END;
531 ' LANGUAGE 'plpgsql';
532 </programlisting>
533    </para>
534   </sect2>
535
536     <sect2 id="plpgsql-declaration-records">
537      <title>Records</title>
538
539     <para>
540 <synopsis>
541 <replaceable>name</replaceable> RECORD;
542 </synopsis>
543     </para>
544
545    <para>
546     Record variables are similar to row-type variables, but they have no
547     predefined structure.  They take on the actual row structure of the
548     row they are assigned during a SELECT or FOR command.  The substructure
549     of a record variable can change each time it is assigned to.
550     A consequence of this is that until a record variable is first assigned
551     to, <emphasis>it has no</> substructure, and any attempt to access a
552     field in it will draw a run-time error.
553    </para>
554
555    <para>
556     Note that <literal>RECORD</> is not a true data type, only a placeholder.
557    </para>
558   </sect2>
559
560     <sect2 id="plpgsql-declaration-attributes">
561      <title>Attributes</title>
562
563      <para>
564       Using the <type>%TYPE</type> and <type>%ROWTYPE</type>
565       attributes, you can declare variables with the same
566       data type or structure as another database item (e.g: a
567       table field).
568      </para>
569
570      <variablelist>
571       <varlistentry>
572        <term>
573         <replaceable>variable</replaceable>%TYPE
574        </term>
575        <listitem>
576         <para>
577          <type>%TYPE</type> provides the data type of a
578          variable or database column. You can use this to
579          declare variables that will hold database
580          values. For example, let's say you have a column
581          named <type>user_id</type> in your
582          <type>users</type> table. To declare a variable with
583          the same data type as <structname>users</>.<structfield>user_id</> you write:
584 <programlisting>
585 user_id   users.user_id%TYPE;
586 </programlisting>
587         </para>
588
589         <para>
590          By using <type>%TYPE</type> you don't need to know
591          the data type of the structure you are referencing,
592          and most important, if the data type of the
593          referenced item changes in the future (e.g: you
594          change your table definition of user_id from INTEGER to
595          REAL), you may not need to change your function
596          definition.
597         </para>
598        </listitem>
599       </varlistentry>
600
601       <varlistentry>
602        <term>
603         <literal><replaceable>table</replaceable>%ROWTYPE</literal>
604        </term>
605        <listitem>
606         <para>
607          <type>%ROWTYPE</type> provides the composite data type corresponding
608          to a whole row of the specified table.
609          <replaceable>table</replaceable> must be an existing
610          table or view name of the database.
611         </para>
612
613 <programlisting>
614 DECLARE
615     users_rec users%ROWTYPE;
616     user_id users.user_id%TYPE;
617 BEGIN
618     user_id := users_rec.user_id;
619     ...
620
621 CREATE FUNCTION does_view_exist(INTEGER) RETURNS bool AS '
622    DECLARE
623         key ALIAS FOR $1;
624         table_data cs_materialized_views%ROWTYPE;
625    BEGIN
626         SELECT INTO table_data * FROM cs_materialized_views
627                WHERE sort_key=key;
628
629         IF NOT FOUND THEN
630            RETURN false;
631         END IF;
632         RETURN true;
633    END;
634 ' LANGUAGE 'plpgsql';
635 </programlisting>
636        </listitem>
637       </varlistentry>
638      </variablelist>
639     </sect2>
640
641     <sect2 id="plpgsql-declaration-renaming-vars">
642      <title>RENAME</title>
643
644      <para>
645 <synopsis>
646 RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
647 </synopsis>
648
649       Using the RENAME declaration you can change the name of a variable,
650       record or row. This is primarily useful if NEW or OLD should be
651       referenced by another name inside a trigger procedure.  See also ALIAS.
652      </para>
653
654      <para>
655       Examples:
656 <programlisting>
657 RENAME id TO user_id;
658 RENAME this_var TO that_var;
659 </programlisting>
660      </para>
661
662     <note>
663     <para>
664           RENAME appears to be broken as of <productname>PostgreSQL</>
665           7.3.  Fixing this is of low priority, since ALIAS covers most of
666           the practical uses of RENAME.
667     </para>
668     </note>
669
670     </sect2>
671   </sect1>
672
673   <sect1 id="plpgsql-expressions">
674   <title>Expressions</title>
675
676     <para>
677      All expressions used in <application>PL/pgSQL</application> statements
678      are processed using the server's regular SQL executor. Expressions that
679      appear to contain 
680      constants may in fact require run-time evaluation
681      (e.g. <literal>'now'</literal>  for the 
682      <type>timestamp</type> type) so
683      it is impossible for the <application>PL/pgSQL</application> parser
684      to identify real constant values other than the NULL keyword. All
685      expressions are evaluated internally by executing a query
686 <synopsis>
687 SELECT <replaceable>expression</replaceable>
688 </synopsis>
689      using the <acronym>SPI</acronym> manager. In the expression, occurrences
690      of <application>PL/pgSQL</application> variable 
691      identifiers are replaced by parameters and the actual values from
692      the variables are passed to the executor in the parameter array.
693      This allows the query plan for the SELECT to be prepared just once
694      and then re-used for subsequent evaluations.
695     </para>
696
697     <para>
698      The evaluation done by the <productname>PostgreSQL</productname>
699      main parser has some side
700      effects on the interpretation of constant values. In detail there
701      is a difference between what these two functions do:
702
703 <programlisting>
704 CREATE FUNCTION logfunc1 (TEXT) RETURNS TIMESTAMP AS '
705     DECLARE
706         logtxt ALIAS FOR $1;
707     BEGIN
708         INSERT INTO logtable VALUES (logtxt, ''now'');
709         RETURN ''now'';
710     END;
711 ' LANGUAGE 'plpgsql';
712 </programlisting>
713
714      and
715
716 <programlisting>
717 CREATE FUNCTION logfunc2 (TEXT) RETURNS TIMESTAMP AS '
718     DECLARE
719         logtxt ALIAS FOR $1;
720         curtime timestamp;
721     BEGIN
722         curtime := ''now'';
723         INSERT INTO logtable VALUES (logtxt, curtime);
724         RETURN curtime;
725     END;
726 ' LANGUAGE 'plpgsql';
727 </programlisting>
728
729      In the case of <function>logfunc1()</function>, the 
730      <productname>PostgreSQL</productname> main parser knows when 
731      preparing the plan for the INSERT, that the string 
732      <literal>'now'</literal> should be interpreted as 
733      <type>timestamp</type> because the target field of <classname>logtable</classname>
734      is of that type. Thus, it will make a constant from it at this
735      time and this constant value is then used in all invocations of 
736      <function>logfunc1()</function> during the lifetime of the
737      backend. Needless to say that this isn't what the
738      programmer wanted.
739     </para>
740
741     <para>
742      In the case of <function>logfunc2()</function>, the 
743      <productname>PostgreSQL</productname> main parser does not know
744      what type <literal>'now'</literal> should become and therefore 
745      it returns a data value of type <type>text</type> containing the string 
746      <literal>'now'</literal>. During the ensuing assignment
747      to the local variable <varname>curtime</varname>, the
748      <application>PL/pgSQL</application> interpreter casts this
749      string to the <type>timestamp</type> type by calling the
750      <function>text_out()</function> and <function>timestamp_in()</function>
751      functions for the conversion.  So, the computed time stamp is updated
752      on each execution as the programmer expects.
753     </para>
754
755     <para>
756      The mutable nature of record variables presents a problem in this
757      connection.  When fields of a record variable are used in
758      expressions or statements, the data types of the fields must not
759      change between calls of one and the same expression, since the
760      expression will be planned using the data type that is present
761      when the expression is first reached.  Keep this in mind when
762      writing trigger procedures that handle events for more than one
763      table.  (<command>EXECUTE</command> can be used to get around
764      this problem when necessary.)
765     </para>
766   </sect1>
767
768   <sect1 id="plpgsql-statements">
769   <title>Basic Statements</title>
770
771    <para>
772     In this section and the following ones, we describe all the statement
773     types that are explicitly understood by
774     <application>PL/pgSQL</application>.
775     Anything not recognized as one of these statement types is presumed
776     to be an SQL query, and is sent to the main database engine to execute
777     (after substitution for any <application>PL/pgSQL</application> variables
778     used in the statement).  Thus,
779     for example, SQL <command>INSERT</>, <command>UPDATE</>, and
780     <command>DELETE</> commands may be considered to be statements of
781     <application>PL/pgSQL</application>.  But they are not specifically
782     listed here.
783    </para>
784    
785    <sect2 id="plpgsql-statements-assignment">
786     <title>Assignment</title>
787
788     <para>
789      An assignment of a value to a variable or row/record field is
790      written as:
791 <synopsis>
792 <replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
793 </synopsis>
794      As explained above, the expression in such a statement is evaluated
795      by means of an SQL <command>SELECT</> command sent to the main
796      database engine.  The expression must yield a single value.
797     </para>
798
799     <para>
800      If the expression's result data type doesn't match the variable's
801      data type, or the variable has a specific size/precision
802      (like <type>char(20)</type>), the result value will be implicitly
803      converted by the <application>PL/pgSQL</application> interpreter using
804      the result type's output-function and 
805      the variable type's input-function. Note that this could potentially
806      result in run-time errors generated by the input function, if the
807      string form of the result value is not acceptable to the input function.
808     </para>
809
810     <para>
811      Examples:
812 <programlisting>
813 user_id := 20;
814 tax := subtotal * 0.06;
815 </programlisting>
816     </para>
817    </sect2>
818
819    <sect2 id="plpgsql-select-into">
820     <title>SELECT INTO</title>
821
822     <para>
823      The result of a SELECT command yielding multiple columns (but
824      only one row) can be assigned to a record variable, row-type
825      variable, or list of scalar variables.  This is done by:
826
827 <synopsis>
828 SELECT INTO <replaceable>target</replaceable> <replaceable>expressions</replaceable> FROM ...;
829 </synopsis>
830
831      where <replaceable>target</replaceable> can be a record variable, a row
832      variable, or a comma-separated list of simple variables and
833      record/row fields. Note that this is quite different from
834      <productname>PostgreSQL</>'s normal interpretation of SELECT INTO, which is that the
835      INTO target is a newly created table.  (If you want to create a
836      table from a SELECT result inside a <application>PL/pgSQL</application> function, use the
837      syntax <command>CREATE TABLE ... AS SELECT</command>.)
838     </para>
839
840     <para>
841      If a row or a variable list is used as target, the selected values
842      must exactly match the structure of the target(s), or a run-time error
843      occurs.  When a record variable is the target, it automatically
844      configures itself to the row type of the query result columns.
845     </para>
846
847     <para>
848      Except for the INTO clause, the SELECT statement is the same as a normal
849      SQL SELECT query and can use the full power of SELECT.
850     </para>
851
852     <para>
853      If the SELECT query returns zero rows, null values are assigned to the
854      target(s).  If the SELECT query returns multiple rows, the first
855      row is assigned to the target(s) and the rest are discarded.
856      (Note that <quote>the first row</> is not well-defined unless you've
857      used ORDER BY.)
858     </para>
859
860     <para>
861      At present, the INTO clause can appear almost anywhere in the SELECT
862      query, but it is recommended to place it immediately after the SELECT
863      keyword as depicted above.  Future versions of
864      <application>PL/pgSQL</application> may be less forgiving about
865      placement of the INTO clause.
866     </para>
867
868     <para>
869      You can use <literal>FOUND</literal> immediately after a SELECT
870      INTO statement to determine whether the assignment was successful
871      (that is, at least one row was was returned by the SELECT
872      statement). For example:
873   
874 <programlisting>
875 SELECT INTO myrec * FROM EMP WHERE empname = myname;
876 IF NOT FOUND THEN
877     RAISE EXCEPTION ''employee % not found'', myname;
878 END IF;
879 </programlisting>
880
881      Alternatively, you can use the <literal>IS NULL</literal> (or <literal>ISNULL</>) conditional to
882      test for whether a RECORD/ROW result is null.  Note that there is no
883      way to tell whether any additional rows might have been discarded.
884     </para>
885
886     <para>
887 <programlisting>
888 DECLARE
889     users_rec RECORD;
890     full_name varchar;
891 BEGIN
892     SELECT INTO users_rec * FROM users WHERE user_id=3;
893
894     IF users_rec.homepage IS NULL THEN
895         -- user entered no homepage, return "http://"
896
897         RETURN ''http://'';
898     END IF;
899 END;
900 </programlisting>
901     </para>
902    </sect2>
903
904    <sect2 id="plpgsql-statements-perform">
905     <title>Executing an expression or query with no result</title>
906
907     <para>
908      Sometimes one wishes to evaluate an expression or query but
909      discard the result (typically because one is calling a function
910      that has useful side-effects but no useful result value).  To do
911      this in <application>PL/pgSQL</application>, use the
912      <command>PERFORM</command> statement:
913
914 <synopsis>
915 PERFORM <replaceable>query</replaceable>;
916 </synopsis>
917
918      This executes a <command>SELECT</command>
919      <replaceable>query</replaceable> and discards the
920      result. <application>PL/pgSQL</application> variables are
921      substituted in the query as usual.  Also, the special variable
922      <literal>FOUND</literal> is set to true if the query produced at
923      least one row, or false if it produced no rows.
924     </para>
925
926     <note>
927          <para>
928           One might expect that <command>SELECT</command> with no INTO
929           clause would accomplish this result, but at present the only
930           accepted way to do it is <command>PERFORM</command>.
931          </para>
932         </note>
933
934     <para>
935      An example:
936 <programlisting>
937 PERFORM create_mv(''cs_session_page_requests_mv'', my_query);
938 </programlisting>
939     </para>
940    </sect2>
941    
942    <sect2 id="plpgsql-statements-executing-dyn-queries">
943     <title>Executing dynamic queries</title>
944     
945     <para>
946      Oftentimes you will want to generate dynamic queries inside your
947      <application>PL/pgSQL</application> functions, that is, queries
948      that will involve different tables or different data types each
949      time they are executed.  <application>PL/pgSQL</application>'s
950      normal attempts to cache plans for queries will not work in such
951      scenarios.  To handle this sort of problem, the
952      <command>EXECUTE</command> statement is provided:
953
954 <synopsis>
955 EXECUTE <replaceable class="command">query-string</replaceable>;
956 </synopsis>
957
958      where <replaceable>query-string</replaceable> is an expression
959      yielding a string (of type
960      <type>text</type>) containing the <replaceable>query</replaceable>
961      to be executed.  This string is fed literally to the SQL engine.
962     </para>
963
964     <para>
965      Note in particular that no substitution of <application>PL/pgSQL</>
966      variables is done on the query string.  The values of variables must
967      be inserted in the query string as it is constructed.
968     </para>
969
970     <para>
971     When working with dynamic queries you will have to face
972     escaping of single quotes in <application>PL/pgSQL</>. Please refer to the
973     table in <xref linkend="plpgsql-porting">
974     for a detailed explanation that will save you some effort.
975     </para>
976      
977     <para>
978      Unlike all other queries in <application>PL/pgSQL</>, a
979      <replaceable>query</replaceable> run by an
980      <command>EXECUTE</command> statement is not prepared and saved
981      just once during the life of the server.  Instead, the
982      <replaceable>query</replaceable> is prepared each time the
983      statement is run. The <replaceable>query-string</replaceable> can
984      be dynamically created within the procedure to perform actions on
985      variable tables and fields.
986     </para>
987   
988     <para>
989      The results from <command>SELECT</command> queries are discarded
990      by <command>EXECUTE</command>, and <command>SELECT INTO</command>
991      is not currently supported within <command>EXECUTE</command>.
992      So, the only way to extract a result from a dynamically-created
993      <command>SELECT</command> is to use the FOR-IN-EXECUTE form
994      described later.
995     </para>
996
997     <para>
998      An example:
999 <informalexample>
1000 <programlisting>
1001 EXECUTE ''UPDATE tbl SET ''
1002         || quote_ident(fieldname)
1003         || '' = ''
1004         || quote_literal(newvalue)
1005         || '' WHERE ...'';
1006 </programlisting>
1007 </informalexample>
1008     </para>
1009
1010     <para>
1011      This example shows use of the functions
1012      <function>quote_ident</function>(<type>TEXT</type>) and
1013      <function>quote_literal</function>(<type>TEXT</type>).
1014      Variables containing field and table identifiers should be
1015      passed to function <function>quote_ident()</function>.
1016      Variables containing literal elements of the dynamic query
1017      string should be passed to
1018      <function>quote_literal()</function>.  Both take the
1019      appropriate steps to return the input text enclosed in single
1020      or double quotes and with any embedded special characters
1021      properly escaped.
1022     </para>
1023
1024     <para>
1025      Here is a much larger example of a dynamic query and
1026      <command>EXECUTE</command>:
1027 <programlisting>
1028 CREATE FUNCTION cs_update_referrer_type_proc() RETURNS INTEGER AS '
1029 DECLARE
1030     referrer_keys RECORD;  -- Declare a generic record to be used in a FOR
1031     a_output varchar(4000);
1032 BEGIN 
1033     a_output := ''CREATE FUNCTION cs_find_referrer_type(varchar,varchar,varchar) 
1034                   RETURNS VARCHAR AS '''' 
1035                      DECLARE 
1036                          v_host ALIAS FOR $1; 
1037                          v_domain ALIAS FOR $2; 
1038                          v_url ALIAS FOR $3;
1039                      BEGIN ''; 
1040
1041     -- 
1042     -- Notice how we scan through the results of a query in a FOR loop
1043     -- using the FOR &lt;record&gt; construct.
1044     --
1045
1046     FOR referrer_keys IN SELECT * FROM cs_referrer_keys ORDER BY try_order LOOP
1047         a_output := a_output || '' IF v_'' || referrer_keys.kind || '' LIKE '''''''''' 
1048                  || referrer_keys.key_string || '''''''''' THEN RETURN '''''' 
1049                  || referrer_keys.referrer_type || ''''''; END IF;''; 
1050     END LOOP; 
1051   
1052     a_output := a_output || '' RETURN NULL; END; '''' LANGUAGE ''''plpgsql'''';''; 
1053  
1054     -- This works because we are not substituting any variables
1055     -- Otherwise it would fail. Look at PERFORM for another way to run functions
1056     
1057     EXECUTE a_output; 
1058 END; 
1059 ' LANGUAGE 'plpgsql';
1060 </programlisting>
1061     </para>
1062    </sect2>
1063
1064    <sect2 id="plpgsql-statements-diagnostics">
1065     <title>Obtaining result status</title>
1066
1067     <para>
1068          There are several ways to determine the effect of a command. The
1069          first method is to use the <literal>GET DIAGNOSTICS</literal>,
1070          which has the form:
1071
1072 <synopsis>
1073 GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional> ;
1074 </synopsis>
1075
1076      This command allows retrieval of system status indicators.  Each
1077      <replaceable>item</replaceable> is a keyword identifying a state
1078      value to be assigned to the specified variable (which should be
1079      of the right data type to receive it).  The currently available
1080      status items are <varname>ROW_COUNT</>, the number of rows
1081      processed by the last <acronym>SQL</acronym> query sent down to
1082      the <acronym>SQL</acronym> engine; and <varname>RESULT_OID</>,
1083      the OID of the last row inserted by the most recent
1084      <acronym>SQL</acronym> query.  Note that <varname>RESULT_OID</>
1085      is only useful after an INSERT query.
1086     </para>
1087     <para>
1088 <informalexample>
1089 <programlisting>
1090       GET DIAGNOSTICS var_integer = ROW_COUNT;
1091 </programlisting>
1092 </informalexample>
1093     </para>
1094
1095     <para>
1096      There is a special variable named <literal>FOUND</literal> of
1097      type <type>boolean</type>.  <literal>FOUND</literal> starts out
1098      false within each <application>PL/pgSQL</application> function.
1099      It is set by each of the following types of statements:
1100          <itemizedlist>
1101           <listitem>
1102            <para>
1103                 A SELECT INTO statement sets <literal>FOUND</literal>
1104                 true if it returns a row, false if no row is returned.
1105            </para>
1106           </listitem>
1107           <listitem>
1108            <para>
1109                 A PERFORM statement sets <literal>FOUND</literal>
1110                 true if it produces (discards) a row, false if no row is
1111                 produced.
1112            </para>
1113           </listitem>
1114           <listitem>
1115            <para>
1116                 UPDATE, INSERT, and DELETE statements set
1117                 <literal>FOUND</literal> true if at least one row is
1118                 affected, false if no row is affected.
1119            </para>
1120           </listitem>
1121           <listitem>
1122            <para>
1123                 A FETCH statement sets <literal>FOUND</literal>
1124                 true if it returns a row, false if no row is returned.
1125            </para>
1126           </listitem>
1127           <listitem>
1128            <para>
1129                 A FOR statement sets <literal>FOUND</literal>
1130                 true if it iterates one or more times, else false.
1131                 This applies to all three variants of the FOR statement
1132                 (integer FOR loops, record-set FOR loops, and dynamic
1133                 record-set FOR loops). <literal>FOUND</literal> is only set
1134                 when the FOR loop exits: inside the execution of the loop,
1135                 <literal>FOUND</literal> is not modified by the FOR statement,
1136                 although it may be changed by the execution of other
1137                 statements within the loop body.
1138            </para>
1139           </listitem>
1140          </itemizedlist>
1141      <literal>FOUND</literal> is a local variable; any changes
1142      to it affect only the current <application>PL/pgSQL</application>
1143      function.
1144     </para>
1145
1146    </sect2>
1147   </sect1>
1148
1149   <sect1 id="plpgsql-control-structures">
1150    <title>Control Structures</title>
1151
1152    <para>
1153     Control structures are probably the most useful (and
1154     important) part of <application>PL/pgSQL</>. With
1155     <application>PL/pgSQL</>'s control structures,
1156     you can manipulate <productname>PostgreSQL</> data in a very
1157     flexible and powerful way. 
1158    </para>
1159    
1160    <sect2 id="plpgsql-statements-returning">
1161     <title>Returning from a function</title>
1162
1163     <para>
1164 <synopsis>
1165 RETURN <replaceable>expression</replaceable>;
1166 </synopsis>
1167
1168      <command>RETURN</command> with an expression is used to return
1169      from a <application>PL/pgSQL</> function that does not return a
1170      set.  The function terminates and the value of
1171      <replaceable>expression</replaceable> is returned to the caller.
1172     </para>
1173
1174     <para>
1175      To return a composite (row) value, you must write a record or row
1176      variable as the <replaceable>expression</replaceable>.  When
1177      returning a scalar type, any expression can be used.
1178      The expression's result will be automatically cast into the
1179      function's return type as described for assignments.
1180      (If you have declared the function to return <type>void</>,
1181      then the expression can be omitted, and will be ignored in any case.)
1182     </para>
1183
1184     <para>
1185      The return value of a function cannot be left undefined. If
1186      control reaches the end of the top-level block of the function
1187      without hitting a <command>RETURN</command> statement, a run-time
1188      error will occur.
1189     </para>
1190
1191     <para>
1192      When a <application>PL/pgSQL</> function is declared to return
1193      <literal>SETOF</literal> <replaceable>sometype</>, the procedure
1194      to follow is slightly different.  In that case, the individual
1195      items to return are specified in <command>RETURN NEXT</command>
1196      commands, and then a final <command>RETURN</command> command with
1197      no arguments is used to indicate that the function has finished
1198      executing.  <command>RETURN NEXT</command> can be used with both
1199      scalar and composite data types; in the later case, an entire
1200      "table" of results will be returned.  Functions that use
1201      <command>RETURN NEXT</command> should be called in the following
1202      fashion:
1203
1204 <programlisting>
1205 SELECT * FROM some_func();
1206 </programlisting>
1207
1208      That is, the function is used as a table source in a FROM clause.
1209
1210 <synopsis>
1211 RETURN NEXT <replaceable>expression</replaceable>;
1212 </synopsis>
1213
1214      <command>RETURN NEXT</command> does not actually return from the
1215      function; it simply saves away the value of the expression (or
1216      record or row variable, as appropriate for the data type being
1217      returned).  Execution then continues with the next statement in
1218      the <application>PL/pgSQL</> function.  As successive
1219      <command>RETURN NEXT</command> commands are executed, the result
1220      set is built up.  A final <command>RETURN</commmand>, which need
1221      have no argument, causes control to exit the function.
1222     </para>
1223
1224    <note>
1225     <para>
1226      The current implementation of <command>RETURN NEXT</command> for
1227      <application>PL/pgSQL</> stores the entire result set before
1228      returning from the function, as discussed above.  That means that
1229      if a <application>PL/pgSQL</> function produces a very large result set,
1230      performance may be poor: data will be written to disk to avoid
1231      memory exhaustion, but the function itself will not return until
1232      the entire result set has been generated.  A future version of
1233      <application>PL/pgSQL</> may allow users to allow users to define set-returning
1234      functions that do not have this limitation.  Currently, the point
1235      at which data begins being written to disk is controlled by the
1236      <varname>SORT_MEM</> configuration variable.  Administrators who
1237      have sufficient memory to store larger result sets in memory
1238      should consider increasing this parameter.
1239     </para>
1240    </note>
1241   </sect2>
1242     
1243    <sect2 id="plpgsql-conditionals">
1244     <title>Conditionals</title>
1245
1246     <para>
1247      <literal>IF</> statements let you execute commands based on
1248      certain conditions.  <application>PL/pgSQL</> has four forms of
1249      <literal>IF</>:
1250     <itemizedlist>
1251      <listitem>
1252       <para><literal>IF ... THEN</></>
1253      </listitem>
1254      <listitem>
1255       <para><literal>IF ... THEN ... ELSE</></>
1256      </listitem>
1257      <listitem>
1258       <para><literal>IF ... THEN ... ELSE IF</> and</>
1259      </listitem>
1260      <listitem>
1261       <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1262      </listitem>
1263     </itemizedlist>
1264     </para>
1265
1266     <sect3>
1267      <title><literal>IF-THEN</></title>
1268
1269        <para>
1270 <synopsis>
1271 IF <replaceable>boolean-expression</replaceable> THEN
1272     <replaceable>statements</replaceable>
1273 END IF;
1274 </synopsis>
1275
1276         IF-THEN statements are the simplest form of IF. The
1277         statements between THEN and END IF will be executed if
1278         the condition is true. Otherwise, they are skipped.
1279
1280 <programlisting>
1281 IF v_user_id &lt;&gt; 0 THEN
1282     UPDATE users SET email = v_email WHERE user_id = v_user_id;
1283 END IF;
1284 </programlisting>
1285        </para>
1286      </sect3>
1287
1288      <sect3>
1289       <title><literal>IF-THEN-ELSE</></title>
1290
1291        <para>
1292 <synopsis>
1293 IF <replaceable>boolean-expression</replaceable> THEN
1294     <replaceable>statements</replaceable>
1295 ELSE
1296     <replaceable>statements</replaceable>
1297 END IF;
1298 </synopsis>
1299
1300         IF-THEN-ELSE statements add to IF-THEN by letting you
1301         specify an alternative set of statements that should be executed if
1302         the condition evaluates to FALSE.
1303
1304 <programlisting>
1305 IF parentid IS NULL or parentid = ''''
1306 THEN 
1307     return fullname;
1308 ELSE
1309     return hp_true_filename(parentid) || ''/'' || fullname;
1310 END IF;
1311
1312
1313 IF v_count > 0 THEN 
1314     INSERT INTO users_count(count) VALUES(v_count);
1315     return ''t'';
1316 ELSE 
1317     return ''f'';
1318 END IF;
1319 </programlisting>
1320        </para>
1321      </sect3>
1322
1323      <sect3>
1324       <title><literal>IF-THEN-ELSE IF</></title>
1325
1326        <para>
1327         IF statements can be nested, as in the following example:
1328 <programlisting>
1329 IF demo_row.sex = ''m'' THEN
1330   pretty_sex := ''man'';
1331 ELSE
1332   IF demo_row.sex = ''f'' THEN
1333     pretty_sex := ''woman'';
1334   END IF;
1335 END IF;
1336 </programlisting>
1337        </para>
1338
1339        <para>
1340         When you use this form, you are actually
1341         nesting an IF statement inside the ELSE part of an outer IF
1342         statement. Thus you need one END IF statement for each
1343         nested IF and one for the parent IF-ELSE.
1344         This is workable but grows tedious when there are many
1345         alternatives to be checked.
1346        </para>
1347      </sect3>
1348
1349      <sect3>
1350       <title><literal>IF-THEN-ELSIF-ELSE</></title>
1351
1352        <para>
1353 <synopsis>
1354 IF <replaceable>boolean-expression</replaceable> THEN
1355     <replaceable>statements</replaceable>
1356 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1357     <replaceable>statements</replaceable>
1358 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1359     <replaceable>statements</replaceable>
1360     ...
1361 </optional>
1362 </optional>
1363 <optional> ELSE
1364     <replaceable>statements</replaceable> </optional>
1365 END IF;
1366 </synopsis>
1367
1368         <literal>IF-THEN-ELSIF-ELSE</> provides a more convenient
1369         method of checking many alternatives in one statement.
1370         Formally it is equivalent to nested
1371         <literal>IF-THEN-ELSE-IF-THEN</> commands, but only one
1372         <literal>END IF</> is needed.
1373        </para>
1374
1375        <para>
1376         Here is an example:
1377
1378 <programlisting>
1379 IF number = 0 THEN
1380     result := ''zero'';
1381 ELSIF number &gt; 0 THEN 
1382     result := ''positive'';
1383 ELSIF number &lt; 0 THEN
1384     result := ''negative'';
1385 ELSE
1386     -- hmm, the only other possibility is that number IS NULL
1387     result := ''NULL'';
1388 END IF;
1389 </programlisting>
1390        </para>
1391
1392        <para>
1393         The final ELSE section is optional.
1394        </para>
1395
1396      </sect3>
1397    </sect2>
1398
1399    <sect2 id="plpgsql-control-structures-loops">
1400     <title>Simple Loops</title>
1401
1402     <para>
1403      With the LOOP, EXIT, WHILE and FOR statements, you can arrange
1404      for your <application>PL/pgSQL</application> function to repeat
1405      a series of commands.
1406     </para>
1407
1408      <sect3>
1409       <title>LOOP</title>
1410
1411        <para>
1412 <synopsis>
1413 <optional>&lt;&lt;label&gt;&gt;</optional>
1414 LOOP
1415     <replaceable>statements</replaceable>
1416 END LOOP;
1417 </synopsis>
1418
1419         LOOP defines an unconditional loop that is repeated indefinitely
1420         until terminated by an EXIT or RETURN statement.
1421         The optional label can be used by
1422         EXIT statements in nested loops to specify which level of
1423         nesting should be terminated.
1424        </para>
1425      </sect3>
1426
1427      <sect3>
1428       <title>EXIT</title>
1429
1430        <para>
1431 <synopsis>
1432 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>expression</replaceable> </optional>;
1433 </synopsis>
1434
1435         If no <replaceable>label</replaceable> is given,
1436         the innermost loop is terminated and the
1437         statement following END LOOP is executed next.
1438         If <replaceable>label</replaceable> is given, it
1439         must be the label of the current or some outer level of nested loop
1440         or block. Then the named loop or block is terminated and control
1441         continues with the statement after the loop's/block's corresponding
1442         END.
1443        </para>
1444
1445        <para>
1446         If WHEN is present, loop exit occurs only if the specified condition
1447         is true, otherwise control passes to the statement after EXIT.
1448        </para>
1449
1450        <para>
1451         Examples:
1452 <programlisting>
1453 LOOP
1454     -- some computations
1455     IF count > 0 THEN
1456         EXIT;  -- exit loop
1457     END IF;
1458 END LOOP;
1459
1460 LOOP
1461     -- some computations
1462     EXIT WHEN count > 0;
1463 END LOOP;
1464
1465 BEGIN
1466     -- some computations
1467     IF stocks > 100000 THEN
1468         EXIT;  -- illegal. Can't use EXIT outside of a LOOP
1469     END IF;
1470 END;
1471 </programlisting>
1472        </para>
1473      </sect3>
1474
1475      <sect3>
1476       <title>WHILE</title>
1477
1478        <para>
1479 <synopsis>
1480 <optional>&lt;&lt;label&gt;&gt;</optional>
1481 WHILE <replaceable>expression</replaceable> LOOP
1482     <replaceable>statements</replaceable>
1483 END LOOP;
1484 </synopsis>
1485
1486         The WHILE statement repeats a
1487         sequence of statements so long as the condition expression
1488         evaluates to true.  The condition is checked just before
1489         each entry to the loop body.
1490        </para>
1491
1492        <para>
1493         For example:
1494 <programlisting>
1495 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
1496     -- some computations here
1497 END LOOP;
1498
1499 WHILE NOT boolean_expression LOOP
1500     -- some computations here
1501 END LOOP;
1502 </programlisting>
1503        </para>
1504      </sect3>
1505
1506      <sect3>
1507       <title>FOR (integer for-loop)</title>
1508
1509        <para>
1510 <synopsis>
1511 <optional>&lt;&lt;label&gt;&gt;</optional>
1512 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
1513     <replaceable>statements</replaceable>
1514 END LOOP;
1515 </synopsis>
1516
1517         This form of FOR creates a loop that iterates over a range of integer
1518         values. The variable 
1519         <replaceable>name</replaceable> is automatically defined as type
1520         integer and exists only inside the loop. The two expressions giving
1521         the lower and upper bound of the range are evaluated once when entering
1522         the loop. The iteration step is normally 1, but is -1 when REVERSE is
1523         specified.
1524        </para>
1525
1526        <para>
1527         Some examples of integer FOR loops:
1528 <programlisting>
1529 FOR i IN 1..10 LOOP
1530   -- some expressions here
1531
1532     RAISE NOTICE ''i is %'',i;
1533 END LOOP;
1534
1535 FOR i IN REVERSE 10..1 LOOP
1536     -- some expressions here
1537 END LOOP;
1538 </programlisting>
1539        </para>
1540      </sect3>
1541    </sect2>
1542
1543    <sect2 id="plpgsql-records-iterating">
1544     <title>Looping Through Query Results</title>
1545
1546     <para>
1547      Using a different type of FOR loop, you can iterate through
1548      the results of a query and manipulate that data
1549      accordingly. The syntax is:
1550 <synopsis>
1551 <optional>&lt;&lt;label&gt;&gt;</optional>
1552 FOR <replaceable>record | row</replaceable> IN <replaceable>select_query</replaceable> LOOP
1553     <replaceable>statements</replaceable>
1554 END LOOP;
1555 </synopsis>
1556      The record or row variable is successively assigned all the rows 
1557      resulting from the SELECT query and the loop body is executed 
1558      for each row. Here is an example:
1559     </para>
1560
1561     <para>
1562 <programlisting>
1563 CREATE FUNCTION cs_refresh_mviews () RETURNS INTEGER AS '
1564 DECLARE
1565      mviews RECORD;
1566 BEGIN
1567      PERFORM cs_log(''Refreshing materialized views...'');
1568
1569      FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
1570
1571          -- Now "mviews" has one record from cs_materialized_views
1572
1573          PERFORM cs_log(''Refreshing materialized view '' || quote_ident(mviews.mv_name) || ''...'');
1574          EXECUTE ''TRUNCATE TABLE  '' || quote_ident(mviews.mv_name);
1575          EXECUTE ''INSERT INTO '' || quote_ident(mviews.mv_name) || '' '' || mviews.mv_query;
1576      END LOOP;
1577
1578      PERFORM cs_log(''Done refreshing materialized views.'');
1579      RETURN 1;
1580 end;
1581 ' LANGUAGE 'plpgsql';
1582 </programlisting>
1583
1584      If the loop is terminated by an EXIT statement, the last
1585      assigned row value is still accessible after the loop.
1586     </para>
1587
1588     <para>
1589      The FOR-IN-EXECUTE statement is another way to iterate over
1590      records:
1591 <synopsis>
1592 <optional>&lt;&lt;label&gt;&gt;</optional>
1593 FOR <replaceable>record | row</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> LOOP 
1594     <replaceable>statements</replaceable>
1595 END LOOP;
1596 </synopsis>
1597      This is like the previous form, except that the source
1598      <command>SELECT</command> statement is specified as a string
1599      expression, which is evaluated and re-planned on each entry to
1600      the FOR loop.  This allows the programmer to choose the speed of
1601      a pre-planned query or the flexibility of a dynamic query, just
1602      as with a plain <command>EXECUTE</command> statement.
1603     </para>
1604
1605     <note>
1606     <para>
1607      The <application>PL/pgSQL</> parser presently distinguishes the
1608      two kinds of FOR loops (integer or record-returning) by checking
1609      whether the target variable mentioned just after FOR has been
1610      declared as a record/row variable.  If not, it's presumed to be
1611      an integer FOR loop.  This can cause rather nonintuitive error
1612      messages when the true problem is, say, that one has
1613      misspelled the FOR variable name.
1614     </para>
1615     </note>
1616   </sect2>
1617   </sect1>
1618
1619   <sect1 id="plpgsql-cursors">
1620    <title>Cursors</title>
1621
1622    <para>
1623     Rather than executing a whole query at once, it is possible to set
1624     up a <firstterm>cursor</> that encapsulates the query, and then read
1625     the query result a few rows at a time. One reason for doing this is
1626     to avoid memory overrun when the result contains a large number of
1627     rows. (However, <application>PL/pgSQL</> users don't normally need
1628     to worry about that, since FOR loops automatically use a cursor
1629     internally to avoid memory problems.) A more interesting usage is to
1630     return a reference to a cursor that it has created, allowing the
1631     caller to read the rows. This provides an efficient way to return
1632     large row sets from functions.
1633    </para>
1634    
1635    <sect2 id="plpgsql-cursor-declarations">
1636     <title>Declaring Cursor Variables</title>
1637
1638     <para>
1639      All access to cursors in <application>PL/pgSQL</> goes through
1640      cursor variables, which are always of the special data type
1641      <type>refcursor</>.  One way to create a cursor variable
1642      is just to declare it as a variable of type <type>refcursor</>.
1643      Another way is to use the cursor declaration syntax,
1644      which in general is:
1645 <synopsis>
1646 <replaceable>name</replaceable> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>select_query</replaceable> ;
1647 </synopsis>
1648      (<literal>FOR</> may be replaced by <literal>IS</> for Oracle
1649      compatibility.)  <replaceable>arguments</replaceable>, if any,
1650      are a comma-separated list of <replaceable>name</replaceable>
1651      <replaceable>datatype</replaceable> pairs that define names to
1652      be replaced by parameter values in the given query.  The actual
1653      values to substitute for these names will be specified later,
1654      when the cursor is opened.
1655     </para>
1656     <para>
1657      Some examples:
1658 <programlisting>
1659 DECLARE
1660     curs1 refcursor;
1661     curs2 CURSOR FOR SELECT * from tenk1;
1662     curs3 CURSOR (key int) IS SELECT * from tenk1 where unique1 = key;
1663 </programlisting>
1664      All three of these variables have the data type <type>refcursor</>,
1665      but the first may be used with any query, while the second has
1666      a fully specified query already <firstterm>bound</> to it, and the last
1667      has a parameterized query bound to it.  (<literal>key</> will be
1668      replaced by an integer parameter value when the cursor is opened.)
1669      The variable <literal>curs1</>
1670      is said to be <firstterm>unbound</> since it is not bound to
1671      any particular query.
1672     </para>
1673    </sect2>
1674
1675    <sect2 id="plpgsql-cursor-opening">
1676     <title>Opening Cursors</title>
1677
1678     <para>
1679      Before a cursor can be used to retrieve rows, it must be
1680      <firstterm>opened</>. (This is the equivalent action to the SQL
1681      command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
1682      four forms of the OPEN statement, two of which use unbound cursor
1683      variables and the other two use bound cursor variables.
1684     </para>
1685
1686     <sect3>
1687      <title>OPEN FOR SELECT</title>
1688
1689        <para>
1690 <synopsis>
1691 OPEN <replaceable>unbound-cursor</replaceable> FOR SELECT ...;
1692 </synopsis>
1693
1694         The cursor variable is opened and given the specified query
1695         to execute.  The cursor cannot be open already, and it must
1696         have been declared as an unbound cursor (that is, as a simple
1697         <type>refcursor</> variable).  The SELECT query is treated
1698         in the same way as other SELECT statements in <application>PL/pgSQL</>:
1699         <application>PL/pgSQL</> variable names are substituted,
1700         and the query plan is cached for possible re-use.
1701
1702 <programlisting>
1703 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
1704 </programlisting>
1705        </para>
1706      </sect3>
1707
1708     <sect3>
1709      <title>OPEN FOR EXECUTE</title>
1710
1711          <para>
1712 <synopsis>
1713 OPEN <replaceable>unbound-cursor</replaceable> FOR EXECUTE <replaceable class="command">query-string</replaceable>;
1714 </synopsis>
1715
1716           The cursor variable is opened and given the specified query to
1717           execute.  The cursor cannot be open already, and it must have been
1718           declared as an unbound cursor (that is, as a simple
1719           <type>refcursor</> variable).  The query is specified as a string
1720           expression in the same way as in the <command>EXECUTE</command>
1721           command.  As usual, this gives flexibility so the query can vary
1722           from one run to the next.
1723
1724 <programlisting>
1725 OPEN curs1 FOR EXECUTE ''SELECT * FROM '' || quote_ident($1);
1726 </programlisting>
1727        </para>
1728      </sect3>
1729
1730     <sect3>
1731      <title>Opening a bound cursor</title>
1732
1733          <para>
1734 <synopsis>
1735 OPEN <replaceable>bound-cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
1736 </synopsis>
1737
1738           This form of <command>OPEN</command> is used to open a cursor
1739           variable whose query was bound to it when it was declared.  The
1740           cursor cannot be open already.  A list of actual argument value
1741           expressions must appear if and only if the cursor was declared to
1742           take arguments.  These values will be substituted in the query.
1743           The query plan for a bound cursor is always considered cacheable
1744           --- there is no equivalent of <command>EXECUTE</command> in this case.
1745
1746 <programlisting>
1747 OPEN curs2;
1748 OPEN curs3(42);
1749 </programlisting>
1750        </para>
1751      </sect3>
1752    </sect2>
1753
1754    <sect2 id="plpgsql-cursor-using">
1755     <title>Using Cursors</title>
1756
1757     <para>
1758      Once a cursor has been opened, it can be manipulated with the
1759      statements described here.
1760     </para>
1761
1762     <para>
1763      These manipulations need not occur in the same function that
1764      opened the cursor to begin with.  You can return a <type>refcursor</>
1765      value out of a function and let the caller operate on the cursor.
1766      (Internally, a <type>refcursor</> value is simply the string name
1767      of a Portal containing the active query for the cursor.  This name
1768      can be passed around, assigned to other <type>refcursor</> variables,
1769      and so on, without disturbing the Portal.)
1770     </para>
1771
1772     <para>
1773      All Portals are implicitly closed at transaction end.  Therefore
1774      a <type>refcursor</> value is useful to reference an open cursor
1775      only until the end of the transaction.
1776     </para>
1777
1778     <sect3>
1779      <title>FETCH</title>
1780
1781          <para>
1782 <synopsis>
1783 FETCH <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
1784 </synopsis>
1785
1786           <command>FETCH</command> retrieves the next row from the
1787           cursor into a target, which may be a row variable, a record
1788           variable, or a comma-separated list of simple variables, just like
1789           <command>SELECT INTO</command>.  As with <command>SELECT
1790            INTO</command>, the special variable <literal>FOUND</literal> may
1791           be checked to see whether a row was obtained or not.
1792
1793 <programlisting>
1794 FETCH curs1 INTO rowvar;
1795 FETCH curs2 INTO foo,bar,baz;
1796 </programlisting>
1797        </para>
1798      </sect3>
1799
1800     <sect3>
1801      <title>CLOSE</title>
1802
1803        <para>
1804 <synopsis>
1805 CLOSE <replaceable>cursor</replaceable>;
1806 </synopsis>
1807
1808         CLOSE closes the Portal underlying an open cursor.
1809         This can be used to release resources earlier than end of
1810         transaction, or to free up the cursor variable to be opened again.
1811
1812 <programlisting>
1813 CLOSE curs1;
1814 </programlisting>
1815        </para>
1816      </sect3>
1817  
1818     <sect3>
1819      <title>Returning Cursors</title>
1820
1821        <para>
1822
1823         <application>PL/pgSQL</> functions can return cursors to the
1824         caller. This is used to return multiple rows or columns from the
1825         function. The function opens the cursor and returns the cursor
1826         name to the caller. The caller can then FETCH rows from the
1827         cursor. The cursor can be closed by the caller, or it will be
1828         closed automatically when the transaction closes.
1829
1830        </para>
1831
1832        <para>
1833         The cursor name returned by the function can be specified by the
1834         caller or automatically generated. The following example shows
1835         how a cursor name can be supplied by the caller:
1836
1837 <programlisting>
1838 CREATE TABLE test (col text);
1839 INSERT INTO test VALUES ('123');
1840
1841 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
1842 BEGIN
1843         OPEN $1 FOR SELECT col FROM test;
1844         RETURN $1;
1845 END;
1846 ' LANGUAGE 'plpgsql';
1847
1848 BEGIN;
1849 SELECT reffunc('funccursor');
1850 FETCH ALL IN funccursor;
1851 COMMIT;
1852 </programlisting>
1853        </para>
1854
1855        <para>
1856         The following example uses automatic cursor name generation:
1857          
1858 <programlisting>
1859 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
1860 DECLARE
1861         ref refcursor;
1862 BEGIN
1863         OPEN ref FOR SELECT col FROM test;
1864         RETURN ref;
1865 END;
1866 ' LANGUAGE 'plpgsql';
1867
1868 BEGIN;
1869 SELECT reffunc2();
1870   
1871         reffunc2      
1872   --------------------
1873    &lt;unnamed cursor 1&gt;
1874   (1 row)
1875
1876 FETCH ALL IN "&lt;unnamed cursor 1&gt;";
1877 COMMIT;
1878 </programlisting>
1879        </para>
1880      </sect3>
1881    </sect2>
1882   </sect1>
1883
1884   <sect1 id="plpgsql-errors-and-messages">
1885    <title>Errors and Messages</title>
1886
1887    <para>
1888     Use the RAISE statement to report messages and raise errors.
1889
1890 <synopsis>
1891 RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">variable</replaceable> <optional>...</optional></optional>;
1892 </synopsis>
1893
1894     Possible levels are <literal>DEBUG</literal> (write the message to
1895     the server log), <literal>LOG</literal> (write the message to the
1896     server log with a higher priority), <literal>INFO</literal>,
1897     <literal>NOTICE</literal> and <literal>WARNING</literal> (write
1898     the message to the server log and send it to the client, with
1899     respectively higher priorities), and <literal>EXCEPTION</literal>
1900     (raise an error and abort the current transaction). Whether error
1901     messages of a particular priority are reported to the client,
1902     written to the server log, or both is controlled by the
1903     <option>SERVER_MIN_MESSAGES</option> and
1904     <option>CLIENT_MIN_MESSAGES</option> configuration variables. See
1905     the <citetitle>PostgreSQL Administrator's Guide</citetitle> for more
1906     information.
1907    </para>
1908
1909    <para>
1910     Inside the format string, <literal>%</literal> is replaced by the
1911     next optional argument's external representation. Write
1912     <literal>%%</literal> to emit a literal <literal>%</literal>. Note
1913     that the optional arguments must presently be simple variables,
1914     not expressions, and the format must be a simple string literal.
1915    </para>
1916
1917    <!--
1918    This example should work, but does not:
1919         RAISE NOTICE ''Id number '' || key || '' not found!'';
1920    Put it back when we allow non-string-literal formats.
1921     -->
1922
1923    <para>
1924     Examples:
1925 <programlisting>
1926 RAISE NOTICE ''Calling cs_create_job(%)'',v_job_id;
1927 </programlisting>
1928
1929     In this example, the value of v_job_id will replace the
1930     <literal>%</literal> in the string.
1931    </para>
1932
1933    <para>
1934 <programlisting>
1935 RAISE EXCEPTION ''Inexistent ID --> %'',user_id;
1936 </programlisting>
1937     This will abort the transaction with the given error message.
1938    </para>
1939
1940   <sect2 id="plpgsql-exceptions">
1941    <title>Exceptions</title>
1942
1943     <para>
1944      <productname>PostgreSQL</productname> does not have a very smart
1945      exception handling model. Whenever the parser, planner/optimizer
1946      or executor decide that a statement cannot be processed any longer,
1947      the whole transaction gets aborted and the system jumps back
1948      into the main loop to get the next query from the client application.
1949     </para>
1950
1951     <para>
1952      It is possible to hook into the error mechanism to notice that this
1953      happens. But currently it is impossible to tell what really
1954      caused the abort (input/output conversion error, floating-point
1955      error, parse error). And it is possible that the database backend
1956      is in an inconsistent state at this point so returning to the upper
1957      executor or issuing more commands might corrupt the whole database.
1958     </para>
1959
1960     <para>
1961      Thus, the only thing <application>PL/pgSQL</application>
1962      currently does when it encounters an abort during execution of a
1963      function or trigger procedure is to write some additional
1964      <literal>NOTICE</literal> level log messages telling in which
1965      function and where (line number and type of statement) this
1966      happened.  The error always stops execution of the function.
1967     </para>
1968   </sect2>
1969  </sect1>
1970
1971  <sect1 id="plpgsql-trigger">
1972   <title>Trigger Procedures</title>
1973
1974   <para>
1975         <application>PL/pgSQL</application> can be used to define trigger
1976         procedures. A trigger procedure is created with the
1977         <command>CREATE FUNCTION</> command as a function with no
1978         arguments and a return type of <type>TRIGGER</type>.  Note that
1979         the function must be declared with no arguments even if it expects
1980         to receive arguments specified in <command>CREATE TRIGGER</> ---
1981         trigger arguments are passed via <varname>TG_ARGV</>, as described
1982         below.
1983   </para>
1984
1985   <para>
1986    When a <application>PL/pgSQL</application> function is called as a
1987    trigger, several special variables are created automatically in the 
1988    top-level block. They are:
1989    
1990    <variablelist>
1991     <varlistentry>
1992      <term><varname>NEW</varname></term>
1993      <listitem>
1994       <para>
1995        Data type <type>RECORD</type>; variable holding the new database row for INSERT/UPDATE
1996        operations in ROW level triggers.
1997       </para>
1998      </listitem>
1999     </varlistentry>
2000
2001     <varlistentry>
2002      <term><varname>OLD</varname></term>
2003      <listitem>
2004       <para>
2005        Data type <type>RECORD</type>; variable holding the old database row for UPDATE/DELETE
2006        operations in ROW level triggers.
2007       </para>
2008      </listitem>
2009     </varlistentry>
2010
2011     <varlistentry>
2012      <term><varname>TG_NAME</varname></term>
2013      <listitem>
2014       <para>
2015        Data type <type>name</type>; variable that contains the name of the trigger actually
2016        fired.
2017       </para>
2018      </listitem>
2019     </varlistentry>
2020
2021     <varlistentry>
2022      <term><varname>TG_WHEN</varname></term>
2023      <listitem>
2024       <para>
2025        Data type <type>text</type>; a string of either 
2026               <literal>BEFORE</literal> or <literal>AFTER</literal> 
2027               depending on the trigger's definition.
2028       </para>
2029      </listitem>
2030     </varlistentry>
2031
2032     <varlistentry>
2033      <term><varname>TG_LEVEL</varname></term>
2034      <listitem>
2035       <para>
2036        Data type <type>text</type>; a string of either 
2037               <literal>ROW</literal> or <literal>STATEMENT</literal> depending on the
2038        trigger's definition.
2039       </para>
2040      </listitem>
2041     </varlistentry>
2042
2043     <varlistentry>
2044      <term><varname>TG_OP</varname></term>
2045      <listitem>
2046       <para>
2047        Data type <type>text</type>; a string of 
2048               <literal>INSERT</literal>, <literal>UPDATE</literal> 
2049               or <literal>DELETE</literal> telling
2050        for which operation the trigger is fired.
2051       </para>
2052      </listitem>
2053     </varlistentry>
2054
2055     <varlistentry>
2056      <term><varname>TG_RELID</varname></term>
2057      <listitem>
2058       <para>
2059        Data type <type>oid</type>; the object ID of the table that caused the
2060        trigger invocation.
2061       </para>
2062      </listitem>
2063     </varlistentry>
2064
2065     <varlistentry>
2066      <term><varname>TG_RELNAME</varname></term>
2067      <listitem>
2068       <para>
2069        Data type <type>name</type>; the name of the table that caused the trigger
2070        invocation.
2071       </para>
2072      </listitem>
2073     </varlistentry>
2074
2075     <varlistentry>
2076      <term><varname>TG_NARGS</varname></term>
2077      <listitem>
2078       <para>
2079        Data type <type>integer</type>; the number of arguments given to the trigger
2080        procedure in the <command>CREATE TRIGGER</command> statement.
2081       </para>
2082      </listitem>
2083     </varlistentry>
2084
2085     <varlistentry>
2086      <term><varname>TG_ARGV[]</varname></term>
2087      <listitem>
2088       <para>
2089        Data type array of <type>text</type>; the arguments from
2090               the <command>CREATE TRIGGER</command> statement.
2091        The index counts from 0 and can be given as an expression. Invalid
2092        indices (&lt; 0 or &gt;= <varname>tg_nargs</>) result in a null value.
2093       </para>
2094      </listitem>
2095     </varlistentry>
2096    </variablelist>
2097   </para>
2098
2099    <para>
2100     A trigger function must return either NULL or a record/row value
2101     having exactly the structure of the table the trigger was fired for.
2102     Triggers fired BEFORE may return NULL to signal the trigger manager
2103     to skip the rest of the operation for this row (ie, subsequent triggers
2104     are not fired, and the INSERT/UPDATE/DELETE does not occur for this
2105     row).  If a non-NULL value is returned then the operation proceeds with
2106     that row value.  Note that returning a row value different from the
2107     original value of NEW alters the row that will be inserted or updated.
2108     It is possible to replace single values directly
2109     in NEW and return that, or to build a complete new record/row to
2110     return.
2111    </para>
2112
2113    <para>
2114     The return value of a trigger fired AFTER is ignored; it may as well
2115     always return a NULL value.  But an AFTER trigger can still abort the
2116     operation by raising an error.
2117    </para>
2118
2119    <example>
2120     <title>A <application>PL/pgSQL</application> Trigger Procedure Example</title>
2121
2122     <para>
2123      This example trigger ensures that any time a row is inserted or updated
2124      in the table, the current user name and time are stamped into the
2125      row. And it ensures that an employee's name is given and that the
2126      salary is a positive value.
2127
2128 <programlisting>
2129 CREATE TABLE emp (
2130     empname text,
2131     salary integer,
2132     last_date timestamp,
2133     last_user text
2134 );
2135
2136 CREATE FUNCTION emp_stamp () RETURNS TRIGGER AS '
2137     BEGIN
2138         -- Check that empname and salary are given
2139         IF NEW.empname ISNULL THEN
2140             RAISE EXCEPTION ''empname cannot be NULL value'';
2141         END IF;
2142         IF NEW.salary ISNULL THEN
2143             RAISE EXCEPTION ''% cannot have NULL salary'', NEW.empname;
2144         END IF;
2145
2146         -- Who works for us when she must pay for?
2147         IF NEW.salary < 0 THEN
2148             RAISE EXCEPTION ''% cannot have a negative salary'', NEW.empname;
2149         END IF;
2150
2151         -- Remember who changed the payroll when
2152         NEW.last_date := ''now'';
2153         NEW.last_user := current_user;
2154         RETURN NEW;
2155     END;
2156 ' LANGUAGE 'plpgsql';
2157
2158 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
2159     FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
2160 </programlisting>
2161     </para>
2162    </example>
2163   </sect1>
2164
2165   <!-- **** PL/pgSQL Examples **** -->
2166
2167   <sect1 id="plpgsql-examples">
2168    <title>Examples</title>
2169
2170    <para>
2171     Here are only a few functions to demonstrate how easy it is to
2172     write <application>PL/pgSQL</>
2173     functions. For more complex examples the programmer
2174     might look at the regression test for <application>PL/pgSQL</>.
2175    </para>
2176
2177    <para>
2178     One painful detail in writing functions in
2179         <application>PL/pgSQL</application> is the handling of single
2180         quotes. The function's source text in <command>CREATE FUNCTION</>
2181         must be a literal string. Single quotes inside of literal strings
2182         must be either doubled or quoted with a backslash. We are still
2183         looking for an elegant alternative. In the meantime, doubling the
2184         single quotes as in the examples below should be used. Any
2185         solution for this in future versions of
2186         <productname>PostgreSQL</productname> will be forward compatible.
2187    </para>
2188
2189    <para>
2190     For a detailed explanation and examples of how to escape single
2191     quotes in different situations, please see <xref linkend="plpgsql-quote">.
2192    </para>
2193
2194    <example>
2195     <title>A Simple <application>PL/pgSQL</application> Function to Increment an Integer</title>
2196
2197     <para>
2198      The following two <application>PL/pgSQL</application> functions are identical to their
2199      counterparts from the C language function discussion. This
2200      function receives an <type>integer</type> and increments it by
2201      one, returning the incremented value.
2202     </para>
2203
2204 <programlisting>
2205 CREATE FUNCTION add_one (integer) RETURNS INTEGER AS '
2206     BEGIN
2207         RETURN $1 + 1;
2208     END;
2209 ' LANGUAGE 'plpgsql';
2210 </programlisting>
2211    </example>
2212
2213    <example>
2214     <title>A Simple <application>PL/pgSQL</application> Function to Concatenate Text</title>
2215
2216     <para>
2217      This function receives two <type>text</type> parameters and
2218      returns the result of concatenating them.
2219     </para>
2220
2221 <programlisting>
2222 CREATE FUNCTION concat_text (TEXT, TEXT) RETURNS TEXT AS '
2223     BEGIN
2224         RETURN $1 || $2;
2225     END;
2226 ' LANGUAGE 'plpgsql';
2227 </programlisting>
2228    </example>
2229
2230    <example>
2231     <title>A <application>PL/pgSQL</application> Function on Composite Type</title>
2232
2233     <para>
2234      In this example, we take <literal>EMP</> (a table) and an
2235      <type>integer</type> as arguments to our function, which returns
2236      a <type>boolean</type>. If the <structfield>salary</> field of the <structname>EMP</> table is
2237      <literal>NULL</literal>, we return <literal>f</>. Otherwise we compare with
2238      that field with the <type>integer</type> passed to the function
2239      and return the <type>boolean</type> result of the comparison (t
2240      or f). This is the <application>PL/pgSQL</application> equivalent to the example from the C
2241      functions.
2242     </para>
2243
2244 <programlisting>
2245 CREATE FUNCTION c_overpaid (EMP, INTEGER) RETURNS BOOLEAN AS '
2246     DECLARE
2247         emprec ALIAS FOR $1;
2248         sallim ALIAS FOR $2;
2249     BEGIN
2250         IF emprec.salary ISNULL THEN
2251             RETURN ''f'';
2252         END IF;
2253         RETURN emprec.salary > sallim;
2254     END;
2255 ' LANGUAGE 'plpgsql';
2256 </programlisting>
2257    </example>
2258   </sect1>
2259
2260   <!-- **** Porting from Oracle PL/SQL **** -->
2261
2262  <sect1 id="plpgsql-porting">
2263
2264   <sect1info>
2265    <date>
2266     February 2001
2267    </date>
2268    <author>
2269     <firstname>Roberto</firstname>
2270     <surname>Mello</surname>
2271     <affiliation>
2272      <address>
2273       <email>rmello@fslc.usu.edu</email>
2274      </address>
2275     </affiliation>
2276    </author>
2277 <!--
2278   Breaks HTML manifest file
2279    <legalnotice>
2280     <para>
2281      Except for portions of this document quoted from other sources,
2282      this document is licensed under the BSD License.
2283     </para>
2284    </legalnotice>
2285 -->
2286   </sect1info> 
2287
2288   <title>Porting from Oracle PL/SQL</title>
2289
2290   <indexterm zone="plpgsql-porting">
2291    <primary>Oracle</primary>
2292   </indexterm>
2293
2294   <indexterm zone="plpgsql-porting">
2295    <primary>PL/SQL</primary>
2296   </indexterm>
2297
2298   <note>
2299    <title>Author</title>
2300    <para>
2301     Roberto Mello (<email>rmello@fslc.usu.edu</email>)
2302    </para>
2303   </note>
2304
2305   <para>
2306    This section explains differences between Oracle's PL/SQL and
2307    <productname>PostgreSQL</>'s <application>PL/pgSQL</application> languages in the hopes of helping developers
2308    port applications from Oracle to <productname>PostgreSQL</>.  Most of the code here
2309    is from the <ulink url="http://www.arsdigita.com">ArsDigita</ulink>
2310    <ulink url="http://www.arsdigita.com/asj/clickstream">Clickstream
2311    module</ulink> that I ported to <productname>PostgreSQL</> when I took an
2312    internship with <ulink url="http://www.openforce.net">OpenForce
2313    Inc.</ulink> in the Summer of 2000.
2314   </para>
2315
2316   <para>
2317    <application>PL/pgSQL</application> is similar to PL/SQL in many aspects. It is a block
2318    structured, imperative language (all variables have to be
2319    declared). PL/SQL has many more features than its <productname>PostgreSQL</>
2320    counterpart, but <application>PL/pgSQL</application> allows for a great deal of functionality
2321    and it is being improved constantly.
2322   </para>
2323
2324   <sect2>
2325    <title>Main Differences</title>
2326
2327    <para>
2328     Some things you should keep in mind when porting from Oracle to <productname>PostgreSQL</>:
2329
2330     <itemizedlist>
2331      <listitem>
2332       <para>
2333        No default parameters in <productname>PostgreSQL</>.
2334       </para>
2335      </listitem>
2336
2337      <listitem>
2338       <para>
2339        You can overload functions in <productname>PostgreSQL</>. This is often used to work 
2340        around the lack of default parameters.
2341       </para>
2342      </listitem>
2343
2344      <listitem>
2345       <para>
2346        Assignments, loops and conditionals are similar. 
2347       </para>
2348      </listitem>
2349
2350      <listitem>
2351       <para>
2352        No need for cursors in <productname>PostgreSQL</>, just put the query in the FOR 
2353        statement (see example below)
2354       </para>
2355      </listitem>
2356
2357      <listitem>
2358       <para>
2359        In <productname>PostgreSQL</> you <emphasis>need</emphasis> to escape single
2360        quotes. See <xref linkend="plpgsql-quote">.
2361       </para>
2362      </listitem>
2363     </itemizedlist>
2364    </para>
2365
2366    <sect3 id="plpgsql-quote">
2367     <title>Quote Me on That: Escaping Single Quotes</title>
2368
2369     <para>
2370      In <productname>PostgreSQL</> you need to escape single quotes inside your
2371      function definition. This can lead to quite amusing code at
2372      times, especially if you are creating a function that generates
2373      other function(s), as in 
2374      <xref linkend="plpgsql-porting-nastyquote">.  
2375      One thing to keep in mind
2376      when escaping lots of single quotes is that, except for the
2377      beginning/ending quotes, all the others will come in even
2378      quantity.
2379     </para>
2380
2381     <para>
2382      <xref linkend="plpgsql-quoting-table"> gives the scoop.  (You'll
2383      love this little chart.)
2384     </para>
2385
2386     <table id="plpgsql-quoting-table">
2387      <title>Single Quotes Escaping Chart</title>
2388
2389      <tgroup cols="4">
2390       <thead>
2391        <row>
2392         <entry>No. of Quotes</entry>
2393         <entry>Usage</entry>
2394         <entry>Example</entry>
2395         <entry>Result</entry>
2396        </row>
2397       </thead>
2398
2399       <tbody>
2400        <row>
2401         <entry>1</entry>
2402         <entry>To begin/terminate function bodies</entry>
2403         <entry><programlisting>
2404 CREATE FUNCTION foo() RETURNS INTEGER AS '...'
2405 LANGUAGE 'plpgsql';
2406 </programlisting></entry>
2407         <entry>as is</entry>
2408        </row>
2409
2410        <row>
2411         <entry>2</entry>
2412         <entry>In assignments, SELECT statements, to delimit strings, etc.</entry>
2413         <entry><programlisting>
2414 a_output := ''Blah'';
2415 SELECT * FROM users WHERE f_name=''foobar'';
2416 </programlisting></entry>
2417         <entry><literal>SELECT * FROM users WHERE f_name='foobar';</literal></entry>
2418        </row>
2419
2420        <row>
2421         <entry>4</entry>
2422         <entry>
2423          When you need two single quotes in your resulting string
2424          without terminating that string.
2425         </entry>
2426         <entry><programlisting>
2427 a_output := a_output || '' AND name 
2428     LIKE ''''foobar'''' AND ...''
2429 </programlisting></entry>
2430         <entry><literal>AND name LIKE 'foobar' AND ...</literal></entry>
2431        </row>
2432
2433        <row>
2434         <entry>6</entry>
2435         <entry>
2436          When you want double quotes in your resulting string
2437          <emphasis>and</emphasis> terminate that string.
2438         </entry>
2439         <entry><programlisting>
2440 a_output := a_output || '' AND name 
2441     LIKE ''''foobar''''''
2442 </programlisting></entry>
2443         <entry>
2444          <literal>AND name LIKE 'foobar'</literal>
2445         </entry>
2446        </row>
2447
2448        <row>
2449         <entry>10</entry>
2450         <entry>
2451          When you want two single quotes in the resulting string
2452          (which accounts for 8 quotes) <emphasis>and</emphasis>
2453          terminate that string (2 more).  You will probably only need
2454          that if you were using a function to generate other functions
2455          (like in <xref linkend="plpgsql-porting-nastyquote">).
2456         </entry>
2457         <entry><programlisting>
2458 a_output := a_output || '' if v_'' || 
2459     referrer_keys.kind || '' like '''''''''' 
2460     || referrer_keys.key_string || '''''''''' 
2461     then return ''''''  || referrer_keys.referrer_type 
2462     || ''''''; end if;''; 
2463 </programlisting></entry>
2464         <entry>
2465          <literal>if v_<...> like ''<...>'' then return ''<...>''; end if;</literal>
2466         </entry>
2467        </row>
2468       </tbody>
2469      </tgroup>
2470     </table>
2471    </sect3>
2472   </sect2>  
2473
2474   <sect2 id="plpgsql-porting-functions">
2475    <title>
2476     Porting Functions
2477    </title>
2478
2479    <example>
2480     <title>
2481      A Simple Function
2482     </title>
2483
2484     <para>
2485      Here is an Oracle function:
2486 <programlisting>
2487 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name IN varchar, v_version IN varchar)
2488 RETURN varchar IS
2489 BEGIN
2490     IF v_version IS NULL THEN
2491         RETURN v_name;
2492     END IF;
2493     RETURN v_name || '/' || v_version;
2494 END;
2495 /
2496 SHOW ERRORS;
2497 </programlisting>
2498     </para>
2499
2500     <para>
2501      Let's go through this function and see the differences to <application>PL/pgSQL</>:
2502
2503      <itemizedlist>
2504       <listitem>
2505        <para>
2506         <productname>PostgreSQL</productname> does not have named
2507         parameters. You have to explicitly alias them inside your
2508         function.
2509        </para>
2510       </listitem>
2511
2512       <listitem>
2513        <para>
2514         Oracle can have <literal>IN</literal>, <literal>OUT</literal>,
2515         and <literal>INOUT</literal> parameters passed to functions.
2516         The <literal>INOUT</literal>, for example, means that the
2517         parameter will receive a value and return another. <productname>PostgreSQL</>
2518         only has <quote>IN</quote> parameters and functions can return
2519         only a single value.
2520        </para>
2521       </listitem>
2522
2523       <listitem>
2524        <para>
2525         The <literal>RETURN</literal> key word in the function
2526         prototype (not the function body) becomes
2527         <literal>RETURNS</literal> in <productname>PostgreSQL</>.
2528        </para>
2529       </listitem>
2530
2531       <listitem>
2532        <para>
2533         On <productname>PostgreSQL</> functions are created using single quotes as
2534         delimiters, so you have to escape single quotes inside your
2535         functions (which can be quite annoying at times; see <xref
2536         linkend="plpgsql-quote">).
2537        </para>
2538       </listitem>
2539
2540       <listitem>
2541        <para>
2542         The <literal>/show errors</literal> command does not exist in
2543         <productname>PostgreSQL</>.
2544        </para>
2545       </listitem>
2546      </itemizedlist>
2547     </para>
2548
2549     <para>
2550      So let's see how this function would look when ported to
2551      <productname>PostgreSQL</>:
2552
2553 <programlisting>
2554 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(VARCHAR, VARCHAR)
2555 RETURNS VARCHAR AS '
2556 DECLARE
2557     v_name ALIAS FOR $1;
2558     v_version ALIAS FOR $2;
2559 BEGIN
2560     IF v_version IS NULL THEN
2561         return v_name;
2562     END IF;
2563     RETURN v_name || ''/'' || v_version;
2564 END;
2565 ' LANGUAGE 'plpgsql';
2566 </programlisting>
2567     </para>
2568    </example>
2569  
2570    <example id="plpgsql-porting-nastyquote">
2571     <title>
2572      A Function that Creates Another Function
2573     </title>
2574
2575     <para>
2576      The following procedure grabs rows from a
2577      <command>SELECT</command> statement and builds a large function
2578      with the results in <literal>IF</literal> statements, for the
2579      sake of efficiency. Notice particularly the differences in
2580      cursors, <literal>FOR</literal> loops, and the need to escape
2581      single quotes in <productname>PostgreSQL</>.
2582
2583 <programlisting>
2584 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
2585     CURSOR referrer_keys IS 
2586         SELECT * FROM cs_referrer_keys 
2587         ORDER BY try_order;
2588
2589     a_output VARCHAR(4000); 
2590 BEGIN 
2591     a_output := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR, v_domain IN VARCHAR, 
2592 v_url IN VARCHAR) RETURN VARCHAR IS BEGIN'; 
2593
2594     FOR referrer_key IN referrer_keys LOOP 
2595         a_output := a_output || ' IF v_' || referrer_key.kind || ' LIKE ''' || 
2596 referrer_key.key_string || ''' THEN RETURN ''' || referrer_key.referrer_type || 
2597 '''; END IF;'; 
2598     END LOOP; 
2599
2600     a_output := a_output || ' RETURN NULL; END;'; 
2601     EXECUTE IMMEDIATE a_output; 
2602 END; 
2603
2604 show errors
2605 </programlisting>
2606     </para>
2607
2608     <para>
2609      Here is how this function would end up in <productname>PostgreSQL</>:
2610
2611 <programlisting>
2612 CREATE FUNCTION cs_update_referrer_type_proc() RETURNS INTEGER AS '
2613 DECLARE
2614     referrer_keys RECORD;  -- Declare a generic record to be used in a FOR
2615     a_output varchar(4000);
2616 BEGIN 
2617     a_output := ''CREATE FUNCTION cs_find_referrer_type(VARCHAR,VARCHAR,VARCHAR) 
2618                   RETURNS VARCHAR AS '''' 
2619                      DECLARE 
2620                          v_host ALIAS FOR $1; 
2621                          v_domain ALIAS FOR $2; 
2622                          v_url ALIAS FOR $3;
2623                      BEGIN ''; 
2624
2625     -- 
2626     -- Notice how we scan through the results of a query in a FOR loop
2627     -- using the FOR &lt;record&gt; construct.
2628     --
2629
2630     FOR referrer_keys IN SELECT * FROM cs_referrer_keys ORDER BY try_order LOOP
2631         a_output := a_output || '' IF v_'' || referrer_keys.kind || '' LIKE '''''''''' 
2632                  || referrer_keys.key_string || '''''''''' THEN RETURN '''''' 
2633                  || referrer_keys.referrer_type || ''''''; END IF;''; 
2634     END LOOP; 
2635   
2636     a_output := a_output || '' RETURN NULL; END; '''' LANGUAGE ''''plpgsql'''';''; 
2637  
2638     -- This works because we are not substituting any variables
2639     -- Otherwise it would fail. Look at PERFORM for another way to run functions
2640     
2641     EXECUTE a_output; 
2642 END; 
2643 ' LANGUAGE 'plpgsql';
2644 </programlisting>
2645     </para>
2646    </example>
2647  
2648    <example>
2649     <title>
2650      A Procedure with a lot of String Manipulation and OUT Parameters
2651     </title>
2652
2653     <para>
2654      The following Oracle PL/SQL procedure is used to parse a URL and
2655      return several elements (host, path and query). It is an
2656      procedure because in <application>PL/pgSQL</application> functions only one value can be returned
2657      (see <xref linkend="plpgsql-porting-procedures">).  In
2658      <productname>PostgreSQL</>, one way to work around this is to split the procedure
2659      in three different functions: one to return the host, another for
2660      the path and another for the query.
2661     </para>
2662
2663 <programlisting>
2664 CREATE OR REPLACE PROCEDURE cs_parse_url(
2665     v_url IN VARCHAR,
2666     v_host OUT VARCHAR,  -- This will be passed back
2667     v_path OUT VARCHAR,  -- This one too
2668     v_query OUT VARCHAR) -- And this one
2669 is
2670     a_pos1 INTEGER;
2671     a_pos2 INTEGER;
2672 begin
2673     v_host := NULL;
2674     v_path := NULL;
2675     v_query := NULL;
2676     a_pos1 := instr(v_url, '//'); -- <productname>PostgreSQL</> doesn't have an instr function
2677
2678     IF a_pos1 = 0 THEN
2679         RETURN;
2680     END IF;
2681     a_pos2 := instr(v_url, '/', a_pos1 + 2);
2682     IF a_pos2 = 0 THEN
2683         v_host := substr(v_url, a_pos1 + 2);
2684         v_path := '/';
2685         RETURN;
2686     END IF;
2687
2688     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
2689     a_pos1 := instr(v_url, '?', a_pos2 + 1);
2690
2691     IF a_pos1 = 0 THEN
2692         v_path := substr(v_url, a_pos2);
2693         RETURN;
2694     END IF;
2695
2696     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
2697     v_query := substr(v_url, a_pos1 + 1);
2698 END;
2699 /
2700 show errors;
2701 </programlisting>
2702
2703     <para>
2704      Here is how this procedure could be translated for <productname>PostgreSQL</>:
2705
2706 <programlisting>
2707 CREATE OR REPLACE FUNCTION cs_parse_url_host(VARCHAR) RETURNS VARCHAR AS ' 
2708 DECLARE 
2709     v_url ALIAS FOR $1; 
2710     v_host VARCHAR; 
2711     v_path VARCHAR; 
2712     a_pos1 INTEGER; 
2713     a_pos2 INTEGER; 
2714     a_pos3 INTEGER; 
2715 BEGIN 
2716     v_host := NULL; 
2717     a_pos1 := instr(v_url,''//''); 
2718
2719     IF a_pos1 = 0 THEN 
2720         RETURN '''';  -- Return a blank
2721     END IF; 
2722
2723     a_pos2 := instr(v_url,''/'',a_pos1 + 2); 
2724     IF a_pos2 = 0 THEN 
2725         v_host := substr(v_url, a_pos1 + 2); 
2726         v_path := ''/''; 
2727         RETURN v_host; 
2728     END IF; 
2729
2730     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2 ); 
2731     RETURN v_host; 
2732 END; 
2733 ' LANGUAGE 'plpgsql';
2734 </programlisting>
2735     </para>
2736    </example>
2737
2738    <note>
2739     <para>
2740      <productname>PostgreSQL</> does not have an <function>instr</function> function,
2741      so you can work around it using a combination of other functions.
2742      I got tired of doing this and created my own
2743      <function>instr</function> functions that behave exactly like
2744      Oracle's (it makes life easier). See the <xref
2745      linkend="plpgsql-porting-appendix"> for the code.
2746     </para>
2747    </note>
2748   </sect2>
2749
2750   <sect2 id="plpgsql-porting-procedures">
2751    <title>
2752     Procedures
2753    </title>
2754
2755    <para>
2756     Oracle procedures give a little more flexibility to the developer
2757     because nothing needs to be explicitly returned, but it can be
2758     through the use of <literal>INOUT</> or <literal>OUT</> parameters.
2759    </para>
2760
2761    <para>
2762     An example:
2763
2764 <programlisting>
2765 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
2766     a_running_job_count INTEGER;
2767     PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
2768 BEGIN
2769     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
2770
2771     SELECT count(*) INTO a_running_job_count 
2772     FROM cs_jobs
2773     WHERE end_stamp IS NULL;
2774
2775     IF a_running_job_count > 0 THEN
2776         COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
2777         raise_application_error(-20000, 'Unable to create a new job: a job is currently running.');
2778     END IF;
2779
2780     DELETE FROM cs_active_job;
2781     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
2782
2783     BEGIN
2784         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
2785         EXCEPTION WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists<co id="co.plpgsql-porting-exception">
2786     END;
2787     COMMIT;
2788 END;
2789 /
2790 show errors
2791 </programlisting>
2792    </para>
2793
2794    <para>
2795     Procedures like this can be easily converted into <productname>PostgreSQL</>
2796     functions returning an <type>INTEGER</type>. This procedure in
2797     particular is interesting because it can teach us some things:
2798
2799     <calloutlist>
2800      <callout arearefs="co.plpgsql-porting-pragma">
2801       <para>
2802        There is no <literal>pragma</literal> statement in <productname>PostgreSQL</>.
2803       </para>
2804      </callout>
2805
2806      <callout arearefs="co.plpgsql-porting-locktable">
2807       <para>
2808        If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>, the lock
2809        will not be released until the calling transaction is finished.
2810       </para>
2811      </callout>
2812
2813      <callout arearefs="co.plpgsql-porting-commit">
2814       <para>
2815        You also cannot have transactions in <application>PL/pgSQL</application> procedures. The
2816        entire function (and other functions called from therein) is
2817        executed in a transaction and <productname>PostgreSQL</> rolls back the results if
2818        something goes wrong. Therefore only one
2819        <command>BEGIN</command> statement is allowed.
2820       </para>
2821      </callout>
2822
2823      <callout arearefs="co.plpgsql-porting-exception">
2824       <para>
2825        The exception when would have to be replaced by an
2826        <literal>IF</literal> statement.
2827       </para>
2828      </callout>
2829     </calloutlist>
2830    </para>
2831
2832    <para>
2833     So let's see one of the ways we could port this procedure to <application>PL/pgSQL</>:
2834
2835 <programlisting>
2836 CREATE OR REPLACE FUNCTION cs_create_job(INTEGER) RETURNS INTEGER AS '
2837 DECLARE
2838     v_job_id ALIAS FOR $1;
2839     a_running_job_count INTEGER;
2840     a_num INTEGER;
2841     -- PRAGMA AUTONOMOUS_TRANSACTION;
2842 BEGIN
2843     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
2844     SELECT count(*) INTO a_running_job_count 
2845     FROM cs_jobs 
2846     WHERE end_stamp IS NULL;
2847
2848     IF a_running_job_count > 0
2849     THEN
2850         -- COMMIT; -- free lock
2851         RAISE EXCEPTION ''Unable to create a new job: a job is currently running.'';
2852     END IF;
2853
2854     DELETE FROM cs_active_job;
2855     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
2856
2857     SELECT count(*) into a_num 
2858     FROM cs_jobs 
2859     WHERE job_id=v_job_id;
2860     IF NOT FOUND THEN  -- If nothing was returned in the last query
2861         -- This job is not in the table so lets insert it.
2862         INSERT INTO cs_jobs(job_id, start_stamp) VALUES (v_job_id, sysdate());
2863         RETURN 1;
2864     ELSE
2865         RAISE NOTICE ''Job already running.'';<co id="co.plpgsql-porting-raise">
2866     END IF;
2867
2868     RETURN 0;
2869 END;
2870 ' LANGUAGE 'plpgsql';
2871 </programlisting>
2872
2873     <calloutlist>
2874      <callout arearefs="co.plpgsql-porting-raise">
2875       <para>
2876        Notice how you can raise notices (or errors) in <application>PL/pgSQL</>.
2877       </para>
2878      </callout>
2879     </calloutlist>
2880    </para>
2881   </sect2>
2882
2883   <sect2 id="plpgsql-porting-packages">
2884    <title>
2885     Packages
2886    </title>
2887
2888    <note>
2889     <para>
2890      I haven't done much with packages myself, so if there are
2891      mistakes here, please let me know.
2892     </para>
2893    </note>
2894
2895    <para>
2896     Packages are a way Oracle gives you to encapsulate PL/SQL
2897     statements and functions into one entity, like Java classes, where
2898     you define methods and objects. You can access these
2899     objects/methods with a <quote><literal>.</literal></quote>
2900     (dot). Here is an example of an Oracle package from ACS 4 (the
2901     <ulink url="http://www.arsdigita.com/doc/">ArsDigita Community
2902     System</ulink>):
2903
2904 <programlisting>
2905 CREATE OR REPLACE PACKAGE BODY acs
2906 AS
2907   FUNCTION add_user (
2908     user_id     IN users.user_id%TYPE DEFAULT NULL,
2909     object_type     IN acs_objects.object_type%TYPE DEFAULT 'user',
2910     creation_date   IN acs_objects.creation_date%TYPE DEFAULT sysdate,
2911     creation_user   IN acs_objects.creation_user%TYPE DEFAULT NULL,
2912     creation_ip     IN acs_objects.creation_ip%TYPE DEFAULT NULL,
2913   ...
2914   ) RETURN users.user_id%TYPE
2915   IS
2916     v_user_id       users.user_id%TYPE;
2917     v_rel_id        membership_rels.rel_id%TYPE;
2918   BEGIN
2919     v_user_id := acs_user.new (user_id, object_type, creation_date,
2920                 creation_user, creation_ip, email, ...
2921     RETURN v_user_id;
2922   END;
2923 END acs;
2924 /
2925 show errors
2926 </programlisting>
2927    </para>
2928
2929    <para>
2930     We port this to <productname>PostgreSQL</> by creating the different objects of
2931     the Oracle package as functions with a standard naming
2932     convention. We have to pay attention to some other details, like
2933     the lack of default parameters in <productname>PostgreSQL</> functions. The above
2934     package would become something like this:
2935  
2936 <programlisting>
2937 CREATE FUNCTION acs__add_user(INTEGER,INTEGER,VARCHAR,TIMESTAMP,INTEGER,INTEGER,...)
2938 RETURNS INTEGER AS '
2939 DECLARE
2940     user_id ALIAS FOR $1;
2941     object_type ALIAS FOR $2;
2942     creation_date ALIAS FOR $3;
2943     creation_user ALIAS FOR $4;
2944     creation_ip ALIAS FOR $5;
2945     ...
2946     v_user_id users.user_id%TYPE;
2947     v_rel_id membership_rels.rel_id%TYPE;
2948 BEGIN
2949     v_user_id := acs_user__new(user_id,object_type,creation_date,creation_user,creation_ip, ...);
2950     ...
2951
2952     RETURN v_user_id;
2953 END;
2954 ' LANGUAGE 'plpgsql';
2955 </programlisting>
2956    </para>
2957   </sect2>
2958
2959   <sect2 id="plpgsql-porting-other">
2960    <title>
2961     Other Things to Watch For
2962    </title>
2963
2964    <sect3>
2965     <title>EXECUTE</title>
2966
2967     <para>
2968      The <productname>PostgreSQL</> version of <command>EXECUTE</command> works
2969      nicely, but you have to remember to use
2970      <function>quote_literal(TEXT)</function> and
2971      <function>quote_string(TEXT)</function> as described in <xref
2972      linkend="plpgsql-statements-executing-dyn-queries">.  Constructs of the type
2973      <literal>EXECUTE ''SELECT * from $1'';</literal> will not work
2974      unless you use these functions.
2975     </para>
2976    </sect3>
2977
2978    <sect3 id="plpgsql-porting-optimization">
2979     <title>Optimizing <application>PL/pgSQL</application> Functions</title>
2980
2981     <para>
2982      <productname>PostgreSQL</> gives you two function creation modifiers to optimize
2983      execution: <literal>iscachable</literal> (function always returns
2984      the same result when given the same arguments) and
2985      <literal>isstrict</literal> (function returns NULL if any
2986      argument is NULL).  Consult the <command>CREATE
2987      FUNCTION</command> reference for details.
2988     </para>
2989
2990     <para>
2991      To make use of these optimization attributes, you have to use the
2992      <literal>WITH</literal> modifier in your <command>CREATE
2993      FUNCTION</command> statement.  Something like:
2994
2995 <programlisting>
2996 CREATE FUNCTION foo(...) RETURNS INTEGER AS '
2997 ...
2998 ' LANGUAGE 'plpgsql'
2999 WITH (isstrict, iscachable);
3000 </programlisting>
3001     </para>
3002    </sect3>
3003   </sect2>
3004
3005   <sect2 id="plpgsql-porting-appendix">
3006    <title>
3007     Appendix
3008    </title>
3009
3010    <sect3>
3011     <title>
3012      Code for my <function>instr</function> functions
3013     </title>
3014
3015     <comment>
3016      This function should probably be integrated into the core.
3017     </comment>
3018
3019 <programlisting>
3020 --
3021 -- instr functions that mimic Oracle's counterpart
3022 -- Syntax: instr(string1,string2,[n],[m]) where [] denotes optional params.
3023 -- 
3024 -- Searches string1 beginning at the nth character for the mth
3025 -- occurrence of string2. If n is negative, search backwards. If m is
3026 -- not passed, assume 1 (search starts at first character).
3027 --
3028 -- by Roberto Mello (rmello@fslc.usu.edu)
3029 -- modified by Robert Gaszewski (graszew@poland.com)
3030 -- Licensed under the GPL v2 or later.
3031 --
3032
3033 CREATE FUNCTION instr(VARCHAR,VARCHAR) RETURNS INTEGER AS '
3034 DECLARE
3035     pos integer;
3036 BEGIN
3037     pos:= instr($1,$2,1);
3038     RETURN pos;
3039 END;
3040 ' LANGUAGE 'plpgsql';
3041
3042
3043 CREATE FUNCTION instr(VARCHAR,VARCHAR,INTEGER) RETURNS INTEGER AS '
3044 DECLARE
3045     string ALIAS FOR $1;
3046     string_to_search ALIAS FOR $2;
3047     beg_index ALIAS FOR $3;
3048     pos integer NOT NULL DEFAULT 0;
3049     temp_str VARCHAR;
3050     beg INTEGER;
3051     length INTEGER;
3052     ss_length INTEGER;
3053 BEGIN
3054     IF beg_index > 0 THEN
3055
3056        temp_str := substring(string FROM beg_index);
3057        pos := position(string_to_search IN temp_str);
3058
3059        IF pos = 0 THEN
3060                  RETURN 0;
3061              ELSE
3062                  RETURN pos + beg_index - 1;
3063              END IF;
3064     ELSE
3065        ss_length := char_length(string_to_search);
3066        length := char_length(string);
3067        beg := length + beg_index - ss_length + 2;
3068
3069        WHILE beg > 0 LOOP
3070            temp_str := substring(string FROM beg FOR ss_length);
3071                  pos := position(string_to_search IN temp_str);
3072
3073                  IF pos > 0 THEN
3074                            RETURN beg;
3075                  END IF;
3076
3077                  beg := beg - 1;
3078        END LOOP;
3079        RETURN 0;
3080     END IF;
3081 END;
3082 ' LANGUAGE 'plpgsql';
3083
3084 --
3085 -- Written by Robert Gaszewski (graszew@poland.com)
3086 -- Licensed under the GPL v2 or later.
3087 --
3088 CREATE FUNCTION instr(VARCHAR,VARCHAR,INTEGER,INTEGER) RETURNS INTEGER AS '
3089 DECLARE
3090     string ALIAS FOR $1;
3091     string_to_search ALIAS FOR $2;
3092     beg_index ALIAS FOR $3;
3093     occur_index ALIAS FOR $4;
3094     pos integer NOT NULL DEFAULT 0;
3095     occur_number INTEGER NOT NULL DEFAULT 0;
3096     temp_str VARCHAR;
3097     beg INTEGER;
3098     i INTEGER;
3099     length INTEGER;
3100     ss_length INTEGER;
3101 BEGIN
3102     IF beg_index > 0 THEN
3103         beg := beg_index;
3104         temp_str := substring(string FROM beg_index);
3105
3106         FOR i IN 1..occur_index LOOP
3107             pos := position(string_to_search IN temp_str);
3108
3109             IF i = 1 THEN
3110                 beg := beg + pos - 1;
3111             ELSE
3112                 beg := beg + pos;
3113             END IF;
3114
3115             temp_str := substring(string FROM beg + 1);
3116         END LOOP;
3117
3118         IF pos = 0 THEN
3119             RETURN 0;
3120         ELSE
3121             RETURN beg;
3122         END IF;
3123     ELSE
3124         ss_length := char_length(string_to_search);
3125         length := char_length(string);
3126         beg := length + beg_index - ss_length + 2;
3127
3128         WHILE beg > 0 LOOP
3129             temp_str := substring(string FROM beg FOR ss_length);
3130             pos := position(string_to_search IN temp_str);
3131
3132             IF pos > 0 THEN
3133                 occur_number := occur_number + 1;
3134
3135                 IF occur_number = occur_index THEN
3136                     RETURN beg;
3137                 END IF;
3138             END IF;
3139
3140             beg := beg - 1;
3141         END LOOP;
3142
3143         RETURN 0;
3144     END IF;
3145 END;
3146 ' LANGUAGE 'plpgsql';
3147 </programlisting>
3148    </sect3>
3149   </sect2>
3150   
3151  </sect1>
3152
3153 </chapter>
3154
3155 <!-- Keep this comment at the end of the file
3156 Local variables:
3157 mode:sgml
3158 sgml-omittag:nil
3159 sgml-shorttag:t
3160 sgml-minimize-attributes:nil
3161 sgml-always-quote-attributes:t
3162 sgml-indent-step:1
3163 sgml-indent-data:t
3164 sgml-parent-document:nil
3165 sgml-default-dtd-file:"./reference.ced"
3166 sgml-exposed-tags:nil
3167 sgml-local-catalogs:("/usr/lib/sgml/catalog")
3168 sgml-local-ecat-files:nil
3169 End:
3170 -->