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