~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to doc/src/sgml/plpgsql.sgml

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!--
 
2
$PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.57.4.1 2005-01-22 23:05:47 momjian Exp $
 
3
-->
 
4
 
 
5
<chapter id="plpgsql"> 
 
6
  <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
 
7
 
 
8
 <indexterm zone="plpgsql">
 
9
  <primary>PL/pgSQL</primary>
 
10
 </indexterm>
 
11
 
 
12
 <para>
 
13
  <application>PL/pgSQL</application> is a loadable procedural
 
14
  language for the <productname>PostgreSQL</productname> database
 
15
  system.  The design goals of <application>PL/pgSQL</> were to create
 
16
  a loadable procedural language that
 
17
 
 
18
    <itemizedlist>
 
19
     <listitem>
 
20
      <para>
 
21
       can be used to create functions and trigger procedures,
 
22
      </para>
 
23
     </listitem>
 
24
     <listitem>
 
25
      <para>
 
26
       adds control structures to the <acronym>SQL</acronym> language,
 
27
      </para>
 
28
     </listitem>
 
29
     <listitem>
 
30
      <para>
 
31
       can perform complex computations,
 
32
      </para>
 
33
     </listitem>
 
34
     <listitem>
 
35
      <para>
 
36
       inherits all user-defined types, functions, and operators,
 
37
      </para>
 
38
     </listitem>
 
39
     <listitem>
 
40
      <para>
 
41
       can be defined to be trusted by the server,
 
42
      </para>
 
43
     </listitem>
 
44
     <listitem>
 
45
      <para>
 
46
       is easy to use.
 
47
      </para>
 
48
     </listitem>
 
49
    </itemizedlist>
 
50
   </para>
 
51
 
 
52
   <para>
 
53
    Except for input/output conversion and calculation functions
 
54
    for user-defined types, anything that can be defined in C language
 
55
    functions can also be done with <application>PL/pgSQL</application>.
 
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
  <sect1 id="plpgsql-overview">
 
62
   <title>Overview</title>
 
63
 
 
64
   <para>
 
65
    The <application>PL/pgSQL</> call handler parses the function's source text and
 
66
    produces an internal binary instruction tree the first time the
 
67
    function is called (within each session).  The instruction tree
 
68
    fully translates the 
 
69
    <application>PL/pgSQL</> statement structure, but individual
 
70
    <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
 
71
    used in the function are not translated immediately.
 
72
   </para>
 
73
 
 
74
   <para>
 
75
    As each expression and <acronym>SQL</acronym> command is first
 
76
    used in the function, the <application>PL/pgSQL</> interpreter
 
77
    creates a prepared execution plan (using the
 
78
    <acronym>SPI</acronym> manager's <function>SPI_prepare</function>
 
79
    and <function>SPI_saveplan</function>
 
80
    functions).<indexterm><primary>preparing a query</><secondary>in
 
81
    PL/pgSQL</></> Subsequent visits to that expression or command
 
82
    reuse the prepared plan.  Thus, a function with conditional code
 
83
    that contains many statements for which execution plans might be
 
84
    required will only prepare and save those plans that are really
 
85
    used during the lifetime of the database connection.  This can
 
86
    substantially reduce the total amount of time required to parse,
 
87
    and generate execution plans for the statements in a
 
88
    <application>PL/pgSQL</> function. A disadvantage is that errors
 
89
    in a specific expression or command may not be detected until that
 
90
    part of the function is reached in execution.
 
91
   </para>
 
92
 
 
93
   <para>
 
94
    Once <application>PL/pgSQL</> has made an execution plan for a particular
 
95
    command in a function, it will reuse that plan for the life of the
 
96
    database connection.  This is usually a win for performance, but it
 
97
    can cause some problems if you dynamically
 
98
    alter your database schema. For example:
 
99
 
 
100
<programlisting>
 
101
CREATE FUNCTION populate() RETURNS integer AS $$
 
102
DECLARE
 
103
    -- declarations
 
104
BEGIN
 
105
    PERFORM my_function();
 
106
END;
 
107
$$ LANGUAGE plpgsql;
 
108
</programlisting>
 
109
 
 
110
    If you execute the above function, it will reference the OID for
 
111
    <function>my_function()</function> in the execution plan produced for
 
112
    the <command>PERFORM</command> statement. Later, if you
 
113
    drop and recreate <function>my_function()</function>, then
 
114
    <function>populate()</function> will not be able to find
 
115
    <function>my_function()</function> anymore. You would then have to
 
116
    recreate <function>populate()</function>, or at least start a new
 
117
    database session so that it will be compiled afresh. Another way
 
118
    to avoid this problem is to use <command>CREATE OR REPLACE
 
119
    FUNCTION</command> when updating the definition of
 
120
    <function>my_function</function> (when a function is
 
121
    <quote>replaced</quote>, its OID is not changed).
 
122
   </para>
 
123
 
 
124
   <para>
 
125
    Because <application>PL/pgSQL</application> saves execution plans
 
126
        in this way, SQL commands that appear directly in a
 
127
        <application>PL/pgSQL</application> function must refer to the
 
128
        same tables and columns on every execution; that is, you cannot use
 
129
        a parameter as the name of a table or column in an SQL command.  To get
 
130
        around this restriction, you can construct dynamic commands using
 
131
        the <application>PL/pgSQL</application> <command>EXECUTE</command>
 
132
        statement &mdash; at the price of constructing a new execution plan on
 
133
        every execution.
 
134
   </para>
 
135
 
 
136
   <note>
 
137
        <para>
 
138
         The <application>PL/pgSQL</application>
 
139
         <command>EXECUTE</command> statement is not related to the
 
140
         <xref linkend="sql-execute" endterm="sql-execute-title"> SQL
 
141
         statement supported by the
 
142
         <productname>PostgreSQL</productname> server. The server's
 
143
         <command>EXECUTE</command> statement cannot be used within
 
144
         <application>PL/pgSQL</> functions (and is not needed).
 
145
        </para>
 
146
   </note>
 
147
 
 
148
  <sect2 id="plpgsql-advantages">
 
149
   <title>Advantages of Using <application>PL/pgSQL</application></title>
 
150
 
 
151
    <para>
 
152
     <acronym>SQL</acronym> is the language <productname>PostgreSQL</>
 
153
     and most other relational databases use as query language. It's
 
154
     portable and easy to learn. But every <acronym>SQL</acronym>
 
155
     statement must be executed individually by the database server.
 
156
    </para>
 
157
 
 
158
    <para>
 
159
     That means that your client application must send each query to
 
160
     the database server, wait for it to be processed, receive the
 
161
     results, do some computation, then send other queries to the
 
162
     server. All this incurs interprocess communication and may also
 
163
     incur network overhead if your client is on a different machine
 
164
     than the database server.
 
165
    </para>
 
166
 
 
167
    <para>
 
168
     With <application>PL/pgSQL</application> you can group a block of computation and a
 
169
     series of queries <emphasis>inside</emphasis> the
 
170
     database server, thus having the power of a procedural
 
171
     language and the ease of use of SQL, but saving lots of
 
172
     time because you don't have the whole client/server
 
173
     communication overhead. This can make for a
 
174
     considerable performance increase.
 
175
    </para>
 
176
 
 
177
    <para>
 
178
     Also, with <application>PL/pgSQL</application> you can use all
 
179
     the data types, operators and functions of SQL.
 
180
    </para>
 
181
  </sect2>
 
182
 
 
183
  <sect2 id="plpgsql-args-results">
 
184
   <title>Supported Argument and Result Data Types</title>
 
185
 
 
186
    <para>
 
187
     Functions written in <application>PL/pgSQL</application> can accept
 
188
     as arguments any scalar or array data type supported by the server,
 
189
     and they can return a result of any of these types.  They can also
 
190
     accept or return any composite type (row type) specified by name.
 
191
     It is also possible to declare a <application>PL/pgSQL</application>
 
192
     function as returning <type>record</>, which means that the result
 
193
     is a row type whose columns are determined by specification in the
 
194
     calling query, as discussed in <xref linkend="queries-tablefunctions">.
 
195
    </para>
 
196
 
 
197
    <para>
 
198
     <application>PL/pgSQL</> functions may also be declared to accept
 
199
     and return the polymorphic types
 
200
     <type>anyelement</type> and <type>anyarray</type>.  The actual
 
201
     data types handled by a polymorphic function can vary from call to
 
202
     call, as discussed in <xref linkend="extend-types-polymorphic">.
 
203
     An example is shown in <xref linkend="plpgsql-declaration-aliases">.
 
204
    </para>
 
205
 
 
206
    <para>
 
207
     <application>PL/pgSQL</> functions can also be declared to return
 
208
     a <quote>set</>, or table, of any data type they can return a single
 
209
     instance of.  Such a function generates its output by executing
 
210
     <literal>RETURN NEXT</> for each desired element of the result set.
 
211
    </para>
 
212
 
 
213
    <para>
 
214
     Finally, a <application>PL/pgSQL</> function may be declared to return
 
215
     <type>void</> if it has no useful return value.
 
216
    </para>
 
217
 
 
218
    <para>
 
219
     <application>PL/pgSQL</> does not currently have full support for
 
220
     domain types: it treats a domain the same as the underlying scalar
 
221
     type.  This means that constraints associated with the domain will
 
222
     not be enforced.  This is not an issue for function arguments, but
 
223
     it is a hazard if you declare a <application>PL/pgSQL</> function
 
224
     as returning a domain type.
 
225
    </para>
 
226
  </sect2>
 
227
 </sect1>
 
228
 
 
229
 <sect1 id="plpgsql-development-tips">
 
230
  <title>Tips for Developing in <application>PL/pgSQL</application></title>
 
231
 
 
232
   <para>
 
233
    One good way to develop in
 
234
    <application>PL/pgSQL</> is to use the text editor of your
 
235
    choice to create your functions, and in another window, use
 
236
    <application>psql</application> to load and test those functions.
 
237
    If you are doing it this way, it
 
238
    is a good idea to write the function using <command>CREATE OR
 
239
    REPLACE FUNCTION</>. That way you can just reload the file to update
 
240
    the function definition.  For example:
 
241
<programlisting>
 
242
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
 
243
          ....
 
244
$$ LANGUAGE plpgsql;
 
245
</programlisting>
 
246
   </para>
 
247
 
 
248
   <para>
 
249
    While running <application>psql</application>, you can load or reload such
 
250
    a function definition file with
 
251
<programlisting>
 
252
\i filename.sql
 
253
</programlisting>
 
254
    and then immediately issue SQL commands to test the function.
 
255
   </para>
 
256
 
 
257
   <para>
 
258
    Another good way to develop in <application>PL/pgSQL</> is with a
 
259
    GUI database access tool that facilitates development in a
 
260
    procedural language. One example of such as a tool is
 
261
    <application>PgAccess</>, although others exist. These tools often
 
262
    provide convenient features such as escaping single quotes and
 
263
    making it easier to recreate and debug functions.
 
264
   </para>
 
265
 
 
266
  <sect2 id="plpgsql-quote-tips">
 
267
   <title>Handling of Quotation Marks</title>
 
268
 
 
269
   <para>
 
270
    The code of a <application>PL/pgSQL</> function is specified in
 
271
    <command>CREATE FUNCTION</command> as a string literal.  If you
 
272
    write the string literal in the ordinary way with surrounding
 
273
    single quotes, then any single quotes inside the function body
 
274
    must be doubled; likewise any backslashes must be doubled.
 
275
    Doubling quotes is at best tedious, and in more complicated cases
 
276
    the code can become downright incomprehensible, because you can
 
277
    easily find yourself needing half a dozen or more adjacent quote marks.
 
278
    It's recommended that you instead write the function body as a
 
279
    <quote>dollar-quoted</> string literal (see <xref
 
280
    linkend="sql-syntax-dollar-quoting">).  In the dollar-quoting
 
281
    approach, you never double any quote marks, but instead take care to
 
282
    choose a different dollar-quoting delimiter for each level of
 
283
    nesting you need.  For example, you might write the <command>CREATE
 
284
    FUNCTION</command> command as
 
285
<programlisting>
 
286
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
 
287
          ....
 
288
$PROC$ LANGUAGE plpgsql;
 
289
</programlisting>
 
290
    Within this, you might use quote marks for simple literal strings in
 
291
    SQL commands and <literal>$$</> to delimit fragments of SQL commands
 
292
    that you are assembling as strings.  If you need to quote text that
 
293
    includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
 
294
   </para>
 
295
 
 
296
   <para>
 
297
    The following chart shows what you have to do when writing quote
 
298
    marks without dollar quoting.  It may be useful when translating
 
299
    pre-dollar quoting code into something more comprehensible.
 
300
  </para>
 
301
 
 
302
  <variablelist>
 
303
   <varlistentry>
 
304
    <term>1 quotation mark</term>
 
305
    <listitem>
 
306
     <para>
 
307
      To begin and end the function body, for example:
 
308
<programlisting>
 
309
CREATE FUNCTION foo() RETURNS integer AS '
 
310
          ....
 
311
' LANGUAGE plpgsql;
 
312
</programlisting>
 
313
      Anywhere within a single-quoted function body, quote marks
 
314
      <emphasis>must</> appear in pairs.
 
315
     </para>
 
316
    </listitem>
 
317
   </varlistentry>
 
318
 
 
319
   <varlistentry>
 
320
    <term>2 quotation marks</term>
 
321
    <listitem>
 
322
     <para>
 
323
      For string literals inside the function body, for example:
 
324
<programlisting>
 
325
a_output := ''Blah'';
 
326
SELECT * FROM users WHERE f_name=''foobar'';
 
327
</programlisting>
 
328
      In the dollar-quoting approach, you'd just write
 
329
<programlisting>
 
330
a_output := 'Blah';
 
331
SELECT * FROM users WHERE f_name='foobar';
 
332
</programlisting>
 
333
      which is exactly what the <application>PL/pgSQL</> parser would see
 
334
      in either case.
 
335
     </para>
 
336
    </listitem>
 
337
   </varlistentry>
 
338
 
 
339
   <varlistentry>
 
340
    <term>4 quotation marks</term>
 
341
    <listitem>
 
342
     <para>
 
343
      When you need a single quotation mark in a string constant inside the
 
344
      function body, for example:
 
345
<programlisting>
 
346
a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
 
347
</programlisting>
 
348
      The value actually appended to <literal>a_output</literal> would be:
 
349
      <literal> AND name LIKE 'foobar' AND xyz</literal>.
 
350
     </para>
 
351
     <para>
 
352
      In the dollar-quoting approach, you'd write
 
353
<programlisting>
 
354
a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
 
355
</programlisting>
 
356
      being careful that any dollar-quote delimiters around this are not
 
357
      just <literal>$$</>.
 
358
     </para>
 
359
    </listitem>
 
360
   </varlistentry>
 
361
 
 
362
   <varlistentry>
 
363
    <term>6 quotation marks</term>
 
364
    <listitem>
 
365
     <para>
 
366
      When a single quotation mark in a string inside the function body is
 
367
      adjacent to the end of that string constant, for example:
 
368
<programlisting>
 
369
a_output := a_output || '' AND name LIKE ''''foobar''''''
 
370
</programlisting>
 
371
      The value appended to <literal>a_output</literal> would then be:
 
372
      <literal> AND name LIKE 'foobar'</literal>.
 
373
     </para>
 
374
     <para>
 
375
      In the dollar-quoting approach, this becomes
 
376
<programlisting>
 
377
a_output := a_output || $$ AND name LIKE 'foobar'$$
 
378
</programlisting>
 
379
     </para>
 
380
    </listitem>
 
381
   </varlistentry>
 
382
 
 
383
   <varlistentry>
 
384
    <term>10 quotation marks</term>
 
385
    <listitem>
 
386
     <para>
 
387
      When you want two single quotation marks in a string constant (which
 
388
      accounts for 8 quotation marks) and this is adjacent to the end of that
 
389
      string constant (2 more).  You will probably only need that if
 
390
      you are writing a function that generates other functions, as in
 
391
      <xref linkend="plpgsql-porting-ex2">.
 
392
      For example:
 
393
<programlisting>
 
394
a_output := a_output || '' if v_'' || 
 
395
    referrer_keys.kind || '' like '''''''''' 
 
396
    || referrer_keys.key_string || '''''''''' 
 
397
    then return ''''''  || referrer_keys.referrer_type 
 
398
    || ''''''; end if;''; 
 
399
</programlisting>
 
400
      The value of <literal>a_output</literal> would then be:
 
401
<programlisting>
 
402
if v_... like ''...'' then return ''...''; end if;
 
403
</programlisting>
 
404
     </para>
 
405
     <para>
 
406
      In the dollar-quoting approach, this becomes
 
407
<programlisting>
 
408
a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
 
409
    || referrer_keys.key_string || $$'
 
410
    then return '$$  || referrer_keys.referrer_type 
 
411
    || $$'; end if;$$; 
 
412
</programlisting>
 
413
      where we assume we only need to put single quote marks into
 
414
      <literal>a_output</literal>, because it will be re-quoted before use.
 
415
     </para>
 
416
    </listitem>
 
417
   </varlistentry>
 
418
  </variablelist>
 
419
 
 
420
   <para>
 
421
    A variant approach is to escape quotation marks in the function body
 
422
    with a backslash rather than by doubling them.  With this method
 
423
    you'll find yourself writing things like <literal>\'\'</> instead
 
424
    of <literal>''''</>.  Some find this easier to keep track of, some
 
425
    do not.
 
426
   </para>
 
427
  </sect2>
 
428
 </sect1>
 
429
 
 
430
 <sect1 id="plpgsql-structure">
 
431
  <title>Structure of <application>PL/pgSQL</application></title>
 
432
 
 
433
  <para>
 
434
   <application>PL/pgSQL</application> is a block-structured language.
 
435
   The complete text of a function definition must be a
 
436
   <firstterm>block</>. A block is defined as:
 
437
 
 
438
<synopsis>
 
439
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
 
440
<optional> DECLARE
 
441
    <replaceable>declarations</replaceable> </optional>
 
442
BEGIN
 
443
    <replaceable>statements</replaceable>
 
444
END;
 
445
</synopsis>
 
446
    </para>
 
447
 
 
448
    <para>
 
449
     Each declaration and each statement within a block is terminated
 
450
     by a semicolon.  A block that appears within another block must
 
451
     have a semicolon after <literal>END</literal>, as shown above;
 
452
     however the final <literal>END</literal> that
 
