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