]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpgsql.sgml
Fix some SGML-compiler warnings on -wxml mode.
[postgresql] / doc / src / sgml / plpgsql.sgml
1 <!-- $PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.137 2009/02/04 21:30:41 alvherre Exp $ -->
2
3 <chapter id="plpgsql">
4   <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
5
6  <indexterm zone="plpgsql">
7   <primary>PL/pgSQL</primary>
8  </indexterm>
9
10  <sect1 id="plpgsql-overview">
11   <title>Overview</title>
12
13  <para>
14   <application>PL/pgSQL</application> is a loadable procedural
15   language for the <productname>PostgreSQL</productname> database
16   system.  The design goals of <application>PL/pgSQL</> were to create
17   a loadable procedural language that
18
19     <itemizedlist>
20      <listitem>
21       <para>
22        can be used to create functions and trigger procedures,
23       </para>
24      </listitem>
25      <listitem>
26       <para>
27        adds control structures to the <acronym>SQL</acronym> language,
28       </para>
29      </listitem>
30      <listitem>
31       <para>
32        can perform complex computations,
33       </para>
34      </listitem>
35      <listitem>
36       <para>
37        inherits all user-defined types, functions, and operators,
38       </para>
39      </listitem>
40      <listitem>
41       <para>
42        can be defined to be trusted by the server,
43       </para>
44      </listitem>
45      <listitem>
46       <para>
47        is easy to use.
48       </para>
49      </listitem>
50     </itemizedlist>
51    </para>
52
53    <para>
54     Functions created with <application>PL/pgSQL</application> can be
55     used anywhere that built-in functions could be used.
56     For example, it is possible to
57     create complex conditional computation functions and later use
58     them to define operators or use them in index expressions.
59    </para>
60
61   <sect2 id="plpgsql-advantages">
62    <title>Advantages of Using <application>PL/pgSQL</application></title>
63
64     <para>
65      <acronym>SQL</acronym> is the language <productname>PostgreSQL</>
66      and most other relational databases use as query language. It's
67      portable and easy to learn. But every <acronym>SQL</acronym>
68      statement must be executed individually by the database server.
69     </para>
70
71     <para>
72      That means that your client application must send each query to
73      the database server, wait for it to be processed, receive and
74      process the results, do some computation, then send further
75      queries to the server.  All this incurs interprocess
76      communication and will also incur network overhead if your client
77      is on a different machine than the database server.
78     </para>
79
80     <para>
81      With <application>PL/pgSQL</application> you can group a block of
82      computation and a series of queries <emphasis>inside</emphasis>
83      the database server, thus having the power of a procedural
84      language and the ease of use of SQL, but with considerable
85      savings of client/server communication overhead.
86     </para>
87     <itemizedlist>
88
89      <listitem><para> Extra round trips between
90      client and server are eliminated </para></listitem>
91
92      <listitem><para> Intermediate results that the client does not
93      need do not have to be marshaled or transferred between server
94      and client </para></listitem>
95
96      <listitem><para> Multiple rounds of query
97      parsing can be avoided </para></listitem>
98
99     </itemizedlist>
100     <para> This can result in a considerable performance increase as
101     compared to an application that does not use stored functions.
102     </para>
103
104     <para>
105      Also, with <application>PL/pgSQL</application> you can use all
106      the data types, operators and functions of SQL.
107     </para>
108   </sect2>
109
110   <sect2 id="plpgsql-args-results">
111    <title>Supported Argument and Result Data Types</title>
112
113     <para>
114      Functions written in <application>PL/pgSQL</application> can accept
115      as arguments any scalar or array data type supported by the server,
116      and they can return a result of any of these types.  They can also
117      accept or return any composite type (row type) specified by name.
118      It is also possible to declare a <application>PL/pgSQL</application>
119      function as returning <type>record</>, which means that the result
120      is a row type whose columns are determined by specification in the
121      calling query, as discussed in <xref linkend="queries-tablefunctions">.
122     </para>
123
124     <para>
125      <application>PL/pgSQL</> functions can be declared to accept a variable
126      number of arguments by using the <literal>VARIADIC</> marker.  This
127      works exactly the same way as for SQL functions, as discussed in
128      <xref linkend="xfunc-sql-variadic-functions">.
129     </para>
130
131     <para>
132      <application>PL/pgSQL</> functions can also be declared to accept
133      and return the polymorphic types
134      <type>anyelement</type>, <type>anyarray</type>, <type>anynonarray</type>,
135      and <type>anyenum</>.  The actual
136      data types handled by a polymorphic function can vary from call to
137      call, as discussed in <xref linkend="extend-types-polymorphic">.
138      An example is shown in <xref linkend="plpgsql-declaration-aliases">.
139     </para>
140
141     <para>
142      <application>PL/pgSQL</> functions can also be declared to return
143      a <quote>set</> (or table) of any data type that can be returned as
144      a single instance.  Such a function generates its output by executing
145      <command>RETURN NEXT</> for each desired element of the result
146      set, or by using <command>RETURN QUERY</> to output the result of
147      evaluating a query.
148     </para>
149
150     <para>
151      Finally, a <application>PL/pgSQL</> function can be declared to return
152      <type>void</> if it has no useful return value.
153     </para>
154
155     <para>
156      <application>PL/pgSQL</> functions can also be declared with output
157      parameters in place of an explicit specification of the return type.
158      This does not add any fundamental capability to the language, but
159      it is often convenient, especially for returning multiple values.
160      The <literal>RETURNS TABLE</> notation can also be used in place
161      of <literal>RETURNS SETOF</>.
162     </para>
163
164     <para>
165      Specific examples appear in
166      <xref linkend="plpgsql-declaration-aliases"> and
167      <xref linkend="plpgsql-statements-returning">.
168     </para>
169   </sect2>
170  </sect1>
171
172  <sect1 id="plpgsql-structure">
173   <title>Structure of <application>PL/pgSQL</application></title>
174
175   <para>
176    <application>PL/pgSQL</application> is a block-structured language.
177    The complete text of a function definition must be a
178    <firstterm>block</>. A block is defined as:
179
180 <synopsis>
181 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
182 <optional> DECLARE
183     <replaceable>declarations</replaceable> </optional>
184 BEGIN
185     <replaceable>statements</replaceable>
186 END <optional> <replaceable>label</replaceable> </optional>;
187 </synopsis>
188     </para>
189
190     <para>
191      Each declaration and each statement within a block is terminated
192      by a semicolon.  A block that appears within another block must
193      have a semicolon after <literal>END</literal>, as shown above;
194      however the final <literal>END</literal> that
195      concludes a function body does not require a semicolon.
196     </para>
197
198     <tip>
199      <para>
200       A common mistake is to write a semicolon immediately after
201       <literal>BEGIN</>.  This is incorrect and will result in a syntax error.
202      </para>
203     </tip>
204
205     <para>
206      A <replaceable>label</replaceable> is only needed if you want to
207      identify the block for use
208      in an <literal>EXIT</> statement, or to qualify the names of the
209      variables declared in the block.  If a label is given after
210      <literal>END</>, it must match the label at the block's beginning.
211     </para>
212
213     <para>
214      All key words are case-insensitive.
215      Identifiers are implicitly converted to lowercase
216      unless double-quoted, just as they are in ordinary SQL commands.
217     </para>
218
219     <para>
220      There are two types of comments in <application>PL/pgSQL</>. A double
221      dash (<literal>--</literal>) starts a comment that extends to the end of
222      the line. A <literal>/*</literal> starts a block comment that extends to
223      the next occurrence of <literal>*/</literal>.  Block comments cannot be
224      nested, but double dash comments can be enclosed into a block comment and
225      a double dash can hide the block comment delimiters <literal>/*</literal>
226      and <literal>*/</literal>.
227     </para>
228
229     <para>
230      Any statement in the statement section of a block
231      can be a <firstterm>subblock</>.  Subblocks can be used for
232      logical grouping or to localize variables to a small group
233      of statements.  Variables declared in a subblock mask any
234      similarly-named variables of outer blocks for the duration
235      of the subblock; but you can access the outer variables anyway
236      if you qualify their names with their block's label. For example:
237 <programlisting>
238 CREATE FUNCTION somefunc() RETURNS integer AS $$
239 &lt;&lt; outerblock &gt;&gt;
240 DECLARE
241     quantity integer := 30;
242 BEGIN
243     RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 30
244     quantity := 50;
245     --
246     -- Create a subblock
247     --
248     DECLARE
249         quantity integer := 80;
250     BEGIN
251         RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 80
252         RAISE NOTICE 'Outer quantity here is %', outerblock.quantity;  -- Prints 50
253     END;
254
255     RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 50
256
257     RETURN quantity;
258 END;
259 $$ LANGUAGE plpgsql;
260 </programlisting>
261     </para>
262
263     <note>
264      <para>
265       There is actually a hidden <quote>outer block</> surrounding the body
266       of any <application>PL/pgSQL</> function.  This block provides the
267       declarations of the function's parameters (if any), as well as some
268       special variables such as <literal>FOUND</literal> (see
269       <xref linkend="plpgsql-statements-diagnostics">).  The outer block is
270       labeled with the function's name, meaning that parameters and special
271       variables can be qualified with the function's name.
272      </para>
273     </note>
274
275     <para>
276      It is important not to confuse the use of
277      <command>BEGIN</>/<command>END</> for grouping statements in
278      <application>PL/pgSQL</> with the similarly-named SQL commands
279      for transaction
280      control.  <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</>
281      are only for grouping; they do not start or end a transaction.
282      Functions and trigger procedures are always executed within a transaction
283      established by an outer query &mdash; they cannot start or commit that
284      transaction, since there would be no context for them to execute in.
285      However, a block containing an <literal>EXCEPTION</> clause effectively
286      forms a subtransaction that can be rolled back without affecting the
287      outer transaction.  For more about that see <xref
288      linkend="plpgsql-error-trapping">.
289     </para>
290   </sect1>
291
292   <sect1 id="plpgsql-declarations">
293     <title>Declarations</title>
294
295     <para>
296      All variables used in a block must be declared in the
297      declarations section of the block.
298      (The only exceptions are that the loop variable of a <literal>FOR</> loop
299      iterating over a range of integer values is automatically declared as an
300      integer variable, and likewise the loop variable of a <literal>FOR</> loop
301      iterating over a cursor's result is automatically declared as a
302      record variable.)
303     </para>
304
305     <para>
306      <application>PL/pgSQL</> variables can have any SQL data type, such as
307      <type>integer</type>, <type>varchar</type>, and
308      <type>char</type>.
309     </para>
310
311     <para>
312      Here are some examples of variable declarations:
313 <programlisting>
314 user_id integer;
315 quantity numeric(5);
316 url varchar;
317 myrow tablename%ROWTYPE;
318 myfield tablename.columnname%TYPE;
319 arow RECORD;
320 </programlisting>
321     </para>
322
323     <para>
324      The general syntax of a variable declaration is:
325 <synopsis>
326 <replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
327 </synopsis>
328       The <literal>DEFAULT</> clause, if given, specifies the initial value assigned
329       to the variable when the block is entered.  If the <literal>DEFAULT</> clause
330       is not given then the variable is initialized to the
331       <acronym>SQL</acronym> null value.
332       The <literal>CONSTANT</> option prevents the variable from being assigned to,
333       so that its value remains constant for the duration of the block.
334       If <literal>NOT NULL</>
335       is specified, an assignment of a null value results in a run-time
336       error. All variables declared as <literal>NOT NULL</>
337       must have a nonnull default value specified.
338      </para>
339
340      <para>
341       A variable's default value is evaluated and assigned to the variable
342       each time the block is entered (not just once per function call).
343       So, for example, assigning <literal>now()</literal> to a variable of type
344       <type>timestamp</type> causes the variable to have the
345       time of the current function call, not the time when the function was
346       precompiled.
347      </para>
348
349      <para>
350       Examples:
351 <programlisting>
352 quantity integer DEFAULT 32;
353 url varchar := 'http://mysite.com';
354 user_id CONSTANT integer := 10;
355 </programlisting>
356      </para>
357
358     <sect2 id="plpgsql-declaration-aliases">
359      <title>Aliases for Function Parameters</title>
360
361      <para>
362       Parameters passed to functions are named with the identifiers
363       <literal>$1</literal>, <literal>$2</literal>,
364       etc.  Optionally, aliases can be declared for
365       <literal>$<replaceable>n</replaceable></literal>
366       parameter names for increased readability.  Either the alias or the
367       numeric identifier can then be used to refer to the parameter value.
368      </para>
369
370      <para>
371       There are two ways to create an alias.  The preferred way is to give a
372       name to the parameter in the <command>CREATE FUNCTION</command> command,
373       for example:
374 <programlisting>
375 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
376 BEGIN
377     RETURN subtotal * 0.06;
378 END;
379 $$ LANGUAGE plpgsql;
380 </programlisting>
381       The other way, which was the only way available before
382       <productname>PostgreSQL</productname> 8.0, is to explicitly
383       declare an alias, using the declaration syntax
384
385 <synopsis>
386 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
387 </synopsis>
388
389       The same example in this style looks like:
390 <programlisting>
391 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
392 DECLARE
393     subtotal ALIAS FOR $1;
394 BEGIN
395     RETURN subtotal * 0.06;
396 END;
397 $$ LANGUAGE plpgsql;
398 </programlisting>
399      </para>
400
401     <note>
402      <para>
403       These two examples are not perfectly equivalent.  In the first case,
404       <literal>subtotal</> could be referenced as
405       <literal>sales_tax.subtotal</>, but in the second case it could not.
406       (Had we attached a label to the block, <literal>subtotal</> could
407       be qualified with that label, instead.)
408      </para>
409     </note>
410
411      <para>
412       Some more examples:
413 <programlisting>
414 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
415 DECLARE
416     v_string ALIAS FOR $1;
417     index ALIAS FOR $2;
418 BEGIN
419     -- some computations using v_string and index here
420 END;
421 $$ LANGUAGE plpgsql;
422
423
424 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
425 BEGIN
426     RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
427 END;
428 $$ LANGUAGE plpgsql;
429 </programlisting>
430      </para>
431
432      <para>
433       When a <application>PL/pgSQL</application> function is declared
434       with output parameters, the output parameters are given
435       <literal>$<replaceable>n</replaceable></literal> names and optional
436       aliases in just the same way as the normal input parameters.  An
437       output parameter is effectively a variable that starts out NULL;
438       it should be assigned to during the execution of the function.
439       The final value of the parameter is what is returned.  For instance,
440       the sales-tax example could also be done this way:
441
442 <programlisting>
443 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
444 BEGIN
445     tax := subtotal * 0.06;
446 END;
447 $$ LANGUAGE plpgsql;
448 </programlisting>
449
450       Notice that we omitted <literal>RETURNS real</> &mdash; we could have
451       included it, but it would be redundant.
452      </para>
453
454      <para>
455       Output parameters are most useful when returning multiple values.
456       A trivial example is:
457
458 <programlisting>
459 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
460 BEGIN
461     sum := x + y;
462     prod := x * y;
463 END;
464 $$ LANGUAGE plpgsql;
465 </programlisting>
466
467       As discussed in <xref linkend="xfunc-output-parameters">, this
468       effectively creates an anonymous record type for the function's
469       results.  If a <literal>RETURNS</> clause is given, it must say
470       <literal>RETURNS record</>.
471      </para>
472
473      <para>
474       Another way to declare a <application>PL/pgSQL</application> function
475       is with <literal>RETURNS TABLE</>, for example:
476
477 <programlisting>
478 CREATE FUNCTION extended_sales(p_itemno int) RETURNS TABLE(quantity int, total numeric) AS $$
479 BEGIN
480     RETURN QUERY SELECT quantity, quantity * price FROM sales WHERE itemno = p_itemno;
481 END;
482 $$ LANGUAGE plpgsql;
483 </programlisting>
484
485       This is exactly equivalent to declaring one or more <literal>OUT</>
486       parameters and specifying <literal>RETURNS SETOF
487       <replaceable>sometype</></literal>.
488      </para>
489
490      <para>
491       When the return type of a <application>PL/pgSQL</application>
492       function is declared as a polymorphic type (<type>anyelement</type>,
493       <type>anyarray</type>, <type>anynonarray</type>, or <type>anyenum</>),
494       a special parameter <literal>$0</literal>
495       is created.  Its data type is the actual return type of the function,
496       as deduced from the actual input types (see <xref
497       linkend="extend-types-polymorphic">).
498       This allows the function to access its actual return type
499       as shown in <xref linkend="plpgsql-declaration-type">.
500       <literal>$0</literal> is initialized to null and can be modified by
501       the function, so it can be used to hold the return value if desired,
502       though that is not required.  <literal>$0</literal> can also be
503       given an alias.  For example, this function works on any data type
504       that has a <literal>+</> operator:
505
506 <programlisting>
507 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
508 RETURNS anyelement AS $$
509 DECLARE
510     result ALIAS FOR $0;
511 BEGIN
512     result := v1 + v2 + v3;
513     RETURN result;
514 END;
515 $$ LANGUAGE plpgsql;
516 </programlisting>
517      </para>
518
519      <para>
520       The same effect can be had by declaring one or more output parameters as
521       polymorphic types.  In this case the
522       special <literal>$0</literal> parameter is not used; the output
523       parameters themselves serve the same purpose.  For example:
524
525 <programlisting>
526 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
527                                  OUT sum anyelement)
528 AS $$
529 BEGIN
530     sum := v1 + v2 + v3;
531 END;
532 $$ LANGUAGE plpgsql;
533 </programlisting>
534      </para>
535     </sect2>
536
537   <sect2 id="plpgsql-declaration-type">
538    <title>Copying Types</title>
539
540 <synopsis>
541 <replaceable>variable</replaceable>%TYPE
542 </synopsis>
543
544    <para>
545     <literal>%TYPE</literal> provides the data type of a variable or
546     table column. You can use this to declare variables that will hold
547     database values. For example, let's say you have a column named
548     <literal>user_id</literal> in your <literal>users</literal>
549     table. To declare a variable with the same data type as
550     <literal>users.user_id</> you write:
551 <programlisting>
552 user_id users.user_id%TYPE;
553 </programlisting>
554    </para>
555
556    <para>
557     By using <literal>%TYPE</literal> you don't need to know the data
558     type of the structure you are referencing, and most importantly,
559     if the data type of the referenced item changes in the future (for
560     instance: you change the type of <literal>user_id</>
561     from <type>integer</type> to <type>real</type>), you might not need
562     to change your function definition.
563    </para>
564
565    <para>
566     <literal>%TYPE</literal> is particularly valuable in polymorphic
567     functions, since the data types needed for internal variables can
568     change from one call to the next.  Appropriate variables can be
569     created by applying <literal>%TYPE</literal> to the function's
570     arguments or result placeholders.
571    </para>
572
573   </sect2>
574
575     <sect2 id="plpgsql-declaration-rowtypes">
576      <title>Row Types</title>
577
578 <synopsis>
579 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
580 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
581 </synopsis>
582
583    <para>
584     A variable of a composite type is called a <firstterm>row</>
585     variable (or <firstterm>row-type</> variable).  Such a variable
586     can hold a whole row of a <command>SELECT</> or <command>FOR</>
587     query result, so long as that query's column set matches the
588     declared type of the variable.
589     The individual fields of the row value
590     are accessed using the usual dot notation, for example
591     <literal>rowvar.field</literal>.
592    </para>
593
594    <para>
595     A row variable can be declared to have the same type as the rows of
596     an existing table or view, by using the
597     <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
598     notation; or it can be declared by giving a composite type's name.
599     (Since every table has an associated composite type of the same name,
600     it actually does not matter in <productname>PostgreSQL</> whether you
601     write <literal>%ROWTYPE</literal> or not.  But the form with
602     <literal>%ROWTYPE</literal> is more portable.)
603    </para>
604
605    <para>
606     Parameters to a function can be
607     composite types (complete table rows). In that case, the
608     corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
609     be selected from it, for example <literal>$1.user_id</literal>.
610    </para>
611
612    <para>
613     Only the user-defined columns of a table row are accessible in a
614     row-type variable, not the OID or other system columns (because the
615     row could be from a view).  The fields of the row type inherit the
616     table's field size or precision for data types such as
617     <type>char(<replaceable>n</>)</type>.
618    </para>
619
620    <para>
621     Here is an example of using composite types.  <structname>table1</>
622     and <structname>table2</> are existing tables having at least the
623     mentioned fields:
624
625 <programlisting>
626 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
627 DECLARE
628     t2_row table2%ROWTYPE;
629 BEGIN
630     SELECT * INTO t2_row FROM table2 WHERE ... ;
631     RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
632 END;
633 $$ LANGUAGE plpgsql;
634
635 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
636 </programlisting>
637    </para>
638   </sect2>
639
640   <sect2 id="plpgsql-declaration-records">
641    <title>Record Types</title>
642
643 <synopsis>
644 <replaceable>name</replaceable> RECORD;
645 </synopsis>
646
647    <para>
648     Record variables are similar to row-type variables, but they have no
649     predefined structure.  They take on the actual row structure of the
650     row they are assigned during a <command>SELECT</> or <command>FOR</> command.  The substructure
651     of a record variable can change each time it is assigned to.
652     A consequence of this is that until a record variable is first assigned
653     to, it has no substructure, and any attempt to access a
654     field in it will draw a run-time error.
655    </para>
656
657    <para>
658     Note that <literal>RECORD</> is not a true data type, only a placeholder.
659     One should also realize that when a <application>PL/pgSQL</application>
660     function is declared to return type <type>record</>, this is not quite the
661     same concept as a record variable, even though such a function might
662     use a record variable to hold its result.  In both cases the actual row
663     structure is unknown when the function is written, but for a function
664     returning <type>record</> the actual structure is determined when the
665     calling query is parsed, whereas a record variable can change its row
666     structure on-the-fly.
667    </para>
668   </sect2>
669
670   <sect2 id="plpgsql-declaration-renaming-vars">
671    <title><literal>RENAME</></title>
672
673 <synopsis>
674 RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
675 </synopsis>
676
677    <para>
678     Using the <literal>RENAME</literal> declaration you can change the
679     name of a variable, record or row. This is primarily useful if
680     <varname>NEW</varname> or <varname>OLD</varname> should be
681     referenced by another name inside a trigger procedure.  See also
682     <literal>ALIAS</literal>.
683    </para>
684
685    <para>
686     Examples:
687 <programlisting>
688 RENAME id TO user_id;
689 RENAME this_var TO that_var;
690 </programlisting>
691    </para>
692
693     <note>
694      <para>
695       <literal>RENAME</literal> appears to be broken as of
696       <productname>PostgreSQL</> 7.3.  Fixing this is of low priority,
697       since <literal>ALIAS</literal> covers most of the practical uses
698       of <literal>RENAME</literal>.
699      </para>
700     </note>
701    </sect2>
702   </sect1>
703
704   <sect1 id="plpgsql-expressions">
705   <title>Expressions</title>
706
707     <para>
708      All expressions used in <application>PL/pgSQL</application>
709      statements are processed using the server's main
710      <acronym>SQL</acronym> executor.  For example, when you write
711      a <application>PL/pgSQL</application> statement like
712 <synopsis>
713 IF <replaceable>expression</replaceable> THEN ...
714 </synopsis>
715      <application>PL/pgSQL</application> will evaluate the expression by
716      feeding a query like
717 <synopsis>
718 SELECT <replaceable>expression</replaceable>
719 </synopsis>
720      to the main SQL engine.  While forming the <command>SELECT</> command,
721      any occurrences of <application>PL/pgSQL</application> variable names
722      are replaced by parameters, as discussed in detail in
723      <xref linkend="plpgsql-var-subst">.
724      This allows the query plan for the <command>SELECT</command> to
725      be prepared just once and then reused for subsequent
726      evaluations with different values of the variables.  Thus, what
727      really happens on first use of an expression is essentially a
728      <command>PREPARE</> command.  For example, if we have declared
729      two integer variables <literal>x</> and <literal>y</>, and we write
730 <programlisting>
731 IF x &lt; y THEN ...
732 </programlisting>
733      what happens behind the scenes is
734 <programlisting>
735 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 &lt; $2;
736 </programlisting>
737      and then this prepared statement is <command>EXECUTE</>d for each
738      execution of the <command>IF</> statement, with the current values
739      of the <application>PL/pgSQL</application> variables supplied as
740      parameter values.
741      The query plan prepared in this way is saved for the life of the database
742      connection, as described in
743      <xref linkend="plpgsql-plan-caching">.  Normally these details are
744      not important to a <application>PL/pgSQL</application> user, but
745      they are useful to know when trying to diagnose a problem.
746     </para>
747   </sect1>
748
749   <sect1 id="plpgsql-statements">
750   <title>Basic Statements</title>
751
752    <para>
753     In this section and the following ones, we describe all the statement
754     types that are explicitly understood by
755     <application>PL/pgSQL</application>.
756     Anything not recognized as one of these statement types is presumed
757     to be an SQL command and is sent to the main database engine to execute,
758     as described in <xref linkend="plpgsql-statements-sql-noresult">
759     and <xref linkend="plpgsql-statements-sql-onerow">.
760    </para>
761
762    <sect2 id="plpgsql-statements-assignment">
763     <title>Assignment</title>
764
765     <para>
766      An assignment of a value to a <application>PL/pgSQL</application>
767      variable or row/record field is written as:
768 <synopsis>
769 <replaceable>variable</replaceable> := <replaceable>expression</replaceable>;
770 </synopsis>
771      As explained above, the expression in such a statement is evaluated
772      by means of an SQL <command>SELECT</> command sent to the main
773      database engine.  The expression must yield a single value.
774     </para>
775
776     <para>
777      If the expression's result data type doesn't match the variable's
778      data type, or the variable has a specific size/precision
779      (like <type>char(20)</type>), the result value will be implicitly
780      converted by the <application>PL/pgSQL</application> interpreter using
781      the result type's output-function and
782      the variable type's input-function. Note that this could potentially
783      result in run-time errors generated by the input function, if the
784      string form of the result value is not acceptable to the input function.
785     </para>
786
787     <para>
788      Examples:
789 <programlisting>
790 tax := subtotal * 0.06;
791 my_record.user_id := 20;
792 </programlisting>
793     </para>
794    </sect2>
795
796    <sect2 id="plpgsql-statements-sql-noresult">
797     <title>Executing a Command With No Result</title>
798
799     <para>
800      For any SQL command that does not return rows, for example
801      <command>INSERT</> without a <literal>RETURNING</> clause, you can
802      execute the command within a <application>PL/pgSQL</application> function
803      just by writing the command.
804     </para>
805
806     <para>
807      Any <application>PL/pgSQL</application> variable name appearing
808      in the command text is replaced by a parameter symbol, and then the
809      current value of the variable is provided as the parameter value
810      at run time.  This is exactly like the processing described earlier
811      for expressions; for details see <xref linkend="plpgsql-var-subst">.
812      As an example, if you write:
813 <programlisting>
814 DECLARE
815     key TEXT;
816     delta INTEGER;
817 BEGIN
818     ...
819     UPDATE mytab SET val = val + delta WHERE id = key;
820 </programlisting>
821       the command text seen by the main SQL engine will look like:
822 <programlisting>
823     UPDATE mytab SET val = val + $1 WHERE id = $2;
824 </programlisting>
825      Although you don't normally have to think about this, it's helpful
826      to know it when you need to make sense of syntax-error messages.
827     </para>
828
829     <caution>
830      <para>
831       <application>PL/pgSQL</application> will substitute for any identifier
832       matching one of the function's declared variables; it is not bright
833       enough to know whether that's what you meant!  Thus, it is a bad idea
834       to use a variable name that is the same as any table, column, or
835       function name that you need to reference in commands within the
836       function.  For more discussion see <xref linkend="plpgsql-var-subst">.
837      </para>
838     </caution>
839
840     <para>
841      When executing a SQL command in this way,
842      <application>PL/pgSQL</application> plans the command just once
843      and re-uses the plan on subsequent executions, for the life of
844      the database connection.  The implications of this are discussed
845      in detail in <xref linkend="plpgsql-plan-caching">.
846     </para>
847
848     <para>
849      Sometimes it is useful to evaluate an expression or <command>SELECT</>
850      query but discard the result, for example when calling a function
851      that has side-effects but no useful result value.  To do
852      this in <application>PL/pgSQL</application>, use the
853      <command>PERFORM</command> statement:
854
855 <synopsis>
856 PERFORM <replaceable>query</replaceable>;
857 </synopsis>
858
859      This executes <replaceable>query</replaceable> and discards the
860      result.  Write the <replaceable>query</replaceable> the same
861      way you would write an SQL <command>SELECT</> command, but replace the
862      initial keyword <command>SELECT</> with <command>PERFORM</command>.
863      <application>PL/pgSQL</application> variables will be
864      substituted into the query just as for commands that return no result,
865      and the plan is cached in the same way.  Also, the special variable
866      <literal>FOUND</literal> is set to true if the query produced at
867      least one row, or false if it produced no rows (see
868      <xref linkend="plpgsql-statements-diagnostics">).
869     </para>
870
871     <note>
872      <para>
873       One might expect that writing <command>SELECT</command> directly
874       would accomplish this result, but at
875       present the only accepted way to do it is
876       <command>PERFORM</command>.  A SQL command that can return rows,
877       such as <command>SELECT</command>, will be rejected as an error
878       unless it has an <literal>INTO</> clause as discussed in the
879       next section.
880      </para>
881     </note>
882
883     <para>
884      An example:
885 <programlisting>
886 PERFORM create_mv('cs_session_page_requests_mv', my_query);
887 </programlisting>
888     </para>
889    </sect2>
890
891    <sect2 id="plpgsql-statements-sql-onerow">
892     <title>Executing a Query with a Single-Row Result</title>
893
894     <indexterm zone="plpgsql-statements-sql-onerow">
895      <primary>SELECT INTO</primary>
896      <secondary>in PL/pgSQL</secondary>
897     </indexterm>
898
899     <indexterm zone="plpgsql-statements-sql-onerow">
900      <primary>RETURNING INTO</primary>
901      <secondary>in PL/pgSQL</secondary>
902     </indexterm>
903
904     <para>
905      The result of a SQL command yielding a single row (possibly of multiple
906      columns) can be assigned to a record variable, row-type variable, or list
907      of scalar variables.  This is done by writing the base SQL command and
908      adding an <literal>INTO</> clause.  For example,
909
910 <synopsis>
911 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
912 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
913 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
914 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
915 </synopsis>
916
917      where <replaceable>target</replaceable> can be a record variable, a row
918      variable, or a comma-separated list of simple variables and
919      record/row fields.
920      <application>PL/pgSQL</application> variables will be
921      substituted into the rest of the query, and the plan is cached,
922      just as described above for commands that do not return rows.
923      This works for <command>SELECT</>,
924      <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
925      <literal>RETURNING</>, and utility commands that return row-set
926      results (such as <command>EXPLAIN</>).
927      Except for the <literal>INTO</> clause, the SQL command is the same
928      as it would be written outside <application>PL/pgSQL</application>.
929     </para>
930
931    <tip>
932     <para>
933      Note that this interpretation of <command>SELECT</> with <literal>INTO</>
934      is quite different from <productname>PostgreSQL</>'s regular
935      <command>SELECT INTO</command> command, wherein the <literal>INTO</>
936      target is a newly created table.  If you want to create a table from a
937      <command>SELECT</> result inside a
938      <application>PL/pgSQL</application> function, use the syntax
939      <command>CREATE TABLE ... AS SELECT</command>.
940     </para>
941    </tip>
942
943     <para>
944      If a row or a variable list is used as target, the query's result columns
945      must exactly match the structure of the target as to number and data
946      types, or a run-time error
947      occurs.  When a record variable is the target, it automatically
948      configures itself to the row type of the query result columns.
949     </para>
950
951     <para>
952      The <literal>INTO</> clause can appear almost anywhere in the SQL
953      command.  Customarily it is written either just before or just after
954      the list of <replaceable>select_expressions</replaceable> in a
955      <command>SELECT</> command, or at the end of the command for other
956      command types.  It is recommended that you follow this convention
957      in case the <application>PL/pgSQL</application> parser becomes
958      stricter in future versions.
959     </para>
960
961     <para>
962      If <literal>STRICT</literal> is not specified in the <literal>INTO</>
963      clause, then <replaceable>target</replaceable> will be set to the first
964      row returned by the query, or to nulls if the query returned no rows.
965      (Note that <quote>the first row</> is not
966      well-defined unless you've used <literal>ORDER BY</>.)  Any result rows
967      after the first row are discarded.
968      You can check the special <literal>FOUND</literal> variable (see
969      <xref linkend="plpgsql-statements-diagnostics">) to
970      determine whether a row was returned:
971
972 <programlisting>
973 SELECT * INTO myrec FROM emp WHERE empname = myname;
974 IF NOT FOUND THEN
975     RAISE EXCEPTION 'employee % not found', myname;
976 END IF;
977 </programlisting>
978
979      If the <literal>STRICT</literal> option is specified, the query must
980      return exactly one row or a run-time error will be reported, either
981      <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
982      (more than one row). You can use an exception block if you wish
983      to catch the error, for example:
984
985 <programlisting>
986 BEGIN
987     SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
988     EXCEPTION
989         WHEN NO_DATA_FOUND THEN
990             RAISE EXCEPTION 'employee % not found', myname;
991         WHEN TOO_MANY_ROWS THEN
992             RAISE EXCEPTION 'employee % not unique', myname;
993 END;
994 </programlisting>
995      Successful execution of a command with <literal>STRICT</>
996      always sets <literal>FOUND</literal> to true.
997     </para>
998
999     <para>
1000      For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1001      <literal>RETURNING</>, <application>PL/pgSQL</application> reports
1002      an error for more than one returned row, even when
1003      <literal>STRICT</literal> is not specified.  This is because there
1004      is no option such as <literal>ORDER BY</> with which to determine
1005      which affected row should be returned.
1006     </para>
1007
1008     <note>
1009      <para>
1010       The <literal>STRICT</> option matches the behavior of
1011       Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1012      </para>
1013     </note>
1014
1015     <para>
1016      To handle cases where you need to process multiple result rows
1017      from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1018     </para>
1019
1020    </sect2>
1021
1022    <sect2 id="plpgsql-statements-executing-dyn">
1023     <title>Executing Dynamic Commands</title>
1024
1025     <para>
1026      Oftentimes you will want to generate dynamic commands inside your
1027      <application>PL/pgSQL</application> functions, that is, commands
1028      that will involve different tables or different data types each
1029      time they are executed.  <application>PL/pgSQL</application>'s
1030      normal attempts to cache plans for commands (as discussed in
1031      <xref linkend="plpgsql-plan-caching">) will not work in such
1032      scenarios.  To handle this sort of problem, the
1033      <command>EXECUTE</command> statement is provided:
1034
1035 <synopsis>
1036 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional>;
1037 </synopsis>
1038
1039      where <replaceable>command-string</replaceable> is an expression
1040      yielding a string (of type <type>text</type>) containing the
1041      command to be executed.  The optional <replaceable>target</replaceable>
1042      is a record variable, a row variable, or a comma-separated list of
1043      simple variables and record/row fields, into which the results of
1044      the command will be stored.  The optional <literal>USING</> expressions
1045      supply values to be inserted into the command.
1046     </para>
1047
1048     <para>
1049      No substitution of <application>PL/pgSQL</> variables is done on the
1050      computed command string.  Any required variable values must be inserted
1051      in the command string as it is constructed; or you can use parameters
1052      as described below.
1053     </para>
1054
1055     <para>
1056      Also, there is no plan caching for commands executed via
1057      <command>EXECUTE</command>.  Instead, the
1058      command is prepared each time the statement is run. Thus the command
1059      string can be dynamically created within the function to perform
1060      actions on different tables and columns.
1061     </para>
1062
1063     <para>
1064      The <literal>INTO</literal> clause specifies where the results of
1065      a SQL command returning rows should be assigned. If a row
1066      or variable list is provided, it must exactly match the structure
1067      of the query's results (when a
1068      record variable is used, it will configure itself to match the
1069      result structure automatically). If multiple rows are returned,
1070      only the first will be assigned to the <literal>INTO</literal>
1071      variable. If no rows are returned, NULL is assigned to the
1072      <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1073      clause is specified, the query results are discarded.
1074     </para>
1075
1076     <para>
1077      If the <literal>STRICT</> option is given, an error is reported
1078      unless the query produces exactly one row.
1079     </para>
1080
1081     <para>
1082      The command string can use parameter values, which are referenced
1083      in the command as <literal>$1</>, <literal>$2</>, etc.
1084      These symbols refer to values supplied in the <literal>USING</>
1085      clause.  This method is often preferable to inserting data values
1086      into the command string as text: it avoids run-time overhead of
1087      converting the values to text and back, and it is much less prone
1088      to SQL-injection attacks since there is no need for quoting or escaping.
1089      An example is:
1090 <programlisting>
1091 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted &lt;= $2'
1092    INTO c
1093    USING checked_user, checked_date;
1094 </programlisting>
1095
1096      Note that parameter symbols can only be used for data values
1097      &mdash; if you want to use dynamically determined table or column
1098      names, you must insert them into the command string textually.
1099      For example, if the preceding query needed to be done against a
1100      dynamically selected table, you could do this:
1101 <programlisting>
1102 EXECUTE 'SELECT count(*) FROM '
1103     || tabname::regclass
1104     || ' WHERE inserted_by = $1 AND inserted &lt;= $2'
1105    INTO c
1106    USING checked_user, checked_date;
1107 </programlisting>
1108     </para>
1109
1110     <para>
1111      An <command>EXECUTE</> with a simple constant command string and some
1112      <literal>USING</> parameters, as in the first example above, is
1113      functionally equivalent to just writing the command directly in
1114      <application>PL/pgSQL</application> and allowing replacement of
1115      <application>PL/pgSQL</application> variables to happen automatically.
1116      The important difference is that <command>EXECUTE</> will re-plan
1117      the command on each execution, generating a plan that is specific
1118      to the current parameter values; whereas
1119      <application>PL/pgSQL</application> normally creates a generic plan
1120      and caches it for re-use.  In situations where the best plan depends
1121      strongly on the parameter values, <command>EXECUTE</> can be
1122      significantly faster; while when the plan is not sensitive to parameter
1123      values, re-planning will be a waste.
1124     </para>
1125
1126     <para>
1127      <command>SELECT INTO</command> is not currently supported within
1128      <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1129      command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1130      itself.
1131     </para>
1132
1133    <note>
1134     <para>
1135      The <application>PL/pgSQL</application>
1136      <command>EXECUTE</command> statement is not related to the
1137      <xref linkend="sql-execute" endterm="sql-execute-title"> SQL
1138      statement supported by the
1139      <productname>PostgreSQL</productname> server. The server's
1140      <command>EXECUTE</command> statement cannot be used directly within
1141      <application>PL/pgSQL</> functions (and is not needed).
1142     </para>
1143    </note>
1144
1145    <example id="plpgsql-quote-literal-example">
1146    <title>Quoting values in dynamic queries</title>
1147
1148     <indexterm>
1149      <primary>quote_ident</primary>
1150      <secondary>use in PL/PgSQL</secondary>
1151     </indexterm>
1152
1153     <indexterm>
1154      <primary>quote_literal</primary>
1155      <secondary>use in PL/PgSQL</secondary>
1156     </indexterm>
1157
1158     <indexterm>
1159      <primary>quote_nullable</primary>
1160      <secondary>use in PL/PgSQL</secondary>
1161     </indexterm>
1162
1163     <para>
1164      When working with dynamic commands you will often have to handle escaping
1165      of single quotes.  The recommended method for quoting fixed text in your
1166      function body is dollar quoting.  (If you have legacy code that does
1167      not use dollar quoting, please refer to the
1168      overview in <xref linkend="plpgsql-quote-tips">, which can save you
1169      some effort when translating said code to a more reasonable scheme.)
1170     </para>
1171
1172     <para>
1173      Dynamic values that are to be inserted into the constructed
1174      query require careful handling since they might themselves contain
1175      quote characters.
1176      An example (this assumes that you are using dollar quoting for the
1177      function as a whole, so the quote marks need not be doubled):
1178 <programlisting>
1179 EXECUTE 'UPDATE tbl SET '
1180         || quote_ident(colname)
1181         || ' = '
1182         || quote_literal(newvalue)
1183         || ' WHERE key = '
1184         || quote_literal(keyvalue);
1185 </programlisting>
1186     </para>
1187
1188     <para>
1189      This example demonstrates the use of the
1190      <function>quote_ident</function> and
1191      <function>quote_literal</function> functions (see <xref
1192      linkend="functions-string">).  For safety, expressions containing column
1193      or table identifiers should be passed through
1194      <function>quote_ident</function> before insertion in a dynamic query.
1195      Expressions containing values that should be literal strings in the
1196      constructed command should be passed through <function>quote_literal</>.
1197      These functions take the appropriate steps to return the input text
1198      enclosed in double or single quotes respectively, with any embedded
1199      special characters properly escaped.
1200     </para>
1201
1202     <para>
1203      Because <function>quote_literal</function> is labelled
1204      <literal>STRICT</literal>, it will always return null when called with a
1205      null argument.  In the above example, if <literal>newvalue</> or
1206      <literal>keyvalue</> were null, the entire dynamic query string would
1207      become null, leading to an error from <command>EXECUTE</command>.
1208      You can avoid this problem by using the <function>quote_nullable</>
1209      function, which works the same as <function>quote_literal</> except that
1210      when called with a null argument it returns the string <literal>NULL</>.
1211      For example,
1212 <programlisting>
1213 EXECUTE 'UPDATE tbl SET '
1214         || quote_ident(colname)
1215         || ' = '
1216         || quote_nullable(newvalue)
1217         || ' WHERE key = '
1218         || quote_nullable(keyvalue);
1219 </programlisting>
1220      If you are dealing with values that might be null, you should usually
1221      use <function>quote_nullable</> in place of <function>quote_literal</>.
1222     </para>
1223
1224     <para>
1225      As always, care must be taken to ensure that null values in a query do
1226      not deliver unintended results.  For example the <literal>WHERE</> clause
1227 <programlisting>
1228      'WHERE key = ' || quote_nullable(keyvalue)
1229 </programlisting>
1230      will never succeed if <literal>keyvalue</> is null, because the
1231      result of using the equality operator <literal>=</> with a null operand
1232      is always null.  If you wish null to work like an ordinary key value,
1233      you would need to rewrite the above as
1234 <programlisting>
1235      'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1236 </programlisting>
1237      (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1238      efficiently than <literal>=</>, so don't do this unless you must.
1239      See <xref linkend="functions-comparison"> for
1240      more information on nulls and <literal>IS DISTINCT</>.)
1241     </para>
1242
1243     <para>
1244      Note that dollar quoting is only useful for quoting fixed text.
1245      It would be a very bad idea to try to write this example as:
1246 <programlisting>
1247 EXECUTE 'UPDATE tbl SET '
1248         || quote_ident(colname)
1249         || ' = $$'
1250         || newvalue
1251         || '$$ WHERE key = '
1252         || quote_literal(keyvalue);
1253 </programlisting>
1254      because it would break if the contents of <literal>newvalue</>
1255      happened to contain <literal>$$</>.  The same objection would
1256      apply to any other dollar-quoting delimiter you might pick.
1257      So, to safely quote text that is not known in advance, you
1258      <emphasis>must</> use <function>quote_literal</>,
1259      <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1260     </para>
1261    </example>
1262
1263     <para>
1264      A much larger example of a dynamic command and
1265      <command>EXECUTE</command> can be seen in <xref
1266      linkend="plpgsql-porting-ex2">, which builds and executes a
1267      <command>CREATE FUNCTION</> command to define a new function.
1268     </para>
1269    </sect2>
1270
1271    <sect2 id="plpgsql-statements-diagnostics">
1272     <title>Obtaining the Result Status</title>
1273
1274     <para>
1275      There are several ways to determine the effect of a command. The
1276      first method is to use the <command>GET DIAGNOSTICS</command>
1277      command, which has the form:
1278
1279 <synopsis>
1280 GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
1281 </synopsis>
1282
1283      This command allows retrieval of system status indicators.  Each
1284      <replaceable>item</replaceable> is a key word identifying a state
1285      value to be assigned to the specified variable (which should be
1286      of the right data type to receive it).  The currently available
1287      status items are <varname>ROW_COUNT</>, the number of rows
1288      processed by the last <acronym>SQL</acronym> command sent down to
1289      the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1290      the OID of the last row inserted by the most recent
1291      <acronym>SQL</acronym> command.  Note that <varname>RESULT_OID</>
1292      is only useful after an <command>INSERT</command> command into a
1293      table containing OIDs.
1294     </para>
1295
1296     <para>
1297      An example:
1298 <programlisting>
1299 GET DIAGNOSTICS integer_var = ROW_COUNT;
1300 </programlisting>
1301     </para>
1302
1303     <para>
1304      The second method to determine the effects of a command is to check the
1305      special variable named <literal>FOUND</literal>, which is of
1306      type <type>boolean</type>.  <literal>FOUND</literal> starts out
1307      false within each <application>PL/pgSQL</application> function call.
1308      It is set by each of the following types of statements:
1309          <itemizedlist>
1310           <listitem>
1311            <para>
1312             A <command>SELECT INTO</command> statement sets
1313             <literal>FOUND</literal> true if a row is assigned, false if no
1314             row is returned.
1315            </para>
1316           </listitem>
1317           <listitem>
1318            <para>
1319             A <command>PERFORM</> statement sets <literal>FOUND</literal>
1320             true if it produces (and discards) one or more rows, false if
1321             no row is produced.
1322            </para>
1323           </listitem>
1324           <listitem>
1325            <para>
1326             <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1327             statements set <literal>FOUND</literal> true if at least one
1328             row is affected, false if no row is affected.
1329            </para>
1330           </listitem>
1331           <listitem>
1332            <para>
1333             A <command>FETCH</> statement sets <literal>FOUND</literal>
1334             true if it returns a row, false if no row is returned.
1335            </para>
1336           </listitem>
1337           <listitem>
1338            <para>
1339             A <command>MOVE</> statement sets <literal>FOUND</literal>
1340             true if it successfully repositions the cursor, false otherwise.
1341            </para>
1342           </listitem>
1343
1344           <listitem>
1345            <para>
1346             A <command>FOR</> statement sets <literal>FOUND</literal> true
1347             if it iterates one or more times, else false.  This applies to
1348             all four variants of the <command>FOR</> statement (integer
1349             <command>FOR</> loops, record-set <command>FOR</> loops,
1350             dynamic record-set <command>FOR</> loops, and cursor
1351             <command>FOR</> loops).
1352             <literal>FOUND</literal> is set this way when the
1353             <command>FOR</> loop exits; inside the execution of the loop,
1354             <literal>FOUND</literal> is not modified by the
1355             <command>FOR</> statement, although it might be changed by the
1356             execution of other statements within the loop body.
1357            </para>
1358           </listitem>
1359          </itemizedlist>
1360
1361      <literal>FOUND</literal> is a local variable within each
1362      <application>PL/pgSQL</application> function; any changes to it
1363      affect only the current function.
1364     </para>
1365
1366    </sect2>
1367
1368    <sect2 id="plpgsql-statements-null">
1369     <title>Doing Nothing At All</title>
1370
1371     <para>
1372      Sometimes a placeholder statement that does nothing is useful.
1373      For example, it can indicate that one arm of an if/then/else
1374      chain is deliberately empty.  For this purpose, use the
1375      <command>NULL</command> statement:
1376
1377 <synopsis>
1378 NULL;
1379 </synopsis>
1380     </para>
1381
1382     <para>
1383      For example, the following two fragments of code are equivalent:
1384 <programlisting>
1385     BEGIN
1386         y := x / 0;
1387     EXCEPTION
1388         WHEN division_by_zero THEN
1389             NULL;  -- ignore the error
1390     END;
1391 </programlisting>
1392
1393 <programlisting>
1394     BEGIN
1395         y := x / 0;
1396     EXCEPTION
1397         WHEN division_by_zero THEN  -- ignore the error
1398     END;
1399 </programlisting>
1400      Which is preferable is a matter of taste.
1401     </para>
1402
1403     <note>
1404      <para>
1405       In Oracle's PL/SQL, empty statement lists are not allowed, and so
1406       <command>NULL</> statements are <emphasis>required</> for situations
1407       such as this.  <application>PL/pgSQL</application> allows you to
1408       just write nothing, instead.
1409      </para>
1410     </note>
1411
1412    </sect2>
1413   </sect1>
1414
1415   <sect1 id="plpgsql-control-structures">
1416    <title>Control Structures</title>
1417
1418    <para>
1419     Control structures are probably the most useful (and
1420     important) part of <application>PL/pgSQL</>. With
1421     <application>PL/pgSQL</>'s control structures,
1422     you can manipulate <productname>PostgreSQL</> data in a very
1423     flexible and powerful way.
1424    </para>
1425
1426    <sect2 id="plpgsql-statements-returning">
1427     <title>Returning From a Function</title>
1428
1429     <para>
1430      There are two commands available that allow you to return data
1431      from a function: <command>RETURN</command> and <command>RETURN
1432      NEXT</command>.
1433     </para>
1434
1435     <sect3>
1436      <title><command>RETURN</></title>
1437
1438 <synopsis>
1439 RETURN <replaceable>expression</replaceable>;
1440 </synopsis>
1441
1442      <para>
1443       <command>RETURN</command> with an expression terminates the
1444       function and returns the value of
1445       <replaceable>expression</replaceable> to the caller.  This form
1446       is to be used for <application>PL/pgSQL</> functions that do
1447       not return a set.
1448      </para>
1449
1450      <para>
1451       When returning a scalar type, any expression can be used. The
1452       expression's result will be automatically cast into the
1453       function's return type as described for assignments. To return a
1454       composite (row) value, you must write a record or row variable
1455       as the <replaceable>expression</replaceable>.
1456      </para>
1457
1458      <para>
1459       If you declared the function with output parameters, write just
1460       <command>RETURN</command> with no expression.  The current values
1461       of the output parameter variables will be returned.
1462      </para>
1463
1464      <para>
1465       If you declared the function to return <type>void</type>, a
1466       <command>RETURN</command> statement can be used to exit the function
1467       early; but do not write an expression following
1468       <command>RETURN</command>.
1469      </para>
1470
1471      <para>
1472       The return value of a function cannot be left undefined. If
1473       control reaches the end of the top-level block of the function
1474       without hitting a <command>RETURN</command> statement, a run-time
1475       error will occur.  This restriction does not apply to functions
1476       with output parameters and functions returning <type>void</type>,
1477       however.  In those cases a <command>RETURN</command> statement is
1478       automatically executed if the top-level block finishes.
1479      </para>
1480     </sect3>
1481
1482     <sect3>
1483      <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1484     <indexterm>
1485      <primary>RETURN NEXT</primary>
1486      <secondary>in PL/PgSQL</secondary>
1487     </indexterm>
1488     <indexterm>
1489      <primary>RETURN QUERY</primary>
1490      <secondary>in PL/PgSQL</secondary>
1491     </indexterm>
1492
1493 <synopsis>
1494 RETURN NEXT <replaceable>expression</replaceable>;
1495 RETURN QUERY <replaceable>query</replaceable>;
1496 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional>;
1497 </synopsis>
1498
1499      <para>
1500       When a <application>PL/pgSQL</> function is declared to return
1501       <literal>SETOF <replaceable>sometype</></literal>, the procedure
1502       to follow is slightly different.  In that case, the individual
1503       items to return are specified by a sequence of <command>RETURN
1504       NEXT</command> or <command>RETURN QUERY</command> commands, and
1505       then a final <command>RETURN</command> command with no argument
1506       is used to indicate that the function has finished executing.
1507       <command>RETURN NEXT</command> can be used with both scalar and
1508       composite data types; with a composite result type, an entire
1509       <quote>table</quote> of results will be returned.
1510       <command>RETURN QUERY</command> appends the results of executing
1511       a query to the function's result set. <command>RETURN
1512       NEXT</command> and <command>RETURN QUERY</command> can be freely
1513       intermixed in a single set-returning function, in which case
1514       their results will be concatenated.
1515      </para>
1516
1517      <para>
1518       <command>RETURN NEXT</command> and <command>RETURN
1519       QUERY</command> do not actually return from the function &mdash;
1520       they simply append zero or more rows to the function's result
1521       set.  Execution then continues with the next statement in the
1522       <application>PL/pgSQL</> function.  As successive
1523       <command>RETURN NEXT</command> or <command>RETURN
1524       QUERY</command> commands are executed, the result set is built
1525       up.  A final <command>RETURN</command>, which should have no
1526       argument, causes control to exit the function (or you can just
1527       let control reach the end of the function).
1528      </para>
1529
1530      <para>
1531       <command>RETURN QUERY</command> has a variant
1532       <command>RETURN QUERY EXECUTE</command>, which specifies the
1533       query to be executed dynamically.  Parameter expressions can
1534       be inserted into the computed query string via <literal>USING</>,
1535       in just the same way as in the <command>EXECUTE</> command.
1536      </para>
1537
1538      <para>
1539       If you declared the function with output parameters, write just
1540       <command>RETURN NEXT</command> with no expression.  On each
1541       execution, the current values of the output parameter
1542       variable(s) will be saved for eventual return as a row of the
1543       result.  Note that you must declare the function as returning
1544       <literal>SETOF record</literal> when there are multiple output
1545       parameters, or <literal>SETOF <replaceable>sometype</></literal>
1546       when there is just one output parameter of type
1547       <replaceable>sometype</>, in order to create a set-returning
1548       function with output parameters.
1549      </para>
1550
1551      <para>
1552       Here is an example of a function using <command>RETURN
1553       NEXT</command>:
1554
1555 <programlisting>
1556 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1557 INSERT INTO foo VALUES (1, 2, 'three');
1558 INSERT INTO foo VALUES (4, 5, 'six');
1559
1560 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1561 $BODY$
1562 DECLARE
1563     r foo%rowtype;
1564 BEGIN
1565     FOR r IN SELECT * FROM foo
1566     WHERE fooid &gt; 0
1567     LOOP
1568         -- can do some processing here
1569         RETURN NEXT r; -- return current row of SELECT
1570     END LOOP;
1571     RETURN;
1572 END
1573 $BODY$
1574 LANGUAGE 'plpgsql' ;
1575
1576 SELECT * FROM getallfoo();
1577 </programlisting>
1578      </para>
1579
1580      <note>
1581       <para>
1582        The current implementation of <command>RETURN NEXT</command>
1583        and <command>RETURN QUERY</command> stores the entire result set
1584        before returning from the function, as discussed above.  That
1585        means that if a <application>PL/pgSQL</> function produces a
1586        very large result set, performance might be poor: data will be
1587        written to disk to avoid memory exhaustion, but the function
1588        itself will not return until the entire result set has been
1589        generated.  A future version of <application>PL/pgSQL</> might
1590        allow users to define set-returning functions
1591        that do not have this limitation.  Currently, the point at
1592        which data begins being written to disk is controlled by the
1593        <xref linkend="guc-work-mem">
1594        configuration variable.  Administrators who have sufficient
1595        memory to store larger result sets in memory should consider
1596        increasing this parameter.
1597       </para>
1598      </note>
1599     </sect3>
1600    </sect2>
1601
1602    <sect2 id="plpgsql-conditionals">
1603     <title>Conditionals</title>
1604
1605     <para>
1606      <command>IF</> and <command>CASE</> statements let you execute
1607      alternative commands based on certain conditions.
1608      <application>PL/pgSQL</> has three forms of <command>IF</>:
1609     <itemizedlist>
1610      <listitem>
1611       <para><literal>IF ... THEN</></>
1612      </listitem>
1613      <listitem>
1614       <para><literal>IF ... THEN ... ELSE</></>
1615      </listitem>
1616      <listitem>
1617       <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1618      </listitem>
1619     </itemizedlist>
1620
1621     and two forms of <command>CASE</>:
1622     <itemizedlist>
1623      <listitem>
1624       <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1625      </listitem>
1626      <listitem>
1627       <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1628      </listitem>
1629     </itemizedlist>
1630     </para>
1631
1632     <sect3>
1633      <title><literal>IF-THEN</></title>
1634
1635 <synopsis>
1636 IF <replaceable>boolean-expression</replaceable> THEN
1637     <replaceable>statements</replaceable>
1638 END IF;
1639 </synopsis>
1640
1641        <para>
1642         <literal>IF-THEN</literal> statements are the simplest form of
1643         <literal>IF</literal>. The statements between
1644         <literal>THEN</literal> and <literal>END IF</literal> will be
1645         executed if the condition is true. Otherwise, they are
1646         skipped.
1647        </para>
1648
1649        <para>
1650         Example:
1651 <programlisting>
1652 IF v_user_id &lt;&gt; 0 THEN
1653     UPDATE users SET email = v_email WHERE user_id = v_user_id;
1654 END IF;
1655 </programlisting>
1656        </para>
1657      </sect3>
1658
1659      <sect3>
1660       <title><literal>IF-THEN-ELSE</></title>
1661
1662 <synopsis>
1663 IF <replaceable>boolean-expression</replaceable> THEN
1664     <replaceable>statements</replaceable>
1665 ELSE
1666     <replaceable>statements</replaceable>
1667 END IF;
1668 </synopsis>
1669
1670        <para>
1671         <literal>IF-THEN-ELSE</literal> statements add to
1672         <literal>IF-THEN</literal> by letting you specify an
1673         alternative set of statements that should be executed if the
1674         condition is not true.  (Note this includes the case where the
1675         condition evaluates to NULL.)
1676        </para>
1677
1678        <para>
1679         Examples:
1680 <programlisting>
1681 IF parentid IS NULL OR parentid = ''
1682 THEN
1683     RETURN fullname;
1684 ELSE
1685     RETURN hp_true_filename(parentid) || '/' || fullname;
1686 END IF;
1687 </programlisting>
1688
1689 <programlisting>
1690 IF v_count &gt; 0 THEN
1691     INSERT INTO users_count (count) VALUES (v_count);
1692     RETURN 't';
1693 ELSE
1694     RETURN 'f';
1695 END IF;
1696 </programlisting>
1697      </para>
1698     </sect3>
1699
1700      <sect3>
1701       <title><literal>IF-THEN-ELSIF</></title>
1702
1703 <synopsis>
1704 IF <replaceable>boolean-expression</replaceable> THEN
1705     <replaceable>statements</replaceable>
1706 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1707     <replaceable>statements</replaceable>
1708 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1709     <replaceable>statements</replaceable>
1710     ...
1711 </optional>
1712 </optional>
1713 <optional> ELSE
1714     <replaceable>statements</replaceable> </optional>
1715 END IF;
1716 </synopsis>
1717
1718        <para>
1719         Sometimes there are more than just two alternatives.
1720         <literal>IF-THEN-ELSIF</> provides a convenient
1721         method of checking several alternatives in turn.
1722         The <literal>IF</> conditions are tested successively
1723         until the first one that is true is found.  Then the
1724         associated statement(s) are executed, after which control
1725         passes to the next statement after <literal>END IF</>.
1726         (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1727         tested.)  If none of the <literal>IF</> conditions is true,
1728         then the <literal>ELSE</> block (if any) is executed.
1729        </para>
1730
1731        <para>
1732         Here is an example:
1733
1734 <programlisting>
1735 IF number = 0 THEN
1736     result := 'zero';
1737 ELSIF number &gt; 0 THEN
1738     result := 'positive';
1739 ELSIF number &lt; 0 THEN
1740     result := 'negative';
1741 ELSE
1742     -- hmm, the only other possibility is that number is null
1743     result := 'NULL';
1744 END IF;
1745 </programlisting>
1746        </para>
1747
1748        <para>
1749         The key word <literal>ELSIF</> can also be spelled
1750         <literal>ELSEIF</>.
1751        </para>
1752
1753        <para>
1754         An alternative way of accomplishing the same task is to nest
1755         <literal>IF-THEN-ELSE</literal> statements, as in the
1756         following example:
1757
1758 <programlisting>
1759 IF demo_row.sex = 'm' THEN
1760     pretty_sex := 'man';
1761 ELSE
1762     IF demo_row.sex = 'f' THEN
1763         pretty_sex := 'woman';
1764     END IF;
1765 END IF;
1766 </programlisting>
1767        </para>
1768
1769        <para>
1770         However, this method requires writing a matching <literal>END IF</>
1771         for each <literal>IF</>, so it is much more cumbersome than
1772         using <literal>ELSIF</> when there are many alternatives.
1773        </para>
1774      </sect3>
1775
1776      <sect3>
1777       <title>Simple <literal>CASE</></title>
1778
1779 <synopsis>
1780 CASE <replaceable>search-expression</replaceable>
1781     WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1782       <replaceable>statements</replaceable>
1783   <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1784       <replaceable>statements</replaceable>
1785     ... </optional>
1786   <optional> ELSE
1787       <replaceable>statements</replaceable> </optional>
1788 END CASE;
1789 </synopsis>
1790
1791       <para>
1792        The simple form of <command>CASE</> provides conditional execution
1793        based on equality of operands.  The <replaceable>search-expression</>
1794        is evaluated (once) and successively compared to each
1795        <replaceable>expression</> in the <literal>WHEN</> clauses.
1796        If a match is found, then the corresponding
1797        <replaceable>statements</replaceable> are executed, and then control
1798        passes to the next statement after <literal>END CASE</>.  (Subsequent
1799        <literal>WHEN</> expressions are not evaluated.)  If no match is
1800        found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1801        executed; but if <literal>ELSE</> is not present, then a
1802        <literal>CASE_NOT_FOUND</literal> exception is raised.
1803       </para>
1804
1805       <para>
1806        Here is a simple example:
1807
1808 <programlisting>
1809 CASE x
1810     WHEN 1, 2 THEN
1811         msg := 'one or two';
1812     ELSE
1813         msg := 'other value than one or two';
1814 END CASE;
1815 </programlisting>
1816       </para>
1817      </sect3>
1818
1819      <sect3>
1820       <title>Searched <literal>CASE</></title>
1821
1822 <synopsis>
1823 CASE
1824     WHEN <replaceable>boolean-expression</replaceable> THEN
1825       <replaceable>statements</replaceable>
1826   <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1827       <replaceable>statements</replaceable>
1828     ... </optional>
1829   <optional> ELSE
1830       <replaceable>statements</replaceable> </optional>
1831 END CASE;
1832 </synopsis>
1833
1834       <para>
1835        The searched form of <command>CASE</> provides conditional execution
1836        based on truth of boolean expressions.  Each <literal>WHEN</> clause's
1837        <replaceable>boolean-expression</replaceable> is evaluated in turn,
1838        until one is found that yields <literal>true</>.  Then the
1839        corresponding <replaceable>statements</replaceable> are executed, and
1840        then control passes to the next statement after <literal>END CASE</>.
1841        (Subsequent <literal>WHEN</> expressions are not evaluated.)
1842        If no true result is found, the <literal>ELSE</>
1843        <replaceable>statements</replaceable> are executed;
1844        but if <literal>ELSE</> is not present, then a
1845        <literal>CASE_NOT_FOUND</literal> exception is raised.
1846       </para>
1847
1848       <para>
1849        Here is an example:
1850
1851 <programlisting>
1852 CASE
1853     WHEN x BETWEEN 0 AND 10 THEN
1854         msg := 'value is between zero and ten';
1855     WHEN x BETWEEN 11 AND 20 THEN
1856         msg := 'value is between eleven and twenty';
1857 END CASE;
1858 </programlisting>
1859       </para>
1860
1861       <para>
1862        This form of <command>CASE</> is entirely equivalent to
1863        <literal>IF-THEN-ELSIF</>, except for the rule that reaching
1864        an omitted <literal>ELSE</> clause results in an error rather
1865        than doing nothing.
1866       </para>
1867
1868      </sect3>
1869    </sect2>
1870
1871    <sect2 id="plpgsql-control-structures-loops">
1872     <title>Simple Loops</title>
1873
1874     <indexterm zone="plpgsql-control-structures-loops">
1875      <primary>loop</primary>
1876      <secondary>in PL/pgSQL</secondary>
1877     </indexterm>
1878
1879     <para>
1880      With the <literal>LOOP</>, <literal>EXIT</>,
1881      <literal>CONTINUE</>, <literal>WHILE</>, and <literal>FOR</>
1882      statements, you can arrange for your <application>PL/pgSQL</>
1883      function to repeat a series of commands.
1884     </para>
1885
1886     <sect3>
1887      <title><literal>LOOP</></title>
1888
1889 <synopsis>
1890 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
1891 LOOP
1892     <replaceable>statements</replaceable>
1893 END LOOP <optional> <replaceable>label</replaceable> </optional>;
1894 </synopsis>
1895
1896      <para>
1897       <literal>LOOP</> defines an unconditional loop that is repeated
1898       indefinitely until terminated by an <literal>EXIT</> or
1899       <command>RETURN</command> statement.  The optional
1900       <replaceable>label</replaceable> can be used by <literal>EXIT</>
1901       and <literal>CONTINUE</literal> statements in nested loops to
1902       specify which loop the statement should be applied to.
1903      </para>
1904     </sect3>
1905
1906      <sect3>
1907       <title><literal>EXIT</></title>
1908
1909      <indexterm>
1910       <primary>EXIT</primary>
1911       <secondary>in PL/pgSQL</secondary>
1912      </indexterm>
1913
1914 <synopsis>
1915 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1916 </synopsis>
1917
1918        <para>
1919         If no <replaceable>label</replaceable> is given, the innermost
1920         loop is terminated and the statement following <literal>END
1921         LOOP</> is executed next.  If <replaceable>label</replaceable>
1922         is given, it must be the label of the current or some outer
1923         level of nested loop or block. Then the named loop or block is
1924         terminated and control continues with the statement after the
1925         loop's/block's corresponding <literal>END</>.
1926        </para>
1927
1928        <para>
1929         If <literal>WHEN</> is specified, the loop exit occurs only if
1930         <replaceable>boolean-expression</> is true. Otherwise, control passes
1931         to the statement after <literal>EXIT</>.
1932        </para>
1933
1934        <para>
1935         <literal>EXIT</> can be used with all types of loops; it is
1936         not limited to use with unconditional loops. When used with a
1937         <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
1938         control to the next statement after the end of the block.
1939        </para>
1940
1941        <para>
1942         Examples:
1943 <programlisting>
1944 LOOP
1945     -- some computations
1946     IF count &gt; 0 THEN
1947         EXIT;  -- exit loop
1948     END IF;
1949 END LOOP;
1950
1951 LOOP
1952     -- some computations
1953     EXIT WHEN count &gt; 0;  -- same result as previous example
1954 END LOOP;
1955
1956 BEGIN
1957     -- some computations
1958     IF stocks &gt; 100000 THEN
1959         EXIT;  -- causes exit from the BEGIN block
1960     END IF;
1961 END;
1962 </programlisting>
1963        </para>
1964      </sect3>
1965
1966      <sect3>
1967       <title><literal>CONTINUE</></title>
1968
1969      <indexterm>
1970       <primary>CONTINUE</primary>
1971       <secondary>in PL/pgSQL</secondary>
1972      </indexterm>
1973
1974 <synopsis>
1975 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1976 </synopsis>
1977
1978        <para>
1979         If no <replaceable>label</> is given, the next iteration of
1980         the innermost loop is begun. That is, all statements remaining
1981         in the loop body are skipped, and control returns
1982         to the loop control expression (if any) to determine whether
1983         another loop iteration is needed.
1984         If <replaceable>label</> is present, it
1985         specifies the label of the loop whose execution will be
1986         continued.
1987        </para>
1988
1989        <para>
1990         If <literal>WHEN</> is specified, the next iteration of the
1991         loop is begun only if <replaceable>boolean-expression</> is
1992         true. Otherwise, control passes to the statement after
1993         <literal>CONTINUE</>.
1994        </para>
1995
1996        <para>
1997         <literal>CONTINUE</> can be used with all types of loops; it
1998         is not limited to use with unconditional loops.
1999        </para>
2000
2001        <para>
2002         Examples:
2003 <programlisting>
2004 LOOP
2005     -- some computations
2006     EXIT WHEN count &gt; 100;
2007     CONTINUE WHEN count &lt; 50;
2008     -- some computations for count IN [50 .. 100]
2009 END LOOP;
2010 </programlisting>
2011        </para>
2012      </sect3>
2013
2014
2015      <sect3>
2016       <title><literal>WHILE</></title>
2017
2018      <indexterm>
2019       <primary>WHILE</primary>
2020       <secondary>in PL/pgSQL</secondary>
2021      </indexterm>
2022
2023 <synopsis>
2024 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2025 WHILE <replaceable>boolean-expression</replaceable> LOOP
2026     <replaceable>statements</replaceable>
2027 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2028 </synopsis>
2029
2030        <para>
2031         The <literal>WHILE</> statement repeats a
2032         sequence of statements so long as the
2033         <replaceable>boolean-expression</replaceable>
2034         evaluates to true.  The expression is checked just before
2035         each entry to the loop body.
2036        </para>
2037
2038        <para>
2039         For example:
2040 <programlisting>
2041 WHILE amount_owed &gt; 0 AND gift_certificate_balance &gt; 0 LOOP
2042     -- some computations here
2043 END LOOP;
2044
2045 WHILE NOT done LOOP
2046     -- some computations here
2047 END LOOP;
2048 </programlisting>
2049        </para>
2050      </sect3>
2051
2052      <sect3 id="plpgsql-integer-for">
2053       <title><literal>FOR</> (integer variant)</title>
2054
2055 <synopsis>
2056 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2057 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2058     <replaceable>statements</replaceable>
2059 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2060 </synopsis>
2061
2062        <para>
2063         This form of <literal>FOR</> creates a loop that iterates over a range
2064         of integer values. The variable
2065         <replaceable>name</replaceable> is automatically defined as type
2066         <type>integer</> and exists only inside the loop (any existing
2067         definition of the variable name is ignored within the loop).
2068         The two expressions giving
2069         the lower and upper bound of the range are evaluated once when entering
2070         the loop. If the <literal>BY</> clause isn't specified the iteration
2071         step is 1, otherwise it's the value specified in the <literal>BY</>
2072         clause, which again is evaluated once on loop entry.
2073         If <literal>REVERSE</> is specified then the step value is
2074         subtracted, rather than added, after each iteration.
2075        </para>
2076
2077        <para>
2078         Some examples of integer <literal>FOR</> loops:
2079 <programlisting>
2080 FOR i IN 1..10 LOOP
2081     -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2082 END LOOP;
2083
2084 FOR i IN REVERSE 10..1 LOOP
2085     -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2086 END LOOP;
2087
2088 FOR i IN REVERSE 10..1 BY 2 LOOP
2089     -- i will take on the values 10,8,6,4,2 within the loop
2090 END LOOP;
2091 </programlisting>
2092        </para>
2093
2094        <para>
2095         If the lower bound is greater than the upper bound (or less than,
2096         in the <literal>REVERSE</> case), the loop body is not
2097         executed at all.  No error is raised.
2098        </para>
2099
2100        <para>
2101         If a <replaceable>label</replaceable> is attached to the
2102         <literal>FOR</> loop then the integer loop variable can be
2103         referenced with a qualified name, using that
2104         <replaceable>label</replaceable>.
2105        </para>
2106      </sect3>
2107    </sect2>
2108
2109    <sect2 id="plpgsql-records-iterating">
2110     <title>Looping Through Query Results</title>
2111
2112     <para>
2113      Using a different type of <literal>FOR</> loop, you can iterate through
2114      the results of a query and manipulate that data
2115      accordingly. The syntax is:
2116 <synopsis>
2117 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2118 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2119     <replaceable>statements</replaceable>
2120 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2121 </synopsis>
2122      The <replaceable>target</replaceable> is a record variable, row variable,
2123      or comma-separated list of scalar variables.
2124      The <replaceable>target</replaceable> is successively assigned each row
2125      resulting from the <replaceable>query</replaceable> and the loop body is
2126      executed for each row. Here is an example:
2127 <programlisting>
2128 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2129 DECLARE
2130     mviews RECORD;
2131 BEGIN
2132     PERFORM cs_log('Refreshing materialized views...');
2133
2134     FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2135
2136         -- Now "mviews" has one record from cs_materialized_views
2137
2138         PERFORM cs_log('Refreshing materialized view ' || quote_ident(mviews.mv_name) || ' ...');
2139         EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2140         EXECUTE 'INSERT INTO ' || quote_ident(mviews.mv_name) || ' ' || mviews.mv_query;
2141     END LOOP;
2142
2143     PERFORM cs_log('Done refreshing materialized views.');
2144     RETURN 1;
2145 END;
2146 $$ LANGUAGE plpgsql;
2147 </programlisting>
2148
2149      If the loop is terminated by an <literal>EXIT</> statement, the last
2150      assigned row value is still accessible after the loop.
2151     </para>
2152
2153     <para>
2154      The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2155      statement can be any SQL command that returns rows to the caller:
2156      <command>SELECT</> is the most common case,
2157      but you can also use <command>INSERT</>, <command>UPDATE</>, or
2158      <command>DELETE</> with a <literal>RETURNING</> clause.  Some utility
2159      commands such as <command>EXPLAIN</> will work too.
2160     </para>
2161
2162     <para>
2163      <application>PL/pgSQL</> variables are substituted into the query text,
2164      and the query plan is cached for possible re-use, as discussed in
2165      detail in <xref linkend="plpgsql-var-subst"> and
2166      <xref linkend="plpgsql-plan-caching">.
2167     </para>
2168
2169     <para>
2170      The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2171      rows:
2172 <synopsis>
2173 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2174 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional> LOOP
2175     <replaceable>statements</replaceable>
2176 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2177 </synopsis>
2178      This is like the previous form, except that the source query
2179      is specified as a string expression, which is evaluated and replanned
2180      on each entry to the <literal>FOR</> loop.  This allows the programmer to
2181      choose the speed of a preplanned query or the flexibility of a dynamic
2182      query, just as with a plain <command>EXECUTE</command> statement.
2183      As with <command>EXECUTE</command>, parameter values can be inserted
2184      into the dynamic command via <literal>USING</>.
2185     </para>
2186
2187     <para>
2188      Another way to specify the query whose results should be iterated
2189      through is to declare it as a cursor.  This is described in
2190      <xref linkend="plpgsql-cursor-for-loop">.
2191     </para>
2192    </sect2>
2193
2194    <sect2 id="plpgsql-error-trapping">
2195     <title>Trapping Errors</title>
2196
2197     <indexterm>
2198      <primary>exceptions</primary>
2199      <secondary>in PL/PgSQL</secondary>
2200     </indexterm>
2201
2202     <para>
2203      By default, any error occurring in a <application>PL/pgSQL</>
2204      function aborts execution of the function, and indeed of the
2205      surrounding transaction as well.  You can trap errors and recover
2206      from them by using a <command>BEGIN</> block with an
2207      <literal>EXCEPTION</> clause.  The syntax is an extension of the
2208      normal syntax for a <command>BEGIN</> block:
2209
2210 <synopsis>
2211 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2212 <optional> DECLARE
2213     <replaceable>declarations</replaceable> </optional>
2214 BEGIN
2215     <replaceable>statements</replaceable>
2216 EXCEPTION
2217     WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2218         <replaceable>handler_statements</replaceable>
2219     <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2220           <replaceable>handler_statements</replaceable>
2221       ... </optional>
2222 END;
2223 </synopsis>
2224     </para>
2225
2226     <para>
2227      If no error occurs, this form of block simply executes all the
2228      <replaceable>statements</replaceable>, and then control passes
2229      to the next statement after <literal>END</>.  But if an error
2230      occurs within the <replaceable>statements</replaceable>, further
2231      processing of the <replaceable>statements</replaceable> is
2232      abandoned, and control passes to the <literal>EXCEPTION</> list.
2233      The list is searched for the first <replaceable>condition</replaceable>
2234      matching the error that occurred.  If a match is found, the
2235      corresponding <replaceable>handler_statements</replaceable> are
2236      executed, and then control passes to the next statement after
2237      <literal>END</>.  If no match is found, the error propagates out
2238      as though the <literal>EXCEPTION</> clause were not there at all:
2239      the error can be caught by an enclosing block with
2240      <literal>EXCEPTION</>, or if there is none it aborts processing
2241      of the function.
2242     </para>
2243
2244     <para>
2245      The <replaceable>condition</replaceable> names can be any of
2246      those shown in <xref linkend="errcodes-appendix">.  A category
2247      name matches any error within its category.  The special
2248      condition name <literal>OTHERS</> matches every error type except
2249      <literal>QUERY_CANCELED</>.  (It is possible, but often unwise,
2250      to trap <literal>QUERY_CANCELED</> by name.)  Condition names are
2251      not case-sensitive.  Also, an error condition can be specified
2252      by <literal>SQLSTATE</> code; for example these are equivalent:
2253 <programlisting>
2254         WHEN division_by_zero THEN ...
2255         WHEN SQLSTATE '22012' THEN ...
2256 </programlisting>
2257     </para>
2258
2259     <para>
2260      If a new error occurs within the selected
2261      <replaceable>handler_statements</replaceable>, it cannot be caught
2262      by this <literal>EXCEPTION</> clause, but is propagated out.
2263      A surrounding <literal>EXCEPTION</> clause could catch it.
2264     </para>
2265
2266     <para>
2267      When an error is caught by an <literal>EXCEPTION</> clause,
2268      the local variables of the <application>PL/pgSQL</> function
2269      remain as they were when the error occurred, but all changes
2270      to persistent database state within the block are rolled back.
2271      As an example, consider this fragment:
2272
2273 <programlisting>
2274     INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2275     BEGIN
2276         UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2277         x := x + 1;
2278         y := x / 0;
2279     EXCEPTION
2280         WHEN division_by_zero THEN
2281             RAISE NOTICE 'caught division_by_zero';
2282             RETURN x;
2283     END;
2284 </programlisting>
2285
2286      When control reaches the assignment to <literal>y</>, it will
2287      fail with a <literal>division_by_zero</> error.  This will be caught by
2288      the <literal>EXCEPTION</> clause.  The value returned in the
2289      <command>RETURN</> statement will be the incremented value of
2290      <literal>x</>, but the effects of the <command>UPDATE</> command will
2291      have been rolled back.  The <command>INSERT</> command preceding the
2292      block is not rolled back, however, so the end result is that the database
2293      contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2294     </para>
2295
2296     <tip>
2297      <para>
2298       A block containing an <literal>EXCEPTION</> clause is significantly
2299       more expensive to enter and exit than a block without one.  Therefore,
2300       don't use <literal>EXCEPTION</> without need.
2301      </para>
2302     </tip>
2303
2304     <para>
2305      Within an exception handler, the <varname>SQLSTATE</varname>
2306      variable contains the error code that corresponds to the
2307      exception that was raised (refer to <xref
2308      linkend="errcodes-table"> for a list of possible error
2309      codes). The <varname>SQLERRM</varname> variable contains the
2310      error message associated with the exception. These variables are
2311      undefined outside exception handlers.
2312     </para>
2313
2314     <example id="plpgsql-upsert-example">
2315     <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2316     <para>
2317
2318     This example uses exception handling to perform either
2319     <command>UPDATE</> or <command>INSERT</>, as appropriate:
2320
2321 <programlisting>
2322 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2323
2324 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2325 $$
2326 BEGIN
2327     LOOP
2328         -- first try to update the key
2329         UPDATE db SET b = data WHERE a = key;
2330         IF found THEN
2331             RETURN;
2332         END IF;
2333         -- not there, so try to insert the key
2334         -- if someone else inserts the same key concurrently,
2335         -- we could get a unique-key failure
2336         BEGIN
2337             INSERT INTO db(a,b) VALUES (key, data);
2338             RETURN;
2339         EXCEPTION WHEN unique_violation THEN
2340             -- do nothing, and loop to try the UPDATE again
2341         END;
2342     END LOOP;
2343 END;
2344 $$
2345 LANGUAGE plpgsql;
2346
2347 SELECT merge_db(1, 'david');
2348 SELECT merge_db(1, 'dennis');
2349 </programlisting>
2350
2351     </para>
2352     </example>
2353   </sect2>
2354   </sect1>
2355
2356   <sect1 id="plpgsql-cursors">
2357    <title>Cursors</title>
2358
2359    <indexterm zone="plpgsql-cursors">
2360     <primary>cursor</primary>
2361     <secondary>in PL/pgSQL</secondary>
2362    </indexterm>
2363
2364    <para>
2365     Rather than executing a whole query at once, it is possible to set
2366     up a <firstterm>cursor</> that encapsulates the query, and then read
2367     the query result a few rows at a time. One reason for doing this is
2368     to avoid memory overrun when the result contains a large number of
2369     rows. (However, <application>PL/pgSQL</> users do not normally need
2370     to worry about that, since <literal>FOR</> loops automatically use a cursor
2371     internally to avoid memory problems.) A more interesting usage is to
2372     return a reference to a cursor that a function has created, allowing the
2373     caller to read the rows. This provides an efficient way to return
2374     large row sets from functions.
2375    </para>
2376
2377    <sect2 id="plpgsql-cursor-declarations">
2378     <title>Declaring Cursor Variables</title>
2379
2380     <para>
2381      All access to cursors in <application>PL/pgSQL</> goes through
2382      cursor variables, which are always of the special data type
2383      <type>refcursor</>.  One way to create a cursor variable
2384      is just to declare it as a variable of type <type>refcursor</>.
2385      Another way is to use the cursor declaration syntax,
2386      which in general is:
2387 <synopsis>
2388 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2389 </synopsis>
2390      (<literal>FOR</> can be replaced by <literal>IS</> for
2391      <productname>Oracle</productname> compatibility.)
2392      If <literal>SCROLL</> is specified, the cursor will be capable of
2393      scrolling backward; if <literal>NO SCROLL</> is specified, backward
2394      fetches will be rejected; if neither specification appears, it is
2395      query-dependent whether backward fetches will be allowed.
2396      <replaceable>arguments</replaceable>, if specified, is a
2397      comma-separated list of pairs <literal><replaceable>name</replaceable>
2398      <replaceable>datatype</replaceable></literal> that define names to be
2399      replaced by parameter values in the given query.  The actual
2400      values to substitute for these names will be specified later,
2401      when the cursor is opened.
2402     </para>
2403     <para>
2404      Some examples:
2405 <programlisting>
2406 DECLARE
2407     curs1 refcursor;
2408     curs2 CURSOR FOR SELECT * FROM tenk1;
2409     curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
2410 </programlisting>
2411      All three of these variables have the data type <type>refcursor</>,
2412      but the first can be used with any query, while the second has
2413      a fully specified query already <firstterm>bound</> to it, and the last
2414      has a parameterized query bound to it.  (<literal>key</> will be
2415      replaced by an integer parameter value when the cursor is opened.)
2416      The variable <literal>curs1</>
2417      is said to be <firstterm>unbound</> since it is not bound to
2418      any particular query.
2419     </para>
2420    </sect2>
2421
2422    <sect2 id="plpgsql-cursor-opening">
2423     <title>Opening Cursors</title>
2424
2425     <para>
2426      Before a cursor can be used to retrieve rows, it must be
2427      <firstterm>opened</>. (This is the equivalent action to the SQL
2428      command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2429      three forms of the <command>OPEN</> statement, two of which use unbound
2430      cursor variables while the third uses a bound cursor variable.
2431     </para>
2432
2433     <note>
2434      <para>
2435       Bound cursors can also be used without explicitly opening them,
2436       via the <command>FOR</> statement described in
2437       <xref linkend="plpgsql-cursor-for-loop">.
2438      </para>
2439     </note>
2440
2441     <sect3>
2442      <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2443
2444 <synopsis>
2445 OPEN <replaceable>unbound_cursor</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2446 </synopsis>
2447
2448        <para>
2449         The cursor variable is opened and given the specified query to
2450         execute.  The cursor cannot be open already, and it must have been
2451         declared as an unbound cursor (that is, as a simple
2452         <type>refcursor</> variable).  The query must be a
2453         <command>SELECT</command>, or something else that returns rows
2454         (such as <command>EXPLAIN</>).  The query
2455         is treated in the same way as other SQL commands in
2456         <application>PL/pgSQL</>: <application>PL/pgSQL</>
2457         variable names are substituted, and the query plan is cached for
2458         possible reuse.  When a <application>PL/pgSQL</>
2459         variable is substituted into the cursor query, the value that is
2460         substituted is the one it has at the time of the <command>OPEN</>;
2461         subsequent changes to the variable will not affect the cursor's
2462         behavior.
2463         The <literal>SCROLL</> and <literal>NO SCROLL</>
2464         options have the same meanings as for a bound cursor.
2465        </para>
2466
2467        <para>
2468         An example:
2469 <programlisting>
2470 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2471 </programlisting>
2472        </para>
2473      </sect3>
2474
2475     <sect3>
2476      <title><command>OPEN FOR EXECUTE</command></title>
2477
2478 <synopsis>
2479 OPEN <replaceable>unbound_cursor</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>;
2480 </synopsis>
2481
2482          <para>
2483           The cursor variable is opened and given the specified query to
2484           execute.  The cursor cannot be open already, and it must have been
2485           declared as an unbound cursor (that is, as a simple
2486           <type>refcursor</> variable).  The query is specified as a string
2487           expression, in the same way as in the <command>EXECUTE</command>
2488           command.  As usual, this gives flexibility so the query plan can vary
2489           from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2490           and it also means that variable substitution is not done on the
2491           command string.
2492           The <literal>SCROLL</> and
2493           <literal>NO SCROLL</> options have the same meanings as for a bound
2494           cursor.
2495          </para>
2496
2497        <para>
2498         An example:
2499 <programlisting>
2500 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident($1);
2501 </programlisting>
2502        </para>
2503      </sect3>
2504
2505     <sect3>
2506      <title>Opening a Bound Cursor</title>
2507
2508 <synopsis>
2509 OPEN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
2510 </synopsis>
2511
2512          <para>
2513           This form of <command>OPEN</command> is used to open a cursor
2514           variable whose query was bound to it when it was declared.  The
2515           cursor cannot be open already.  A list of actual argument value
2516           expressions must appear if and only if the cursor was declared to
2517           take arguments.  These values will be substituted in the query.
2518           The query plan for a bound cursor is always considered cacheable;
2519           there is no equivalent of <command>EXECUTE</command> in this case.
2520           Notice that <literal>SCROLL</> and
2521           <literal>NO SCROLL</> cannot be specified, as the cursor's scrolling
2522           behavior was already determined.
2523          </para>
2524
2525          <para>
2526           Note that because variable substitution is done on the bound
2527           cursor's query, there are two ways to pass values into the cursor:
2528           either with an explicit argument to <command>OPEN</>, or
2529           implicitly by referencing a <application>PL/pgSQL</> variable
2530           in the query.  However, only variables declared before the bound
2531           cursor was declared will be substituted into it.  In either case
2532           the value to be passed is determined at the time of the
2533           <command>OPEN</>.
2534          </para>
2535
2536     <para>
2537      Examples:
2538 <programlisting>
2539 OPEN curs2;
2540 OPEN curs3(42);
2541 </programlisting>
2542        </para>
2543      </sect3>
2544    </sect2>
2545
2546    <sect2 id="plpgsql-cursor-using">
2547     <title>Using Cursors</title>
2548
2549     <para>
2550      Once a cursor has been opened, it can be manipulated with the
2551      statements described here.
2552     </para>
2553
2554     <para>
2555      These manipulations need not occur in the same function that
2556      opened the cursor to begin with.  You can return a <type>refcursor</>
2557      value out of a function and let the caller operate on the cursor.
2558      (Internally, a <type>refcursor</> value is simply the string name
2559      of a so-called portal containing the active query for the cursor.  This name
2560      can be passed around, assigned to other <type>refcursor</> variables,
2561      and so on, without disturbing the portal.)
2562     </para>
2563
2564     <para>
2565      All portals are implicitly closed at transaction end.  Therefore
2566      a <type>refcursor</> value is usable to reference an open cursor
2567      only until the end of the transaction.
2568     </para>
2569
2570     <sect3>
2571      <title><literal>FETCH</></title>
2572
2573 <synopsis>
2574 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2575 </synopsis>
2576
2577     <para>
2578      <command>FETCH</command> retrieves the next row from the
2579      cursor into a target, which might be a row variable, a record
2580      variable, or a comma-separated list of simple variables, just like
2581      <command>SELECT INTO</command>.  If there is no next row, the
2582      target is set to NULL(s).  As with <command>SELECT
2583      INTO</command>, the special variable <literal>FOUND</literal> can
2584      be checked to see whether a row was obtained or not.
2585     </para>
2586
2587     <para>
2588      The <replaceable>direction</replaceable> clause can be any of the
2589      variants allowed in the SQL <xref linkend="sql-fetch"
2590      endterm="sql-fetch-title"> command except the ones that can fetch
2591      more than one row; namely, it can be
2592      <literal>NEXT</>,
2593      <literal>PRIOR</>,
2594      <literal>FIRST</>,
2595      <literal>LAST</>,
2596      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2597      <literal>RELATIVE</> <replaceable>count</replaceable>,
2598      <literal>FORWARD</>, or
2599      <literal>BACKWARD</>.
2600      Omitting <replaceable>direction</replaceable> is the same
2601      as specifying <literal>NEXT</>.
2602      <replaceable>direction</replaceable> values that require moving
2603      backward are likely to fail unless the cursor was declared or opened
2604      with the <literal>SCROLL</> option.
2605     </para>
2606
2607     <para>
2608      <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2609      variable that references an open cursor portal.
2610     </para>
2611
2612     <para>
2613      Examples:
2614 <programlisting>
2615 FETCH curs1 INTO rowvar;
2616 FETCH curs2 INTO foo, bar, baz;
2617 FETCH LAST FROM curs3 INTO x, y;
2618 FETCH RELATIVE -2 FROM curs4 INTO x;
2619 </programlisting>
2620        </para>
2621      </sect3>
2622
2623     <sect3>
2624      <title><literal>MOVE</></title>
2625
2626 <synopsis>
2627 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2628 </synopsis>
2629
2630     <para>
2631      <command>MOVE</command> repositions a cursor without retrieving
2632      any data. <command>MOVE</command> works exactly like the
2633      <command>FETCH</command> command, except it only repositions the
2634      cursor and does not return the row moved to. As with <command>SELECT
2635      INTO</command>, the special variable <literal>FOUND</literal> can
2636      be checked to see whether there was a next row to move to.
2637     </para>
2638
2639     <para>
2640      The options for the <replaceable>direction</replaceable> clause are
2641      the same as for <command>FETCH</>, namely
2642      <literal>NEXT</>,
2643      <literal>PRIOR</>,
2644      <literal>FIRST</>,
2645      <literal>LAST</>,
2646      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2647      <literal>RELATIVE</> <replaceable>count</replaceable>,
2648      <literal>FORWARD</>, or
2649      <literal>BACKWARD</>.
2650      Omitting <replaceable>direction</replaceable> is the same
2651      as specifying <literal>NEXT</>.
2652      <replaceable>direction</replaceable> values that require moving
2653      backward are likely to fail unless the cursor was declared or opened
2654      with the <literal>SCROLL</> option.
2655     </para>
2656
2657     <para>
2658      Examples:
2659 <programlisting>
2660 MOVE curs1;
2661 MOVE LAST FROM curs3;
2662 MOVE RELATIVE -2 FROM curs4;
2663 </programlisting>
2664        </para>
2665      </sect3>
2666
2667     <sect3>
2668      <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
2669
2670 <synopsis>
2671 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
2672 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
2673 </synopsis>
2674
2675        <para>
2676         When a cursor is positioned on a table row, that row can be updated
2677         or deleted using the cursor to identify the row.  There are
2678         restrictions on what the cursor's query can be (in particular,
2679         no grouping) and it's best to use <literal>FOR UPDATE</> in the
2680         cursor.  For additional information see the
2681         <xref linkend="sql-declare" endterm="sql-declare-title">
2682         reference page.
2683        </para>
2684
2685        <para>
2686         An example:
2687 <programlisting>
2688 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
2689 </programlisting>
2690        </para>
2691      </sect3>
2692
2693     <sect3>
2694      <title><literal>CLOSE</></title>
2695
2696 <synopsis>
2697 CLOSE <replaceable>cursor</replaceable>;
2698 </synopsis>
2699
2700        <para>
2701         <command>CLOSE</command> closes the portal underlying an open
2702         cursor.  This can be used to release resources earlier than end of
2703         transaction, or to free up the cursor variable to be opened again.
2704        </para>
2705
2706        <para>
2707         An example:
2708 <programlisting>
2709 CLOSE curs1;
2710 </programlisting>
2711        </para>
2712      </sect3>
2713
2714     <sect3>
2715      <title>Returning Cursors</title>
2716
2717        <para>
2718         <application>PL/pgSQL</> functions can return cursors to the
2719         caller. This is useful to return multiple rows or columns,
2720         especially with very large result sets.  To do this, the function
2721         opens the cursor and returns the cursor name to the caller (or simply
2722         opens the cursor using a portal name specified by or otherwise known
2723         to the caller).  The caller can then fetch rows from the cursor. The
2724         cursor can be closed by the caller, or it will be closed automatically
2725         when the transaction closes.
2726        </para>
2727
2728        <para>
2729         The portal name used for a cursor can be specified by the
2730         programmer or automatically generated.  To specify a portal name,
2731         simply assign a string to the <type>refcursor</> variable before
2732         opening it.  The string value of the <type>refcursor</> variable
2733         will be used by <command>OPEN</> as the name of the underlying portal.
2734         However, if the <type>refcursor</> variable is null,
2735         <command>OPEN</> automatically generates a name that does not
2736         conflict with any existing portal, and assigns it to the
2737         <type>refcursor</> variable.
2738        </para>
2739
2740        <note>
2741         <para>
2742          A bound cursor variable is initialized to the string value
2743          representing its name, so that the portal name is the same as
2744          the cursor variable name, unless the programmer overrides it
2745          by assignment before opening the cursor.  But an unbound cursor
2746          variable defaults to the null value initially, so it will receive
2747          an automatically-generated unique name, unless overridden.
2748         </para>
2749        </note>
2750
2751        <para>
2752         The following example shows one way a cursor name can be supplied by
2753         the caller:
2754
2755 <programlisting>
2756 CREATE TABLE test (col text);
2757 INSERT INTO test VALUES ('123');
2758
2759 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
2760 BEGIN
2761     OPEN $1 FOR SELECT col FROM test;
2762     RETURN $1;
2763 END;
2764 ' LANGUAGE plpgsql;
2765
2766 BEGIN;
2767 SELECT reffunc('funccursor');
2768 FETCH ALL IN funccursor;
2769 COMMIT;
2770 </programlisting>
2771        </para>
2772
2773        <para>
2774         The following example uses automatic cursor name generation:
2775
2776 <programlisting>
2777 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
2778 DECLARE
2779     ref refcursor;
2780 BEGIN
2781     OPEN ref FOR SELECT col FROM test;
2782     RETURN ref;
2783 END;
2784 ' LANGUAGE plpgsql;
2785
2786 BEGIN;
2787 SELECT reffunc2();
2788
2789       reffunc2
2790 --------------------
2791  &lt;unnamed cursor 1&gt;
2792 (1 row)
2793
2794 FETCH ALL IN "&lt;unnamed cursor 1&gt;";
2795 COMMIT;
2796 </programlisting>
2797        </para>
2798
2799        <para>
2800         The following example shows one way to return multiple cursors
2801         from a single function:
2802
2803 <programlisting>
2804 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
2805 BEGIN
2806     OPEN $1 FOR SELECT * FROM table_1;
2807     RETURN NEXT $1;
2808     OPEN $2 FOR SELECT * FROM table_2;
2809     RETURN NEXT $2;
2810 END;
2811 $$ LANGUAGE plpgsql;
2812
2813 -- need to be in a transaction to use cursors.
2814 BEGIN;
2815
2816 SELECT * FROM myfunc('a', 'b');
2817
2818 FETCH ALL FROM a;
2819 FETCH ALL FROM b;
2820 COMMIT;
2821 </programlisting>
2822        </para>
2823      </sect3>
2824    </sect2>
2825
2826    <sect2 id="plpgsql-cursor-for-loop">
2827     <title>Looping Through a Cursor's Result</title>
2828
2829     <para>
2830      There is a variant of the <command>FOR</> statement that allows
2831      iterating through the rows returned by a cursor.  The syntax is:
2832
2833 <synopsis>
2834 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2835 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional> LOOP
2836     <replaceable>statements</replaceable>
2837 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2838 </synopsis>
2839
2840      The cursor variable must have been bound to some query when it was
2841      declared, and it <emphasis>cannot</> be open already.  The
2842      <command>FOR</> statement automatically opens the cursor, and it closes
2843      the cursor again when the loop exits.  A list of actual argument value
2844      expressions must appear if and only if the cursor was declared to take
2845      arguments.  These values will be substituted in the query, in just
2846      the same way as during an <command>OPEN</>.
2847      The variable <replaceable>recordvar</replaceable> is automatically
2848      defined as type <type>record</> and exists only inside the loop (any
2849      existing definition of the variable name is ignored within the loop).
2850      Each row returned by the cursor is successively assigned to this
2851      record variable and the loop body is executed.
2852     </para>
2853    </sect2>
2854
2855   </sect1>
2856
2857   <sect1 id="plpgsql-errors-and-messages">
2858    <title>Errors and Messages</title>
2859
2860    <indexterm>
2861     <primary>RAISE</primary>
2862    </indexterm>
2863
2864    <indexterm>
2865     <primary>reporting errors</primary>
2866     <secondary>in PL/PgSQL</secondary>
2867    </indexterm>
2868
2869    <para>
2870     Use the <command>RAISE</command> statement to report messages and
2871     raise errors.
2872
2873 <synopsis>
2874 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">expression</replaceable> <optional>, ...</optional></optional> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
2875 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> <replaceable class="parameter">condition_name</> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
2876 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> SQLSTATE '<replaceable class="parameter">sqlstate</>' <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
2877 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
2878 RAISE ;
2879 </synopsis>
2880
2881     The <replaceable class="parameter">level</replaceable> option specifies
2882     the error severity.  Allowed levels are <literal>DEBUG</literal>,
2883     <literal>LOG</literal>, <literal>INFO</literal>,
2884     <literal>NOTICE</literal>, <literal>WARNING</literal>,
2885     and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
2886     being the default.
2887     <literal>EXCEPTION</literal> raises an error (which normally aborts the
2888     current transaction); the other levels only generate messages of different
2889     priority levels.
2890     Whether messages of a particular priority are reported to the client,
2891     written to the server log, or both is controlled by the
2892     <xref linkend="guc-log-min-messages"> and
2893     <xref linkend="guc-client-min-messages"> configuration
2894     variables. See <xref linkend="runtime-config"> for more
2895     information.
2896    </para>
2897
2898    <para>
2899     After <replaceable class="parameter">level</replaceable> if any,
2900     you can write a <replaceable class="parameter">format</replaceable>
2901     (which must be a simple string literal, not an expression).  The
2902     format string specifies the error message text to be reported.
2903     The format string can be followed
2904     by optional argument expressions to be inserted into the message.
2905     Inside the format string, <literal>%</literal> is replaced by the
2906     string representation of the next optional argument's value. Write
2907     <literal>%%</literal> to emit a literal <literal>%</literal>.
2908    </para>
2909
2910    <para>
2911     In this example, the value of <literal>v_job_id</> will replace the
2912     <literal>%</literal> in the string:
2913 <programlisting>
2914 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
2915 </programlisting>
2916    </para>
2917
2918    <para>
2919     You can attach additional information to the error report by writing
2920     <literal>USING</> followed by <replaceable
2921     class="parameter">option</replaceable> = <replaceable
2922     class="parameter">expression</replaceable> items.  The allowed
2923     <replaceable class="parameter">option</replaceable> keywords are
2924     <literal>MESSAGE</>, <literal>DETAIL</>, <literal>HINT</>, and
2925     <literal>ERRCODE</>, while each <replaceable
2926     class="parameter">expression</replaceable> can be any string-valued
2927     expression.
2928     <literal>MESSAGE</> sets the error message text (this option can't
2929     be used in the form of <command>RAISE</> that includes a format
2930     string before <literal>USING</>).
2931     <literal>DETAIL</> supplies an error detail message, while
2932     <literal>HINT</> supplies a hint message.
2933     <literal>ERRCODE</> specifies the error code (SQLSTATE) to report,
2934     either by condition name as shown in <xref linkend="errcodes-appendix">,
2935     or directly as a five-character SQLSTATE code.
2936    </para>
2937
2938    <para>
2939     This example will abort the transaction with the given error message
2940     and hint:
2941 <programlisting>
2942 RAISE EXCEPTION 'Nonexistent ID --> %', user_id USING HINT = 'Please check your user id';
2943 </programlisting>
2944    </para>
2945
2946    <para>
2947     These two examples show equivalent ways of setting the SQLSTATE:
2948 <programlisting>
2949 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
2950 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
2951 </programlisting>
2952    </para>
2953
2954    <para>
2955     There is a second <command>RAISE</> syntax in which the main argument
2956     is the condition name or SQLSTATE to be reported, for example:
2957 <programlisting>
2958 RAISE division_by_zero;
2959 RAISE SQLSTATE '22012';
2960 </programlisting>
2961     In this syntax, <literal>USING</> can be used to supply a custom
2962     error message, detail, or hint.  Another way to do the earlier
2963     example is
2964 <programlisting>
2965 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
2966 </programlisting>
2967    </para>
2968
2969    <para>
2970     Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
2971     <replaceable class="parameter">level</replaceable> USING</> and put
2972     everything else into the <literal>USING</> list.
2973    </para>
2974
2975    <para>
2976     The last variant of <command>RAISE</> has no parameters at all.
2977     This form can only be used inside a <literal>BEGIN</> block's
2978     <literal>EXCEPTION</> clause;
2979     it causes the error currently being handled to be re-thrown to the
2980     next enclosing block.
2981    </para>
2982
2983    <para>
2984     If no condition name nor SQLSTATE is specified in a
2985     <command>RAISE EXCEPTION</command> command, the default is to use
2986     <literal>RAISE_EXCEPTION</> (<literal>P0001</>).  If no message
2987     text is specified, the default is to use the condition name or
2988     SQLSTATE as message text.
2989    </para>
2990
2991    <note>
2992     <para>
2993      When specifying an error code by SQLSTATE code, you are not
2994      limited to the predefined error codes, but can select any
2995      error code consisting of five digits and/or upper-case ASCII
2996      letters, other than <literal>00000</>.  It is recommended that
2997      you avoid throwing error codes that end in three zeroes, because
2998      these are category codes and can only be trapped by trapping
2999      the whole category.
3000     </para>
3001    </note>
3002
3003  </sect1>
3004
3005  <sect1 id="plpgsql-trigger">
3006   <title>Trigger Procedures</title>
3007
3008   <indexterm zone="plpgsql-trigger">
3009    <primary>trigger</primary>
3010    <secondary>in PL/pgSQL</secondary>
3011   </indexterm>
3012
3013   <para>
3014     <application>PL/pgSQL</application> can be used to define trigger
3015     procedures. A trigger procedure is created with the
3016     <command>CREATE FUNCTION</> command, declaring it as a function with
3017     no arguments and a return type of <type>trigger</type>.  Note that
3018     the function must be declared with no arguments even if it expects
3019     to receive arguments specified in <command>CREATE TRIGGER</> &mdash;
3020     trigger arguments are passed via <varname>TG_ARGV</>, as described
3021     below.
3022   </para>
3023
3024   <para>
3025    When a <application>PL/pgSQL</application> function is called as a
3026    trigger, several special variables are created automatically in the
3027    top-level block. They are:
3028
3029    <variablelist>
3030     <varlistentry>
3031      <term><varname>NEW</varname></term>
3032      <listitem>
3033       <para>
3034        Data type <type>RECORD</type>; variable holding the new
3035        database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3036        triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3037        and for <command>DELETE</command> operations.
3038       </para>
3039      </listitem>
3040     </varlistentry>
3041
3042     <varlistentry>
3043      <term><varname>OLD</varname></term>
3044      <listitem>
3045       <para>
3046        Data type <type>RECORD</type>; variable holding the old
3047        database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3048        triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3049        and for <command>INSERT</command> operations.
3050       </para>
3051      </listitem>
3052     </varlistentry>
3053
3054     <varlistentry>
3055      <term><varname>TG_NAME</varname></term>
3056      <listitem>
3057       <para>
3058        Data type <type>name</type>; variable that contains the name of the trigger actually
3059        fired.
3060       </para>
3061      </listitem>
3062     </varlistentry>
3063
3064     <varlistentry>
3065      <term><varname>TG_WHEN</varname></term>
3066      <listitem>
3067       <para>
3068        Data type <type>text</type>; a string of either
3069        <literal>BEFORE</literal> or <literal>AFTER</literal>
3070        depending on the trigger's definition.
3071       </para>
3072      </listitem>
3073     </varlistentry>
3074
3075     <varlistentry>
3076      <term><varname>TG_LEVEL</varname></term>
3077      <listitem>
3078       <para>
3079        Data type <type>text</type>; a string of either
3080        <literal>ROW</literal> or <literal>STATEMENT</literal>
3081        depending on the trigger's definition.
3082       </para>
3083      </listitem>
3084     </varlistentry>
3085
3086     <varlistentry>
3087      <term><varname>TG_OP</varname></term>
3088      <listitem>
3089       <para>
3090        Data type <type>text</type>; a string of
3091        <literal>INSERT</literal>, <literal>UPDATE</literal>,
3092        <literal>DELETE</literal>, or <literal>TRUNCATE</>
3093        telling for which operation the trigger was fired.
3094       </para>
3095      </listitem>
3096     </varlistentry>
3097
3098     <varlistentry>
3099      <term><varname>TG_RELID</varname></term>
3100      <listitem>
3101       <para>
3102        Data type <type>oid</type>; the object ID of the table that caused the
3103        trigger invocation.
3104       </para>
3105      </listitem>
3106     </varlistentry>
3107
3108     <varlistentry>
3109      <term><varname>TG_RELNAME</varname></term>
3110      <listitem>
3111       <para>
3112        Data type <type>name</type>; the name of the table that caused the trigger
3113        invocation. This is now deprecated, and could disappear in a future
3114        release. Use <literal>TG_TABLE_NAME</> instead.
3115       </para>
3116      </listitem>
3117     </varlistentry>
3118
3119     <varlistentry>
3120      <term><varname>TG_TABLE_NAME</varname></term>
3121      <listitem>
3122       <para>
3123        Data type <type>name</type>; the name of the table that
3124        caused the trigger invocation.
3125       </para>
3126      </listitem>
3127     </varlistentry>
3128
3129     <varlistentry>
3130      <term><varname>TG_TABLE_SCHEMA</varname></term>
3131      <listitem>
3132       <para>
3133        Data type <type>name</type>; the name of the schema of the
3134        table that caused the trigger invocation.
3135       </para>
3136      </listitem>
3137     </varlistentry>
3138
3139     <varlistentry>
3140      <term><varname>TG_NARGS</varname></term>
3141      <listitem>
3142       <para>
3143        Data type <type>integer</type>; the number of arguments given to the trigger
3144        procedure in the <command>CREATE TRIGGER</command> statement.
3145       </para>
3146      </listitem>
3147     </varlistentry>
3148
3149     <varlistentry>
3150      <term><varname>TG_ARGV[]</varname></term>
3151      <listitem>
3152       <para>
3153        Data type array of <type>text</type>; the arguments from
3154               the <command>CREATE TRIGGER</command> statement.
3155        The index counts from 0. Invalid
3156        indices (less than 0 or greater than or equal to <varname>tg_nargs</>) result in a null value.
3157       </para>
3158      </listitem>
3159     </varlistentry>
3160    </variablelist>
3161   </para>
3162
3163    <para>
3164     A trigger function must return either <symbol>NULL</symbol> or a
3165     record/row value having exactly the structure of the table the
3166     trigger was fired for.
3167    </para>
3168
3169    <para>
3170     Row-level triggers fired <literal>BEFORE</> can return null to signal the
3171     trigger manager to skip the rest of the operation for this row
3172     (i.e., subsequent triggers are not fired, and the
3173     <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3174     for this row).  If a nonnull
3175     value is returned then the operation proceeds with that row value.
3176     Returning a row value different from the original value
3177     of <varname>NEW</> alters the row that will be inserted or updated
3178     (but has no direct effect in the <command>DELETE</> case).
3179     To alter the row to be stored, it is possible to replace single values
3180     directly in <varname>NEW</> and return the modified <varname>NEW</>,
3181     or to build a complete new record/row to return.
3182    </para>
3183
3184    <para>
3185     The return value of a <literal>BEFORE</> or <literal>AFTER</>
3186     statement-level trigger or an <literal>AFTER</> row-level trigger is
3187     always ignored; it might as well be null. However, any of these types of
3188     triggers might still abort the entire operation by raising an error.
3189    </para>
3190
3191    <para>
3192     <xref linkend="plpgsql-trigger-example"> shows an example of a
3193     trigger procedure in <application>PL/pgSQL</application>.
3194    </para>
3195
3196    <example id="plpgsql-trigger-example">
3197     <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3198
3199     <para>
3200      This example trigger ensures that any time a row is inserted or updated
3201      in the table, the current user name and time are stamped into the
3202      row. And it checks that an employee's name is given and that the
3203      salary is a positive value.
3204     </para>
3205
3206 <programlisting>
3207 CREATE TABLE emp (
3208     empname text,
3209     salary integer,
3210     last_date timestamp,
3211     last_user text
3212 );
3213
3214 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3215     BEGIN
3216         -- Check that empname and salary are given
3217         IF NEW.empname IS NULL THEN
3218             RAISE EXCEPTION 'empname cannot be null';
3219         END IF;
3220         IF NEW.salary IS NULL THEN
3221             RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3222         END IF;
3223
3224         -- Who works for us when she must pay for it?
3225         IF NEW.salary &lt; 0 THEN
3226             RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3227         END IF;
3228
3229         -- Remember who changed the payroll when
3230         NEW.last_date := current_timestamp;
3231         NEW.last_user := current_user;
3232         RETURN NEW;
3233     END;
3234 $emp_stamp$ LANGUAGE plpgsql;
3235
3236 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3237     FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3238 </programlisting>
3239    </example>
3240
3241    <para>
3242     Another way to log changes to a table involves creating a new table that
3243     holds a row for each insert, update, or delete that occurs. This approach
3244     can be thought of as auditing changes to a table.
3245     <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3246     audit trigger procedure in <application>PL/pgSQL</application>.
3247    </para>
3248
3249    <example id="plpgsql-trigger-audit-example">
3250     <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3251
3252     <para>
3253      This example trigger ensures that any insert, update or delete of a row
3254      in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3255      The current time and user name are stamped into the row, together with
3256      the type of operation performed on it.
3257     </para>
3258
3259 <programlisting>
3260 CREATE TABLE emp (
3261     empname           text NOT NULL,
3262     salary            integer
3263 );
3264
3265 CREATE TABLE emp_audit(
3266     operation         char(1)   NOT NULL,
3267     stamp             timestamp NOT NULL,
3268     userid            text      NOT NULL,
3269     empname           text      NOT NULL,
3270     salary integer
3271 );
3272
3273 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3274     BEGIN
3275         --
3276         -- Create a row in emp_audit to reflect the operation performed on emp,
3277         -- make use of the special variable TG_OP to work out the operation.
3278         --
3279         IF (TG_OP = 'DELETE') THEN
3280             INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3281             RETURN OLD;
3282         ELSIF (TG_OP = 'UPDATE') THEN
3283             INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3284             RETURN NEW;
3285         ELSIF (TG_OP = 'INSERT') THEN
3286             INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3287             RETURN NEW;
3288         END IF;
3289         RETURN NULL; -- result is ignored since this is an AFTER trigger
3290     END;
3291 $emp_audit$ LANGUAGE plpgsql;
3292
3293 CREATE TRIGGER emp_audit
3294 AFTER INSERT OR UPDATE OR DELETE ON emp
3295     FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3296 </programlisting>
3297    </example>
3298
3299    <para>
3300     One use of triggers is to maintain a summary table
3301     of another table. The resulting summary can be used in place of the
3302     original table for certain queries &mdash; often with vastly reduced run
3303     times.
3304     This technique is commonly used in Data Warehousing, where the tables
3305     of measured or observed data (called fact tables) might be extremely large.
3306     <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3307     trigger procedure in <application>PL/pgSQL</application> that maintains
3308     a summary table for a fact table in a data warehouse.
3309    </para>
3310
3311
3312    <example id="plpgsql-trigger-summary-example">
3313     <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3314
3315     <para>
3316      The schema detailed here is partly based on the <emphasis>Grocery Store
3317      </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3318      by Ralph Kimball.
3319     </para>
3320
3321 <programlisting>
3322 --
3323 -- Main tables - time dimension and sales fact.
3324 --
3325 CREATE TABLE time_dimension (
3326     time_key                    integer NOT NULL,
3327     day_of_week                 integer NOT NULL,
3328     day_of_month                integer NOT NULL,
3329     month                       integer NOT NULL,
3330     quarter                     integer NOT NULL,
3331     year                        integer NOT NULL
3332 );
3333 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3334
3335 CREATE TABLE sales_fact (
3336     time_key                    integer NOT NULL,
3337     product_key                 integer NOT NULL,
3338     store_key                   integer NOT NULL,
3339     amount_sold                 numeric(12,2) NOT NULL,
3340     units_sold                  integer NOT NULL,
3341     amount_cost                 numeric(12,2) NOT NULL
3342 );
3343 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3344
3345 --
3346 -- Summary table - sales by time.
3347 --
3348 CREATE TABLE sales_summary_bytime (
3349     time_key                    integer NOT NULL,
3350     amount_sold                 numeric(15,2) NOT NULL,
3351     units_sold                  numeric(12) NOT NULL,
3352     amount_cost                 numeric(15,2) NOT NULL
3353 );
3354 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3355
3356 --
3357 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3358 --
3359 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER AS $maint_sales_summary_bytime$
3360     DECLARE
3361         delta_time_key          integer;
3362         delta_amount_sold       numeric(15,2);
3363         delta_units_sold        numeric(12);
3364         delta_amount_cost       numeric(15,2);
3365     BEGIN
3366
3367         -- Work out the increment/decrement amount(s).
3368         IF (TG_OP = 'DELETE') THEN
3369
3370             delta_time_key = OLD.time_key;
3371             delta_amount_sold = -1 * OLD.amount_sold;
3372             delta_units_sold = -1 * OLD.units_sold;
3373             delta_amount_cost = -1 * OLD.amount_cost;
3374
3375         ELSIF (TG_OP = 'UPDATE') THEN
3376
3377             -- forbid updates that change the time_key -
3378             -- (probably not too onerous, as DELETE + INSERT is how most
3379             -- changes will be made).
3380             IF ( OLD.time_key != NEW.time_key) THEN
3381                 RAISE EXCEPTION 'Update of time_key : % -&gt; % not allowed', OLD.time_key, NEW.time_key;
3382             END IF;
3383
3384             delta_time_key = OLD.time_key;
3385             delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3386             delta_units_sold = NEW.units_sold - OLD.units_sold;
3387             delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3388
3389         ELSIF (TG_OP = 'INSERT') THEN
3390
3391             delta_time_key = NEW.time_key;
3392             delta_amount_sold = NEW.amount_sold;
3393             delta_units_sold = NEW.units_sold;
3394             delta_amount_cost = NEW.amount_cost;
3395
3396         END IF;
3397
3398
3399         -- Insert or update the summary row with the new values.
3400         &lt;&lt;insert_update&gt;&gt;
3401         LOOP
3402             UPDATE sales_summary_bytime
3403                 SET amount_sold = amount_sold + delta_amount_sold,
3404                     units_sold = units_sold + delta_units_sold,
3405                     amount_cost = amount_cost + delta_amount_cost
3406                 WHERE time_key = delta_time_key;
3407
3408             EXIT insert_update WHEN found;
3409
3410             BEGIN
3411                 INSERT INTO sales_summary_bytime (
3412                             time_key,
3413                             amount_sold,
3414                             units_sold,
3415                             amount_cost)
3416                     VALUES (
3417                             delta_time_key,
3418                             delta_amount_sold,
3419                             delta_units_sold,
3420                             delta_amount_cost
3421                            );
3422
3423                 EXIT insert_update;
3424
3425             EXCEPTION
3426                 WHEN UNIQUE_VIOLATION THEN
3427                     -- do nothing
3428             END;
3429         END LOOP insert_update;
3430
3431         RETURN NULL;
3432
3433     END;
3434 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3435
3436 CREATE TRIGGER maint_sales_summary_bytime
3437 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3438     FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3439
3440 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3441 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3442 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3443 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3444 SELECT * FROM sales_summary_bytime;
3445 DELETE FROM sales_fact WHERE product_key = 1;
3446 SELECT * FROM sales_summary_bytime;
3447 UPDATE sales_fact SET units_sold = units_sold * 2;
3448 SELECT * FROM sales_summary_bytime;
3449 </programlisting>
3450    </example>
3451
3452   </sect1>
3453
3454   <sect1 id="plpgsql-implementation">
3455    <title><application>PL/pgSQL</> Under the Hood</title>
3456
3457    <para>
3458     This section discusses some implementation details that are
3459     frequently important for <application>PL/pgSQL</> users to know.
3460    </para>
3461
3462   <sect2 id="plpgsql-var-subst">
3463    <title>Variable Substitution</title>
3464
3465    <para>
3466     When <application>PL/pgSQL</> prepares a SQL statement or expression
3467     for execution, any <application>PL/pgSQL</application> variable name
3468     appearing in the statement or expression is replaced by a parameter symbol,
3469     <literal>$<replaceable>n</replaceable></literal>.  The current value
3470     of the variable is then provided as the value for the parameter whenever
3471     the statement or expression is executed.  As an example, consider the
3472     function
3473 <programlisting>
3474 CREATE FUNCTION logfunc(logtxt text) RETURNS void AS $$
3475     DECLARE
3476         curtime timestamp := now();
3477     BEGIN
3478         INSERT INTO logtable VALUES (logtxt, curtime);
3479     END;
3480 $$ LANGUAGE plpgsql;
3481 </programlisting>
3482     The <command>INSERT</> statement will effectively be processed as
3483 <programlisting>
3484 PREPARE <replaceable>statement_name</>(text, timestamp) AS
3485   INSERT INTO logtable VALUES ($1, $2);
3486 </programlisting>
3487     followed on each execution by <command>EXECUTE</> with the current
3488     actual values of the two variables.  (Note: here we are speaking of
3489     the main SQL engine's
3490     <xref linkend="sql-execute" endterm="sql-execute-title"> command,
3491     not <application>PL/pgSQL</application>'s <command>EXECUTE</>.)
3492    </para>
3493
3494    <para>
3495     <emphasis>The substitution mechanism will replace any token that matches a
3496     known variable's name.</>  This poses various traps for the unwary.
3497     For example, it is a bad idea
3498     to use a variable name that is the same as any table or column name
3499     that you need to reference in queries within the function, because
3500     what you think is a table or column name will still get replaced.
3501     In the above example, suppose that <structname>logtable</> has
3502     column names <structfield>logtxt</> and <structfield>logtime</>,
3503     and we try to write the <command>INSERT</> as
3504 <programlisting>
3505         INSERT INTO logtable (logtxt, logtime) VALUES (logtxt, curtime);
3506 </programlisting>
3507     This will be fed to the main SQL parser as
3508 <programlisting>
3509         INSERT INTO logtable ($1, logtime) VALUES ($1, $2);
3510 </programlisting>
3511     resulting in a syntax error like this:
3512 <screen>
3513 ERROR:  syntax error at or near "$1"
3514 LINE 1: INSERT INTO logtable ( $1 , logtime) VALUES ( $1 ,  $2 )
3515                                ^
3516 QUERY:  INSERT INTO logtable ( $1 , logtime) VALUES ( $1 ,  $2 )
3517 CONTEXT:  SQL statement in PL/PgSQL function "logfunc2" near line 5
3518 </screen>
3519    </para>
3520
3521    <para>
3522     This example is fairly easy to diagnose, since it leads to an
3523     obvious syntax error.  Much nastier are cases where the substitution
3524     is syntactically permissible, since the only symptom may be misbehavior
3525     of the function.  In one case, a user wrote something like this:
3526 <programlisting>
3527     DECLARE
3528         val text;
3529         search_key integer;
3530     BEGIN
3531         ...
3532         FOR val IN SELECT val FROM table WHERE key = search_key LOOP ...
3533 </programlisting>
3534     and wondered why all his table entries seemed to be NULL.  Of course
3535     what happened here was that the query became
3536 <programlisting>
3537         SELECT $1 FROM table WHERE key = $2
3538 </programlisting>
3539     and thus it was just an expensive way of assigning <literal>val</>'s
3540     current value back to itself for each row.
3541    </para>
3542
3543    <para>
3544     A commonly used coding rule for avoiding such traps is to use a
3545     different naming convention for <application>PL/pgSQL</application>
3546     variables than you use for table and column names.  For example,
3547     if all your variables are named
3548     <literal>v_<replaceable>something</></literal> while none of your
3549     table or column names start with <literal>v_</>, you're pretty safe.
3550    </para>
3551
3552    <para>
3553     Another workaround is to use qualified (dotted) names for SQL entities.
3554     For instance we could safely have written the above example as
3555 <programlisting>
3556         FOR val IN SELECT table.val FROM table WHERE key = search_key LOOP ...
3557 </programlisting>
3558     because <application>PL/pgSQL</application> will not substitute a
3559     variable for a trailing component of a qualified name.
3560     However this solution does not work in every case &mdash; you can't
3561     qualify a name in an <command>INSERT</>'s column name list, for instance.
3562     Another point is that record and row variable names will be matched to
3563     the first components of qualified names, so a qualified SQL name is
3564     still vulnerable in some cases.
3565     In such cases choosing a non-conflicting variable name is the only way.
3566    </para>
3567
3568    <para>
3569     Another technique you can use is to attach a label to the block in
3570     which your variables are declared, and then qualify the variable names
3571     in your SQL commands (see <xref linkend="plpgsql-structure">).
3572     For example,
3573 <programlisting>
3574     &lt;&lt;pl&gt;&gt;
3575     DECLARE
3576         val text;
3577     BEGIN
3578         ...
3579         UPDATE table SET col = pl.val WHERE ...
3580 </programlisting>
3581     This is not in itself a solution to the problem of conflicts,
3582     since an unqualified name in a SQL command is still at risk of being
3583     interpreted the <quote>wrong</> way.  But it is useful for clarifying
3584     the intent of potentially-ambiguous code.
3585    </para>
3586
3587    <para>
3588     Variable substitution does not happen in the command string given
3589     to <command>EXECUTE</> or one of its variants.  If you need to
3590     insert a varying value into such a command, do so as part of
3591     constructing the string value, as illustrated in
3592     <xref linkend="plpgsql-statements-executing-dyn">.
3593    </para>
3594
3595    <para>
3596     Variable substitution currently works only in <command>SELECT</>,
3597     <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
3598     because the main SQL engine allows parameter symbols only in these
3599     commands.  To use a non-constant name or value in other statement
3600     types (generically called utility statements), you must construct
3601     the utility statement as a string and <command>EXECUTE</> it.
3602    </para>
3603
3604   </sect2>
3605
3606   <sect2 id="plpgsql-plan-caching">
3607    <title>Plan Caching</title>
3608
3609    <para>
3610     The <application>PL/pgSQL</> interpreter parses the function's source
3611     text and produces an internal binary instruction tree the first time the
3612     function is called (within each session).  The instruction tree
3613     fully translates the
3614     <application>PL/pgSQL</> statement structure, but individual
3615     <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
3616     used in the function are not translated immediately.
3617    </para>
3618
3619    <para>
3620     As each expression and <acronym>SQL</acronym> command is first
3621     executed in the function, the <application>PL/pgSQL</> interpreter
3622     creates a prepared execution plan (using the
3623     <acronym>SPI</acronym> manager's <function>SPI_prepare</function>
3624     and <function>SPI_saveplan</function>
3625     functions).<indexterm><primary>preparing a query</><secondary>in
3626     PL/pgSQL</></> Subsequent visits to that expression or command
3627     reuse the prepared plan.  Thus, a function with conditional code
3628     that contains many statements for which execution plans might be
3629     required will only prepare and save those plans that are really
3630     used during the lifetime of the database connection.  This can
3631     substantially reduce the total amount of time required to parse
3632     and generate execution plans for the statements in a
3633     <application>PL/pgSQL</> function. A disadvantage is that errors
3634     in a specific expression or command cannot be detected until that
3635     part of the function is reached in execution.  (Trivial syntax
3636     errors will be detected during the initial parsing pass, but
3637     anything deeper will not be detected until execution.)
3638    </para>
3639
3640    <para>
3641     Once <application>PL/pgSQL</> has made an execution plan for a particular
3642     command in a function, it will reuse that plan for the life of the
3643     database connection.  This is usually a win for performance, but it
3644     can cause some problems if you dynamically
3645     alter your database schema. For example:
3646
3647 <programlisting>
3648 CREATE FUNCTION populate() RETURNS integer AS $$
3649 DECLARE
3650     -- declarations
3651 BEGIN
3652     PERFORM my_function();
3653 END;
3654 $$ LANGUAGE plpgsql;
3655 </programlisting>
3656
3657     If you execute the above function, it will reference the OID for
3658     <function>my_function()</function> in the execution plan produced for
3659     the <command>PERFORM</command> statement. Later, if you
3660     drop and recreate <function>my_function()</function>, then
3661     <function>populate()</function> will not be able to find
3662     <function>my_function()</function> anymore. You would then have to
3663     start a new database session so that <function>populate()</function>
3664     will be compiled afresh, before it will work again. You can avoid
3665     this problem by using <command>CREATE OR REPLACE FUNCTION</command>
3666     when updating the definition of
3667     <function>my_function</function>, since when a function is
3668     <quote>replaced</quote>, its OID is not changed.
3669    </para>
3670
3671    <note>
3672     <para>
3673      In <productname>PostgreSQL</productname> 8.3 and later, saved plans
3674      will be replaced whenever any schema changes have occurred to any
3675      tables they reference.  This eliminates one of the major disadvantages
3676      of saved plans.  However, there is no such mechanism for function
3677      references, and thus the above example involving a reference to a
3678      deleted function is still valid.
3679     </para>
3680    </note>
3681
3682    <para>
3683     Because <application>PL/pgSQL</application> saves execution plans
3684     in this way, SQL commands that appear directly in a
3685     <application>PL/pgSQL</application> function must refer to the
3686     same tables and columns on every execution; that is, you cannot use
3687     a parameter as the name of a table or column in an SQL command.  To get
3688     around this restriction, you can construct dynamic commands using
3689     the <application>PL/pgSQL</application> <command>EXECUTE</command>
3690     statement &mdash; at the price of constructing a new execution plan on
3691     every execution.
3692    </para>
3693
3694    <para>
3695     Another important point is that the prepared plans are parameterized
3696     to allow the values of <application>PL/pgSQL</application> variables
3697     to change from one use to the next, as discussed in detail above.
3698     Sometimes this means that a plan is less efficient than it would be
3699     if generated for a specific variable value.  As an example, consider
3700 <programlisting>
3701 SELECT * INTO myrec FROM dictionary WHERE word LIKE search_term;
3702 </programlisting>
3703     where <literal>search_term</> is a <application>PL/pgSQL</application>
3704     variable.  The cached plan for this query will never use an index on
3705     <structfield>word</>, since the planner cannot assume that the
3706     <literal>LIKE</> pattern will be left-anchored at run time.  To use
3707     an index the query must be planned with a specific constant
3708     <literal>LIKE</> pattern provided.  This is another situation where
3709     <command>EXECUTE</command> can be used to force a new plan to be
3710     generated for each execution.
3711    </para>
3712
3713     <para>
3714      The mutable nature of record variables presents another problem in this
3715      connection.  When fields of a record variable are used in
3716      expressions or statements, the data types of the fields must not
3717      change from one call of the function to the next, since each
3718      expression will be planned using the data type that is present
3719      when the expression is first reached.  <command>EXECUTE</command> can be
3720      used to get around this problem when necessary.
3721     </para>
3722
3723     <para>
3724      If the same function is used as a trigger for more than one table,
3725      <application>PL/pgSQL</application> prepares and caches plans
3726      independently for each such table &mdash; that is, there is a cache
3727      for each trigger function and table combination, not just for each
3728      function.  This alleviates some of the problems with varying
3729      data types; for instance, a trigger function will be able to work
3730      successfully with a column named <literal>key</> even if it happens
3731      to have different types in different tables.
3732     </para>
3733
3734     <para>
3735      Likewise, functions having polymorphic argument types have a separate
3736      plan cache for each combination of actual argument types they have been
3737      invoked for, so that data type differences do not cause unexpected
3738      failures.
3739     </para>
3740
3741    <para>
3742     Plan caching can sometimes have surprising effects on the interpretation
3743     of time-sensitive values.  For example there
3744     is a difference between what these two functions do:
3745
3746 <programlisting>
3747 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
3748     BEGIN
3749         INSERT INTO logtable VALUES (logtxt, 'now');
3750     END;
3751 $$ LANGUAGE plpgsql;
3752 </programlisting>
3753
3754      and:
3755
3756 <programlisting>
3757 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
3758     DECLARE
3759         curtime timestamp;
3760     BEGIN
3761         curtime := 'now';
3762         INSERT INTO logtable VALUES (logtxt, curtime);
3763     END;
3764 $$ LANGUAGE plpgsql;
3765 </programlisting>
3766     </para>
3767
3768     <para>
3769      In the case of <function>logfunc1</function>, the
3770      <productname>PostgreSQL</productname> main parser knows when
3771      preparing the plan for the <command>INSERT</command> that the
3772      string <literal>'now'</literal> should be interpreted as
3773      <type>timestamp</type>, because the target column of
3774      <classname>logtable</classname> is of that type. Thus,
3775      <literal>'now'</literal> will be converted to a constant when the
3776      <command>INSERT</command> is planned, and then used in all
3777      invocations of <function>logfunc1</function> during the lifetime
3778      of the session. Needless to say, this isn't what the programmer
3779      wanted.
3780     </para>
3781
3782     <para>
3783      In the case of <function>logfunc2</function>, the
3784      <productname>PostgreSQL</productname> main parser does not know
3785      what type <literal>'now'</literal> should become and therefore
3786      it returns a data value of type <type>text</type> containing the string
3787      <literal>now</literal>. During the ensuing assignment
3788      to the local variable <varname>curtime</varname>, the
3789      <application>PL/pgSQL</application> interpreter casts this
3790      string to the <type>timestamp</type> type by calling the
3791      <function>text_out</function> and <function>timestamp_in</function>
3792      functions for the conversion.  So, the computed time stamp is updated
3793      on each execution as the programmer expects.
3794     </para>
3795
3796   </sect2>
3797
3798   </sect1>
3799
3800  <sect1 id="plpgsql-development-tips">
3801   <title>Tips for Developing in <application>PL/pgSQL</application></title>
3802
3803    <para>
3804     One good way to develop in
3805     <application>PL/pgSQL</> is to use the text editor of your
3806     choice to create your functions, and in another window, use
3807     <application>psql</application> to load and test those functions.
3808     If you are doing it this way, it
3809     is a good idea to write the function using <command>CREATE OR
3810     REPLACE FUNCTION</>. That way you can just reload the file to update
3811     the function definition.  For example:
3812 <programlisting>
3813 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
3814           ....
3815 $$ LANGUAGE plpgsql;
3816 </programlisting>
3817    </para>
3818
3819    <para>
3820     While running <application>psql</application>, you can load or reload such
3821     a function definition file with:
3822 <programlisting>
3823 \i filename.sql
3824 </programlisting>
3825     and then immediately issue SQL commands to test the function.
3826    </para>
3827
3828    <para>
3829     Another good way to develop in <application>PL/pgSQL</> is with a
3830     GUI database access tool that facilitates development in a
3831     procedural language. One example of such as a tool is
3832     <application>pgAdmin</>, although others exist. These tools often
3833     provide convenient features such as escaping single quotes and
3834     making it easier to recreate and debug functions.
3835    </para>
3836
3837   <sect2 id="plpgsql-quote-tips">
3838    <title>Handling of Quotation Marks</title>
3839
3840    <para>
3841     The code of a <application>PL/pgSQL</> function is specified in
3842     <command>CREATE FUNCTION</command> as a string literal.  If you
3843     write the string literal in the ordinary way with surrounding
3844     single quotes, then any single quotes inside the function body
3845     must be doubled; likewise any backslashes must be doubled (assuming
3846     escape string syntax is used).
3847     Doubling quotes is at best tedious, and in more complicated cases
3848     the code can become downright incomprehensible, because you can
3849     easily find yourself needing half a dozen or more adjacent quote marks.
3850     It's recommended that you instead write the function body as a
3851     <quote>dollar-quoted</> string literal (see <xref
3852     linkend="sql-syntax-dollar-quoting">).  In the dollar-quoting
3853     approach, you never double any quote marks, but instead take care to
3854     choose a different dollar-quoting delimiter for each level of
3855     nesting you need.  For example, you might write the <command>CREATE
3856     FUNCTION</command> command as:
3857 <programlisting>
3858 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
3859           ....
3860 $PROC$ LANGUAGE plpgsql;
3861 </programlisting>
3862     Within this, you might use quote marks for simple literal strings in
3863     SQL commands and <literal>$$</> to delimit fragments of SQL commands
3864     that you are assembling as strings.  If you need to quote text that
3865     includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
3866    </para>
3867
3868    <para>
3869     The following chart shows what you have to do when writing quote
3870     marks without dollar quoting.  It might be useful when translating
3871     pre-dollar quoting code into something more comprehensible.
3872   </para>
3873
3874   <variablelist>
3875    <varlistentry>
3876     <term>1 quotation mark</term>
3877     <listitem>
3878      <para>
3879       To begin and end the function body, for example:
3880 <programlisting>
3881 CREATE FUNCTION foo() RETURNS integer AS '
3882           ....
3883 ' LANGUAGE plpgsql;
3884 </programlisting>
3885       Anywhere within a single-quoted function body, quote marks
3886       <emphasis>must</> appear in pairs.
3887      </para>
3888     </listitem>
3889    </varlistentry>
3890
3891    <varlistentry>
3892     <term>2 quotation marks</term>
3893     <listitem>
3894      <para>
3895       For string literals inside the function body, for example:
3896 <programlisting>
3897 a_output := ''Blah'';
3898 SELECT * FROM users WHERE f_name=''foobar'';
3899 </programlisting>
3900       In the dollar-quoting approach, you'd just write:
3901 <programlisting>
3902 a_output := 'Blah';
3903 SELECT * FROM users WHERE f_name='foobar';
3904 </programlisting>
3905       which is exactly what the <application>PL/pgSQL</> parser would see
3906       in either case.
3907      </para>
3908     </listitem>
3909    </varlistentry>
3910
3911    <varlistentry>
3912     <term>4 quotation marks</term>
3913     <listitem>
3914      <para>
3915       When you need a single quotation mark in a string constant inside the
3916       function body, for example:
3917 <programlisting>
3918 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
3919 </programlisting>
3920       The value actually appended to <literal>a_output</literal> would be:
3921       <literal> AND name LIKE 'foobar' AND xyz</literal>.
3922      </para>
3923      <para>
3924       In the dollar-quoting approach, you'd write:
3925 <programlisting>
3926 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
3927 </programlisting>
3928       being careful that any dollar-quote delimiters around this are not
3929       just <literal>$$</>.
3930      </para>
3931     </listitem>
3932    </varlistentry>
3933
3934    <varlistentry>
3935     <term>6 quotation marks</term>
3936     <listitem>
3937      <para>
3938       When a single quotation mark in a string inside the function body is
3939       adjacent to the end of that string constant, for example:
3940 <programlisting>
3941 a_output := a_output || '' AND name LIKE ''''foobar''''''
3942 </programlisting>
3943       The value appended to <literal>a_output</literal> would then be:
3944       <literal> AND name LIKE 'foobar'</literal>.
3945      </para>
3946      <para>
3947       In the dollar-quoting approach, this becomes:
3948 <programlisting>
3949 a_output := a_output || $$ AND name LIKE 'foobar'$$
3950 </programlisting>
3951      </para>
3952     </listitem>
3953    </varlistentry>
3954
3955    <varlistentry>
3956     <term>10 quotation marks</term>
3957     <listitem>
3958      <para>
3959       When you want two single quotation marks in a string constant (which
3960       accounts for 8 quotation marks) and this is adjacent to the end of that
3961       string constant (2 more).  You will probably only need that if
3962       you are writing a function that generates other functions, as in
3963       <xref linkend="plpgsql-porting-ex2">.
3964       For example:
3965 <programlisting>
3966 a_output := a_output || '' if v_'' ||
3967     referrer_keys.kind || '' like ''''''''''
3968     || referrer_keys.key_string || ''''''''''
3969     then return ''''''  || referrer_keys.referrer_type
3970     || ''''''; end if;'';
3971 </programlisting>
3972       The value of <literal>a_output</literal> would then be:
3973 <programlisting>
3974 if v_... like ''...'' then return ''...''; end if;
3975 </programlisting>
3976      </para>
3977      <para>
3978       In the dollar-quoting approach, this becomes:
3979 <programlisting>
3980 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
3981     || referrer_keys.key_string || $$'
3982     then return '$$  || referrer_keys.referrer_type
3983     || $$'; end if;$$;
3984 </programlisting>
3985       where we assume we only need to put single quote marks into
3986       <literal>a_output</literal>, because it will be re-quoted before use.
3987      </para>
3988     </listitem>
3989    </varlistentry>
3990   </variablelist>
3991
3992   </sect2>
3993  </sect1>
3994
3995   <!-- **** Porting from Oracle PL/SQL **** -->
3996
3997  <sect1 id="plpgsql-porting">
3998   <title>Porting from <productname>Oracle</productname> PL/SQL</title>
3999
4000   <indexterm zone="plpgsql-porting">
4001    <primary>Oracle</primary>
4002    <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4003   </indexterm>
4004
4005   <indexterm zone="plpgsql-porting">
4006    <primary>PL/SQL (Oracle)</primary>
4007    <secondary>porting to PL/pgSQL</secondary>
4008   </indexterm>
4009
4010   <para>
4011    This section explains differences between
4012    <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4013    language and Oracle's <application>PL/SQL</application> language,
4014    to help developers who port applications from
4015    <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4016   </para>
4017
4018   <para>
4019    <application>PL/pgSQL</application> is similar to PL/SQL in many
4020    aspects. It is a block-structured, imperative language, and all
4021    variables have to be declared.  Assignments, loops, conditionals
4022    are similar.  The main differences you should keep in mind when
4023    porting from <application>PL/SQL</> to
4024    <application>PL/pgSQL</application> are:
4025
4026     <itemizedlist>
4027      <listitem>
4028       <para>
4029        There are no default values for parameters in <productname>PostgreSQL</>.
4030       </para>
4031      </listitem>
4032
4033      <listitem>
4034       <para>
4035        You can overload function names in <productname>PostgreSQL</>. This is
4036        often used to work around the lack of default parameters.
4037       </para>
4038      </listitem>
4039
4040      <listitem>
4041       <para>
4042        If a name used in a SQL command could be either a column name of a
4043        table or a reference to a variable of the function,
4044        <application>PL/SQL</> treats it as a column name, while
4045        <application>PL/pgSQL</> treats it as a variable name.  It's best
4046        to avoid such ambiguities in the first place, but if necessary you
4047        can fix them by properly qualifying the ambiguous name.
4048        (See <xref linkend="plpgsql-var-subst">.)
4049       </para>
4050      </listitem>
4051
4052      <listitem>
4053       <para>
4054        In <productname>PostgreSQL</> the function body must be written as
4055        a string literal.  Therefore you need to use dollar quoting or escape
4056        single quotes in the function body. (See <xref
4057        linkend="plpgsql-quote-tips">.)
4058       </para>
4059      </listitem>
4060
4061      <listitem>
4062       <para>
4063        Instead of packages, use schemas to organize your functions
4064        into groups.
4065       </para>
4066      </listitem>
4067
4068      <listitem>
4069       <para>
4070        Since there are no packages, there are no package-level variables
4071        either. This is somewhat annoying.  You can keep per-session state
4072        in temporary tables instead.
4073       </para>
4074      </listitem>
4075
4076      <listitem>
4077       <para>
4078        Integer <command>FOR</> loops with <literal>REVERSE</> work
4079        differently: <application>PL/SQL</> counts down from the second
4080        number to the first, while <application>PL/pgSQL</> counts down
4081        from the first number to the second, requiring the loop bounds
4082        to be swapped when porting.  This incompatibility is unfortunate
4083        but is unlikely to be changed. (See <xref
4084        linkend="plpgsql-integer-for">.)
4085       </para>
4086      </listitem>
4087
4088      <listitem>
4089       <para>
4090        <command>FOR</> loops over queries (other than cursors) also work
4091        differently: the target variable(s) must have been declared,
4092        whereas <application>PL/SQL</> always declares them implicitly.
4093        An advantage of this is that the variable values are still accessible
4094        after the loop exits.
4095       </para>
4096      </listitem>
4097
4098      <listitem>
4099       <para>
4100        There are various notational differences for the use of cursor
4101        variables.
4102       </para>
4103      </listitem>
4104
4105     </itemizedlist>
4106    </para>
4107
4108   <sect2>
4109    <title>Porting Examples</title>
4110
4111    <para>
4112     <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4113     function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4114    </para>
4115
4116    <example id="pgsql-porting-ex1">
4117     <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4118
4119     <para>
4120      Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4121 <programlisting>
4122 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4123                                                   v_version varchar)
4124 RETURN varchar IS
4125 BEGIN
4126     IF v_version IS NULL THEN
4127         RETURN v_name;
4128     END IF;
4129     RETURN v_name || '/' || v_version;
4130 END;
4131 /
4132 show errors;
4133 </programlisting>
4134     </para>
4135
4136     <para>
4137      Let's go through this function and see the differences compared to
4138      <application>PL/pgSQL</>:
4139
4140      <itemizedlist>
4141       <listitem>
4142        <para>
4143         The <literal>RETURN</literal> key word in the function
4144         prototype (not the function body) becomes
4145         <literal>RETURNS</literal> in
4146         <productname>PostgreSQL</productname>.
4147         Also, <literal>IS</> becomes <literal>AS</>, and you need to
4148         add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4149         is not the only possible function language.
4150        </para>
4151       </listitem>
4152
4153       <listitem>
4154        <para>
4155         In <productname>PostgreSQL</>, the function body is considered
4156         to be a string literal, so you need to use quote marks or dollar
4157         quotes around it.  This substitutes for the terminating <literal>/</>
4158         in the Oracle approach.
4159        </para>
4160       </listitem>
4161
4162       <listitem>
4163        <para>
4164         The <literal>show errors</literal> command does not exist in
4165         <productname>PostgreSQL</>, and is not needed since errors are
4166         reported automatically.
4167        </para>
4168       </listitem>
4169      </itemizedlist>
4170     </para>
4171
4172     <para>
4173      This is how this function would look when ported to
4174      <productname>PostgreSQL</>:
4175
4176 <programlisting>
4177 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4178                                                   v_version varchar)
4179 RETURNS varchar AS $$
4180 BEGIN
4181     IF v_version IS NULL THEN
4182         RETURN v_name;
4183     END IF;
4184     RETURN v_name || '/' || v_version;
4185 END;
4186 $$ LANGUAGE plpgsql;
4187 </programlisting>
4188     </para>
4189    </example>
4190
4191    <para>
4192     <xref linkend="plpgsql-porting-ex2"> shows how to port a
4193     function that creates another function and how to handle the
4194     ensuing quoting problems.
4195    </para>
4196
4197    <example id="plpgsql-porting-ex2">
4198     <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4199
4200     <para>
4201      The following procedure grabs rows from a
4202      <command>SELECT</command> statement and builds a large function
4203      with the results in <literal>IF</literal> statements, for the
4204      sake of efficiency.
4205     </para>
4206
4207     <para>
4208      This is the Oracle version:
4209 <programlisting>
4210 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4211     CURSOR referrer_keys IS
4212         SELECT * FROM cs_referrer_keys
4213         ORDER BY try_order;
4214     func_cmd VARCHAR(4000);
4215 BEGIN
4216     func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4217                  v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4218
4219     FOR referrer_key IN referrer_keys LOOP
4220         func_cmd := func_cmd ||
4221           ' IF v_' || referrer_key.kind
4222           || ' LIKE ''' || referrer_key.key_string
4223           || ''' THEN RETURN ''' || referrer_key.referrer_type
4224           || '''; END IF;';
4225     END LOOP;
4226
4227     func_cmd := func_cmd || ' RETURN NULL; END;';
4228
4229     EXECUTE IMMEDIATE func_cmd;
4230 END;
4231 /
4232 show errors;
4233 </programlisting>
4234     </para>
4235
4236     <para>
4237      Here is how this function would end up in <productname>PostgreSQL</>:
4238 <programlisting>
4239 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4240 DECLARE
4241     CURSOR referrer_keys IS
4242         SELECT * FROM cs_referrer_keys
4243         ORDER BY try_order;
4244     func_body text;
4245     func_cmd text;
4246 BEGIN
4247     func_body := 'BEGIN';
4248
4249     FOR referrer_key IN referrer_keys LOOP
4250         func_body := func_body ||
4251           ' IF v_' || referrer_key.kind
4252           || ' LIKE ' || quote_literal(referrer_key.key_string)
4253           || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4254           || '; END IF;' ;
4255     END LOOP;
4256
4257     func_body := func_body || ' RETURN NULL; END;';
4258
4259     func_cmd :=
4260       'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4261                                                         v_domain varchar,
4262                                                         v_url varchar)
4263         RETURNS varchar AS '
4264       || quote_literal(func_body)
4265       || ' LANGUAGE plpgsql;' ;
4266
4267     EXECUTE func_cmd;
4268 END;
4269 $func$ LANGUAGE plpgsql;
4270 </programlisting>
4271      Notice how the body of the function is built separately and passed
4272      through <literal>quote_literal</> to double any quote marks in it.  This
4273      technique is needed because we cannot safely use dollar quoting for
4274      defining the new function: we do not know for sure what strings will
4275      be interpolated from the <structfield>referrer_key.key_string</> field.
4276      (We are assuming here that <structfield>referrer_key.kind</> can be
4277      trusted to always be <literal>host</>, <literal>domain</>, or
4278      <literal>url</>, but <structfield>referrer_key.key_string</> might be
4279      anything, in particular it might contain dollar signs.) This function
4280      is actually an improvement on the Oracle original, because it will
4281      not generate broken code when <structfield>referrer_key.key_string</> or
4282      <structfield>referrer_key.referrer_type</> contain quote marks.
4283     </para>
4284    </example>
4285
4286    <para>
4287     <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4288     with <literal>OUT</> parameters and string manipulation.
4289     <productname>PostgreSQL</> does not have a built-in
4290     <function>instr</function> function, but you can create one
4291     using a combination of other
4292     functions.<indexterm><primary>instr</></indexterm> In <xref
4293     linkend="plpgsql-porting-appendix"> there is a
4294     <application>PL/pgSQL</application> implementation of
4295     <function>instr</function> that you can use to make your porting
4296     easier.
4297    </para>
4298
4299    <example id="plpgsql-porting-ex3">
4300     <title>Porting a Procedure With String Manipulation and
4301     <literal>OUT</> Parameters from <application>PL/SQL</> to
4302     <application>PL/pgSQL</></title>
4303
4304     <para>
4305      The following <productname>Oracle</productname> PL/SQL procedure is used
4306      to parse a URL and return several elements (host, path, and query).
4307     </para>
4308
4309     <para>
4310      This is the Oracle version:
4311 <programlisting>
4312 CREATE OR REPLACE PROCEDURE cs_parse_url(
4313     v_url IN VARCHAR,
4314     v_host OUT VARCHAR,  -- This will be passed back
4315     v_path OUT VARCHAR,  -- This one too
4316     v_query OUT VARCHAR) -- And this one
4317 IS
4318     a_pos1 INTEGER;
4319     a_pos2 INTEGER;
4320 BEGIN
4321     v_host := NULL;
4322     v_path := NULL;
4323     v_query := NULL;
4324     a_pos1 := instr(v_url, '//');
4325
4326     IF a_pos1 = 0 THEN
4327         RETURN;
4328     END IF;
4329     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4330     IF a_pos2 = 0 THEN
4331         v_host := substr(v_url, a_pos1 + 2);
4332         v_path := '/';
4333         RETURN;
4334     END IF;
4335
4336     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4337     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4338
4339     IF a_pos1 = 0 THEN
4340         v_path := substr(v_url, a_pos2);
4341         RETURN;
4342     END IF;
4343
4344     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4345     v_query := substr(v_url, a_pos1 + 1);
4346 END;
4347 /
4348 show errors;
4349 </programlisting>
4350     </para>
4351
4352     <para>
4353      Here is a possible translation into <application>PL/pgSQL</>:
4354 <programlisting>
4355 CREATE OR REPLACE FUNCTION cs_parse_url(
4356     v_url IN VARCHAR,
4357     v_host OUT VARCHAR,  -- This will be passed back
4358     v_path OUT VARCHAR,  -- This one too
4359     v_query OUT VARCHAR) -- And this one
4360 AS $$
4361 DECLARE
4362     a_pos1 INTEGER;
4363     a_pos2 INTEGER;
4364 BEGIN
4365     v_host := NULL;
4366     v_path := NULL;
4367     v_query := NULL;
4368     a_pos1 := instr(v_url, '//');
4369
4370     IF a_pos1 = 0 THEN
4371         RETURN;
4372     END IF;
4373     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4374     IF a_pos2 = 0 THEN
4375         v_host := substr(v_url, a_pos1 + 2);
4376         v_path := '/';
4377         RETURN;
4378     END IF;
4379
4380     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4381     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4382
4383     IF a_pos1 = 0 THEN
4384         v_path := substr(v_url, a_pos2);
4385         RETURN;
4386     END IF;
4387
4388     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4389     v_query := substr(v_url, a_pos1 + 1);
4390 END;
4391 $$ LANGUAGE plpgsql;
4392 </programlisting>
4393
4394      This function could be used like this:
4395 <programlisting>
4396 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4397 </programlisting>
4398     </para>
4399    </example>
4400
4401    <para>
4402     <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4403     that uses numerous features that are specific to Oracle.
4404    </para>
4405
4406    <example id="plpgsql-porting-ex4">
4407     <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4408
4409     <para>
4410      The Oracle version:
4411
4412 <programlisting>
4413 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4414     a_running_job_count INTEGER;
4415     PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4416 BEGIN
4417     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4418
4419     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4420
4421     IF a_running_job_count &gt; 0 THEN
4422         COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4423         raise_application_error(-20000, 'Unable to create a new job: a job is currently running.');
4424     END IF;
4425
4426     DELETE FROM cs_active_job;
4427     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4428
4429     BEGIN
4430         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4431     EXCEPTION
4432         WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4433     END;
4434     COMMIT;
4435 END;
4436 /
4437 show errors
4438 </programlisting>
4439    </para>
4440
4441    <para>
4442     Procedures like this can easily be converted into <productname>PostgreSQL</>
4443     functions returning <type>void</type>. This procedure in
4444     particular is interesting because it can teach us some things:
4445
4446     <calloutlist>
4447      <callout arearefs="co.plpgsql-porting-pragma">
4448       <para>
4449        There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
4450       </para>
4451      </callout>
4452
4453      <callout arearefs="co.plpgsql-porting-locktable">
4454       <para>
4455        If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
4456        the lock will not be released until the calling transaction is
4457        finished.
4458       </para>
4459      </callout>
4460
4461      <callout arearefs="co.plpgsql-porting-commit">
4462       <para>
4463        You cannot issue <command>COMMIT</> in a
4464        <application>PL/pgSQL</application> function.  The function is
4465        running within some outer transaction and so <command>COMMIT</>
4466        would imply terminating the function's execution.  However, in
4467        this particular case it is not necessary anyway, because the lock
4468        obtained by the <command>LOCK TABLE</command> will be released when
4469        we raise an error.
4470       </para>
4471      </callout>
4472     </calloutlist>
4473    </para>
4474
4475    <para>
4476     This is how we could port this procedure to <application>PL/pgSQL</>:
4477
4478 <programlisting>
4479 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
4480 DECLARE
4481     a_running_job_count integer;
4482 BEGIN
4483     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
4484
4485     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4486
4487     IF a_running_job_count &gt; 0 THEN
4488         RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
4489     END IF;
4490
4491     DELETE FROM cs_active_job;
4492     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4493
4494     BEGIN
4495         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
4496     EXCEPTION
4497         WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
4498             -- don't worry if it already exists
4499     END;
4500 END;
4501 $$ LANGUAGE plpgsql;
4502 </programlisting>
4503
4504     <calloutlist>
4505      <callout arearefs="co.plpgsql-porting-raise">
4506       <para>
4507        The syntax of <literal>RAISE</> is considerably different from
4508        Oracle's statement, although the basic case <literal>RAISE</>
4509        <replaceable class="parameter">exception_name</replaceable> works
4510        similarly.
4511       </para>
4512      </callout>
4513      <callout arearefs="co.plpgsql-porting-exception">
4514       <para>
4515        The exception names supported by <application>PL/pgSQL</> are
4516        different from Oracle's.  The set of built-in exception names
4517        is much larger (see <xref linkend="errcodes-appendix">).  There
4518        is not currently a way to declare user-defined exception names.
4519       </para>
4520      </callout>
4521     </calloutlist>
4522
4523     The main functional difference between this procedure and the
4524     Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
4525     table will be held until the calling transaction completes.  Also, if
4526     the caller later aborts (for example due to an error), the effects of
4527     this procedure will be rolled back.
4528    </para>
4529    </example>
4530   </sect2>
4531
4532   <sect2 id="plpgsql-porting-other">
4533    <title>Other Things to Watch For</title>
4534
4535    <para>
4536     This section explains a few other things to watch for when porting
4537     Oracle <application>PL/SQL</> functions to
4538     <productname>PostgreSQL</productname>.
4539    </para>
4540
4541    <sect3 id="plpgsql-porting-exceptions">
4542     <title>Implicit Rollback after Exceptions</title>
4543
4544     <para>
4545      In <application>PL/pgSQL</>, when an exception is caught by an
4546      <literal>EXCEPTION</> clause, all database changes since the block's
4547      <literal>BEGIN</> are automatically rolled back.  That is, the behavior
4548      is equivalent to what you'd get in Oracle with:
4549
4550 <programlisting>
4551     BEGIN
4552         SAVEPOINT s1;
4553         ... code here ...
4554     EXCEPTION
4555         WHEN ... THEN
4556             ROLLBACK TO s1;
4557             ... code here ...
4558         WHEN ... THEN
4559             ROLLBACK TO s1;
4560             ... code here ...
4561     END;
4562 </programlisting>
4563
4564      If you are translating an Oracle procedure that uses
4565      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
4566      your task is easy: just omit the <command>SAVEPOINT</> and
4567      <command>ROLLBACK TO</>.  If you have a procedure that uses
4568      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
4569      then some actual thought will be required.
4570     </para>
4571    </sect3>
4572
4573    <sect3>
4574     <title><command>EXECUTE</command></title>
4575
4576     <para>
4577      The <application>PL/pgSQL</> version of
4578      <command>EXECUTE</command> works similarly to the
4579      <application>PL/SQL</> version, but you have to remember to use
4580      <function>quote_literal</function> and
4581      <function>quote_ident</function> as described in <xref
4582      linkend="plpgsql-statements-executing-dyn">.  Constructs of the
4583      type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
4584      reliably unless you use these functions.
4585     </para>
4586    </sect3>
4587
4588    <sect3 id="plpgsql-porting-optimization">
4589     <title>Optimizing <application>PL/pgSQL</application> Functions</title>
4590
4591     <para>
4592      <productname>PostgreSQL</> gives you two function creation
4593      modifiers to optimize execution: <quote>volatility</> (whether
4594      the function always returns the same result when given the same
4595      arguments) and <quote>strictness</quote> (whether the function
4596      returns null if any argument is null).  Consult the <xref
4597      linkend="sql-createfunction" endterm="sql-createfunction-title">
4598      reference page for details.
4599     </para>
4600
4601     <para>
4602      When making use of these optimization attributes, your
4603      <command>CREATE FUNCTION</command> statement might look something
4604      like this:
4605
4606 <programlisting>
4607 CREATE FUNCTION foo(...) RETURNS integer AS $$
4608 ...
4609 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4610 </programlisting>
4611     </para>
4612    </sect3>
4613   </sect2>
4614
4615   <sect2 id="plpgsql-porting-appendix">
4616    <title>Appendix</title>
4617
4618    <para>
4619     This section contains the code for a set of Oracle-compatible
4620     <function>instr</function> functions that you can use to simplify
4621     your porting efforts.
4622    </para>
4623
4624 <programlisting>
4625 --
4626 -- instr functions that mimic Oracle's counterpart
4627 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
4628 --
4629 -- Searches string1 beginning at the nth character for the mth occurrence
4630 -- of string2.  If n is negative, search backwards.  If m is not passed,
4631 -- assume 1 (search starts at first character).
4632 --
4633
4634 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
4635 DECLARE
4636     pos integer;
4637 BEGIN
4638     pos:= instr($1, $2, 1);
4639     RETURN pos;
4640 END;
4641 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4642
4643
4644 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
4645 RETURNS integer AS $$
4646 DECLARE
4647     pos integer NOT NULL DEFAULT 0;
4648     temp_str varchar;
4649     beg integer;
4650     length integer;
4651     ss_length integer;
4652 BEGIN
4653     IF beg_index &gt; 0 THEN
4654         temp_str := substring(string FROM beg_index);
4655         pos := position(string_to_search IN temp_str);
4656
4657         IF pos = 0 THEN
4658             RETURN 0;
4659         ELSE
4660             RETURN pos + beg_index - 1;
4661         END IF;
4662     ELSE
4663         ss_length := char_length(string_to_search);
4664         length := char_length(string);
4665         beg := length + beg_index - ss_length + 2;
4666
4667         WHILE beg &gt; 0 LOOP
4668             temp_str := substring(string FROM beg FOR ss_length);
4669             pos := position(string_to_search IN temp_str);
4670
4671             IF pos &gt; 0 THEN
4672                 RETURN beg;
4673             END IF;
4674
4675             beg := beg - 1;
4676         END LOOP;
4677
4678         RETURN 0;
4679     END IF;
4680 END;
4681 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4682
4683
4684 CREATE FUNCTION instr(string varchar, string_to_search varchar,
4685                       beg_index integer, occur_index integer)
4686 RETURNS integer AS $$
4687 DECLARE
4688     pos integer NOT NULL DEFAULT 0;
4689     occur_number integer NOT NULL DEFAULT 0;
4690     temp_str varchar;
4691     beg integer;
4692     i integer;
4693     length integer;
4694     ss_length integer;
4695 BEGIN
4696     IF beg_index &gt; 0 THEN
4697         beg := beg_index;
4698         temp_str := substring(string FROM beg_index);
4699
4700         FOR i IN 1..occur_index LOOP
4701             pos := position(string_to_search IN temp_str);
4702
4703             IF i = 1 THEN
4704                 beg := beg + pos - 1;
4705             ELSE
4706                 beg := beg + pos;
4707             END IF;
4708
4709             temp_str := substring(string FROM beg + 1);
4710         END LOOP;
4711
4712         IF pos = 0 THEN
4713             RETURN 0;
4714         ELSE
4715             RETURN beg;
4716         END IF;
4717     ELSE
4718         ss_length := char_length(string_to_search);
4719         length := char_length(string);
4720         beg := length + beg_index - ss_length + 2;
4721
4722         WHILE beg &gt; 0 LOOP
4723             temp_str := substring(string FROM beg FOR ss_length);
4724             pos := position(string_to_search IN temp_str);
4725
4726             IF pos &gt; 0 THEN
4727                 occur_number := occur_number + 1;
4728
4729                 IF occur_number = occur_index THEN
4730                     RETURN beg;
4731                 END IF;
4732             END IF;
4733
4734             beg := beg - 1;
4735         END LOOP;
4736
4737         RETURN 0;
4738     END IF;
4739 END;
4740 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4741 </programlisting>
4742   </sect2>
4743
4744  </sect1>
4745
4746 </chapter>