453
     concludes a function body does not require a semicolon.
 
454
    </para>
 
455
 
 
456
    <para>
 
457
     All key words and identifiers can be written in mixed upper and
 
458
     lower case.  Identifiers are implicitly converted to lowercase
 
459
     unless double-quoted.
 
460
    </para>
 
461
 
 
462
    <para>
 
463
     There are two types of comments in <application>PL/pgSQL</>. A double
 
464
     dash (<literal>--</literal>) starts a comment that extends to the end of
 
465
     the line. A <literal>/*</literal> starts a block comment that extends to
 
466
     the next occurrence of <literal>*/</literal>.  Block comments cannot be
 
467
     nested, but double dash comments can be enclosed into a block comment and
 
468
     a double dash can hide the block comment delimiters <literal>/*</literal>
 
469
     and <literal>*/</literal>.
 
470
    </para>
 
471
 
 
472
    <para>
 
473
     Any statement in the statement section of a block
 
474
     can be a <firstterm>subblock</>.  Subblocks can be used for
 
475
     logical grouping or to localize variables to a small group
 
476
     of statements.
 
477
    </para>
 
478
 
 
479
    <para>
 
480
     The variables declared in the declarations section preceding a
 
481
     block are initialized to their default values every time the
 
482
     block is entered, not only once per function call. For example:
 
483
<programlisting>
 
484
CREATE FUNCTION somefunc() RETURNS integer AS $$
 
485
DECLARE
 
486
    quantity integer := 30;
 
487
BEGIN
 
488
    RAISE NOTICE 'Quantity here is %', quantity;  -- Quantity here is 30
 
489
    quantity := 50;
 
490
    --
 
491
    -- Create a subblock
 
492
    --
 
493
    DECLARE
 
494
        quantity integer := 80;
 
495
    BEGIN
 
496
        RAISE NOTICE 'Quantity here is %', quantity;  -- Quantity here is 80
 
497
    END;
 
498
 
 
499
    RAISE NOTICE 'Quantity here is %', quantity;  -- Quantity here is 50
 
500
 
 
501
    RETURN quantity;
 
502
END;
 
503
$$ LANGUAGE plpgsql;
 
504
</programlisting>
 
505
    </para>
 
506
 
 
507
    <para>
 
508
     It is important not to confuse the use of
 
509
     <command>BEGIN</>/<command>END</> for grouping statements in
 
510
     <application>PL/pgSQL</> with the database commands for transaction
 
511
     control.  <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</>
 
512
     are only for grouping; they do not start or end a transaction.
 
513
     Functions and trigger procedures are always executed within a transaction
 
514
     established by an outer query &mdash; they cannot start or commit that
 
515
     transaction, since there would be no context for them to execute in.
 
516
     However, a block containing an <literal>EXCEPTION</> clause effectively
 
517
     forms a subtransaction that can be rolled back without affecting the
 
518
     outer transaction.  For more about that see <xref
 
519
     linkend="plpgsql-error-trapping">.
 
520
    </para>
 
521
  </sect1>
 
522
 
 
523
  <sect1 id="plpgsql-declarations">
 
524
    <title>Declarations</title>
 
525
 
 
526
    <para>
 
527
     All variables used in a block must be declared in the
 
528
     declarations section of the block. 
 
529
     (The only exception is that the loop variable of a <literal>FOR</> loop
 
530
     iterating over a range of integer values is automatically declared as an
 
531
     integer variable.)
 
532
    </para>
 
533
 
 
534
    <para>
 
535
     <application>PL/pgSQL</> variables can have any SQL data type, such as
 
536
     <type>integer</type>, <type>varchar</type>, and
 
537
     <type>char</type>.
 
538
    </para>
 
539
 
 
540
    <para>
 
541
     Here are some examples of variable declarations:
 
542
<programlisting>
 
543
user_id integer;
 
544
quantity numeric(5);
 
545
url varchar;
 
546
myrow tablename%ROWTYPE;
 
547
myfield tablename.columnname%TYPE;
 
548
arow RECORD;
 
549
</programlisting>
 
550
    </para>
 
551
 
 
552
    <para>
 
553
     The general syntax of a variable declaration is:
 
554
<synopsis>
 
555
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
 
556
</synopsis>
 
557
      The <literal>DEFAULT</> clause, if given, specifies the initial value assigned
 
558
      to the variable when the block is entered.  If the <literal>DEFAULT</> clause
 
559
      is not given then the variable is initialized to the
 
560
      <acronym>SQL</acronym> null value. 
 
561
      The <literal>CONSTANT</> option prevents the variable from being assigned to,
 
562
      so that its value remains constant for the duration of the block.
 
563
      If <literal>NOT NULL</>
 
564
      is specified, an assignment of a null value results in a run-time
 
565
      error. All variables declared as <literal>NOT NULL</>
 
566
      must have a nonnull default value specified.
 
567
     </para>
 
568
 
 
569
     <para>
 
570
      The default value is evaluated every time the block is entered. So,
 
571
      for example, assigning <literal>now()</literal> to a variable of type
 
572
      <type>timestamp</type> causes the variable to have the
 
573
      time of the current function call, not the time when the function was
 
574
      precompiled.
 
575
     </para>
 
576
 
 
577
     <para>
 
578
      Examples:
 
579
<programlisting>
 
580
quantity integer DEFAULT 32;
 
581
url varchar := 'http://mysite.com';
 
582
user_id CONSTANT integer := 10;
 
583
</programlisting>
 
584
     </para>
 
585
 
 
586
    <sect2 id="plpgsql-declaration-aliases">
 
587
     <title>Aliases for Function Parameters</title>
 
588
 
 
589
     <para>
 
590
      Parameters passed to functions are named with the identifiers
 
591
      <literal>$1</literal>, <literal>$2</literal>,
 
592
      etc.  Optionally, aliases can be declared for
 
593
      <literal>$<replaceable>n</replaceable></literal>
 
594
      parameter names for increased readability.  Either the alias or the
 
595
      numeric identifier can then be used to refer to the parameter value.
 
596
     </para>
 
597
 
 
598
     <para>
 
599
      There are two ways to create an alias.  The preferred way is to give a
 
600
      name to the parameter in the <command>CREATE FUNCTION</command> command,
 
601
      for example:
 
602
<programlisting>
 
603
CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
 
604
BEGIN
 
605
    RETURN subtotal * 0.06;
 
606
END;
 
607
$$ LANGUAGE plpgsql;
 
608
</programlisting>
 
609
      The other way, which was the only way available before
 
610
      <productname>PostgreSQL</productname> 8.0, is to explicitly
 
611
      declare an alias, using the declaration syntax
 
612
 
 
613
<synopsis>
 
614
<replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
 
615
</synopsis>
 
616
 
 
617
      The same example in this style looks like
 
618
<programlisting>
 
619
CREATE FUNCTION sales_tax(real) RETURNS real AS $$
 
620
DECLARE
 
621
    subtotal ALIAS FOR $1;
 
622
BEGIN
 
623
    RETURN subtotal * 0.06;
 
624
END;
 
625
$$ LANGUAGE plpgsql;
 
626
</programlisting>
 
627
      Some more examples:
 
628
<programlisting>
 
629
CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
 
630
DECLARE
 
631
    v_string ALIAS FOR $1;
 
632
    index ALIAS FOR $2;
 
633
BEGIN
 
634
    -- some computations here
 
635
END;
 
636
$$ LANGUAGE plpgsql;
 
637
 
 
638
 
 
639
CREATE FUNCTION concat_selected_fields(in_t tablename) RETURNS text AS $$
 
640
BEGIN
 
641
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
 
642
END;
 
643
$$ LANGUAGE plpgsql;
 
644
</programlisting>
 
645
     </para>
 
646
 
 
647
     <para>
 
648
      When the return type of a <application>PL/pgSQL</application>
 
649
      function is declared as a polymorphic type (<type>anyelement</type>
 
650
      or <type>anyarray</type>), a special parameter <literal>$0</literal>
 
651
      is created.  Its data type is the actual return type of the function,
 
652
      as deduced from the actual input types (see <xref
 
653
      linkend="extend-types-polymorphic">).
 
654
      This allows the function to access its actual return type
 
655
      as shown in <xref linkend="plpgsql-declaration-type">.
 
656
      <literal>$0</literal> is initialized to null and can be modified by
 
657
      the function, so it can be used to hold the return value if desired,
 
658
      though that is not required.  <literal>$0</literal> can also be
 
659
      given an alias.  For example, this function works on any data type
 
660
      that has a <literal>+</> operator:
 
661
<programlisting>
 
662
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
 
663
RETURNS anyelement AS $$
 
664
DECLARE
 
665
    result ALIAS FOR $0;
 
666
BEGIN
 
667
    result := v1 + v2 + v3;
 
668
    RETURN result;
 
669
END;
 
670
$$ LANGUAGE plpgsql;
 
671
</programlisting>
 
672
     </para>
 
673
    </sect2>
 
674
 
 
675
  <sect2 id="plpgsql-declaration-type">
 
676
   <title>Copying Types</title>
 
677
 
 
678
<synopsis>
 
679
<replaceable>variable</replaceable>%TYPE
 
680
</synopsis>
 
681
 
 
682
   <para>
 
683
    <literal>%TYPE</literal> provides the data type of a variable or
 
684
    table column. You can use this to declare variables that will hold
 
685
    database values. For example, let's say you have a column named
 
686
    <literal>user_id</literal> in your <literal>users</literal>
 
687
    table. To declare a variable with the same data type as
 
688
    <literal>users.user_id</> you write:
 
689
<programlisting>
 
690
user_id users.user_id%TYPE;
 
691
</programlisting>
 
692
   </para>
 
693
 
 
694
   <para>
 
695
    By using <literal>%TYPE</literal> you don't need to know the data
 
696
    type of the structure you are referencing, and most importantly,
 
697
    if the data type of the referenced item changes in the future (for
 
698
    instance: you change the type of <literal>user_id</>
 
699
    from <type>integer</type> to <type>real</type>), you may not need
 
700
    to change your function definition.
 
701
   </para>
 
702
 
 
703
   <para>
 
704
    <literal>%TYPE</literal> is particularly valuable in polymorphic
 
705
    functions, since the data types needed for internal variables may
 
706
    change from one call to the next.  Appropriate variables can be
 
707
    created by applying <literal>%TYPE</literal> to the function's
 
708
    arguments or result placeholders.
 
709
   </para>
 
710
 
 
711
  </sect2>
 
712
 
 
713
    <sect2 id="plpgsql-declaration-rowtypes">
 
714
     <title>Row Types</title>
 
715
 
 
716
<synopsis>
 
717
<replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
 
718
<replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
 
719
</synopsis>
 
720
 
 
721
   <para>
 
722
    A variable of a composite type is called a <firstterm>row</>
 
723
    variable (or <firstterm>row-type</> variable).  Such a variable
 
724
    can hold a whole row of a <command>SELECT</> or <command>FOR</>
 
725
    query result, so long as that query's column set matches the
 
726
    declared type of the variable.
 
727
    The individual fields of the row value
 
728
    are accessed using the usual dot notation, for example
 
729
    <literal>rowvar.field</literal>.
 
730
   </para>
 
731
 
 
732
   <para>
 
733
    A row variable can be declared to have the same type as the rows of
 
734
    an existing table or view, by using the
 
735
    <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
 
736
    notation; or it can be declared by giving a composite type's name.
 
737
    (Since every table has an associated composite type of the same name,
 
738
    it actually does not matter in <productname>PostgreSQL</> whether you
 
739
    write <literal>%ROWTYPE</literal> or not.  But the form with
 
740
    <literal>%ROWTYPE</literal> is more portable.)
 
741
   </para>
 
742
 
 
743
   <para>
 
744
    Parameters to a function can be
 
745
    composite types (complete table rows). In that case, the
 
746
    corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
 
747
    be selected from it, for example <literal>$1.user_id</literal>.
 
748
   </para>
 
749
 
 
750
   <para>
 
751
    Only the user-defined columns of a table row are accessible in a
 
752
    row-type variable, not the OID or other system columns (because the
 
753
    row could be from a view).  The fields of the row type inherit the
 
754
    table's field size or precision for data types such as
 
755
    <type>char(<replaceable>n</>)</type>.
 
756
   </para>
 
757
 
 
758
   <para>
 
759
    Here is an example of using composite types:
 
760
<programlisting>
 
761
CREATE FUNCTION merge_fields(t_row tablename) RETURNS text AS $$
 
762
DECLARE
 
763
    t2_row table2name%ROWTYPE;
 
764
BEGIN
 
765
    SELECT * INTO t2_row FROM table2name WHERE ... ;
 
766
    RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
 
767
END;
 
768
$$ LANGUAGE plpgsql;
 
769
 
 
770
SELECT merge_fields(t.*) FROM tablename t WHERE ... ;
 
771
</programlisting>
 
772
   </para>
 
773
  </sect2>
 
774
 
 
775
  <sect2 id="plpgsql-declaration-records">
 
776
   <title>Record Types</title>
 
777
 
 
778
<synopsis>
 
779
<replaceable>name</replaceable> RECORD;
 
780
</synopsis>
 
781
 
 
782
   <para>
 
783
    Record variables are similar to row-type variables, but they have no
 
784
    predefined structure.  They take on the actual row structure of the
 
785
    row they are assigned during a <command>SELECT</> or <command>FOR</> command.  The substructure
 
786
    of a record variable can change each time it is assigned to.
 
787
    A consequence of this is that until a record variable is first assigned
 
788
    to, it has no substructure, and any attempt to access a
 
789
    field in it will draw a run-time error.
 
790
   </para>
 
791
 
 
792
   <para>
 
793
    Note that <literal>RECORD</> is not a true data type, only a placeholder.
 
794
    One should also realize that when a <application>PL/pgSQL</application>
 
795
    function is declared to return type <type>record</>, this is not quite the
 
796
    same concept as a record variable, even though such a function may well
 
797
    use a record variable to hold its result.  In both cases the actual row
 
798
    structure is unknown when the function is written, but for a function
 
799
    returning <type>record</> the actual structure is determined when the
 
800
    calling query is parsed, whereas a record variable can change its row
 
801
    structure on-the-fly.
 
802
   </para>
 
803
  </sect2>
 
804
 
 
805
  <sect2 id="plpgsql-declaration-renaming-vars">
 
806
   <title><literal>RENAME</></title>
 
807
 
 
808
<synopsis>
 
809
RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
 
810
</synopsis>
 
811
 
 
812
   <para>
 
813
    Using the <literal>RENAME</literal> declaration you can change the
 
814
    name of a variable, record or row. This is primarily useful if
 
815
    <varname>NEW</varname> or <varname>OLD</varname> should be
 
816
    referenced by another name inside a trigger procedure.  See also
 
817
    <literal>ALIAS</literal>.
 
818
   </para>
 
819
 
 
820
   <para>
 
821
    Examples:
 
822
<programlisting>
 
823
RENAME id TO user_id;
 
824
RENAME this_var TO that_var;
 
825
</programlisting>
 
826
   </para>
 
827
 
 
828
    <note>
 
829
     <para>
 
830
      <literal>RENAME</literal> appears to be broken as of
 
831
      <productname>PostgreSQL</> 7.3.  Fixing this is of low priority,
 
832
      since <literal>ALIAS</literal> covers most of the practical uses
 
833
      of <literal>RENAME</literal>.
 
834
     </para>
 
835
    </note>
 
836
   </sect2>
 
837
  </sect1>
 
838
 
 
839
  <sect1 id="plpgsql-expressions">
 
840
  <title>Expressions</title>
 
841
 
 
842
    <para>
 
843
     All expressions used in <application>PL/pgSQL</application>
 
844
     statements are processed using the server's regular
 
845
     <acronym>SQL</acronym> executor.  In effect, a query like
 
846
<synopsis>
 
847
SELECT <replaceable>expression</replaceable>
 
848
</synopsis>
 
849
     is executed using the <acronym>SPI</acronym> manager. Before evaluation,
 
850
     occurrences of <application>PL/pgSQL</application> variable
 
851
     identifiers are replaced by parameters, and the actual values from
 
852
     the variables are passed to the executor in the parameter array.
 
853
     This allows the query plan for the <command>SELECT</command> to
 
854
     be prepared just once and then reused for subsequent
 
855
     evaluations.
 
856
    </para>
 
857
 
 
858
    <para>
 
859
     The evaluation done by the <productname>PostgreSQL</productname>
 
860
     main parser has some side
 
861
     effects on the interpretation of constant values. In detail there
 
862
     is a difference between what these two functions do:
 
863
 
 
864
<programlisting>
 
865
CREATE FUNCTION logfunc1(logtxt text) RETURNS timestamp AS $$
 
866
    BEGIN
 
867
        INSERT INTO logtable VALUES (logtxt, 'now');
 
868
        RETURN 'now';
 
869
    END;
 
870
$$ LANGUAGE plpgsql;
 
871
</programlisting>
 
872
 
 
873
     and
 
874
 
 
875
<programlisting>
 
876
CREATE FUNCTION logfunc2(logtxt text) RETURNS timestamp AS $$
 
877
    DECLARE
 
878
        curtime timestamp;
 
879
    BEGIN
 
880
        curtime := 'now';
 
881
        INSERT INTO logtable VALUES (logtxt, curtime);
 
882
        RETURN curtime;
 
883
    END;
 
884
$$ LANGUAGE plpgsql;
 
885
</programlisting>
 
886
    </para>
 
887
 
 
888
    <para>
 
889
     In the case of <function>logfunc1</function>, the 
 
890
     <productname>PostgreSQL</productname> main parser knows when 
 
891
     preparing the plan for the <command>INSERT</command>, that the string 
 
892
     <literal>'now'</literal> should be interpreted as 
 
893
     <type>timestamp</type> because the target column of <classname>logtable</classname>
 
894
     is of that type. Thus, it will make a constant from it at this
 
895
     time and this constant value is then used in all invocations of 
 
896
     <function>logfunc1</function> during the lifetime of the
 
897
     session. Needless to say that this isn't what the
 
898
     programmer wanted.
 
899
    </para>
 
900
 
 
901
    <para>
 
902
     In the case of <function>logfunc2</function>, the 
 
903
     <productname>PostgreSQL</productname> main parser does not know
 
904
     what type <literal>'now'</literal> should become and therefore 
 
905
     it returns a data value of type <type>text</type> containing the string 
 
906
     <literal>now</literal>. During the ensuing assignment
 
