]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpgsql.sgml
Remove cvs keywords from all files.
[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     <para>
1156      When working with dynamic commands you will often have to handle escaping
1157      of single quotes.  The recommended method for quoting fixed text in your
1158      function body is dollar quoting.  (If you have legacy code that does
1159      not use dollar quoting, please refer to the
1160      overview in <xref linkend="plpgsql-quote-tips">, which can save you
1161      some effort when translating said code to a more reasonable scheme.)
1162     </para>
1163
1164     <para>
1165      Dynamic values that are to be inserted into the constructed
1166      query require careful handling since they might themselves contain
1167      quote characters.
1168      An example (this assumes that you are using dollar quoting for the
1169      function as a whole, so the quote marks need not be doubled):
1170 <programlisting>
1171 EXECUTE 'UPDATE tbl SET '
1172         || quote_ident(colname)
1173         || ' = '
1174         || quote_literal(newvalue)
1175         || ' WHERE key = '
1176         || quote_literal(keyvalue);
1177 </programlisting>
1178     </para>
1179
1180     <para>
1181      This example demonstrates the use of the
1182      <function>quote_ident</function> and
1183      <function>quote_literal</function> functions (see <xref
1184      linkend="functions-string">).  For safety, expressions containing column
1185      or table identifiers should be passed through
1186      <function>quote_ident</function> before insertion in a dynamic query.
1187      Expressions containing values that should be literal strings in the
1188      constructed command should be passed through <function>quote_literal</>.
1189      These functions take the appropriate steps to return the input text
1190      enclosed in double or single quotes respectively, with any embedded
1191      special characters properly escaped.
1192     </para>
1193
1194     <para>
1195      Because <function>quote_literal</function> is labelled
1196      <literal>STRICT</literal>, it will always return null when called with a
1197      null argument.  In the above example, if <literal>newvalue</> or
1198      <literal>keyvalue</> were null, the entire dynamic query string would
1199      become null, leading to an error from <command>EXECUTE</command>.
1200      You can avoid this problem by using the <function>quote_nullable</>
1201      function, which works the same as <function>quote_literal</> except that
1202      when called with a null argument it returns the string <literal>NULL</>.
1203      For example,
1204 <programlisting>
1205 EXECUTE 'UPDATE tbl SET '
1206         || quote_ident(colname)
1207         || ' = '
1208         || quote_nullable(newvalue)
1209         || ' WHERE key = '
1210         || quote_nullable(keyvalue);
1211 </programlisting>
1212      If you are dealing with values that might be null, you should usually
1213      use <function>quote_nullable</> in place of <function>quote_literal</>.
1214     </para>
1215
1216     <para>
1217      As always, care must be taken to ensure that null values in a query do
1218      not deliver unintended results.  For example the <literal>WHERE</> clause
1219 <programlisting>
1220 'WHERE key = ' || quote_nullable(keyvalue)
1221 </programlisting>
1222      will never succeed if <literal>keyvalue</> is null, because the
1223      result of using the equality operator <literal>=</> with a null operand
1224      is always null.  If you wish null to work like an ordinary key value,
1225      you would need to rewrite the above as
1226 <programlisting>
1227 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1228 </programlisting>
1229      (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1230      efficiently than <literal>=</>, so don't do this unless you must.
1231      See <xref linkend="functions-comparison"> for
1232      more information on nulls and <literal>IS DISTINCT</>.)
1233     </para>
1234
1235     <para>
1236      Note that dollar quoting is only useful for quoting fixed text.
1237      It would be a very bad idea to try to write this example as:
1238 <programlisting>
1239 EXECUTE 'UPDATE tbl SET '
1240         || quote_ident(colname)
1241         || ' = $$'
1242         || newvalue
1243         || '$$ WHERE key = '
1244         || quote_literal(keyvalue);
1245 </programlisting>
1246      because it would break if the contents of <literal>newvalue</>
1247      happened to contain <literal>$$</>.  The same objection would
1248      apply to any other dollar-quoting delimiter you might pick.
1249      So, to safely quote text that is not known in advance, you
1250      <emphasis>must</> use <function>quote_literal</>,
1251      <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1252     </para>
1253    </example>
1254
1255     <para>
1256      A much larger example of a dynamic command and
1257      <command>EXECUTE</command> can be seen in <xref
1258      linkend="plpgsql-porting-ex2">, which builds and executes a
1259      <command>CREATE FUNCTION</> command to define a new function.
1260     </para>
1261    </sect2>
1262
1263    <sect2 id="plpgsql-statements-diagnostics">
1264     <title>Obtaining the Result Status</title>
1265
1266     <para>
1267      There are several ways to determine the effect of a command. The
1268      first method is to use the <command>GET DIAGNOSTICS</command>
1269      command, which has the form:
1270
1271 <synopsis>
1272 GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
1273 </synopsis>
1274
1275      This command allows retrieval of system status indicators.  Each
1276      <replaceable>item</replaceable> is a key word identifying a state
1277      value to be assigned to the specified variable (which should be
1278      of the right data type to receive it).  The currently available
1279      status items are <varname>ROW_COUNT</>, the number of rows
1280      processed by the last <acronym>SQL</acronym> command sent to
1281      the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1282      the OID of the last row inserted by the most recent
1283      <acronym>SQL</acronym> command.  Note that <varname>RESULT_OID</>
1284      is only useful after an <command>INSERT</command> command into a
1285      table containing OIDs.
1286     </para>
1287
1288     <para>
1289      An example:
1290 <programlisting>
1291 GET DIAGNOSTICS integer_var = ROW_COUNT;
1292 </programlisting>
1293     </para>
1294
1295     <para>
1296      The second method to determine the effects of a command is to check the
1297      special variable named <literal>FOUND</literal>, which is of
1298      type <type>boolean</type>.  <literal>FOUND</literal> starts out
1299      false within each <application>PL/pgSQL</application> function call.
1300      It is set by each of the following types of statements:
1301
1302          <itemizedlist>
1303           <listitem>
1304            <para>
1305             A <command>SELECT INTO</command> statement sets
1306             <literal>FOUND</literal> true if a row is assigned, false if no
1307             row is returned.
1308            </para>
1309           </listitem>
1310           <listitem>
1311            <para>
1312             A <command>PERFORM</> statement sets <literal>FOUND</literal>
1313             true if it produces (and discards) one or more rows, false if
1314             no row is produced.
1315            </para>
1316           </listitem>
1317           <listitem>
1318            <para>
1319             <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1320             statements set <literal>FOUND</literal> true if at least one
1321             row is affected, false if no row is affected.
1322            </para>
1323           </listitem>
1324           <listitem>
1325            <para>
1326             A <command>FETCH</> statement sets <literal>FOUND</literal>
1327             true if it returns a row, false if no row is returned.
1328            </para>
1329           </listitem>
1330           <listitem>
1331            <para>
1332             A <command>MOVE</> statement sets <literal>FOUND</literal>
1333             true if it successfully repositions the cursor, false otherwise.
1334            </para>
1335           </listitem>
1336
1337           <listitem>
1338            <para>
1339             A <command>FOR</> statement sets <literal>FOUND</literal> true
1340             if it iterates one or more times, else false.  This applies to
1341             all four variants of the <command>FOR</> statement (integer
1342             <command>FOR</> loops, record-set <command>FOR</> loops,
1343             dynamic record-set <command>FOR</> loops, and cursor
1344             <command>FOR</> loops).
1345             <literal>FOUND</literal> is set this way when the
1346             <command>FOR</> loop exits; inside the execution of the loop,
1347             <literal>FOUND</literal> is not modified by the
1348             <command>FOR</> statement, although it might be changed by the
1349             execution of other statements within the loop body.
1350            </para>
1351           </listitem>
1352           <listitem>
1353            <para>
1354             <command>RETURN QUERY</command> and <command>RETURN QUERY
1355             EXECUTE</command> statements set <literal>FOUND</literal>
1356             true if the query returns at least one row, false if no row
1357             is returned.
1358            </para>
1359           </listitem>
1360          </itemizedlist>
1361
1362      Other <application>PL/pgSQL</application> statements do not change
1363      the state of <literal>FOUND</literal>.
1364      Note in particular that <command>EXECUTE</command>
1365      changes the output of <command>GET DIAGNOSTICS</command>, but
1366      does not change <literal>FOUND</literal>.
1367     </para>
1368
1369     <para>
1370      <literal>FOUND</literal> is a local variable within each
1371      <application>PL/pgSQL</application> function; any changes to it
1372      affect only the current function.
1373     </para>
1374
1375    </sect2>
1376
1377    <sect2 id="plpgsql-statements-null">
1378     <title>Doing Nothing At All</title>
1379
1380     <para>
1381      Sometimes a placeholder statement that does nothing is useful.
1382      For example, it can indicate that one arm of an if/then/else
1383      chain is deliberately empty.  For this purpose, use the
1384      <command>NULL</command> statement:
1385
1386 <synopsis>
1387 NULL;
1388 </synopsis>
1389     </para>
1390
1391     <para>
1392      For example, the following two fragments of code are equivalent:
1393 <programlisting>
1394 BEGIN
1395     y := x / 0;
1396 EXCEPTION
1397     WHEN division_by_zero THEN
1398         NULL;  -- ignore the error
1399 END;
1400 </programlisting>
1401
1402 <programlisting>
1403 BEGIN
1404     y := x / 0;
1405 EXCEPTION
1406     WHEN division_by_zero THEN  -- ignore the error
1407 END;
1408 </programlisting>
1409      Which is preferable is a matter of taste.
1410     </para>
1411
1412     <note>
1413      <para>
1414       In Oracle's PL/SQL, empty statement lists are not allowed, and so
1415       <command>NULL</> statements are <emphasis>required</> for situations
1416       such as this.  <application>PL/pgSQL</application> allows you to
1417       just write nothing, instead.
1418      </para>
1419     </note>
1420
1421    </sect2>
1422   </sect1>
1423
1424   <sect1 id="plpgsql-control-structures">
1425    <title>Control Structures</title>
1426
1427    <para>
1428     Control structures are probably the most useful (and
1429     important) part of <application>PL/pgSQL</>. With
1430     <application>PL/pgSQL</>'s control structures,
1431     you can manipulate <productname>PostgreSQL</> data in a very
1432     flexible and powerful way.
1433    </para>
1434
1435    <sect2 id="plpgsql-statements-returning">
1436     <title>Returning From a Function</title>
1437
1438     <para>
1439      There are two commands available that allow you to return data
1440      from a function: <command>RETURN</command> and <command>RETURN
1441      NEXT</command>.
1442     </para>
1443
1444     <sect3>
1445      <title><command>RETURN</></title>
1446
1447 <synopsis>
1448 RETURN <replaceable>expression</replaceable>;
1449 </synopsis>
1450
1451      <para>
1452       <command>RETURN</command> with an expression terminates the
1453       function and returns the value of
1454       <replaceable>expression</replaceable> to the caller.  This form
1455       is used for <application>PL/pgSQL</> functions that do
1456       not return a set.
1457      </para>
1458
1459      <para>
1460       When returning a scalar type, any expression can be used. The
1461       expression's result will be automatically cast into the
1462       function's return type as described for assignments. To return a
1463       composite (row) value, you must write a record or row variable
1464       as the <replaceable>expression</replaceable>.
1465      </para>
1466
1467      <para>
1468       If you declared the function with output parameters, write just
1469       <command>RETURN</command> with no expression.  The current values
1470       of the output parameter variables will be returned.
1471      </para>
1472
1473      <para>
1474       If you declared the function to return <type>void</type>, a
1475       <command>RETURN</command> statement can be used to exit the function
1476       early; but do not write an expression following
1477       <command>RETURN</command>.
1478      </para>
1479
1480      <para>
1481       The return value of a function cannot be left undefined. If
1482       control reaches the end of the top-level block of the function
1483       without hitting a <command>RETURN</command> statement, a run-time
1484       error will occur.  This restriction does not apply to functions
1485       with output parameters and functions returning <type>void</type>,
1486       however.  In those cases a <command>RETURN</command> statement is
1487       automatically executed if the top-level block finishes.
1488      </para>
1489     </sect3>
1490
1491     <sect3>
1492      <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1493     <indexterm>
1494      <primary>RETURN NEXT</primary>
1495      <secondary>in PL/PgSQL</secondary>
1496     </indexterm>
1497     <indexterm>
1498      <primary>RETURN QUERY</primary>
1499      <secondary>in PL/PgSQL</secondary>
1500     </indexterm>
1501
1502 <synopsis>
1503 RETURN NEXT <replaceable>expression</replaceable>;
1504 RETURN QUERY <replaceable>query</replaceable>;
1505 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1506 </synopsis>
1507
1508      <para>
1509       When a <application>PL/pgSQL</> function is declared to return
1510       <literal>SETOF <replaceable>sometype</></literal>, the procedure
1511       to follow is slightly different.  In that case, the individual
1512       items to return are specified by a sequence of <command>RETURN
1513       NEXT</command> or <command>RETURN QUERY</command> commands, and
1514       then a final <command>RETURN</command> command with no argument
1515       is used to indicate that the function has finished executing.
1516       <command>RETURN NEXT</command> can be used with both scalar and
1517       composite data types; with a composite result type, an entire
1518       <quote>table</quote> of results will be returned.
1519       <command>RETURN QUERY</command> appends the results of executing
1520       a query to the function's result set. <command>RETURN
1521       NEXT</command> and <command>RETURN QUERY</command> can be freely
1522       intermixed in a single set-returning function, in which case
1523       their results will be concatenated.
1524      </para>
1525
1526      <para>
1527       <command>RETURN NEXT</command> and <command>RETURN
1528       QUERY</command> do not actually return from the function &mdash;
1529       they simply append zero or more rows to the function's result
1530       set.  Execution then continues with the next statement in the
1531       <application>PL/pgSQL</> function.  As successive
1532       <command>RETURN NEXT</command> or <command>RETURN
1533       QUERY</command> commands are executed, the result set is built
1534       up.  A final <command>RETURN</command>, which should have no
1535       argument, causes control to exit the function (or you can just
1536       let control reach the end of the function).
1537      </para>
1538
1539      <para>
1540       <command>RETURN QUERY</command> has a variant
1541       <command>RETURN QUERY EXECUTE</command>, which specifies the
1542       query to be executed dynamically.  Parameter expressions can
1543       be inserted into the computed query string via <literal>USING</>,
1544       in just the same way as in the <command>EXECUTE</> command.
1545      </para>
1546
1547      <para>
1548       If you declared the function with output parameters, write just
1549       <command>RETURN NEXT</command> with no expression.  On each
1550       execution, the current values of the output parameter
1551       variable(s) will be saved for eventual return as a row of the
1552       result.  Note that you must declare the function as returning
1553       <literal>SETOF record</literal> when there are multiple output
1554       parameters, or <literal>SETOF <replaceable>sometype</></literal>
1555       when there is just one output parameter of type
1556       <replaceable>sometype</>, in order to create a set-returning
1557       function with output parameters.
1558      </para>
1559
1560      <para>
1561       Here is an example of a function using <command>RETURN
1562       NEXT</command>:
1563
1564 <programlisting>
1565 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1566 INSERT INTO foo VALUES (1, 2, 'three');
1567 INSERT INTO foo VALUES (4, 5, 'six');
1568
1569 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1570 $BODY$
1571 DECLARE
1572     r foo%rowtype;
1573 BEGIN
1574     FOR r IN SELECT * FROM foo
1575     WHERE fooid &gt; 0
1576     LOOP
1577         -- can do some processing here
1578         RETURN NEXT r; -- return current row of SELECT
1579     END LOOP;
1580     RETURN;
1581 END
1582 $BODY$
1583 LANGUAGE 'plpgsql' ;
1584
1585 SELECT * FROM getallfoo();
1586 </programlisting>
1587      </para>
1588
1589      <note>
1590       <para>
1591        The current implementation of <command>RETURN NEXT</command>
1592        and <command>RETURN QUERY</command> stores the entire result set
1593        before returning from the function, as discussed above.  That
1594        means that if a <application>PL/pgSQL</> function produces a
1595        very large result set, performance might be poor: data will be
1596        written to disk to avoid memory exhaustion, but the function
1597        itself will not return until the entire result set has been
1598        generated.  A future version of <application>PL/pgSQL</> might
1599        allow users to define set-returning functions
1600        that do not have this limitation.  Currently, the point at
1601        which data begins being written to disk is controlled by the
1602        <xref linkend="guc-work-mem">
1603        configuration variable.  Administrators who have sufficient
1604        memory to store larger result sets in memory should consider
1605        increasing this parameter.
1606       </para>
1607      </note>
1608     </sect3>
1609    </sect2>
1610
1611    <sect2 id="plpgsql-conditionals">
1612     <title>Conditionals</title>
1613
1614     <para>
1615      <command>IF</> and <command>CASE</> statements let you execute
1616      alternative commands based on certain conditions.
1617      <application>PL/pgSQL</> has three forms of <command>IF</>:
1618     <itemizedlist>
1619      <listitem>
1620       <para><literal>IF ... THEN</></>
1621      </listitem>
1622      <listitem>
1623       <para><literal>IF ... THEN ... ELSE</></>
1624      </listitem>
1625      <listitem>
1626       <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1627      </listitem>
1628     </itemizedlist>
1629
1630     and two forms of <command>CASE</>:
1631     <itemizedlist>
1632      <listitem>
1633       <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1634      </listitem>
1635      <listitem>
1636       <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1637      </listitem>
1638     </itemizedlist>
1639     </para>
1640
1641     <sect3>
1642      <title><literal>IF-THEN</></title>
1643
1644 <synopsis>
1645 IF <replaceable>boolean-expression</replaceable> THEN
1646     <replaceable>statements</replaceable>
1647 END IF;
1648 </synopsis>
1649
1650        <para>
1651         <literal>IF-THEN</literal> statements are the simplest form of
1652         <literal>IF</literal>. The statements between
1653         <literal>THEN</literal> and <literal>END IF</literal> will be
1654         executed if the condition is true. Otherwise, they are
1655         skipped.
1656        </para>
1657
1658        <para>
1659         Example:
1660 <programlisting>
1661 IF v_user_id &lt;&gt; 0 THEN
1662     UPDATE users SET email = v_email WHERE user_id = v_user_id;
1663 END IF;
1664 </programlisting>
1665        </para>
1666      </sect3>
1667
1668      <sect3>
1669       <title><literal>IF-THEN-ELSE</></title>
1670
1671 <synopsis>
1672 IF <replaceable>boolean-expression</replaceable> THEN
1673     <replaceable>statements</replaceable>
1674 ELSE
1675     <replaceable>statements</replaceable>
1676 END IF;
1677 </synopsis>
1678
1679        <para>
1680         <literal>IF-THEN-ELSE</literal> statements add to
1681         <literal>IF-THEN</literal> by letting you specify an
1682         alternative set of statements that should be executed if the
1683         condition is not true.  (Note this includes the case where the
1684         condition evaluates to NULL.)
1685        </para>
1686
1687        <para>
1688         Examples:
1689 <programlisting>
1690 IF parentid IS NULL OR parentid = ''
1691 THEN
1692     RETURN fullname;
1693 ELSE
1694     RETURN hp_true_filename(parentid) || '/' || fullname;
1695 END IF;
1696 </programlisting>
1697
1698 <programlisting>
1699 IF v_count &gt; 0 THEN
1700     INSERT INTO users_count (count) VALUES (v_count);
1701     RETURN 't';
1702 ELSE
1703     RETURN 'f';
1704 END IF;
1705 </programlisting>
1706      </para>
1707     </sect3>
1708
1709      <sect3>
1710       <title><literal>IF-THEN-ELSIF</></title>
1711
1712 <synopsis>
1713 IF <replaceable>boolean-expression</replaceable> THEN
1714     <replaceable>statements</replaceable>
1715 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1716     <replaceable>statements</replaceable>
1717 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1718     <replaceable>statements</replaceable>
1719     ...
1720 </optional>
1721 </optional>
1722 <optional> ELSE
1723     <replaceable>statements</replaceable> </optional>
1724 END IF;
1725 </synopsis>
1726
1727        <para>
1728         Sometimes there are more than just two alternatives.
1729         <literal>IF-THEN-ELSIF</> provides a convenient
1730         method of checking several alternatives in turn.
1731         The <literal>IF</> conditions are tested successively
1732         until the first one that is true is found.  Then the
1733         associated statement(s) are executed, after which control
1734         passes to the next statement after <literal>END IF</>.
1735         (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1736         tested.)  If none of the <literal>IF</> conditions is true,
1737         then the <literal>ELSE</> block (if any) is executed.
1738        </para>
1739
1740        <para>
1741         Here is an example:
1742
1743 <programlisting>
1744 IF number = 0 THEN
1745     result := 'zero';
1746 ELSIF number &gt; 0 THEN
1747     result := 'positive';
1748 ELSIF number &lt; 0 THEN
1749     result := 'negative';
1750 ELSE
1751     -- hmm, the only other possibility is that number is null
1752     result := 'NULL';
1753 END IF;
1754 </programlisting>
1755        </para>
1756
1757        <para>
1758         The key word <literal>ELSIF</> can also be spelled
1759         <literal>ELSEIF</>.
1760        </para>
1761
1762        <para>
1763         An alternative way of accomplishing the same task is to nest
1764         <literal>IF-THEN-ELSE</literal> statements, as in the
1765         following example:
1766
1767 <programlisting>
1768 IF demo_row.sex = 'm' THEN
1769     pretty_sex := 'man';
1770 ELSE
1771     IF demo_row.sex = 'f' THEN
1772         pretty_sex := 'woman';
1773     END IF;
1774 END IF;
1775 </programlisting>
1776        </para>
1777
1778        <para>
1779         However, this method requires writing a matching <literal>END IF</>
1780         for each <literal>IF</>, so it is much more cumbersome than
1781         using <literal>ELSIF</> when there are many alternatives.
1782        </para>
1783      </sect3>
1784
1785      <sect3>
1786       <title>Simple <literal>CASE</></title>
1787
1788 <synopsis>
1789 CASE <replaceable>search-expression</replaceable>
1790     WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1791       <replaceable>statements</replaceable>
1792   <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1793       <replaceable>statements</replaceable>
1794     ... </optional>
1795   <optional> ELSE
1796       <replaceable>statements</replaceable> </optional>
1797 END CASE;
1798 </synopsis>
1799
1800       <para>
1801        The simple form of <command>CASE</> provides conditional execution
1802        based on equality of operands.  The <replaceable>search-expression</>
1803        is evaluated (once) and successively compared to each
1804        <replaceable>expression</> in the <literal>WHEN</> clauses.
1805        If a match is found, then the corresponding
1806        <replaceable>statements</replaceable> are executed, and then control
1807        passes to the next statement after <literal>END CASE</>.  (Subsequent
1808        <literal>WHEN</> expressions are not evaluated.)  If no match is
1809        found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1810        executed; but if <literal>ELSE</> is not present, then a
1811        <literal>CASE_NOT_FOUND</literal> exception is raised.
1812       </para>
1813
1814       <para>
1815        Here is a simple example:
1816
1817 <programlisting>
1818 CASE x
1819     WHEN 1, 2 THEN
1820         msg := 'one or two';
1821     ELSE
1822         msg := 'other value than one or two';
1823 END CASE;
1824 </programlisting>
1825       </para>
1826      </sect3>
1827
1828      <sect3>
1829       <title>Searched <literal>CASE</></title>
1830
1831 <synopsis>
1832 CASE
1833     WHEN <replaceable>boolean-expression</replaceable> THEN
1834       <replaceable>statements</replaceable>
1835   <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1836       <replaceable>statements</replaceable>
1837     ... </optional>
1838   <optional> ELSE
1839       <replaceable>statements</replaceable> </optional>
1840 END CASE;
1841 </synopsis>
1842
1843       <para>
1844        The searched form of <command>CASE</> provides conditional execution
1845        based on truth of Boolean expressions.  Each <literal>WHEN</> clause's
1846        <replaceable>boolean-expression</replaceable> is evaluated in turn,
1847        until one is found that yields <literal>true</>.  Then the
1848        corresponding <replaceable>statements</replaceable> are executed, and
1849        then control passes to the next statement after <literal>END CASE</>.
1850        (Subsequent <literal>WHEN</> expressions are not evaluated.)
1851        If no true result is found, the <literal>ELSE</>
1852        <replaceable>statements</replaceable> are executed;
1853        but if <literal>ELSE</> is not present, then a
1854        <literal>CASE_NOT_FOUND</literal> exception is raised.
1855       </para>
1856
1857       <para>
1858        Here is an example:
1859
1860 <programlisting>
1861 CASE
1862     WHEN x BETWEEN 0 AND 10 THEN
1863         msg := 'value is between zero and ten';
1864     WHEN x BETWEEN 11 AND 20 THEN
1865         msg := 'value is between eleven and twenty';
1866 END CASE;
1867 </programlisting>
1868       </para>
1869
1870       <para>
1871        This form of <command>CASE</> is entirely equivalent to
1872        <literal>IF-THEN-ELSIF</>, except for the rule that reaching
1873        an omitted <literal>ELSE</> clause results in an error rather
1874        than doing nothing.
1875       </para>
1876
1877      </sect3>
1878    </sect2>
1879
1880    <sect2 id="plpgsql-control-structures-loops">
1881     <title>Simple Loops</title>
1882
1883     <indexterm zone="plpgsql-control-structures-loops">
1884      <primary>loop</primary>
1885      <secondary>in PL/pgSQL</secondary>
1886     </indexterm>
1887
1888     <para>
1889      With the <literal>LOOP</>, <literal>EXIT</>,
1890      <literal>CONTINUE</>, <literal>WHILE</>, and <literal>FOR</>
1891      statements, you can arrange for your <application>PL/pgSQL</>
1892      function to repeat a series of commands.
1893     </para>
1894
1895     <sect3>
1896      <title><literal>LOOP</></title>
1897
1898 <synopsis>
1899 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
1900 LOOP
1901     <replaceable>statements</replaceable>
1902 END LOOP <optional> <replaceable>label</replaceable> </optional>;
1903 </synopsis>
1904
1905      <para>
1906       <literal>LOOP</> defines an unconditional loop that is repeated
1907       indefinitely until terminated by an <literal>EXIT</> or
1908       <command>RETURN</command> statement.  The optional
1909       <replaceable>label</replaceable> can be used by <literal>EXIT</>
1910       and <literal>CONTINUE</literal> statements within nested loops to
1911       specify which loop those statements refer to.
1912      </para>
1913     </sect3>
1914
1915      <sect3>
1916       <title><literal>EXIT</></title>
1917
1918      <indexterm>
1919       <primary>EXIT</primary>
1920       <secondary>in PL/pgSQL</secondary>
1921      </indexterm>
1922
1923 <synopsis>
1924 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1925 </synopsis>
1926
1927        <para>
1928         If no <replaceable>label</replaceable> is given, the innermost
1929         loop is terminated and the statement following <literal>END
1930         LOOP</> is executed next.  If <replaceable>label</replaceable>
1931         is given, it must be the label of the current or some outer
1932         level of nested loop or block. Then the named loop or block is
1933         terminated and control continues with the statement after the
1934         loop's/block's corresponding <literal>END</>.
1935        </para>
1936
1937        <para>
1938         If <literal>WHEN</> is specified, the loop exit occurs only if
1939         <replaceable>boolean-expression</> is true. Otherwise, control passes
1940         to the statement after <literal>EXIT</>.
1941        </para>
1942
1943        <para>
1944         <literal>EXIT</> can be used with all types of loops; it is
1945         not limited to use with unconditional loops.
1946        </para>
1947
1948        <para>
1949         When used with a
1950         <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
1951         control to the next statement after the end of the block.
1952         Note that a label must be used for this purpose; an unlabelled
1953         <literal>EXIT</literal> is never considered to match a
1954         <literal>BEGIN</literal> block.  (This is a change from
1955         pre-8.4 releases of <productname>PostgreSQL</productname>, which
1956         would allow an unlabelled <literal>EXIT</literal> to match
1957         a <literal>BEGIN</literal> block.)
1958        </para>
1959
1960        <para>
1961         Examples:
1962 <programlisting>
1963 LOOP
1964     -- some computations
1965     IF count &gt; 0 THEN
1966         EXIT;  -- exit loop
1967     END IF;
1968 END LOOP;
1969
1970 LOOP
1971     -- some computations
1972     EXIT WHEN count &gt; 0;  -- same result as previous example
1973 END LOOP;
1974
1975 &lt;&lt;ablock&gt;&gt;
1976 BEGIN
1977     -- some computations
1978     IF stocks &gt; 100000 THEN
1979         EXIT ablock;  -- causes exit from the BEGIN block
1980     END IF;
1981     -- computations here will be skipped when stocks &gt; 100000
1982 END;
1983 </programlisting>
1984        </para>
1985      </sect3>
1986
1987      <sect3>
1988       <title><literal>CONTINUE</></title>
1989
1990      <indexterm>
1991       <primary>CONTINUE</primary>
1992       <secondary>in PL/pgSQL</secondary>
1993      </indexterm>
1994
1995 <synopsis>
1996 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1997 </synopsis>
1998
1999        <para>
2000         If no <replaceable>label</> is given, the next iteration of
2001         the innermost loop is begun. That is, all statements remaining
2002         in the loop body are skipped, and control returns
2003         to the loop control expression (if any) to determine whether
2004         another loop iteration is needed.
2005         If <replaceable>label</> is present, it
2006         specifies the label of the loop whose execution will be
2007         continued.
2008        </para>
2009
2010        <para>
2011         If <literal>WHEN</> is specified, the next iteration of the
2012         loop is begun only if <replaceable>boolean-expression</> is
2013         true. Otherwise, control passes to the statement after
2014         <literal>CONTINUE</>.
2015        </para>
2016
2017        <para>
2018         <literal>CONTINUE</> can be used with all types of loops; it
2019         is not limited to use with unconditional loops.
2020        </para>
2021
2022        <para>
2023         Examples:
2024 <programlisting>
2025 LOOP
2026     -- some computations
2027     EXIT WHEN count &gt; 100;
2028     CONTINUE WHEN count &lt; 50;
2029     -- some computations for count IN [50 .. 100]
2030 END LOOP;
2031 </programlisting>
2032        </para>
2033      </sect3>
2034
2035
2036      <sect3>
2037       <title><literal>WHILE</></title>
2038
2039      <indexterm>
2040       <primary>WHILE</primary>
2041       <secondary>in PL/pgSQL</secondary>
2042      </indexterm>
2043
2044 <synopsis>
2045 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2046 WHILE <replaceable>boolean-expression</replaceable> LOOP
2047     <replaceable>statements</replaceable>
2048 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2049 </synopsis>
2050
2051        <para>
2052         The <literal>WHILE</> statement repeats a
2053         sequence of statements so long as the
2054         <replaceable>boolean-expression</replaceable>
2055         evaluates to true.  The expression is checked just before
2056         each entry to the loop body.
2057        </para>
2058
2059        <para>
2060         For example:
2061 <programlisting>
2062 WHILE amount_owed &gt; 0 AND gift_certificate_balance &gt; 0 LOOP
2063     -- some computations here
2064 END LOOP;
2065
2066 WHILE NOT done LOOP
2067     -- some computations here
2068 END LOOP;
2069 </programlisting>
2070        </para>
2071      </sect3>
2072
2073      <sect3 id="plpgsql-integer-for">
2074       <title><literal>FOR</> (integer variant)</title>
2075
2076 <synopsis>
2077 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2078 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2079     <replaceable>statements</replaceable>
2080 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2081 </synopsis>
2082
2083        <para>
2084         This form of <literal>FOR</> creates a loop that iterates over a range
2085         of integer values. The variable
2086         <replaceable>name</replaceable> is automatically defined as type
2087         <type>integer</> and exists only inside the loop (any existing
2088         definition of the variable name is ignored within the loop).
2089         The two expressions giving
2090         the lower and upper bound of the range are evaluated once when entering
2091         the loop. If the <literal>BY</> clause isn't specified the iteration
2092         step is 1, otherwise it's the value specified in the <literal>BY</>
2093         clause, which again is evaluated once on loop entry.
2094         If <literal>REVERSE</> is specified then the step value is
2095         subtracted, rather than added, after each iteration.
2096        </para>
2097
2098        <para>
2099         Some examples of integer <literal>FOR</> loops:
2100 <programlisting>
2101 FOR i IN 1..10 LOOP
2102     -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2103 END LOOP;
2104
2105 FOR i IN REVERSE 10..1 LOOP
2106     -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2107 END LOOP;
2108
2109 FOR i IN REVERSE 10..1 BY 2 LOOP
2110     -- i will take on the values 10,8,6,4,2 within the loop
2111 END LOOP;
2112 </programlisting>
2113        </para>
2114
2115        <para>
2116         If the lower bound is greater than the upper bound (or less than,
2117         in the <literal>REVERSE</> case), the loop body is not
2118         executed at all.  No error is raised.
2119        </para>
2120
2121        <para>
2122         If a <replaceable>label</replaceable> is attached to the
2123         <literal>FOR</> loop then the integer loop variable can be
2124         referenced with a qualified name, using that
2125         <replaceable>label</replaceable>.
2126        </para>
2127      </sect3>
2128    </sect2>
2129
2130    <sect2 id="plpgsql-records-iterating">
2131     <title>Looping Through Query Results</title>
2132
2133     <para>
2134      Using a different type of <literal>FOR</> loop, you can iterate through
2135      the results of a query and manipulate that data
2136      accordingly. The syntax is:
2137 <synopsis>
2138 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2139 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2140     <replaceable>statements</replaceable>
2141 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2142 </synopsis>
2143      The <replaceable>target</replaceable> is a record variable, row variable,
2144      or comma-separated list of scalar variables.
2145      The <replaceable>target</replaceable> is successively assigned each row
2146      resulting from the <replaceable>query</replaceable> and the loop body is
2147      executed for each row. Here is an example:
2148 <programlisting>
2149 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2150 DECLARE
2151     mviews RECORD;
2152 BEGIN
2153     PERFORM cs_log('Refreshing materialized views...');
2154
2155     FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2156
2157         -- Now "mviews" has one record from cs_materialized_views
2158
2159         PERFORM cs_log('Refreshing materialized view '
2160                    || quote_ident(mviews.mv_name) || ' ...');
2161         EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2162         EXECUTE 'INSERT INTO '
2163                    || quote_ident(mviews.mv_name) || ' '
2164                    || mviews.mv_query;
2165     END LOOP;
2166
2167     PERFORM cs_log('Done refreshing materialized views.');
2168     RETURN 1;
2169 END;
2170 $$ LANGUAGE plpgsql;
2171 </programlisting>
2172
2173      If the loop is terminated by an <literal>EXIT</> statement, the last
2174      assigned row value is still accessible after the loop.
2175     </para>
2176
2177     <para>
2178      The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2179      statement can be any SQL command that returns rows to the caller:
2180      <command>SELECT</> is the most common case,
2181      but you can also use <command>INSERT</>, <command>UPDATE</>, or
2182      <command>DELETE</> with a <literal>RETURNING</> clause.  Some utility
2183      commands such as <command>EXPLAIN</> will work too.
2184     </para>
2185
2186     <para>
2187      <application>PL/pgSQL</> variables are substituted into the query text,
2188      and the query plan is cached for possible re-use, as discussed in
2189      detail in <xref linkend="plpgsql-var-subst"> and
2190      <xref linkend="plpgsql-plan-caching">.
2191     </para>
2192
2193     <para>
2194      The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2195      rows:
2196 <synopsis>
2197 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2198 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2199     <replaceable>statements</replaceable>
2200 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2201 </synopsis>
2202      This is like the previous form, except that the source query
2203      is specified as a string expression, which is evaluated and replanned
2204      on each entry to the <literal>FOR</> loop.  This allows the programmer to
2205      choose the speed of a preplanned query or the flexibility of a dynamic
2206      query, just as with a plain <command>EXECUTE</command> statement.
2207      As with <command>EXECUTE</command>, parameter values can be inserted
2208      into the dynamic command via <literal>USING</>.
2209     </para>
2210
2211     <para>
2212      Another way to specify the query whose results should be iterated
2213      through is to declare it as a cursor.  This is described in
2214      <xref linkend="plpgsql-cursor-for-loop">.
2215     </para>
2216    </sect2>
2217
2218    <sect2 id="plpgsql-error-trapping">
2219     <title>Trapping Errors</title>
2220
2221     <indexterm>
2222      <primary>exceptions</primary>
2223      <secondary>in PL/PgSQL</secondary>
2224     </indexterm>
2225
2226     <para>
2227      By default, any error occurring in a <application>PL/pgSQL</>
2228      function aborts execution of the function, and indeed of the
2229      surrounding transaction as well.  You can trap errors and recover
2230      from them by using a <command>BEGIN</> block with an
2231      <literal>EXCEPTION</> clause.  The syntax is an extension of the
2232      normal syntax for a <command>BEGIN</> block:
2233
2234 <synopsis>
2235 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2236 <optional> DECLARE
2237     <replaceable>declarations</replaceable> </optional>
2238 BEGIN
2239     <replaceable>statements</replaceable>
2240 EXCEPTION
2241     WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2242         <replaceable>handler_statements</replaceable>
2243     <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2244           <replaceable>handler_statements</replaceable>
2245       ... </optional>
2246 END;
2247 </synopsis>
2248     </para>
2249
2250     <para>
2251      If no error occurs, this form of block simply executes all the
2252      <replaceable>statements</replaceable>, and then control passes
2253      to the next statement after <literal>END</>.  But if an error
2254      occurs within the <replaceable>statements</replaceable>, further
2255      processing of the <replaceable>statements</replaceable> is
2256      abandoned, and control passes to the <literal>EXCEPTION</> list.
2257      The list is searched for the first <replaceable>condition</replaceable>
2258      matching the error that occurred.  If a match is found, the
2259      corresponding <replaceable>handler_statements</replaceable> are
2260      executed, and then control passes to the next statement after
2261      <literal>END</>.  If no match is found, the error propagates out
2262      as though the <literal>EXCEPTION</> clause were not there at all:
2263      the error can be caught by an enclosing block with
2264      <literal>EXCEPTION</>, or if there is none it aborts processing
2265      of the function.
2266     </para>
2267
2268     <para>
2269      The <replaceable>condition</replaceable> names can be any of
2270      those shown in <xref linkend="errcodes-appendix">.  A category
2271      name matches any error within its category.  The special
2272      condition name <literal>OTHERS</> matches every error type except
2273      <literal>QUERY_CANCELED</>.  (It is possible, but often unwise,
2274      to trap <literal>QUERY_CANCELED</> by name.)  Condition names are
2275      not case-sensitive.  Also, an error condition can be specified
2276      by <literal>SQLSTATE</> code; for example these are equivalent:
2277 <programlisting>
2278 WHEN division_by_zero THEN ...
2279 WHEN SQLSTATE '22012' THEN ...
2280 </programlisting>
2281     </para>
2282
2283     <para>
2284      If a new error occurs within the selected
2285      <replaceable>handler_statements</replaceable>, it cannot be caught
2286      by this <literal>EXCEPTION</> clause, but is propagated out.
2287      A surrounding <literal>EXCEPTION</> clause could catch it.
2288     </para>
2289
2290     <para>
2291      When an error is caught by an <literal>EXCEPTION</> clause,
2292      the local variables of the <application>PL/pgSQL</> function
2293      remain as they were when the error occurred, but all changes
2294      to persistent database state within the block are rolled back.
2295      As an example, consider this fragment:
2296
2297 <programlisting>
2298 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2299 BEGIN
2300     UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2301     x := x + 1;
2302     y := x / 0;
2303 EXCEPTION
2304     WHEN division_by_zero THEN
2305         RAISE NOTICE 'caught division_by_zero';
2306         RETURN x;
2307 END;
2308 </programlisting>
2309
2310      When control reaches the assignment to <literal>y</>, it will
2311      fail with a <literal>division_by_zero</> error.  This will be caught by
2312      the <literal>EXCEPTION</> clause.  The value returned in the
2313      <command>RETURN</> statement will be the incremented value of
2314      <literal>x</>, but the effects of the <command>UPDATE</> command will
2315      have been rolled back.  The <command>INSERT</> command preceding the
2316      block is not rolled back, however, so the end result is that the database
2317      contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2318     </para>
2319
2320     <tip>
2321      <para>
2322       A block containing an <literal>EXCEPTION</> clause is significantly
2323       more expensive to enter and exit than a block without one.  Therefore,
2324       don't use <literal>EXCEPTION</> without need.
2325      </para>
2326     </tip>
2327
2328     <para>
2329      Within an exception handler, the <varname>SQLSTATE</varname>
2330      variable contains the error code that corresponds to the
2331      exception that was raised (refer to <xref
2332      linkend="errcodes-table"> for a list of possible error
2333      codes). The <varname>SQLERRM</varname> variable contains the
2334      error message associated with the exception. These variables are
2335      undefined outside exception handlers.
2336     </para>
2337
2338     <example id="plpgsql-upsert-example">
2339     <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2340     <para>
2341
2342     This example uses exception handling to perform either
2343     <command>UPDATE</> or <command>INSERT</>, as appropriate:
2344
2345 <programlisting>
2346 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2347
2348 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2349 $$
2350 BEGIN
2351     LOOP
2352         -- first try to update the key
2353         UPDATE db SET b = data WHERE a = key;
2354         IF found THEN
2355             RETURN;
2356         END IF;
2357         -- not there, so try to insert the key
2358         -- if someone else inserts the same key concurrently,
2359         -- we could get a unique-key failure
2360         BEGIN
2361             INSERT INTO db(a,b) VALUES (key, data);
2362             RETURN;
2363         EXCEPTION WHEN unique_violation THEN
2364             -- do nothing, and loop to try the UPDATE again
2365         END;
2366     END LOOP;
2367 END;
2368 $$
2369 LANGUAGE plpgsql;
2370
2371 SELECT merge_db(1, 'david');
2372 SELECT merge_db(1, 'dennis');
2373 </programlisting>
2374
2375     </para>
2376     </example>
2377   </sect2>
2378   </sect1>
2379
2380   <sect1 id="plpgsql-cursors">
2381    <title>Cursors</title>
2382
2383    <indexterm zone="plpgsql-cursors">
2384     <primary>cursor</primary>
2385     <secondary>in PL/pgSQL</secondary>
2386    </indexterm>
2387
2388    <para>
2389     Rather than executing a whole query at once, it is possible to set
2390     up a <firstterm>cursor</> that encapsulates the query, and then read
2391     the query result a few rows at a time. One reason for doing this is
2392     to avoid memory overrun when the result contains a large number of
2393     rows. (However, <application>PL/pgSQL</> users do not normally need
2394     to worry about that, since <literal>FOR</> loops automatically use a cursor
2395     internally to avoid memory problems.) A more interesting usage is to
2396     return a reference to a cursor that a function has created, allowing the
2397     caller to read the rows. This provides an efficient way to return
2398     large row sets from functions.
2399    </para>
2400
2401    <sect2 id="plpgsql-cursor-declarations">
2402     <title>Declaring Cursor Variables</title>
2403
2404     <para>
2405      All access to cursors in <application>PL/pgSQL</> goes through
2406      cursor variables, which are always of the special data type
2407      <type>refcursor</>.  One way to create a cursor variable
2408      is just to declare it as a variable of type <type>refcursor</>.
2409      Another way is to use the cursor declaration syntax,
2410      which in general is:
2411 <synopsis>
2412 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2413 </synopsis>
2414      (<literal>FOR</> can be replaced by <literal>IS</> for
2415      <productname>Oracle</productname> compatibility.)
2416      If <literal>SCROLL</> is specified, the cursor will be capable of
2417      scrolling backward; if <literal>NO SCROLL</> is specified, backward
2418      fetches will be rejected; if neither specification appears, it is
2419      query-dependent whether backward fetches will be allowed.
2420      <replaceable>arguments</replaceable>, if specified, is a
2421      comma-separated list of pairs <literal><replaceable>name</replaceable>
2422      <replaceable>datatype</replaceable></literal> that define names to be
2423      replaced by parameter values in the given query.  The actual
2424      values to substitute for these names will be specified later,
2425      when the cursor is opened.
2426     </para>
2427     <para>
2428      Some examples:
2429 <programlisting>
2430 DECLARE
2431     curs1 refcursor;
2432     curs2 CURSOR FOR SELECT * FROM tenk1;
2433     curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
2434 </programlisting>
2435      All three of these variables have the data type <type>refcursor</>,
2436      but the first can be used with any query, while the second has
2437      a fully specified query already <firstterm>bound</> to it, and the last
2438      has a parameterized query bound to it.  (<literal>key</> will be
2439      replaced by an integer parameter value when the cursor is opened.)
2440      The variable <literal>curs1</>
2441      is said to be <firstterm>unbound</> since it is not bound to
2442      any particular query.
2443     </para>
2444    </sect2>
2445
2446    <sect2 id="plpgsql-cursor-opening">
2447     <title>Opening Cursors</title>
2448
2449     <para>
2450      Before a cursor can be used to retrieve rows, it must be
2451      <firstterm>opened</>. (This is the equivalent action to the SQL
2452      command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2453      three forms of the <command>OPEN</> statement, two of which use unbound
2454      cursor variables while the third uses a bound cursor variable.
2455     </para>
2456
2457     <note>
2458      <para>
2459       Bound cursor variables can also be used without explicitly opening the cursor,
2460       via the <command>FOR</> statement described in
2461       <xref linkend="plpgsql-cursor-for-loop">.
2462      </para>
2463     </note>
2464
2465     <sect3>
2466      <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2467
2468 <synopsis>
2469 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2470 </synopsis>
2471
2472        <para>
2473         The cursor variable is opened and given the specified query to
2474         execute.  The cursor cannot be open already, and it must have been
2475         declared as an unbound cursor variable (that is, as a simple
2476         <type>refcursor</> variable).  The query must be a
2477         <command>SELECT</command>, or something else that returns rows
2478         (such as <command>EXPLAIN</>).  The query
2479         is treated in the same way as other SQL commands in
2480         <application>PL/pgSQL</>: <application>PL/pgSQL</>
2481         variable names are substituted, and the query plan is cached for
2482         possible reuse.  When a <application>PL/pgSQL</>
2483         variable is substituted into the cursor query, the value that is
2484         substituted is the one it has at the time of the <command>OPEN</>;
2485         subsequent changes to the variable will not affect the cursor's
2486         behavior.
2487         The <literal>SCROLL</> and <literal>NO SCROLL</>
2488         options have the same meanings as for a bound cursor.
2489        </para>
2490
2491        <para>
2492         An example:
2493 <programlisting>
2494 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2495 </programlisting>
2496        </para>
2497      </sect3>
2498
2499     <sect3>
2500      <title><command>OPEN FOR EXECUTE</command></title>
2501
2502 <synopsis>
2503 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2504                                      <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2505 </synopsis>
2506
2507          <para>
2508           The cursor variable is opened and given the specified query to
2509           execute.  The cursor cannot be open already, and it must have been
2510           declared as an unbound cursor variable (that is, as a simple
2511           <type>refcursor</> variable).  The query is specified as a string
2512           expression, in the same way as in the <command>EXECUTE</command>
2513           command.  As usual, this gives flexibility so the query plan can vary
2514           from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2515           and it also means that variable substitution is not done on the
2516           command string. As with <command>EXECUTE</command>, parameter values
2517           can be inserted into the dynamic command via <literal>USING</>.
2518           The <literal>SCROLL</> and
2519           <literal>NO SCROLL</> options have the same meanings as for a bound
2520           cursor.
2521          </para>
2522
2523        <para>
2524         An example:
2525 <programlisting>
2526 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident(tabname)
2527                                         || ' WHERE col1 = $1' USING keyvalue;
2528 </programlisting>
2529         In this example, the table name is inserted into the query textually,
2530         so use of <function>quote_ident()</> is recommended to guard against
2531         SQL injection.  The comparison value for <literal>col1</> is inserted
2532         via a <literal>USING</> parameter, so it needs no quoting.
2533        </para>
2534      </sect3>
2535
2536     <sect3>
2537      <title>Opening a Bound Cursor</title>
2538
2539 <synopsis>
2540 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
2541 </synopsis>
2542
2543          <para>
2544           This form of <command>OPEN</command> is used to open a cursor
2545           variable whose query was bound to it when it was declared.  The
2546           cursor cannot be open already.  A list of actual argument value
2547           expressions must appear if and only if the cursor was declared to
2548           take arguments.  These values will be substituted in the query.
2549           The query plan for a bound cursor is always considered cacheable;
2550           there is no equivalent of <command>EXECUTE</command> in this case.
2551           Notice that <literal>SCROLL</> and
2552           <literal>NO SCROLL</> cannot be specified, as the cursor's scrolling
2553           behavior was already determined.
2554          </para>
2555
2556          <para>
2557           Note that because variable substitution is done on the bound
2558           cursor's query, there are two ways to pass values into the cursor:
2559           either with an explicit argument to <command>OPEN</>, or
2560           implicitly by referencing a <application>PL/pgSQL</> variable
2561           in the query.  However, only variables declared before the bound
2562           cursor was declared will be substituted into it.  In either case
2563           the value to be passed is determined at the time of the
2564           <command>OPEN</>.
2565          </para>
2566
2567     <para>
2568      Examples:
2569 <programlisting>
2570 OPEN curs2;
2571 OPEN curs3(42);
2572 </programlisting>
2573        </para>
2574      </sect3>
2575    </sect2>
2576
2577    <sect2 id="plpgsql-cursor-using">
2578     <title>Using Cursors</title>
2579
2580     <para>
2581      Once a cursor has been opened, it can be manipulated with the
2582      statements described here.
2583     </para>
2584
2585     <para>
2586      These manipulations need not occur in the same function that
2587      opened the cursor to begin with.  You can return a <type>refcursor</>
2588      value out of a function and let the caller operate on the cursor.
2589      (Internally, a <type>refcursor</> value is simply the string name
2590      of a so-called portal containing the active query for the cursor.  This name
2591      can be passed around, assigned to other <type>refcursor</> variables,
2592      and so on, without disturbing the portal.)
2593     </para>
2594
2595     <para>
2596      All portals are implicitly closed at transaction end.  Therefore
2597      a <type>refcursor</> value is usable to reference an open cursor
2598      only until the end of the transaction.
2599     </para>
2600
2601     <sect3>
2602      <title><literal>FETCH</></title>
2603
2604 <synopsis>
2605 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2606 </synopsis>
2607
2608     <para>
2609      <command>FETCH</command> retrieves the next row from the
2610      cursor into a target, which might be a row variable, a record
2611      variable, or a comma-separated list of simple variables, just like
2612      <command>SELECT INTO</command>.  If there is no next row, the
2613      target is set to NULL(s).  As with <command>SELECT
2614      INTO</command>, the special variable <literal>FOUND</literal> can
2615      be checked to see whether a row was obtained or not.
2616     </para>
2617
2618     <para>
2619      The <replaceable>direction</replaceable> clause can be any of the
2620      variants allowed in the SQL <xref linkend="sql-fetch">
2621      command except the ones that can fetch
2622      more than one row; namely, it can be
2623      <literal>NEXT</>,
2624      <literal>PRIOR</>,
2625      <literal>FIRST</>,
2626      <literal>LAST</>,
2627      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2628      <literal>RELATIVE</> <replaceable>count</replaceable>,
2629      <literal>FORWARD</>, or
2630      <literal>BACKWARD</>.
2631      Omitting <replaceable>direction</replaceable> is the same
2632      as specifying <literal>NEXT</>.
2633      <replaceable>direction</replaceable> values that require moving
2634      backward are likely to fail unless the cursor was declared or opened
2635      with the <literal>SCROLL</> option.
2636     </para>
2637
2638     <para>
2639      <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2640      variable that references an open cursor portal.
2641     </para>
2642
2643     <para>
2644      Examples:
2645 <programlisting>
2646 FETCH curs1 INTO rowvar;
2647 FETCH curs2 INTO foo, bar, baz;
2648 FETCH LAST FROM curs3 INTO x, y;
2649 FETCH RELATIVE -2 FROM curs4 INTO x;
2650 </programlisting>
2651        </para>
2652      </sect3>
2653
2654     <sect3>
2655      <title><literal>MOVE</></title>
2656
2657 <synopsis>
2658 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2659 </synopsis>
2660
2661     <para>
2662      <command>MOVE</command> repositions a cursor without retrieving
2663      any data. <command>MOVE</command> works exactly like the
2664      <command>FETCH</command> command, except it only repositions the
2665      cursor and does not return the row moved to. As with <command>SELECT
2666      INTO</command>, the special variable <literal>FOUND</literal> can
2667      be checked to see whether there was a next row to move to.
2668     </para>
2669
2670     <para>
2671      The <replaceable>direction</replaceable> clause can be any of the
2672      variants allowed in the SQL <xref linkend="sql-fetch">
2673      command, namely
2674      <literal>NEXT</>,
2675      <literal>PRIOR</>,
2676      <literal>FIRST</>,
2677      <literal>LAST</>,
2678      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2679      <literal>RELATIVE</> <replaceable>count</replaceable>,
2680      <literal>ALL</>,
2681      <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
2682      <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
2683      Omitting <replaceable>direction</replaceable> is the same
2684      as specifying <literal>NEXT</>.
2685      <replaceable>direction</replaceable> values that require moving
2686      backward are likely to fail unless the cursor was declared or opened
2687      with the <literal>SCROLL</> option.
2688     </para>
2689
2690     <para>
2691      Examples:
2692 <programlisting>
2693 MOVE curs1;
2694 MOVE LAST FROM curs3;
2695 MOVE RELATIVE -2 FROM curs4;
2696 MOVE FORWARD 2 FROM curs4;
2697 </programlisting>
2698        </para>
2699      </sect3>
2700
2701     <sect3>
2702      <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
2703
2704 <synopsis>
2705 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
2706 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
2707 </synopsis>
2708
2709        <para>
2710         When a cursor is positioned on a table row, that row can be updated
2711         or deleted using the cursor to identify the row.  There are
2712         restrictions on what the cursor's query can be (in particular,
2713         no grouping) and it's best to use <literal>FOR UPDATE</> in the
2714         cursor.  For more information see the
2715         <xref linkend="sql-declare">
2716         reference page.
2717        </para>
2718
2719        <para>
2720         An example:
2721 <programlisting>
2722 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
2723 </programlisting>
2724        </para>
2725      </sect3>
2726
2727     <sect3>
2728      <title><literal>CLOSE</></title>
2729
2730 <synopsis>
2731 CLOSE <replaceable>cursor</replaceable>;
2732 </synopsis>
2733
2734        <para>
2735         <command>CLOSE</command> closes the portal underlying an open
2736         cursor.  This can be used to release resources earlier than end of
2737         transaction, or to free up the cursor variable to be opened again.
2738        </para>
2739
2740        <para>
2741         An example:
2742 <programlisting>
2743 CLOSE curs1;
2744 </programlisting>
2745        </para>
2746      </sect3>
2747
2748     <sect3>
2749      <title>Returning Cursors</title>
2750
2751        <para>
2752         <application>PL/pgSQL</> functions can return cursors to the
2753         caller. This is useful to return multiple rows or columns,
2754         especially with very large result sets.  To do this, the function
2755         opens the cursor and returns the cursor name to the caller (or simply
2756         opens the cursor using a portal name specified by or otherwise known
2757         to the caller).  The caller can then fetch rows from the cursor. The
2758         cursor can be closed by the caller, or it will be closed automatically
2759         when the transaction closes.
2760        </para>
2761
2762        <para>
2763         The portal name used for a cursor can be specified by the
2764         programmer or automatically generated.  To specify a portal name,
2765         simply assign a string to the <type>refcursor</> variable before
2766         opening it.  The string value of the <type>refcursor</> variable
2767         will be used by <command>OPEN</> as the name of the underlying portal.
2768         However, if the <type>refcursor</> variable is null,
2769         <command>OPEN</> automatically generates a name that does not
2770         conflict with any existing portal, and assigns it to the
2771         <type>refcursor</> variable.
2772        </para>
2773
2774        <note>
2775         <para>
2776          A bound cursor variable is initialized to the string value
2777          representing its name, so that the portal name is the same as
2778          the cursor variable name, unless the programmer overrides it
2779          by assignment before opening the cursor.  But an unbound cursor
2780          variable defaults to the null value initially, so it will receive
2781          an automatically-generated unique name, unless overridden.
2782         </para>
2783        </note>
2784
2785        <para>
2786         The following example shows one way a cursor name can be supplied by
2787         the caller:
2788
2789 <programlisting>
2790 CREATE TABLE test (col text);
2791 INSERT INTO test VALUES ('123');
2792
2793 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
2794 BEGIN
2795     OPEN $1 FOR SELECT col FROM test;
2796     RETURN $1;
2797 END;
2798 ' LANGUAGE plpgsql;
2799
2800 BEGIN;
2801 SELECT reffunc('funccursor');
2802 FETCH ALL IN funccursor;
2803 COMMIT;
2804 </programlisting>
2805        </para>
2806
2807        <para>
2808         The following example uses automatic cursor name generation:
2809
2810 <programlisting>
2811 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
2812 DECLARE
2813     ref refcursor;
2814 BEGIN
2815     OPEN ref FOR SELECT col FROM test;
2816     RETURN ref;
2817 END;
2818 ' LANGUAGE plpgsql;
2819
2820 -- need to be in a transaction to use cursors.
2821 BEGIN;
2822 SELECT reffunc2();
2823
2824       reffunc2
2825 --------------------
2826  &lt;unnamed cursor 1&gt;
2827 (1 row)
2828
2829 FETCH ALL IN "&lt;unnamed cursor 1&gt;";
2830 COMMIT;
2831 </programlisting>
2832        </para>
2833
2834        <para>
2835         The following example shows one way to return multiple cursors
2836         from a single function:
2837
2838 <programlisting>
2839 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
2840 BEGIN
2841     OPEN $1 FOR SELECT * FROM table_1;
2842     RETURN NEXT $1;
2843     OPEN $2 FOR SELECT * FROM table_2;
2844     RETURN NEXT $2;
2845 END;
2846 $$ LANGUAGE plpgsql;
2847
2848 -- need to be in a transaction to use cursors.
2849 BEGIN;
2850
2851 SELECT * FROM myfunc('a', 'b');
2852
2853 FETCH ALL FROM a;
2854 FETCH ALL FROM b;
2855 COMMIT;
2856 </programlisting>
2857        </para>
2858      </sect3>
2859    </sect2>
2860
2861    <sect2 id="plpgsql-cursor-for-loop">
2862     <title>Looping Through a Cursor's Result</title>
2863
2864     <para>
2865      There is a variant of the <command>FOR</> statement that allows
2866      iterating through the rows returned by a cursor.  The syntax is:
2867
2868 <synopsis>
2869 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2870 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional> LOOP
2871     <replaceable>statements</replaceable>
2872 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2873 </synopsis>
2874
2875      The cursor variable must have been bound to some query when it was
2876      declared, and it <emphasis>cannot</> be open already.  The
2877      <command>FOR</> statement automatically opens the cursor, and it closes
2878      the cursor again when the loop exits.  A list of actual argument value
2879      expressions must appear if and only if the cursor was declared to take
2880      arguments.  These values will be substituted in the query, in just
2881      the same way as during an <command>OPEN</>.
2882      The variable <replaceable>recordvar</replaceable> is automatically
2883      defined as type <type>record</> and exists only inside the loop (any
2884      existing definition of the variable name is ignored within the loop).
2885      Each row returned by the cursor is successively assigned to this
2886      record variable and the loop body is executed.
2887     </para>
2888    </sect2>
2889
2890   </sect1>
2891
2892   <sect1 id="plpgsql-errors-and-messages">
2893    <title>Errors and Messages</title>
2894
2895    <indexterm>
2896     <primary>RAISE</primary>
2897    </indexterm>
2898
2899    <indexterm>
2900     <primary>reporting errors</primary>
2901     <secondary>in PL/PgSQL</secondary>
2902    </indexterm>
2903
2904    <para>
2905     Use the <command>RAISE</command> statement to report messages and
2906     raise errors.
2907
2908 <synopsis>
2909 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>;
2910 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>;
2911 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>;
2912 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
2913 RAISE ;
2914 </synopsis>
2915
2916     The <replaceable class="parameter">level</replaceable> option specifies
2917     the error severity.  Allowed levels are <literal>DEBUG</literal>,
2918     <literal>LOG</literal>, <literal>INFO</literal>,
2919     <literal>NOTICE</literal>, <literal>WARNING</literal>,
2920     and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
2921     being the default.
2922     <literal>EXCEPTION</literal> raises an error (which normally aborts the
2923     current transaction); the other levels only generate messages of different
2924     priority levels.
2925     Whether messages of a particular priority are reported to the client,
2926     written to the server log, or both is controlled by the
2927     <xref linkend="guc-log-min-messages"> and
2928     <xref linkend="guc-client-min-messages"> configuration
2929     variables. See <xref linkend="runtime-config"> for more
2930     information.
2931    </para>
2932
2933    <para>
2934     After <replaceable class="parameter">level</replaceable> if any,
2935     you can write a <replaceable class="parameter">format</replaceable>
2936     (which must be a simple string literal, not an expression).  The
2937     format string specifies the error message text to be reported.
2938     The format string can be followed
2939     by optional argument expressions to be inserted into the message.
2940     Inside the format string, <literal>%</literal> is replaced by the
2941     string representation of the next optional argument's value. Write
2942     <literal>%%</literal> to emit a literal <literal>%</literal>.
2943    </para>
2944
2945    <para>
2946     In this example, the value of <literal>v_job_id</> will replace the
2947     <literal>%</literal> in the string:
2948 <programlisting>
2949 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
2950 </programlisting>
2951    </para>
2952
2953    <para>
2954     You can attach additional information to the error report by writing
2955     <literal>USING</> followed by <replaceable
2956     class="parameter">option</replaceable> = <replaceable
2957     class="parameter">expression</replaceable> items.  The allowed
2958     <replaceable class="parameter">option</replaceable> keywords are
2959     <literal>MESSAGE</>, <literal>DETAIL</>, <literal>HINT</>, and
2960     <literal>ERRCODE</>, while each <replaceable
2961     class="parameter">expression</replaceable> can be any string-valued
2962     expression.
2963     <literal>MESSAGE</> sets the error message text (this option can't
2964     be used in the form of <command>RAISE</> that includes a format
2965     string before <literal>USING</>).
2966     <literal>DETAIL</> supplies an error detail message, while
2967     <literal>HINT</> supplies a hint message.
2968     <literal>ERRCODE</> specifies the error code (SQLSTATE) to report,
2969     either by condition name as shown in <xref linkend="errcodes-appendix">,
2970     or directly as a five-character SQLSTATE code.
2971    </para>
2972
2973    <para>
2974     This example will abort the transaction with the given error message
2975     and hint:
2976 <programlisting>
2977 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
2978       USING HINT = 'Please check your user id';
2979 </programlisting>
2980    </para>
2981
2982    <para>
2983     These two examples show equivalent ways of setting the SQLSTATE:
2984 <programlisting>
2985 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
2986 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
2987 </programlisting>
2988    </para>
2989
2990    <para>
2991     There is a second <command>RAISE</> syntax in which the main argument
2992     is the condition name or SQLSTATE to be reported, for example:
2993 <programlisting>
2994 RAISE division_by_zero;
2995 RAISE SQLSTATE '22012';
2996 </programlisting>
2997     In this syntax, <literal>USING</> can be used to supply a custom
2998     error message, detail, or hint.  Another way to do the earlier
2999     example is
3000 <programlisting>
3001 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3002 </programlisting>
3003    </para>
3004
3005    <para>
3006     Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3007     <replaceable class="parameter">level</replaceable> USING</> and put
3008     everything else into the <literal>USING</> list.
3009    </para>
3010
3011    <para>
3012     The last variant of <command>RAISE</> has no parameters at all.
3013     This form can only be used inside a <literal>BEGIN</> block's
3014     <literal>EXCEPTION</> clause;
3015     it causes the error currently being handled to be re-thrown.
3016    </para>
3017
3018    <note>
3019     <para>
3020      Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3021      parameters was interpreted as re-throwing the error from the block
3022      containing the active exception handler.  Thus an <literal>EXCEPTION</>
3023      clause nested within that handler could not catch it, even if the
3024      <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3025      block. This was deemed surprising as well as being incompatible with
3026      Oracle's PL/SQL.
3027     </para>
3028    </note>
3029
3030    <para>
3031     If no condition name nor SQLSTATE is specified in a
3032     <command>RAISE EXCEPTION</command> command, the default is to use
3033     <literal>RAISE_EXCEPTION</> (<literal>P0001</>).  If no message
3034     text is specified, the default is to use the condition name or
3035     SQLSTATE as message text.
3036    </para>
3037
3038    <note>
3039     <para>
3040      When specifying an error code by SQLSTATE code, you are not
3041      limited to the predefined error codes, but can select any
3042      error code consisting of five digits and/or upper-case ASCII
3043      letters, other than <literal>00000</>.  It is recommended that
3044      you avoid throwing error codes that end in three zeroes, because
3045      these are category codes and can only be trapped by trapping
3046      the whole category.
3047     </para>
3048    </note>
3049
3050  </sect1>
3051
3052  <sect1 id="plpgsql-trigger">
3053   <title>Trigger Procedures</title>
3054
3055   <indexterm zone="plpgsql-trigger">
3056    <primary>trigger</primary>
3057    <secondary>in PL/pgSQL</secondary>
3058   </indexterm>
3059
3060   <para>
3061     <application>PL/pgSQL</application> can be used to define trigger
3062     procedures. A trigger procedure is created with the
3063     <command>CREATE FUNCTION</> command, declaring it as a function with
3064     no arguments and a return type of <type>trigger</type>.  Note that
3065     the function must be declared with no arguments even if it expects
3066     to receive arguments specified in <command>CREATE TRIGGER</> &mdash;
3067     trigger arguments are passed via <varname>TG_ARGV</>, as described
3068     below.
3069   </para>
3070
3071   <para>
3072    When a <application>PL/pgSQL</application> function is called as a
3073    trigger, several special variables are created automatically in the
3074    top-level block. They are:
3075
3076    <variablelist>
3077     <varlistentry>
3078      <term><varname>NEW</varname></term>
3079      <listitem>
3080       <para>
3081        Data type <type>RECORD</type>; variable holding the new
3082        database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3083        triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3084        and for <command>DELETE</command> operations.
3085       </para>
3086      </listitem>
3087     </varlistentry>
3088
3089     <varlistentry>
3090      <term><varname>OLD</varname></term>
3091      <listitem>
3092       <para>
3093        Data type <type>RECORD</type>; variable holding the old
3094        database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3095        triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3096        and for <command>INSERT</command> operations.
3097       </para>
3098      </listitem>
3099     </varlistentry>
3100
3101     <varlistentry>
3102      <term><varname>TG_NAME</varname></term>
3103      <listitem>
3104       <para>
3105        Data type <type>name</type>; variable that contains the name of the trigger actually
3106        fired.
3107       </para>
3108      </listitem>
3109     </varlistentry>
3110
3111     <varlistentry>
3112      <term><varname>TG_WHEN</varname></term>
3113      <listitem>
3114       <para>
3115        Data type <type>text</type>; a string of either
3116        <literal>BEFORE</literal> or <literal>AFTER</literal>
3117        depending on the trigger's definition.
3118       </para>
3119      </listitem>
3120     </varlistentry>
3121
3122     <varlistentry>
3123      <term><varname>TG_LEVEL</varname></term>
3124      <listitem>
3125       <para>
3126        Data type <type>text</type>; a string of either
3127        <literal>ROW</literal> or <literal>STATEMENT</literal>
3128        depending on the trigger's definition.
3129       </para>
3130      </listitem>
3131     </varlistentry>
3132
3133     <varlistentry>
3134      <term><varname>TG_OP</varname></term>
3135      <listitem>
3136       <para>
3137        Data type <type>text</type>; a string of
3138        <literal>INSERT</literal>, <literal>UPDATE</literal>,
3139        <literal>DELETE</literal>, or <literal>TRUNCATE</>
3140        telling for which operation the trigger was fired.
3141       </para>
3142      </listitem>
3143     </varlistentry>
3144
3145     <varlistentry>
3146      <term><varname>TG_RELID</varname></term>
3147      <listitem>
3148       <para>
3149        Data type <type>oid</type>; the object ID of the table that caused the
3150        trigger invocation.
3151       </para>
3152      </listitem>
3153     </varlistentry>
3154
3155     <varlistentry>
3156      <term><varname>TG_RELNAME</varname></term>
3157      <listitem>
3158       <para>
3159        Data type <type>name</type>; the name of the table that caused the trigger
3160        invocation. This is now deprecated, and could disappear in a future
3161        release. Use <literal>TG_TABLE_NAME</> instead.
3162       </para>
3163      </listitem>
3164     </varlistentry>
3165
3166     <varlistentry>
3167      <term><varname>TG_TABLE_NAME</varname></term>
3168      <listitem>
3169       <para>
3170        Data type <type>name</type>; the name of the table that
3171        caused the trigger invocation.
3172       </para>
3173      </listitem>
3174     </varlistentry>
3175
3176     <varlistentry>
3177      <term><varname>TG_TABLE_SCHEMA</varname></term>
3178      <listitem>
3179       <para>
3180        Data type <type>name</type>; the name of the schema of the
3181        table that caused the trigger invocation.
3182       </para>
3183      </listitem>
3184     </varlistentry>
3185
3186     <varlistentry>
3187      <term><varname>TG_NARGS</varname></term>
3188      <listitem>
3189       <para>
3190        Data type <type>integer</type>; the number of arguments given to the trigger
3191        procedure in the <command>CREATE TRIGGER</command> statement.
3192       </para>
3193      </listitem>
3194     </varlistentry>
3195
3196     <varlistentry>
3197      <term><varname>TG_ARGV[]</varname></term>
3198      <listitem>
3199       <para>
3200        Data type array of <type>text</type>; the arguments from
3201        the <command>CREATE TRIGGER</command> statement.
3202        The index counts from 0. Invalid
3203        indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3204        result in a null value.
3205       </para>
3206      </listitem>
3207     </varlistentry>
3208    </variablelist>
3209   </para>
3210
3211    <para>
3212     A trigger function must return either <symbol>NULL</symbol> or a
3213     record/row value having exactly the structure of the table the
3214     trigger was fired for.
3215    </para>
3216
3217    <para>
3218     Row-level triggers fired <literal>BEFORE</> can return null to signal the
3219     trigger manager to skip the rest of the operation for this row
3220     (i.e., subsequent triggers are not fired, and the
3221     <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3222     for this row).  If a nonnull
3223     value is returned then the operation proceeds with that row value.
3224     Returning a row value different from the original value
3225     of <varname>NEW</> alters the row that will be inserted or
3226     updated.  Thus, if the trigger function wants the triggering
3227     action to succeed normally without altering the row
3228     value, <varname>NEW</varname> (or a value equal thereto) has to be
3229     returned.  To alter the row to be stored, it is possible to
3230     replace single values directly in <varname>NEW</> and return the
3231     modified <varname>NEW</>, or to build a complete new record/row to
3232     return.  In the case of a before-trigger
3233     on <command>DELETE</command>, the returned value has no direct
3234     effect, but it has to be nonnull to allow the trigger action to
3235     proceed.  Note that <varname>NEW</varname> is null
3236     in <command>DELETE</command> triggers, so returning that is
3237     usually not sensible.  A useful idiom in <command>DELETE</command>
3238     triggers might be to return <varname>OLD</varname>.
3239    </para>
3240
3241    <para>
3242     The return value of a row-level trigger
3243     fired <literal>AFTER</literal> or a statement-level trigger
3244     fired <literal>BEFORE</> or <literal>AFTER</> is
3245     always ignored; it might as well be null. However, any of these types of
3246     triggers might still abort the entire operation by raising an error.
3247    </para>
3248
3249    <para>
3250     <xref linkend="plpgsql-trigger-example"> shows an example of a
3251     trigger procedure in <application>PL/pgSQL</application>.
3252    </para>
3253
3254    <example id="plpgsql-trigger-example">
3255     <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3256
3257     <para>
3258      This example trigger ensures that any time a row is inserted or updated
3259      in the table, the current user name and time are stamped into the
3260      row. And it checks that an employee's name is given and that the
3261      salary is a positive value.
3262     </para>
3263
3264 <programlisting>
3265 CREATE TABLE emp (
3266     empname text,
3267     salary integer,
3268     last_date timestamp,
3269     last_user text
3270 );
3271
3272 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3273     BEGIN
3274         -- Check that empname and salary are given
3275         IF NEW.empname IS NULL THEN
3276             RAISE EXCEPTION 'empname cannot be null';
3277         END IF;
3278         IF NEW.salary IS NULL THEN
3279             RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3280         END IF;
3281
3282         -- Who works for us when she must pay for it?
3283         IF NEW.salary &lt; 0 THEN
3284             RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3285         END IF;
3286
3287         -- Remember who changed the payroll when
3288         NEW.last_date := current_timestamp;
3289         NEW.last_user := current_user;
3290         RETURN NEW;
3291     END;
3292 $emp_stamp$ LANGUAGE plpgsql;
3293
3294 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3295     FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3296 </programlisting>
3297    </example>
3298
3299    <para>
3300     Another way to log changes to a table involves creating a new table that
3301     holds a row for each insert, update, or delete that occurs. This approach
3302     can be thought of as auditing changes to a table.
3303     <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3304     audit trigger procedure in <application>PL/pgSQL</application>.
3305    </para>
3306
3307    <example id="plpgsql-trigger-audit-example">
3308     <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3309
3310     <para>
3311      This example trigger ensures that any insert, update or delete of a row
3312      in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3313      The current time and user name are stamped into the row, together with
3314      the type of operation performed on it.
3315     </para>
3316
3317 <programlisting>
3318 CREATE TABLE emp (
3319     empname           text NOT NULL,
3320     salary            integer
3321 );
3322
3323 CREATE TABLE emp_audit(
3324     operation         char(1)   NOT NULL,
3325     stamp             timestamp NOT NULL,
3326     userid            text      NOT NULL,
3327     empname           text      NOT NULL,
3328     salary integer
3329 );
3330
3331 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3332     BEGIN
3333         --
3334         -- Create a row in emp_audit to reflect the operation performed on emp,
3335         -- make use of the special variable TG_OP to work out the operation.
3336         --
3337         IF (TG_OP = 'DELETE') THEN
3338             INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3339             RETURN OLD;
3340         ELSIF (TG_OP = 'UPDATE') THEN
3341             INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3342             RETURN NEW;
3343         ELSIF (TG_OP = 'INSERT') THEN
3344             INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3345             RETURN NEW;
3346         END IF;
3347         RETURN NULL; -- result is ignored since this is an AFTER trigger
3348     END;
3349 $emp_audit$ LANGUAGE plpgsql;
3350
3351 CREATE TRIGGER emp_audit
3352 AFTER INSERT OR UPDATE OR DELETE ON emp
3353     FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3354 </programlisting>
3355    </example>
3356
3357    <para>
3358     One use of triggers is to maintain a summary table
3359     of another table. The resulting summary can be used in place of the
3360     original table for certain queries &mdash; often with vastly reduced run
3361     times.
3362     This technique is commonly used in Data Warehousing, where the tables
3363     of measured or observed data (called fact tables) might be extremely large.
3364     <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3365     trigger procedure in <application>PL/pgSQL</application> that maintains
3366     a summary table for a fact table in a data warehouse.
3367    </para>
3368
3369
3370    <example id="plpgsql-trigger-summary-example">
3371     <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3372
3373     <para>
3374      The schema detailed here is partly based on the <emphasis>Grocery Store
3375      </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3376      by Ralph Kimball.
3377     </para>
3378
3379 <programlisting>
3380 --
3381 -- Main tables - time dimension and sales fact.
3382 --
3383 CREATE TABLE time_dimension (
3384     time_key                    integer NOT NULL,
3385     day_of_week                 integer NOT NULL,
3386     day_of_month                integer NOT NULL,
3387     month                       integer NOT NULL,
3388     quarter                     integer NOT NULL,
3389     year                        integer NOT NULL
3390 );
3391 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3392
3393 CREATE TABLE sales_fact (
3394     time_key                    integer NOT NULL,
3395     product_key                 integer NOT NULL,
3396     store_key                   integer NOT NULL,
3397     amount_sold                 numeric(12,2) NOT NULL,
3398     units_sold                  integer NOT NULL,
3399     amount_cost                 numeric(12,2) NOT NULL
3400 );
3401 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3402
3403 --
3404 -- Summary table - sales by time.
3405 --
3406 CREATE TABLE sales_summary_bytime (
3407     time_key                    integer NOT NULL,
3408     amount_sold                 numeric(15,2) NOT NULL,
3409     units_sold                  numeric(12) NOT NULL,
3410     amount_cost                 numeric(15,2) NOT NULL
3411 );
3412 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3413
3414 --
3415 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3416 --
3417 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
3418 AS $maint_sales_summary_bytime$
3419     DECLARE
3420         delta_time_key          integer;
3421         delta_amount_sold       numeric(15,2);
3422         delta_units_sold        numeric(12);
3423         delta_amount_cost       numeric(15,2);
3424     BEGIN
3425
3426         -- Work out the increment/decrement amount(s).
3427         IF (TG_OP = 'DELETE') THEN
3428
3429             delta_time_key = OLD.time_key;
3430             delta_amount_sold = -1 * OLD.amount_sold;
3431             delta_units_sold = -1 * OLD.units_sold;
3432             delta_amount_cost = -1 * OLD.amount_cost;
3433
3434         ELSIF (TG_OP = 'UPDATE') THEN
3435
3436             -- forbid updates that change the time_key -
3437             -- (probably not too onerous, as DELETE + INSERT is how most
3438             -- changes will be made).
3439             IF ( OLD.time_key != NEW.time_key) THEN
3440                 RAISE EXCEPTION 'Update of time_key : % -&gt; % not allowed',
3441                                                       OLD.time_key, NEW.time_key;
3442             END IF;
3443
3444             delta_time_key = OLD.time_key;
3445             delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3446             delta_units_sold = NEW.units_sold - OLD.units_sold;
3447             delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3448
3449         ELSIF (TG_OP = 'INSERT') THEN
3450
3451             delta_time_key = NEW.time_key;
3452             delta_amount_sold = NEW.amount_sold;
3453             delta_units_sold = NEW.units_sold;
3454             delta_amount_cost = NEW.amount_cost;
3455
3456         END IF;
3457
3458
3459         -- Insert or update the summary row with the new values.
3460         &lt;&lt;insert_update&gt;&gt;
3461         LOOP
3462             UPDATE sales_summary_bytime
3463                 SET amount_sold = amount_sold + delta_amount_sold,
3464                     units_sold = units_sold + delta_units_sold,
3465                     amount_cost = amount_cost + delta_amount_cost
3466                 WHERE time_key = delta_time_key;
3467
3468             EXIT insert_update WHEN found;
3469
3470             BEGIN
3471                 INSERT INTO sales_summary_bytime (
3472                             time_key,
3473                             amount_sold,
3474                             units_sold,
3475                             amount_cost)
3476                     VALUES (
3477                             delta_time_key,
3478                             delta_amount_sold,
3479                             delta_units_sold,
3480                             delta_amount_cost
3481                            );
3482
3483                 EXIT insert_update;
3484
3485             EXCEPTION
3486                 WHEN UNIQUE_VIOLATION THEN
3487                     -- do nothing
3488             END;
3489         END LOOP insert_update;
3490
3491         RETURN NULL;
3492
3493     END;
3494 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3495
3496 CREATE TRIGGER maint_sales_summary_bytime
3497 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3498     FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3499
3500 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3501 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3502 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3503 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3504 SELECT * FROM sales_summary_bytime;
3505 DELETE FROM sales_fact WHERE product_key = 1;
3506 SELECT * FROM sales_summary_bytime;
3507 UPDATE sales_fact SET units_sold = units_sold * 2;
3508 SELECT * FROM sales_summary_bytime;
3509 </programlisting>
3510    </example>
3511
3512   </sect1>
3513
3514   <sect1 id="plpgsql-implementation">
3515    <title><application>PL/pgSQL</> Under the Hood</title>
3516
3517    <para>
3518     This section discusses some implementation details that are
3519     frequently important for <application>PL/pgSQL</> users to know.
3520    </para>
3521
3522   <sect2 id="plpgsql-var-subst">
3523    <title>Variable Substitution</title>
3524
3525    <para>
3526     SQL statements and expressions within a <application>PL/pgSQL</> function
3527     can refer to variables and parameters of the function.  Behind the scenes,
3528     <application>PL/pgSQL</> substitutes query parameters for such references.
3529     Parameters will only be substituted in places where a parameter or
3530     column reference is syntactically allowed.  As an extreme case, consider
3531     this example of poor programming style:
3532 <programlisting>
3533 INSERT INTO foo (foo) VALUES (foo);
3534 </programlisting>
3535     The first occurrence of <literal>foo</> must syntactically be a table
3536     name, so it will not be substituted, even if the function has a variable
3537     named <literal>foo</>.  The second occurrence must be the name of a
3538     column of the table, so it will not be substituted either.  Only the
3539     third occurrence is a candidate to be a reference to the function's
3540     variable.
3541    </para>
3542
3543    <note>
3544     <para>
3545      <productname>PostgreSQL</productname> versions before 9.0 would try
3546      to substitute the variable in all three cases, leading to syntax errors.
3547     </para>
3548    </note>
3549
3550    <para>
3551     Since the names of variables are syntactically no different from the names
3552     of table columns, there can be ambiguity in statements that also refer to
3553     tables: is a given name meant to refer to a table column, or a variable?
3554     Let's change the previous example to
3555 <programlisting>
3556 INSERT INTO dest (col) SELECT foo + bar FROM src;
3557 </programlisting>
3558     Here, <literal>dest</> and <literal>src</> must be table names, and
3559     <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
3560     and <literal>bar</> might reasonably be either variables of the function
3561     or columns of <literal>src</>.
3562    </para>
3563
3564    <para>
3565     By default, <application>PL/pgSQL</> will report an error if a name
3566     in a SQL statement could refer to either a variable or a table column.
3567     You can fix such a problem by renaming the variable or column,
3568     or by qualifying the ambiguous reference, or by telling
3569     <application>PL/pgSQL</> which interpretation to prefer.
3570    </para>
3571
3572    <para>
3573     The simplest solution is to rename the variable or column.
3574     A common coding rule is to use a
3575     different naming convention for <application>PL/pgSQL</application>
3576     variables than you use for column names.  For example,
3577     if you consistently name function variables
3578     <literal>v_<replaceable>something</></literal> while none of your
3579     column names start with <literal>v_</>, no conflicts will occur.
3580    </para>
3581
3582    <para>
3583     Alternatively you can qualify ambiguous references to make them clear.
3584     In the above example, <literal>src.foo</> would be an unambiguous reference
3585     to the table column.  To create an unambiguous reference to a variable,
3586     declare it in a labeled block and use the block's label
3587     (see <xref linkend="plpgsql-structure">).  For example,
3588 <programlisting>
3589 &lt;&lt;block&gt;&gt;
3590 DECLARE
3591     foo int;
3592 BEGIN
3593     foo := ...;
3594     INSERT INTO dest (col) SELECT block.foo + bar FROM src;
3595 </programlisting>
3596     Here <literal>block.foo</> means the variable even if there is a column
3597     <literal>foo</> in <literal>src</>.  Function parameters, as well as
3598     special variables such as <literal>FOUND</>, can be qualified by the
3599     function's name, because they are implicitly declared in an outer block
3600     labeled with the function's name.
3601    </para>
3602
3603    <para>
3604     Sometimes it is impractical to fix all the ambiguous references in a
3605     large body of <application>PL/pgSQL</> code.  In such cases you can
3606     specify that <application>PL/pgSQL</> should resolve ambiguous references
3607     as the variable (which is compatible with <application>PL/pgSQL</>'s
3608     behavior before <productname>PostgreSQL</productname> 9.0), or as the
3609     table column (which is compatible with some other systems such as
3610     <productname>Oracle</productname>).
3611    </para>
3612
3613    <indexterm>
3614      <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
3615    </indexterm>
3616
3617    <para>
3618     To change this behavior on a system-wide basis, set the configuration
3619     parameter <literal>plpgsql.variable_conflict</> to one of
3620     <literal>error</>, <literal>use_variable</>, or
3621     <literal>use_column</> (where <literal>error</> is the factory default).
3622     This parameter affects subsequent compilations
3623     of statements in <application>PL/pgSQL</> functions, but not statements
3624     already compiled in the current session.  To set the parameter before
3625     <application>PL/pgSQL</> has been loaded, it is necessary to have added
3626     <quote><literal>plpgsql</></> to the <xref
3627     linkend="guc-custom-variable-classes"> list in
3628     <filename>postgresql.conf</filename>.  Because changing this setting
3629     can cause unexpected changes in the behavior of <application>PL/pgSQL</>
3630     functions, it can only be changed by a superuser.
3631    </para>
3632
3633    <para>
3634     You can also set the behavior on a function-by-function basis, by
3635     inserting one of these special commands at the start of the function
3636     text:
3637 <programlisting>
3638 #variable_conflict error
3639 #variable_conflict use_variable
3640 #variable_conflict use_column
3641 </programlisting>
3642     These commands affect only the function they are written in, and override
3643     the setting of <literal>plpgsql.variable_conflict</>.  An example is
3644 <programlisting>
3645 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
3646     #variable_conflict use_variable
3647     DECLARE
3648         curtime timestamp := now();
3649     BEGIN
3650         UPDATE users SET last_modified = curtime, comment = comment
3651           WHERE users.id = id;
3652     END;
3653 $$ LANGUAGE plpgsql;
3654 </programlisting>
3655     In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
3656     and <literal>id</> will refer to the function's variable and parameters
3657     whether or not <literal>users</> has columns of those names.  Notice
3658     that we had to qualify the reference to <literal>users.id</> in the
3659     <literal>WHERE</> clause to make it refer to the table column.
3660     But we did not have to qualify the reference to <literal>comment</>
3661     as a target in the <literal>UPDATE</> list, because syntactically
3662     that must be a column of <literal>users</>.  We could write the same
3663     function without depending on the <literal>variable_conflict</> setting
3664     in this way:
3665 <programlisting>
3666 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
3667     &lt;&lt;fn&gt;&gt;
3668     DECLARE
3669         curtime timestamp := now();
3670     BEGIN
3671         UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
3672           WHERE users.id = stamp_user.id;
3673     END;
3674 $$ LANGUAGE plpgsql;
3675 </programlisting>
3676    </para>
3677
3678    <para>
3679     Variable substitution does not happen in the command string given
3680     to <command>EXECUTE</> or one of its variants.  If you need to
3681     insert a varying value into such a command, do so as part of
3682     constructing the string value, or use <literal>USING</>, as illustrated in
3683     <xref linkend="plpgsql-statements-executing-dyn">.
3684    </para>
3685
3686    <para>
3687     Variable substitution currently works only in <command>SELECT</>,
3688     <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
3689     because the main SQL engine allows query parameters only in these
3690     commands.  To use a non-constant name or value in other statement
3691     types (generically called utility statements), you must construct
3692     the utility statement as a string and <command>EXECUTE</> it.
3693    </para>
3694
3695   </sect2>
3696
3697   <sect2 id="plpgsql-plan-caching">
3698    <title>Plan Caching</title>
3699
3700    <para>
3701     The <application>PL/pgSQL</> interpreter parses the function's source
3702     text and produces an internal binary instruction tree the first time the
3703     function is called (within each session).  The instruction tree
3704     fully translates the
3705     <application>PL/pgSQL</> statement structure, but individual
3706     <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
3707     used in the function are not translated immediately.
3708    </para>
3709
3710    <para>
3711     As each expression and <acronym>SQL</acronym> command is first
3712     executed in the function, the <application>PL/pgSQL</> interpreter
3713     creates a prepared execution plan (using the
3714     <acronym>SPI</acronym> manager's <function>SPI_prepare</function>
3715     and <function>SPI_saveplan</function>
3716     functions).<indexterm><primary>preparing a query</><secondary>in
3717     PL/pgSQL</></> Subsequent visits to that expression or command
3718     reuse the prepared plan.  Thus, a function with conditional code
3719     that contains many statements for which execution plans might be
3720     required will only prepare and save those plans that are really
3721     used during the lifetime of the database connection.  This can
3722     substantially reduce the total amount of time required to parse
3723     and generate execution plans for the statements in a
3724     <application>PL/pgSQL</> function. A disadvantage is that errors
3725     in a specific expression or command cannot be detected until that
3726     part of the function is reached in execution.  (Trivial syntax
3727     errors will be detected during the initial parsing pass, but
3728     anything deeper will not be detected until execution.)
3729    </para>
3730
3731    <para>
3732     A saved plan will be re-planned automatically if there is any schema
3733     change to any table used in the query, or if any user-defined function
3734     used in the query is redefined.  This makes the re-use of prepared plans
3735     transparent in most cases, but there are corner cases where a stale plan
3736     might be re-used.  An example is that dropping and re-creating a
3737     user-defined operator won't affect already-cached plans; they'll continue
3738     to call the original operator's underlying function, if that has not been
3739     changed.  When necessary, the cache can be flushed by starting a fresh
3740     database session.
3741    </para>
3742
3743    <para>
3744     Because <application>PL/pgSQL</application> saves execution plans
3745     in this way, SQL commands that appear directly in a
3746     <application>PL/pgSQL</application> function must refer to the
3747     same tables and columns on every execution; that is, you cannot use
3748     a parameter as the name of a table or column in an SQL command.  To get
3749     around this restriction, you can construct dynamic commands using
3750     the <application>PL/pgSQL</application> <command>EXECUTE</command>
3751     statement &mdash; at the price of constructing a new execution plan on
3752     every execution.
3753    </para>
3754
3755    <para>
3756     Another important point is that the prepared plans are parameterized
3757     to allow the values of <application>PL/pgSQL</application> variables
3758     to change from one use to the next, as discussed in detail above.
3759     Sometimes this means that a plan is less efficient than it would be
3760     if generated for a specific variable value.  As an example, consider
3761 <programlisting>
3762 SELECT * INTO myrec FROM dictionary WHERE word LIKE search_term;
3763 </programlisting>
3764     where <literal>search_term</> is a <application>PL/pgSQL</application>
3765     variable.  The cached plan for this query will never use an index on
3766     <structfield>word</>, since the planner cannot assume that the
3767     <literal>LIKE</> pattern will be left-anchored at run time.  To use
3768     an index the query must be planned with a specific constant
3769     <literal>LIKE</> pattern provided.  This is another situation where
3770     <command>EXECUTE</command> can be used to force a new plan to be
3771     generated for each execution.
3772    </para>
3773
3774     <para>
3775      The mutable nature of record variables presents another problem in this
3776      connection.  When fields of a record variable are used in
3777      expressions or statements, the data types of the fields must not
3778      change from one call of the function to the next, since each
3779      expression will be planned using the data type that is present
3780      when the expression is first reached.  <command>EXECUTE</command> can be
3781      used to get around this problem when necessary.
3782     </para>
3783
3784     <para>
3785      If the same function is used as a trigger for more than one table,
3786      <application>PL/pgSQL</application> prepares and caches plans
3787      independently for each such table &mdash; that is, there is a cache
3788      for each trigger function and table combination, not just for each
3789      function.  This alleviates some of the problems with varying
3790      data types; for instance, a trigger function will be able to work
3791      successfully with a column named <literal>key</> even if it happens
3792      to have different types in different tables.
3793     </para>
3794
3795     <para>
3796      Likewise, functions having polymorphic argument types have a separate
3797      plan cache for each combination of actual argument types they have been
3798      invoked for, so that data type differences do not cause unexpected
3799      failures.
3800     </para>
3801
3802    <para>
3803     Plan caching can sometimes have surprising effects on the interpretation
3804     of time-sensitive values.  For example there
3805     is a difference between what these two functions do:
3806
3807 <programlisting>
3808 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
3809     BEGIN
3810         INSERT INTO logtable VALUES (logtxt, 'now');
3811     END;
3812 $$ LANGUAGE plpgsql;
3813 </programlisting>
3814
3815      and:
3816
3817 <programlisting>
3818 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
3819     DECLARE
3820         curtime timestamp;
3821     BEGIN
3822         curtime := 'now';
3823         INSERT INTO logtable VALUES (logtxt, curtime);
3824     END;
3825 $$ LANGUAGE plpgsql;
3826 </programlisting>
3827     </para>
3828
3829     <para>
3830      In the case of <function>logfunc1</function>, the
3831      <productname>PostgreSQL</productname> main parser knows when
3832      preparing the plan for the <command>INSERT</command> that the
3833      string <literal>'now'</literal> should be interpreted as
3834      <type>timestamp</type>, because the target column of
3835      <classname>logtable</classname> is of that type. Thus,
3836      <literal>'now'</literal> will be converted to a constant when the
3837      <command>INSERT</command> is planned, and then used in all
3838      invocations of <function>logfunc1</function> during the lifetime
3839      of the session. Needless to say, this isn't what the programmer
3840      wanted.
3841     </para>
3842
3843     <para>
3844      In the case of <function>logfunc2</function>, the
3845      <productname>PostgreSQL</productname> main parser does not know
3846      what type <literal>'now'</literal> should become and therefore
3847      it returns a data value of type <type>text</type> containing the string
3848      <literal>now</literal>. During the ensuing assignment
3849      to the local variable <varname>curtime</varname>, the
3850      <application>PL/pgSQL</application> interpreter casts this
3851      string to the <type>timestamp</type> type by calling the
3852      <function>text_out</function> and <function>timestamp_in</function>
3853      functions for the conversion.  So, the computed time stamp is updated
3854      on each execution as the programmer expects.
3855     </para>
3856
3857   </sect2>
3858
3859   </sect1>
3860
3861  <sect1 id="plpgsql-development-tips">
3862   <title>Tips for Developing in <application>PL/pgSQL</application></title>
3863
3864    <para>
3865     One good way to develop in
3866     <application>PL/pgSQL</> is to use the text editor of your
3867     choice to create your functions, and in another window, use
3868     <application>psql</application> to load and test those functions.
3869     If you are doing it this way, it
3870     is a good idea to write the function using <command>CREATE OR
3871     REPLACE FUNCTION</>. That way you can just reload the file to update
3872     the function definition.  For example:
3873 <programlisting>
3874 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
3875           ....
3876 $$ LANGUAGE plpgsql;
3877 </programlisting>
3878    </para>
3879
3880    <para>
3881     While running <application>psql</application>, you can load or reload such
3882     a function definition file with:
3883 <programlisting>
3884 \i filename.sql
3885 </programlisting>
3886     and then immediately issue SQL commands to test the function.
3887    </para>
3888
3889    <para>
3890     Another good way to develop in <application>PL/pgSQL</> is with a
3891     GUI database access tool that facilitates development in a
3892     procedural language. One example of such a tool is
3893     <application>pgAdmin</>, although others exist. These tools often
3894     provide convenient features such as escaping single quotes and
3895     making it easier to recreate and debug functions.
3896    </para>
3897
3898   <sect2 id="plpgsql-quote-tips">
3899    <title>Handling of Quotation Marks</title>
3900
3901    <para>
3902     The code of a <application>PL/pgSQL</> function is specified in
3903     <command>CREATE FUNCTION</command> as a string literal.  If you
3904     write the string literal in the ordinary way with surrounding
3905     single quotes, then any single quotes inside the function body
3906     must be doubled; likewise any backslashes must be doubled (assuming
3907     escape string syntax is used).
3908     Doubling quotes is at best tedious, and in more complicated cases
3909     the code can become downright incomprehensible, because you can
3910     easily find yourself needing half a dozen or more adjacent quote marks.
3911     It's recommended that you instead write the function body as a
3912     <quote>dollar-quoted</> string literal (see <xref
3913     linkend="sql-syntax-dollar-quoting">).  In the dollar-quoting
3914     approach, you never double any quote marks, but instead take care to
3915     choose a different dollar-quoting delimiter for each level of
3916     nesting you need.  For example, you might write the <command>CREATE
3917     FUNCTION</command> command as:
3918 <programlisting>
3919 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
3920           ....
3921 $PROC$ LANGUAGE plpgsql;
3922 </programlisting>
3923     Within this, you might use quote marks for simple literal strings in
3924     SQL commands and <literal>$$</> to delimit fragments of SQL commands
3925     that you are assembling as strings.  If you need to quote text that
3926     includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
3927    </para>
3928
3929    <para>
3930     The following chart shows what you have to do when writing quote
3931     marks without dollar quoting.  It might be useful when translating
3932     pre-dollar quoting code into something more comprehensible.
3933   </para>
3934
3935   <variablelist>
3936    <varlistentry>
3937     <term>1 quotation mark</term>
3938     <listitem>
3939      <para>
3940       To begin and end the function body, for example:
3941 <programlisting>
3942 CREATE FUNCTION foo() RETURNS integer AS '
3943           ....
3944 ' LANGUAGE plpgsql;
3945 </programlisting>
3946       Anywhere within a single-quoted function body, quote marks
3947       <emphasis>must</> appear in pairs.
3948      </para>
3949     </listitem>
3950    </varlistentry>
3951
3952    <varlistentry>
3953     <term>2 quotation marks</term>
3954     <listitem>
3955      <para>
3956       For string literals inside the function body, for example:
3957 <programlisting>
3958 a_output := ''Blah'';
3959 SELECT * FROM users WHERE f_name=''foobar'';
3960 </programlisting>
3961       In the dollar-quoting approach, you'd just write:
3962 <programlisting>
3963 a_output := 'Blah';
3964 SELECT * FROM users WHERE f_name='foobar';
3965 </programlisting>
3966       which is exactly what the <application>PL/pgSQL</> parser would see
3967       in either case.
3968      </para>
3969     </listitem>
3970    </varlistentry>
3971
3972    <varlistentry>
3973     <term>4 quotation marks</term>
3974     <listitem>
3975      <para>
3976       When you need a single quotation mark in a string constant inside the
3977       function body, for example:
3978 <programlisting>
3979 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
3980 </programlisting>
3981       The value actually appended to <literal>a_output</literal> would be:
3982       <literal> AND name LIKE 'foobar' AND xyz</literal>.
3983      </para>
3984      <para>
3985       In the dollar-quoting approach, you'd write:
3986 <programlisting>
3987 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
3988 </programlisting>
3989       being careful that any dollar-quote delimiters around this are not
3990       just <literal>$$</>.
3991      </para>
3992     </listitem>
3993    </varlistentry>
3994
3995    <varlistentry>
3996     <term>6 quotation marks</term>
3997     <listitem>
3998      <para>
3999       When a single quotation mark in a string inside the function body is
4000       adjacent to the end of that string constant, for example:
4001 <programlisting>
4002 a_output := a_output || '' AND name LIKE ''''foobar''''''
4003 </programlisting>
4004       The value appended to <literal>a_output</literal> would then be:
4005       <literal> AND name LIKE 'foobar'</literal>.
4006      </para>
4007      <para>
4008       In the dollar-quoting approach, this becomes:
4009 <programlisting>
4010 a_output := a_output || $$ AND name LIKE 'foobar'$$
4011 </programlisting>
4012      </para>
4013     </listitem>
4014    </varlistentry>
4015
4016    <varlistentry>
4017     <term>10 quotation marks</term>
4018     <listitem>
4019      <para>
4020       When you want two single quotation marks in a string constant (which
4021       accounts for 8 quotation marks) and this is adjacent to the end of that
4022       string constant (2 more).  You will probably only need that if
4023       you are writing a function that generates other functions, as in
4024       <xref linkend="plpgsql-porting-ex2">.
4025       For example:
4026 <programlisting>
4027 a_output := a_output || '' if v_'' ||
4028     referrer_keys.kind || '' like ''''''''''
4029     || referrer_keys.key_string || ''''''''''
4030     then return ''''''  || referrer_keys.referrer_type
4031     || ''''''; end if;'';
4032 </programlisting>
4033       The value of <literal>a_output</literal> would then be:
4034 <programlisting>
4035 if v_... like ''...'' then return ''...''; end if;
4036 </programlisting>
4037      </para>
4038      <para>
4039       In the dollar-quoting approach, this becomes:
4040 <programlisting>
4041 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4042     || referrer_keys.key_string || $$'
4043     then return '$$  || referrer_keys.referrer_type
4044     || $$'; end if;$$;
4045 </programlisting>
4046       where we assume we only need to put single quote marks into
4047       <literal>a_output</literal>, because it will be re-quoted before use.
4048      </para>
4049     </listitem>
4050    </varlistentry>
4051   </variablelist>
4052
4053   </sect2>
4054  </sect1>
4055
4056   <!-- **** Porting from Oracle PL/SQL **** -->
4057
4058  <sect1 id="plpgsql-porting">
4059   <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4060
4061   <indexterm zone="plpgsql-porting">
4062    <primary>Oracle</primary>
4063    <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4064   </indexterm>
4065
4066   <indexterm zone="plpgsql-porting">
4067    <primary>PL/SQL (Oracle)</primary>
4068    <secondary>porting to PL/pgSQL</secondary>
4069   </indexterm>
4070
4071   <para>
4072    This section explains differences between
4073    <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4074    language and Oracle's <application>PL/SQL</application> language,
4075    to help developers who port applications from
4076    <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4077   </para>
4078
4079   <para>
4080    <application>PL/pgSQL</application> is similar to PL/SQL in many
4081    aspects. It is a block-structured, imperative language, and all
4082    variables have to be declared.  Assignments, loops, conditionals
4083    are similar.  The main differences you should keep in mind when
4084    porting from <application>PL/SQL</> to
4085    <application>PL/pgSQL</application> are:
4086
4087     <itemizedlist>
4088      <listitem>
4089       <para>
4090        If a name used in a SQL command could be either a column name of a
4091        table or a reference to a variable of the function,
4092        <application>PL/SQL</> treats it as a column name.  This corresponds
4093        to <application>PL/pgSQL</>'s
4094        <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4095        behavior, which is not the default,
4096        as explained in <xref linkend="plpgsql-var-subst">.
4097        It's often best to avoid such ambiguities in the first place,
4098        but if you have to port a large amount of code that depends on
4099        this behavior, setting <literal>variable_conflict</> may be the
4100        best solution.
4101       </para>
4102      </listitem>
4103
4104      <listitem>
4105       <para>
4106        In <productname>PostgreSQL</> the function body must be written as
4107        a string literal.  Therefore you need to use dollar quoting or escape
4108        single quotes in the function body. (See <xref
4109        linkend="plpgsql-quote-tips">.)
4110       </para>
4111      </listitem>
4112
4113      <listitem>
4114       <para>
4115        Instead of packages, use schemas to organize your functions
4116        into groups.
4117       </para>
4118      </listitem>
4119
4120      <listitem>
4121       <para>
4122        Since there are no packages, there are no package-level variables
4123        either. This is somewhat annoying.  You can keep per-session state
4124        in temporary tables instead.
4125       </para>
4126      </listitem>
4127
4128      <listitem>
4129       <para>
4130        Integer <command>FOR</> loops with <literal>REVERSE</> work
4131        differently: <application>PL/SQL</> counts down from the second
4132        number to the first, while <application>PL/pgSQL</> counts down
4133        from the first number to the second, requiring the loop bounds
4134        to be swapped when porting.  This incompatibility is unfortunate
4135        but is unlikely to be changed. (See <xref
4136        linkend="plpgsql-integer-for">.)
4137       </para>
4138      </listitem>
4139
4140      <listitem>
4141       <para>
4142        <command>FOR</> loops over queries (other than cursors) also work
4143        differently: the target variable(s) must have been declared,
4144        whereas <application>PL/SQL</> always declares them implicitly.
4145        An advantage of this is that the variable values are still accessible
4146        after the loop exits.
4147       </para>
4148      </listitem>
4149
4150      <listitem>
4151       <para>
4152        There are various notational differences for the use of cursor
4153        variables.
4154       </para>
4155      </listitem>
4156
4157     </itemizedlist>
4158    </para>
4159
4160   <sect2>
4161    <title>Porting Examples</title>
4162
4163    <para>
4164     <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4165     function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4166    </para>
4167
4168    <example id="pgsql-porting-ex1">
4169     <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4170
4171     <para>
4172      Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4173 <programlisting>
4174 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4175                                                   v_version varchar)
4176 RETURN varchar IS
4177 BEGIN
4178     IF v_version IS NULL THEN
4179         RETURN v_name;
4180     END IF;
4181     RETURN v_name || '/' || v_version;
4182 END;
4183 /
4184 show errors;
4185 </programlisting>
4186     </para>
4187
4188     <para>
4189      Let's go through this function and see the differences compared to
4190      <application>PL/pgSQL</>:
4191
4192      <itemizedlist>
4193       <listitem>
4194        <para>
4195         The <literal>RETURN</literal> key word in the function
4196         prototype (not the function body) becomes
4197         <literal>RETURNS</literal> in
4198         <productname>PostgreSQL</productname>.
4199         Also, <literal>IS</> becomes <literal>AS</>, and you need to
4200         add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4201         is not the only possible function language.
4202        </para>
4203       </listitem>
4204
4205       <listitem>
4206        <para>
4207         In <productname>PostgreSQL</>, the function body is considered
4208         to be a string literal, so you need to use quote marks or dollar
4209         quotes around it.  This substitutes for the terminating <literal>/</>
4210         in the Oracle approach.
4211        </para>
4212       </listitem>
4213
4214       <listitem>
4215        <para>
4216         The <literal>show errors</literal> command does not exist in
4217         <productname>PostgreSQL</>, and is not needed since errors are
4218         reported automatically.
4219        </para>
4220       </listitem>
4221      </itemizedlist>
4222     </para>
4223
4224     <para>
4225      This is how this function would look when ported to
4226      <productname>PostgreSQL</>:
4227
4228 <programlisting>
4229 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4230                                                   v_version varchar)
4231 RETURNS varchar AS $$
4232 BEGIN
4233     IF v_version IS NULL THEN
4234         RETURN v_name;
4235     END IF;
4236     RETURN v_name || '/' || v_version;
4237 END;
4238 $$ LANGUAGE plpgsql;
4239 </programlisting>
4240     </para>
4241    </example>
4242
4243    <para>
4244     <xref linkend="plpgsql-porting-ex2"> shows how to port a
4245     function that creates another function and how to handle the
4246     ensuing quoting problems.
4247    </para>
4248
4249    <example id="plpgsql-porting-ex2">
4250     <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4251
4252     <para>
4253      The following procedure grabs rows from a
4254      <command>SELECT</command> statement and builds a large function
4255      with the results in <literal>IF</literal> statements, for the
4256      sake of efficiency.
4257     </para>
4258
4259     <para>
4260      This is the Oracle version:
4261 <programlisting>
4262 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4263     CURSOR referrer_keys IS
4264         SELECT * FROM cs_referrer_keys
4265         ORDER BY try_order;
4266     func_cmd VARCHAR(4000);
4267 BEGIN
4268     func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4269                  v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4270
4271     FOR referrer_key IN referrer_keys LOOP
4272         func_cmd := func_cmd ||
4273           ' IF v_' || referrer_key.kind
4274           || ' LIKE ''' || referrer_key.key_string
4275           || ''' THEN RETURN ''' || referrer_key.referrer_type
4276           || '''; END IF;';
4277     END LOOP;
4278
4279     func_cmd := func_cmd || ' RETURN NULL; END;';
4280
4281     EXECUTE IMMEDIATE func_cmd;
4282 END;
4283 /
4284 show errors;
4285 </programlisting>
4286     </para>
4287
4288     <para>
4289      Here is how this function would end up in <productname>PostgreSQL</>:
4290 <programlisting>
4291 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4292 DECLARE
4293     referrer_keys CURSOR IS
4294         SELECT * FROM cs_referrer_keys
4295         ORDER BY try_order;
4296     func_body text;
4297     func_cmd text;
4298 BEGIN
4299     func_body := 'BEGIN';
4300
4301     FOR referrer_key IN referrer_keys LOOP
4302         func_body := func_body ||
4303           ' IF v_' || referrer_key.kind
4304           || ' LIKE ' || quote_literal(referrer_key.key_string)
4305           || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4306           || '; END IF;' ;
4307     END LOOP;
4308
4309     func_body := func_body || ' RETURN NULL; END;';
4310
4311     func_cmd :=
4312       'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4313                                                         v_domain varchar,
4314                                                         v_url varchar)
4315         RETURNS varchar AS '
4316       || quote_literal(func_body)
4317       || ' LANGUAGE plpgsql;' ;
4318
4319     EXECUTE func_cmd;
4320 END;
4321 $func$ LANGUAGE plpgsql;
4322 </programlisting>
4323      Notice how the body of the function is built separately and passed
4324      through <literal>quote_literal</> to double any quote marks in it.  This
4325      technique is needed because we cannot safely use dollar quoting for
4326      defining the new function: we do not know for sure what strings will
4327      be interpolated from the <structfield>referrer_key.key_string</> field.
4328      (We are assuming here that <structfield>referrer_key.kind</> can be
4329      trusted to always be <literal>host</>, <literal>domain</>, or
4330      <literal>url</>, but <structfield>referrer_key.key_string</> might be
4331      anything, in particular it might contain dollar signs.) This function
4332      is actually an improvement on the Oracle original, because it will
4333      not generate broken code when <structfield>referrer_key.key_string</> or
4334      <structfield>referrer_key.referrer_type</> contain quote marks.
4335     </para>
4336    </example>
4337
4338    <para>
4339     <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4340     with <literal>OUT</> parameters and string manipulation.
4341     <productname>PostgreSQL</> does not have a built-in
4342     <function>instr</function> function, but you can create one
4343     using a combination of other
4344     functions.<indexterm><primary>instr</></indexterm> In <xref
4345     linkend="plpgsql-porting-appendix"> there is a
4346     <application>PL/pgSQL</application> implementation of
4347     <function>instr</function> that you can use to make your porting
4348     easier.
4349    </para>
4350
4351    <example id="plpgsql-porting-ex3">
4352     <title>Porting a Procedure With String Manipulation and
4353     <literal>OUT</> Parameters from <application>PL/SQL</> to
4354     <application>PL/pgSQL</></title>
4355
4356     <para>
4357      The following <productname>Oracle</productname> PL/SQL procedure is used
4358      to parse a URL and return several elements (host, path, and query).
4359     </para>
4360
4361     <para>
4362      This is the Oracle version:
4363 <programlisting>
4364 CREATE OR REPLACE PROCEDURE cs_parse_url(
4365     v_url IN VARCHAR,
4366     v_host OUT VARCHAR,  -- This will be passed back
4367     v_path OUT VARCHAR,  -- This one too
4368     v_query OUT VARCHAR) -- And this one
4369 IS
4370     a_pos1 INTEGER;
4371     a_pos2 INTEGER;
4372 BEGIN
4373     v_host := NULL;
4374     v_path := NULL;
4375     v_query := NULL;
4376     a_pos1 := instr(v_url, '//');
4377
4378     IF a_pos1 = 0 THEN
4379         RETURN;
4380     END IF;
4381     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4382     IF a_pos2 = 0 THEN
4383         v_host := substr(v_url, a_pos1 + 2);
4384         v_path := '/';
4385         RETURN;
4386     END IF;
4387
4388     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4389     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4390
4391     IF a_pos1 = 0 THEN
4392         v_path := substr(v_url, a_pos2);
4393         RETURN;
4394     END IF;
4395
4396     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4397     v_query := substr(v_url, a_pos1 + 1);
4398 END;
4399 /
4400 show errors;
4401 </programlisting>
4402     </para>
4403
4404     <para>
4405      Here is a possible translation into <application>PL/pgSQL</>:
4406 <programlisting>
4407 CREATE OR REPLACE FUNCTION cs_parse_url(
4408     v_url IN VARCHAR,
4409     v_host OUT VARCHAR,  -- This will be passed back
4410     v_path OUT VARCHAR,  -- This one too
4411     v_query OUT VARCHAR) -- And this one
4412 AS $$
4413 DECLARE
4414     a_pos1 INTEGER;
4415     a_pos2 INTEGER;
4416 BEGIN
4417     v_host := NULL;
4418     v_path := NULL;
4419     v_query := NULL;
4420     a_pos1 := instr(v_url, '//');
4421
4422     IF a_pos1 = 0 THEN
4423         RETURN;
4424     END IF;
4425     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4426     IF a_pos2 = 0 THEN
4427         v_host := substr(v_url, a_pos1 + 2);
4428         v_path := '/';
4429         RETURN;
4430     END IF;
4431
4432     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4433     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4434
4435     IF a_pos1 = 0 THEN
4436         v_path := substr(v_url, a_pos2);
4437         RETURN;
4438     END IF;
4439
4440     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4441     v_query := substr(v_url, a_pos1 + 1);
4442 END;
4443 $$ LANGUAGE plpgsql;
4444 </programlisting>
4445
4446      This function could be used like this:
4447 <programlisting>
4448 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4449 </programlisting>
4450     </para>
4451    </example>
4452
4453    <para>
4454     <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4455     that uses numerous features that are specific to Oracle.
4456    </para>
4457
4458    <example id="plpgsql-porting-ex4">
4459     <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4460
4461     <para>
4462      The Oracle version:
4463
4464 <programlisting>
4465 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4466     a_running_job_count INTEGER;
4467     PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4468 BEGIN
4469     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4470
4471     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4472
4473     IF a_running_job_count &gt; 0 THEN
4474         COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4475         raise_application_error(-20000,
4476                  'Unable to create a new job: a job is currently running.');
4477     END IF;
4478
4479     DELETE FROM cs_active_job;
4480     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4481
4482     BEGIN
4483         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4484     EXCEPTION
4485         WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4486     END;
4487     COMMIT;
4488 END;
4489 /
4490 show errors
4491 </programlisting>
4492    </para>
4493
4494    <para>
4495     Procedures like this can easily be converted into <productname>PostgreSQL</>
4496     functions returning <type>void</type>. This procedure in
4497     particular is interesting because it can teach us some things:
4498
4499     <calloutlist>
4500      <callout arearefs="co.plpgsql-porting-pragma">
4501       <para>
4502        There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
4503       </para>
4504      </callout>
4505
4506      <callout arearefs="co.plpgsql-porting-locktable">
4507       <para>
4508        If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
4509        the lock will not be released until the calling transaction is
4510        finished.
4511       </para>
4512      </callout>
4513
4514      <callout arearefs="co.plpgsql-porting-commit">
4515       <para>
4516        You cannot issue <command>COMMIT</> in a
4517        <application>PL/pgSQL</application> function.  The function is
4518        running within some outer transaction and so <command>COMMIT</>
4519        would imply terminating the function's execution.  However, in
4520        this particular case it is not necessary anyway, because the lock
4521        obtained by the <command>LOCK TABLE</command> will be released when
4522        we raise an error.
4523       </para>
4524      </callout>
4525     </calloutlist>
4526    </para>
4527
4528    <para>
4529     This is how we could port this procedure to <application>PL/pgSQL</>:
4530
4531 <programlisting>
4532 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
4533 DECLARE
4534     a_running_job_count integer;
4535 BEGIN
4536     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
4537
4538     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4539
4540     IF a_running_job_count &gt; 0 THEN
4541         RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
4542     END IF;
4543
4544     DELETE FROM cs_active_job;
4545     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4546
4547     BEGIN
4548         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
4549     EXCEPTION
4550         WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
4551             -- don't worry if it already exists
4552     END;
4553 END;
4554 $$ LANGUAGE plpgsql;
4555 </programlisting>
4556
4557     <calloutlist>
4558      <callout arearefs="co.plpgsql-porting-raise">
4559       <para>
4560        The syntax of <literal>RAISE</> is considerably different from
4561        Oracle's statement, although the basic case <literal>RAISE</>
4562        <replaceable class="parameter">exception_name</replaceable> works
4563        similarly.
4564       </para>
4565      </callout>
4566      <callout arearefs="co.plpgsql-porting-exception">
4567       <para>
4568        The exception names supported by <application>PL/pgSQL</> are
4569        different from Oracle's.  The set of built-in exception names
4570        is much larger (see <xref linkend="errcodes-appendix">).  There
4571        is not currently a way to declare user-defined exception names,
4572        although you can throw user-chosen SQLSTATE values instead.
4573       </para>
4574      </callout>
4575     </calloutlist>
4576
4577     The main functional difference between this procedure and the
4578     Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
4579     table will be held until the calling transaction completes.  Also, if
4580     the caller later aborts (for example due to an error), the effects of
4581     this procedure will be rolled back.
4582    </para>
4583    </example>
4584   </sect2>
4585
4586   <sect2 id="plpgsql-porting-other">
4587    <title>Other Things to Watch For</title>
4588
4589    <para>
4590     This section explains a few other things to watch for when porting
4591     Oracle <application>PL/SQL</> functions to
4592     <productname>PostgreSQL</productname>.
4593    </para>
4594
4595    <sect3 id="plpgsql-porting-exceptions">
4596     <title>Implicit Rollback after Exceptions</title>
4597
4598     <para>
4599      In <application>PL/pgSQL</>, when an exception is caught by an
4600      <literal>EXCEPTION</> clause, all database changes since the block's
4601      <literal>BEGIN</> are automatically rolled back.  That is, the behavior
4602      is equivalent to what you'd get in Oracle with:
4603
4604 <programlisting>
4605 BEGIN
4606     SAVEPOINT s1;
4607     ... code here ...
4608 EXCEPTION
4609     WHEN ... THEN
4610         ROLLBACK TO s1;
4611         ... code here ...
4612     WHEN ... THEN
4613         ROLLBACK TO s1;
4614         ... code here ...
4615 END;
4616 </programlisting>
4617
4618      If you are translating an Oracle procedure that uses
4619      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
4620      your task is easy: just omit the <command>SAVEPOINT</> and
4621      <command>ROLLBACK TO</>.  If you have a procedure that uses
4622      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
4623      then some actual thought will be required.
4624     </para>
4625    </sect3>
4626
4627    <sect3>
4628     <title><command>EXECUTE</command></title>
4629
4630     <para>
4631      The <application>PL/pgSQL</> version of
4632      <command>EXECUTE</command> works similarly to the
4633      <application>PL/SQL</> version, but you have to remember to use
4634      <function>quote_literal</function> and
4635      <function>quote_ident</function> as described in <xref
4636      linkend="plpgsql-statements-executing-dyn">.  Constructs of the
4637      type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
4638      reliably unless you use these functions.
4639     </para>
4640    </sect3>
4641
4642    <sect3 id="plpgsql-porting-optimization">
4643     <title>Optimizing <application>PL/pgSQL</application> Functions</title>
4644
4645     <para>
4646      <productname>PostgreSQL</> gives you two function creation
4647      modifiers to optimize execution: <quote>volatility</> (whether
4648      the function always returns the same result when given the same
4649      arguments) and <quote>strictness</quote> (whether the function
4650      returns null if any argument is null).  Consult the <xref
4651      linkend="sql-createfunction">
4652      reference page for details.
4653     </para>
4654
4655     <para>
4656      When making use of these optimization attributes, your
4657      <command>CREATE FUNCTION</command> statement might look something
4658      like this:
4659
4660 <programlisting>
4661 CREATE FUNCTION foo(...) RETURNS integer AS $$
4662 ...
4663 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4664 </programlisting>
4665     </para>
4666    </sect3>
4667   </sect2>
4668
4669   <sect2 id="plpgsql-porting-appendix">
4670    <title>Appendix</title>
4671
4672    <para>
4673     This section contains the code for a set of Oracle-compatible
4674     <function>instr</function> functions that you can use to simplify
4675     your porting efforts.
4676    </para>
4677
4678 <programlisting>
4679 --
4680 -- instr functions that mimic Oracle's counterpart
4681 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
4682 --
4683 -- Searches string1 beginning at the nth character for the mth occurrence
4684 -- of string2.  If n is negative, search backwards.  If m is not passed,
4685 -- assume 1 (search starts at first character).
4686 --
4687
4688 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
4689 DECLARE
4690     pos integer;
4691 BEGIN
4692     pos:= instr($1, $2, 1);
4693     RETURN pos;
4694 END;
4695 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4696
4697
4698 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
4699 RETURNS integer AS $$
4700 DECLARE
4701     pos integer NOT NULL DEFAULT 0;
4702     temp_str varchar;
4703     beg integer;
4704     length integer;
4705     ss_length integer;
4706 BEGIN
4707     IF beg_index &gt; 0 THEN
4708         temp_str := substring(string FROM beg_index);
4709         pos := position(string_to_search IN temp_str);
4710
4711         IF pos = 0 THEN
4712             RETURN 0;
4713         ELSE
4714             RETURN pos + beg_index - 1;
4715         END IF;
4716     ELSE
4717         ss_length := char_length(string_to_search);
4718         length := char_length(string);
4719         beg := length + beg_index - ss_length + 2;
4720
4721         WHILE beg &gt; 0 LOOP
4722             temp_str := substring(string FROM beg FOR ss_length);
4723             pos := position(string_to_search IN temp_str);
4724
4725             IF pos &gt; 0 THEN
4726                 RETURN beg;
4727             END IF;
4728
4729             beg := beg - 1;
4730         END LOOP;
4731
4732         RETURN 0;
4733     END IF;
4734 END;
4735 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4736
4737
4738 CREATE FUNCTION instr(string varchar, string_to_search varchar,
4739                       beg_index integer, occur_index integer)
4740 RETURNS integer AS $$
4741 DECLARE
4742     pos integer NOT NULL DEFAULT 0;
4743     occur_number integer NOT NULL DEFAULT 0;
4744     temp_str varchar;
4745     beg integer;
4746     i integer;
4747     length integer;
4748     ss_length integer;
4749 BEGIN
4750     IF beg_index &gt; 0 THEN
4751         beg := beg_index;
4752         temp_str := substring(string FROM beg_index);
4753
4754         FOR i IN 1..occur_index LOOP
4755             pos := position(string_to_search IN temp_str);
4756
4757             IF i = 1 THEN
4758                 beg := beg + pos - 1;
4759             ELSE
4760                 beg := beg + pos;
4761             END IF;
4762
4763             temp_str := substring(string FROM beg + 1);
4764         END LOOP;
4765
4766         IF pos = 0 THEN
4767             RETURN 0;
4768         ELSE
4769             RETURN beg;
4770         END IF;
4771     ELSE
4772         ss_length := char_length(string_to_search);
4773         length := char_length(string);
4774         beg := length + beg_index - ss_length + 2;
4775
4776         WHILE beg &gt; 0 LOOP
4777             temp_str := substring(string FROM beg FOR ss_length);
4778             pos := position(string_to_search IN temp_str);
4779
4780             IF pos &gt; 0 THEN
4781                 occur_number := occur_number + 1;
4782
4783                 IF occur_number = occur_index THEN
4784                     RETURN beg;
4785                 END IF;
4786             END IF;
4787
4788             beg := beg - 1;
4789         END LOOP;
4790
4791         RETURN 0;
4792     END IF;
4793 END;
4794 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4795 </programlisting>
4796   </sect2>
4797
4798  </sect1>
4799
4800 </chapter>