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