907
     to the local variable <varname>curtime</varname>, the
 
908
     <application>PL/pgSQL</application> interpreter casts this
 
909
     string to the <type>timestamp</type> type by calling the
 
910
     <function>text_out</function> and <function>timestamp_in</function>
 
911
     functions for the conversion.  So, the computed time stamp is updated
 
912
     on each execution as the programmer expects.
 
913
    </para>
 
914
 
 
915
    <para>
 
916
     The mutable nature of record variables presents a problem in this
 
917
     connection.  When fields of a record variable are used in
 
918
     expressions or statements, the data types of the fields must not
 
919
     change between calls of one and the same expression, since the
 
920
     expression will be planned using the data type that is present
 
921
     when the expression is first reached.  Keep this in mind when
 
922
     writing trigger procedures that handle events for more than one
 
923
     table.  (<command>EXECUTE</command> can be used to get around
 
924
     this problem when necessary.)
 
925
    </para>
 
926
  </sect1>
 
927
 
 
928
  <sect1 id="plpgsql-statements">
 
929
  <title>Basic Statements</title>
 
930
 
 
931
   <para>
 
932
    In this section and the following ones, we describe all the statement
 
933
    types that are explicitly understood by
 
934
    <application>PL/pgSQL</application>.
 
935
    Anything not recognized as one of these statement types is presumed
 
936
    to be an SQL command and is sent to the main database engine to execute
 
937
    (after substitution of any <application>PL/pgSQL</application> variables
 
938
    used in the statement).  Thus,
 
939
    for example, the SQL commands <command>INSERT</>, <command>UPDATE</>, and
 
940
    <command>DELETE</> may be considered to be statements of
 
941
    <application>PL/pgSQL</application>, but they are not specifically
 
942
    listed here.
 
943
   </para>
 
944
 
 
945
   <sect2 id="plpgsql-statements-assignment">
 
946
    <title>Assignment</title>
 
947
 
 
948
    <para>
 
949
     An assignment of a value to a variable or row/record field is
 
950
     written as:
 
951
<synopsis>
 
952
<replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
 
953
</synopsis>
 
954
     As explained above, the expression in such a statement is evaluated
 
955
     by means of an SQL <command>SELECT</> command sent to the main
 
956
     database engine.  The expression must yield a single value.
 
957
    </para>
 
958
 
 
959
    <para>
 
960
     If the expression's result data type doesn't match the variable's
 
961
     data type, or the variable has a specific size/precision
 
962
     (like <type>char(20)</type>), the result value will be implicitly
 
963
     converted by the <application>PL/pgSQL</application> interpreter using
 
964
     the result type's output-function and 
 
965
     the variable type's input-function. Note that this could potentially
 
966
     result in run-time errors generated by the input function, if the
 
967
     string form of the result value is not acceptable to the input function.
 
968
    </para>
 
969
 
 
970
    <para>
 
971
     Examples:
 
972
<programlisting>
 
973
user_id := 20;
 
974
tax := subtotal * 0.06;
 
975
</programlisting>
 
976
    </para>
 
977
   </sect2>
 
978
 
 
979
   <sect2 id="plpgsql-select-into">
 
980
    <title><command>SELECT INTO</command></title>
 
981
 
 
982
    <indexterm zone="plpgsql-select-into">
 
983
     <primary>SELECT INTO</primary>
 
984
     <secondary>in PL/pgSQL</secondary>
 
985
    </indexterm>
 
986
 
 
987
    <para>
 
988
     The result of a <command>SELECT</command> command yielding multiple columns (but
 
989
     only one row) can be assigned to a record variable, row-type
 
990
     variable, or list of scalar variables.  This is done by:
 
991
 
 
992
<synopsis>
 
993
SELECT INTO <replaceable>target</replaceable> <replaceable>select_expressions</replaceable> FROM ...;
 
994
</synopsis>
 
995
 
 
996
     where <replaceable>target</replaceable> can be a record variable, a row
 
997
     variable, or a comma-separated list of simple variables and
 
998
     record/row fields.  The <replaceable>select_expressions</replaceable>
 
999
     and the remainder of the command are the same as in regular SQL.
 
1000
    </para>
 
1001
 
 
1002
    <para>
 
1003
     Note that this is quite different from
 
1004
     <productname>PostgreSQL</>'s normal interpretation of
 
1005
     <command>SELECT INTO</command>, where the <literal>INTO</> target
 
1006
     is a newly created table.  If you want to create a table from a
 
1007
     <command>SELECT</> result inside a
 
1008
     <application>PL/pgSQL</application> function, use the syntax
 
1009
     <command>CREATE TABLE ... AS SELECT</command>.
 
1010
    </para>
 
1011
 
 
1012
    <para>
 
1013
     If a row or a variable list is used as target, the selected values
 
1014
     must exactly match the structure of the target, or a run-time error
 
1015
     occurs.  When a record variable is the target, it automatically
 
1016
     configures itself to the row type of the query result columns.
 
1017
    </para>
 
1018
 
 
1019
    <para>
 
1020
     Except for the <literal>INTO</> clause, the <command>SELECT</>
 
1021
     statement is the same as a normal SQL <command>SELECT</> command
 
1022
     and can use its full power.
 
1023
    </para>
 
1024
 
 
1025
    <para>
 
1026
     The <literal>INTO</> clause can appear almost anywhere in the
 
1027
     <command>SELECT</command> statement.  Customarily it is written
 
1028
     either just after <literal>SELECT</> as shown above, or
 
1029
     just before <literal>FROM</> &mdash; that is, either just before
 
1030
     or just after the list of <replaceable>select_expressions</replaceable>.
 
1031
    </para>
 
1032
 
 
1033
    <para>
 
1034
     If the query returns zero rows, null values are assigned to the
 
1035
     target(s).  If the query returns multiple rows, the first
 
1036
     row is assigned to the target(s) and the rest are discarded.
 
1037
     (Note that <quote>the first row</> is not well-defined unless you've
 
1038
     used <literal>ORDER BY</>.)
 
1039
    </para>
 
1040
 
 
1041
    <para>
 
1042
     You can check the special <literal>FOUND</literal> variable (see
 
1043
     <xref linkend="plpgsql-statements-diagnostics">) after a
 
1044
     <command>SELECT INTO</command> statement to determine whether the
 
1045
     assignment was successful, that is, at least one row was was returned by
 
1046
     the query. For example:
 
1047
 
 
1048
<programlisting>
 
1049
SELECT INTO myrec * FROM emp WHERE empname = myname;
 
1050
IF NOT FOUND THEN
 
1051
    RAISE EXCEPTION 'employee % not found', myname;
 
1052
END IF;
 
1053
</programlisting>
 
1054
    </para>
 
1055
 
 
1056
    <para>
 
1057
     To test for whether a record/row result is null, you can use the
 
1058
     <literal>IS NULL</literal> conditional.  There is, however, no
 
1059
     way to tell whether any additional rows might have been
 
1060
     discarded.  Here is an example that handles the case where no
 
1061
     rows have been returned:
 
1062
<programlisting>
 
1063
DECLARE
 
1064
    users_rec RECORD;
 
1065
BEGIN
 
1066
    SELECT INTO users_rec * FROM users WHERE user_id=3;
 
1067
 
 
1068
    IF users_rec.homepage IS NULL THEN
 
1069
        -- user entered no homepage, return "http://"
 
1070
        RETURN 'http://';
 
1071
    END IF;
 
1072
END;
 
1073
</programlisting>
 
1074
    </para>
 
1075
   </sect2>
 
1076
 
 
1077
   <sect2 id="plpgsql-statements-perform">
 
1078
    <title>Executing an Expression or Query With No Result</title>
 
1079
 
 
1080
    <para>
 
1081
     Sometimes one wishes to evaluate an expression or query but
 
1082
     discard the result (typically because one is calling a function
 
1083
     that has useful side-effects but no useful result value).  To do
 
1084
     this in <application>PL/pgSQL</application>, use the
 
1085
     <command>PERFORM</command> statement:
 
1086
 
 
1087
<synopsis>
 
1088
PERFORM <replaceable>query</replaceable>;
 
1089
</synopsis>
 
1090
 
 
1091
     This executes <replaceable>query</replaceable> and discards the
 
1092
     result.  Write the <replaceable>query</replaceable> the same
 
1093
     way as you would in an SQL <command>SELECT</> command, but replace the
 
1094
     initial keyword <command>SELECT</> with <command>PERFORM</command>.
 
1095
     <application>PL/pgSQL</application> variables will be
 
1096
     substituted into the query as usual.  Also, the special variable
 
1097
     <literal>FOUND</literal> is set to true if the query produced at
 
1098
     least one row or false if it produced no rows.
 
1099
    </para>
 
1100
 
 
1101
    <note>
 
1102
     <para>
 
1103
      One might expect that <command>SELECT</command> with no
 
1104
      <literal>INTO</> clause would accomplish this result, but at
 
1105
      present the only accepted way to do it is
 
1106
      <command>PERFORM</command>.
 
1107
     </para>
 
1108
    </note>
 
1109
 
 
1110
    <para>
 
1111
     An example:
 
1112
<programlisting>
 
1113
PERFORM create_mv('cs_session_page_requests_mv', my_query);
 
1114
</programlisting>
 
1115
    </para>
 
1116
   </sect2>
 
1117
 
 
1118
   <sect2 id="plpgsql-statements-null">
 
1119
    <title>Doing Nothing At All</title>
 
1120
 
 
1121
    <para>
 
1122
     Sometimes a placeholder statement that does nothing is useful.
 
1123
     For example, it can indicate that one arm of an if/then/else
 
1124
     chain is deliberately empty.  For this purpose, use the
 
1125
     <command>NULL</command> statement:
 
1126
 
 
1127
<synopsis>
 
1128
NULL;
 
1129
</synopsis>
 
1130
    </para>
 
1131
 
 
1132
    <para>
 
1133
     For example, the following two fragments of code are equivalent:
 
1134
<programlisting>
 
1135
    BEGIN
 
1136
        y := x / 0;
 
1137
    EXCEPTION
 
1138
        WHEN division_by_zero THEN
 
1139
            NULL;  -- ignore the error
 
1140
    END;
 
1141
</programlisting>
 
1142
 
 
1143
<programlisting>
 
1144
    BEGIN
 
1145
        y := x / 0;
 
1146
    EXCEPTION
 
1147
        WHEN division_by_zero THEN  -- ignore the error
 
1148
    END;
 
1149
</programlisting>
 
1150
     Which is preferable is a matter of taste.
 
1151
    </para>
 
1152
 
 
1153
    <note>
 
1154
     <para>
 
1155
      In Oracle's PL/SQL, empty statement lists are not allowed, and so
 
1156
      <command>NULL</> statements are <emphasis>required</> for situations
 
1157
      such as this.  <application>PL/pgSQL</application> allows you to
 
1158
      just write nothing, instead.
 
1159
     </para>
 
1160
    </note>
 
1161
 
 
1162
   </sect2>
 
1163
 
 
1164
   <sect2 id="plpgsql-statements-executing-dyn">
 
1165
    <title>Executing Dynamic Commands</title>
 
1166
 
 
1167
    <para>
 
1168
     Oftentimes you will want to generate dynamic commands inside your
 
1169
     <application>PL/pgSQL</application> functions, that is, commands
 
1170
     that will involve different tables or different data types each
 
1171
     time they are executed.  <application>PL/pgSQL</application>'s
 
1172
     normal attempts to cache plans for commands will not work in such
 
1173
     scenarios.  To handle this sort of problem, the
 
1174
     <command>EXECUTE</command> statement is provided:
 
1175
 
 
1176
<synopsis>
 
1177
EXECUTE <replaceable class="command">command-string</replaceable>;
 
1178
</synopsis>
 
1179
 
 
1180
     where <replaceable>command-string</replaceable> is an expression
 
1181
     yielding a string (of type
 
1182
     <type>text</type>) containing the command
 
1183
     to be executed.  This string is fed literally to the SQL engine.
 
1184
    </para>
 
1185
 
 
1186
    <para>
 
1187
     Note in particular that no substitution of <application>PL/pgSQL</>
 
1188
     variables is done on the command string.  The values of variables must
 
1189
     be inserted in the command string as it is constructed.
 
1190
    </para>
 
1191
 
 
1192
    <para>
 
1193
     Unlike all other commands in <application>PL/pgSQL</>, a command
 
1194
     run by an <command>EXECUTE</command> statement is not prepared
 
1195
     and saved just once during the life of the session.  Instead, the
 
1196
     command is prepared each time the statement is run. The command
 
1197
     string can be dynamically created within the function to perform
 
1198
     actions on different tables and columns.
 
1199
    </para>
 
1200
 
 
1201
    <para>
 
1202
     The results from <command>SELECT</command> commands are discarded
 
1203
     by <command>EXECUTE</command>, and <command>SELECT INTO</command>
 
1204
     is not currently supported within <command>EXECUTE</command>.
 
1205
     So there is no way to extract a result from a dynamically-created
 
1206
     <command>SELECT</command> using the plain <command>EXECUTE</command>
 
1207
     command.  There are two other ways to do it, however: one is to use the
 
1208
     <command>FOR-IN-EXECUTE</>
 
1209
     loop form described in <xref linkend="plpgsql-records-iterating">,
 
1210
     and the other is to use a cursor with <command>OPEN-FOR-EXECUTE</>, as
 
1211
     described in <xref linkend="plpgsql-cursor-opening">.
 
1212
    </para>
 
1213
 
 
1214
    <para>
 
1215
     When working with dynamic commands you will often have to handle escaping
 
1216
     of single quotes.  The recommended method for quoting fixed text in your
 
1217
     function body is dollar quoting.  (If you have legacy code that does
 
1218
     not use dollar quoting, please refer to the
 
1219
     overview in <xref linkend="plpgsql-quote-tips">, which can save you
 
1220
     some effort when translating said code to a more reasonable scheme.)
 
1221
    </para>
 
1222
 
 
1223
    <para>
 
1224
     Dynamic values that are to be inserted into the constructed
 
1225
     query require special handling since they might themselves contain
 
1226
     quote characters.
 
1227
     An example (this assumes that you are using dollar quoting for the
 
1228
     function as a whole, so the quote marks need not be doubled):
 
1229
<programlisting>
 
1230
EXECUTE 'UPDATE tbl SET '
 
1231
        || quote_ident(colname)
 
1232
        || ' = '
 
1233
        || quote_literal(newvalue)
 
1234
        || ' WHERE key = '
 
1235
        || quote_literal(keyvalue);
 
1236
</programlisting>
 
1237
    </para>
 
1238
 
 
1239
    <para>
 
1240
     This example shows use of the functions
 
1241
     <function>quote_ident(<type>text</type>)</function> and
 
1242
     <function>quote_literal(<type>text</type>)</function>.<indexterm><primary>quote_ident</><secondary>use
 
1243
     in
 
1244
     PL/pgSQL</></indexterm><indexterm><primary>quote_literal</><secondary>use
 
1245
     in PL/pgSQL</></indexterm> For safety, variables containing column and
 
1246
     table identifiers should be passed to function
 
1247
     <function>quote_ident</function>.  Variables containing values
 
1248
     that should be literal strings in the constructed command should
 
1249
     be passed to <function>quote_literal</function>.  Both take the
 
1250
     appropriate steps to return the input text enclosed in double or
 
1251
     single quotes respectively, with any embedded special characters
 
1252
     properly escaped.
 
1253
    </para>
 
1254
 
 
1255
    <para>
 
1256
     Note that dollar quoting is only useful for quoting fixed text.
 
1257
     It would be a very bad idea to try to do the above example as
 
1258
<programlisting>
 
1259
EXECUTE 'UPDATE tbl SET '
 
1260
        || quote_ident(colname)
 
1261
        || ' = $$'
 
1262
        || newvalue
 
1263
        || '$$ WHERE key = '
 
1264
        || quote_literal(keyvalue);
 
1265
</programlisting>
 
1266
     because it would break if the contents of <literal>newvalue</>
 
1267
     happened to contain <literal>$$</>.  The same objection would
 
1268
     apply to any other dollar-quoting delimiter you might pick.
 
1269
     So, to safely quote text that is not known in advance, you
 
1270
     <emphasis>must</> use <function>quote_literal</function>.
 
1271
    </para>
 
1272
 
 
1273
    <para>
 
1274
     A much larger example of a dynamic command and
 
1275
     <command>EXECUTE</command> can be seen in <xref
 
1276
     linkend="plpgsql-porting-ex2">, which builds and executes a
 
1277
     <command>CREATE FUNCTION</> command to define a new function.
 
1278
    </para>
 
1279
   </sect2>
 
1280
 
 
1281
   <sect2 id="plpgsql-statements-diagnostics">
 
1282
    <title>Obtaining the Result Status</title>
 
1283
 
 
1284
    <para>
 
1285
     There are several ways to determine the effect of a command. The
 
1286
     first method is to use the <command>GET DIAGNOSTICS</command>
 
1287
     command, which has the form:
 
1288
 
 
1289
<synopsis>
 
1290
GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional> ;
 
1291
</synopsis>
 
1292
 
 
1293
     This command allows retrieval of system status indicators.  Each
 
1294
     <replaceable>item</replaceable> is a key word identifying a state
 
1295
     value to be assigned to the specified variable (which should be
 
1296
     of the right data type to receive it).  The currently available
 
1297
     status items are <varname>ROW_COUNT</>, the number of rows
 
1298
     processed by the last <acronym>SQL</acronym> command sent down to
 
1299
     the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
 
1300
     the OID of the last row inserted by the most recent
 
1301
     <acronym>SQL</acronym> command.  Note that <varname>RESULT_OID</>
 
1302
     is only useful after an <command>INSERT</command> command.
 
1303
    </para>
 
1304
 
 
1305
    <para>
 
1306
     An example:
 
1307
<programlisting>
 
1308
GET DIAGNOSTICS integer_var = ROW_COUNT;
 
1309
</programlisting>
 
1310
    </para>
 
1311
 
 
1312
    <para>
 
1313
     The second method to determine the effects of a command is to check the
 
1314
     special variable named <literal>FOUND</literal>, which is of
 
1315
     type <type>boolean</type>.  <literal>FOUND</literal> starts out
 
1316
     false within each <application>PL/pgSQL</application> function call.
 
1317
     It is set by each of the following types of statements:
 
1318
         <itemizedlist>
 
1319
          <listitem>
 
1320
           <para>
 
1321
                A <command>SELECT INTO</command> statement sets
 
