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