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