1322
                <literal>FOUND</literal> true if it returns a row, false if no
 
1323
                row is returned.
 
1324
           </para>
 
1325
          </listitem>
 
1326
          <listitem>
 
1327
           <para>
 
1328
                A <command>PERFORM</> statement sets <literal>FOUND</literal>
 
1329
                true if it produces (and discards) a row, false if no row is
 
1330
                produced.
 
1331
           </para>
 
1332
          </listitem>
 
1333
          <listitem>
 
1334
           <para>
 
1335
                <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
 
1336
                statements set <literal>FOUND</literal> true if at least one
 
1337
                row is affected, false if no row is affected.
 
1338
           </para>
 
1339
          </listitem>
 
1340
          <listitem>
 
1341
           <para>
 
1342
                A <command>FETCH</> statement sets <literal>FOUND</literal>
 
1343
                true if it returns a row, false if no row is returned.
 
1344
           </para>
 
1345
          </listitem>
 
1346
          <listitem>
 
1347
           <para>
 
1348
                A <command>FOR</> statement sets <literal>FOUND</literal> true
 
1349
                if it iterates one or more times, else false.  This applies to
 
1350
                all three variants of the <command>FOR</> statement (integer
 
1351
                <command>FOR</> loops, record-set <command>FOR</> loops, and
 
1352
                dynamic record-set <command>FOR</>
 
1353
                loops). <literal>FOUND</literal> is set this way when the
 
1354
                <command>FOR</> loop exits; inside the execution of the loop,
 
1355
                <literal>FOUND</literal> is not modified by the
 
1356
                <command>FOR</> statement, although it may be changed by the
 
1357
                execution of other statements within the loop body.
 
1358
           </para>
 
1359
          </listitem>
 
1360
         </itemizedlist>
 
1361
 
 
1362
     <literal>FOUND</literal> is a local variable within each
 
1363
     <application>PL/pgSQL</application> function; so any changes
 
1364
     to it affect only the current function.
 
1365
    </para>
 
1366
 
 
1367
   </sect2>
 
1368
  </sect1>
 
1369
 
 
1370
  <sect1 id="plpgsql-control-structures">
 
1371
   <title>Control Structures</title>
 
1372
 
 
1373
   <para>
 
1374
    Control structures are probably the most useful (and
 
1375
    important) part of <application>PL/pgSQL</>. With
 
1376
    <application>PL/pgSQL</>'s control structures,
 
1377
    you can manipulate <productname>PostgreSQL</> data in a very
 
1378
    flexible and powerful way. 
 
1379
   </para>
 
1380
 
 
1381
   <sect2 id="plpgsql-statements-returning">
 
1382
    <title>Returning From a Function</title>
 
1383
 
 
1384
    <para>
 
1385
     There are two commands available that allow you to return data
 
1386
     from a function: <command>RETURN</command> and <command>RETURN
 
1387
     NEXT</command>.
 
1388
    </para>
 
1389
 
 
1390
    <sect3>
 
1391
     <title><command>RETURN</></title>
 
1392
 
 
1393
<synopsis>
 
1394
RETURN <replaceable>expression</replaceable>;
 
1395
</synopsis>
 
1396
 
 
1397
     <para>
 
1398
      <command>RETURN</command> with an expression terminates the
 
1399
      function and returns the value of
 
1400
      <replaceable>expression</replaceable> to the caller.  This form
 
1401
      is to be used for <application>PL/pgSQL</> functions that do
 
1402
      not return a set.
 
1403
     </para>
 
1404
 
 
1405
     <para>
 
1406
      When returning a scalar type, any expression can be used. The
 
1407
      expression's result will be automatically cast into the
 
1408
      function's return type as described for assignments. To return a
 
1409
      composite (row) value, you must write a record or row variable
 
1410
      as the <replaceable>expression</replaceable>.
 
1411
     </para>
 
1412
 
 
1413
     <para>
 
1414
      The return value of a function cannot be left undefined. If
 
1415
      control reaches the end of the top-level block of the function
 
1416
      without hitting a <command>RETURN</command> statement, a run-time
 
1417
      error will occur.
 
1418
     </para>
 
1419
 
 
1420
     <para>
 
1421
      If you have declared the function to
 
1422
      return <type>void</type>, a <command>RETURN</command> statement
 
1423
      must still be provided; but in this case the expression following
 
1424
      <command>RETURN</command> is optional and will be ignored if present.
 
1425
     </para>
 
1426
    </sect3>
 
1427
 
 
1428
    <sect3>
 
1429
     <title><command>RETURN NEXT</></title>
 
1430
 
 
1431
<synopsis>
 
1432
RETURN NEXT <replaceable>expression</replaceable>;
 
1433
</synopsis>
 
1434
 
 
1435
     <para>
 
1436
      When a <application>PL/pgSQL</> function is declared to return
 
1437
      <literal>SETOF <replaceable>sometype</></literal>, the procedure
 
1438
      to follow is slightly different.  In that case, the individual
 
1439
      items to return are specified in <command>RETURN NEXT</command>
 
1440
      commands, and then a final <command>RETURN</command> command
 
1441
      with no argument is used to indicate that the function has
 
1442
      finished executing.  <command>RETURN NEXT</command> can be used
 
1443
      with both scalar and composite data types; in the latter case, an
 
1444
      entire <quote>table</quote> of results will be returned.
 
1445
     </para>
 
1446
 
 
1447
     <para>
 
1448
      Functions that use <command>RETURN NEXT</command> should be
 
1449
      called in the following fashion:
 
1450
 
 
1451
<programlisting>
 
1452
SELECT * FROM some_func();
 
1453
</programlisting>
 
1454
 
 
1455
      That is, the function must be used as a table source in a
 
1456
      <literal>FROM</literal> clause.
 
1457
     </para>
 
1458
 
 
1459
     <para>
 
1460
      <command>RETURN NEXT</command> does not actually return from the
 
1461
      function; it simply saves away the value of the expression.
 
1462
      Execution then continues with the next statement in
 
1463
      the <application>PL/pgSQL</> function.  As successive
 
1464
      <command>RETURN NEXT</command> commands are executed, the result
 
1465
      set is built up.  A final <command>RETURN</command>, which should
 
1466
      have no argument, causes control to exit the function.
 
1467
     </para>
 
1468
 
 
1469
     <note>
 
1470
      <para>
 
1471
       The current implementation of <command>RETURN NEXT</command>
 
1472
       for <application>PL/pgSQL</> stores the entire result set
 
1473
       before returning from the function, as discussed above.  That
 
1474
       means that if a <application>PL/pgSQL</> function produces a
 
1475
       very large result set, performance may be poor: data will be
 
1476
       written to disk to avoid memory exhaustion, but the function
 
1477
       itself will not return until the entire result set has been
 
1478
       generated.  A future version of <application>PL/pgSQL</> may
 
1479
       allow users to define set-returning functions
 
1480
       that do not have this limitation.  Currently, the point at
 
1481
       which data begins being written to disk is controlled by the
 
1482
       <varname>work_mem</> configuration variable.  Administrators
 
1483
       who have sufficient memory to store larger result sets in
 
1484
       memory should consider increasing this parameter.
 
1485
      </para>
 
1486
     </note>
 
1487
    </sect3>
 
1488
   </sect2>
 
1489
 
 
1490
   <sect2 id="plpgsql-conditionals">
 
1491
    <title>Conditionals</title>
 
1492
 
 
1493
    <para>
 
1494
     <literal>IF</> statements let you execute commands based on
 
1495
     certain conditions.  <application>PL/pgSQL</> has five forms of
 
1496
     <literal>IF</>:
 
1497
    <itemizedlist>
 
1498
     <listitem>
 
1499
      <para><literal>IF ... THEN</></>
 
1500
     </listitem>
 
1501
     <listitem>
 
1502
      <para><literal>IF ... THEN ... ELSE</></>
 
1503
     </listitem>
 
1504
     <listitem>
 
1505
      <para><literal>IF ... THEN ... ELSE IF</></>
 
1506
     </listitem>
 
1507
     <listitem>
 
1508
      <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
 
1509
     </listitem>
 
1510
     <listitem>
 
1511
      <para><literal>IF ... THEN ... ELSEIF ... THEN ... ELSE</></>
 
1512
     </listitem>
 
1513
    </itemizedlist>
 
1514
    </para>
 
1515
 
 
1516
    <sect3>
 
1517
     <title><literal>IF-THEN</></title>
 
1518
 
 
1519
<synopsis>
 
1520
IF <replaceable>boolean-expression</replaceable> THEN
 
1521
    <replaceable>statements</replaceable>
 
1522
END IF;
 
1523
</synopsis>
 
1524
 
 
1525
       <para>
 
1526
        <literal>IF-THEN</literal> statements are the simplest form of
 
1527
        <literal>IF</literal>. The statements between
 
1528
        <literal>THEN</literal> and <literal>END IF</literal> will be
 
1529
        executed if the condition is true. Otherwise, they are
 
1530
        skipped.
 
1531
       </para>
 
1532
 
 
1533
       <para>
 
1534
        Example:
 
1535
<programlisting>
 
1536
IF v_user_id &lt;&gt; 0 THEN
 
1537
    UPDATE users SET email = v_email WHERE user_id = v_user_id;
 
1538
END IF;
 
1539
</programlisting>
 
1540
       </para>
 
1541
     </sect3>
 
1542
 
 
1543
     <sect3>
 
1544
      <title><literal>IF-THEN-ELSE</></title>
 
1545
 
 
1546
<synopsis>
 
1547
IF <replaceable>boolean-expression</replaceable> THEN
 
1548
    <replaceable>statements</replaceable>
 
1549
ELSE
 
1550
    <replaceable>statements</replaceable>
 
1551
END IF;
 
1552
</synopsis>
 
1553
 
 
1554
       <para>
 
1555
        <literal>IF-THEN-ELSE</literal> statements add to
 
1556
        <literal>IF-THEN</literal> by letting you specify an
 
1557
        alternative set of statements that should be executed if the
 
1558
        condition evaluates to false.
 
1559
       </para>
 
1560
 
 
1561
       <para>
 
1562
        Examples:
 
1563
<programlisting>
 
1564
IF parentid IS NULL OR parentid = ''
 
1565
THEN
 
1566
    RETURN fullname;
 
1567
ELSE
 
1568
    RETURN hp_true_filename(parentid) || '/' || fullname;
 
1569
END IF;
 
1570
</programlisting>
 
1571
 
 
1572
<programlisting>
 
1573
IF v_count &gt; 0 THEN 
 
1574
    INSERT INTO users_count (count) VALUES (v_count);
 
1575
    RETURN 't';
 
1576
ELSE
 
1577
    RETURN 'f';
 
1578
END IF;
 
1579
</programlisting>
 
1580
     </para>
 
1581
    </sect3>
 
1582
 
 
1583
     <sect3>
 
1584
      <title><literal>IF-THEN-ELSE IF</></title>
 
1585
 
 
1586
       <para>
 
1587
        <literal>IF</literal> statements can be nested, as in the
 
1588
        following example:
 
1589
 
 
1590
<programlisting>
 
1591
IF demo_row.sex = 'm' THEN
 
1592
    pretty_sex := 'man';
 
1593
ELSE
 
1594
    IF demo_row.sex = 'f' THEN
 
1595
        pretty_sex := 'woman';
 
1596
    END IF;
 
1597
END IF;
 
1598
</programlisting>
 
1599
       </para>
 
1600
 
 
1601
       <para>
 
1602
        When you use this form, you are actually nesting an
 
1603
        <literal>IF</literal> statement inside the
 
1604
        <literal>ELSE</literal> part of an outer <literal>IF</literal>
 
1605
        statement. Thus you need one <literal>END IF</literal>
 
1606
        statement for each nested <literal>IF</literal> and one for the parent
 
1607
        <literal>IF-ELSE</literal>.  This is workable but grows
 
1608
        tedious when there are many alternatives to be checked.
 
1609
        Hence the next form.
 
1610
       </para>
 
1611
     </sect3>
 
1612
 
 
1613
     <sect3>
 
1614
      <title><literal>IF-THEN-ELSIF-ELSE</></title>
 
1615
 
 
1616
<synopsis>
 
1617
IF <replaceable>boolean-expression</replaceable> THEN
 
1618
    <replaceable>statements</replaceable>
 
1619
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
 
1620
    <replaceable>statements</replaceable>
 
1621
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
 
1622
    <replaceable>statements</replaceable>
 
1623
    ...
 
1624
</optional>
 
1625
</optional>
 
1626
<optional> ELSE
 
1627
    <replaceable>statements</replaceable> </optional>
 
1628
END IF;
 
1629
</synopsis>
 
1630
 
 
1631
       <para>
 
1632
        <literal>IF-THEN-ELSIF-ELSE</> provides a more convenient
 
1633
        method of checking many alternatives in one statement.
 
1634
        Formally it is equivalent to nested
 
1635
        <literal>IF-THEN-ELSE-IF-THEN</> commands, but only one
 
1636
        <literal>END IF</> is needed.
 
1637
       </para>
 
1638
 
 
1639
       <para>
 
1640
        Here is an example:
 
1641
 
 
1642
<programlisting>
 
1643
IF number = 0 THEN
 
1644
    result := 'zero';
 
1645
ELSIF number &gt; 0 THEN 
 
1646
    result := 'positive';
 
1647
ELSIF number &lt; 0 THEN
 
1648
    result := 'negative';
 
1649
ELSE
 
1650
    -- hmm, the only other possibility is that number is null
 
1651
    result := 'NULL';
 
1652
END IF;
 
1653
</programlisting>
 
1654
       </para>
 
1655
     </sect3>
 
1656
 
 
1657
     <sect3>
 
1658
      <title><literal>IF-THEN-ELSEIF-ELSE</></title>
 
1659
 
 
1660
      <para>
 
1661
       <literal>ELSEIF</> is an alias for <literal>ELSIF</>.
 
1662
      </para>
 
1663
     </sect3>
 
1664
   </sect2>
 
1665
 
 
1666
   <sect2 id="plpgsql-control-structures-loops">
 
1667
    <title>Simple Loops</title>
 
1668
 
 
1669
    <indexterm zone="plpgsql-control-structures-loops">
 
1670
     <primary>loop</primary>
 
1671
     <secondary>in PL/pgSQL</secondary>
 
1672
    </indexterm>
 
1673
 
 
1674
    <para>
 
1675
     With the <literal>LOOP</>, <literal>EXIT</>, <literal>WHILE</>,
 
1676
     and <literal>FOR</> statements, you can arrange for your
 
1677
     <application>PL/pgSQL</application> function to repeat a series
 
1678
     of commands.
 
1679
    </para>
 
1680
 
 
1681
    <sect3>
 
1682
     <title><literal>LOOP</></title>
 
1683
 
 
1684
<synopsis>
 
1685
<optional>&lt;&lt;<replaceable>label</replaceable>&gt;&gt;</optional>
 
1686
LOOP
 
1687
    <replaceable>statements</replaceable>
 
1688
END LOOP;
 
1689
</synopsis>
 
1690
 
 
1691
     <para>
 
1692
      <literal>LOOP</> defines an unconditional loop that is repeated indefinitely
 
1693
      until terminated by an <literal>EXIT</> or <command>RETURN</command>
 
1694
      statement.  The optional label can be used by <literal>EXIT</> statements in
 
1695
      nested loops to specify which level of nesting should be
 
1696
      terminated.
 
1697
     </para>
 
1698
    </sect3>
 
1699
 
 
1700
     <sect3>
 
1701
      <title><literal>EXIT</></title>
 
1702
 
 
1703
<synopsis>
 
1704
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>expression</replaceable> </optional>;
 
1705
</synopsis>
 
1706
 
 
1707
       <para>
 
1708
        If no <replaceable>label</replaceable> is given,
 
1709
        the innermost loop is terminated and the
 
1710
        statement following <literal>END LOOP</> is executed next.
 
1711
        If <replaceable>label</replaceable> is given, it
 
1712
        must be the label of the current or some outer level of nested loop
 
1713
        or block. Then the named loop or block is terminated and control
 
1714
        continues with the statement after the loop's/block's corresponding
 
1715
        <literal>END</>.
 
1716
       </para>
 
1717
 
 
1718
       <para>
 
1719
        If <literal>WHEN</> is present, loop exit occurs only if the specified
 
1720
        condition is true, otherwise control passes to the statement after
 
1721
        <literal>EXIT</>.
 
1722
       </para>
 
1723
 
 
1724
       <para>
 
1725
        <literal>EXIT</> can be used to cause early exit from all types of
 
1726
        loops; it is not limited to use with unconditional loops.
 
1727
       </para>
 
1728
 
 
1729
       <para>
 
1730
        Examples:
 
1731
<programlisting>
 
1732
LOOP
 
1733
    -- some computations
 
1734
    IF count &gt; 0 THEN
 
1735
        EXIT;  -- exit loop
 
1736
    END IF;
 
1737
END LOOP;
 
1738
 
 
1739
LOOP
 
1740
    -- some computations
 
1741
    EXIT WHEN count &gt; 0;  -- same result as previous example
 
1742
END LOOP;
 
1743
 
 
1744
BEGIN
 
1745
    -- some computations
 
1746
    IF stocks &gt; 100000 THEN
 
1747
        EXIT;  -- causes exit from the BEGIN block
 
1748
    END IF;
 
1749
END;
 
1750
</programlisting>
 
1751
       </para>
 
1752
     </sect3>
 
1753
 
 
1754
     <sect3>
 
1755
      <title><literal>WHILE</></title>
 
1756
 
 
1757
<synopsis>
 
1758
<optional>&lt;&lt;<replaceable>label</replaceable>&gt;&gt;</optional>
 
1759
WHILE <replaceable>expression</replaceable> LOOP
 
1760
    <replaceable>statements</replaceable>
 
1761
END LOOP;
 
1762
</synopsis>
 
1763
 
 
1764
       <para>
 
1765
        The <literal>WHILE</> statement repeats a
 
1766
        sequence of statements so long as the condition expression
 
1767
        evaluates to true.  The condition is checked just before
 
1768
        each entry to the loop body.
 
1769
       </para>
 
1770
 
 
1771
       <para>
 
1772
        For example:
 
1773
<programlisting>
 
1774
WHILE amount_owed &gt; 0 AND gift_certificate_balance &gt; 0 LOOP
 
1775
    -- some computations here
 
1776
END LOOP;
 
