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