2
$PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.57.4.1 2005-01-22 23:05:47 momjian Exp $
6
<title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
8
<indexterm zone="plpgsql">
9
<primary>PL/pgSQL</primary>
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
21
can be used to create functions and trigger procedures,
26
adds control structures to the <acronym>SQL</acronym> language,
31
can perform complex computations,
36
inherits all user-defined types, functions, and operators,
41
can be defined to be trusted by the server,
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.
61
<sect1 id="plpgsql-overview">
62
<title>Overview</title>
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
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.
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.
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:
101
CREATE FUNCTION populate() RETURNS integer AS $$
105
PERFORM my_function();
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).
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 — at the price of constructing a new execution plan on
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).
148
<sect2 id="plpgsql-advantages">
149
<title>Advantages of Using <application>PL/pgSQL</application></title>
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.
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.
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.
178
Also, with <application>PL/pgSQL</application> you can use all
179
the data types, operators and functions of SQL.
183
<sect2 id="plpgsql-args-results">
184
<title>Supported Argument and Result Data Types</title>
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">.
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">.
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.
214
Finally, a <application>PL/pgSQL</> function may be declared to return
215
<type>void</> if it has no useful return value.
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.
229
<sect1 id="plpgsql-development-tips">
230
<title>Tips for Developing in <application>PL/pgSQL</application></title>
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:
242
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
249
While running <application>psql</application>, you can load or reload such
250
a function definition file with
254
and then immediately issue SQL commands to test the function.
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.
266
<sect2 id="plpgsql-quote-tips">
267
<title>Handling of Quotation Marks</title>
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
286
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
288
$PROC$ LANGUAGE plpgsql;
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.
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.
304
<term>1 quotation mark</term>
307
To begin and end the function body, for example:
309
CREATE FUNCTION foo() RETURNS integer AS '
313
Anywhere within a single-quoted function body, quote marks
314
<emphasis>must</> appear in pairs.
320
<term>2 quotation marks</term>
323
For string literals inside the function body, for example:
325
a_output := ''Blah'';
326
SELECT * FROM users WHERE f_name=''foobar'';
328
In the dollar-quoting approach, you'd just write
331
SELECT * FROM users WHERE f_name='foobar';
333
which is exactly what the <application>PL/pgSQL</> parser would see
340
<term>4 quotation marks</term>
343
When you need a single quotation mark in a string constant inside the
344
function body, for example:
346
a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
348
The value actually appended to <literal>a_output</literal> would be:
349
<literal> AND name LIKE 'foobar' AND xyz</literal>.
352
In the dollar-quoting approach, you'd write
354
a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
356
being careful that any dollar-quote delimiters around this are not
363
<term>6 quotation marks</term>
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:
369
a_output := a_output || '' AND name LIKE ''''foobar''''''
371
The value appended to <literal>a_output</literal> would then be:
372
<literal> AND name LIKE 'foobar'</literal>.
375
In the dollar-quoting approach, this becomes
377
a_output := a_output || $$ AND name LIKE 'foobar'$$
384
<term>10 quotation marks</term>
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">.
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;'';
400
The value of <literal>a_output</literal> would then be:
402
if v_... like ''...'' then return ''...''; end if;
406
In the dollar-quoting approach, this becomes
408
a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
409
|| referrer_keys.key_string || $$'
410
then return '$$ || referrer_keys.referrer_type
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.
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
430
<sect1 id="plpgsql-structure">
431
<title>Structure of <application>PL/pgSQL</application></title>
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:
439
<optional> <<<replaceable>label</replaceable>>> </optional>
441
<replaceable>declarations</replaceable> </optional>
443
<replaceable>statements</replaceable>
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.
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.
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>.
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
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:
484
CREATE FUNCTION somefunc() RETURNS integer AS $$
486
quantity integer := 30;
488
RAISE NOTICE 'Quantity here is %', quantity; -- Quantity here is 30
494
quantity integer := 80;
496
RAISE NOTICE 'Quantity here is %', quantity; -- Quantity here is 80
499
RAISE NOTICE 'Quantity here is %', quantity; -- Quantity here is 50
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 — 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">.
523
<sect1 id="plpgsql-declarations">
524
<title>Declarations</title>
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
535
<application>PL/pgSQL</> variables can have any SQL data type, such as
536
<type>integer</type>, <type>varchar</type>, and
541
Here are some examples of variable declarations:
546
myrow tablename%ROWTYPE;
547
myfield tablename.columnname%TYPE;
553
The general syntax of a variable declaration is:
555
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
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.
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
580
quantity integer DEFAULT 32;
581
url varchar := 'http://mysite.com';
582
user_id CONSTANT integer := 10;
586
<sect2 id="plpgsql-declaration-aliases">
587
<title>Aliases for Function Parameters</title>
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.
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,
603
CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
605
RETURN subtotal * 0.06;
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
614
<replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
617
The same example in this style looks like
619
CREATE FUNCTION sales_tax(real) RETURNS real AS $$
621
subtotal ALIAS FOR $1;
623
RETURN subtotal * 0.06;
629
CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
631
v_string ALIAS FOR $1;
634
-- some computations here
639
CREATE FUNCTION concat_selected_fields(in_t tablename) RETURNS text AS $$
641
RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
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:
662
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
663
RETURNS anyelement AS $$
667
result := v1 + v2 + v3;
675
<sect2 id="plpgsql-declaration-type">
676
<title>Copying Types</title>
679
<replaceable>variable</replaceable>%TYPE
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:
690
user_id users.user_id%TYPE;
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.
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.
713
<sect2 id="plpgsql-declaration-rowtypes">
714
<title>Row Types</title>
717
<replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
718
<replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
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>.
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.)
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>.
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>.
759
Here is an example of using composite types:
761
CREATE FUNCTION merge_fields(t_row tablename) RETURNS text AS $$
763
t2_row table2name%ROWTYPE;
765
SELECT * INTO t2_row FROM table2name WHERE ... ;
766
RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
770
SELECT merge_fields(t.*) FROM tablename t WHERE ... ;
775
<sect2 id="plpgsql-declaration-records">
776
<title>Record Types</title>
779
<replaceable>name</replaceable> RECORD;
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.
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.
805
<sect2 id="plpgsql-declaration-renaming-vars">
806
<title><literal>RENAME</></title>
809
RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
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>.
823
RENAME id TO user_id;
824
RENAME this_var TO that_var;
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>.
839
<sect1 id="plpgsql-expressions">
840
<title>Expressions</title>
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
847
SELECT <replaceable>expression</replaceable>
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
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:
865
CREATE FUNCTION logfunc1(logtxt text) RETURNS timestamp AS $$
867
INSERT INTO logtable VALUES (logtxt, 'now');
876
CREATE FUNCTION logfunc2(logtxt text) RETURNS timestamp AS $$
881
INSERT INTO logtable VALUES (logtxt, curtime);
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
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.
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.)
928
<sect1 id="plpgsql-statements">
929
<title>Basic Statements</title>
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
945
<sect2 id="plpgsql-statements-assignment">
946
<title>Assignment</title>
949
An assignment of a value to a variable or row/record field is
952
<replaceable>identifier</replaceable> := <replaceable>expression</replaceable>;
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.
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.
974
tax := subtotal * 0.06;
979
<sect2 id="plpgsql-select-into">
980
<title><command>SELECT INTO</command></title>
982
<indexterm zone="plpgsql-select-into">
983
<primary>SELECT INTO</primary>
984
<secondary>in PL/pgSQL</secondary>
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:
993
SELECT INTO <replaceable>target</replaceable> <replaceable>select_expressions</replaceable> FROM ...;
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.
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>.
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.
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.
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</> — that is, either just before
1030
or just after the list of <replaceable>select_expressions</replaceable>.
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</>.)
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:
1049
SELECT INTO myrec * FROM emp WHERE empname = myname;
1051
RAISE EXCEPTION 'employee % not found', myname;
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:
1066
SELECT INTO users_rec * FROM users WHERE user_id=3;
1068
IF users_rec.homepage IS NULL THEN
1069
-- user entered no homepage, return "http://"
1077
<sect2 id="plpgsql-statements-perform">
1078
<title>Executing an Expression or Query With No Result</title>
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:
1088
PERFORM <replaceable>query</replaceable>;
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.
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>.
1113
PERFORM create_mv('cs_session_page_requests_mv', my_query);
1118
<sect2 id="plpgsql-statements-null">
1119
<title>Doing Nothing At All</title>
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:
1133
For example, the following two fragments of code are equivalent:
1138
WHEN division_by_zero THEN
1139
NULL; -- ignore the error
1147
WHEN division_by_zero THEN -- ignore the error
1150
Which is preferable is a matter of taste.
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.
1164
<sect2 id="plpgsql-statements-executing-dyn">
1165
<title>Executing Dynamic Commands</title>
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:
1177
EXECUTE <replaceable class="command">command-string</replaceable>;
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.
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.
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.
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">.
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.)
1224
Dynamic values that are to be inserted into the constructed
1225
query require special handling since they might themselves contain
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):
1230
EXECUTE 'UPDATE tbl SET '
1231
|| quote_ident(colname)
1233
|| quote_literal(newvalue)
1235
|| quote_literal(keyvalue);
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
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
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
1259
EXECUTE 'UPDATE tbl SET '
1260
|| quote_ident(colname)
1263
|| '$$ WHERE key = '
1264
|| quote_literal(keyvalue);
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>.
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.
1281
<sect2 id="plpgsql-statements-diagnostics">
1282
<title>Obtaining the Result Status</title>
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:
1290
GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional> ;
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.
1308
GET DIAGNOSTICS integer_var = ROW_COUNT;
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:
1321
A <command>SELECT INTO</command> statement sets
1322
<literal>FOUND</literal> true if it returns a row, false if no
1328
A <command>PERFORM</> statement sets <literal>FOUND</literal>
1329
true if it produces (and discards) a row, false if no row is
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.
1342
A <command>FETCH</> statement sets <literal>FOUND</literal>
1343
true if it returns a row, false if no row is returned.
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.
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.
1370
<sect1 id="plpgsql-control-structures">
1371
<title>Control Structures</title>
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.
1381
<sect2 id="plpgsql-statements-returning">
1382
<title>Returning From a Function</title>
1385
There are two commands available that allow you to return data
1386
from a function: <command>RETURN</command> and <command>RETURN
1391
<title><command>RETURN</></title>
1394
RETURN <replaceable>expression</replaceable>;
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
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>.
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
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.
1429
<title><command>RETURN NEXT</></title>
1432
RETURN NEXT <replaceable>expression</replaceable>;
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.
1448
Functions that use <command>RETURN NEXT</command> should be
1449
called in the following fashion:
1452
SELECT * FROM some_func();
1455
That is, the function must be used as a table source in a
1456
<literal>FROM</literal> clause.
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.
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.
1490
<sect2 id="plpgsql-conditionals">
1491
<title>Conditionals</title>
1494
<literal>IF</> statements let you execute commands based on
1495
certain conditions. <application>PL/pgSQL</> has five forms of
1499
<para><literal>IF ... THEN</></>
1502
<para><literal>IF ... THEN ... ELSE</></>
1505
<para><literal>IF ... THEN ... ELSE IF</></>
1508
<para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1511
<para><literal>IF ... THEN ... ELSEIF ... THEN ... ELSE</></>
1517
<title><literal>IF-THEN</></title>
1520
IF <replaceable>boolean-expression</replaceable> THEN
1521
<replaceable>statements</replaceable>
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
1536
IF v_user_id <> 0 THEN
1537
UPDATE users SET email = v_email WHERE user_id = v_user_id;
1544
<title><literal>IF-THEN-ELSE</></title>
1547
IF <replaceable>boolean-expression</replaceable> THEN
1548
<replaceable>statements</replaceable>
1550
<replaceable>statements</replaceable>
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.
1564
IF parentid IS NULL OR parentid = ''
1568
RETURN hp_true_filename(parentid) || '/' || fullname;
1573
IF v_count > 0 THEN
1574
INSERT INTO users_count (count) VALUES (v_count);
1584
<title><literal>IF-THEN-ELSE IF</></title>
1587
<literal>IF</literal> statements can be nested, as in the
1591
IF demo_row.sex = 'm' THEN
1592
pretty_sex := 'man';
1594
IF demo_row.sex = 'f' THEN
1595
pretty_sex := 'woman';
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.
1614
<title><literal>IF-THEN-ELSIF-ELSE</></title>
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>
1627
<replaceable>statements</replaceable> </optional>
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.
1645
ELSIF number > 0 THEN
1646
result := 'positive';
1647
ELSIF number < 0 THEN
1648
result := 'negative';
1650
-- hmm, the only other possibility is that number is null
1658
<title><literal>IF-THEN-ELSEIF-ELSE</></title>
1661
<literal>ELSEIF</> is an alias for <literal>ELSIF</>.
1666
<sect2 id="plpgsql-control-structures-loops">
1667
<title>Simple Loops</title>
1669
<indexterm zone="plpgsql-control-structures-loops">
1670
<primary>loop</primary>
1671
<secondary>in PL/pgSQL</secondary>
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
1682
<title><literal>LOOP</></title>
1685
<optional><<<replaceable>label</replaceable>>></optional>
1687
<replaceable>statements</replaceable>
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
1701
<title><literal>EXIT</></title>
1704
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>expression</replaceable> </optional>;
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
1719
If <literal>WHEN</> is present, loop exit occurs only if the specified
1720
condition is true, otherwise control passes to the statement after
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.
1733
-- some computations
1734
IF count > 0 THEN
1740
-- some computations
1741
EXIT WHEN count > 0; -- same result as previous example
1745
-- some computations
1746
IF stocks > 100000 THEN
1747
EXIT; -- causes exit from the BEGIN block
1755
<title><literal>WHILE</></title>
1758
<optional><<<replaceable>label</replaceable>>></optional>
1759
WHILE <replaceable>expression</replaceable> LOOP
1760
<replaceable>statements</replaceable>
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.
1774
WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
1775
-- some computations here
1778
WHILE NOT boolean_expression LOOP
1779
-- some computations here
1786
<title><literal>FOR</> (integer variant)</title>
1789
<optional><<<replaceable>label</replaceable>>></optional>
1790
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> LOOP
1791
<replaceable>statements</replaceable>
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
1806
Some examples of integer <literal>FOR</> loops:
1809
-- some computations here
1810
RAISE NOTICE 'i is %', i;
1813
FOR i IN REVERSE 10..1 LOOP
1814
-- some computations here
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.
1827
<sect2 id="plpgsql-records-iterating">
1828
<title>Looping Through Query Results</title>
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:
1835
<optional><<<replaceable>label</replaceable>>></optional>
1836
FOR <replaceable>record_or_row</replaceable> IN <replaceable>query</replaceable> LOOP
1837
<replaceable>statements</replaceable>
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:
1845
CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
1849
PERFORM cs_log('Refreshing materialized views...');
1851
FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
1853
-- Now "mviews" has one record from cs_materialized_views
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;
1860
PERFORM cs_log('Done refreshing materialized views.');
1863
$$ LANGUAGE plpgsql;
1866
If the loop is terminated by an <literal>EXIT</> statement, the last
1867
assigned row value is still accessible after the loop.
1871
The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
1874
<optional><<<replaceable>label</replaceable>>></optional>
1875
FOR <replaceable>record_or_row</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> LOOP
1876
<replaceable>statements</replaceable>
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.
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.
1901
<sect2 id="plpgsql-error-trapping">
1902
<title>Trapping Errors</title>
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:
1913
<optional> <<<replaceable>label</replaceable>>> </optional>
1915
<replaceable>declarations</replaceable> </optional>
1917
<replaceable>statements</replaceable>
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>
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
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.
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.
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:
1972
INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
1974
UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
1978
WHEN division_by_zero THEN
1979
RAISE NOTICE 'caught division_by_zero';
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</>.
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.
2004
<sect1 id="plpgsql-cursors">
2005
<title>Cursors</title>
2007
<indexterm zone="plpgsql-cursors">
2008
<primary>cursor</primary>
2009
<secondary>in PL/pgSQL</secondary>
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.
2025
<sect2 id="plpgsql-cursor-declarations">
2026
<title>Declaring Cursor Variables</title>
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:
2036
<replaceable>name</replaceable> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable> ;
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.
2052
curs2 CURSOR FOR SELECT * FROM tenk1;
2053
curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
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.
2066
<sect2 id="plpgsql-cursor-opening">
2067
<title>Opening Cursors</title>
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.
2078
<title><command>OPEN FOR SELECT</command></title>
2081
OPEN <replaceable>unbound_cursor</replaceable> FOR SELECT ...;
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
2098
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2104
<title><command>OPEN FOR EXECUTE</command></title>
2107
OPEN <replaceable>unbound_cursor</replaceable> FOR EXECUTE <replaceable class="command">query_string</replaceable>;
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.
2123
OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident($1);
2129
<title>Opening a Bound Cursor</title>
2132
OPEN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
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.
2155
<sect2 id="plpgsql-cursor-using">
2156
<title>Using Cursors</title>
2159
Once a cursor has been opened, it can be manipulated with the
2160
statements described here.
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.)
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.
2180
<title><literal>FETCH</></title>
2183
FETCH <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
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.
2198
FETCH curs1 INTO rowvar;
2199
FETCH curs2 INTO foo, bar, baz;
2205
<title><literal>CLOSE</></title>
2208
CLOSE <replaceable>cursor</replaceable>;
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.
2226
<title>Returning Cursors</title>
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.
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.
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.
2263
The following example shows one way a cursor name can be supplied by
2267
CREATE TABLE test (col text);
2268
INSERT INTO test VALUES ('123');
2270
CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
2272
OPEN $1 FOR SELECT col FROM test;
2278
SELECT reffunc('funccursor');
2279
FETCH ALL IN funccursor;
2285
The following example uses automatic cursor name generation:
2288
CREATE FUNCTION reffunc2() RETURNS refcursor AS '
2292
OPEN ref FOR SELECT col FROM test;
2301
--------------------
2302
<unnamed cursor 1>
2305
FETCH ALL IN "<unnamed cursor 1>";
2311
The following example shows one way to return multiple cursors
2312
from a single function:
2315
CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
2317
OPEN $1 FOR SELECT * FROM table_1;
2319
OPEN $2 FOR SELECT * FROM table_2;
2323
$$ LANGUAGE plpgsql;
2325
-- need to be in a transaction to use cursors.
2328
SELECT * FROM myfunc('a', 'b');
2339
<sect1 id="plpgsql-errors-and-messages">
2340
<title>Errors and Messages</title>
2343
Use the <command>RAISE</command> statement to report messages and
2347
RAISE <replaceable class="parameter">level</replaceable> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">variable</replaceable> <optional>, ...</optional></optional>;
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
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
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.
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.
2380
In this example, the value of <literal>v_job_id</> will replace the
2381
<literal>%</literal> in the string:
2383
RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
2388
This example will abort the transaction with the given error message:
2390
RAISE EXCEPTION 'Nonexistent ID --> %', user_id;
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.
2403
<sect1 id="plpgsql-trigger">
2404
<title>Trigger Procedures</title>
2406
<indexterm zone="plpgsql-trigger">
2407
<primary>trigger</primary>
2408
<secondary>in PL/pgSQL</secondary>
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</> —
2418
trigger arguments are passed via <varname>TG_ARGV</>, as described
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:
2429
<term><varname>NEW</varname></term>
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.
2440
<term><varname>OLD</varname></term>
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.
2451
<term><varname>TG_NAME</varname></term>
2454
Data type <type>name</type>; variable that contains the name of the trigger actually
2461
<term><varname>TG_WHEN</varname></term>
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.
2472
<term><varname>TG_LEVEL</varname></term>
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.
2483
<term><varname>TG_OP</varname></term>
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
2495
<term><varname>TG_RELID</varname></term>
2498
Data type <type>oid</type>; the object ID of the table that caused the
2505
<term><varname>TG_RELNAME</varname></term>
2508
Data type <type>name</type>; the name of the table that caused the trigger
2515
<term><varname>TG_NARGS</varname></term>
2518
Data type <type>integer</type>; the number of arguments given to the trigger
2519
procedure in the <command>CREATE TRIGGER</command> statement.
2525
<term><varname>TG_ARGV[]</varname></term>
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.
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.
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.
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.
2567
<xref linkend="plpgsql-trigger-example"> shows an example of a
2568
trigger procedure in <application>PL/pgSQL</application>.
2571
<example id="plpgsql-trigger-example">
2572
<title>A <application>PL/pgSQL</application> Trigger Procedure</title>
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.
2585
last_date timestamp,
2589
CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
2591
-- Check that empname and salary are given
2592
IF NEW.empname IS NULL THEN
2593
RAISE EXCEPTION 'empname cannot be null';
2595
IF NEW.salary IS NULL THEN
2596
RAISE EXCEPTION '% cannot have null salary', NEW.empname;
2599
-- Who works for us when she must pay for it?
2600
IF NEW.salary < 0 THEN
2601
RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
2604
-- Remember who changed the payroll when
2605
NEW.last_date := 'now';
2606
NEW.last_user := current_user;
2609
$emp_stamp$ LANGUAGE plpgsql;
2611
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
2612
FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
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>.
2624
<example id="plpgsql-trigger-audit-example">
2625
<title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
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.
2636
empname text NOT NULL,
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,
2648
CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
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.
2654
IF (TG_OP = 'DELETE') THEN
2655
INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
2657
ELSIF (TG_OP = 'UPDATE') THEN
2658
INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
2660
ELSIF (TG_OP = 'INSERT') THEN
2661
INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
2664
RETURN NULL; -- result is ignored since this is an AFTER trigger
2666
$emp_audit$ language plpgsql;
2668
CREATE TRIGGER emp_audit
2669
AFTER INSERT OR UPDATE OR DELETE ON emp
2670
FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
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 — often with vastly reduced run
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.
2687
<example id="plpgsql-trigger-summary-example">
2688
<title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
2691
The schema detailed here is partly based on the <emphasis>Grocery Store
2692
</emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
2698
-- Main tables - time dimension and sales fact.
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
2708
CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
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
2718
CREATE INDEX sales_fact_time ON sales_fact(time_key);
2721
-- Summary table - sales by time.
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
2729
CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
2732
-- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
2734
CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER AS $maint_sales_summary_bytime$
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);
2742
-- Work out the increment/decrement amount(s).
2743
IF (TG_OP = 'DELETE') THEN
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;
2750
ELSIF (TG_OP = 'UPDATE') THEN
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 : % -> % not allowed', OLD.time_key, NEW.time_key;
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;
2764
ELSIF (TG_OP = 'INSERT') THEN
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;
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;
2782
-- There might have been no row with this time_key (e.g new data!).
2785
INSERT INTO sales_summary_bytime (
2798
-- Catch race condition when two transactions are adding data
2799
-- for a new time_key.
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;
2813
$maint_sales_summary_bytime$ LANGUAGE plpgsql;
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();
2823
<!-- **** Porting from Oracle PL/SQL **** -->
2825
<sect1 id="plpgsql-porting">
2826
<title>Porting from <productname>Oracle</productname> PL/SQL</title>
2828
<indexterm zone="plpgsql-porting">
2829
<primary>Oracle</primary>
2830
<secondary>porting from PL/SQL to PL/pgSQL</secondary>
2833
<indexterm zone="plpgsql-porting">
2834
<primary>PL/SQL (Oracle)</primary>
2835
<secondary>porting to PL/pgSQL</secondary>
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</>.
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:
2857
There are no default values for parameters in <productname>PostgreSQL</>.
2863
You can overload function names in <productname>PostgreSQL</>. This is
2864
often used to work around the lack of default parameters.
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">.)
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">.
2886
Instead of packages, use schemas to organize your functions
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.
2902
<title>Porting Examples</title>
2905
<xref linkend="pgsql-porting-ex1"> shows how to port a simple
2906
function from <application>PL/SQL</> to <application>PL/pgSQL</>.
2909
<example id="pgsql-porting-ex1">
2910
<title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
2913
Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
2915
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name IN varchar,
2916
v_version IN varchar)
2919
IF v_version IS NULL THEN
2922
RETURN v_name || '/' || v_version;
2930
Let's go through this function and see the differences to <application>PL/pgSQL</>:
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.
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.
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.
2968
The <literal>show errors</literal> command does not exist in
2969
<productname>PostgreSQL</>, and is not needed since errors are
2970
reported automatically.
2977
This is how this function would look when ported to
2978
<productname>PostgreSQL</>:
2981
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
2983
RETURNS varchar AS $$
2985
IF v_version IS NULL THEN
2988
RETURN v_name || '/' || v_version;
2990
$$ LANGUAGE plpgsql;
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.
3001
<example id="plpgsql-porting-ex2">
3002
<title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
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.
3013
This is the Oracle version:
3015
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
3016
CURSOR referrer_keys IS
3017
SELECT * FROM cs_referrer_keys
3020
func_cmd VARCHAR(4000);
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';
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
3033
func_cmd := func_cmd || ' RETURN NULL; END;';
3035
EXECUTE IMMEDIATE func_cmd;
3043
Here is how this function would end up in <productname>PostgreSQL</>:
3045
CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
3047
referrer_key RECORD; -- declare a generic record to be used in a FOR
3051
func_body := 'BEGIN' ;
3053
-- Notice how we scan through the results of a query in a FOR loop
3054
-- using the FOR <record> construct.
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)
3064
func_body := func_body || ' RETURN NULL; END;';
3067
'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
3070
RETURNS varchar AS '
3071
|| quote_literal(func_body)
3072
|| ' LANGUAGE plpgsql;' ;
3077
$func$ LANGUAGE plpgsql;
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.
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
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>
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
3121
This is the Oracle version:
3123
CREATE OR REPLACE PROCEDURE cs_parse_url(
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
3135
a_pos1 := instr(v_url, '//');
3140
a_pos2 := instr(v_url, '/', a_pos1 + 2);
3142
v_host := substr(v_url, a_pos1 + 2);
3147
v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
3148
a_pos1 := instr(v_url, '?', a_pos2 + 1);
3151
v_path := substr(v_url, a_pos2);
3155
v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
3156
v_query := substr(v_url, a_pos1 + 1);
3164
Here is a possible translation into <application>PL/pgSQL</>:
3166
CREATE TYPE cs_parse_url_result AS (
3172
CREATE OR REPLACE FUNCTION cs_parse_url(v_url VARCHAR)
3173
RETURNS cs_parse_url_result AS $$
3175
res cs_parse_url_result;
3181
res.v_query := NULL;
3182
a_pos1 := instr(v_url, '//');
3187
a_pos2 := instr(v_url, '/', a_pos1 + 2);
3189
res.v_host := substr(v_url, a_pos1 + 2);
3194
res.v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
3195
a_pos1 := instr(v_url, '?', a_pos2 + 1);
3198
res.v_path := substr(v_url, a_pos2);
3202
res.v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
3203
res.v_query := substr(v_url, a_pos1 + 1);
3206
$$ LANGUAGE plpgsql;
3209
This function could be used like this:
3211
SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
3217
<xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
3218
that uses numerous features that are specific to Oracle.
3221
<example id="plpgsql-porting-ex4">
3222
<title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
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">
3232
LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
3234
SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
3236
IF a_running_job_count > 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.');
3241
DELETE FROM cs_active_job;
3242
INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
3245
INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
3247
WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
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:
3262
<callout arearefs="co.plpgsql-porting-pragma">
3264
There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
3268
<callout arearefs="co.plpgsql-porting-locktable">
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
3276
<callout arearefs="co.plpgsql-porting-commit">
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
3291
This is how we could port this procedure to <application>PL/pgSQL</>:
3294
CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
3296
a_running_job_count integer;
3298
LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
3300
SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
3302
IF a_running_job_count > 0 THEN
3303
RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
3306
DELETE FROM cs_active_job;
3307
INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
3310
INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
3312
WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
3313
-- don't worry if it already exists
3318
$$ LANGUAGE plpgsql;
3322
<callout arearefs="co.plpgsql-porting-raise">
3324
The syntax of <literal>RAISE</> is considerably different from
3325
Oracle's similar statement.
3328
<callout arearefs="co.plpgsql-porting-exception">
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.
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.
3347
<sect2 id="plpgsql-porting-other">
3348
<title>Other Things to Watch For</title>
3351
This section explains a few other things to watch for when porting
3352
Oracle <application>PL/SQL</> functions to
3353
<productname>PostgreSQL</productname>.
3356
<sect3 id="plpgsql-porting-exceptions">
3357
<title>Implicit Rollback after Exceptions</title>
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
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.
3389
<title><command>EXECUTE</command></title>
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.
3403
<sect3 id="plpgsql-porting-optimization">
3404
<title>Optimizing <application>PL/pgSQL</application> Functions</title>
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.
3416
When making use of these optimization attributes, your
3417
<command>CREATE FUNCTION</command> statement might look something
3421
CREATE FUNCTION foo(...) RETURNS integer AS $$
3423
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
3429
<sect2 id="plpgsql-porting-appendix">
3430
<title>Appendix</title>
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.
3440
-- instr functions that mimic Oracle's counterpart
3441
-- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
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).
3448
CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
3452
pos:= instr($1, $2, 1);
3455
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
3458
CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
3459
RETURNS integer AS $$
3461
pos integer NOT NULL DEFAULT 0;
3467
IF beg_index > 0 THEN
3468
temp_str := substring(string FROM beg_index);
3469
pos := position(string_to_search IN temp_str);
3474
RETURN pos + beg_index - 1;
3477
ss_length := char_length(string_to_search);
3478
length := char_length(string);
3479
beg := length + beg_index - ss_length + 2;
3481
WHILE beg > 0 LOOP
3482
temp_str := substring(string FROM beg FOR ss_length);
3483
pos := position(string_to_search IN temp_str);
3495
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
3498
CREATE FUNCTION instr(string varchar, string_to_search varchar,
3499
beg_index integer, occur_index integer)
3500
RETURNS integer AS $$
3502
pos integer NOT NULL DEFAULT 0;
3503
occur_number integer NOT NULL DEFAULT 0;
3510
IF beg_index > 0 THEN
3512
temp_str := substring(string FROM beg_index);
3514
FOR i IN 1..occur_index LOOP
3515
pos := position(string_to_search IN temp_str);
3518
beg := beg + pos - 1;
3523
temp_str := substring(string FROM beg + 1);
3532
ss_length := char_length(string_to_search);
3533
length := char_length(string);
3534
beg := length + beg_index - ss_length + 2;
3536
WHILE beg > 0 LOOP
3537
temp_str := substring(string FROM beg FOR ss_length);
3538
pos := position(string_to_search IN temp_str);
3541
occur_number := occur_number + 1;
3543
IF occur_number = occur_index THEN
3554
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
3562
<!-- Keep this comment at the end of the file
3567
sgml-minimize-attributes:nil
3568
sgml-always-quote-attributes: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