1777
 
 
1778
WHILE NOT boolean_expression LOOP
 
1779
    -- some computations here
 
1780
END LOOP;
 
1781
</programlisting>
 
1782
       </para>
 
1783
     </sect3>
 
1784
 
 
1785
     <sect3>
 
1786
      <title><literal>FOR</> (integer variant)</title>
 
1787
 
 
1788
<synopsis>
 
1789
<optional>&lt;&lt;<replaceable>label</replaceable>&gt;&gt;</optional>
 
1790
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
 
1791
    <replaceable>statements</replaceable>
 
1792
END LOOP;
 
1793
</synopsis>
 
1794
 
 
1795
       <para>
 
1796
        This form of <literal>FOR</> creates a loop that iterates over a range of integer
 
1797
        values. The variable 
 
1798
        <replaceable>name</replaceable> is automatically defined as type
 
1799
        <type>integer</> and exists only inside the loop. The two expressions giving
 
1800
        the lower and upper bound of the range are evaluated once when entering
 
1801
        the loop. The iteration step is normally 1, but is -1 when <literal>REVERSE</> is
 
1802
        specified.
 
1803
       </para>
 
1804
 
 
1805
       <para>
 
1806
        Some examples of integer <literal>FOR</> loops:
 
1807
<programlisting>
 
1808
FOR i IN 1..10 LOOP
 
1809
    -- some computations here
 
1810
    RAISE NOTICE 'i is %', i;
 
1811
END LOOP;
 
1812
 
 
1813
FOR i IN REVERSE 10..1 LOOP
 
1814
    -- some computations here
 
1815
END LOOP;
 
1816
</programlisting>
 
1817
       </para>
 
1818
 
 
1819
       <para>
 
1820
        If the lower bound is greater than the upper bound (or less than,
 
1821
        in the <literal>REVERSE</> case), the loop body is not
 
1822
        executed at all.  No error is raised.
 
1823
       </para>
 
1824
     </sect3>
 
1825
   </sect2>
 
1826
 
 
1827
   <sect2 id="plpgsql-records-iterating">
 
1828
    <title>Looping Through Query Results</title>
 
1829
 
 
1830
    <para>
 
1831
     Using a different type of <literal>FOR</> loop, you can iterate through
 
1832
     the results of a query and manipulate that data
 
1833
     accordingly. The syntax is:
 
1834
<synopsis>
 
1835
<optional>&lt;&lt;<replaceable>label</replaceable>&gt;&gt;</optional>
 
1836
FOR <replaceable>record_or_row</replaceable> IN <replaceable>query</replaceable> LOOP
 
1837
    <replaceable>statements</replaceable>
 
1838
END LOOP;
 
1839
</synopsis>
 
1840
     The record or row variable is successively assigned each row
 
1841
     resulting from the <replaceable>query</replaceable> (which must be a
 
1842
     <command>SELECT</command> command) and the loop body is executed for each
 
1843
     row. Here is an example:
 
1844
<programlisting>
 
1845
CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
 
1846
DECLARE
 
1847
    mviews RECORD;
 
1848
BEGIN
 
1849
    PERFORM cs_log('Refreshing materialized views...');
 
1850
 
 
1851
    FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
 
1852
 
 
1853
        -- Now "mviews" has one record from cs_materialized_views
 
1854
 
 
1855
        PERFORM cs_log('Refreshing materialized view ' || quote_ident(mviews.mv_name) || ' ...');
 
1856
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
 
1857
        EXECUTE 'INSERT INTO ' || quote_ident(mviews.mv_name) || ' ' || mviews.mv_query;
 
1858
    END LOOP;
 
1859
 
 
1860
    PERFORM cs_log('Done refreshing materialized views.');
 
1861
    RETURN 1;
 
1862
END;
 
1863
$$ LANGUAGE plpgsql;
 
1864
</programlisting>
 
1865
 
 
1866
     If the loop is terminated by an <literal>EXIT</> statement, the last
 
1867
     assigned row value is still accessible after the loop.
 
1868
    </para>
 
1869
 
 
1870
    <para>
 
1871
     The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
 
1872
     rows:
 
1873
<synopsis>
 
1874
<optional>&lt;&lt;<replaceable>label</replaceable>&gt;&gt;</optional>
 
1875
FOR <replaceable>record_or_row</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> LOOP 
 
1876
    <replaceable>statements</replaceable>
 
1877
END LOOP;
 
1878
</synopsis>
 
1879
     This is like the previous form, except that the source
 
1880
     <command>SELECT</command> statement is specified as a string
 
1881
     expression, which is evaluated and replanned on each entry to
 
1882
     the <literal>FOR</> loop.  This allows the programmer to choose the speed of
 
1883
     a preplanned query or the flexibility of a dynamic query, just
 
1884
     as with a plain <command>EXECUTE</command> statement.
 
1885
    </para>
 
1886
 
 
1887
    <note>
 
1888
    <para>
 
1889
     The <application>PL/pgSQL</> parser presently distinguishes the
 
1890
     two kinds of <literal>FOR</> loops (integer or query result) by checking
 
1891
     whether <literal>..</> appears outside any parentheses between
 
1892
     <literal>IN</> and <literal>LOOP</>.  If <literal>..</> is not seen then
 
1893
     the loop is presumed to be a loop over rows.  Mistyping the <literal>..</>
 
1894
     is thus likely to lead to a complaint along the lines of
 
1895
     <quote>loop variable of loop over rows must be a record or row variable</>,
 
1896
     rather than the simple syntax error one might expect to get.
 
1897
    </para>
 
1898
    </note>
 
1899
   </sect2>
 
1900
 
 
1901
   <sect2 id="plpgsql-error-trapping">
 
1902
    <title>Trapping Errors</title>
 
1903
 
 
1904
    <para>
 
1905
     By default, any error occurring in a <application>PL/pgSQL</>
 
1906
     function aborts execution of the function, and indeed of the
 
1907
     surrounding transaction as well.  You can trap errors and recover
 
1908
     from them by using a <command>BEGIN</> block with an
 
1909
     <literal>EXCEPTION</> clause.  The syntax is an extension of the
 
1910
     normal syntax for a <command>BEGIN</> block:
 
1911
 
 
1912
<synopsis>
 
1913
<optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
 
1914
<optional> DECLARE
 
1915
    <replaceable>declarations</replaceable> </optional>
 
1916
BEGIN
 
1917
    <replaceable>statements</replaceable>
 
1918
EXCEPTION
 
1919
    WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
 
1920
        <replaceable>handler_statements</replaceable>
 
1921
    <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
 
1922
          <replaceable>handler_statements</replaceable>
 
1923
      ... </optional>
 
1924
END;
 
1925
</synopsis>
 
1926
    </para>
 
1927
 
 
1928
    <para>
 
1929
     If no error occurs, this form of block simply executes all the
 
1930
     <replaceable>statements</replaceable>, and then control passes
 
1931
     to the next statement after <literal>END</>.  But if an error
 
1932
     occurs within the <replaceable>statements</replaceable>, further
 
1933
     processing of the <replaceable>statements</replaceable> is
 
1934
     abandoned, and control passes to the <literal>EXCEPTION</> list.
 
1935
     The list is searched for the first <replaceable>condition</replaceable>
 
1936
     matching the error that occurred.  If a match is found, the
 
1937
     corresponding <replaceable>handler_statements</replaceable> are
 
1938
     executed, and then control passes to the next statement after
 
1939
     <literal>END</>.  If no match is found, the error propagates out
 
1940
     as though the <literal>EXCEPTION</> clause were not there at all:
 
1941
     the error can be caught by an enclosing block with
 
1942
     <literal>EXCEPTION</>, or if there is none it aborts processing
 
1943
     of the function.
 
1944
    </para>
 
1945
 
 
1946
    <para>
 
1947
     The <replaceable>condition</replaceable> names can be any of those
 
1948
     shown in <xref linkend="errcodes-appendix">.  A category name matches
 
1949
     any error within its category.
 
1950
     The special condition name <literal>OTHERS</>
 
1951
     matches every error type except <literal>QUERY_CANCELED</>.
 
1952
     (It is possible, but often unwise, to trap
 
1953
     <literal>QUERY_CANCELED</> by name.)
 
1954
     Condition names are not case-sensitive.
 
1955
    </para>
 
1956
 
 
1957
    <para>
 
1958
     If a new error occurs within the selected
 
1959
     <replaceable>handler_statements</replaceable>, it cannot be caught
 
1960
     by this <literal>EXCEPTION</> clause, but is propagated out.
 
1961
     A surrounding <literal>EXCEPTION</> clause could catch it.
 
1962
    </para>
 
1963
 
 
1964
    <para>
 
1965
     When an error is caught by an <literal>EXCEPTION</> clause,
 
1966
     the local variables of the <application>PL/pgSQL</> function
 
1967
     remain as they were when the error occurred, but all changes
 
1968
     to persistent database state within the block are rolled back.
 
1969
     As an example, consider this fragment:
 
1970
 
 
1971
<programlisting>
 
1972
    INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
 
1973
    BEGIN
 
1974
        UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
 
1975
        x := x + 1;
 
1976
        y := x / 0;
 
1977
    EXCEPTION
 
1978
        WHEN division_by_zero THEN
 
1979
            RAISE NOTICE 'caught division_by_zero';
 
1980
            RETURN x;
 
1981
    END;
 
1982
</programlisting>
 
1983
 
 
1984
     When control reaches the assignment to <literal>y</>, it will
 
1985
     fail with a <literal>division_by_zero</> error.  This will be caught by
 
1986
     the <literal>EXCEPTION</> clause.  The value returned in the
 
1987
     <command>RETURN</> statement will be the incremented value of
 
1988
     <literal>x</>, but the effects of the <command>UPDATE</> command will
 
1989
     have been rolled back.  The <command>INSERT</> command preceding the
 
1990
     block is not rolled back, however, so the end result is that the database
 
1991
     contains <literal>Tom Jones</> not <literal>Joe Jones</>.
 
1992
    </para>
 
1993
 
 
1994
    <tip>
 
1995
     <para>
 
1996
      A block containing an <literal>EXCEPTION</> clause is significantly
 
1997
      more expensive to enter and exit than a block without one.  Therefore,
 
1998
      don't use <literal>EXCEPTION</> without need.
 
1999
     </para>
 
2000
    </tip>
 
2001
  </sect2>
 
2002
  </sect1>
 
2003
 
 
2004
  <sect1 id="plpgsql-cursors">
 
2005
   <title>Cursors</title>
 
2006
 
 
2007
   <indexterm zone="plpgsql-cursors">
 
2008
    <primary>cursor</primary>
 
2009
    <secondary>in PL/pgSQL</secondary>
 
2010
   </indexterm>
 
2011
 
 
2012
   <para>
 
2013
    Rather than executing a whole query at once, it is possible to set
 
2014
    up a <firstterm>cursor</> that encapsulates the query, and then read
 
2015
    the query result a few rows at a time. One reason for doing this is
 
2016
    to avoid memory overrun when the result contains a large number of
 
2017
    rows. (However, <application>PL/pgSQL</> users do not normally need
 
2018
    to worry about that, since <literal>FOR</> loops automatically use a cursor
 
2019
    internally to avoid memory problems.) A more interesting usage is to
 
2020
    return a reference to a cursor that a function has created, allowing the
 
2021
    caller to read the rows. This provides an efficient way to return
 
2022
    large row sets from functions.
 
2023
   </para>
 
2024
 
 
2025
   <sect2 id="plpgsql-cursor-declarations">
 
2026
    <title>Declaring Cursor Variables</title>
 
2027
 
 
2028
    <para>
 
2029
     All access to cursors in <application>PL/pgSQL</> goes through
 
2030
     cursor variables, which are always of the special data type
 
2031
     <type>refcursor</>.  One way to create a cursor variable
 
2032
     is just to declare it as a variable of type <type>refcursor</>.
 
2033
     Another way is to use the cursor declaration syntax,
 
2034
     which in general is:
 
2035
<synopsis>
 
2036
<replaceable>name</replaceable> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable> ;
 
2037
</synopsis>
 
2038
     (<literal>FOR</> may be replaced by <literal>IS</> for
 
2039
     <productname>Oracle</productname> compatibility.)
 
2040
     <replaceable>arguments</replaceable>, if specified, is a
 
2041
     comma-separated list of pairs <literal><replaceable>name</replaceable>
 
2042
     <replaceable>datatype</replaceable></literal> that define names to be
 
2043
     replaced by parameter values in the given query.  The actual
 
2044
     values to substitute for these names will be specified later,
 
2045
     when the cursor is opened.
 
2046
    </para>
 
2047
    <para>
 
2048
     Some examples:
 
2049
<programlisting>
 
2050
DECLARE
 
2051
    curs1 refcursor;
 
2052
    curs2 CURSOR FOR SELECT * FROM tenk1;
 
2053
    curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
 
2054
</programlisting>
 
2055
     All three of these variables have the data type <type>refcursor</>,
 
2056
     but the first may be used with any query, while the second has
 
2057
     a fully specified query already <firstterm>bound</> to it, and the last
 
2058
     has a parameterized query bound to it.  (<literal>key</> will be
 
2059
     replaced by an integer parameter value when the cursor is opened.)
 
2060
     The variable <literal>curs1</>
 
2061
     is said to be <firstterm>unbound</> since it is not bound to
 
2062
     any particular query.
 
2063
    </para>
 
2064
   </sect2>
 
2065
 
 
2066
   <sect2 id="plpgsql-cursor-opening">
 
2067
    <title>Opening Cursors</title>
 
2068
 
 
2069
    <para>
 
2070
     Before a cursor can be used to retrieve rows, it must be
 
2071
     <firstterm>opened</>. (This is the equivalent action to the SQL
 
2072
     command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
 
2073
     three forms of the <command>OPEN</> statement, two of which use unbound
 
2074
     cursor variables while the third uses a bound cursor variable.
 
2075
    </para>
 
2076
 
 
2077
    <sect3>
 
2078
     <title><command>OPEN FOR SELECT</command></title>
 
2079
 
 
2080
<synopsis>
 
2081
OPEN <replaceable>unbound_cursor</replaceable> FOR SELECT ...;
 
2082
</synopsis>
 
2083
 
 
2084
       <para>
 
2085
    The cursor variable is opened and given the specified query to
 
2086
        execute.  The cursor cannot be open already, and it must have been
 
2087
        declared as an unbound cursor (that is, as a simple
 
2088
        <type>refcursor</> variable).  The <command>SELECT</command> query
 
2089
        is treated in the same way as other <command>SELECT</command>
 
2090
        statements in <application>PL/pgSQL</>: <application>PL/pgSQL</>
 
2091
        variable names are substituted, and the query plan is cached for
 
2092
        possible reuse.
 
2093
       </para>
 
2094
 
 
2095
       <para>
 
2096
        An example:
 
2097
<programlisting>
 
2098
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
 
2099
</programlisting>
 
2100
       </para>
 
2101
     </sect3>
 
2102
 
 
2103
    <sect3>
 
2104
     <title><command>OPEN FOR EXECUTE</command></title>
 
2105
 
 
2106
<synopsis>
 
2107
OPEN <replaceable>unbound_cursor</replaceable> FOR EXECUTE <replaceable class="command">query_string</replaceable>;
 
2108
</synopsis>
 
2109
 
 
2110
         <para>
 
2111
          The cursor variable is opened and given the specified query to
 
2112
          execute.  The cursor cannot be open already, and it must have been
 
2113
          declared as an unbound cursor (that is, as a simple
 
2114
          <type>refcursor</> variable).  The query is specified as a string
 
2115
          expression in the same way as in the <command>EXECUTE</command>
 
2116
          command.  As usual, this gives flexibility so the query can vary
 
2117
          from one run to the next.
 
2118
       </para>
 
2119
 
 
2120
       <para>
 
2121
        An example:
 
2122
<programlisting>
 
2123
OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident($1);
 
2124
</programlisting>
 
2125
       </para>
 
2126
     </sect3>
 
2127
 
 
2128
    <sect3>
 
2129
     <title>Opening a Bound Cursor</title>
 
2130
 
 
2131
<synopsis>
 
2132
OPEN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
 
2133
</synopsis>
 
2134
 
 
2135
         <para>
 
2136
          This form of <command>OPEN</command> is used to open a cursor
 
2137
          variable whose query was bound to it when it was declared.  The
 
2138
          cursor cannot be open already.  A list of actual argument value
 
2139
          expressions must appear if and only if the cursor was declared to
 
2140
          take arguments.  These values will be substituted in the query.
 
2141
          The query plan for a bound cursor is always considered cacheable;
 
2142
          there is no equivalent of <command>EXECUTE</command> in this case.
 
2143
         </para>
 
2144
 
 
2145
    <para>
 
2146
     Examples:
 
2147
<programlisting>
 
2148
OPEN curs2;
 
2149
OPEN curs3(42);
 
2150
</programlisting>
 
2151
       </para>
 
2152
     </sect3>
 
2153
   </sect2>
 
2154
 
 
2155
   <sect2 id="plpgsql-cursor-using">
 
2156
    <title>Using Cursors</title>
 
2157
 
 
2158
    <para>
 
2159
     Once a cursor has been opened, it can be manipulated with the
 
2160
     statements described here.
 
2161
    </para>
 
2162
 
 
2163
    <para>
 
2164
     These manipulations need not occur in the same function that
 
2165
     opened the cursor to begin with.  You can return a <type>refcursor</>
 
2166
     value out of a function and let the caller operate on the cursor.
 
2167
     (Internally, a <type>refcursor</> value is simply the string name
 
2168
     of a so-called portal containing the active query for the cursor.  This name
 
2169
     can be passed around, assigned to other <type>refcursor</> variables,
 
2170
     and so on, without disturbing the portal.)
 
2171
    </para>
 
2172
 
 
2173
    <para>
 
2174
     All portals are implicitly closed at transaction end.  Therefore
 
2175
     a <type>refcursor</> value is usable to reference an open cursor
 
2176
     only until the end of the transaction.
 
2177
    </para>
 
2178
 
 
2179
    <sect3>
 
2180
     <title><literal>FETCH</></title>
 
2181
 
 
2182
<synopsis>
 
2183
FETCH <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
 
2184
</synopsis>
 
2185
 
 
2186
         <para>
 
2187
          <command>FETCH</command> retrieves the next row from the
 
2188
          cursor into a target, which may be a row variable, a record
 
2189
          variable, or a comma-separated list of simple variables, just like
 
2190
          <command>SELECT INTO</command>.  As with <command>SELECT
 
2191
           INTO</command>, the special variable <literal>FOUND</literal> may
 
2192
          be checked to see whether a row was obtained or not.
 
2193
         </para>
 
2194
 
 
2195
    <para>
 
2196
     An example:
 
2197
<programlisting>
 
2198
FETCH curs1 INTO rowvar;
 
2199
FETCH curs2 INTO foo, bar, baz;
 
2200
</programlisting>
 
2201
       </para>
 
2202
     </sect3>
 
2203
 
 
2204
    <sect3>
 
2205
     <title><literal>CLOSE</></title>
 
2206
 
 
2207
<synopsis>
 
2208
CLOSE <replaceable>cursor</replaceable>;
 
2209
</synopsis>
 
2210
 
 
2211
       <para>
 
2212
        <command>CLOSE</command> closes the portal underlying an open
 
2213
        cursor.  This can be used to release resources earlier than end of
 
2214
        transaction, or to free up the cursor variable to be opened again.
 
2215
       </para>
 
2216
 
 
2217
       <para>
 
2218
        An example:
 
2219
<programlisting>
 
2220
CLOSE curs1;
 
2221
</programlisting>
 
2222
       </para>
 
2223
     </sect3>
 
2224
 
 
2225
    <sect3>
 
2226
     <title>Returning Cursors</title>
 
2227
 
 
2228
       <para>
 
2229
        <application>PL/pgSQL</> functions can return cursors to the
 
2230
        caller. This is useful to return multiple rows or columns,
 
2231
        especially with very large result sets.  To do this, the function
 
2232
        opens the cursor and returns the cursor name to the caller (or simply
 
2233
        opens the cursor using a portal name specified by or otherwise known
 
2234
        to the caller).  The caller can then fetch rows from the cursor. The
 
2235
        cursor can be closed by the caller, or it will be closed automatically
 
2236
        when the transaction closes.
 
2237
       </para>
 
2238
 
 
2239
       <para>
 
2240
        The portal name used for a cursor can be specified by the
 
2241
        programmer or automatically generated.  To specify a portal name,
 
2242
        simply assign a string to the <type>refcursor</> variable before
 
2243
        opening it.  The string value of the <type>refcursor</> variable
 
2244
        will be used by <command>OPEN</> as the name of the underlying portal.
 
2245
        However, if the <type>refcursor</> variable is null,
 
2246
        <command>OPEN</> automatically generates a name that does not
 
2247
        conflict with any existing portal, and assigns it to the
 
2248
        <type>refcursor</> variable.
 
2249
       </para>
 
2250
 
 
2251
       <note>
 
2252
        <para>
 
2253
         A bound cursor variable is initialized to the string value
 
2254
         representing its name, so that the portal name is the same as
 
2255
         the cursor variable name, unless the programmer overrides it
 
2256
         by assignment before opening the cursor.  But an unbound cursor
 
2257
         variable defaults to the null value initially , so it will receive
 
2258
         an automatically-generated unique name, unless overridden.
 
2259
        </para>
 
2260
       </note>
 
2261
 
 
2262
       <para>
 
2263
        The following example shows one way a cursor name can be supplied by
 
2264
        the caller:
 
2265
 
 
2266
<programlisting>
 
2267
CREATE TABLE test (col text);
 
2268
INSERT INTO test VALUES ('123');
 
2269
 
 
2270
CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
 
2271
BEGIN
 
2272
    OPEN $1 FOR SELECT col FROM test;
 
2273
    RETURN $1;
 
2274
END;
 
2275
' LANGUAGE plpgsql;
 
2276
 
 
2277
BEGIN;
 
2278
SELECT reffunc('funccursor');
 
2279
FETCH ALL IN funccursor;
 
2280
COMMIT;
 
2281
</programlisting>
 
2282
       </para>
 
2283
 
 
2284
       <para>
 
2285
        The following example uses automatic cursor name generation:
 
2286
 
 
2287
<programlisting>
 
2288
CREATE FUNCTION reffunc2() RETURNS refcursor AS '
 
2289
DECLARE
 
2290
    ref refcursor;
 
2291
BEGIN
 
2292
    OPEN ref FOR SELECT col FROM test;
 
2293
    RETURN ref;
 
2294
END;
 
2295
' LANGUAGE plpgsql;
 
2296
 
 
2297
BEGIN;
 
2298
SELECT reffunc2();
 
2299
 
 
2300
      reffunc2      
 
2301
--------------------
 
2302
 &lt;unnamed cursor 1&gt;
 
2303
(1 row)
 
2304
 
 
2305
FETCH ALL IN "&lt;unnamed cursor 1&gt;";
 
2306
COMMIT;
 
2307
</programlisting>
 
2308
       </para>
 
2309
 
 
2310
       <para>
 
2311
        The following example shows one way to return multiple cursors
 
2312
        from a single function:
 
2313
 
 
2314
<programlisting>
 
2315
CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
 
2316
BEGIN
 
2317
    OPEN $1 FOR SELECT * FROM table_1;
 
2318
    RETURN NEXT $1;
 
2319
    OPEN $2 FOR SELECT * FROM table_2;
 
2320
    RETURN NEXT $2;
 
2321
    RETURN;
 
2322
END;
 
2323
$$ LANGUAGE plpgsql;
 
2324
 
 
2325
-- need to be in a transaction to use cursors.
 
2326
BEGIN;
 
2327
 
 
2328
SELECT * FROM myfunc('a', 'b');
 
2329
 
 
2330
FETCH ALL FROM a;
 
2331
FETCH ALL FROM b;
 
2332
COMMIT;
 
2333
</programlisting>
 
2334
       </para>
 
2335
     </sect3>
 
2336
   </sect2>
 
2337
  </sect1>
 
2338
 
 
2339
  <sect1 id="plpgsql-errors-and-messages">
 
2340
   <title>Errors and Messages</title>
 
2341
 
 
2342
   <para>
 
2343
    Use the <command>RAISE</command> statement to report messages and
 
2344
    raise errors.
 
2345
 
 
2346
<synopsis>
 
2347
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">variable</replaceable> <optional>, ...</optional></optional>;
 
2348
</synopsis>
 
2349
 
 
2350
    Possible levels are <literal>DEBUG</literal>,
 
2351
    <literal>LOG</literal>, <literal>INFO</literal>,
 
2352
    <literal>NOTICE</literal>, <literal>WARNING</literal>,
 
2353
    and <literal>EXCEPTION</literal>.
 
2354
    <literal>EXCEPTION</literal> raises an error (which normally aborts the
 
2355
    current transaction); the other levels only generate messages of different
 
2356
    priority levels.
 
2357
    Whether messages of a particular priority are reported to the client,
 
2358
    written to the server log, or both is controlled by the
 
2359
    <xref linkend="guc-log-min-messages"> and
 
2360
    <xref linkend="guc-client-min-messages"> configuration
 
2361
    variables. See <xref linkend="runtime-config"> for more
 
2362
    information.
 
2363
   </para>
 
2364
 
 
2365
   <para>
 
2366
    Inside the format string, <literal>%</literal> is replaced by the
 
2367
    next optional argument's string representation. Write
 
2368
    <literal>%%</literal> to emit a literal <literal>%</literal>. Note
 
2369
    that the optional arguments must presently be simple variables,
 
2370
    not expressions, and the format must be a simple string literal.
 
2371
   </para>
 
2372
 
 
2373
   <!--
 
2374
   This example should work, but does not:
 
2375
        RAISE NOTICE 'Id number ' || key || ' not found!';
 
2376
   Put it back when we allow non-string-literal formats.
 
2377
    -->
 
2378
 
 
2379
   <para>
 
2380
    In this example, the value of <literal>v_job_id</> will replace the
 
2381
    <literal>%</literal> in the string:
 
2382
<programlisting>
 
2383
RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
 
2384
</programlisting>
 
2385
   </para>
 
2386
 
 
2387
   <para>
 
2388
    This example will abort the transaction with the given error message:
 
2389
<programlisting>
 
2390
RAISE EXCEPTION 'Nonexistent ID --> %', user_id;
 
2391
</programlisting>
 
2392
   </para>
 
2393
 
 
2394
    <para>
 
2395
     <command>RAISE EXCEPTION</command> presently always generates
 
2396
     the same SQLSTATE code, <literal>P0001</>, no matter what message
 
2397
     it is invoked with.  It is possible to trap this exception with
 
2398
     <literal>EXCEPTION ... WHEN RAISE_EXCEPTION THEN ...</> but there
 
2399
     is no way to tell one <command>RAISE</> from another.
 
2400
    </para>
 
2401
 </sect1>
 
2402
 
 
2403
 <sect1 id="plpgsql-trigger">
 
2404
  <title>Trigger Procedures</title>
 
2405
 
 
2406
  <indexterm zone="plpgsql-trigger">
 
2407
   <primary>trigger</primary>
 
2408
   <secondary>in PL/pgSQL</secondary>
 
2409
  </indexterm>
 
2410
 
 
2411
  <para>
 
2412
        <application>PL/pgSQL</application> can be used to define trigger
 
2413
        procedures. A trigger procedure is created with the
 
2414
        <command>CREATE FUNCTION</> command, declaring it as a function with
 
2415
        no arguments and a return type of <type>trigger</type>.  Note that
 
2416
        the function must be declared with no arguments even if it expects
 
2417
        to receive arguments specified in <command>CREATE TRIGGER</> &mdash;
 
2418
        trigger arguments are passed via <varname>TG_ARGV</>, as described
 
2419
        below.
 
2420
  </para>
 
2421
 
 
2422
  <para>
 
2423
   When a <application>PL/pgSQL</application> function is called as a
 
2424
   trigger, several special variables are created automatically in the 
 
2425
   top-level block. They are:
 
2426
 
 
2427
   <variablelist>
 
2428
    <varlistentry>
 
2429
     <term><varname>NEW</varname></term>
 
2430
     <listitem>
 
2431
      <para>
 
2432
       Data type <type>RECORD</type>; variable holding the new
 
2433
       database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
 
2434
       triggers. This variable is <symbol>NULL</symbol> in statement-level triggers.
 
2435
      </para>
 
2436
     </listitem>
 
2437
    </varlistentry>
 
2438
 
 
2439
    <varlistentry>
 
2440
     <term><varname>OLD</varname></term>
 
2441
     <listitem>
 
2442
      <para>
 
2443
       Data type <type>RECORD</type>; variable holding the old
 
2444
       database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
 
2445
       triggers. This variable is <symbol>NULL</symbol> in statement-level triggers.
 
2446
      </para>
 
2447
     </listitem>
 
2448
    </varlistentry>
 
2449
 
 
2450
    <varlistentry>
 
2451
     <term><varname>TG_NAME</varname></term>
 
2452
     <listitem>
 
2453
      <para>
 
2454
       Data type <type>name</type>; variable that contains the name of the trigger actually
 
2455
       fired.
 
2456
      </para>
 
2457
     </listitem>
 
2458
    </varlistentry>
 
2459
 
 
2460
    <varlistentry>
 
2461
     <term><varname>TG_WHEN</varname></term>
 
2462
     <listitem>
 
2463
      <para>
 
2464
       Data type <type>text</type>; a string of either 
 
2465
              <literal>BEFORE</literal> or <literal>AFTER</literal>
 
2466
              depending on the trigger's definition.
 
2467
      </para>
 
2468
     </listitem>
 
2469
    </varlistentry>
 
2470
 
 
2471
    <varlistentry>
 
2472
     <term><varname>TG_LEVEL</varname></term>
 
2473
     <listitem>
 
2474
      <para>
 
2475
       Data type <type>text</type>; a string of either
 
2476
       <literal>ROW</literal> or <literal>STATEMENT</literal>
 
2477
       depending on the trigger's definition.
 
2478
      </para>
 
2479
     </listitem>
 
2480
    </varlistentry>
 
2481
 
 
2482
    <varlistentry>
 
2483
     <term><varname>TG_OP</varname></term>
 
2484
     <listitem>
 
2485
      <para>
 
2486
       Data type <type>text</type>; a string of
 
2487
       <literal>INSERT</literal>, <literal>UPDATE</literal>, or
 
2488
       <literal>DELETE</literal> telling for which operation the
 
2489
       trigger was fired.
 
2490
      </para>
 
2491
     </listitem>
 
2492
    </varlistentry>
 
2493
 
 
2494
    <varlistentry>
 
2495
     <term><varname>TG_RELID</varname></term>
 
2496
     <listitem>
 
2497
      <para>
 
2498
       Data type <type>oid</type>; the object ID of the table that caused the
 
2499
       trigger invocation.
 
2500
      </para>
 
2501
     </listitem>
 
2502
    </varlistentry>
 
2503
 
 
2504
    <varlistentry>
 
2505
     <term><varname>TG_RELNAME</varname></term>
 
2506
     <listitem>
 
2507
      <para>
 
2508
       Data type <type>name</type>; the name of the table that caused the trigger
 
2509
       invocation.
 
2510
      </para>
 
2511
     </listitem>
 
2512
    </varlistentry>
 
2513
 
 
2514
    <varlistentry>
 
2515
     <term><varname>TG_NARGS</varname></term>
 
2516
     <listitem>
 
2517
      <para>
 
2518
       Data type <type>integer</type>; the number of arguments given to the trigger
 
2519
       procedure in the <command>CREATE TRIGGER</command> statement.
 
2520
      </para>
 
2521
     </listitem>
 
2522
    </varlistentry>
 
2523
 
 
2524
    <varlistentry>
 
2525
     <term><varname>TG_ARGV[]</varname></term>
 
2526
     <listitem>
 
2527
      <para>
 
2528
       Data type array of <type>text</type>; the arguments from
 
2529
              the <command>CREATE TRIGGER</command> statement.
 
2530
       The index counts from 0. Invalid
 
2531
       indices (less than 0 or greater than or equal to <varname>tg_nargs</>) result in a null value.
 
2532
      </para>
 
2533
     </listitem>
 
2534
    </varlistentry>
 
2535
   </variablelist>
 
2536
  </para>
 
2537
 
 
2538
   <para>
 
2539
    A trigger function must return either <symbol>NULL</symbol> or a
 
2540
    record/row value having exactly the structure of the table the
 
2541
    trigger was fired for.
 
2542
   </para>
 
2543
 
 
2544
   <para>
 
2545
    Row-level triggers fired <literal>BEFORE</> may return null to signal the
 
2546
    trigger manager to skip the rest of the operation for this row
 
2547
    (i.e., subsequent triggers are not fired, and the
 
2548
    <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
 
2549
    for this row).  If a nonnull 
 
2550
    value is returned then the operation proceeds with that row value.
 
2551
    Returning a row value different from the original value
 
2552
    of <varname>NEW</> alters the row that will be inserted or updated
 
2553
    (but has no direct effect in the <command>DELETE</> case).
 
2554
    To alter the row to be stored, it is possible to replace single values
 
2555
    directly in <varname>NEW</> and return the modified <varname>NEW</>,
 
2556
    or to build a complete new record/row to return.
 
2557
   </para>
 
2558
 
 
2559
   <para>
 
2560
    The return value of a <literal>BEFORE</> or <literal>AFTER</>
 
2561
    statement-level trigger or an <literal>AFTER</> row-level trigger is
 
2562
    always ignored; it may as well be null. However, any of these types of
 
2563
    triggers can still abort the entire operation by raising an error.
 
2564
   </para>
 
2565
 
 
2566
   <para>
 
2567
    <xref linkend="plpgsql-trigger-example"> shows an example of a
 
2568
    trigger procedure in <application>PL/pgSQL</application>.
 
2569
   </para>
 
2570
 
 
2571
   <example id="plpgsql-trigger-example">
 
2572
    <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
 
2573
 
 
2574
    <para>
 
2575
     This example trigger ensures that any time a row is inserted or updated
 
2576
     in the table, the current user name and time are stamped into the
 
2577
     row. And it checks that an employee's name is given and that the
 
2578
     salary is a positive value.
 
2579
    </para>
 
2580
 
 
2581
<programlisting>
 
2582
CREATE TABLE emp (
 
2583
    empname text,
 
2584
    salary integer,
 
2585
    last_date timestamp,
 
2586
    last_user text
 
2587
);
 
2588
 
 
2589
CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
 
2590
    BEGIN
 
2591
        -- Check that empname and salary are given
 
2592
        IF NEW.empname IS NULL THEN
 
2593
            RAISE EXCEPTION 'empname cannot be null';
 
2594
        END IF;
 
2595
        IF NEW.salary IS NULL THEN
 
2596
            RAISE EXCEPTION '% cannot have null salary', NEW.empname;
 
2597
        END IF;
 
2598
 
 
2599
        -- Who works for us when she must pay for it?
 
2600
        IF NEW.salary &lt; 0 THEN
 
2601
            RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
 
2602
        END IF;
 
2603
 
 
2604
        -- Remember who changed the payroll when
 
2605
        NEW.last_date := 'now';
 
2606
        NEW.last_user := current_user;
 
2607
        RETURN NEW;
 
2608
    END;
 
2609
$emp_stamp$ LANGUAGE plpgsql;
 
2610
 
 
2611
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
 
2612
    FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
 
2613
</programlisting>
 
2614
   </example>
 
2615
 
 
2616
   <para>
 
2617
    Another way to log changes to a table involves creating a new table that
 
2618
    holds a row for each insert, update, or delete that occurs. This approach
 
2619
    can be thought of as auditing changes to a table.
 
2620
    <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
 
2621
    audit trigger procedure in <application>PL/pgSQL</application>.
 
2622
   </para>
 
2623
 
 
2624
   <example id="plpgsql-trigger-audit-example">
 
2625
    <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
 
2626
 
 
2627
    <para>
 
2628
     This example trigger ensures that any insert, update or delete of a row
 
2629
     in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table. 
 
2630
     The current time and user name are stamped into the row, together with 
 
2631
     the type of operation performed on it.
 
2632
    </para>
 
2633
 
 
2634
<programlisting>
 
2635
CREATE TABLE emp (
 
2636
    empname           text NOT NULL,
 
2637
    salary            integer
 
2638
);
 
2639
 
 
2640
CREATE TABLE emp_audit( 
 
2641
    operation         char(1)   NOT NULL,
 
2642
    stamp             timestamp NOT NULL,
 
2643
    userid            text      NOT NULL,
 
2644
    empname           text      NOT NULL,
 
2645
    salary integer
 
2646
);
 
2647
 
 
2648
CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
 
2649
    BEGIN
 
2650
        --
 
2651
        -- Create a row in emp_audit to reflect the operation performed on emp,
 
2652
        -- make use of the special variable TG_OP to work out the operation.
 
2653
        --
 
2654
        IF (TG_OP = 'DELETE') THEN
 
2655
            INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
 
2656
            RETURN OLD;
 
2657
        ELSIF (TG_OP = 'UPDATE') THEN
 
2658
            INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
 
2659
            RETURN NEW;
 
2660
        ELSIF (TG_OP = 'INSERT') THEN
 
2661
            INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
 
2662
            RETURN NEW;
 
2663
        END IF;
 
2664
        RETURN NULL; -- result is ignored since this is an AFTER trigger
 
2665
    END;
 
2666
$emp_audit$ language plpgsql;
 
2667
 
 
2668
CREATE TRIGGER emp_audit
 
2669
AFTER INSERT OR UPDATE OR DELETE ON emp
 
2670
    FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
 
2671
</programlisting>
 
2672
   </example>
 
2673
 
 
2674
   <para>
 
2675
    One use of triggers is to maintain a summary table
 
2676
    of another table. The resulting summary can be used in place of the 
 
2677
    original table for certain queries &mdash; often with vastly reduced run 
 
2678
    times.
 
2679
    This technique is commonly used in Data Warehousing, where the tables
 
2680
    of measured or observed data (called fact tables) can be extremely large.
 
2681
    <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
 
2682
    trigger procedure in <application>PL/pgSQL</application> that maintains
 
2683
    a summary table for a fact table in a data warehouse.
 
2684
   </para>
 
2685
 
 
2686
 
 
2687
   <example id="plpgsql-trigger-summary-example">
 
2688
    <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
 
2689
 
 
2690
    <para>
 
2691
     The schema detailed here is partly based on the <emphasis>Grocery Store
 
2692
     </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis> 
 
2693
     by Ralph Kimball.
 
2694
    </para>
 
2695
 
 
2696
<programlisting>
 
2697
--
 
2698
-- Main tables - time dimension and sales fact.
 
2699
--
 
2700
CREATE TABLE time_dimension (
 
2701
    time_key                    integer NOT NULL,
 
2702
    day_of_week                 integer NOT NULL,
 
2703
    day_of_month                integer NOT NULL,
 
2704
    month                       integer NOT NULL,
 
2705
    quarter                     integer NOT NULL,
 
2706
    year                        integer NOT NULL
 
2707
);
 
2708
CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
 
2709
 
 
2710
CREATE TABLE sales_fact (
 
2711
    time_key                    integer NOT NULL,
 
2712
    product_key                 integer NOT NULL,
 
2713
    store_key                   integer NOT NULL,
 
2714
    amount_sold                 numeric(12,2) NOT NULL,
 
2715
    units_sold                  integer NOT NULL,
 
2716
    amount_cost                 numeric(12,2) NOT NULL
 
2717
);
 
2718
CREATE INDEX sales_fact_time ON sales_fact(time_key);
 
2719
 
 
2720
--
 
2721
-- Summary table - sales by time.
 
2722
--
 
2723
CREATE TABLE sales_summary_bytime (
 
2724
    time_key                    integer NOT NULL,
 
2725
    amount_sold                 numeric(15,2) NOT NULL,
 
2726
    units_sold                  numeric(12) NOT NULL,
 
2727
    amount_cost                 numeric(15,2) NOT NULL
 
2728
);
 
2729
CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
 
2730
 
 
2731
--
 
2732
-- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
 
2733
--
 
2734
CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER AS $maint_sales_summary_bytime$
 
2735
    DECLARE
 
2736
        delta_time_key          integer;
 
2737
        delta_amount_sold       numeric(15,2);
 
2738
        delta_units_sold        numeric(12);
 
2739
        delta_amount_cost       numeric(15,2);
 
2740
    BEGIN
 
2741
 
 
2742
        -- Work out the increment/decrement amount(s).
 
2743
        IF (TG_OP = 'DELETE') THEN
 
2744
 
 
2745
            delta_time_key = OLD.time_key;
 
2746
            delta_amount_sold = -1 * OLD.amount_sold;
 
2747
            delta_units_sold = -1 * OLD.units_sold;
 
2748
            delta_amount_cost = -1 * OLD.amount_cost;
 
2749
 
 
2750
        ELSIF (TG_OP = 'UPDATE') THEN
 
2751
 
 
2752
            -- forbid updates that change the time_key -
 
2753
            -- (probably not too onerous, as DELETE + INSERT is how most 
 
2754
            -- changes will be made).
 
2755
            IF ( OLD.time_key != NEW.time_key) THEN
 
2756
                RAISE EXCEPTION 'Update of time_key : % -&gt; % not allowed', OLD.time_key, NEW.time_key;
 
2757
            END IF;
 
2758
 
 
2759
            delta_time_key = OLD.time_key;
 
2760
            delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
 
2761
            delta_units_sold = NEW.units_sold - OLD.units_sold;
 
2762
            delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
 
2763
 
 
2764
        ELSIF (TG_OP = 'INSERT') THEN
 
2765
 
 
2766
            delta_time_key = NEW.time_key;
 
2767
            delta_amount_sold = NEW.amount_sold;
 
2768
            delta_units_sold = NEW.units_sold;
 
2769
            delta_amount_cost = NEW.amount_cost;
 
2770
 
 
2771
        END IF;
 
2772
 
 
2773
 
 
2774
        -- Update the summary row with the new values.
 
2775
        UPDATE sales_summary_bytime
 
2776
            SET amount_sold = amount_sold + delta_amount_sold,
 
2777
                units_sold = units_sold + delta_units_sold,
 
2778
                amount_cost = amount_cost + delta_amount_cost
 
2779
            WHERE time_key = delta_time_key;
 
2780
 
 
2781
 
 
2782
        -- There might have been no row with this time_key (e.g new data!).
 
2783
        IF (NOT FOUND) THEN
 
2784
            BEGIN
 
2785
                INSERT INTO sales_summary_bytime (
 
2786
                            time_key, 
 
2787
                            amount_sold, 
 
2788
                            units_sold, 
 
2789
                            amount_cost)
 
2790
                    VALUES ( 
 
2791
                            delta_time_key,
 
2792
                            delta_amount_sold,
 
2793
                            delta_units_sold,
 
2794
                            delta_amount_cost
 
2795
                           );
 
2796
            EXCEPTION
 
2797
                --
 
2798
                -- Catch race condition when two transactions are adding data
 
2799
                -- for a new time_key.
 
2800
                --
 
2801
                WHEN UNIQUE_VIOLATION THEN
 
2802
                    UPDATE sales_summary_bytime
 
2803
                        SET amount_sold = amount_sold + delta_amount_sold,
 
2804
                            units_sold = units_sold + delta_units_sold,
 
2805
                            amount_cost = amount_cost + delta_amount_cost
 
2806
                        WHERE time_key = delta_time_key;
 
2807
 
 
2808
            END;
 
2809
        END IF;
 
2810
        RETURN NULL;
 
2811
 
 
2812
    END;
 
2813
$maint_sales_summary_bytime$ LANGUAGE plpgsql;
 
2814
 
 
2815
CREATE TRIGGER maint_sales_summary_bytime
 
2816
AFTER INSERT OR UPDATE OR DELETE ON sales_fact
 
2817
    FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
 
2818
</programlisting>
 
2819
   </example>
 
2820
 
 
2821
  </sect1>
 
2822
 
 
2823
  <!-- **** Porting from Oracle PL/SQL **** -->
 
2824
 
 
2825
 <sect1 id="plpgsql-porting">
 
2826
  <title>Porting from <productname>Oracle</productname> PL/SQL</title>
 
2827
 
 
2828
  <indexterm zone="plpgsql-porting">
 
2829
   <primary>Oracle</primary>
 
2830
   <secondary>porting from PL/SQL to PL/pgSQL</secondary>
 
2831
  </indexterm>
 
2832
 
 
2833
  <indexterm zone="plpgsql-porting">
 
2834
   <primary>PL/SQL (Oracle)</primary>
 
2835
   <secondary>porting to PL/pgSQL</secondary>
 
2836
  </indexterm>
 
2837
 
 
2838
  <para>
 
2839
   This section explains differences between
 
2840
   <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
 
2841
   language and Oracle's <application>PL/SQL</application> language,
 
2842
   to help developers who port applications from
 
2843
   <trademark class=registered>Oracle</> to <productname>PostgreSQL</>.
 
2844
  </para>
 
2845
 
 
2846
  <para>
 
2847
   <application>PL/pgSQL</application> is similar to PL/SQL in many
 
2848
   aspects. It is a block-structured, imperative language, and all
 
2849
   variables have to be declared.  Assignments, loops, conditionals
 
2850
   are similar.  The main differences you should keep in mind when
 
2851
   porting from <application>PL/SQL</> to
 
2852
   <application>PL/pgSQL</application> are:
 
2853
 
 
2854
    <itemizedlist>
 
2855
     <listitem>
 
2856
      <para>
 
2857
       There are no default values for parameters in <productname>PostgreSQL</>.
 
2858
      </para>
 
2859
     </listitem>
 
2860
 
 
2861
     <listitem>
 
2862
      <para>
 
2863
       You can overload function names in <productname>PostgreSQL</>. This is
 
2864
       often used to work around the lack of default parameters.
 
2865
      </para>
 
2866
     </listitem>
 
2867
 
 
2868
     <listitem>
 
2869
      <para>
 
2870
       No need for cursors in <application>PL/pgSQL</>, just put the
 
2871
       query in the <literal>FOR</literal> statement.  (See <xref
 
2872
       linkend="plpgsql-porting-ex2">.)
 
2873
      </para>
 
2874
     </listitem>
 
2875
 
 
2876
     <listitem>
 
2877
      <para>
 
2878
       In <productname>PostgreSQL</> you need to use dollar quoting or escape
 
2879
       single quotes in the function body. See <xref
 
2880
       linkend="plpgsql-quote-tips">.
 
2881
      </para>
 
2882
     </listitem>
 
2883
 
 
2884
     <listitem>
 
2885
      <para>
 
2886
       Instead of packages, use schemas to organize your functions
 
2887
       into groups.
 
2888
      </para>
 
2889
     </listitem>
 
2890
 
 
2891
     <listitem>
 
2892
      <para>
 
2893
       Since there are no packages, there are no package-level variables
 
2894
       either. This is somewhat annoying.  You may be able to keep per-session
 
2895
       state in temporary tables, instead.
 
2896
      </para>
 
2897
     </listitem>
 
2898
    </itemizedlist>
 
2899
   </para>
 
2900
 
 
2901
  <sect2>
 
2902
   <title>Porting Examples</title>
 
2903
 
 
2904
   <para>
 
2905
    <xref linkend="pgsql-porting-ex1"> shows how to port a simple
 
2906
    function from <application>PL/SQL</> to <application>PL/pgSQL</>.
 
2907
   </para>
 
2908
 
 
2909
   <example id="pgsql-porting-ex1">
 
2910
    <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
 
2911
 
 
2912
    <para>
 
2913
     Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
 
2914
<programlisting>
 
2915
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name IN varchar,
 
2916
                                                  v_version IN varchar)
 
2917
RETURN varchar IS
 
2918
BEGIN
 
2919
    IF v_version IS NULL THEN
 
2920
        RETURN v_name;
 
2921
    END IF;
 
2922
    RETURN v_name || '/' || v_version;
 
2923
END;
 
2924
/
 
2925
show errors;
 
2926
</programlisting>
 
2927
    </para>
 
2928
 
 
2929
    <para>
 
2930
     Let's go through this function and see the differences to <application>PL/pgSQL</>:
 
2931
 
 
2932
     <itemizedlist>
 
2933
      <listitem>
 
2934
       <para>
 
2935
        <productname>Oracle</productname> can have
 
2936
        <literal>IN</literal>, <literal>OUT</literal>, and
 
2937
        <literal>INOUT</literal> parameters passed to functions.
 
2938
        <literal>INOUT</literal>, for example, means that the
 
2939
        parameter will receive a value and return
 
2940
        another. <productname>PostgreSQL</> only has <literal>IN</literal>
 
2941
        parameters, and hence there is no specification of the parameter kind.
 
2942
       </para>
 
2943
      </listitem>
 
2944
 
 
2945
      <listitem>
 
2946
       <para>
 
2947
        The <literal>RETURN</literal> key word in the function
 
2948
        prototype (not the function body) becomes
 
2949
        <literal>RETURNS</literal> in
 
2950
        <productname>PostgreSQL</productname>.
 
2951
        Also, <literal>IS</> becomes <literal>AS</>, and you need to
 
2952
        add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
 
2953
        is not the only possible function language.
 
2954
       </para>
 
2955
      </listitem>
 
2956
 
 
2957
      <listitem>
 
2958
       <para>
 
2959
        In <productname>PostgreSQL</>, the function body is considered
 
2960
        to be a string literal, so you need to use quote marks or dollar
 
2961
        quotes around it.  This substitutes for the terminating <literal>/</>
 
2962
        in the Oracle approach.
 
2963
       </para>
 
2964
      </listitem>
 
2965
 
 
2966
      <listitem>
 
2967
       <para>
 
2968
        The <literal>show errors</literal> command does not exist in
 
2969
        <productname>PostgreSQL</>, and is not needed since errors are
 
2970
        reported automatically.
 
2971
       </para>
 
2972
      </listitem>
 
2973
     </itemizedlist>
 
2974
    </para>
 
2975
 
 
2976
    <para>
 
2977
     This is how this function would look when ported to
 
2978
     <productname>PostgreSQL</>:
 
2979
 
 
2980
<programlisting>
 
2981
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
 
2982
                                                  v_version varchar)
 
2983
RETURNS varchar AS $$
 
2984
BEGIN
 
2985
    IF v_version IS NULL THEN
 
2986
        RETURN v_name;
 
2987
    END IF;
 
2988
    RETURN v_name || '/' || v_version;
 
2989
END;
 
2990
$$ LANGUAGE plpgsql;
 
2991
</programlisting>
 
2992
    </para>
 
2993
   </example>
 
2994
 
 
2995
   <para>
 
2996
    <xref linkend="plpgsql-porting-ex2"> shows how to port a
 
2997
    function that creates another function and how to handle the
 
2998
    ensuing quoting problems.
 
2999
   </para>
 
3000
 
 
3001
   <example id="plpgsql-porting-ex2">
 
3002
    <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
 
3003
 
 
3004
    <para>
 
3005
     The following procedure grabs rows from a
 
3006
     <command>SELECT</command> statement and builds a large function
 
3007
     with the results in <literal>IF</literal> statements, for the
 
3008
     sake of efficiency. Notice particularly the differences in the
 
3009
     cursor and the <literal>FOR</literal> loop.
 
3010
    </para>
 
3011
 
 
3012
    <para>
 
3013
     This is the Oracle version:
 
3014
<programlisting>
 
3015
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
 
3016
    CURSOR referrer_keys IS 
 
3017
        SELECT * FROM cs_referrer_keys 
 
3018
        ORDER BY try_order;
 
3019
 
 
3020
    func_cmd VARCHAR(4000); 
 
3021
BEGIN 
 
3022
    func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
 
3023
                 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN'; 
 
3024
 
 
3025
    FOR referrer_key IN referrer_keys LOOP 
 
3026
        func_cmd := func_cmd ||
 
3027
          ' IF v_' || referrer_key.kind
 
3028
          || ' LIKE ''' || referrer_key.key_string
 
3029
          || ''' THEN RETURN ''' || referrer_key.referrer_type
 
3030
          || '''; END IF;'; 
 
3031
    END LOOP; 
 
3032
 
 
3033
    func_cmd := func_cmd || ' RETURN NULL; END;'; 
 
3034
 
 
3035
    EXECUTE IMMEDIATE func_cmd; 
 
3036
END; 
 
3037
 
3038
show errors;
 
3039
</programlisting>
 
3040
    </para>
 
3041
 
 
3042
    <para>
 
3043
     Here is how this function would end up in <productname>PostgreSQL</>:
 
3044
<programlisting>
 
3045
CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
 
3046
DECLARE
 
3047
    referrer_key RECORD;  -- declare a generic record to be used in a FOR
 
3048
    func_body text;
 
3049
    func_cmd text;
 
3050
BEGIN 
 
3051
    func_body := 'BEGIN' ;
 
3052
 
 
3053
    -- Notice how we scan through the results of a query in a FOR loop
 
3054
    -- using the FOR &lt;record&gt; construct.
 
3055
 
 
3056
    FOR referrer_key IN SELECT * FROM cs_referrer_keys ORDER BY try_order LOOP
 
3057
        func_body := func_body ||
 
3058
          ' IF v_' || referrer_key.kind
 
3059
          || ' LIKE ' || quote_literal(referrer_key.key_string)
 
3060
          || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
 
3061
          || '; END IF;' ;
 
3062
    END LOOP; 
 
3063
 
 
3064
    func_body := func_body || ' RETURN NULL; END;';
 
3065
 
 
3066
    func_cmd :=
 
3067
      'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
 
3068
                                                        v_domain varchar,
 
3069
                                                        v_url varchar) 
 
3070
        RETURNS varchar AS '
 
3071
      || quote_literal(func_body)
 
3072
      || ' LANGUAGE plpgsql;' ;
 
3073
 
 
3074
    EXECUTE func_cmd;
 
3075
    RETURN;
 
3076
END;
 
3077
$func$ LANGUAGE plpgsql;
 
3078
</programlisting>
 
3079
     Notice how the body of the function is built separately and passed
 
3080
     through <literal>quote_literal</> to double any quote marks in it.  This
 
3081
     technique is needed because we cannot safely use dollar quoting for
 
3082
     defining the new function: we do not know for sure what strings will
 
3083
     be interpolated from the <structfield>referrer_key.key_string</> field.
 
3084
     (We are assuming here that <structfield>referrer_key.kind</> can be
 
3085
     trusted to always be <literal>host</>, <literal>domain</>, or
 
3086
     <literal>url</>, but <structfield>referrer_key.key_string</> might be
 
3087
     anything, in particular it might contain dollar signs.) This function
 
3088
     is actually an improvement on the Oracle original, because it will
 
3089
     not generate broken code when <structfield>referrer_key.key_string</> or
 
3090
     <structfield>referrer_key.referrer_type</> contain quote marks.
 
3091
    </para>
 
3092
   </example>
 
3093
 
 
3094
   <para>
 
3095
    <xref linkend="plpgsql-porting-ex3"> shows how to port a function
 
3096
    with <literal>OUT</> parameters and string manipulation.
 
3097
    <productname>PostgreSQL</> does not have an
 
3098
    <function>instr</function> function, but you can work around it
 
3099
    using a combination of other
 
3100
    functions.<indexterm><primary>instr</></indexterm> In <xref
 
3101
    linkend="plpgsql-porting-appendix"> there is a
 
3102
    <application>PL/pgSQL</application> implementation of
 
3103
    <function>instr</function> that you can use to make your porting
 
3104
    easier.
 
3105
   </para>
 
3106
 
 
3107
   <example id="plpgsql-porting-ex3">
 
3108
    <title>Porting a Procedure With String Manipulation and
 
3109
    <literal>OUT</> Parameters from <application>PL/SQL</> to
 
3110
    <application>PL/pgSQL</></title>
 
3111
 
 
3112
    <para>
 
3113
     The following <productname>Oracle</productname> PL/SQL procedure is used
 
3114
     to parse a URL and return several elements (host, path, and query).
 
3115
     In <productname>PostgreSQL</>, functions can return only one value.
 
3116
     One way to work around this is to make the return value a composite
 
3117
     type (row type).
 
3118
    </para>
 
3119
 
 
3120
    <para>
 
3121
     This is the Oracle version:
 
3122
<programlisting>
 
3123
CREATE OR REPLACE PROCEDURE cs_parse_url(
 
3124
    v_url IN VARCHAR,
 
3125
    v_host OUT VARCHAR,  -- This will be passed back
 
3126
    v_path OUT VARCHAR,  -- This one too
 
3127
    v_query OUT VARCHAR) -- And this one
 
3128
IS
 
3129
    a_pos1 INTEGER;
 
3130
    a_pos2 INTEGER;
 
3131
BEGIN
 
3132
    v_host := NULL;
 
3133
    v_path := NULL;
 
3134
    v_query := NULL;
 
3135
    a_pos1 := instr(v_url, '//');
 
3136
 
 
3137
    IF a_pos1 = 0 THEN
 
3138
        RETURN;
 
3139
    END IF;
 
3140
    a_pos2 := instr(v_url, '/', a_pos1 + 2);
 
3141
    IF a_pos2 = 0 THEN
 
3142
        v_host := substr(v_url, a_pos1 + 2);
 
3143
        v_path := '/';
 
3144
        RETURN;
 
3145
    END IF;
 
3146
 
 
3147
    v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
 
3148
    a_pos1 := instr(v_url, '?', a_pos2 + 1);
 
3149
 
 
3150
    IF a_pos1 = 0 THEN
 
3151
        v_path := substr(v_url, a_pos2);
 
3152
        RETURN;
 
3153
    END IF;
 
3154
 
 
3155
    v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
 
3156
    v_query := substr(v_url, a_pos1 + 1);
 
3157
END;
 
3158
/
 
3159
show errors;
 
3160
</programlisting>
 
3161
    </para>
 
3162
 
 
3163
    <para>
 
3164
     Here is a possible translation into <application>PL/pgSQL</>:
 
3165
<programlisting>
 
3166
CREATE TYPE cs_parse_url_result AS (
 
3167
    v_host VARCHAR,
 
3168
    v_path VARCHAR,
 
3169
    v_query VARCHAR
 
3170
);
 
3171
 
 
3172
CREATE OR REPLACE FUNCTION cs_parse_url(v_url VARCHAR)
 
3173
RETURNS cs_parse_url_result AS $$
 
3174
DECLARE
 
3175
    res cs_parse_url_result;
 
3176
    a_pos1 INTEGER;
 
3177
    a_pos2 INTEGER;
 
3178
BEGIN
 
3179
    res.v_host := NULL;
 
3180
    res.v_path := NULL;
 
3181
    res.v_query := NULL;
 
3182
    a_pos1 := instr(v_url, '//');
 
3183
 
 
3184
    IF a_pos1 = 0 THEN
 
3185
        RETURN res;
 
3186
    END IF;
 
3187
    a_pos2 := instr(v_url, '/', a_pos1 + 2);
 
3188
    IF a_pos2 = 0 THEN
 
3189
        res.v_host := substr(v_url, a_pos1 + 2);
 
3190
        res.v_path := '/';
 
3191
        RETURN res;
 
3192
    END IF;
 
3193
 
 
3194
    res.v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
 
3195
    a_pos1 := instr(v_url, '?', a_pos2 + 1);
 
3196
 
 
3197
    IF a_pos1 = 0 THEN
 
3198
        res.v_path := substr(v_url, a_pos2);
 
3199
        RETURN res;
 
3200
    END IF;
 
3201
 
 
3202
    res.v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
 
3203
    res.v_query := substr(v_url, a_pos1 + 1);
 
3204
    RETURN res;
 
3205
END;
 
3206
$$ LANGUAGE plpgsql;
 
3207
</programlisting>
 
3208
 
 
3209
     This function could be used like this:
 
3210
<programlisting>
 
3211
SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
 
3212
</programlisting>
 
3213
    </para>
 
3214
   </example>
 
3215
 
 
3216
   <para>
 
3217
    <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
 
3218
    that uses numerous features that are specific to Oracle.
 
3219
   </para>
 
3220
 
 
3221
   <example id="plpgsql-porting-ex4">
 
3222
    <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
 
3223
 
 
3224
    <para>
 
3225
     The Oracle version:
 
3226
 
 
3227
<programlisting>
 
3228
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
 
3229
    a_running_job_count INTEGER;
 
3230
    PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
 
3231
BEGIN
 
3232
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
 
3233
 
 
3234
    SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
 
3235
 
 
3236
    IF a_running_job_count &gt; 0 THEN
 
3237
        COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
 
3238
        raise_application_error(-20000, 'Unable to create a new job: a job is currently running.');
 
3239
    END IF;
 
3240
 
 
3241
    DELETE FROM cs_active_job;
 
3242
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
 
3243
 
 
3244
    BEGIN
 
3245
        INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
 
3246
    EXCEPTION
 
3247
        WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
 
3248
    END;
 
3249
    COMMIT;
 
3250
END;
 
3251
/
 
3252
show errors
 
3253
</programlisting>
 
3254
   </para>
 
3255
 
 
3256
   <para>
 
3257
    Procedures like this can easily be converted into <productname>PostgreSQL</>
 
3258
    functions returning <type>void</type>. This procedure in
 
3259
    particular is interesting because it can teach us some things:
 
3260
 
 
3261
    <calloutlist>
 
3262
     <callout arearefs="co.plpgsql-porting-pragma">
 
3263
      <para>
 
3264
       There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
 
3265
      </para>
 
3266
     </callout>
 
3267
 
 
3268
     <callout arearefs="co.plpgsql-porting-locktable">
 
3269
      <para>
 
3270
       If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
 
3271
       the lock will not be released until the calling transaction is
 
3272
       finished.
 
3273
      </para>
 
3274
     </callout>
 
3275
 
 
3276
     <callout arearefs="co.plpgsql-porting-commit">
 
3277
      <para>
 
3278
       You cannot issue <command>COMMIT</> in a
 
3279
       <application>PL/pgSQL</application> function.  The function is
 
3280
       running within some outer transaction and so <command>COMMIT</>
 
3281
       would imply terminating the function's execution.  However, in
 
3282
       this particular case it is not necessary anyway, because the lock
 
3283
       obtained by the <command>LOCK TABLE</command> will be released when
 
3284
       we raise an error.
 
3285
      </para>
 
3286
     </callout>
 
3287
    </calloutlist>
 
3288
   </para>
 
3289
 
 
3290
   <para>
 
3291
    This is how we could port this procedure to <application>PL/pgSQL</>:
 
3292
 
 
3293
<programlisting>
 
3294
CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
 
3295
DECLARE
 
3296
    a_running_job_count integer;
 
3297
BEGIN
 
3298
    LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
 
3299
 
 
3300
    SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
 
3301
 
 
3302
    IF a_running_job_count &gt; 0 THEN
 
3303
        RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
 
3304
    END IF;
 
3305
 
 
3306
    DELETE FROM cs_active_job;
 
3307
    INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
 
3308
 
 
3309
    BEGIN
 
3310
        INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
 
3311
    EXCEPTION
 
3312
        WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
 
3313
            -- don't worry if it already exists
 
3314
    END;
 
3315
 
 
3316
    RETURN;
 
3317
END;
 
3318
$$ LANGUAGE plpgsql;
 
3319
</programlisting>
 
3320
 
 
3321
    <calloutlist>
 
3322
     <callout arearefs="co.plpgsql-porting-raise">
 
3323
      <para>
 
3324
       The syntax of <literal>RAISE</> is considerably different from
 
3325
       Oracle's similar statement.
 
3326
      </para>
 
3327
     </callout>
 
3328
     <callout arearefs="co.plpgsql-porting-exception">
 
3329
      <para>
 
3330
       The exception names supported by <application>PL/pgSQL</> are
 
3331
       different from Oracle's.  The set of built-in exception names
 
3332
       is much larger (see <xref linkend="errcodes-appendix">).  There
 
3333
       is not currently a way to declare user-defined exception names.
 
3334
      </para>
 
3335
     </callout>
 
3336
    </calloutlist>
 
3337
 
 
3338
    The main functional difference between this procedure and the
 
3339
    Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
 
3340
    table will be held until the calling transaction completes.  Also, if
 
3341
    the caller later aborts (for example due to an error), the effects of
 
3342
    this procedure will be rolled back.
 
3343
   </para>
 
3344
   </example>
 
3345
  </sect2>
 
3346
 
 
3347
  <sect2 id="plpgsql-porting-other">
 
3348
   <title>Other Things to Watch For</title>
 
3349
 
 
3350
   <para>
 
3351
    This section explains a few other things to watch for when porting
 
3352
    Oracle <application>PL/SQL</> functions to
 
3353
    <productname>PostgreSQL</productname>.
 
3354
   </para>
 
3355
 
 
3356
   <sect3 id="plpgsql-porting-exceptions">
 
3357
    <title>Implicit Rollback after Exceptions</title>
 
3358
 
 
3359
    <para>
 
3360
     In <application>PL/pgSQL</>, when an exception is caught by an
 
3361
     <literal>EXCEPTION</> clause, all database changes since the block's
 
3362
     <literal>BEGIN</> are automatically rolled back.  That is, the behavior
 
3363
     is equivalent to what you'd get in Oracle with
 
3364
 
 
3365
<programlisting>
 
3366
    BEGIN
 
3367
        SAVEPOINT s1;
 
3368
        ... code here ...
 
3369
    EXCEPTION
 
3370
        WHEN ... THEN
 
3371
            ROLLBACK TO s1;
 
3372
            ... code here ...
 
3373
        WHEN ... THEN
 
3374
            ROLLBACK TO s1;
 
3375
            ... code here ...
 
3376
    END;
 
3377
</programlisting>
 
3378
 
 
3379
     If you are translating an Oracle procedure that uses
 
3380
     <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
 
3381
     your task is easy: just omit the <command>SAVEPOINT</> and
 
3382
     <command>ROLLBACK TO</>.  If you have a procedure that uses
 
3383
     <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
 
3384
     then some actual thought will be required.
 
3385
    </para>
 
3386
   </sect3>
 
3387
 
 
3388
   <sect3>
 
3389
    <title><command>EXECUTE</command></title>
 
3390
 
 
3391
    <para>
 
3392
     The <application>PL/pgSQL</> version of
 
3393
     <command>EXECUTE</command> works similarly to the
 
3394
     <application>PL/SQL</> version, but you have to remember to use
 
3395
     <function>quote_literal(text)</function> and
 
3396
     <function>quote_string(text)</function> as described in <xref
 
3397
     linkend="plpgsql-statements-executing-dyn">.  Constructs of the
 
3398
     type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not
 
3399
     work unless you use these functions.
 
3400
    </para>
 
3401
   </sect3>
 
3402
 
 
3403
   <sect3 id="plpgsql-porting-optimization">
 
3404
    <title>Optimizing <application>PL/pgSQL</application> Functions</title>
 
3405
 
 
3406
    <para>
 
3407
     <productname>PostgreSQL</> gives you two function creation
 
3408
     modifiers to optimize execution: <quote>volatility</> (whether the
 
3409
     function always returns the same result when given the same
 
3410
     arguments) and <quote>strictness</quote> (whether the
 
3411
     function returns null if any argument is null).  Consult the
 
3412
     <xref linkend="sql-createfunction"> reference page for details.
 
3413
    </para>
 
3414
 
 
3415
    <para>
 
3416
     When making use of these optimization attributes, your
 
3417
     <command>CREATE FUNCTION</command> statement might look something
 
3418
     like this:
 
3419
 
 
3420
<programlisting>
 
3421
CREATE FUNCTION foo(...) RETURNS integer AS $$
 
3422
...
 
3423
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
 
3424
</programlisting>
 
3425
    </para>
 
3426
   </sect3>
 
3427
  </sect2>
 
3428
 
 
3429
  <sect2 id="plpgsql-porting-appendix">
 
3430
   <title>Appendix</title>
 
3431
 
 
3432
   <para>
 
3433
    This section contains the code for a set of Oracle-compatible
 
3434
    <function>instr</function> functions that you can use to simplify
 
3435
    your porting efforts.
 
3436
   </para>
 
3437
 
 
3438
<programlisting>
 
3439
--
 
3440
-- instr functions that mimic Oracle's counterpart
 
3441
-- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
 
3442
-- 
 
3443
-- Searches string1 beginning at the nth character for the mth occurrence
 
3444
-- of string2.  If n is negative, search backwards.  If m is not passed,
 
3445
-- assume 1 (search starts at first character).
 
3446
--
 
3447
 
 
3448
CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
 
3449
DECLARE
 
3450
    pos integer;
 
3451
BEGIN
 
3452
    pos:= instr($1, $2, 1);
 
3453
    RETURN pos;
 
3454
END;
 
3455
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
 
3456
 
 
3457
 
 
3458
CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
 
3459
RETURNS integer AS $$
 
3460
DECLARE
 
3461
    pos integer NOT NULL DEFAULT 0;
 
3462
    temp_str varchar;
 
3463
    beg integer;
 
3464
    length integer;
 
3465
    ss_length integer;
 
3466
BEGIN
 
3467
    IF beg_index &gt; 0 THEN
 
3468
        temp_str := substring(string FROM beg_index);
 
3469
        pos := position(string_to_search IN temp_str);
 
3470
 
 
3471
        IF pos = 0 THEN
 
3472
            RETURN 0;
 
3473
        ELSE
 
3474
            RETURN pos + beg_index - 1;
 
3475
        END IF;
 
3476
    ELSE
 
3477
        ss_length := char_length(string_to_search);
 
3478
        length := char_length(string);
 
3479
        beg := length + beg_index - ss_length + 2;
 
3480
 
 
3481
        WHILE beg &gt; 0 LOOP
 
3482
            temp_str := substring(string FROM beg FOR ss_length);
 
3483
            pos := position(string_to_search IN temp_str);
 
3484
 
 
3485
            IF pos &gt; 0 THEN
 
3486
                RETURN beg;
 
3487
            END IF;
 
3488
 
 
3489
            beg := beg - 1;
 
3490
        END LOOP;
 
3491
 
 
3492
        RETURN 0;
 
3493
    END IF;
 
3494
END;
 
3495
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
 
3496
 
 
3497
 
 
3498
CREATE FUNCTION instr(string varchar, string_to_search varchar,
 
3499
                      beg_index integer, occur_index integer)
 
3500
RETURNS integer AS $$
 
3501
DECLARE
 
3502
    pos integer NOT NULL DEFAULT 0;
 
3503
    occur_number integer NOT NULL DEFAULT 0;
 
3504
    temp_str varchar;
 
3505
    beg integer;
 
3506
    i integer;
 
3507
    length integer;
 
3508
    ss_length integer;
 
3509
BEGIN
 
3510
    IF beg_index &gt; 0 THEN
 
3511
        beg := beg_index;
 
3512
        temp_str := substring(string FROM beg_index);
 
3513
 
 
3514
        FOR i IN 1..occur_index LOOP
 
3515
            pos := position(string_to_search IN temp_str);
 
3516
 
 
3517
            IF i = 1 THEN
 
3518
                beg := beg + pos - 1;
 
3519
            ELSE
 
3520
                beg := beg + pos;
 
3521
            END IF;
 
3522
 
 
3523
            temp_str := substring(string FROM beg + 1);
 
3524
        END LOOP;
 
3525
 
 
3526
        IF pos = 0 THEN
 
3527
            RETURN 0;
 
3528
        ELSE
 
3529
            RETURN beg;
 
3530
        END IF;
 
3531
    ELSE
 
3532
        ss_length := char_length(string_to_search);
 
3533
        length := char_length(string);
 
3534
        beg := length + beg_index - ss_length + 2;
 
3535
 
 
3536
        WHILE beg &gt; 0 LOOP
 
3537
            temp_str := substring(string FROM beg FOR ss_length);
 
3538
            pos := position(string_to_search IN temp_str);
 
3539
 
 
3540
            IF pos &gt; 0 THEN
 
3541
                occur_number := occur_number + 1;
 
3542
 
 
3543
                IF occur_number = occur_index THEN
 
3544
                    RETURN beg;
 
3545
                END IF;
 
3546
            END IF;
 
3547
 
 
3548
            beg := beg - 1;
 
3549
        END LOOP;
 
3550
 
 
3551
        RETURN 0;
 
3552
    END IF;
 
3553
END;
 
3554
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
 
3555
</programlisting>
 
3556
  </sect2>
 
3557
 
 
3558
 </sect1>
 
3559
 
 
3560
</chapter>
 
3561
 
 
3562
<!-- Keep this comment at the end of the file
 
3563
Local variables:
 
3564
mode:sgml
 
3565
sgml-omittag:nil
 
3566
sgml-shorttag:t
 
3567
sgml-minimize-attributes:nil
 
3568
sgml-always-quote-attributes:t
 
3569
sgml-indent-step:1
 
3570
sgml-indent-data:t
 
3571
sgml-parent-document:nil
 
3572
sgml-default-dtd-file:"./reference.ced"
 
3573
sgml-exposed-tags:nil
 
3574
sgml-local-catalogs:("/usr/lib/sgml/catalog")
 
3575
sgml-local-ecat-files:nil
 
3576
End:
 
3577
-->