| 1 |
<!-- doc/src/sgml/plpgsql.sgml --> |
| 2 |
|
| 3 |
<chapter id="plpgsql"> |
| 4 |
<title><application>PL/pgSQL</application> — <acronym>SQL</acronym> Procedural Language</title> |
| 5 |
|
| 6 |
<indexterm zone="plpgsql"> |
| 7 |
<primary>PL/pgSQL</primary> |
| 8 |
</indexterm> |
| 9 |
|
| 10 |
<sect1 id="plpgsql-overview"> |
| 11 |
<title>Overview</title> |
| 12 |
|
| 13 |
<para> |
| 14 |
<application>PL/pgSQL</application> is a loadable procedural |
| 15 |
language for the <productname>PostgreSQL</productname> database |
| 16 |
system. The design goals of <application>PL/pgSQL</application> were to create |
| 17 |
a loadable procedural language that |
| 18 |
|
| 19 |
<itemizedlist> |
| 20 |
<listitem> |
| 21 |
<para> |
| 22 |
can be used to create functions, procedures, and triggers, |
| 23 |
</para> |
| 24 |
</listitem> |
| 25 |
<listitem> |
| 26 |
<para> |
| 27 |
adds control structures to the <acronym>SQL</acronym> language, |
| 28 |
</para> |
| 29 |
</listitem> |
| 30 |
<listitem> |
| 31 |
<para> |
| 32 |
can perform complex computations, |
| 33 |
</para> |
| 34 |
</listitem> |
| 35 |
<listitem> |
| 36 |
<para> |
| 37 |
inherits all user-defined types, functions, procedures, and operators, |
| 38 |
</para> |
| 39 |
</listitem> |
| 40 |
<listitem> |
| 41 |
<para> |
| 42 |
can be defined to be trusted by the server, |
| 43 |
</para> |
| 44 |
</listitem> |
| 45 |
<listitem> |
| 46 |
<para> |
| 47 |
is easy to use. |
| 48 |
</para> |
| 49 |
</listitem> |
| 50 |
</itemizedlist> |
| 51 |
</para> |
| 52 |
|
| 53 |
<para> |
| 54 |
Functions created with <application>PL/pgSQL</application> can be |
| 55 |
used anywhere that built-in functions could be used. |
| 56 |
For example, it is possible to |
| 57 |
create complex conditional computation functions and later use |
| 58 |
them to define operators or use them in index expressions. |
| 59 |
</para> |
| 60 |
|
| 61 |
<para> |
| 62 |
In <productname>PostgreSQL</productname> 9.0 and later, |
| 63 |
<application>PL/pgSQL</application> is installed by default. |
| 64 |
However it is still a loadable module, so especially security-conscious |
| 65 |
administrators could choose to remove it. |
| 66 |
</para> |
| 67 |
|
| 68 |
<sect2 id="plpgsql-advantages"> |
| 69 |
<title>Advantages of Using <application>PL/pgSQL</application></title> |
| 70 |
|
| 71 |
<para> |
| 72 |
<acronym>SQL</acronym> is the language <productname>PostgreSQL</productname> |
| 73 |
and most other relational databases use as query language. It's |
| 74 |
portable and easy to learn. But every <acronym>SQL</acronym> |
| 75 |
statement must be executed individually by the database server. |
| 76 |
</para> |
| 77 |
|
| 78 |
<para> |
| 79 |
That means that your client application must send each query to |
| 80 |
the database server, wait for it to be processed, receive and |
| 81 |
process the results, do some computation, then send further |
| 82 |
queries to the server. All this incurs interprocess |
| 83 |
communication and will also incur network overhead if your client |
| 84 |
is on a different machine than the database server. |
| 85 |
</para> |
| 86 |
|
| 87 |
<para> |
| 88 |
With <application>PL/pgSQL</application> you can group a block of |
| 89 |
computation and a series of queries <emphasis>inside</emphasis> |
| 90 |
the database server, thus having the power of a procedural |
| 91 |
language and the ease of use of SQL, but with considerable |
| 92 |
savings of client/server communication overhead. |
| 93 |
</para> |
| 94 |
<itemizedlist> |
| 95 |
|
| 96 |
<listitem><para> Extra round trips between |
| 97 |
client and server are eliminated </para></listitem> |
| 98 |
|
| 99 |
<listitem><para> Intermediate results that the client does not |
| 100 |
need do not have to be marshaled or transferred between server |
| 101 |
and client </para></listitem> |
| 102 |
|
| 103 |
<listitem><para> Multiple rounds of query |
| 104 |
parsing can be avoided </para></listitem> |
| 105 |
|
| 106 |
</itemizedlist> |
| 107 |
<para> This can result in a considerable performance increase as |
| 108 |
compared to an application that does not use stored functions. |
| 109 |
</para> |
| 110 |
|
| 111 |
<para> |
| 112 |
Also, with <application>PL/pgSQL</application> you can use all |
| 113 |
the data types, operators and functions of SQL. |
| 114 |
</para> |
| 115 |
</sect2> |
| 116 |
|
| 117 |
<sect2 id="plpgsql-args-results"> |
| 118 |
<title>Supported Argument and Result Data Types</title> |
| 119 |
|
| 120 |
<para> |
| 121 |
Functions written in <application>PL/pgSQL</application> can accept |
| 122 |
as arguments any scalar or array data type supported by the server, |
| 123 |
and they can return a result of any of these types. They can also |
| 124 |
accept or return any composite type (row type) specified by name. |
| 125 |
It is also possible to declare a <application>PL/pgSQL</application> |
| 126 |
function as accepting <type>record</type>, which means that any |
| 127 |
composite type will do as input, or |
| 128 |
as returning <type>record</type>, which means that the result |
| 129 |
is a row type whose columns are determined by specification in the |
| 130 |
calling query, as discussed in <xref linkend="queries-tablefunctions"/>. |
| 131 |
</para> |
| 132 |
|
| 133 |
<para> |
| 134 |
<application>PL/pgSQL</application> functions can be declared to accept a variable |
| 135 |
number of arguments by using the <literal>VARIADIC</literal> marker. This |
| 136 |
works exactly the same way as for SQL functions, as discussed in |
| 137 |
<xref linkend="xfunc-sql-variadic-functions"/>. |
| 138 |
</para> |
| 139 |
|
| 140 |
<para> |
| 141 |
<application>PL/pgSQL</application> functions can also be declared to |
| 142 |
accept and return the polymorphic types described in |
| 143 |
<xref linkend="extend-types-polymorphic"/>, thus allowing the actual data |
| 144 |
types handled by the function to vary from call to call. |
| 145 |
Examples appear in <xref linkend="plpgsql-declaration-parameters"/>. |
| 146 |
</para> |
| 147 |
|
| 148 |
<para> |
| 149 |
<application>PL/pgSQL</application> functions can also be declared to return |
| 150 |
a <quote>set</quote> (or table) of any data type that can be returned as |
| 151 |
a single instance. Such a function generates its output by executing |
| 152 |
<command>RETURN NEXT</command> for each desired element of the result |
| 153 |
set, or by using <command>RETURN QUERY</command> to output the result of |
| 154 |
evaluating a query. |
| 155 |
</para> |
| 156 |
|
| 157 |
<para> |
| 158 |
Finally, a <application>PL/pgSQL</application> function can be declared to return |
| 159 |
<type>void</type> if it has no useful return value. (Alternatively, it |
| 160 |
could be written as a procedure in that case.) |
| 161 |
</para> |
| 162 |
|
| 163 |
<para> |
| 164 |
<application>PL/pgSQL</application> functions can also be declared with output |
| 165 |
parameters in place of an explicit specification of the return type. |
| 166 |
This does not add any fundamental capability to the language, but |
| 167 |
it is often convenient, especially for returning multiple values. |
| 168 |
The <literal>RETURNS TABLE</literal> notation can also be used in place |
| 169 |
of <literal>RETURNS SETOF</literal>. |
| 170 |
</para> |
| 171 |
|
| 172 |
<para> |
| 173 |
Specific examples appear in |
| 174 |
<xref linkend="plpgsql-declaration-parameters"/> and |
| 175 |
<xref linkend="plpgsql-statements-returning"/>. |
| 176 |
</para> |
| 177 |
</sect2> |
| 178 |
</sect1> |
| 179 |
|
| 180 |
<sect1 id="plpgsql-structure"> |
| 181 |
<title>Structure of <application>PL/pgSQL</application></title> |
| 182 |
|
| 183 |
<para> |
| 184 |
Functions written in <application>PL/pgSQL</application> are defined |
| 185 |
to the server by executing <xref linkend="sql-createfunction"/> commands. |
| 186 |
Such a command would normally look like, say, |
| 187 |
<programlisting> |
| 188 |
CREATE FUNCTION somefunc(integer, text) RETURNS integer |
| 189 |
AS '<replaceable>function body text</replaceable>' |
| 190 |
LANGUAGE plpgsql; |
| 191 |
</programlisting> |
| 192 |
The function body is simply a string literal so far as <command>CREATE |
| 193 |
FUNCTION</command> is concerned. It is often helpful to use dollar quoting |
| 194 |
(see <xref linkend="sql-syntax-dollar-quoting"/>) to write the function |
| 195 |
body, rather than the normal single quote syntax. Without dollar quoting, |
| 196 |
any single quotes or backslashes in the function body must be escaped by |
| 197 |
doubling them. Almost all the examples in this chapter use dollar-quoted |
| 198 |
literals for their function bodies. |
| 199 |
</para> |
| 200 |
|
| 201 |
<para> |
| 202 |
<application>PL/pgSQL</application> is a block-structured language. |
| 203 |
The complete text of a function body must be a |
| 204 |
<firstterm>block</firstterm>. A block is defined as: |
| 205 |
|
| 206 |
<synopsis> |
| 207 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 208 |
<optional> DECLARE |
| 209 |
<replaceable>declarations</replaceable> </optional> |
| 210 |
BEGIN |
| 211 |
<replaceable>statements</replaceable> |
| 212 |
END <optional> <replaceable>label</replaceable> </optional>; |
| 213 |
</synopsis> |
| 214 |
</para> |
| 215 |
|
| 216 |
<para> |
| 217 |
Each declaration and each statement within a block is terminated |
| 218 |
by a semicolon. A block that appears within another block must |
| 219 |
have a semicolon after <literal>END</literal>, as shown above; |
| 220 |
however the final <literal>END</literal> that |
| 221 |
concludes a function body does not require a semicolon. |
| 222 |
</para> |
| 223 |
|
| 224 |
<tip> |
| 225 |
<para> |
| 226 |
A common mistake is to write a semicolon immediately after |
| 227 |
<literal>BEGIN</literal>. This is incorrect and will result in a syntax error. |
| 228 |
</para> |
| 229 |
</tip> |
| 230 |
|
| 231 |
<para> |
| 232 |
A <replaceable>label</replaceable> is only needed if you want to |
| 233 |
identify the block for use |
| 234 |
in an <literal>EXIT</literal> statement, or to qualify the names of the |
| 235 |
variables declared in the block. If a label is given after |
| 236 |
<literal>END</literal>, it must match the label at the block's beginning. |
| 237 |
</para> |
| 238 |
|
| 239 |
<para> |
| 240 |
All key words are case-insensitive. |
| 241 |
Identifiers are implicitly converted to lower case |
| 242 |
unless double-quoted, just as they are in ordinary SQL commands. |
| 243 |
</para> |
| 244 |
|
| 245 |
<para> |
| 246 |
Comments work the same way in <application>PL/pgSQL</application> code as in |
| 247 |
ordinary SQL. A double dash (<literal>--</literal>) starts a comment |
| 248 |
that extends to the end of the line. A <literal>/*</literal> starts a |
| 249 |
block comment that extends to the matching occurrence of |
| 250 |
<literal>*/</literal>. Block comments nest. |
| 251 |
</para> |
| 252 |
|
| 253 |
<para> |
| 254 |
Any statement in the statement section of a block |
| 255 |
can be a <firstterm>subblock</firstterm>. Subblocks can be used for |
| 256 |
logical grouping or to localize variables to a small group |
| 257 |
of statements. Variables declared in a subblock mask any |
| 258 |
similarly-named variables of outer blocks for the duration |
| 259 |
of the subblock; but you can access the outer variables anyway |
| 260 |
if you qualify their names with their block's label. For example: |
| 261 |
<programlisting> |
| 262 |
CREATE FUNCTION somefunc() RETURNS integer AS $$ |
| 263 |
<< outerblock >> |
| 264 |
DECLARE |
| 265 |
quantity integer := 30; |
| 266 |
BEGIN |
| 267 |
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30 |
| 268 |
quantity := 50; |
| 269 |
-- |
| 270 |
-- Create a subblock |
| 271 |
-- |
| 272 |
DECLARE |
| 273 |
quantity integer := 80; |
| 274 |
BEGIN |
| 275 |
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80 |
| 276 |
RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50 |
| 277 |
END; |
| 278 |
|
| 279 |
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50 |
| 280 |
|
| 281 |
RETURN quantity; |
| 282 |
END; |
| 283 |
$$ LANGUAGE plpgsql; |
| 284 |
</programlisting> |
| 285 |
</para> |
| 286 |
|
| 287 |
<note> |
| 288 |
<para> |
| 289 |
There is actually a hidden <quote>outer block</quote> surrounding the body |
| 290 |
of any <application>PL/pgSQL</application> function. This block provides the |
| 291 |
declarations of the function's parameters (if any), as well as some |
| 292 |
special variables such as <literal>FOUND</literal> (see |
| 293 |
<xref linkend="plpgsql-statements-diagnostics"/>). The outer block is |
| 294 |
labeled with the function's name, meaning that parameters and special |
| 295 |
variables can be qualified with the function's name. |
| 296 |
</para> |
| 297 |
</note> |
| 298 |
|
| 299 |
<para> |
| 300 |
It is important not to confuse the use of |
| 301 |
<command>BEGIN</command>/<command>END</command> for grouping statements in |
| 302 |
<application>PL/pgSQL</application> with the similarly-named SQL commands |
| 303 |
for transaction |
| 304 |
control. <application>PL/pgSQL</application>'s <command>BEGIN</command>/<command>END</command> |
| 305 |
are only for grouping; they do not start or end a transaction. |
| 306 |
See <xref linkend="plpgsql-transactions"/> for information on managing |
| 307 |
transactions in <application>PL/pgSQL</application>. |
| 308 |
Also, a block containing an <literal>EXCEPTION</literal> clause effectively |
| 309 |
forms a subtransaction that can be rolled back without affecting the |
| 310 |
outer transaction. For more about that see <xref |
| 311 |
linkend="plpgsql-error-trapping"/>. |
| 312 |
</para> |
| 313 |
</sect1> |
| 314 |
|
| 315 |
<sect1 id="plpgsql-declarations"> |
| 316 |
<title>Declarations</title> |
| 317 |
|
| 318 |
<para> |
| 319 |
All variables used in a block must be declared in the |
| 320 |
declarations section of the block. |
| 321 |
(The only exceptions are that the loop variable of a <literal>FOR</literal> loop |
| 322 |
iterating over a range of integer values is automatically declared as an |
| 323 |
integer variable, and likewise the loop variable of a <literal>FOR</literal> loop |
| 324 |
iterating over a cursor's result is automatically declared as a |
| 325 |
record variable.) |
| 326 |
</para> |
| 327 |
|
| 328 |
<para> |
| 329 |
<application>PL/pgSQL</application> variables can have any SQL data type, such as |
| 330 |
<type>integer</type>, <type>varchar</type>, and |
| 331 |
<type>char</type>. |
| 332 |
</para> |
| 333 |
|
| 334 |
<para> |
| 335 |
Here are some examples of variable declarations: |
| 336 |
<programlisting> |
| 337 |
user_id integer; |
| 338 |
quantity numeric(5); |
| 339 |
url varchar; |
| 340 |
myrow tablename%ROWTYPE; |
| 341 |
myfield tablename.columnname%TYPE; |
| 342 |
arow RECORD; |
| 343 |
</programlisting> |
| 344 |
</para> |
| 345 |
|
| 346 |
<para> |
| 347 |
The general syntax of a variable declaration is: |
| 348 |
<synopsis> |
| 349 |
<replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> COLLATE <replaceable>collation_name</replaceable> </optional> <optional> NOT NULL </optional> <optional> { DEFAULT | := | = } <replaceable>expression</replaceable> </optional>; |
| 350 |
</synopsis> |
| 351 |
The <literal>DEFAULT</literal> clause, if given, specifies the initial value assigned |
| 352 |
to the variable when the block is entered. If the <literal>DEFAULT</literal> clause |
| 353 |
is not given then the variable is initialized to the |
| 354 |
<acronym>SQL</acronym> null value. |
| 355 |
The <literal>CONSTANT</literal> option prevents the variable from being |
| 356 |
assigned to after initialization, so that its value will remain constant |
| 357 |
for the duration of the block. |
| 358 |
The <literal>COLLATE</literal> option specifies a collation to use for the |
| 359 |
variable (see <xref linkend="plpgsql-declaration-collation"/>). |
| 360 |
If <literal>NOT NULL</literal> |
| 361 |
is specified, an assignment of a null value results in a run-time |
| 362 |
error. All variables declared as <literal>NOT NULL</literal> |
| 363 |
must have a nonnull default value specified. |
| 364 |
Equal (<literal>=</literal>) can be used instead of PL/SQL-compliant |
| 365 |
<literal>:=</literal>. |
| 366 |
</para> |
| 367 |
|
| 368 |
<para> |
| 369 |
A variable's default value is evaluated and assigned to the variable |
| 370 |
each time the block is entered (not just once per function call). |
| 371 |
So, for example, assigning <literal>now()</literal> to a variable of type |
| 372 |
<type>timestamp</type> causes the variable to have the |
| 373 |
time of the current function call, not the time when the function was |
| 374 |
precompiled. |
| 375 |
</para> |
| 376 |
|
| 377 |
<para> |
| 378 |
Examples: |
| 379 |
<programlisting> |
| 380 |
quantity integer DEFAULT 32; |
| 381 |
url varchar := 'http://mysite.com'; |
| 382 |
transaction_time CONSTANT timestamp with time zone := now(); |
| 383 |
</programlisting> |
| 384 |
</para> |
| 385 |
|
| 386 |
<para> |
| 387 |
Once declared, a variable's value can be used in later initialization |
| 388 |
expressions in the same block, for example: |
| 389 |
<programlisting> |
| 390 |
DECLARE |
| 391 |
x integer := 1; |
| 392 |
y integer := x + 1; |
| 393 |
</programlisting> |
| 394 |
</para> |
| 395 |
|
| 396 |
<sect2 id="plpgsql-declaration-parameters"> |
| 397 |
<title>Declaring Function Parameters</title> |
| 398 |
|
| 399 |
<para> |
| 400 |
Parameters passed to functions are named with the identifiers |
| 401 |
<literal>$1</literal>, <literal>$2</literal>, |
| 402 |
etc. Optionally, aliases can be declared for |
| 403 |
<literal>$<replaceable>n</replaceable></literal> |
| 404 |
parameter names for increased readability. Either the alias or the |
| 405 |
numeric identifier can then be used to refer to the parameter value. |
| 406 |
</para> |
| 407 |
|
| 408 |
<para> |
| 409 |
There are two ways to create an alias. The preferred way is to give a |
| 410 |
name to the parameter in the <command>CREATE FUNCTION</command> command, |
| 411 |
for example: |
| 412 |
<programlisting> |
| 413 |
CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$ |
| 414 |
BEGIN |
| 415 |
RETURN subtotal * 0.06; |
| 416 |
END; |
| 417 |
$$ LANGUAGE plpgsql; |
| 418 |
</programlisting> |
| 419 |
The other way is to explicitly declare an alias, using the |
| 420 |
declaration syntax |
| 421 |
|
| 422 |
<synopsis> |
| 423 |
<replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>; |
| 424 |
</synopsis> |
| 425 |
|
| 426 |
The same example in this style looks like: |
| 427 |
<programlisting> |
| 428 |
CREATE FUNCTION sales_tax(real) RETURNS real AS $$ |
| 429 |
DECLARE |
| 430 |
subtotal ALIAS FOR $1; |
| 431 |
BEGIN |
| 432 |
RETURN subtotal * 0.06; |
| 433 |
END; |
| 434 |
$$ LANGUAGE plpgsql; |
| 435 |
</programlisting> |
| 436 |
</para> |
| 437 |
|
| 438 |
<note> |
| 439 |
<para> |
| 440 |
These two examples are not perfectly equivalent. In the first case, |
| 441 |
<literal>subtotal</literal> could be referenced as |
| 442 |
<literal>sales_tax.subtotal</literal>, but in the second case it could not. |
| 443 |
(Had we attached a label to the inner block, <literal>subtotal</literal> could |
| 444 |
be qualified with that label, instead.) |
| 445 |
</para> |
| 446 |
</note> |
| 447 |
|
| 448 |
<para> |
| 449 |
Some more examples: |
| 450 |
<programlisting> |
| 451 |
CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$ |
| 452 |
DECLARE |
| 453 |
v_string ALIAS FOR $1; |
| 454 |
index ALIAS FOR $2; |
| 455 |
BEGIN |
| 456 |
-- some computations using v_string and index here |
| 457 |
END; |
| 458 |
$$ LANGUAGE plpgsql; |
| 459 |
|
| 460 |
|
| 461 |
CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$ |
| 462 |
BEGIN |
| 463 |
RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7; |
| 464 |
END; |
| 465 |
$$ LANGUAGE plpgsql; |
| 466 |
</programlisting> |
| 467 |
</para> |
| 468 |
|
| 469 |
<para> |
| 470 |
When a <application>PL/pgSQL</application> function is declared |
| 471 |
with output parameters, the output parameters are given |
| 472 |
<literal>$<replaceable>n</replaceable></literal> names and optional |
| 473 |
aliases in just the same way as the normal input parameters. An |
| 474 |
output parameter is effectively a variable that starts out NULL; |
| 475 |
it should be assigned to during the execution of the function. |
| 476 |
The final value of the parameter is what is returned. For instance, |
| 477 |
the sales-tax example could also be done this way: |
| 478 |
|
| 479 |
<programlisting> |
| 480 |
CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$ |
| 481 |
BEGIN |
| 482 |
tax := subtotal * 0.06; |
| 483 |
END; |
| 484 |
$$ LANGUAGE plpgsql; |
| 485 |
</programlisting> |
| 486 |
|
| 487 |
Notice that we omitted <literal>RETURNS real</literal> — we could have |
| 488 |
included it, but it would be redundant. |
| 489 |
</para> |
| 490 |
|
| 491 |
<para> |
| 492 |
To call a function with <literal>OUT</literal> parameters, omit the |
| 493 |
output parameter(s) in the function call: |
| 494 |
<programlisting> |
| 495 |
SELECT sales_tax(100.00); |
| 496 |
</programlisting> |
| 497 |
</para> |
| 498 |
|
| 499 |
<para> |
| 500 |
Output parameters are most useful when returning multiple values. |
| 501 |
A trivial example is: |
| 502 |
|
| 503 |
<programlisting> |
| 504 |
CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$ |
| 505 |
BEGIN |
| 506 |
sum := x + y; |
| 507 |
prod := x * y; |
| 508 |
END; |
| 509 |
$$ LANGUAGE plpgsql; |
| 510 |
|
| 511 |
SELECT * FROM sum_n_product(2, 4); |
| 512 |
sum | prod |
| 513 |
-----+------ |
| 514 |
6 | 8 |
| 515 |
</programlisting> |
| 516 |
|
| 517 |
As discussed in <xref linkend="xfunc-output-parameters"/>, this |
| 518 |
effectively creates an anonymous record type for the function's |
| 519 |
results. If a <literal>RETURNS</literal> clause is given, it must say |
| 520 |
<literal>RETURNS record</literal>. |
| 521 |
</para> |
| 522 |
|
| 523 |
<para> |
| 524 |
This also works with procedures, for example: |
| 525 |
|
| 526 |
<programlisting> |
| 527 |
CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$ |
| 528 |
BEGIN |
| 529 |
sum := x + y; |
| 530 |
prod := x * y; |
| 531 |
END; |
| 532 |
$$ LANGUAGE plpgsql; |
| 533 |
</programlisting> |
| 534 |
|
| 535 |
In a call to a procedure, all the parameters must be specified. For |
| 536 |
output parameters, <literal>NULL</literal> may be specified when |
| 537 |
calling the procedure from plain SQL: |
| 538 |
<programlisting> |
| 539 |
CALL sum_n_product(2, 4, NULL, NULL); |
| 540 |
sum | prod |
| 541 |
-----+------ |
| 542 |
6 | 8 |
| 543 |
</programlisting> |
| 544 |
|
| 545 |
However, when calling a procedure |
| 546 |
from <application>PL/pgSQL</application>, you should instead write a |
| 547 |
variable for any output parameter; the variable will receive the result |
| 548 |
of the call. See <xref linkend="plpgsql-statements-calling-procedure"/> |
| 549 |
for details. |
| 550 |
</para> |
| 551 |
|
| 552 |
<para> |
| 553 |
Another way to declare a <application>PL/pgSQL</application> function |
| 554 |
is with <literal>RETURNS TABLE</literal>, for example: |
| 555 |
|
| 556 |
<programlisting> |
| 557 |
CREATE FUNCTION extended_sales(p_itemno int) |
| 558 |
RETURNS TABLE(quantity int, total numeric) AS $$ |
| 559 |
BEGIN |
| 560 |
RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s |
| 561 |
WHERE s.itemno = p_itemno; |
| 562 |
END; |
| 563 |
$$ LANGUAGE plpgsql; |
| 564 |
</programlisting> |
| 565 |
|
| 566 |
This is exactly equivalent to declaring one or more <literal>OUT</literal> |
| 567 |
parameters and specifying <literal>RETURNS SETOF |
| 568 |
<replaceable>sometype</replaceable></literal>. |
| 569 |
</para> |
| 570 |
|
| 571 |
<para> |
| 572 |
When the return type of a <application>PL/pgSQL</application> function |
| 573 |
is declared as a polymorphic type (see |
| 574 |
<xref linkend="extend-types-polymorphic"/>), a special |
| 575 |
parameter <literal>$0</literal> is created. Its data type is the actual |
| 576 |
return type of the function, as deduced from the actual input types. |
| 577 |
This allows the function to access its actual return type |
| 578 |
as shown in <xref linkend="plpgsql-declaration-type"/>. |
| 579 |
<literal>$0</literal> is initialized to null and can be modified by |
| 580 |
the function, so it can be used to hold the return value if desired, |
| 581 |
though that is not required. <literal>$0</literal> can also be |
| 582 |
given an alias. For example, this function works on any data type |
| 583 |
that has a <literal>+</literal> operator: |
| 584 |
|
| 585 |
<programlisting> |
| 586 |
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement) |
| 587 |
RETURNS anyelement AS $$ |
| 588 |
DECLARE |
| 589 |
result ALIAS FOR $0; |
| 590 |
BEGIN |
| 591 |
result := v1 + v2 + v3; |
| 592 |
RETURN result; |
| 593 |
END; |
| 594 |
$$ LANGUAGE plpgsql; |
| 595 |
</programlisting> |
| 596 |
</para> |
| 597 |
|
| 598 |
<para> |
| 599 |
The same effect can be obtained by declaring one or more output parameters as |
| 600 |
polymorphic types. In this case the |
| 601 |
special <literal>$0</literal> parameter is not used; the output |
| 602 |
parameters themselves serve the same purpose. For example: |
| 603 |
|
| 604 |
<programlisting> |
| 605 |
CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement, |
| 606 |
OUT sum anyelement) |
| 607 |
AS $$ |
| 608 |
BEGIN |
| 609 |
sum := v1 + v2 + v3; |
| 610 |
END; |
| 611 |
$$ LANGUAGE plpgsql; |
| 612 |
</programlisting> |
| 613 |
</para> |
| 614 |
|
| 615 |
<para> |
| 616 |
In practice it might be more useful to declare a polymorphic function |
| 617 |
using the <type>anycompatible</type> family of types, so that automatic |
| 618 |
promotion of the input arguments to a common type will occur. |
| 619 |
For example: |
| 620 |
|
| 621 |
<programlisting> |
| 622 |
CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompatible) |
| 623 |
RETURNS anycompatible AS $$ |
| 624 |
BEGIN |
| 625 |
RETURN v1 + v2 + v3; |
| 626 |
END; |
| 627 |
$$ LANGUAGE plpgsql; |
| 628 |
</programlisting> |
| 629 |
|
| 630 |
With this example, a call such as |
| 631 |
|
| 632 |
<programlisting> |
| 633 |
SELECT add_three_values(1, 2, 4.7); |
| 634 |
</programlisting> |
| 635 |
|
| 636 |
will work, automatically promoting the integer inputs to numeric. |
| 637 |
The function using <type>anyelement</type> would require you to |
| 638 |
cast the three inputs to the same type manually. |
| 639 |
</para> |
| 640 |
</sect2> |
| 641 |
|
| 642 |
<sect2 id="plpgsql-declaration-alias"> |
| 643 |
<title><literal>ALIAS</literal></title> |
| 644 |
|
| 645 |
<synopsis> |
| 646 |
<replaceable>newname</replaceable> ALIAS FOR <replaceable>oldname</replaceable>; |
| 647 |
</synopsis> |
| 648 |
|
| 649 |
<para> |
| 650 |
The <literal>ALIAS</literal> syntax is more general than is suggested in the |
| 651 |
previous section: you can declare an alias for any variable, not just |
| 652 |
function parameters. The main practical use for this is to assign |
| 653 |
a different name for variables with predetermined names, such as |
| 654 |
<varname>NEW</varname> or <varname>OLD</varname> within |
| 655 |
a trigger function. |
| 656 |
</para> |
| 657 |
|
| 658 |
<para> |
| 659 |
Examples: |
| 660 |
<programlisting> |
| 661 |
DECLARE |
| 662 |
prior ALIAS FOR old; |
| 663 |
updated ALIAS FOR new; |
| 664 |
</programlisting> |
| 665 |
</para> |
| 666 |
|
| 667 |
<para> |
| 668 |
Since <literal>ALIAS</literal> creates two different ways to name the same |
| 669 |
object, unrestricted use can be confusing. It's best to use it only |
| 670 |
for the purpose of overriding predetermined names. |
| 671 |
</para> |
| 672 |
</sect2> |
| 673 |
|
| 674 |
<sect2 id="plpgsql-declaration-type"> |
| 675 |
<title>Copying Types</title> |
| 676 |
|
| 677 |
<synopsis> |
| 678 |
<replaceable>name</replaceable> <replaceable>table</replaceable>.<replaceable>column</replaceable>%TYPE |
| 679 |
<replaceable>name</replaceable> <replaceable>variable</replaceable>%TYPE |
| 680 |
</synopsis> |
| 681 |
|
| 682 |
<para> |
| 683 |
<literal>%TYPE</literal> provides the data type of a table column |
| 684 |
or a previously-declared <application>PL/pgSQL</application> |
| 685 |
variable. You can use this to declare variables that will hold |
| 686 |
database values. For example, let's say you have a column named |
| 687 |
<literal>user_id</literal> in your <literal>users</literal> |
| 688 |
table. To declare a variable with the same data type as |
| 689 |
<literal>users.user_id</literal> you write: |
| 690 |
<programlisting> |
| 691 |
user_id users.user_id%TYPE; |
| 692 |
</programlisting> |
| 693 |
</para> |
| 694 |
|
| 695 |
<para> |
| 696 |
It is also possible to write array decoration |
| 697 |
after <literal>%TYPE</literal>, thereby creating a variable that holds |
| 698 |
an array of the referenced type: |
| 699 |
<programlisting> |
| 700 |
user_ids users.user_id%TYPE[]; |
| 701 |
user_ids users.user_id%TYPE ARRAY[4]; -- equivalent to the above |
| 702 |
</programlisting> |
| 703 |
Just as when declaring table columns that are arrays, it doesn't |
| 704 |
matter whether you write multiple bracket pairs or specific array |
| 705 |
dimensions: <productname>PostgreSQL</productname> treats all arrays of |
| 706 |
a given element type as the same type, regardless of dimensionality. |
| 707 |
(See <xref linkend="arrays-declaration"/>.) |
| 708 |
</para> |
| 709 |
|
| 710 |
<para> |
| 711 |
By using <literal>%TYPE</literal> you don't need to know the data |
| 712 |
type of the structure you are referencing, and most importantly, |
| 713 |
if the data type of the referenced item changes in the future (for |
| 714 |
instance: you change the type of <literal>user_id</literal> |
| 715 |
from <type>integer</type> to <type>real</type>), you might not need |
| 716 |
to change your function definition. |
| 717 |
</para> |
| 718 |
|
| 719 |
<para> |
| 720 |
<literal>%TYPE</literal> is particularly valuable in polymorphic |
| 721 |
functions, since the data types needed for internal variables can |
| 722 |
change from one call to the next. Appropriate variables can be |
| 723 |
created by applying <literal>%TYPE</literal> to the function's |
| 724 |
arguments or result placeholders. |
| 725 |
</para> |
| 726 |
|
| 727 |
</sect2> |
| 728 |
|
| 729 |
<sect2 id="plpgsql-declaration-rowtypes"> |
| 730 |
<title>Row Types</title> |
| 731 |
|
| 732 |
<synopsis> |
| 733 |
<replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>; |
| 734 |
<replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>; |
| 735 |
</synopsis> |
| 736 |
|
| 737 |
<para> |
| 738 |
A variable of a composite type is called a <firstterm>row</firstterm> |
| 739 |
variable (or <firstterm>row-type</firstterm> variable). Such a variable |
| 740 |
can hold a whole row of a <command>SELECT</command> or <command>FOR</command> |
| 741 |
query result, so long as that query's column set matches the |
| 742 |
declared type of the variable. |
| 743 |
The individual fields of the row value |
| 744 |
are accessed using the usual dot notation, for example |
| 745 |
<literal>rowvar.field</literal>. |
| 746 |
</para> |
| 747 |
|
| 748 |
<para> |
| 749 |
A row variable can be declared to have the same type as the rows of |
| 750 |
an existing table or view, by using the |
| 751 |
<replaceable>table_name</replaceable><literal>%ROWTYPE</literal> |
| 752 |
notation; or it can be declared by giving a composite type's name. |
| 753 |
(Since every table has an associated composite type of the same name, |
| 754 |
it actually does not matter in <productname>PostgreSQL</productname> whether you |
| 755 |
write <literal>%ROWTYPE</literal> or not. But the form with |
| 756 |
<literal>%ROWTYPE</literal> is more portable.) |
| 757 |
</para> |
| 758 |
|
| 759 |
<para> |
| 760 |
As with <literal>%TYPE</literal>, <literal>%ROWTYPE</literal> can be |
| 761 |
followed by array decoration to declare a variable that holds an array |
| 762 |
of the referenced composite type. |
| 763 |
</para> |
| 764 |
|
| 765 |
<para> |
| 766 |
Parameters to a function can be |
| 767 |
composite types (complete table rows). In that case, the |
| 768 |
corresponding identifier <literal>$<replaceable>n</replaceable></literal> will be a row variable, and fields can |
| 769 |
be selected from it, for example <literal>$1.user_id</literal>. |
| 770 |
</para> |
| 771 |
|
| 772 |
<para> |
| 773 |
Here is an example of using composite types. <structname>table1</structname> |
| 774 |
and <structname>table2</structname> are existing tables having at least the |
| 775 |
mentioned fields: |
| 776 |
|
| 777 |
<programlisting> |
| 778 |
CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$ |
| 779 |
DECLARE |
| 780 |
t2_row table2%ROWTYPE; |
| 781 |
BEGIN |
| 782 |
SELECT * INTO t2_row FROM table2 WHERE ... ; |
| 783 |
RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7; |
| 784 |
END; |
| 785 |
$$ LANGUAGE plpgsql; |
| 786 |
|
| 787 |
SELECT merge_fields(t.*) FROM table1 t WHERE ... ; |
| 788 |
</programlisting> |
| 789 |
</para> |
| 790 |
</sect2> |
| 791 |
|
| 792 |
<sect2 id="plpgsql-declaration-records"> |
| 793 |
<title>Record Types</title> |
| 794 |
|
| 795 |
<synopsis> |
| 796 |
<replaceable>name</replaceable> RECORD; |
| 797 |
</synopsis> |
| 798 |
|
| 799 |
<para> |
| 800 |
Record variables are similar to row-type variables, but they have no |
| 801 |
predefined structure. They take on the actual row structure of the |
| 802 |
row they are assigned during a <command>SELECT</command> or <command>FOR</command> command. The substructure |
| 803 |
of a record variable can change each time it is assigned to. |
| 804 |
A consequence of this is that until a record variable is first assigned |
| 805 |
to, it has no substructure, and any attempt to access a |
| 806 |
field in it will draw a run-time error. |
| 807 |
</para> |
| 808 |
|
| 809 |
<para> |
| 810 |
Note that <literal>RECORD</literal> is not a true data type, only a placeholder. |
| 811 |
One should also realize that when a <application>PL/pgSQL</application> |
| 812 |
function is declared to return type <type>record</type>, this is not quite the |
| 813 |
same concept as a record variable, even though such a function might |
| 814 |
use a record variable to hold its result. In both cases the actual row |
| 815 |
structure is unknown when the function is written, but for a function |
| 816 |
returning <type>record</type> the actual structure is determined when the |
| 817 |
calling query is parsed, whereas a record variable can change its row |
| 818 |
structure on-the-fly. |
| 819 |
</para> |
| 820 |
</sect2> |
| 821 |
|
| 822 |
<sect2 id="plpgsql-declaration-collation"> |
| 823 |
<title>Collation of <application>PL/pgSQL</application> Variables</title> |
| 824 |
|
| 825 |
<indexterm> |
| 826 |
<primary>collation</primary> |
| 827 |
<secondary>in PL/pgSQL</secondary> |
| 828 |
</indexterm> |
| 829 |
|
| 830 |
<para> |
| 831 |
When a <application>PL/pgSQL</application> function has one or more |
| 832 |
parameters of collatable data types, a collation is identified for each |
| 833 |
function call depending on the collations assigned to the actual |
| 834 |
arguments, as described in <xref linkend="collation"/>. If a collation is |
| 835 |
successfully identified (i.e., there are no conflicts of implicit |
| 836 |
collations among the arguments) then all the collatable parameters are |
| 837 |
treated as having that collation implicitly. This will affect the |
| 838 |
behavior of collation-sensitive operations within the function. |
| 839 |
For example, consider |
| 840 |
|
| 841 |
<programlisting> |
| 842 |
CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$ |
| 843 |
BEGIN |
| 844 |
RETURN a < b; |
| 845 |
END; |
| 846 |
$$ LANGUAGE plpgsql; |
| 847 |
|
| 848 |
SELECT less_than(text_field_1, text_field_2) FROM table1; |
| 849 |
SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1; |
| 850 |
</programlisting> |
| 851 |
|
| 852 |
The first use of <function>less_than</function> will use the common collation |
| 853 |
of <structfield>text_field_1</structfield> and <structfield>text_field_2</structfield> for |
| 854 |
the comparison, while the second use will use <literal>C</literal> collation. |
| 855 |
</para> |
| 856 |
|
| 857 |
<para> |
| 858 |
Furthermore, the identified collation is also assumed as the collation of |
| 859 |
any local variables that are of collatable types. Thus this function |
| 860 |
would not work any differently if it were written as |
| 861 |
|
| 862 |
<programlisting> |
| 863 |
CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$ |
| 864 |
DECLARE |
| 865 |
local_a text := a; |
| 866 |
local_b text := b; |
| 867 |
BEGIN |
| 868 |
RETURN local_a < local_b; |
| 869 |
END; |
| 870 |
$$ LANGUAGE plpgsql; |
| 871 |
</programlisting> |
| 872 |
</para> |
| 873 |
|
| 874 |
<para> |
| 875 |
If there are no parameters of collatable data types, or no common |
| 876 |
collation can be identified for them, then parameters and local variables |
| 877 |
use the default collation of their data type (which is usually the |
| 878 |
database's default collation, but could be different for variables of |
| 879 |
domain types). |
| 880 |
</para> |
| 881 |
|
| 882 |
<para> |
| 883 |
A local variable of a collatable data type can have a different collation |
| 884 |
associated with it by including the <literal>COLLATE</literal> option in its |
| 885 |
declaration, for example |
| 886 |
|
| 887 |
<programlisting> |
| 888 |
DECLARE |
| 889 |
local_a text COLLATE "en_US"; |
| 890 |
</programlisting> |
| 891 |
|
| 892 |
This option overrides the collation that would otherwise be |
| 893 |
given to the variable according to the rules above. |
| 894 |
</para> |
| 895 |
|
| 896 |
<para> |
| 897 |
Also, of course explicit <literal>COLLATE</literal> clauses can be written inside |
| 898 |
a function if it is desired to force a particular collation to be used in |
| 899 |
a particular operation. For example, |
| 900 |
|
| 901 |
<programlisting> |
| 902 |
CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$ |
| 903 |
BEGIN |
| 904 |
RETURN a < b COLLATE "C"; |
| 905 |
END; |
| 906 |
$$ LANGUAGE plpgsql; |
| 907 |
</programlisting> |
| 908 |
|
| 909 |
This overrides the collations associated with the table columns, |
| 910 |
parameters, or local variables used in the expression, just as would |
| 911 |
happen in a plain SQL command. |
| 912 |
</para> |
| 913 |
</sect2> |
| 914 |
</sect1> |
| 915 |
|
| 916 |
<sect1 id="plpgsql-expressions"> |
| 917 |
<title>Expressions</title> |
| 918 |
|
| 919 |
<para> |
| 920 |
All expressions used in <application>PL/pgSQL</application> |
| 921 |
statements are processed using the server's main |
| 922 |
<acronym>SQL</acronym> executor. For example, when you write |
| 923 |
a <application>PL/pgSQL</application> statement like |
| 924 |
<synopsis> |
| 925 |
IF <replaceable>expression</replaceable> THEN ... |
| 926 |
</synopsis> |
| 927 |
<application>PL/pgSQL</application> will evaluate the expression by |
| 928 |
feeding a query like |
| 929 |
<synopsis> |
| 930 |
SELECT <replaceable>expression</replaceable> |
| 931 |
</synopsis> |
| 932 |
to the main SQL engine. While forming the <command>SELECT</command> command, |
| 933 |
any occurrences of <application>PL/pgSQL</application> variable names |
| 934 |
are replaced by query parameters, as discussed in detail in |
| 935 |
<xref linkend="plpgsql-var-subst"/>. |
| 936 |
This allows the query plan for the <command>SELECT</command> to |
| 937 |
be prepared just once and then reused for subsequent |
| 938 |
evaluations with different values of the variables. Thus, what |
| 939 |
really happens on first use of an expression is essentially a |
| 940 |
<command>PREPARE</command> command. For example, if we have declared |
| 941 |
two integer variables <literal>x</literal> and <literal>y</literal>, and we write |
| 942 |
<programlisting> |
| 943 |
IF x < y THEN ... |
| 944 |
</programlisting> |
| 945 |
what happens behind the scenes is equivalent to |
| 946 |
<programlisting> |
| 947 |
PREPARE <replaceable>statement_name</replaceable>(integer, integer) AS SELECT $1 < $2; |
| 948 |
</programlisting> |
| 949 |
and then this prepared statement is <command>EXECUTE</command>d for each |
| 950 |
execution of the <command>IF</command> statement, with the current values |
| 951 |
of the <application>PL/pgSQL</application> variables supplied as |
| 952 |
parameter values. Normally these details are |
| 953 |
not important to a <application>PL/pgSQL</application> user, but |
| 954 |
they are useful to know when trying to diagnose a problem. |
| 955 |
More information appears in <xref linkend="plpgsql-plan-caching"/>. |
| 956 |
</para> |
| 957 |
|
| 958 |
<para> |
| 959 |
Since an <replaceable>expression</replaceable> is converted to a |
| 960 |
<literal>SELECT</literal> command, it can contain the same clauses |
| 961 |
that an ordinary <literal>SELECT</literal> would, except that it |
| 962 |
cannot include a top-level <literal>UNION</literal>, |
| 963 |
<literal>INTERSECT</literal>, or <literal>EXCEPT</literal> clause. |
| 964 |
Thus for example one could test whether a table is non-empty with |
| 965 |
<programlisting> |
| 966 |
IF count(*) > 0 FROM my_table THEN ... |
| 967 |
</programlisting> |
| 968 |
since the <replaceable>expression</replaceable> |
| 969 |
between <literal>IF</literal> and <literal>THEN</literal> is parsed as |
| 970 |
though it were <literal>SELECT count(*) > 0 FROM my_table</literal>. |
| 971 |
The <literal>SELECT</literal> must produce a single column, and not |
| 972 |
more than one row. (If it produces no rows, the result is taken as |
| 973 |
NULL.) |
| 974 |
</para> |
| 975 |
</sect1> |
| 976 |
|
| 977 |
<sect1 id="plpgsql-statements"> |
| 978 |
<title>Basic Statements</title> |
| 979 |
|
| 980 |
<para> |
| 981 |
In this section and the following ones, we describe all the statement |
| 982 |
types that are explicitly understood by |
| 983 |
<application>PL/pgSQL</application>. |
| 984 |
Anything not recognized as one of these statement types is presumed |
| 985 |
to be an SQL command and is sent to the main database engine to execute, |
| 986 |
as described in <xref linkend="plpgsql-statements-general-sql"/>. |
| 987 |
</para> |
| 988 |
|
| 989 |
<sect2 id="plpgsql-statements-assignment"> |
| 990 |
<title>Assignment</title> |
| 991 |
|
| 992 |
<para> |
| 993 |
An assignment of a value to a <application>PL/pgSQL</application> |
| 994 |
variable is written as: |
| 995 |
<synopsis> |
| 996 |
<replaceable>variable</replaceable> { := | = } <replaceable>expression</replaceable>; |
| 997 |
</synopsis> |
| 998 |
As explained previously, the expression in such a statement is evaluated |
| 999 |
by means of an SQL <command>SELECT</command> command sent to the main |
| 1000 |
database engine. The expression must yield a single value (possibly |
| 1001 |
a row value, if the variable is a row or record variable). The target |
| 1002 |
variable can be a simple variable (optionally qualified with a block |
| 1003 |
name), a field of a row or record target, or an element or slice of |
| 1004 |
an array target. Equal (<literal>=</literal>) can be |
| 1005 |
used instead of PL/SQL-compliant <literal>:=</literal>. |
| 1006 |
</para> |
| 1007 |
|
| 1008 |
<para> |
| 1009 |
If the expression's result data type doesn't match the variable's |
| 1010 |
data type, the value will be coerced as though by an assignment cast |
| 1011 |
(see <xref linkend="typeconv-query"/>). If no assignment cast is known |
| 1012 |
for the pair of data types involved, the <application>PL/pgSQL</application> |
| 1013 |
interpreter will attempt to convert the result value textually, that is |
| 1014 |
by applying the result type's output function followed by the variable |
| 1015 |
type's input function. Note that this could result in run-time errors |
| 1016 |
generated by the input function, if the string form of the result value |
| 1017 |
is not acceptable to the input function. |
| 1018 |
</para> |
| 1019 |
|
| 1020 |
<para> |
| 1021 |
Examples: |
| 1022 |
<programlisting> |
| 1023 |
tax := subtotal * 0.06; |
| 1024 |
my_record.user_id := 20; |
| 1025 |
my_array[j] := 20; |
| 1026 |
my_array[1:3] := array[1,2,3]; |
| 1027 |
complex_array[n].realpart = 12.3; |
| 1028 |
</programlisting> |
| 1029 |
</para> |
| 1030 |
</sect2> |
| 1031 |
|
| 1032 |
<sect2 id="plpgsql-statements-general-sql"> |
| 1033 |
<title>Executing SQL Commands</title> |
| 1034 |
|
| 1035 |
<para> |
| 1036 |
In general, any SQL command that does not return rows can be executed |
| 1037 |
within a <application>PL/pgSQL</application> function just by writing |
| 1038 |
the command. For example, you could create and fill a table by writing |
| 1039 |
<programlisting> |
| 1040 |
CREATE TABLE mytable (id int primary key, data text); |
| 1041 |
INSERT INTO mytable VALUES (1,'one'), (2,'two'); |
| 1042 |
</programlisting> |
| 1043 |
</para> |
| 1044 |
|
| 1045 |
<para> |
| 1046 |
If the command does return rows (for example <command>SELECT</command>, or |
| 1047 |
<command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>/<command>MERGE</command> |
| 1048 |
with <literal>RETURNING</literal>), there are two ways to proceed. |
| 1049 |
When the command will return at most one row, or you only care about |
| 1050 |
the first row of output, write the command as usual but add |
| 1051 |
an <literal>INTO</literal> clause to capture the output, as described |
| 1052 |
in <xref linkend="plpgsql-statements-sql-onerow"/>. |
| 1053 |
To process all of the output rows, write the command as the data |
| 1054 |
source for a <command>FOR</command> loop, as described in |
| 1055 |
<xref linkend="plpgsql-records-iterating"/>. |
| 1056 |
</para> |
| 1057 |
|
| 1058 |
<para> |
| 1059 |
Usually it is not sufficient just to execute statically-defined SQL |
| 1060 |
commands. Typically you'll want a command to use varying data values, |
| 1061 |
or even to vary in more fundamental ways such as by using different |
| 1062 |
table names at different times. Again, there are two ways to proceed |
| 1063 |
depending on the situation. |
| 1064 |
</para> |
| 1065 |
|
| 1066 |
<para> |
| 1067 |
<application>PL/pgSQL</application> variable values can be |
| 1068 |
automatically inserted into optimizable SQL commands, which |
| 1069 |
are <command>SELECT</command>, <command>INSERT</command>, |
| 1070 |
<command>UPDATE</command>, <command>DELETE</command>, |
| 1071 |
<command>MERGE</command>, and certain |
| 1072 |
utility commands that incorporate one of these, such |
| 1073 |
as <command>EXPLAIN</command> and <command>CREATE TABLE ... AS |
| 1074 |
SELECT</command>. In these commands, |
| 1075 |
any <application>PL/pgSQL</application> variable name appearing |
| 1076 |
in the command text is replaced by a query parameter, and then the |
| 1077 |
current value of the variable is provided as the parameter value |
| 1078 |
at run time. This is exactly like the processing described earlier |
| 1079 |
for expressions; for details see <xref linkend="plpgsql-var-subst"/>. |
| 1080 |
</para> |
| 1081 |
|
| 1082 |
<para> |
| 1083 |
When executing an optimizable SQL command in this way, |
| 1084 |
<application>PL/pgSQL</application> may cache and re-use the execution |
| 1085 |
plan for the command, as discussed in |
| 1086 |
<xref linkend="plpgsql-plan-caching"/>. |
| 1087 |
</para> |
| 1088 |
|
| 1089 |
<para> |
| 1090 |
Non-optimizable SQL commands (also called utility commands) are not |
| 1091 |
capable of accepting query parameters. So automatic substitution |
| 1092 |
of <application>PL/pgSQL</application> variables does not work in such |
| 1093 |
commands. To include non-constant text in a utility command executed |
| 1094 |
from <application>PL/pgSQL</application>, you must build the utility |
| 1095 |
command as a string and then <command>EXECUTE</command> it, as |
| 1096 |
discussed in <xref linkend="plpgsql-statements-executing-dyn"/>. |
| 1097 |
</para> |
| 1098 |
|
| 1099 |
<para> |
| 1100 |
<command>EXECUTE</command> must also be used if you want to modify |
| 1101 |
the command in some other way than supplying a data value, for example |
| 1102 |
by changing a table name. |
| 1103 |
</para> |
| 1104 |
|
| 1105 |
<para> |
| 1106 |
Sometimes it is useful to evaluate an expression or <command>SELECT</command> |
| 1107 |
query but discard the result, for example when calling a function |
| 1108 |
that has side-effects but no useful result value. To do |
| 1109 |
this in <application>PL/pgSQL</application>, use the |
| 1110 |
<command>PERFORM</command> statement: |
| 1111 |
|
| 1112 |
<synopsis> |
| 1113 |
PERFORM <replaceable>query</replaceable>; |
| 1114 |
</synopsis> |
| 1115 |
|
| 1116 |
This executes <replaceable>query</replaceable> and discards the |
| 1117 |
result. Write the <replaceable>query</replaceable> the same |
| 1118 |
way you would write an SQL <command>SELECT</command> command, but replace the |
| 1119 |
initial keyword <command>SELECT</command> with <command>PERFORM</command>. |
| 1120 |
For <command>WITH</command> queries, use <command>PERFORM</command> and then |
| 1121 |
place the query in parentheses. (In this case, the query can only |
| 1122 |
return one row.) |
| 1123 |
<application>PL/pgSQL</application> variables will be |
| 1124 |
substituted into the query just as described above, |
| 1125 |
and the plan is cached in the same way. Also, the special variable |
| 1126 |
<literal>FOUND</literal> is set to true if the query produced at |
| 1127 |
least one row, or false if it produced no rows (see |
| 1128 |
<xref linkend="plpgsql-statements-diagnostics"/>). |
| 1129 |
</para> |
| 1130 |
|
| 1131 |
<note> |
| 1132 |
<para> |
| 1133 |
One might expect that writing <command>SELECT</command> directly |
| 1134 |
would accomplish this result, but at |
| 1135 |
present the only accepted way to do it is |
| 1136 |
<command>PERFORM</command>. An SQL command that can return rows, |
| 1137 |
such as <command>SELECT</command>, will be rejected as an error |
| 1138 |
unless it has an <literal>INTO</literal> clause as discussed in the |
| 1139 |
next section. |
| 1140 |
</para> |
| 1141 |
</note> |
| 1142 |
|
| 1143 |
<para> |
| 1144 |
An example: |
| 1145 |
<programlisting> |
| 1146 |
PERFORM create_mv('cs_session_page_requests_mv', my_query); |
| 1147 |
</programlisting> |
| 1148 |
</para> |
| 1149 |
</sect2> |
| 1150 |
|
| 1151 |
<sect2 id="plpgsql-statements-sql-onerow"> |
| 1152 |
<title>Executing a Command with a Single-Row Result</title> |
| 1153 |
|
| 1154 |
<indexterm zone="plpgsql-statements-sql-onerow"> |
| 1155 |
<primary>SELECT INTO</primary> |
| 1156 |
<secondary>in PL/pgSQL</secondary> |
| 1157 |
</indexterm> |
| 1158 |
|
| 1159 |
<indexterm zone="plpgsql-statements-sql-onerow"> |
| 1160 |
<primary>RETURNING INTO</primary> |
| 1161 |
<secondary>in PL/pgSQL</secondary> |
| 1162 |
</indexterm> |
| 1163 |
|
| 1164 |
<para> |
| 1165 |
The result of an SQL command yielding a single row (possibly of multiple |
| 1166 |
columns) can be assigned to a record variable, row-type variable, or list |
| 1167 |
of scalar variables. This is done by writing the base SQL command and |
| 1168 |
adding an <literal>INTO</literal> clause. For example, |
| 1169 |
|
| 1170 |
<synopsis> |
| 1171 |
SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...; |
| 1172 |
INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>; |
| 1173 |
UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>; |
| 1174 |
DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>; |
| 1175 |
MERGE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>; |
| 1176 |
</synopsis> |
| 1177 |
|
| 1178 |
where <replaceable>target</replaceable> can be a record variable, a row |
| 1179 |
variable, or a comma-separated list of simple variables and |
| 1180 |
record/row fields. |
| 1181 |
<application>PL/pgSQL</application> variables will be |
| 1182 |
substituted into the rest of the command (that is, everything but the |
| 1183 |
<literal>INTO</literal> clause) just as described above, |
| 1184 |
and the plan is cached in the same way. |
| 1185 |
This works for <command>SELECT</command>, |
| 1186 |
<command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>/<command>MERGE</command> |
| 1187 |
with <literal>RETURNING</literal>, and certain utility commands |
| 1188 |
that return row sets, such as <command>EXPLAIN</command>. |
| 1189 |
Except for the <literal>INTO</literal> clause, the SQL command is the same |
| 1190 |
as it would be written outside <application>PL/pgSQL</application>. |
| 1191 |
</para> |
| 1192 |
|
| 1193 |
<tip> |
| 1194 |
<para> |
| 1195 |
Note that this interpretation of <command>SELECT</command> with <literal>INTO</literal> |
| 1196 |
is quite different from <productname>PostgreSQL</productname>'s regular |
| 1197 |
<command>SELECT INTO</command> command, wherein the <literal>INTO</literal> |
| 1198 |
target is a newly created table. If you want to create a table from a |
| 1199 |
<command>SELECT</command> result inside a |
| 1200 |
<application>PL/pgSQL</application> function, use the syntax |
| 1201 |
<command>CREATE TABLE ... AS SELECT</command>. |
| 1202 |
</para> |
| 1203 |
</tip> |
| 1204 |
|
| 1205 |
<para> |
| 1206 |
If a row variable or a variable list is used as target, |
| 1207 |
the command's result columns |
| 1208 |
must exactly match the structure of the target as to number and data |
| 1209 |
types, or else a run-time error |
| 1210 |
occurs. When a record variable is the target, it automatically |
| 1211 |
configures itself to the row type of the command's result columns. |
| 1212 |
</para> |
| 1213 |
|
| 1214 |
<para> |
| 1215 |
The <literal>INTO</literal> clause can appear almost anywhere in the SQL |
| 1216 |
command. Customarily it is written either just before or just after |
| 1217 |
the list of <replaceable>select_expressions</replaceable> in a |
| 1218 |
<command>SELECT</command> command, or at the end of the command for other |
| 1219 |
command types. It is recommended that you follow this convention |
| 1220 |
in case the <application>PL/pgSQL</application> parser becomes |
| 1221 |
stricter in future versions. |
| 1222 |
</para> |
| 1223 |
|
| 1224 |
<para> |
| 1225 |
If <literal>STRICT</literal> is not specified in the <literal>INTO</literal> |
| 1226 |
clause, then <replaceable>target</replaceable> will be set to the first |
| 1227 |
row returned by the command, or to nulls if the command returned no rows. |
| 1228 |
(Note that <quote>the first row</quote> is not |
| 1229 |
well-defined unless you've used <literal>ORDER BY</literal>.) Any result rows |
| 1230 |
after the first row are discarded. |
| 1231 |
You can check the special <literal>FOUND</literal> variable (see |
| 1232 |
<xref linkend="plpgsql-statements-diagnostics"/>) to |
| 1233 |
determine whether a row was returned: |
| 1234 |
|
| 1235 |
<programlisting> |
| 1236 |
SELECT * INTO myrec FROM emp WHERE empname = myname; |
| 1237 |
IF NOT FOUND THEN |
| 1238 |
RAISE EXCEPTION 'employee % not found', myname; |
| 1239 |
END IF; |
| 1240 |
</programlisting> |
| 1241 |
|
| 1242 |
If the <literal>STRICT</literal> option is specified, the command must |
| 1243 |
return exactly one row or a run-time error will be reported, either |
| 1244 |
<literal>NO_DATA_FOUND</literal> (no rows) or <literal>TOO_MANY_ROWS</literal> |
| 1245 |
(more than one row). You can use an exception block if you wish |
| 1246 |
to catch the error, for example: |
| 1247 |
|
| 1248 |
<programlisting> |
| 1249 |
BEGIN |
| 1250 |
SELECT * INTO STRICT myrec FROM emp WHERE empname = myname; |
| 1251 |
EXCEPTION |
| 1252 |
WHEN NO_DATA_FOUND THEN |
| 1253 |
RAISE EXCEPTION 'employee % not found', myname; |
| 1254 |
WHEN TOO_MANY_ROWS THEN |
| 1255 |
RAISE EXCEPTION 'employee % not unique', myname; |
| 1256 |
END; |
| 1257 |
</programlisting> |
| 1258 |
Successful execution of a command with <literal>STRICT</literal> |
| 1259 |
always sets <literal>FOUND</literal> to true. |
| 1260 |
</para> |
| 1261 |
|
| 1262 |
<para> |
| 1263 |
For <command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>/<command>MERGE</command> with |
| 1264 |
<literal>RETURNING</literal>, <application>PL/pgSQL</application> reports |
| 1265 |
an error for more than one returned row, even when |
| 1266 |
<literal>STRICT</literal> is not specified. This is because there |
| 1267 |
is no option such as <literal>ORDER BY</literal> with which to determine |
| 1268 |
which affected row should be returned. |
| 1269 |
</para> |
| 1270 |
|
| 1271 |
<para> |
| 1272 |
If <literal>print_strict_params</literal> is enabled for the function, |
| 1273 |
then when an error is thrown because the requirements |
| 1274 |
of <literal>STRICT</literal> are not met, the <literal>DETAIL</literal> part of |
| 1275 |
the error message will include information about the parameters |
| 1276 |
passed to the command. |
| 1277 |
You can change the <literal>print_strict_params</literal> |
| 1278 |
setting for all functions by setting |
| 1279 |
<varname>plpgsql.print_strict_params</varname>, though only subsequent |
| 1280 |
function compilations will be affected. You can also enable it |
| 1281 |
on a per-function basis by using a compiler option, for example: |
| 1282 |
<programlisting> |
| 1283 |
CREATE FUNCTION get_userid(username text) RETURNS int |
| 1284 |
AS $$ |
| 1285 |
#print_strict_params on |
| 1286 |
DECLARE |
| 1287 |
userid int; |
| 1288 |
BEGIN |
| 1289 |
SELECT users.userid INTO STRICT userid |
| 1290 |
FROM users WHERE users.username = get_userid.username; |
| 1291 |
RETURN userid; |
| 1292 |
END; |
| 1293 |
$$ LANGUAGE plpgsql; |
| 1294 |
</programlisting> |
| 1295 |
On failure, this function might produce an error message such as |
| 1296 |
<programlisting> |
| 1297 |
ERROR: query returned no rows |
| 1298 |
DETAIL: parameters: username = 'nosuchuser' |
| 1299 |
CONTEXT: PL/pgSQL function get_userid(text) line 6 at SQL statement |
| 1300 |
</programlisting> |
| 1301 |
</para> |
| 1302 |
|
| 1303 |
<note> |
| 1304 |
<para> |
| 1305 |
The <literal>STRICT</literal> option matches the behavior of |
| 1306 |
Oracle PL/SQL's <command>SELECT INTO</command> and related statements. |
| 1307 |
</para> |
| 1308 |
</note> |
| 1309 |
|
| 1310 |
</sect2> |
| 1311 |
|
| 1312 |
<sect2 id="plpgsql-statements-executing-dyn"> |
| 1313 |
<title>Executing Dynamic Commands</title> |
| 1314 |
|
| 1315 |
<para> |
| 1316 |
Oftentimes you will want to generate dynamic commands inside your |
| 1317 |
<application>PL/pgSQL</application> functions, that is, commands |
| 1318 |
that will involve different tables or different data types each |
| 1319 |
time they are executed. <application>PL/pgSQL</application>'s |
| 1320 |
normal attempts to cache plans for commands (as discussed in |
| 1321 |
<xref linkend="plpgsql-plan-caching"/>) will not work in such |
| 1322 |
scenarios. To handle this sort of problem, the |
| 1323 |
<command>EXECUTE</command> statement is provided: |
| 1324 |
|
| 1325 |
<synopsis> |
| 1326 |
EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>; |
| 1327 |
</synopsis> |
| 1328 |
|
| 1329 |
where <replaceable>command-string</replaceable> is an expression |
| 1330 |
yielding a string (of type <type>text</type>) containing the |
| 1331 |
command to be executed. The optional <replaceable>target</replaceable> |
| 1332 |
is a record variable, a row variable, or a comma-separated list of |
| 1333 |
simple variables and record/row fields, into which the results of |
| 1334 |
the command will be stored. The optional <literal>USING</literal> expressions |
| 1335 |
supply values to be inserted into the command. |
| 1336 |
</para> |
| 1337 |
|
| 1338 |
<para> |
| 1339 |
No substitution of <application>PL/pgSQL</application> variables is done on the |
| 1340 |
computed command string. Any required variable values must be inserted |
| 1341 |
in the command string as it is constructed; or you can use parameters |
| 1342 |
as described below. |
| 1343 |
</para> |
| 1344 |
|
| 1345 |
<para> |
| 1346 |
Also, there is no plan caching for commands executed via |
| 1347 |
<command>EXECUTE</command>. Instead, the command is always planned |
| 1348 |
each time the statement is run. Thus the command |
| 1349 |
string can be dynamically created within the function to perform |
| 1350 |
actions on different tables and columns. |
| 1351 |
</para> |
| 1352 |
|
| 1353 |
<para> |
| 1354 |
The <literal>INTO</literal> clause specifies where the results of |
| 1355 |
an SQL command returning rows should be assigned. If a row variable |
| 1356 |
or variable list is provided, it must exactly match the structure |
| 1357 |
of the command's results; if a |
| 1358 |
record variable is provided, it will configure itself to match the |
| 1359 |
result structure automatically. If multiple rows are returned, |
| 1360 |
only the first will be assigned to the <literal>INTO</literal> |
| 1361 |
variable(s). If no rows are returned, NULL is assigned to the |
| 1362 |
<literal>INTO</literal> variable(s). If no <literal>INTO</literal> |
| 1363 |
clause is specified, the command results are discarded. |
| 1364 |
</para> |
| 1365 |
|
| 1366 |
<para> |
| 1367 |
If the <literal>STRICT</literal> option is given, an error is reported |
| 1368 |
unless the command produces exactly one row. |
| 1369 |
</para> |
| 1370 |
|
| 1371 |
<para> |
| 1372 |
The command string can use parameter values, which are referenced |
| 1373 |
in the command as <literal>$1</literal>, <literal>$2</literal>, etc. |
| 1374 |
These symbols refer to values supplied in the <literal>USING</literal> |
| 1375 |
clause. This method is often preferable to inserting data values |
| 1376 |
into the command string as text: it avoids run-time overhead of |
| 1377 |
converting the values to text and back, and it is much less prone |
| 1378 |
to SQL-injection attacks since there is no need for quoting or escaping. |
| 1379 |
An example is: |
| 1380 |
<programlisting> |
| 1381 |
EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2' |
| 1382 |
INTO c |
| 1383 |
USING checked_user, checked_date; |
| 1384 |
</programlisting> |
| 1385 |
</para> |
| 1386 |
|
| 1387 |
<para> |
| 1388 |
Note that parameter symbols can only be used for data values |
| 1389 |
— if you want to use dynamically determined table or column |
| 1390 |
names, you must insert them into the command string textually. |
| 1391 |
For example, if the preceding query needed to be done against a |
| 1392 |
dynamically selected table, you could do this: |
| 1393 |
<programlisting> |
| 1394 |
EXECUTE 'SELECT count(*) FROM ' |
| 1395 |
|| quote_ident(tabname) |
| 1396 |
|| ' WHERE inserted_by = $1 AND inserted <= $2' |
| 1397 |
INTO c |
| 1398 |
USING checked_user, checked_date; |
| 1399 |
</programlisting> |
| 1400 |
A cleaner approach is to use <function>format()</function>'s <literal>%I</literal> |
| 1401 |
specification to insert table or column names with automatic quoting: |
| 1402 |
<programlisting> |
| 1403 |
EXECUTE format('SELECT count(*) FROM %I ' |
| 1404 |
'WHERE inserted_by = $1 AND inserted <= $2', tabname) |
| 1405 |
INTO c |
| 1406 |
USING checked_user, checked_date; |
| 1407 |
</programlisting> |
| 1408 |
(This example relies on the SQL rule that string literals separated by a |
| 1409 |
newline are implicitly concatenated.) |
| 1410 |
</para> |
| 1411 |
|
| 1412 |
<para> |
| 1413 |
Another restriction on parameter symbols is that they only work in |
| 1414 |
optimizable SQL commands |
| 1415 |
(<command>SELECT</command>, <command>INSERT</command>, <command>UPDATE</command>, |
| 1416 |
<command>DELETE</command>, <command>MERGE</command>, and certain commands containing one of these). |
| 1417 |
In other statement |
| 1418 |
types (generically called utility statements), you must insert |
| 1419 |
values textually even if they are just data values. |
| 1420 |
</para> |
| 1421 |
|
| 1422 |
<para> |
| 1423 |
An <command>EXECUTE</command> with a simple constant command string and some |
| 1424 |
<literal>USING</literal> parameters, as in the first example above, is |
| 1425 |
functionally equivalent to just writing the command directly in |
| 1426 |
<application>PL/pgSQL</application> and allowing replacement of |
| 1427 |
<application>PL/pgSQL</application> variables to happen automatically. |
| 1428 |
The important difference is that <command>EXECUTE</command> will re-plan |
| 1429 |
the command on each execution, generating a plan that is specific |
| 1430 |
to the current parameter values; whereas |
| 1431 |
<application>PL/pgSQL</application> may otherwise create a generic plan |
| 1432 |
and cache it for re-use. In situations where the best plan depends |
| 1433 |
strongly on the parameter values, it can be helpful to use |
| 1434 |
<command>EXECUTE</command> to positively ensure that a generic plan is not |
| 1435 |
selected. |
| 1436 |
</para> |
| 1437 |
|
| 1438 |
<para> |
| 1439 |
<command>SELECT INTO</command> is not currently supported within |
| 1440 |
<command>EXECUTE</command>; instead, execute a plain <command>SELECT</command> |
| 1441 |
command and specify <literal>INTO</literal> as part of the <command>EXECUTE</command> |
| 1442 |
itself. |
| 1443 |
</para> |
| 1444 |
|
| 1445 |
<note> |
| 1446 |
<para> |
| 1447 |
The <application>PL/pgSQL</application> |
| 1448 |
<command>EXECUTE</command> statement is not related to the |
| 1449 |
<link linkend="sql-execute"><command>EXECUTE</command></link> SQL |
| 1450 |
statement supported by the |
| 1451 |
<productname>PostgreSQL</productname> server. The server's |
| 1452 |
<command>EXECUTE</command> statement cannot be used directly within |
| 1453 |
<application>PL/pgSQL</application> functions (and is not needed). |
| 1454 |
</para> |
| 1455 |
</note> |
| 1456 |
|
| 1457 |
<example id="plpgsql-quote-literal-example"> |
| 1458 |
<title>Quoting Values in Dynamic Queries</title> |
| 1459 |
|
| 1460 |
<indexterm> |
| 1461 |
<primary>quote_ident</primary> |
| 1462 |
<secondary>use in PL/pgSQL</secondary> |
| 1463 |
</indexterm> |
| 1464 |
|
| 1465 |
<indexterm> |
| 1466 |
<primary>quote_literal</primary> |
| 1467 |
<secondary>use in PL/pgSQL</secondary> |
| 1468 |
</indexterm> |
| 1469 |
|
| 1470 |
<indexterm> |
| 1471 |
<primary>quote_nullable</primary> |
| 1472 |
<secondary>use in PL/pgSQL</secondary> |
| 1473 |
</indexterm> |
| 1474 |
|
| 1475 |
<indexterm> |
| 1476 |
<primary>format</primary> |
| 1477 |
<secondary>use in PL/pgSQL</secondary> |
| 1478 |
</indexterm> |
| 1479 |
|
| 1480 |
<para> |
| 1481 |
When working with dynamic commands you will often have to handle escaping |
| 1482 |
of single quotes. The recommended method for quoting fixed text in your |
| 1483 |
function body is dollar quoting. (If you have legacy code that does |
| 1484 |
not use dollar quoting, please refer to the |
| 1485 |
overview in <xref linkend="plpgsql-quote-tips"/>, which can save you |
| 1486 |
some effort when translating said code to a more reasonable scheme.) |
| 1487 |
</para> |
| 1488 |
|
| 1489 |
<para> |
| 1490 |
Dynamic values require careful handling since they might contain |
| 1491 |
quote characters. |
| 1492 |
An example using <function>format()</function> (this assumes that you are |
| 1493 |
dollar quoting the function body so quote marks need not be doubled): |
| 1494 |
<programlisting> |
| 1495 |
EXECUTE format('UPDATE tbl SET %I = $1 ' |
| 1496 |
'WHERE key = $2', colname) USING newvalue, keyvalue; |
| 1497 |
</programlisting> |
| 1498 |
It is also possible to call the quoting functions directly: |
| 1499 |
<programlisting> |
| 1500 |
EXECUTE 'UPDATE tbl SET ' |
| 1501 |
|| quote_ident(colname) |
| 1502 |
|| ' = ' |
| 1503 |
|| quote_literal(newvalue) |
| 1504 |
|| ' WHERE key = ' |
| 1505 |
|| quote_literal(keyvalue); |
| 1506 |
</programlisting> |
| 1507 |
</para> |
| 1508 |
|
| 1509 |
<para> |
| 1510 |
This example demonstrates the use of the |
| 1511 |
<function>quote_ident</function> and |
| 1512 |
<function>quote_literal</function> functions (see <xref |
| 1513 |
linkend="functions-string"/>). For safety, expressions containing column |
| 1514 |
or table identifiers should be passed through |
| 1515 |
<function>quote_ident</function> before insertion in a dynamic query. |
| 1516 |
Expressions containing values that should be literal strings in the |
| 1517 |
constructed command should be passed through <function>quote_literal</function>. |
| 1518 |
These functions take the appropriate steps to return the input text |
| 1519 |
enclosed in double or single quotes respectively, with any embedded |
| 1520 |
special characters properly escaped. |
| 1521 |
</para> |
| 1522 |
|
| 1523 |
<para> |
| 1524 |
Because <function>quote_literal</function> is labeled |
| 1525 |
<literal>STRICT</literal>, it will always return null when called with a |
| 1526 |
null argument. In the above example, if <literal>newvalue</literal> or |
| 1527 |
<literal>keyvalue</literal> were null, the entire dynamic query string would |
| 1528 |
become null, leading to an error from <command>EXECUTE</command>. |
| 1529 |
You can avoid this problem by using the <function>quote_nullable</function> |
| 1530 |
function, which works the same as <function>quote_literal</function> except that |
| 1531 |
when called with a null argument it returns the string <literal>NULL</literal>. |
| 1532 |
For example, |
| 1533 |
<programlisting> |
| 1534 |
EXECUTE 'UPDATE tbl SET ' |
| 1535 |
|| quote_ident(colname) |
| 1536 |
|| ' = ' |
| 1537 |
|| quote_nullable(newvalue) |
| 1538 |
|| ' WHERE key = ' |
| 1539 |
|| quote_nullable(keyvalue); |
| 1540 |
</programlisting> |
| 1541 |
If you are dealing with values that might be null, you should usually |
| 1542 |
use <function>quote_nullable</function> in place of <function>quote_literal</function>. |
| 1543 |
</para> |
| 1544 |
|
| 1545 |
<para> |
| 1546 |
As always, care must be taken to ensure that null values in a query do |
| 1547 |
not deliver unintended results. For example the <literal>WHERE</literal> clause |
| 1548 |
<programlisting> |
| 1549 |
'WHERE key = ' || quote_nullable(keyvalue) |
| 1550 |
</programlisting> |
| 1551 |
will never succeed if <literal>keyvalue</literal> is null, because the |
| 1552 |
result of using the equality operator <literal>=</literal> with a null operand |
| 1553 |
is always null. If you wish null to work like an ordinary key value, |
| 1554 |
you would need to rewrite the above as |
| 1555 |
<programlisting> |
| 1556 |
'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue) |
| 1557 |
</programlisting> |
| 1558 |
(At present, <literal>IS NOT DISTINCT FROM</literal> is handled much less |
| 1559 |
efficiently than <literal>=</literal>, so don't do this unless you must. |
| 1560 |
See <xref linkend="functions-comparison"/> for |
| 1561 |
more information on nulls and <literal>IS DISTINCT</literal>.) |
| 1562 |
</para> |
| 1563 |
|
| 1564 |
<para> |
| 1565 |
Note that dollar quoting is only useful for quoting fixed text. |
| 1566 |
It would be a very bad idea to try to write this example as: |
| 1567 |
<programlisting> |
| 1568 |
EXECUTE 'UPDATE tbl SET ' |
| 1569 |
|| quote_ident(colname) |
| 1570 |
|| ' = $$' |
| 1571 |
|| newvalue |
| 1572 |
|| '$$ WHERE key = ' |
| 1573 |
|| quote_literal(keyvalue); |
| 1574 |
</programlisting> |
| 1575 |
because it would break if the contents of <literal>newvalue</literal> |
| 1576 |
happened to contain <literal>$$</literal>. The same objection would |
| 1577 |
apply to any other dollar-quoting delimiter you might pick. |
| 1578 |
So, to safely quote text that is not known in advance, you |
| 1579 |
<emphasis>must</emphasis> use <function>quote_literal</function>, |
| 1580 |
<function>quote_nullable</function>, or <function>quote_ident</function>, as appropriate. |
| 1581 |
</para> |
| 1582 |
|
| 1583 |
<para> |
| 1584 |
Dynamic SQL statements can also be safely constructed using the |
| 1585 |
<function>format</function> function (see <xref |
| 1586 |
linkend="functions-string-format"/>). For example: |
| 1587 |
<programlisting> |
| 1588 |
EXECUTE format('UPDATE tbl SET %I = %L ' |
| 1589 |
'WHERE key = %L', colname, newvalue, keyvalue); |
| 1590 |
</programlisting> |
| 1591 |
<literal>%I</literal> is equivalent to <function>quote_ident</function>, and |
| 1592 |
<literal>%L</literal> is equivalent to <function>quote_nullable</function>. |
| 1593 |
The <function>format</function> function can be used in conjunction with |
| 1594 |
the <literal>USING</literal> clause: |
| 1595 |
<programlisting> |
| 1596 |
EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname) |
| 1597 |
USING newvalue, keyvalue; |
| 1598 |
</programlisting> |
| 1599 |
This form is better because the variables are handled in their native |
| 1600 |
data type format, rather than unconditionally converting them to |
| 1601 |
text and quoting them via <literal>%L</literal>. It is also more efficient. |
| 1602 |
</para> |
| 1603 |
</example> |
| 1604 |
|
| 1605 |
<para> |
| 1606 |
A much larger example of a dynamic command and |
| 1607 |
<command>EXECUTE</command> can be seen in <xref |
| 1608 |
linkend="plpgsql-porting-ex2"/>, which builds and executes a |
| 1609 |
<command>CREATE FUNCTION</command> command to define a new function. |
| 1610 |
</para> |
| 1611 |
</sect2> |
| 1612 |
|
| 1613 |
<sect2 id="plpgsql-statements-diagnostics"> |
| 1614 |
<title>Obtaining the Result Status</title> |
| 1615 |
|
| 1616 |
<para> |
| 1617 |
There are several ways to determine the effect of a command. The |
| 1618 |
first method is to use the <command>GET DIAGNOSTICS</command> |
| 1619 |
command, which has the form: |
| 1620 |
|
| 1621 |
<synopsis> |
| 1622 |
GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>; |
| 1623 |
</synopsis> |
| 1624 |
|
| 1625 |
This command allows retrieval of system status indicators. |
| 1626 |
<literal>CURRENT</literal> is a noise word (but see also <command>GET STACKED |
| 1627 |
DIAGNOSTICS</command> in <xref linkend="plpgsql-exception-diagnostics"/>). |
| 1628 |
Each <replaceable>item</replaceable> is a key word identifying a status |
| 1629 |
value to be assigned to the specified <replaceable>variable</replaceable> |
| 1630 |
(which should be of the right data type to receive it). The currently |
| 1631 |
available status items are shown |
| 1632 |
in <xref linkend="plpgsql-current-diagnostics-values"/>. Colon-equal |
| 1633 |
(<literal>:=</literal>) can be used instead of the SQL-standard <literal>=</literal> |
| 1634 |
token. An example: |
| 1635 |
<programlisting> |
| 1636 |
GET DIAGNOSTICS integer_var = ROW_COUNT; |
| 1637 |
</programlisting> |
| 1638 |
</para> |
| 1639 |
|
| 1640 |
<table id="plpgsql-current-diagnostics-values"> |
| 1641 |
<title>Available Diagnostics Items</title> |
| 1642 |
<tgroup cols="3"> |
| 1643 |
<colspec colname="col1" colwidth="1*"/> |
| 1644 |
<colspec colname="col2" colwidth="1*"/> |
| 1645 |
<colspec colname="col3" colwidth="2*"/> |
| 1646 |
<thead> |
| 1647 |
<row> |
| 1648 |
<entry>Name</entry> |
| 1649 |
<entry>Type</entry> |
| 1650 |
<entry>Description</entry> |
| 1651 |
</row> |
| 1652 |
</thead> |
| 1653 |
<tbody> |
| 1654 |
<row> |
| 1655 |
<entry><varname>ROW_COUNT</varname></entry> |
| 1656 |
<entry><type>bigint</type></entry> |
| 1657 |
<entry>the number of rows processed by the most |
| 1658 |
recent <acronym>SQL</acronym> command</entry> |
| 1659 |
</row> |
| 1660 |
<row> |
| 1661 |
<entry><literal>PG_CONTEXT</literal></entry> |
| 1662 |
<entry><type>text</type></entry> |
| 1663 |
<entry>line(s) of text describing the current call stack |
| 1664 |
(see <xref linkend="plpgsql-call-stack"/>)</entry> |
| 1665 |
</row> |
| 1666 |
<row> |
| 1667 |
<entry><literal>PG_ROUTINE_OID</literal></entry> |
| 1668 |
<entry><type>oid</type></entry> |
| 1669 |
<entry>OID of the current function</entry> |
| 1670 |
</row> |
| 1671 |
</tbody> |
| 1672 |
</tgroup> |
| 1673 |
</table> |
| 1674 |
|
| 1675 |
<para> |
| 1676 |
The second method to determine the effects of a command is to check the |
| 1677 |
special variable named <literal>FOUND</literal>, which is of |
| 1678 |
type <type>boolean</type>. <literal>FOUND</literal> starts out |
| 1679 |
false within each <application>PL/pgSQL</application> function call. |
| 1680 |
It is set by each of the following types of statements: |
| 1681 |
|
| 1682 |
<itemizedlist> |
| 1683 |
<listitem> |
| 1684 |
<para> |
| 1685 |
A <command>SELECT INTO</command> statement sets |
| 1686 |
<literal>FOUND</literal> true if a row is assigned, false if no |
| 1687 |
row is returned. |
| 1688 |
</para> |
| 1689 |
</listitem> |
| 1690 |
<listitem> |
| 1691 |
<para> |
| 1692 |
A <command>PERFORM</command> statement sets <literal>FOUND</literal> |
| 1693 |
true if it produces (and discards) one or more rows, false if |
| 1694 |
no row is produced. |
| 1695 |
</para> |
| 1696 |
</listitem> |
| 1697 |
<listitem> |
| 1698 |
<para> |
| 1699 |
<command>UPDATE</command>, <command>INSERT</command>, <command>DELETE</command>, |
| 1700 |
and <command>MERGE</command> |
| 1701 |
statements set <literal>FOUND</literal> true if at least one |
| 1702 |
row is affected, false if no row is affected. |
| 1703 |
</para> |
| 1704 |
</listitem> |
| 1705 |
<listitem> |
| 1706 |
<para> |
| 1707 |
A <command>FETCH</command> statement sets <literal>FOUND</literal> |
| 1708 |
true if it returns a row, false if no row is returned. |
| 1709 |
</para> |
| 1710 |
</listitem> |
| 1711 |
<listitem> |
| 1712 |
<para> |
| 1713 |
A <command>MOVE</command> statement sets <literal>FOUND</literal> |
| 1714 |
true if it successfully repositions the cursor, false otherwise. |
| 1715 |
</para> |
| 1716 |
</listitem> |
| 1717 |
<listitem> |
| 1718 |
<para> |
| 1719 |
A <command>FOR</command> or <command>FOREACH</command> statement sets |
| 1720 |
<literal>FOUND</literal> true |
| 1721 |
if it iterates one or more times, else false. |
| 1722 |
<literal>FOUND</literal> is set this way when the |
| 1723 |
loop exits; inside the execution of the loop, |
| 1724 |
<literal>FOUND</literal> is not modified by the |
| 1725 |
loop statement, although it might be changed by the |
| 1726 |
execution of other statements within the loop body. |
| 1727 |
</para> |
| 1728 |
</listitem> |
| 1729 |
<listitem> |
| 1730 |
<para> |
| 1731 |
<command>RETURN QUERY</command> and <command>RETURN QUERY |
| 1732 |
EXECUTE</command> statements set <literal>FOUND</literal> |
| 1733 |
true if the query returns at least one row, false if no row |
| 1734 |
is returned. |
| 1735 |
</para> |
| 1736 |
</listitem> |
| 1737 |
</itemizedlist> |
| 1738 |
|
| 1739 |
Other <application>PL/pgSQL</application> statements do not change |
| 1740 |
the state of <literal>FOUND</literal>. |
| 1741 |
Note in particular that <command>EXECUTE</command> |
| 1742 |
changes the output of <command>GET DIAGNOSTICS</command>, but |
| 1743 |
does not change <literal>FOUND</literal>. |
| 1744 |
</para> |
| 1745 |
|
| 1746 |
<para> |
| 1747 |
<literal>FOUND</literal> is a local variable within each |
| 1748 |
<application>PL/pgSQL</application> function; any changes to it |
| 1749 |
affect only the current function. |
| 1750 |
</para> |
| 1751 |
|
| 1752 |
</sect2> |
| 1753 |
|
| 1754 |
<sect2 id="plpgsql-statements-null"> |
| 1755 |
<title>Doing Nothing At All</title> |
| 1756 |
|
| 1757 |
<para> |
| 1758 |
Sometimes a placeholder statement that does nothing is useful. |
| 1759 |
For example, it can indicate that one arm of an if/then/else |
| 1760 |
chain is deliberately empty. For this purpose, use the |
| 1761 |
<command>NULL</command> statement: |
| 1762 |
|
| 1763 |
<synopsis> |
| 1764 |
NULL; |
| 1765 |
</synopsis> |
| 1766 |
</para> |
| 1767 |
|
| 1768 |
<para> |
| 1769 |
For example, the following two fragments of code are equivalent: |
| 1770 |
<programlisting> |
| 1771 |
BEGIN |
| 1772 |
y := x / 0; |
| 1773 |
EXCEPTION |
| 1774 |
WHEN division_by_zero THEN |
| 1775 |
NULL; -- ignore the error |
| 1776 |
END; |
| 1777 |
</programlisting> |
| 1778 |
|
| 1779 |
<programlisting> |
| 1780 |
BEGIN |
| 1781 |
y := x / 0; |
| 1782 |
EXCEPTION |
| 1783 |
WHEN division_by_zero THEN -- ignore the error |
| 1784 |
END; |
| 1785 |
</programlisting> |
| 1786 |
Which is preferable is a matter of taste. |
| 1787 |
</para> |
| 1788 |
|
| 1789 |
<note> |
| 1790 |
<para> |
| 1791 |
In Oracle's PL/SQL, empty statement lists are not allowed, and so |
| 1792 |
<command>NULL</command> statements are <emphasis>required</emphasis> for situations |
| 1793 |
such as this. <application>PL/pgSQL</application> allows you to |
| 1794 |
just write nothing, instead. |
| 1795 |
</para> |
| 1796 |
</note> |
| 1797 |
|
| 1798 |
</sect2> |
| 1799 |
</sect1> |
| 1800 |
|
| 1801 |
<sect1 id="plpgsql-control-structures"> |
| 1802 |
<title>Control Structures</title> |
| 1803 |
|
| 1804 |
<para> |
| 1805 |
Control structures are probably the most useful (and |
| 1806 |
important) part of <application>PL/pgSQL</application>. With |
| 1807 |
<application>PL/pgSQL</application>'s control structures, |
| 1808 |
you can manipulate <productname>PostgreSQL</productname> data in a very |
| 1809 |
flexible and powerful way. |
| 1810 |
</para> |
| 1811 |
|
| 1812 |
<sect2 id="plpgsql-statements-returning"> |
| 1813 |
<title>Returning from a Function</title> |
| 1814 |
|
| 1815 |
<para> |
| 1816 |
There are two commands available that allow you to return data |
| 1817 |
from a function: <command>RETURN</command> and <command>RETURN |
| 1818 |
NEXT</command>. |
| 1819 |
</para> |
| 1820 |
|
| 1821 |
<sect3 id="plpgsql-statements-returning-return"> |
| 1822 |
<title><command>RETURN</command></title> |
| 1823 |
|
| 1824 |
<synopsis> |
| 1825 |
RETURN <replaceable>expression</replaceable>; |
| 1826 |
</synopsis> |
| 1827 |
|
| 1828 |
<para> |
| 1829 |
<command>RETURN</command> with an expression terminates the |
| 1830 |
function and returns the value of |
| 1831 |
<replaceable>expression</replaceable> to the caller. This form |
| 1832 |
is used for <application>PL/pgSQL</application> functions that do |
| 1833 |
not return a set. |
| 1834 |
</para> |
| 1835 |
|
| 1836 |
<para> |
| 1837 |
In a function that returns a scalar type, the expression's result will |
| 1838 |
automatically be cast into the function's return type as described for |
| 1839 |
assignments. But to return a composite (row) value, you must write an |
| 1840 |
expression delivering exactly the requested column set. This may |
| 1841 |
require use of explicit casting. |
| 1842 |
</para> |
| 1843 |
|
| 1844 |
<para> |
| 1845 |
If you declared the function with output parameters, write just |
| 1846 |
<command>RETURN</command> with no expression. The current values |
| 1847 |
of the output parameter variables will be returned. |
| 1848 |
</para> |
| 1849 |
|
| 1850 |
<para> |
| 1851 |
If you declared the function to return <type>void</type>, a |
| 1852 |
<command>RETURN</command> statement can be used to exit the function |
| 1853 |
early; but do not write an expression following |
| 1854 |
<command>RETURN</command>. |
| 1855 |
</para> |
| 1856 |
|
| 1857 |
<para> |
| 1858 |
The return value of a function cannot be left undefined. If |
| 1859 |
control reaches the end of the top-level block of the function |
| 1860 |
without hitting a <command>RETURN</command> statement, a run-time |
| 1861 |
error will occur. This restriction does not apply to functions |
| 1862 |
with output parameters and functions returning <type>void</type>, |
| 1863 |
however. In those cases a <command>RETURN</command> statement is |
| 1864 |
automatically executed if the top-level block finishes. |
| 1865 |
</para> |
| 1866 |
|
| 1867 |
<para> |
| 1868 |
Some examples: |
| 1869 |
|
| 1870 |
<programlisting> |
| 1871 |
-- functions returning a scalar type |
| 1872 |
RETURN 1 + 2; |
| 1873 |
RETURN scalar_var; |
| 1874 |
|
| 1875 |
-- functions returning a composite type |
| 1876 |
RETURN composite_type_var; |
| 1877 |
RETURN (1, 2, 'three'::text); -- must cast columns to correct types |
| 1878 |
</programlisting> |
| 1879 |
</para> |
| 1880 |
</sect3> |
| 1881 |
|
| 1882 |
<sect3 id="plpgsql-statements-returning-return-next"> |
| 1883 |
<title><command>RETURN NEXT</command> and <command>RETURN QUERY</command></title> |
| 1884 |
<indexterm> |
| 1885 |
<primary>RETURN NEXT</primary> |
| 1886 |
<secondary>in PL/pgSQL</secondary> |
| 1887 |
</indexterm> |
| 1888 |
<indexterm> |
| 1889 |
<primary>RETURN QUERY</primary> |
| 1890 |
<secondary>in PL/pgSQL</secondary> |
| 1891 |
</indexterm> |
| 1892 |
|
| 1893 |
<synopsis> |
| 1894 |
RETURN NEXT <replaceable>expression</replaceable>; |
| 1895 |
RETURN QUERY <replaceable>query</replaceable>; |
| 1896 |
RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>; |
| 1897 |
</synopsis> |
| 1898 |
|
| 1899 |
<para> |
| 1900 |
When a <application>PL/pgSQL</application> function is declared to return |
| 1901 |
<literal>SETOF <replaceable>sometype</replaceable></literal>, the procedure |
| 1902 |
to follow is slightly different. In that case, the individual |
| 1903 |
items to return are specified by a sequence of <command>RETURN |
| 1904 |
NEXT</command> or <command>RETURN QUERY</command> commands, and |
| 1905 |
then a final <command>RETURN</command> command with no argument |
| 1906 |
is used to indicate that the function has finished executing. |
| 1907 |
<command>RETURN NEXT</command> can be used with both scalar and |
| 1908 |
composite data types; with a composite result type, an entire |
| 1909 |
<quote>table</quote> of results will be returned. |
| 1910 |
<command>RETURN QUERY</command> appends the results of executing |
| 1911 |
a query to the function's result set. <command>RETURN |
| 1912 |
NEXT</command> and <command>RETURN QUERY</command> can be freely |
| 1913 |
intermixed in a single set-returning function, in which case |
| 1914 |
their results will be concatenated. |
| 1915 |
</para> |
| 1916 |
|
| 1917 |
<para> |
| 1918 |
<command>RETURN NEXT</command> and <command>RETURN |
| 1919 |
QUERY</command> do not actually return from the function — |
| 1920 |
they simply append zero or more rows to the function's result |
| 1921 |
set. Execution then continues with the next statement in the |
| 1922 |
<application>PL/pgSQL</application> function. As successive |
| 1923 |
<command>RETURN NEXT</command> or <command>RETURN |
| 1924 |
QUERY</command> commands are executed, the result set is built |
| 1925 |
up. A final <command>RETURN</command>, which should have no |
| 1926 |
argument, causes control to exit the function (or you can just |
| 1927 |
let control reach the end of the function). |
| 1928 |
</para> |
| 1929 |
|
| 1930 |
<para> |
| 1931 |
<command>RETURN QUERY</command> has a variant |
| 1932 |
<command>RETURN QUERY EXECUTE</command>, which specifies the |
| 1933 |
query to be executed dynamically. Parameter expressions can |
| 1934 |
be inserted into the computed query string via <literal>USING</literal>, |
| 1935 |
in just the same way as in the <command>EXECUTE</command> command. |
| 1936 |
</para> |
| 1937 |
|
| 1938 |
<para> |
| 1939 |
If you declared the function with output parameters, write just |
| 1940 |
<command>RETURN NEXT</command> with no expression. On each |
| 1941 |
execution, the current values of the output parameter |
| 1942 |
variable(s) will be saved for eventual return as a row of the |
| 1943 |
result. Note that you must declare the function as returning |
| 1944 |
<literal>SETOF record</literal> when there are multiple output |
| 1945 |
parameters, or <literal>SETOF <replaceable>sometype</replaceable></literal> |
| 1946 |
when there is just one output parameter of type |
| 1947 |
<replaceable>sometype</replaceable>, in order to create a set-returning |
| 1948 |
function with output parameters. |
| 1949 |
</para> |
| 1950 |
|
| 1951 |
<para> |
| 1952 |
Here is an example of a function using <command>RETURN |
| 1953 |
NEXT</command>: |
| 1954 |
|
| 1955 |
<programlisting> |
| 1956 |
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT); |
| 1957 |
INSERT INTO foo VALUES (1, 2, 'three'); |
| 1958 |
INSERT INTO foo VALUES (4, 5, 'six'); |
| 1959 |
|
| 1960 |
CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS |
| 1961 |
$BODY$ |
| 1962 |
DECLARE |
| 1963 |
r foo%rowtype; |
| 1964 |
BEGIN |
| 1965 |
FOR r IN |
| 1966 |
SELECT * FROM foo WHERE fooid > 0 |
| 1967 |
LOOP |
| 1968 |
-- can do some processing here |
| 1969 |
RETURN NEXT r; -- return current row of SELECT |
| 1970 |
END LOOP; |
| 1971 |
RETURN; |
| 1972 |
END; |
| 1973 |
$BODY$ |
| 1974 |
LANGUAGE plpgsql; |
| 1975 |
|
| 1976 |
SELECT * FROM get_all_foo(); |
| 1977 |
</programlisting> |
| 1978 |
</para> |
| 1979 |
|
| 1980 |
<para> |
| 1981 |
Here is an example of a function using <command>RETURN |
| 1982 |
QUERY</command>: |
| 1983 |
|
| 1984 |
<programlisting> |
| 1985 |
CREATE FUNCTION get_available_flightid(date) RETURNS SETOF integer AS |
| 1986 |
$BODY$ |
| 1987 |
BEGIN |
| 1988 |
RETURN QUERY SELECT flightid |
| 1989 |
FROM flight |
| 1990 |
WHERE flightdate >= $1 |
| 1991 |
AND flightdate < ($1 + 1); |
| 1992 |
|
| 1993 |
-- Since execution is not finished, we can check whether rows were returned |
| 1994 |
-- and raise exception if not. |
| 1995 |
IF NOT FOUND THEN |
| 1996 |
RAISE EXCEPTION 'No flight at %.', $1; |
| 1997 |
END IF; |
| 1998 |
|
| 1999 |
RETURN; |
| 2000 |
END; |
| 2001 |
$BODY$ |
| 2002 |
LANGUAGE plpgsql; |
| 2003 |
|
| 2004 |
-- Returns available flights or raises exception if there are no |
| 2005 |
-- available flights. |
| 2006 |
SELECT * FROM get_available_flightid(CURRENT_DATE); |
| 2007 |
</programlisting> |
| 2008 |
</para> |
| 2009 |
|
| 2010 |
<note> |
| 2011 |
<para> |
| 2012 |
The current implementation of <command>RETURN NEXT</command> |
| 2013 |
and <command>RETURN QUERY</command> stores the entire result set |
| 2014 |
before returning from the function, as discussed above. That |
| 2015 |
means that if a <application>PL/pgSQL</application> function produces a |
| 2016 |
very large result set, performance might be poor: data will be |
| 2017 |
written to disk to avoid memory exhaustion, but the function |
| 2018 |
itself will not return until the entire result set has been |
| 2019 |
generated. A future version of <application>PL/pgSQL</application> might |
| 2020 |
allow users to define set-returning functions |
| 2021 |
that do not have this limitation. Currently, the point at |
| 2022 |
which data begins being written to disk is controlled by the |
| 2023 |
<xref linkend="guc-work-mem"/> |
| 2024 |
configuration variable. Administrators who have sufficient |
| 2025 |
memory to store larger result sets in memory should consider |
| 2026 |
increasing this parameter. |
| 2027 |
</para> |
| 2028 |
</note> |
| 2029 |
</sect3> |
| 2030 |
</sect2> |
| 2031 |
|
| 2032 |
<sect2 id="plpgsql-statements-returning-procedure"> |
| 2033 |
<title>Returning from a Procedure</title> |
| 2034 |
|
| 2035 |
<para> |
| 2036 |
A procedure does not have a return value. A procedure can therefore end |
| 2037 |
without a <command>RETURN</command> statement. If you wish to use |
| 2038 |
a <command>RETURN</command> statement to exit the code early, write |
| 2039 |
just <command>RETURN</command> with no expression. |
| 2040 |
</para> |
| 2041 |
|
| 2042 |
<para> |
| 2043 |
If the procedure has output parameters, the final values of the output |
| 2044 |
parameter variables will be returned to the caller. |
| 2045 |
</para> |
| 2046 |
</sect2> |
| 2047 |
|
| 2048 |
<sect2 id="plpgsql-statements-calling-procedure"> |
| 2049 |
<title>Calling a Procedure</title> |
| 2050 |
|
| 2051 |
<para> |
| 2052 |
A <application>PL/pgSQL</application> function, procedure, |
| 2053 |
or <command>DO</command> block can call a procedure |
| 2054 |
using <command>CALL</command>. Output parameters are handled |
| 2055 |
differently from the way that <command>CALL</command> works in plain |
| 2056 |
SQL. Each <literal>OUT</literal> or <literal>INOUT</literal> |
| 2057 |
parameter of the procedure must |
| 2058 |
correspond to a variable in the <command>CALL</command> statement, and |
| 2059 |
whatever the procedure returns is assigned back to that variable after |
| 2060 |
it returns. For example: |
| 2061 |
<programlisting> |
| 2062 |
CREATE PROCEDURE triple(INOUT x int) |
| 2063 |
LANGUAGE plpgsql |
| 2064 |
AS $$ |
| 2065 |
BEGIN |
| 2066 |
x := x * 3; |
| 2067 |
END; |
| 2068 |
$$; |
| 2069 |
|
| 2070 |
DO $$ |
| 2071 |
DECLARE myvar int := 5; |
| 2072 |
BEGIN |
| 2073 |
CALL triple(myvar); |
| 2074 |
RAISE NOTICE 'myvar = %', myvar; -- prints 15 |
| 2075 |
END; |
| 2076 |
$$; |
| 2077 |
</programlisting> |
| 2078 |
The variable corresponding to an output parameter can be a simple |
| 2079 |
variable or a field of a composite-type variable. Currently, |
| 2080 |
it cannot be an element of an array. |
| 2081 |
</para> |
| 2082 |
</sect2> |
| 2083 |
|
| 2084 |
<sect2 id="plpgsql-conditionals"> |
| 2085 |
<title>Conditionals</title> |
| 2086 |
|
| 2087 |
<para> |
| 2088 |
<command>IF</command> and <command>CASE</command> statements let you execute |
| 2089 |
alternative commands based on certain conditions. |
| 2090 |
<application>PL/pgSQL</application> has three forms of <command>IF</command>: |
| 2091 |
<itemizedlist> |
| 2092 |
<listitem> |
| 2093 |
<para><literal>IF ... THEN ... END IF</literal></para> |
| 2094 |
</listitem> |
| 2095 |
<listitem> |
| 2096 |
<para><literal>IF ... THEN ... ELSE ... END IF</literal></para> |
| 2097 |
</listitem> |
| 2098 |
<listitem> |
| 2099 |
<para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF</literal></para> |
| 2100 |
</listitem> |
| 2101 |
</itemizedlist> |
| 2102 |
|
| 2103 |
and two forms of <command>CASE</command>: |
| 2104 |
<itemizedlist> |
| 2105 |
<listitem> |
| 2106 |
<para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</literal></para> |
| 2107 |
</listitem> |
| 2108 |
<listitem> |
| 2109 |
<para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</literal></para> |
| 2110 |
</listitem> |
| 2111 |
</itemizedlist> |
| 2112 |
</para> |
| 2113 |
|
| 2114 |
<sect3 id="plpgsql-conditionals-if-then"> |
| 2115 |
<title><literal>IF-THEN</literal></title> |
| 2116 |
|
| 2117 |
<synopsis> |
| 2118 |
IF <replaceable>boolean-expression</replaceable> THEN |
| 2119 |
<replaceable>statements</replaceable> |
| 2120 |
END IF; |
| 2121 |
</synopsis> |
| 2122 |
|
| 2123 |
<para> |
| 2124 |
<literal>IF-THEN</literal> statements are the simplest form of |
| 2125 |
<literal>IF</literal>. The statements between |
| 2126 |
<literal>THEN</literal> and <literal>END IF</literal> will be |
| 2127 |
executed if the condition is true. Otherwise, they are |
| 2128 |
skipped. |
| 2129 |
</para> |
| 2130 |
|
| 2131 |
<para> |
| 2132 |
Example: |
| 2133 |
<programlisting> |
| 2134 |
IF v_user_id <> 0 THEN |
| 2135 |
UPDATE users SET email = v_email WHERE user_id = v_user_id; |
| 2136 |
END IF; |
| 2137 |
</programlisting> |
| 2138 |
</para> |
| 2139 |
</sect3> |
| 2140 |
|
| 2141 |
<sect3 id="plpgsql-conditionals-if-then-else"> |
| 2142 |
<title><literal>IF-THEN-ELSE</literal></title> |
| 2143 |
|
| 2144 |
<synopsis> |
| 2145 |
IF <replaceable>boolean-expression</replaceable> THEN |
| 2146 |
<replaceable>statements</replaceable> |
| 2147 |
ELSE |
| 2148 |
<replaceable>statements</replaceable> |
| 2149 |
END IF; |
| 2150 |
</synopsis> |
| 2151 |
|
| 2152 |
<para> |
| 2153 |
<literal>IF-THEN-ELSE</literal> statements add to |
| 2154 |
<literal>IF-THEN</literal> by letting you specify an |
| 2155 |
alternative set of statements that should be executed if the |
| 2156 |
condition is not true. (Note this includes the case where the |
| 2157 |
condition evaluates to NULL.) |
| 2158 |
</para> |
| 2159 |
|
| 2160 |
<para> |
| 2161 |
Examples: |
| 2162 |
<programlisting> |
| 2163 |
IF parentid IS NULL OR parentid = '' |
| 2164 |
THEN |
| 2165 |
RETURN fullname; |
| 2166 |
ELSE |
| 2167 |
RETURN hp_true_filename(parentid) || '/' || fullname; |
| 2168 |
END IF; |
| 2169 |
</programlisting> |
| 2170 |
|
| 2171 |
<programlisting> |
| 2172 |
IF v_count > 0 THEN |
| 2173 |
INSERT INTO users_count (count) VALUES (v_count); |
| 2174 |
RETURN 't'; |
| 2175 |
ELSE |
| 2176 |
RETURN 'f'; |
| 2177 |
END IF; |
| 2178 |
</programlisting> |
| 2179 |
</para> |
| 2180 |
</sect3> |
| 2181 |
|
| 2182 |
<sect3 id="plpgsql-conditionals-if-then-elsif"> |
| 2183 |
<title><literal>IF-THEN-ELSIF</literal></title> |
| 2184 |
|
| 2185 |
<synopsis> |
| 2186 |
IF <replaceable>boolean-expression</replaceable> THEN |
| 2187 |
<replaceable>statements</replaceable> |
| 2188 |
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN |
| 2189 |
<replaceable>statements</replaceable> |
| 2190 |
<optional> ELSIF <replaceable>boolean-expression</replaceable> THEN |
| 2191 |
<replaceable>statements</replaceable> |
| 2192 |
... |
| 2193 |
</optional> |
| 2194 |
</optional> |
| 2195 |
<optional> ELSE |
| 2196 |
<replaceable>statements</replaceable> </optional> |
| 2197 |
END IF; |
| 2198 |
</synopsis> |
| 2199 |
|
| 2200 |
<para> |
| 2201 |
Sometimes there are more than just two alternatives. |
| 2202 |
<literal>IF-THEN-ELSIF</literal> provides a convenient |
| 2203 |
method of checking several alternatives in turn. |
| 2204 |
The <literal>IF</literal> conditions are tested successively |
| 2205 |
until the first one that is true is found. Then the |
| 2206 |
associated statement(s) are executed, after which control |
| 2207 |
passes to the next statement after <literal>END IF</literal>. |
| 2208 |
(Any subsequent <literal>IF</literal> conditions are <emphasis>not</emphasis> |
| 2209 |
tested.) If none of the <literal>IF</literal> conditions is true, |
| 2210 |
then the <literal>ELSE</literal> block (if any) is executed. |
| 2211 |
</para> |
| 2212 |
|
| 2213 |
<para> |
| 2214 |
Here is an example: |
| 2215 |
|
| 2216 |
<programlisting> |
| 2217 |
IF number = 0 THEN |
| 2218 |
result := 'zero'; |
| 2219 |
ELSIF number > 0 THEN |
| 2220 |
result := 'positive'; |
| 2221 |
ELSIF number < 0 THEN |
| 2222 |
result := 'negative'; |
| 2223 |
ELSE |
| 2224 |
-- hmm, the only other possibility is that number is null |
| 2225 |
result := 'NULL'; |
| 2226 |
END IF; |
| 2227 |
</programlisting> |
| 2228 |
</para> |
| 2229 |
|
| 2230 |
<para> |
| 2231 |
The key word <literal>ELSIF</literal> can also be spelled |
| 2232 |
<literal>ELSEIF</literal>. |
| 2233 |
</para> |
| 2234 |
|
| 2235 |
<para> |
| 2236 |
An alternative way of accomplishing the same task is to nest |
| 2237 |
<literal>IF-THEN-ELSE</literal> statements, as in the |
| 2238 |
following example: |
| 2239 |
|
| 2240 |
<programlisting> |
| 2241 |
IF demo_row.sex = 'm' THEN |
| 2242 |
pretty_sex := 'man'; |
| 2243 |
ELSE |
| 2244 |
IF demo_row.sex = 'f' THEN |
| 2245 |
pretty_sex := 'woman'; |
| 2246 |
END IF; |
| 2247 |
END IF; |
| 2248 |
</programlisting> |
| 2249 |
</para> |
| 2250 |
|
| 2251 |
<para> |
| 2252 |
However, this method requires writing a matching <literal>END IF</literal> |
| 2253 |
for each <literal>IF</literal>, so it is much more cumbersome than |
| 2254 |
using <literal>ELSIF</literal> when there are many alternatives. |
| 2255 |
</para> |
| 2256 |
</sect3> |
| 2257 |
|
| 2258 |
<sect3 id="plpgsql-conditionals-simple-case"> |
| 2259 |
<title>Simple <literal>CASE</literal></title> |
| 2260 |
|
| 2261 |
<synopsis> |
| 2262 |
CASE <replaceable>search-expression</replaceable> |
| 2263 |
WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN |
| 2264 |
<replaceable>statements</replaceable> |
| 2265 |
<optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN |
| 2266 |
<replaceable>statements</replaceable> |
| 2267 |
... </optional> |
| 2268 |
<optional> ELSE |
| 2269 |
<replaceable>statements</replaceable> </optional> |
| 2270 |
END CASE; |
| 2271 |
</synopsis> |
| 2272 |
|
| 2273 |
<para> |
| 2274 |
The simple form of <command>CASE</command> provides conditional execution |
| 2275 |
based on equality of operands. The <replaceable>search-expression</replaceable> |
| 2276 |
is evaluated (once) and successively compared to each |
| 2277 |
<replaceable>expression</replaceable> in the <literal>WHEN</literal> clauses. |
| 2278 |
If a match is found, then the corresponding |
| 2279 |
<replaceable>statements</replaceable> are executed, and then control |
| 2280 |
passes to the next statement after <literal>END CASE</literal>. (Subsequent |
| 2281 |
<literal>WHEN</literal> expressions are not evaluated.) If no match is |
| 2282 |
found, the <literal>ELSE</literal> <replaceable>statements</replaceable> are |
| 2283 |
executed; but if <literal>ELSE</literal> is not present, then a |
| 2284 |
<literal>CASE_NOT_FOUND</literal> exception is raised. |
| 2285 |
</para> |
| 2286 |
|
| 2287 |
<para> |
| 2288 |
Here is a simple example: |
| 2289 |
|
| 2290 |
<programlisting> |
| 2291 |
CASE x |
| 2292 |
WHEN 1, 2 THEN |
| 2293 |
msg := 'one or two'; |
| 2294 |
ELSE |
| 2295 |
msg := 'other value than one or two'; |
| 2296 |
END CASE; |
| 2297 |
</programlisting> |
| 2298 |
</para> |
| 2299 |
</sect3> |
| 2300 |
|
| 2301 |
<sect3 id="plpgsql-conditionals-searched-case"> |
| 2302 |
<title>Searched <literal>CASE</literal></title> |
| 2303 |
|
| 2304 |
<synopsis> |
| 2305 |
CASE |
| 2306 |
WHEN <replaceable>boolean-expression</replaceable> THEN |
| 2307 |
<replaceable>statements</replaceable> |
| 2308 |
<optional> WHEN <replaceable>boolean-expression</replaceable> THEN |
| 2309 |
<replaceable>statements</replaceable> |
| 2310 |
... </optional> |
| 2311 |
<optional> ELSE |
| 2312 |
<replaceable>statements</replaceable> </optional> |
| 2313 |
END CASE; |
| 2314 |
</synopsis> |
| 2315 |
|
| 2316 |
<para> |
| 2317 |
The searched form of <command>CASE</command> provides conditional execution |
| 2318 |
based on truth of Boolean expressions. Each <literal>WHEN</literal> clause's |
| 2319 |
<replaceable>boolean-expression</replaceable> is evaluated in turn, |
| 2320 |
until one is found that yields <literal>true</literal>. Then the |
| 2321 |
corresponding <replaceable>statements</replaceable> are executed, and |
| 2322 |
then control passes to the next statement after <literal>END CASE</literal>. |
| 2323 |
(Subsequent <literal>WHEN</literal> expressions are not evaluated.) |
| 2324 |
If no true result is found, the <literal>ELSE</literal> |
| 2325 |
<replaceable>statements</replaceable> are executed; |
| 2326 |
but if <literal>ELSE</literal> is not present, then a |
| 2327 |
<literal>CASE_NOT_FOUND</literal> exception is raised. |
| 2328 |
</para> |
| 2329 |
|
| 2330 |
<para> |
| 2331 |
Here is an example: |
| 2332 |
|
| 2333 |
<programlisting> |
| 2334 |
CASE |
| 2335 |
WHEN x BETWEEN 0 AND 10 THEN |
| 2336 |
msg := 'value is between zero and ten'; |
| 2337 |
WHEN x BETWEEN 11 AND 20 THEN |
| 2338 |
msg := 'value is between eleven and twenty'; |
| 2339 |
END CASE; |
| 2340 |
</programlisting> |
| 2341 |
</para> |
| 2342 |
|
| 2343 |
<para> |
| 2344 |
This form of <command>CASE</command> is entirely equivalent to |
| 2345 |
<literal>IF-THEN-ELSIF</literal>, except for the rule that reaching |
| 2346 |
an omitted <literal>ELSE</literal> clause results in an error rather |
| 2347 |
than doing nothing. |
| 2348 |
</para> |
| 2349 |
|
| 2350 |
</sect3> |
| 2351 |
</sect2> |
| 2352 |
|
| 2353 |
<sect2 id="plpgsql-control-structures-loops"> |
| 2354 |
<title>Simple Loops</title> |
| 2355 |
|
| 2356 |
<indexterm zone="plpgsql-control-structures-loops"> |
| 2357 |
<primary>loop</primary> |
| 2358 |
<secondary>in PL/pgSQL</secondary> |
| 2359 |
</indexterm> |
| 2360 |
|
| 2361 |
<para> |
| 2362 |
With the <literal>LOOP</literal>, <literal>EXIT</literal>, |
| 2363 |
<literal>CONTINUE</literal>, <literal>WHILE</literal>, <literal>FOR</literal>, |
| 2364 |
and <literal>FOREACH</literal> statements, you can arrange for your |
| 2365 |
<application>PL/pgSQL</application> function to repeat a series of commands. |
| 2366 |
</para> |
| 2367 |
|
| 2368 |
<sect3 id="plpgsql-control-structures-loops-loop"> |
| 2369 |
<title><literal>LOOP</literal></title> |
| 2370 |
|
| 2371 |
<synopsis> |
| 2372 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2373 |
LOOP |
| 2374 |
<replaceable>statements</replaceable> |
| 2375 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2376 |
</synopsis> |
| 2377 |
|
| 2378 |
<para> |
| 2379 |
<literal>LOOP</literal> defines an unconditional loop that is repeated |
| 2380 |
indefinitely until terminated by an <literal>EXIT</literal> or |
| 2381 |
<command>RETURN</command> statement. The optional |
| 2382 |
<replaceable>label</replaceable> can be used by <literal>EXIT</literal> |
| 2383 |
and <literal>CONTINUE</literal> statements within nested loops to |
| 2384 |
specify which loop those statements refer to. |
| 2385 |
</para> |
| 2386 |
</sect3> |
| 2387 |
|
| 2388 |
<sect3 id="plpgsql-control-structures-loops-exit"> |
| 2389 |
<title><literal>EXIT</literal></title> |
| 2390 |
|
| 2391 |
<indexterm> |
| 2392 |
<primary>EXIT</primary> |
| 2393 |
<secondary>in PL/pgSQL</secondary> |
| 2394 |
</indexterm> |
| 2395 |
|
| 2396 |
<synopsis> |
| 2397 |
EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>; |
| 2398 |
</synopsis> |
| 2399 |
|
| 2400 |
<para> |
| 2401 |
If no <replaceable>label</replaceable> is given, the innermost |
| 2402 |
loop is terminated and the statement following <literal>END |
| 2403 |
LOOP</literal> is executed next. If <replaceable>label</replaceable> |
| 2404 |
is given, it must be the label of the current or some outer |
| 2405 |
level of nested loop or block. Then the named loop or block is |
| 2406 |
terminated and control continues with the statement after the |
| 2407 |
loop's/block's corresponding <literal>END</literal>. |
| 2408 |
</para> |
| 2409 |
|
| 2410 |
<para> |
| 2411 |
If <literal>WHEN</literal> is specified, the loop exit occurs only if |
| 2412 |
<replaceable>boolean-expression</replaceable> is true. Otherwise, control passes |
| 2413 |
to the statement after <literal>EXIT</literal>. |
| 2414 |
</para> |
| 2415 |
|
| 2416 |
<para> |
| 2417 |
<literal>EXIT</literal> can be used with all types of loops; it is |
| 2418 |
not limited to use with unconditional loops. |
| 2419 |
</para> |
| 2420 |
|
| 2421 |
<para> |
| 2422 |
When used with a |
| 2423 |
<literal>BEGIN</literal> block, <literal>EXIT</literal> passes |
| 2424 |
control to the next statement after the end of the block. |
| 2425 |
Note that a label must be used for this purpose; an unlabeled |
| 2426 |
<literal>EXIT</literal> is never considered to match a |
| 2427 |
<literal>BEGIN</literal> block. (This is a change from |
| 2428 |
pre-8.4 releases of <productname>PostgreSQL</productname>, which |
| 2429 |
would allow an unlabeled <literal>EXIT</literal> to match |
| 2430 |
a <literal>BEGIN</literal> block.) |
| 2431 |
</para> |
| 2432 |
|
| 2433 |
<para> |
| 2434 |
Examples: |
| 2435 |
<programlisting> |
| 2436 |
LOOP |
| 2437 |
-- some computations |
| 2438 |
IF count > 0 THEN |
| 2439 |
EXIT; -- exit loop |
| 2440 |
END IF; |
| 2441 |
END LOOP; |
| 2442 |
|
| 2443 |
LOOP |
| 2444 |
-- some computations |
| 2445 |
EXIT WHEN count > 0; -- same result as previous example |
| 2446 |
END LOOP; |
| 2447 |
|
| 2448 |
<<ablock>> |
| 2449 |
BEGIN |
| 2450 |
-- some computations |
| 2451 |
IF stocks > 100000 THEN |
| 2452 |
EXIT ablock; -- causes exit from the BEGIN block |
| 2453 |
END IF; |
| 2454 |
-- computations here will be skipped when stocks > 100000 |
| 2455 |
END; |
| 2456 |
</programlisting> |
| 2457 |
</para> |
| 2458 |
</sect3> |
| 2459 |
|
| 2460 |
<sect3 id="plpgsql-control-structures-loops-continue"> |
| 2461 |
<title><literal>CONTINUE</literal></title> |
| 2462 |
|
| 2463 |
<indexterm> |
| 2464 |
<primary>CONTINUE</primary> |
| 2465 |
<secondary>in PL/pgSQL</secondary> |
| 2466 |
</indexterm> |
| 2467 |
|
| 2468 |
<synopsis> |
| 2469 |
CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>; |
| 2470 |
</synopsis> |
| 2471 |
|
| 2472 |
<para> |
| 2473 |
If no <replaceable>label</replaceable> is given, the next iteration of |
| 2474 |
the innermost loop is begun. That is, all statements remaining |
| 2475 |
in the loop body are skipped, and control returns |
| 2476 |
to the loop control expression (if any) to determine whether |
| 2477 |
another loop iteration is needed. |
| 2478 |
If <replaceable>label</replaceable> is present, it |
| 2479 |
specifies the label of the loop whose execution will be |
| 2480 |
continued. |
| 2481 |
</para> |
| 2482 |
|
| 2483 |
<para> |
| 2484 |
If <literal>WHEN</literal> is specified, the next iteration of the |
| 2485 |
loop is begun only if <replaceable>boolean-expression</replaceable> is |
| 2486 |
true. Otherwise, control passes to the statement after |
| 2487 |
<literal>CONTINUE</literal>. |
| 2488 |
</para> |
| 2489 |
|
| 2490 |
<para> |
| 2491 |
<literal>CONTINUE</literal> can be used with all types of loops; it |
| 2492 |
is not limited to use with unconditional loops. |
| 2493 |
</para> |
| 2494 |
|
| 2495 |
<para> |
| 2496 |
Examples: |
| 2497 |
<programlisting> |
| 2498 |
LOOP |
| 2499 |
-- some computations |
| 2500 |
EXIT WHEN count > 100; |
| 2501 |
CONTINUE WHEN count < 50; |
| 2502 |
-- some computations for count IN [50 .. 100] |
| 2503 |
END LOOP; |
| 2504 |
</programlisting> |
| 2505 |
</para> |
| 2506 |
</sect3> |
| 2507 |
|
| 2508 |
|
| 2509 |
<sect3 id="plpgsql-control-structures-loops-while"> |
| 2510 |
<title><literal>WHILE</literal></title> |
| 2511 |
|
| 2512 |
<indexterm> |
| 2513 |
<primary>WHILE</primary> |
| 2514 |
<secondary>in PL/pgSQL</secondary> |
| 2515 |
</indexterm> |
| 2516 |
|
| 2517 |
<synopsis> |
| 2518 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2519 |
WHILE <replaceable>boolean-expression</replaceable> LOOP |
| 2520 |
<replaceable>statements</replaceable> |
| 2521 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2522 |
</synopsis> |
| 2523 |
|
| 2524 |
<para> |
| 2525 |
The <literal>WHILE</literal> statement repeats a |
| 2526 |
sequence of statements so long as the |
| 2527 |
<replaceable>boolean-expression</replaceable> |
| 2528 |
evaluates to true. The expression is checked just before |
| 2529 |
each entry to the loop body. |
| 2530 |
</para> |
| 2531 |
|
| 2532 |
<para> |
| 2533 |
For example: |
| 2534 |
<programlisting> |
| 2535 |
WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP |
| 2536 |
-- some computations here |
| 2537 |
END LOOP; |
| 2538 |
|
| 2539 |
WHILE NOT done LOOP |
| 2540 |
-- some computations here |
| 2541 |
END LOOP; |
| 2542 |
</programlisting> |
| 2543 |
</para> |
| 2544 |
</sect3> |
| 2545 |
|
| 2546 |
<sect3 id="plpgsql-integer-for"> |
| 2547 |
<title><literal>FOR</literal> (Integer Variant)</title> |
| 2548 |
|
| 2549 |
<synopsis> |
| 2550 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2551 |
FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP |
| 2552 |
<replaceable>statements</replaceable> |
| 2553 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2554 |
</synopsis> |
| 2555 |
|
| 2556 |
<para> |
| 2557 |
This form of <literal>FOR</literal> creates a loop that iterates over a range |
| 2558 |
of integer values. The variable |
| 2559 |
<replaceable>name</replaceable> is automatically defined as type |
| 2560 |
<type>integer</type> and exists only inside the loop (any existing |
| 2561 |
definition of the variable name is ignored within the loop). |
| 2562 |
The two expressions giving |
| 2563 |
the lower and upper bound of the range are evaluated once when entering |
| 2564 |
the loop. If the <literal>BY</literal> clause isn't specified the iteration |
| 2565 |
step is 1, otherwise it's the value specified in the <literal>BY</literal> |
| 2566 |
clause, which again is evaluated once on loop entry. |
| 2567 |
If <literal>REVERSE</literal> is specified then the step value is |
| 2568 |
subtracted, rather than added, after each iteration. |
| 2569 |
</para> |
| 2570 |
|
| 2571 |
<para> |
| 2572 |
Some examples of integer <literal>FOR</literal> loops: |
| 2573 |
<programlisting> |
| 2574 |
FOR i IN 1..10 LOOP |
| 2575 |
-- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop |
| 2576 |
END LOOP; |
| 2577 |
|
| 2578 |
FOR i IN REVERSE 10..1 LOOP |
| 2579 |
-- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop |
| 2580 |
END LOOP; |
| 2581 |
|
| 2582 |
FOR i IN REVERSE 10..1 BY 2 LOOP |
| 2583 |
-- i will take on the values 10,8,6,4,2 within the loop |
| 2584 |
END LOOP; |
| 2585 |
</programlisting> |
| 2586 |
</para> |
| 2587 |
|
| 2588 |
<para> |
| 2589 |
If the lower bound is greater than the upper bound (or less than, |
| 2590 |
in the <literal>REVERSE</literal> case), the loop body is not |
| 2591 |
executed at all. No error is raised. |
| 2592 |
</para> |
| 2593 |
|
| 2594 |
<para> |
| 2595 |
If a <replaceable>label</replaceable> is attached to the |
| 2596 |
<literal>FOR</literal> loop then the integer loop variable can be |
| 2597 |
referenced with a qualified name, using that |
| 2598 |
<replaceable>label</replaceable>. |
| 2599 |
</para> |
| 2600 |
</sect3> |
| 2601 |
</sect2> |
| 2602 |
|
| 2603 |
<sect2 id="plpgsql-records-iterating"> |
| 2604 |
<title>Looping through Query Results</title> |
| 2605 |
|
| 2606 |
<para> |
| 2607 |
Using a different type of <literal>FOR</literal> loop, you can iterate through |
| 2608 |
the results of a query and manipulate that data |
| 2609 |
accordingly. The syntax is: |
| 2610 |
<synopsis> |
| 2611 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2612 |
FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP |
| 2613 |
<replaceable>statements</replaceable> |
| 2614 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2615 |
</synopsis> |
| 2616 |
The <replaceable>target</replaceable> is a record variable, row variable, |
| 2617 |
or comma-separated list of scalar variables. |
| 2618 |
The <replaceable>target</replaceable> is successively assigned each row |
| 2619 |
resulting from the <replaceable>query</replaceable> and the loop body is |
| 2620 |
executed for each row. Here is an example: |
| 2621 |
<programlisting> |
| 2622 |
CREATE FUNCTION refresh_mviews() RETURNS integer AS $$ |
| 2623 |
DECLARE |
| 2624 |
mviews RECORD; |
| 2625 |
BEGIN |
| 2626 |
RAISE NOTICE 'Refreshing all materialized views...'; |
| 2627 |
|
| 2628 |
FOR mviews IN |
| 2629 |
SELECT n.nspname AS mv_schema, |
| 2630 |
c.relname AS mv_name, |
| 2631 |
pg_catalog.pg_get_userbyid(c.relowner) AS owner |
| 2632 |
FROM pg_catalog.pg_class c |
| 2633 |
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) |
| 2634 |
WHERE c.relkind = 'm' |
| 2635 |
ORDER BY 1 |
| 2636 |
LOOP |
| 2637 |
|
| 2638 |
-- Now "mviews" has one record with information about the materialized view |
| 2639 |
|
| 2640 |
RAISE NOTICE 'Refreshing materialized view %.% (owner: %)...', |
| 2641 |
quote_ident(mviews.mv_schema), |
| 2642 |
quote_ident(mviews.mv_name), |
| 2643 |
quote_ident(mviews.owner); |
| 2644 |
EXECUTE format('REFRESH MATERIALIZED VIEW %I.%I', mviews.mv_schema, mviews.mv_name); |
| 2645 |
END LOOP; |
| 2646 |
|
| 2647 |
RAISE NOTICE 'Done refreshing materialized views.'; |
| 2648 |
RETURN 1; |
| 2649 |
END; |
| 2650 |
$$ LANGUAGE plpgsql; |
| 2651 |
</programlisting> |
| 2652 |
|
| 2653 |
If the loop is terminated by an <literal>EXIT</literal> statement, the last |
| 2654 |
assigned row value is still accessible after the loop. |
| 2655 |
</para> |
| 2656 |
|
| 2657 |
<para> |
| 2658 |
The <replaceable>query</replaceable> used in this type of <literal>FOR</literal> |
| 2659 |
statement can be any SQL command that returns rows to the caller: |
| 2660 |
<command>SELECT</command> is the most common case, |
| 2661 |
but you can also use <command>INSERT</command>, <command>UPDATE</command>, |
| 2662 |
<command>DELETE</command>, or <command>MERGE</command> with a |
| 2663 |
<literal>RETURNING</literal> clause. Some utility |
| 2664 |
commands such as <command>EXPLAIN</command> will work too. |
| 2665 |
</para> |
| 2666 |
|
| 2667 |
<para> |
| 2668 |
<application>PL/pgSQL</application> variables are replaced by query parameters, |
| 2669 |
and the query plan is cached for possible re-use, as discussed in |
| 2670 |
detail in <xref linkend="plpgsql-var-subst"/> and |
| 2671 |
<xref linkend="plpgsql-plan-caching"/>. |
| 2672 |
</para> |
| 2673 |
|
| 2674 |
<para> |
| 2675 |
The <literal>FOR-IN-EXECUTE</literal> statement is another way to iterate over |
| 2676 |
rows: |
| 2677 |
<synopsis> |
| 2678 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2679 |
FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP |
| 2680 |
<replaceable>statements</replaceable> |
| 2681 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2682 |
</synopsis> |
| 2683 |
This is like the previous form, except that the source query |
| 2684 |
is specified as a string expression, which is evaluated and replanned |
| 2685 |
on each entry to the <literal>FOR</literal> loop. This allows the programmer to |
| 2686 |
choose the speed of a preplanned query or the flexibility of a dynamic |
| 2687 |
query, just as with a plain <command>EXECUTE</command> statement. |
| 2688 |
As with <command>EXECUTE</command>, parameter values can be inserted |
| 2689 |
into the dynamic command via <literal>USING</literal>. |
| 2690 |
</para> |
| 2691 |
|
| 2692 |
<para> |
| 2693 |
Another way to specify the query whose results should be iterated |
| 2694 |
through is to declare it as a cursor. This is described in |
| 2695 |
<xref linkend="plpgsql-cursor-for-loop"/>. |
| 2696 |
</para> |
| 2697 |
</sect2> |
| 2698 |
|
| 2699 |
<sect2 id="plpgsql-foreach-array"> |
| 2700 |
<title>Looping through Arrays</title> |
| 2701 |
|
| 2702 |
<para> |
| 2703 |
The <literal>FOREACH</literal> loop is much like a <literal>FOR</literal> loop, |
| 2704 |
but instead of iterating through the rows returned by an SQL query, |
| 2705 |
it iterates through the elements of an array value. |
| 2706 |
(In general, <literal>FOREACH</literal> is meant for looping through |
| 2707 |
components of a composite-valued expression; variants for looping |
| 2708 |
through composites besides arrays may be added in future.) |
| 2709 |
The <literal>FOREACH</literal> statement to loop over an array is: |
| 2710 |
|
| 2711 |
<synopsis> |
| 2712 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2713 |
FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP |
| 2714 |
<replaceable>statements</replaceable> |
| 2715 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 2716 |
</synopsis> |
| 2717 |
</para> |
| 2718 |
|
| 2719 |
<para> |
| 2720 |
Without <literal>SLICE</literal>, or if <literal>SLICE 0</literal> is specified, |
| 2721 |
the loop iterates through individual elements of the array produced |
| 2722 |
by evaluating the <replaceable>expression</replaceable>. |
| 2723 |
The <replaceable>target</replaceable> variable is assigned each |
| 2724 |
element value in sequence, and the loop body is executed for each element. |
| 2725 |
Here is an example of looping through the elements of an integer |
| 2726 |
array: |
| 2727 |
|
| 2728 |
<programlisting> |
| 2729 |
CREATE FUNCTION sum(int[]) RETURNS int8 AS $$ |
| 2730 |
DECLARE |
| 2731 |
s int8 := 0; |
| 2732 |
x int; |
| 2733 |
BEGIN |
| 2734 |
FOREACH x IN ARRAY $1 |
| 2735 |
LOOP |
| 2736 |
s := s + x; |
| 2737 |
END LOOP; |
| 2738 |
RETURN s; |
| 2739 |
END; |
| 2740 |
$$ LANGUAGE plpgsql; |
| 2741 |
</programlisting> |
| 2742 |
|
| 2743 |
The elements are visited in storage order, regardless of the number of |
| 2744 |
array dimensions. Although the <replaceable>target</replaceable> is |
| 2745 |
usually just a single variable, it can be a list of variables when |
| 2746 |
looping through an array of composite values (records). In that case, |
| 2747 |
for each array element, the variables are assigned from successive |
| 2748 |
columns of the composite value. |
| 2749 |
</para> |
| 2750 |
|
| 2751 |
<para> |
| 2752 |
With a positive <literal>SLICE</literal> value, <literal>FOREACH</literal> |
| 2753 |
iterates through slices of the array rather than single elements. |
| 2754 |
The <literal>SLICE</literal> value must be an integer constant not larger |
| 2755 |
than the number of dimensions of the array. The |
| 2756 |
<replaceable>target</replaceable> variable must be an array, |
| 2757 |
and it receives successive slices of the array value, where each slice |
| 2758 |
is of the number of dimensions specified by <literal>SLICE</literal>. |
| 2759 |
Here is an example of iterating through one-dimensional slices: |
| 2760 |
|
| 2761 |
<programlisting> |
| 2762 |
CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$ |
| 2763 |
DECLARE |
| 2764 |
x int[]; |
| 2765 |
BEGIN |
| 2766 |
FOREACH x SLICE 1 IN ARRAY $1 |
| 2767 |
LOOP |
| 2768 |
RAISE NOTICE 'row = %', x; |
| 2769 |
END LOOP; |
| 2770 |
END; |
| 2771 |
$$ LANGUAGE plpgsql; |
| 2772 |
|
| 2773 |
SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]); |
| 2774 |
|
| 2775 |
NOTICE: row = {1,2,3} |
| 2776 |
NOTICE: row = {4,5,6} |
| 2777 |
NOTICE: row = {7,8,9} |
| 2778 |
NOTICE: row = {10,11,12} |
| 2779 |
</programlisting> |
| 2780 |
</para> |
| 2781 |
</sect2> |
| 2782 |
|
| 2783 |
<sect2 id="plpgsql-error-trapping"> |
| 2784 |
<title>Trapping Errors</title> |
| 2785 |
|
| 2786 |
<indexterm> |
| 2787 |
<primary>exceptions</primary> |
| 2788 |
<secondary>in PL/pgSQL</secondary> |
| 2789 |
</indexterm> |
| 2790 |
|
| 2791 |
<para> |
| 2792 |
By default, any error occurring in a <application>PL/pgSQL</application> |
| 2793 |
function aborts execution of the function and the |
| 2794 |
surrounding transaction. You can trap errors and recover |
| 2795 |
from them by using a <command>BEGIN</command> block with an |
| 2796 |
<literal>EXCEPTION</literal> clause. The syntax is an extension of the |
| 2797 |
normal syntax for a <command>BEGIN</command> block: |
| 2798 |
|
| 2799 |
<synopsis> |
| 2800 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 2801 |
<optional> DECLARE |
| 2802 |
<replaceable>declarations</replaceable> </optional> |
| 2803 |
BEGIN |
| 2804 |
<replaceable>statements</replaceable> |
| 2805 |
EXCEPTION |
| 2806 |
WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN |
| 2807 |
<replaceable>handler_statements</replaceable> |
| 2808 |
<optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN |
| 2809 |
<replaceable>handler_statements</replaceable> |
| 2810 |
... </optional> |
| 2811 |
END; |
| 2812 |
</synopsis> |
| 2813 |
</para> |
| 2814 |
|
| 2815 |
<para> |
| 2816 |
If no error occurs, this form of block simply executes all the |
| 2817 |
<replaceable>statements</replaceable>, and then control passes |
| 2818 |
to the next statement after <literal>END</literal>. But if an error |
| 2819 |
occurs within the <replaceable>statements</replaceable>, further |
| 2820 |
processing of the <replaceable>statements</replaceable> is |
| 2821 |
abandoned, and control passes to the <literal>EXCEPTION</literal> list. |
| 2822 |
The list is searched for the first <replaceable>condition</replaceable> |
| 2823 |
matching the error that occurred. If a match is found, the |
| 2824 |
corresponding <replaceable>handler_statements</replaceable> are |
| 2825 |
executed, and then control passes to the next statement after |
| 2826 |
<literal>END</literal>. If no match is found, the error propagates out |
| 2827 |
as though the <literal>EXCEPTION</literal> clause were not there at all: |
| 2828 |
the error can be caught by an enclosing block with |
| 2829 |
<literal>EXCEPTION</literal>, or if there is none it aborts processing |
| 2830 |
of the function. |
| 2831 |
</para> |
| 2832 |
|
| 2833 |
<para> |
| 2834 |
The <replaceable>condition</replaceable> names can be any of |
| 2835 |
those shown in <xref linkend="errcodes-appendix"/>. A category |
| 2836 |
name matches any error within its category. The special |
| 2837 |
condition name <literal>OTHERS</literal> matches every error type except |
| 2838 |
<literal>QUERY_CANCELED</literal> and <literal>ASSERT_FAILURE</literal>. |
| 2839 |
(It is possible, but often unwise, to trap those two error types |
| 2840 |
by name.) Condition names are |
| 2841 |
not case-sensitive. Also, an error condition can be specified |
| 2842 |
by <literal>SQLSTATE</literal> code; for example these are equivalent: |
| 2843 |
<programlisting> |
| 2844 |
WHEN division_by_zero THEN ... |
| 2845 |
WHEN SQLSTATE '22012' THEN ... |
| 2846 |
</programlisting> |
| 2847 |
</para> |
| 2848 |
|
| 2849 |
<para> |
| 2850 |
If a new error occurs within the selected |
| 2851 |
<replaceable>handler_statements</replaceable>, it cannot be caught |
| 2852 |
by this <literal>EXCEPTION</literal> clause, but is propagated out. |
| 2853 |
A surrounding <literal>EXCEPTION</literal> clause could catch it. |
| 2854 |
</para> |
| 2855 |
|
| 2856 |
<para> |
| 2857 |
When an error is caught by an <literal>EXCEPTION</literal> clause, |
| 2858 |
the local variables of the <application>PL/pgSQL</application> function |
| 2859 |
remain as they were when the error occurred, but all changes |
| 2860 |
to persistent database state within the block are rolled back. |
| 2861 |
As an example, consider this fragment: |
| 2862 |
|
| 2863 |
<programlisting> |
| 2864 |
INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones'); |
| 2865 |
BEGIN |
| 2866 |
UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones'; |
| 2867 |
x := x + 1; |
| 2868 |
y := x / 0; |
| 2869 |
EXCEPTION |
| 2870 |
WHEN division_by_zero THEN |
| 2871 |
RAISE NOTICE 'caught division_by_zero'; |
| 2872 |
RETURN x; |
| 2873 |
END; |
| 2874 |
</programlisting> |
| 2875 |
|
| 2876 |
When control reaches the assignment to <literal>y</literal>, it will |
| 2877 |
fail with a <literal>division_by_zero</literal> error. This will be caught by |
| 2878 |
the <literal>EXCEPTION</literal> clause. The value returned in the |
| 2879 |
<command>RETURN</command> statement will be the incremented value of |
| 2880 |
<literal>x</literal>, but the effects of the <command>UPDATE</command> command will |
| 2881 |
have been rolled back. The <command>INSERT</command> command preceding the |
| 2882 |
block is not rolled back, however, so the end result is that the database |
| 2883 |
contains <literal>Tom Jones</literal> not <literal>Joe Jones</literal>. |
| 2884 |
</para> |
| 2885 |
|
| 2886 |
<tip> |
| 2887 |
<para> |
| 2888 |
A block containing an <literal>EXCEPTION</literal> clause is significantly |
| 2889 |
more expensive to enter and exit than a block without one. Therefore, |
| 2890 |
don't use <literal>EXCEPTION</literal> without need. |
| 2891 |
</para> |
| 2892 |
</tip> |
| 2893 |
|
| 2894 |
<example id="plpgsql-upsert-example"> |
| 2895 |
<title>Exceptions with <command>UPDATE</command>/<command>INSERT</command></title> |
| 2896 |
<para> |
| 2897 |
|
| 2898 |
This example uses exception handling to perform either |
| 2899 |
<command>UPDATE</command> or <command>INSERT</command>, as appropriate. It is |
| 2900 |
recommended that applications use <command>INSERT</command> with |
| 2901 |
<literal>ON CONFLICT DO UPDATE</literal> rather than actually using |
| 2902 |
this pattern. This example serves primarily to illustrate use of |
| 2903 |
<application>PL/pgSQL</application> control flow structures: |
| 2904 |
|
| 2905 |
<programlisting> |
| 2906 |
CREATE TABLE db (a INT PRIMARY KEY, b TEXT); |
| 2907 |
|
| 2908 |
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS |
| 2909 |
$$ |
| 2910 |
BEGIN |
| 2911 |
LOOP |
| 2912 |
-- first try to update the key |
| 2913 |
UPDATE db SET b = data WHERE a = key; |
| 2914 |
IF found THEN |
| 2915 |
RETURN; |
| 2916 |
END IF; |
| 2917 |
-- not there, so try to insert the key |
| 2918 |
-- if someone else inserts the same key concurrently, |
| 2919 |
-- we could get a unique-key failure |
| 2920 |
BEGIN |
| 2921 |
INSERT INTO db(a,b) VALUES (key, data); |
| 2922 |
RETURN; |
| 2923 |
EXCEPTION WHEN unique_violation THEN |
| 2924 |
-- Do nothing, and loop to try the UPDATE again. |
| 2925 |
END; |
| 2926 |
END LOOP; |
| 2927 |
END; |
| 2928 |
$$ |
| 2929 |
LANGUAGE plpgsql; |
| 2930 |
|
| 2931 |
SELECT merge_db(1, 'david'); |
| 2932 |
SELECT merge_db(1, 'dennis'); |
| 2933 |
</programlisting> |
| 2934 |
|
| 2935 |
This coding assumes the <literal>unique_violation</literal> error is caused by |
| 2936 |
the <command>INSERT</command>, and not by, say, an <command>INSERT</command> in a |
| 2937 |
trigger function on the table. It might also misbehave if there is |
| 2938 |
more than one unique index on the table, since it will retry the |
| 2939 |
operation regardless of which index caused the error. |
| 2940 |
More safety could be had by using the |
| 2941 |
features discussed next to check that the trapped error was the one |
| 2942 |
expected. |
| 2943 |
</para> |
| 2944 |
</example> |
| 2945 |
|
| 2946 |
<sect3 id="plpgsql-exception-diagnostics"> |
| 2947 |
<title>Obtaining Information about an Error</title> |
| 2948 |
|
| 2949 |
<para> |
| 2950 |
Exception handlers frequently need to identify the specific error that |
| 2951 |
occurred. There are two ways to get information about the current |
| 2952 |
exception in <application>PL/pgSQL</application>: special variables and the |
| 2953 |
<command>GET STACKED DIAGNOSTICS</command> command. |
| 2954 |
</para> |
| 2955 |
|
| 2956 |
<para> |
| 2957 |
Within an exception handler, the special variable |
| 2958 |
<varname>SQLSTATE</varname> contains the error code that corresponds to |
| 2959 |
the exception that was raised (refer to <xref linkend="errcodes-table"/> |
| 2960 |
for a list of possible error codes). The special variable |
| 2961 |
<varname>SQLERRM</varname> contains the error message associated with the |
| 2962 |
exception. These variables are undefined outside exception handlers. |
| 2963 |
</para> |
| 2964 |
|
| 2965 |
<para> |
| 2966 |
Within an exception handler, one may also retrieve |
| 2967 |
information about the current exception by using the |
| 2968 |
<command>GET STACKED DIAGNOSTICS</command> command, which has the form: |
| 2969 |
|
| 2970 |
<synopsis> |
| 2971 |
GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>; |
| 2972 |
</synopsis> |
| 2973 |
|
| 2974 |
Each <replaceable>item</replaceable> is a key word identifying a status |
| 2975 |
value to be assigned to the specified <replaceable>variable</replaceable> |
| 2976 |
(which should be of the right data type to receive it). The currently |
| 2977 |
available status items are shown |
| 2978 |
in <xref linkend="plpgsql-exception-diagnostics-values"/>. |
| 2979 |
</para> |
| 2980 |
|
| 2981 |
<table id="plpgsql-exception-diagnostics-values"> |
| 2982 |
<title>Error Diagnostics Items</title> |
| 2983 |
<tgroup cols="3"> |
| 2984 |
<colspec colname="col1" colwidth="2*"/> |
| 2985 |
<colspec colname="col2" colwidth="1*"/> |
| 2986 |
<colspec colname="col3" colwidth="2*"/> |
| 2987 |
<thead> |
| 2988 |
<row> |
| 2989 |
<entry>Name</entry> |
| 2990 |
<entry>Type</entry> |
| 2991 |
<entry>Description</entry> |
| 2992 |
</row> |
| 2993 |
</thead> |
| 2994 |
<tbody> |
| 2995 |
<row> |
| 2996 |
<entry><literal>RETURNED_SQLSTATE</literal></entry> |
| 2997 |
<entry><type>text</type></entry> |
| 2998 |
<entry>the SQLSTATE error code of the exception</entry> |
| 2999 |
</row> |
| 3000 |
<row> |
| 3001 |
<entry><literal>COLUMN_NAME</literal></entry> |
| 3002 |
<entry><type>text</type></entry> |
| 3003 |
<entry>the name of the column related to exception</entry> |
| 3004 |
</row> |
| 3005 |
<row> |
| 3006 |
<entry><literal>CONSTRAINT_NAME</literal></entry> |
| 3007 |
<entry><type>text</type></entry> |
| 3008 |
<entry>the name of the constraint related to exception</entry> |
| 3009 |
</row> |
| 3010 |
<row> |
| 3011 |
<entry><literal>PG_DATATYPE_NAME</literal></entry> |
| 3012 |
<entry><type>text</type></entry> |
| 3013 |
<entry>the name of the data type related to exception</entry> |
| 3014 |
</row> |
| 3015 |
<row> |
| 3016 |
<entry><literal>MESSAGE_TEXT</literal></entry> |
| 3017 |
<entry><type>text</type></entry> |
| 3018 |
<entry>the text of the exception's primary message</entry> |
| 3019 |
</row> |
| 3020 |
<row> |
| 3021 |
<entry><literal>TABLE_NAME</literal></entry> |
| 3022 |
<entry><type>text</type></entry> |
| 3023 |
<entry>the name of the table related to exception</entry> |
| 3024 |
</row> |
| 3025 |
<row> |
| 3026 |
<entry><literal>SCHEMA_NAME</literal></entry> |
| 3027 |
<entry><type>text</type></entry> |
| 3028 |
<entry>the name of the schema related to exception</entry> |
| 3029 |
</row> |
| 3030 |
<row> |
| 3031 |
<entry><literal>PG_EXCEPTION_DETAIL</literal></entry> |
| 3032 |
<entry><type>text</type></entry> |
| 3033 |
<entry>the text of the exception's detail message, if any</entry> |
| 3034 |
</row> |
| 3035 |
<row> |
| 3036 |
<entry><literal>PG_EXCEPTION_HINT</literal></entry> |
| 3037 |
<entry><type>text</type></entry> |
| 3038 |
<entry>the text of the exception's hint message, if any</entry> |
| 3039 |
</row> |
| 3040 |
<row> |
| 3041 |
<entry><literal>PG_EXCEPTION_CONTEXT</literal></entry> |
| 3042 |
<entry><type>text</type></entry> |
| 3043 |
<entry>line(s) of text describing the call stack at the time of the |
| 3044 |
exception (see <xref linkend="plpgsql-call-stack"/>)</entry> |
| 3045 |
</row> |
| 3046 |
</tbody> |
| 3047 |
</tgroup> |
| 3048 |
</table> |
| 3049 |
|
| 3050 |
<para> |
| 3051 |
If the exception did not set a value for an item, an empty string |
| 3052 |
will be returned. |
| 3053 |
</para> |
| 3054 |
|
| 3055 |
<para> |
| 3056 |
Here is an example: |
| 3057 |
<programlisting> |
| 3058 |
DECLARE |
| 3059 |
text_var1 text; |
| 3060 |
text_var2 text; |
| 3061 |
text_var3 text; |
| 3062 |
BEGIN |
| 3063 |
-- some processing which might cause an exception |
| 3064 |
... |
| 3065 |
EXCEPTION WHEN OTHERS THEN |
| 3066 |
GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT, |
| 3067 |
text_var2 = PG_EXCEPTION_DETAIL, |
| 3068 |
text_var3 = PG_EXCEPTION_HINT; |
| 3069 |
END; |
| 3070 |
</programlisting> |
| 3071 |
</para> |
| 3072 |
</sect3> |
| 3073 |
</sect2> |
| 3074 |
|
| 3075 |
<sect2 id="plpgsql-call-stack"> |
| 3076 |
<title>Obtaining Execution Location Information</title> |
| 3077 |
|
| 3078 |
<para> |
| 3079 |
The <command>GET DIAGNOSTICS</command> command, previously described |
| 3080 |
in <xref linkend="plpgsql-statements-diagnostics"/>, retrieves information |
| 3081 |
about current execution state (whereas the <command>GET STACKED |
| 3082 |
DIAGNOSTICS</command> command discussed above reports information about |
| 3083 |
the execution state as of a previous error). Its <literal>PG_CONTEXT</literal> |
| 3084 |
status item is useful for identifying the current execution |
| 3085 |
location. <literal>PG_CONTEXT</literal> returns a text string with line(s) |
| 3086 |
of text describing the call stack. The first line refers to the current |
| 3087 |
function and currently executing <command>GET DIAGNOSTICS</command> |
| 3088 |
command. The second and any subsequent lines refer to calling functions |
| 3089 |
further up the call stack. For example: |
| 3090 |
|
| 3091 |
<programlisting> |
| 3092 |
CREATE OR REPLACE FUNCTION outer_func() RETURNS integer AS $$ |
| 3093 |
BEGIN |
| 3094 |
RETURN inner_func(); |
| 3095 |
END; |
| 3096 |
$$ LANGUAGE plpgsql; |
| 3097 |
|
| 3098 |
CREATE OR REPLACE FUNCTION inner_func() RETURNS integer AS $$ |
| 3099 |
DECLARE |
| 3100 |
stack text; |
| 3101 |
BEGIN |
| 3102 |
GET DIAGNOSTICS stack = PG_CONTEXT; |
| 3103 |
RAISE NOTICE E'--- Call Stack ---\n%', stack; |
| 3104 |
RETURN 1; |
| 3105 |
END; |
| 3106 |
$$ LANGUAGE plpgsql; |
| 3107 |
|
| 3108 |
SELECT outer_func(); |
| 3109 |
|
| 3110 |
NOTICE: --- Call Stack --- |
| 3111 |
PL/pgSQL function inner_func() line 5 at GET DIAGNOSTICS |
| 3112 |
PL/pgSQL function outer_func() line 3 at RETURN |
| 3113 |
CONTEXT: PL/pgSQL function outer_func() line 3 at RETURN |
| 3114 |
outer_func |
| 3115 |
------------ |
| 3116 |
1 |
| 3117 |
(1 row) |
| 3118 |
</programlisting> |
| 3119 |
|
| 3120 |
</para> |
| 3121 |
|
| 3122 |
<para> |
| 3123 |
<literal>GET STACKED DIAGNOSTICS ... PG_EXCEPTION_CONTEXT</literal> |
| 3124 |
returns the same sort of stack trace, but describing the location |
| 3125 |
at which an error was detected, rather than the current location. |
| 3126 |
</para> |
| 3127 |
</sect2> |
| 3128 |
</sect1> |
| 3129 |
|
| 3130 |
<sect1 id="plpgsql-cursors"> |
| 3131 |
<title>Cursors</title> |
| 3132 |
|
| 3133 |
<indexterm zone="plpgsql-cursors"> |
| 3134 |
<primary>cursor</primary> |
| 3135 |
<secondary>in PL/pgSQL</secondary> |
| 3136 |
</indexterm> |
| 3137 |
|
| 3138 |
<para> |
| 3139 |
Rather than executing a whole query at once, it is possible to set |
| 3140 |
up a <firstterm>cursor</firstterm> that encapsulates the query, and then read |
| 3141 |
the query result a few rows at a time. One reason for doing this is |
| 3142 |
to avoid memory overrun when the result contains a large number of |
| 3143 |
rows. (However, <application>PL/pgSQL</application> users do not normally need |
| 3144 |
to worry about that, since <literal>FOR</literal> loops automatically use a cursor |
| 3145 |
internally to avoid memory problems.) A more interesting usage is to |
| 3146 |
return a reference to a cursor that a function has created, allowing the |
| 3147 |
caller to read the rows. This provides an efficient way to return |
| 3148 |
large row sets from functions. |
| 3149 |
</para> |
| 3150 |
|
| 3151 |
<sect2 id="plpgsql-cursor-declarations"> |
| 3152 |
<title>Declaring Cursor Variables</title> |
| 3153 |
|
| 3154 |
<para> |
| 3155 |
All access to cursors in <application>PL/pgSQL</application> goes through |
| 3156 |
cursor variables, which are always of the special data type |
| 3157 |
<type>refcursor</type>. One way to create a cursor variable |
| 3158 |
is just to declare it as a variable of type <type>refcursor</type>. |
| 3159 |
Another way is to use the cursor declaration syntax, |
| 3160 |
which in general is: |
| 3161 |
<synopsis> |
| 3162 |
<replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>; |
| 3163 |
</synopsis> |
| 3164 |
(<literal>FOR</literal> can be replaced by <literal>IS</literal> for |
| 3165 |
<productname>Oracle</productname> compatibility.) |
| 3166 |
If <literal>SCROLL</literal> is specified, the cursor will be capable of |
| 3167 |
scrolling backward; if <literal>NO SCROLL</literal> is specified, backward |
| 3168 |
fetches will be rejected; if neither specification appears, it is |
| 3169 |
query-dependent whether backward fetches will be allowed. |
| 3170 |
<replaceable>arguments</replaceable>, if specified, is a |
| 3171 |
comma-separated list of pairs <literal><replaceable>name</replaceable> |
| 3172 |
<replaceable>datatype</replaceable></literal> that define names to be |
| 3173 |
replaced by parameter values in the given query. The actual |
| 3174 |
values to substitute for these names will be specified later, |
| 3175 |
when the cursor is opened. |
| 3176 |
</para> |
| 3177 |
<para> |
| 3178 |
Some examples: |
| 3179 |
<programlisting> |
| 3180 |
DECLARE |
| 3181 |
curs1 refcursor; |
| 3182 |
curs2 CURSOR FOR SELECT * FROM tenk1; |
| 3183 |
curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key; |
| 3184 |
</programlisting> |
| 3185 |
All three of these variables have the data type <type>refcursor</type>, |
| 3186 |
but the first can be used with any query, while the second has |
| 3187 |
a fully specified query already <firstterm>bound</firstterm> to it, and the last |
| 3188 |
has a parameterized query bound to it. (<literal>key</literal> will be |
| 3189 |
replaced by an integer parameter value when the cursor is opened.) |
| 3190 |
The variable <literal>curs1</literal> |
| 3191 |
is said to be <firstterm>unbound</firstterm> since it is not bound to |
| 3192 |
any particular query. |
| 3193 |
</para> |
| 3194 |
|
| 3195 |
<para> |
| 3196 |
The <literal>SCROLL</literal> option cannot be used when the cursor's |
| 3197 |
query uses <literal>FOR UPDATE/SHARE</literal>. Also, it is |
| 3198 |
best to use <literal>NO SCROLL</literal> with a query that involves |
| 3199 |
volatile functions. The implementation of <literal>SCROLL</literal> |
| 3200 |
assumes that re-reading the query's output will give consistent |
| 3201 |
results, which a volatile function might not do. |
| 3202 |
</para> |
| 3203 |
</sect2> |
| 3204 |
|
| 3205 |
<sect2 id="plpgsql-cursor-opening"> |
| 3206 |
<title>Opening Cursors</title> |
| 3207 |
|
| 3208 |
<para> |
| 3209 |
Before a cursor can be used to retrieve rows, it must be |
| 3210 |
<firstterm>opened</firstterm>. (This is the equivalent action to the SQL |
| 3211 |
command <link linkend="sql-declare"><command>DECLARE |
| 3212 |
CURSOR</command></link>.) |
| 3213 |
<application>PL/pgSQL</application> has |
| 3214 |
three forms of the <command>OPEN</command> statement, two of which use unbound |
| 3215 |
cursor variables while the third uses a bound cursor variable. |
| 3216 |
</para> |
| 3217 |
|
| 3218 |
<note> |
| 3219 |
<para> |
| 3220 |
Bound cursor variables can also be used without explicitly opening the cursor, |
| 3221 |
via the <command>FOR</command> statement described in |
| 3222 |
<xref linkend="plpgsql-cursor-for-loop"/>. |
| 3223 |
A <command>FOR</command> loop will open the cursor and then |
| 3224 |
close it again when the loop completes. |
| 3225 |
</para> |
| 3226 |
</note> |
| 3227 |
|
| 3228 |
<indexterm> |
| 3229 |
<primary>portal</primary> |
| 3230 |
<secondary>in PL/pgSQL</secondary> |
| 3231 |
</indexterm> |
| 3232 |
|
| 3233 |
<para> |
| 3234 |
Opening a cursor involves creating a server-internal data structure |
| 3235 |
called a <firstterm>portal</firstterm>, which holds the execution |
| 3236 |
state for the cursor's query. A portal has a name, which must be |
| 3237 |
unique within the session for the duration of the portal's existence. |
| 3238 |
By default, <application>PL/pgSQL</application> will assign a unique |
| 3239 |
name to each portal it creates. However, if you assign a non-null |
| 3240 |
string value to a cursor variable, that string will be used as its |
| 3241 |
portal name. This feature can be used as described in |
| 3242 |
<xref linkend="plpgsql-cursor-returning"/>. |
| 3243 |
</para> |
| 3244 |
|
| 3245 |
<sect3 id="plpgsql-cursor-opening-open-for-query"> |
| 3246 |
<title><command>OPEN FOR</command> <replaceable>query</replaceable></title> |
| 3247 |
|
| 3248 |
<synopsis> |
| 3249 |
OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>; |
| 3250 |
</synopsis> |
| 3251 |
|
| 3252 |
<para> |
| 3253 |
The cursor variable is opened and given the specified query to |
| 3254 |
execute. The cursor cannot be open already, and it must have been |
| 3255 |
declared as an unbound cursor variable (that is, as a simple |
| 3256 |
<type>refcursor</type> variable). The query must be a |
| 3257 |
<command>SELECT</command>, or something else that returns rows |
| 3258 |
(such as <command>EXPLAIN</command>). The query |
| 3259 |
is treated in the same way as other SQL commands in |
| 3260 |
<application>PL/pgSQL</application>: <application>PL/pgSQL</application> |
| 3261 |
variable names are substituted, and the query plan is cached for |
| 3262 |
possible reuse. When a <application>PL/pgSQL</application> |
| 3263 |
variable is substituted into the cursor query, the value that is |
| 3264 |
substituted is the one it has at the time of the <command>OPEN</command>; |
| 3265 |
subsequent changes to the variable will not affect the cursor's |
| 3266 |
behavior. |
| 3267 |
The <literal>SCROLL</literal> and <literal>NO SCROLL</literal> |
| 3268 |
options have the same meanings as for a bound cursor. |
| 3269 |
</para> |
| 3270 |
|
| 3271 |
<para> |
| 3272 |
An example: |
| 3273 |
<programlisting> |
| 3274 |
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey; |
| 3275 |
</programlisting> |
| 3276 |
</para> |
| 3277 |
</sect3> |
| 3278 |
|
| 3279 |
<sect3 id="plpgsql-cursor-opening-open-for-execute"> |
| 3280 |
<title><command>OPEN FOR EXECUTE</command></title> |
| 3281 |
|
| 3282 |
<synopsis> |
| 3283 |
OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable> |
| 3284 |
<optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>; |
| 3285 |
</synopsis> |
| 3286 |
|
| 3287 |
<para> |
| 3288 |
The cursor variable is opened and given the specified query to |
| 3289 |
execute. The cursor cannot be open already, and it must have been |
| 3290 |
declared as an unbound cursor variable (that is, as a simple |
| 3291 |
<type>refcursor</type> variable). The query is specified as a string |
| 3292 |
expression, in the same way as in the <command>EXECUTE</command> |
| 3293 |
command. As usual, this gives flexibility so the query plan can vary |
| 3294 |
from one run to the next (see <xref linkend="plpgsql-plan-caching"/>), |
| 3295 |
and it also means that variable substitution is not done on the |
| 3296 |
command string. As with <command>EXECUTE</command>, parameter values |
| 3297 |
can be inserted into the dynamic command via |
| 3298 |
<literal>format()</literal> and <literal>USING</literal>. |
| 3299 |
The <literal>SCROLL</literal> and |
| 3300 |
<literal>NO SCROLL</literal> options have the same meanings as for a bound |
| 3301 |
cursor. |
| 3302 |
</para> |
| 3303 |
|
| 3304 |
<para> |
| 3305 |
An example: |
| 3306 |
<programlisting> |
| 3307 |
OPEN curs1 FOR EXECUTE format('SELECT * FROM %I WHERE col1 = $1',tabname) USING keyvalue; |
| 3308 |
</programlisting> |
| 3309 |
In this example, the table name is inserted into the query via |
| 3310 |
<function>format()</function>. The comparison value for <literal>col1</literal> |
| 3311 |
is inserted via a <literal>USING</literal> parameter, so it needs |
| 3312 |
no quoting. |
| 3313 |
</para> |
| 3314 |
</sect3> |
| 3315 |
|
| 3316 |
<sect3 id="plpgsql-open-bound-cursor"> |
| 3317 |
<title>Opening a Bound Cursor</title> |
| 3318 |
|
| 3319 |
<synopsis> |
| 3320 |
OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> { := | => } </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>; |
| 3321 |
</synopsis> |
| 3322 |
|
| 3323 |
<para> |
| 3324 |
This form of <command>OPEN</command> is used to open a cursor |
| 3325 |
variable whose query was bound to it when it was declared. The |
| 3326 |
cursor cannot be open already. A list of actual argument value |
| 3327 |
expressions must appear if and only if the cursor was declared to |
| 3328 |
take arguments. These values will be substituted in the query. |
| 3329 |
</para> |
| 3330 |
|
| 3331 |
<para> |
| 3332 |
The query plan for a bound cursor is always considered cacheable; |
| 3333 |
there is no equivalent of <command>EXECUTE</command> in this case. |
| 3334 |
Notice that <literal>SCROLL</literal> and <literal>NO SCROLL</literal> cannot be |
| 3335 |
specified in <command>OPEN</command>, as the cursor's scrolling |
| 3336 |
behavior was already determined. |
| 3337 |
</para> |
| 3338 |
|
| 3339 |
<para> |
| 3340 |
Argument values can be passed using either <firstterm>positional</firstterm> |
| 3341 |
or <firstterm>named</firstterm> notation. In positional |
| 3342 |
notation, all arguments are specified in order. In named notation, |
| 3343 |
each argument's name is specified using <literal>:=</literal> |
| 3344 |
or <literal>=></literal> to |
| 3345 |
separate it from the argument expression. Similar to calling |
| 3346 |
functions, described in <xref linkend="sql-syntax-calling-funcs"/>, it |
| 3347 |
is also allowed to mix positional and named notation. |
| 3348 |
</para> |
| 3349 |
|
| 3350 |
<para> |
| 3351 |
Examples (these use the cursor declaration examples above): |
| 3352 |
<programlisting> |
| 3353 |
OPEN curs2; |
| 3354 |
OPEN curs3(42); |
| 3355 |
OPEN curs3(key := 42); |
| 3356 |
OPEN curs3(key => 42); |
| 3357 |
</programlisting> |
| 3358 |
</para> |
| 3359 |
|
| 3360 |
<para> |
| 3361 |
Because variable substitution is done on a bound cursor's query, |
| 3362 |
there are really two ways to pass values into the cursor: either |
| 3363 |
with an explicit argument to <command>OPEN</command>, or implicitly by |
| 3364 |
referencing a <application>PL/pgSQL</application> variable in the query. |
| 3365 |
However, only variables declared before the bound cursor was |
| 3366 |
declared will be substituted into it. In either case the value to |
| 3367 |
be passed is determined at the time of the <command>OPEN</command>. |
| 3368 |
For example, another way to get the same effect as the |
| 3369 |
<literal>curs3</literal> example above is |
| 3370 |
<programlisting> |
| 3371 |
DECLARE |
| 3372 |
key integer; |
| 3373 |
curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key; |
| 3374 |
BEGIN |
| 3375 |
key := 42; |
| 3376 |
OPEN curs4; |
| 3377 |
</programlisting> |
| 3378 |
</para> |
| 3379 |
</sect3> |
| 3380 |
</sect2> |
| 3381 |
|
| 3382 |
<sect2 id="plpgsql-cursor-using"> |
| 3383 |
<title>Using Cursors</title> |
| 3384 |
|
| 3385 |
<para> |
| 3386 |
Once a cursor has been opened, it can be manipulated with the |
| 3387 |
statements described here. |
| 3388 |
</para> |
| 3389 |
|
| 3390 |
<para> |
| 3391 |
These manipulations need not occur in the same function that |
| 3392 |
opened the cursor to begin with. You can return a <type>refcursor</type> |
| 3393 |
value out of a function and let the caller operate on the cursor. |
| 3394 |
(Internally, a <type>refcursor</type> value is simply the string name |
| 3395 |
of the portal containing the active query for the cursor. This name |
| 3396 |
can be passed around, assigned to other <type>refcursor</type> variables, |
| 3397 |
and so on, without disturbing the portal.) |
| 3398 |
</para> |
| 3399 |
|
| 3400 |
<para> |
| 3401 |
All portals are implicitly closed at transaction end. Therefore |
| 3402 |
a <type>refcursor</type> value is usable to reference an open cursor |
| 3403 |
only until the end of the transaction. |
| 3404 |
</para> |
| 3405 |
|
| 3406 |
<sect3 id="plpgsql-cursor-using-fetch"> |
| 3407 |
<title><literal>FETCH</literal></title> |
| 3408 |
|
| 3409 |
<synopsis> |
| 3410 |
FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>; |
| 3411 |
</synopsis> |
| 3412 |
|
| 3413 |
<para> |
| 3414 |
<command>FETCH</command> retrieves the next row (in the indicated |
| 3415 |
direction) from the |
| 3416 |
cursor into a target, which might be a row variable, a record |
| 3417 |
variable, or a comma-separated list of simple variables, just like |
| 3418 |
<command>SELECT INTO</command>. If there is no suitable row, the |
| 3419 |
target is set to NULL(s). As with <command>SELECT |
| 3420 |
INTO</command>, the special variable <literal>FOUND</literal> can |
| 3421 |
be checked to see whether a row was obtained or not. If no row is |
| 3422 |
obtained, the cursor is positioned after the last row or before the |
| 3423 |
first row, depending on the movement direction. |
| 3424 |
</para> |
| 3425 |
|
| 3426 |
<para> |
| 3427 |
The <replaceable>direction</replaceable> clause can be any of the |
| 3428 |
variants allowed in the SQL <xref linkend="sql-fetch"/> |
| 3429 |
command except the ones that can fetch |
| 3430 |
more than one row; namely, it can be |
| 3431 |
<literal>NEXT</literal>, |
| 3432 |
<literal>PRIOR</literal>, |
| 3433 |
<literal>FIRST</literal>, |
| 3434 |
<literal>LAST</literal>, |
| 3435 |
<literal>ABSOLUTE</literal> <replaceable>count</replaceable>, |
| 3436 |
<literal>RELATIVE</literal> <replaceable>count</replaceable>, |
| 3437 |
<literal>FORWARD</literal>, or |
| 3438 |
<literal>BACKWARD</literal>. |
| 3439 |
Omitting <replaceable>direction</replaceable> is the same |
| 3440 |
as specifying <literal>NEXT</literal>. |
| 3441 |
In the forms using a <replaceable>count</replaceable>, |
| 3442 |
the <replaceable>count</replaceable> can be any integer-valued |
| 3443 |
expression (unlike the SQL <command>FETCH</command> command, |
| 3444 |
which only allows an integer constant). |
| 3445 |
<replaceable>direction</replaceable> values that require moving |
| 3446 |
backward are likely to fail unless the cursor was declared or opened |
| 3447 |
with the <literal>SCROLL</literal> option. |
| 3448 |
</para> |
| 3449 |
|
| 3450 |
<para> |
| 3451 |
<replaceable>cursor</replaceable> must be the name of a <type>refcursor</type> |
| 3452 |
variable that references an open cursor portal. |
| 3453 |
</para> |
| 3454 |
|
| 3455 |
<para> |
| 3456 |
Examples: |
| 3457 |
<programlisting> |
| 3458 |
FETCH curs1 INTO rowvar; |
| 3459 |
FETCH curs2 INTO foo, bar, baz; |
| 3460 |
FETCH LAST FROM curs3 INTO x, y; |
| 3461 |
FETCH RELATIVE -2 FROM curs4 INTO x; |
| 3462 |
</programlisting> |
| 3463 |
</para> |
| 3464 |
</sect3> |
| 3465 |
|
| 3466 |
<sect3 id="plpgsql-cursor-using-move"> |
| 3467 |
<title><literal>MOVE</literal></title> |
| 3468 |
|
| 3469 |
<synopsis> |
| 3470 |
MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>; |
| 3471 |
</synopsis> |
| 3472 |
|
| 3473 |
<para> |
| 3474 |
<command>MOVE</command> repositions a cursor without retrieving |
| 3475 |
any data. <command>MOVE</command> works like the |
| 3476 |
<command>FETCH</command> command, except it only repositions the |
| 3477 |
cursor and does not return the row moved to. |
| 3478 |
The <replaceable>direction</replaceable> clause can be any of the |
| 3479 |
variants allowed in the SQL <xref linkend="sql-fetch"/> |
| 3480 |
command, including those that can fetch more than one row; |
| 3481 |
the cursor is positioned to the last such row. |
| 3482 |
(However, the case in which the <replaceable>direction</replaceable> |
| 3483 |
clause is simply a <replaceable>count</replaceable> expression with |
| 3484 |
no key word is deprecated in <application>PL/pgSQL</application>. |
| 3485 |
That syntax is ambiguous with the case where |
| 3486 |
the <replaceable>direction</replaceable> clause is omitted |
| 3487 |
altogether, and hence it may fail if |
| 3488 |
the <replaceable>count</replaceable> is not a constant.) |
| 3489 |
As with <command>SELECT |
| 3490 |
INTO</command>, the special variable <literal>FOUND</literal> can |
| 3491 |
be checked to see whether there was a row to move to. If there is no |
| 3492 |
such row, the cursor is positioned after the last row or before the |
| 3493 |
first row, depending on the movement direction. |
| 3494 |
</para> |
| 3495 |
|
| 3496 |
<para> |
| 3497 |
Examples: |
| 3498 |
<programlisting> |
| 3499 |
MOVE curs1; |
| 3500 |
MOVE LAST FROM curs3; |
| 3501 |
MOVE RELATIVE -2 FROM curs4; |
| 3502 |
MOVE FORWARD 2 FROM curs4; |
| 3503 |
</programlisting> |
| 3504 |
</para> |
| 3505 |
</sect3> |
| 3506 |
|
| 3507 |
<sect3 id="plpgsql-cursor-using-update-delete"> |
| 3508 |
<title><literal>UPDATE/DELETE WHERE CURRENT OF</literal></title> |
| 3509 |
|
| 3510 |
<synopsis> |
| 3511 |
UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>; |
| 3512 |
DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>; |
| 3513 |
</synopsis> |
| 3514 |
|
| 3515 |
<para> |
| 3516 |
When a cursor is positioned on a table row, that row can be updated |
| 3517 |
or deleted using the cursor to identify the row. There are |
| 3518 |
restrictions on what the cursor's query can be (in particular, |
| 3519 |
no grouping) and it's best to use <literal>FOR UPDATE</literal> in the |
| 3520 |
cursor. For more information see the |
| 3521 |
<xref linkend="sql-declare"/> |
| 3522 |
reference page. |
| 3523 |
</para> |
| 3524 |
|
| 3525 |
<para> |
| 3526 |
An example: |
| 3527 |
<programlisting> |
| 3528 |
UPDATE foo SET dataval = myval WHERE CURRENT OF curs1; |
| 3529 |
</programlisting> |
| 3530 |
</para> |
| 3531 |
</sect3> |
| 3532 |
|
| 3533 |
<sect3 id="plpgsql-cursor-using-close"> |
| 3534 |
<title><literal>CLOSE</literal></title> |
| 3535 |
|
| 3536 |
<synopsis> |
| 3537 |
CLOSE <replaceable>cursor</replaceable>; |
| 3538 |
</synopsis> |
| 3539 |
|
| 3540 |
<para> |
| 3541 |
<command>CLOSE</command> closes the portal underlying an open |
| 3542 |
cursor. This can be used to release resources earlier than end of |
| 3543 |
transaction, or to free up the cursor variable to be opened again. |
| 3544 |
</para> |
| 3545 |
|
| 3546 |
<para> |
| 3547 |
An example: |
| 3548 |
<programlisting> |
| 3549 |
CLOSE curs1; |
| 3550 |
</programlisting> |
| 3551 |
</para> |
| 3552 |
</sect3> |
| 3553 |
|
| 3554 |
<sect3 id="plpgsql-cursor-returning"> |
| 3555 |
<title>Returning Cursors</title> |
| 3556 |
|
| 3557 |
<para> |
| 3558 |
<application>PL/pgSQL</application> functions can return cursors to the |
| 3559 |
caller. This is useful to return multiple rows or columns, |
| 3560 |
especially with very large result sets. To do this, the function |
| 3561 |
opens the cursor and returns the cursor name to the caller (or simply |
| 3562 |
opens the cursor using a portal name specified by or otherwise known |
| 3563 |
to the caller). The caller can then fetch rows from the cursor. The |
| 3564 |
cursor can be closed by the caller, or it will be closed automatically |
| 3565 |
when the transaction closes. |
| 3566 |
</para> |
| 3567 |
|
| 3568 |
<para> |
| 3569 |
The portal name used for a cursor can be specified by the |
| 3570 |
programmer or automatically generated. To specify a portal name, |
| 3571 |
simply assign a string to the <type>refcursor</type> variable before |
| 3572 |
opening it. The string value of the <type>refcursor</type> variable |
| 3573 |
will be used by <command>OPEN</command> as the name of the underlying portal. |
| 3574 |
However, if the <type>refcursor</type> variable's value is null |
| 3575 |
(as it will be by default), then |
| 3576 |
<command>OPEN</command> automatically generates a name that does not |
| 3577 |
conflict with any existing portal, and assigns it to the |
| 3578 |
<type>refcursor</type> variable. |
| 3579 |
</para> |
| 3580 |
|
| 3581 |
<note> |
| 3582 |
<para> |
| 3583 |
Prior to <productname>PostgreSQL</productname> 16, bound cursor |
| 3584 |
variables were initialized to contain their own names, rather |
| 3585 |
than being left as null, so that the underlying portal name would |
| 3586 |
be the same as the cursor variable's name by default. This was |
| 3587 |
changed because it created too much risk of conflicts between |
| 3588 |
similarly-named cursors in different functions. |
| 3589 |
</para> |
| 3590 |
</note> |
| 3591 |
|
| 3592 |
<para> |
| 3593 |
The following example shows one way a cursor name can be supplied by |
| 3594 |
the caller: |
| 3595 |
|
| 3596 |
<programlisting> |
| 3597 |
CREATE TABLE test (col text); |
| 3598 |
INSERT INTO test VALUES ('123'); |
| 3599 |
|
| 3600 |
CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS ' |
| 3601 |
BEGIN |
| 3602 |
OPEN $1 FOR SELECT col FROM test; |
| 3603 |
RETURN $1; |
| 3604 |
END; |
| 3605 |
' LANGUAGE plpgsql; |
| 3606 |
|
| 3607 |
BEGIN; |
| 3608 |
SELECT reffunc('funccursor'); |
| 3609 |
FETCH ALL IN funccursor; |
| 3610 |
COMMIT; |
| 3611 |
</programlisting> |
| 3612 |
</para> |
| 3613 |
|
| 3614 |
<para> |
| 3615 |
The following example uses automatic cursor name generation: |
| 3616 |
|
| 3617 |
<programlisting> |
| 3618 |
CREATE FUNCTION reffunc2() RETURNS refcursor AS ' |
| 3619 |
DECLARE |
| 3620 |
ref refcursor; |
| 3621 |
BEGIN |
| 3622 |
OPEN ref FOR SELECT col FROM test; |
| 3623 |
RETURN ref; |
| 3624 |
END; |
| 3625 |
' LANGUAGE plpgsql; |
| 3626 |
|
| 3627 |
-- need to be in a transaction to use cursors. |
| 3628 |
BEGIN; |
| 3629 |
SELECT reffunc2(); |
| 3630 |
|
| 3631 |
reffunc2 |
| 3632 |
-------------------- |
| 3633 |
<unnamed cursor 1> |
| 3634 |
(1 row) |
| 3635 |
|
| 3636 |
FETCH ALL IN "<unnamed cursor 1>"; |
| 3637 |
COMMIT; |
| 3638 |
</programlisting> |
| 3639 |
</para> |
| 3640 |
|
| 3641 |
<para> |
| 3642 |
The following example shows one way to return multiple cursors |
| 3643 |
from a single function: |
| 3644 |
|
| 3645 |
<programlisting> |
| 3646 |
CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$ |
| 3647 |
BEGIN |
| 3648 |
OPEN $1 FOR SELECT * FROM table_1; |
| 3649 |
RETURN NEXT $1; |
| 3650 |
OPEN $2 FOR SELECT * FROM table_2; |
| 3651 |
RETURN NEXT $2; |
| 3652 |
END; |
| 3653 |
$$ LANGUAGE plpgsql; |
| 3654 |
|
| 3655 |
-- need to be in a transaction to use cursors. |
| 3656 |
BEGIN; |
| 3657 |
|
| 3658 |
SELECT * FROM myfunc('a', 'b'); |
| 3659 |
|
| 3660 |
FETCH ALL FROM a; |
| 3661 |
FETCH ALL FROM b; |
| 3662 |
COMMIT; |
| 3663 |
</programlisting> |
| 3664 |
</para> |
| 3665 |
</sect3> |
| 3666 |
</sect2> |
| 3667 |
|
| 3668 |
<sect2 id="plpgsql-cursor-for-loop"> |
| 3669 |
<title>Looping through a Cursor's Result</title> |
| 3670 |
|
| 3671 |
<para> |
| 3672 |
There is a variant of the <command>FOR</command> statement that allows |
| 3673 |
iterating through the rows returned by a cursor. The syntax is: |
| 3674 |
|
| 3675 |
<synopsis> |
| 3676 |
<optional> <<<replaceable>label</replaceable>>> </optional> |
| 3677 |
FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> { := | => } </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP |
| 3678 |
<replaceable>statements</replaceable> |
| 3679 |
END LOOP <optional> <replaceable>label</replaceable> </optional>; |
| 3680 |
</synopsis> |
| 3681 |
|
| 3682 |
The cursor variable must have been bound to some query when it was |
| 3683 |
declared, and it <emphasis>cannot</emphasis> be open already. The |
| 3684 |
<command>FOR</command> statement automatically opens the cursor, and it closes |
| 3685 |
the cursor again when the loop exits. A list of actual argument value |
| 3686 |
expressions must appear if and only if the cursor was declared to take |
| 3687 |
arguments. These values will be substituted in the query, in just |
| 3688 |
the same way as during an <command>OPEN</command> (see <xref |
| 3689 |
linkend="plpgsql-open-bound-cursor"/>). |
| 3690 |
</para> |
| 3691 |
|
| 3692 |
<para> |
| 3693 |
The variable <replaceable>recordvar</replaceable> is automatically |
| 3694 |
defined as type <type>record</type> and exists only inside the loop (any |
| 3695 |
existing definition of the variable name is ignored within the loop). |
| 3696 |
Each row returned by the cursor is successively assigned to this |
| 3697 |
record variable and the loop body is executed. |
| 3698 |
</para> |
| 3699 |
</sect2> |
| 3700 |
|
| 3701 |
</sect1> |
| 3702 |
|
| 3703 |
<sect1 id="plpgsql-transactions"> |
| 3704 |
<title>Transaction Management</title> |
| 3705 |
|
| 3706 |
<para> |
| 3707 |
In procedures invoked by the <command>CALL</command> command |
| 3708 |
as well as in anonymous code blocks (<command>DO</command> command), |
| 3709 |
it is possible to end transactions using the |
| 3710 |
commands <command>COMMIT</command> and <command>ROLLBACK</command>. A new |
| 3711 |
transaction is started automatically after a transaction is ended using |
| 3712 |
these commands, so there is no separate <command>START |
| 3713 |
TRANSACTION</command> command. (Note that <command>BEGIN</command> and |
| 3714 |
<command>END</command> have different meanings in PL/pgSQL.) |
| 3715 |
</para> |
| 3716 |
|
| 3717 |
<para> |
| 3718 |
Here is a simple example: |
| 3719 |
<programlisting> |
| 3720 |
CREATE PROCEDURE transaction_test1() |
| 3721 |
LANGUAGE plpgsql |
| 3722 |
AS $$ |
| 3723 |
BEGIN |
| 3724 |
FOR i IN 0..9 LOOP |
| 3725 |
INSERT INTO test1 (a) VALUES (i); |
| 3726 |
IF i % 2 = 0 THEN |
| 3727 |
COMMIT; |
| 3728 |
ELSE |
| 3729 |
ROLLBACK; |
| 3730 |
END IF; |
| 3731 |
END LOOP; |
| 3732 |
END; |
| 3733 |
$$; |
| 3734 |
|
| 3735 |
CALL transaction_test1(); |
| 3736 |
</programlisting> |
| 3737 |
</para> |
| 3738 |
|
| 3739 |
<indexterm zone="plpgsql-transaction-chain"> |
| 3740 |
<primary>chained transactions</primary> |
| 3741 |
<secondary>in PL/pgSQL</secondary> |
| 3742 |
</indexterm> |
| 3743 |
|
| 3744 |
<para id="plpgsql-transaction-chain"> |
| 3745 |
A new transaction starts out with default transaction characteristics such |
| 3746 |
as transaction isolation level. In cases where transactions are committed |
| 3747 |
in a loop, it might be desirable to start new transactions automatically |
| 3748 |
with the same characteristics as the previous one. The commands |
| 3749 |
<command>COMMIT AND CHAIN</command> and <command>ROLLBACK AND |
| 3750 |
CHAIN</command> accomplish this. |
| 3751 |
</para> |
| 3752 |
|
| 3753 |
<para> |
| 3754 |
Transaction control is only possible in <command>CALL</command> or |
| 3755 |
<command>DO</command> invocations from the top level or nested |
| 3756 |
<command>CALL</command> or <command>DO</command> invocations without any |
| 3757 |
other intervening command. For example, if the call stack is |
| 3758 |
<command>CALL proc1()</command> → <command>CALL proc2()</command> |
| 3759 |
→ <command>CALL proc3()</command>, then the second and third |
| 3760 |
procedures can perform transaction control actions. But if the call stack |
| 3761 |
is <command>CALL proc1()</command> → <command>SELECT |
| 3762 |
func2()</command> → <command>CALL proc3()</command>, then the last |
| 3763 |
procedure cannot do transaction control, because of the |
| 3764 |
<command>SELECT</command> in between. |
| 3765 |
</para> |
| 3766 |
|
| 3767 |
<para> |
| 3768 |
<application>PL/pgSQL</application> does not support savepoints |
| 3769 |
(<command>SAVEPOINT</command>/<command>ROLLBACK TO |
| 3770 |
SAVEPOINT</command>/<command>RELEASE SAVEPOINT</command> commands). |
| 3771 |
Typical usage patterns for savepoints can be replaced by blocks with |
| 3772 |
exception handlers (see <xref linkend="plpgsql-error-trapping"/>). |
| 3773 |
Under the hood, a block with exception handlers forms a |
| 3774 |
subtransaction, which means that transactions cannot be ended inside |
| 3775 |
such a block. |
| 3776 |
</para> |
| 3777 |
|
| 3778 |
<para> |
| 3779 |
Special considerations apply to cursor loops. Consider this example: |
| 3780 |
<programlisting> |
| 3781 |
CREATE PROCEDURE transaction_test2() |
| 3782 |
LANGUAGE plpgsql |
| 3783 |
AS $$ |
| 3784 |
DECLARE |
| 3785 |
r RECORD; |
| 3786 |
BEGIN |
| 3787 |
FOR r IN SELECT * FROM test2 ORDER BY x LOOP |
| 3788 |
INSERT INTO test1 (a) VALUES (r.x); |
| 3789 |
COMMIT; |
| 3790 |
END LOOP; |
| 3791 |
END; |
| 3792 |
$$; |
| 3793 |
|
| 3794 |
CALL transaction_test2(); |
| 3795 |
</programlisting> |
| 3796 |
Normally, cursors are automatically closed at transaction commit. |
| 3797 |
However, a cursor created as part of a loop like this is automatically |
| 3798 |
converted to a holdable cursor by the first <command>COMMIT</command> or |
| 3799 |
<command>ROLLBACK</command>. That means that the cursor is fully |
| 3800 |
evaluated at the first <command>COMMIT</command> or |
| 3801 |
<command>ROLLBACK</command> rather than row by row. The cursor is still |
| 3802 |
removed automatically after the loop, so this is mostly invisible to the |
| 3803 |
user. But one must keep in mind that any table or row locks taken by |
| 3804 |
the cursor's query will no longer be held after the |
| 3805 |
first <command>COMMIT</command> or |
| 3806 |
<command>ROLLBACK</command>. |
| 3807 |
</para> |
| 3808 |
|
| 3809 |
<para> |
| 3810 |
Transaction commands are not allowed in cursor loops driven by commands |
| 3811 |
that are not read-only (for example <command>UPDATE |
| 3812 |
... RETURNING</command>). |
| 3813 |
</para> |
| 3814 |
</sect1> |
| 3815 |
|
| 3816 |
<sect1 id="plpgsql-errors-and-messages"> |
| 3817 |
<title>Errors and Messages</title> |
| 3818 |
|
| 3819 |
<sect2 id="plpgsql-statements-raise"> |
| 3820 |
<title>Reporting Errors and Messages</title> |
| 3821 |
|
| 3822 |
<indexterm> |
| 3823 |
<primary>RAISE</primary> |
| 3824 |
<secondary>in PL/pgSQL</secondary> |
| 3825 |
</indexterm> |
| 3826 |
|
| 3827 |
<indexterm> |
| 3828 |
<primary>reporting errors</primary> |
| 3829 |
<secondary>in PL/pgSQL</secondary> |
| 3830 |
</indexterm> |
| 3831 |
|
| 3832 |
<para> |
| 3833 |
Use the <command>RAISE</command> statement to report messages and |
| 3834 |
raise errors. |
| 3835 |
|
| 3836 |
<synopsis> |
| 3837 |
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">expression</replaceable> <optional>, ... </optional></optional> <optional> USING <replaceable class="parameter">option</replaceable> { = | := } <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>; |
| 3838 |
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> <replaceable class="parameter">condition_name</replaceable> <optional> USING <replaceable class="parameter">option</replaceable> { = | := } <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>; |
| 3839 |
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> SQLSTATE '<replaceable class="parameter">sqlstate</replaceable>' <optional> USING <replaceable class="parameter">option</replaceable> { = | := } <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>; |
| 3840 |
RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> { = | := } <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>; |
| 3841 |
RAISE ; |
| 3842 |
</synopsis> |
| 3843 |
|
| 3844 |
The <replaceable class="parameter">level</replaceable> option specifies |
| 3845 |
the error severity. Allowed levels are <literal>DEBUG</literal>, |
| 3846 |
<literal>LOG</literal>, <literal>INFO</literal>, |
| 3847 |
<literal>NOTICE</literal>, <literal>WARNING</literal>, |
| 3848 |
and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal> |
| 3849 |
being the default. |
| 3850 |
<literal>EXCEPTION</literal> raises an error (which normally aborts the |
| 3851 |
current transaction); the other levels only generate messages of different |
| 3852 |
priority levels. |
| 3853 |
Whether messages of a particular priority are reported to the client, |
| 3854 |
written to the server log, or both is controlled by the |
| 3855 |
<xref linkend="guc-log-min-messages"/> and |
| 3856 |
<xref linkend="guc-client-min-messages"/> configuration |
| 3857 |
variables. See <xref linkend="runtime-config"/> for more |
| 3858 |
information. |
| 3859 |
</para> |
| 3860 |
|
| 3861 |
<para> |
| 3862 |
In the first syntax variant, |
| 3863 |
after the <replaceable class="parameter">level</replaceable> if any, |
| 3864 |
write a <replaceable class="parameter">format</replaceable> string |
| 3865 |
(which must be a simple string literal, not an expression). The |
| 3866 |
format string specifies the error message text to be reported. |
| 3867 |
The format string can be followed |
| 3868 |
by optional argument expressions to be inserted into the message. |
| 3869 |
Inside the format string, <literal>%</literal> is replaced by the |
| 3870 |
string representation of the next optional argument's value. Write |
| 3871 |
<literal>%%</literal> to emit a literal <literal>%</literal>. |
| 3872 |
The number of arguments must match the number of <literal>%</literal> |
| 3873 |
placeholders in the format string, or an error is raised during |
| 3874 |
the compilation of the function. |
| 3875 |
</para> |
| 3876 |
|
| 3877 |
<para> |
| 3878 |
In this example, the value of <literal>v_job_id</literal> will replace the |
| 3879 |
<literal>%</literal> in the string: |
| 3880 |
<programlisting> |
| 3881 |
RAISE NOTICE 'Calling cs_create_job(%)', v_job_id; |
| 3882 |
</programlisting> |
| 3883 |
</para> |
| 3884 |
|
| 3885 |
<para> |
| 3886 |
In the second and third syntax variants, |
| 3887 |
<replaceable class="parameter">condition_name</replaceable> and |
| 3888 |
<replaceable class="parameter">sqlstate</replaceable> specify an |
| 3889 |
error condition name or a five-character SQLSTATE code, respectively. |
| 3890 |
See <xref linkend="errcodes-appendix"/> for the valid error condition |
| 3891 |
names and the predefined SQLSTATE codes. |
| 3892 |
</para> |
| 3893 |
|
| 3894 |
<para> |
| 3895 |
Here are examples |
| 3896 |
of <replaceable class="parameter">condition_name</replaceable> |
| 3897 |
and <replaceable class="parameter">sqlstate</replaceable> usage: |
| 3898 |
<programlisting> |
| 3899 |
RAISE division_by_zero; |
| 3900 |
RAISE WARNING SQLSTATE '22012'; |
| 3901 |
</programlisting> |
| 3902 |
</para> |
| 3903 |
|
| 3904 |
<para> |
| 3905 |
In any of these syntax variants, |
| 3906 |
you can attach additional information to the error report by writing |
| 3907 |
<literal>USING</literal> followed by <replaceable |
| 3908 |
class="parameter">option</replaceable> = <replaceable |
| 3909 |
class="parameter">expression</replaceable> items. Each |
| 3910 |
<replaceable class="parameter">expression</replaceable> can be any |
| 3911 |
string-valued expression. The allowed <replaceable |
| 3912 |
class="parameter">option</replaceable> key words are: |
| 3913 |
|
| 3914 |
<variablelist id="raise-using-options"> |
| 3915 |
<varlistentry id="raise-using-option-message"> |
| 3916 |
<term><literal>MESSAGE</literal></term> |
| 3917 |
<listitem> |
| 3918 |
<para>Sets the error message text. This option can't be used in the |
| 3919 |
first syntax variant, since the message is already supplied.</para> |
| 3920 |
</listitem> |
| 3921 |
</varlistentry> |
| 3922 |
|
| 3923 |
<varlistentry id="raise-using-option-detail"> |
| 3924 |
<term><literal>DETAIL</literal></term> |
| 3925 |
<listitem> |
| 3926 |
<para>Supplies an error detail message.</para> |
| 3927 |
</listitem> |
| 3928 |
</varlistentry> |
| 3929 |
|
| 3930 |
<varlistentry id="raise-using-option-hint"> |
| 3931 |
<term><literal>HINT</literal></term> |
| 3932 |
<listitem> |
| 3933 |
<para>Supplies a hint message.</para> |
| 3934 |
</listitem> |
| 3935 |
</varlistentry> |
| 3936 |
|
| 3937 |
<varlistentry id="raise-using-option-errcode"> |
| 3938 |
<term><literal>ERRCODE</literal></term> |
| 3939 |
<listitem> |
| 3940 |
<para>Specifies the error code (SQLSTATE) to report, either by condition |
| 3941 |
name, as shown in <xref linkend="errcodes-appendix"/>, or directly as a |
| 3942 |
five-character SQLSTATE code. This option can't be used in the |
| 3943 |
second or third syntax variant, since the error code is already |
| 3944 |
supplied.</para> |
| 3945 |
</listitem> |
| 3946 |
</varlistentry> |
| 3947 |
|
| 3948 |
<varlistentry id="raise-using-option-column"> |
| 3949 |
<term><literal>COLUMN</literal></term> |
| 3950 |
<term><literal>CONSTRAINT</literal></term> |
| 3951 |
<term><literal>DATATYPE</literal></term> |
| 3952 |
<term><literal>TABLE</literal></term> |
| 3953 |
<term><literal>SCHEMA</literal></term> |
| 3954 |
<listitem> |
| 3955 |
<para>Supplies the name of a related object.</para> |
| 3956 |
</listitem> |
| 3957 |
</varlistentry> |
| 3958 |
</variablelist> |
| 3959 |
</para> |
| 3960 |
|
| 3961 |
<para> |
| 3962 |
This example will abort the transaction with the given error message |
| 3963 |
and hint: |
| 3964 |
<programlisting> |
| 3965 |
RAISE EXCEPTION 'Nonexistent ID --> %', user_id |
| 3966 |
USING HINT = 'Please check your user ID'; |
| 3967 |
</programlisting> |
| 3968 |
</para> |
| 3969 |
|
| 3970 |
<para> |
| 3971 |
These two examples show equivalent ways of setting the SQLSTATE: |
| 3972 |
<programlisting> |
| 3973 |
RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation'; |
| 3974 |
RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505'; |
| 3975 |
</programlisting> |
| 3976 |
Another way to produce the same result is: |
| 3977 |
<programlisting> |
| 3978 |
RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id; |
| 3979 |
</programlisting> |
| 3980 |
</para> |
| 3981 |
|
| 3982 |
<para> |
| 3983 |
As shown in the fourth syntax variant, it is also possible to |
| 3984 |
write <literal>RAISE USING</literal> or <literal>RAISE |
| 3985 |
<replaceable class="parameter">level</replaceable> USING</literal> and put |
| 3986 |
everything else into the <literal>USING</literal> list. |
| 3987 |
</para> |
| 3988 |
|
| 3989 |
<para> |
| 3990 |
The last variant of <command>RAISE</command> has no parameters at all. |
| 3991 |
This form can only be used inside a <literal>BEGIN</literal> block's |
| 3992 |
<literal>EXCEPTION</literal> clause; |
| 3993 |
it causes the error currently being handled to be re-thrown. |
| 3994 |
</para> |
| 3995 |
|
| 3996 |
<note> |
| 3997 |
<para> |
| 3998 |
Before <productname>PostgreSQL</productname> 9.1, <command>RAISE</command> without |
| 3999 |
parameters was interpreted as re-throwing the error from the block |
| 4000 |
containing the active exception handler. Thus an <literal>EXCEPTION</literal> |
| 4001 |
clause nested within that handler could not catch it, even if the |
| 4002 |
<command>RAISE</command> was within the nested <literal>EXCEPTION</literal> clause's |
| 4003 |
block. This was deemed surprising as well as being incompatible with |
| 4004 |
Oracle's PL/SQL. |
| 4005 |
</para> |
| 4006 |
</note> |
| 4007 |
|
| 4008 |
<para> |
| 4009 |
If no condition name nor SQLSTATE is specified in a |
| 4010 |
<command>RAISE EXCEPTION</command> command, the default is to use |
| 4011 |
<literal>raise_exception</literal> (<literal>P0001</literal>). |
| 4012 |
If no message text is specified, the default is to use the condition |
| 4013 |
name or SQLSTATE as message text. |
| 4014 |
</para> |
| 4015 |
|
| 4016 |
<note> |
| 4017 |
<para> |
| 4018 |
When specifying an error code by SQLSTATE code, you are not |
| 4019 |
limited to the predefined error codes, but can select any |
| 4020 |
error code consisting of five digits and/or upper-case ASCII |
| 4021 |
letters, other than <literal>00000</literal>. It is recommended that |
| 4022 |
you avoid throwing error codes that end in three zeroes, because |
| 4023 |
these are category codes and can only be trapped by trapping |
| 4024 |
the whole category. |
| 4025 |
</para> |
| 4026 |
</note> |
| 4027 |
|
| 4028 |
</sect2> |
| 4029 |
|
| 4030 |
<sect2 id="plpgsql-statements-assert"> |
| 4031 |
<title>Checking Assertions</title> |
| 4032 |
|
| 4033 |
<indexterm> |
| 4034 |
<primary>ASSERT</primary> |
| 4035 |
<secondary>in PL/pgSQL</secondary> |
| 4036 |
</indexterm> |
| 4037 |
|
| 4038 |
<indexterm> |
| 4039 |
<primary>assertions</primary> |
| 4040 |
<secondary>in PL/pgSQL</secondary> |
| 4041 |
</indexterm> |
| 4042 |
|
| 4043 |
<indexterm> |
| 4044 |
<primary><varname>plpgsql.check_asserts</varname> configuration parameter</primary> |
| 4045 |
</indexterm> |
| 4046 |
|
| 4047 |
<para> |
| 4048 |
The <command>ASSERT</command> statement is a convenient shorthand for |
| 4049 |
inserting debugging checks into <application>PL/pgSQL</application> |
| 4050 |
functions. |
| 4051 |
|
| 4052 |
<synopsis> |
| 4053 |
ASSERT <replaceable class="parameter">condition</replaceable> <optional> , <replaceable class="parameter">message</replaceable> </optional>; |
| 4054 |
</synopsis> |
| 4055 |
|
| 4056 |
The <replaceable class="parameter">condition</replaceable> is a Boolean |
| 4057 |
expression that is expected to always evaluate to true; if it does, |
| 4058 |
the <command>ASSERT</command> statement does nothing further. If the |
| 4059 |
result is false or null, then an <literal>ASSERT_FAILURE</literal> exception |
| 4060 |
is raised. (If an error occurs while evaluating |
| 4061 |
the <replaceable class="parameter">condition</replaceable>, it is |
| 4062 |
reported as a normal error.) |
| 4063 |
</para> |
| 4064 |
|
| 4065 |
<para> |
| 4066 |
If the optional <replaceable class="parameter">message</replaceable> is |
| 4067 |
provided, it is an expression whose result (if not null) replaces the |
| 4068 |
default error message text <quote>assertion failed</quote>, should |
| 4069 |
the <replaceable class="parameter">condition</replaceable> fail. |
| 4070 |
The <replaceable class="parameter">message</replaceable> expression is |
| 4071 |
not evaluated in the normal case where the assertion succeeds. |
| 4072 |
</para> |
| 4073 |
|
| 4074 |
<para> |
| 4075 |
Testing of assertions can be enabled or disabled via the configuration |
| 4076 |
parameter <literal>plpgsql.check_asserts</literal>, which takes a Boolean |
| 4077 |
value; the default is <literal>on</literal>. If this parameter |
| 4078 |
is <literal>off</literal> then <command>ASSERT</command> statements do nothing. |
| 4079 |
</para> |
| 4080 |
|
| 4081 |
<para> |
| 4082 |
Note that <command>ASSERT</command> is meant for detecting program |
| 4083 |
bugs, not for reporting ordinary error conditions. Use |
| 4084 |
the <command>RAISE</command> statement, described above, for that. |
| 4085 |
</para> |
| 4086 |
|
| 4087 |
</sect2> |
| 4088 |
|
| 4089 |
</sect1> |
| 4090 |
|
| 4091 |
<sect1 id="plpgsql-trigger"> |
| 4092 |
<title>Trigger Functions</title> |
| 4093 |
|
| 4094 |
<indexterm zone="plpgsql-trigger"> |
| 4095 |
<primary>trigger</primary> |
| 4096 |
<secondary>in PL/pgSQL</secondary> |
| 4097 |
</indexterm> |
| 4098 |
|
| 4099 |
<para> |
| 4100 |
<application>PL/pgSQL</application> can be used to define trigger |
| 4101 |
functions on data changes or database events. |
| 4102 |
A trigger function is created with the <command>CREATE FUNCTION</command> |
| 4103 |
command, declaring it as a function with no arguments and a return type of |
| 4104 |
<type>trigger</type> (for data change triggers) or |
| 4105 |
<type>event_trigger</type> (for database event triggers). |
| 4106 |
Special local variables named <varname>TG_<replaceable>something</replaceable></varname> are |
| 4107 |
automatically defined to describe the condition that triggered the call. |
| 4108 |
</para> |
| 4109 |
|
| 4110 |
<sect2 id="plpgsql-dml-trigger"> |
| 4111 |
<title>Triggers on Data Changes</title> |
| 4112 |
|
| 4113 |
<para> |
| 4114 |
A <link linkend="triggers">data change trigger</link> is declared as a |
| 4115 |
function with no arguments and a return type of <type>trigger</type>. |
| 4116 |
Note that the function must be declared with no arguments even if it |
| 4117 |
expects to receive some arguments specified in <command>CREATE TRIGGER</command> |
| 4118 |
— such arguments are passed via <varname>TG_ARGV</varname>, as described |
| 4119 |
below. |
| 4120 |
</para> |
| 4121 |
|
| 4122 |
<para> |
| 4123 |
When a <application>PL/pgSQL</application> function is called as a |
| 4124 |
trigger, several special variables are created automatically in the |
| 4125 |
top-level block. They are: |
| 4126 |
|
| 4127 |
<variablelist> |
| 4128 |
<varlistentry id="plpgsql-dml-trigger-new"> |
| 4129 |
<term><varname>NEW</varname> <type>record</type></term> |
| 4130 |
<listitem> |
| 4131 |
<para> |
| 4132 |
new database row for <command>INSERT</command>/<command>UPDATE</command> operations in row-level |
| 4133 |
triggers. This variable is null in statement-level triggers |
| 4134 |
and for <command>DELETE</command> operations. |
| 4135 |
</para> |
| 4136 |
</listitem> |
| 4137 |
</varlistentry> |
| 4138 |
|
| 4139 |
<varlistentry id="plpgsql-dml-trigger-old"> |
| 4140 |
<term><varname>OLD</varname> <type>record</type></term> |
| 4141 |
<listitem> |
| 4142 |
<para> |
| 4143 |
old database row for <command>UPDATE</command>/<command>DELETE</command> operations in row-level |
| 4144 |
triggers. This variable is null in statement-level triggers |
| 4145 |
and for <command>INSERT</command> operations. |
| 4146 |
</para> |
| 4147 |
</listitem> |
| 4148 |
</varlistentry> |
| 4149 |
|
| 4150 |
<varlistentry id="plpgsql-dml-trigger-tg-name"> |
| 4151 |
<term><varname>TG_NAME</varname> <type>name</type></term> |
| 4152 |
<listitem> |
| 4153 |
<para> |
| 4154 |
name of the trigger which fired. |
| 4155 |
</para> |
| 4156 |
</listitem> |
| 4157 |
</varlistentry> |
| 4158 |
|
| 4159 |
<varlistentry id="plpgsql-dml-trigger-tg-when"> |
| 4160 |
<term><varname>TG_WHEN</varname> <type>text</type></term> |
| 4161 |
<listitem> |
| 4162 |
<para> |
| 4163 |
<literal>BEFORE</literal>, <literal>AFTER</literal>, or |
| 4164 |
<literal>INSTEAD OF</literal>, depending on the trigger's definition. |
| 4165 |
</para> |
| 4166 |
</listitem> |
| 4167 |
</varlistentry> |
| 4168 |
|
| 4169 |
<varlistentry id="plpgsql-dml-trigger-tg-level"> |
| 4170 |
<term><varname>TG_LEVEL</varname> <type>text</type></term> |
| 4171 |
<listitem> |
| 4172 |
<para> |
| 4173 |
<literal>ROW</literal> or <literal>STATEMENT</literal>, |
| 4174 |
depending on the trigger's definition. |
| 4175 |
</para> |
| 4176 |
</listitem> |
| 4177 |
</varlistentry> |
| 4178 |
|
| 4179 |
<varlistentry id="plpgsql-dml-trigger-tg-op"> |
| 4180 |
<term><varname>TG_OP</varname> <type>text</type></term> |
| 4181 |
<listitem> |
| 4182 |
<para> |
| 4183 |
operation for which the trigger was fired: |
| 4184 |
<literal>INSERT</literal>, <literal>UPDATE</literal>, |
| 4185 |
<literal>DELETE</literal>, or <literal>TRUNCATE</literal>. |
| 4186 |
</para> |
| 4187 |
</listitem> |
| 4188 |
</varlistentry> |
| 4189 |
|
| 4190 |
<varlistentry id="plpgsql-dml-trigger-tg-relid"> |
| 4191 |
<term><varname>TG_RELID</varname> <type>oid</type> (references <link linkend="catalog-pg-class"><structname>pg_class</structname></link>.<structfield>oid</structfield>)</term> |
| 4192 |
<listitem> |
| 4193 |
<para> |
| 4194 |
object ID of the table that caused the trigger invocation. |
| 4195 |
</para> |
| 4196 |
</listitem> |
| 4197 |
</varlistentry> |
| 4198 |
|
| 4199 |
<varlistentry id="plpgsql-dml-trigger-tg-relname"> |
| 4200 |
<term><varname>TG_RELNAME</varname> <type>name</type></term> |
| 4201 |
<listitem> |
| 4202 |
<para> |
| 4203 |
table that caused the trigger |
| 4204 |
invocation. This is now deprecated, and could disappear in a future |
| 4205 |
release. Use <literal>TG_TABLE_NAME</literal> instead. |
| 4206 |
</para> |
| 4207 |
</listitem> |
| 4208 |
</varlistentry> |
| 4209 |
|
| 4210 |
<varlistentry id="plpgsql-dml-trigger-tg-table-name"> |
| 4211 |
<term><varname>TG_TABLE_NAME</varname> <type>name</type></term> |
| 4212 |
<listitem> |
| 4213 |
<para> |
| 4214 |
table that caused the trigger invocation. |
| 4215 |
</para> |
| 4216 |
</listitem> |
| 4217 |
</varlistentry> |
| 4218 |
|
| 4219 |
<varlistentry id="plpgsql-dml-trigger-tg-table-schema"> |
| 4220 |
<term><varname>TG_TABLE_SCHEMA</varname> <type>name</type></term> |
| 4221 |
<listitem> |
| 4222 |
<para> |
| 4223 |
schema of the table that caused the trigger invocation. |
| 4224 |
</para> |
| 4225 |
</listitem> |
| 4226 |
</varlistentry> |
| 4227 |
|
| 4228 |
<varlistentry id="plpgsql-dml-trigger-tg-nargs"> |
| 4229 |
<term><varname>TG_NARGS</varname> <type>integer</type></term> |
| 4230 |
<listitem> |
| 4231 |
<para> |
| 4232 |
number of arguments given to the trigger |
| 4233 |
function in the <command>CREATE TRIGGER</command> statement. |
| 4234 |
</para> |
| 4235 |
</listitem> |
| 4236 |
</varlistentry> |
| 4237 |
|
| 4238 |
<varlistentry id="plpgsql-dml-trigger-tg-argv"> |
| 4239 |
<term><varname>TG_ARGV</varname> <type>text[]</type></term> |
| 4240 |
<listitem> |
| 4241 |
<para> |
| 4242 |
arguments from |
| 4243 |
the <command>CREATE TRIGGER</command> statement. |
| 4244 |
The index counts from 0. Invalid |
| 4245 |
indexes (less than 0 or greater than or equal to <varname>tg_nargs</varname>) |
| 4246 |
result in a null value. |
| 4247 |
</para> |
| 4248 |
</listitem> |
| 4249 |
</varlistentry> |
| 4250 |
</variablelist> |
| 4251 |
</para> |
| 4252 |
|
| 4253 |
<para> |
| 4254 |
A trigger function must return either <symbol>NULL</symbol> or a |
| 4255 |
record/row value having exactly the structure of the table the |
| 4256 |
trigger was fired for. |
| 4257 |
</para> |
| 4258 |
|
| 4259 |
<para> |
| 4260 |
Row-level triggers fired <literal>BEFORE</literal> can return null to signal the |
| 4261 |
trigger manager to skip the rest of the operation for this row |
| 4262 |
(i.e., subsequent triggers are not fired, and the |
| 4263 |
<command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command> does not occur |
| 4264 |
for this row). If a nonnull |
| 4265 |
value is returned then the operation proceeds with that row value. |
| 4266 |
Returning a row value different from the original value |
| 4267 |
of <varname>NEW</varname> alters the row that will be inserted or |
| 4268 |
updated. Thus, if the trigger function wants the triggering |
| 4269 |
action to succeed normally without altering the row |
| 4270 |
value, <varname>NEW</varname> (or a value equal thereto) has to be |
| 4271 |
returned. To alter the row to be stored, it is possible to |
| 4272 |
replace single values directly in <varname>NEW</varname> and return the |
| 4273 |
modified <varname>NEW</varname>, or to build a complete new record/row to |
| 4274 |
return. In the case of a before-trigger |
| 4275 |
on <command>DELETE</command>, the returned value has no direct |
| 4276 |
effect, but it has to be nonnull to allow the trigger action to |
| 4277 |
proceed. Note that <varname>NEW</varname> is null |
| 4278 |
in <command>DELETE</command> triggers, so returning that is |
| 4279 |
usually not sensible. The usual idiom in <command>DELETE</command> |
| 4280 |
triggers is to return <varname>OLD</varname>. |
| 4281 |
</para> |
| 4282 |
|
| 4283 |
<para> |
| 4284 |
<literal>INSTEAD OF</literal> triggers (which are always row-level triggers, |
| 4285 |
and may only be used on views) can return null to signal that they did |
| 4286 |
not perform any updates, and that the rest of the operation for this |
| 4287 |
row should be skipped (i.e., subsequent triggers are not fired, and the |
| 4288 |
row is not counted in the rows-affected status for the surrounding |
| 4289 |
<command>INSERT</command>/<command>UPDATE</command>/<command>DELETE</command>). |
| 4290 |
Otherwise a nonnull value should be returned, to signal |
| 4291 |
that the trigger performed the requested operation. For |
| 4292 |
<command>INSERT</command> and <command>UPDATE</command> operations, the return value |
| 4293 |
should be <varname>NEW</varname>, which the trigger function may modify to |
| 4294 |
support <command>INSERT RETURNING</command> and <command>UPDATE RETURNING</command> |
| 4295 |
(this will also affect the row value passed to any subsequent triggers, |
| 4296 |
or passed to a special <varname>EXCLUDED</varname> alias reference within |
| 4297 |
an <command>INSERT</command> statement with an <literal>ON CONFLICT DO |
| 4298 |
UPDATE</literal> clause). For <command>DELETE</command> operations, the return |
| 4299 |
value should be <varname>OLD</varname>. |
| 4300 |
</para> |
| 4301 |
|
| 4302 |
<para> |
| 4303 |
The return value of a row-level trigger |
| 4304 |
fired <literal>AFTER</literal> or a statement-level trigger |
| 4305 |
fired <literal>BEFORE</literal> or <literal>AFTER</literal> is |
| 4306 |
always ignored; it might as well be null. However, any of these types of |
| 4307 |
triggers might still abort the entire operation by raising an error. |
| 4308 |
</para> |
| 4309 |
|
| 4310 |
<para> |
| 4311 |
<xref linkend="plpgsql-trigger-example"/> shows an example of a |
| 4312 |
trigger function in <application>PL/pgSQL</application>. |
| 4313 |
</para> |
| 4314 |
|
| 4315 |
<example id="plpgsql-trigger-example"> |
| 4316 |
<title>A <application>PL/pgSQL</application> Trigger Function</title> |
| 4317 |
|
| 4318 |
<para> |
| 4319 |
This example trigger ensures that any time a row is inserted or updated |
| 4320 |
in the table, the current user name and time are stamped into the |
| 4321 |
row. And it checks that an employee's name is given and that the |
| 4322 |
salary is a positive value. |
| 4323 |
</para> |
| 4324 |
|
| 4325 |
<programlisting> |
| 4326 |
CREATE TABLE emp ( |
| 4327 |
empname text, |
| 4328 |
salary integer, |
| 4329 |
last_date timestamp, |
| 4330 |
last_user text |
| 4331 |
); |
| 4332 |
|
| 4333 |
CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$ |
| 4334 |
BEGIN |
| 4335 |
-- Check that empname and salary are given |
| 4336 |
IF NEW.empname IS NULL THEN |
| 4337 |
RAISE EXCEPTION 'empname cannot be null'; |
| 4338 |
END IF; |
| 4339 |
IF NEW.salary IS NULL THEN |
| 4340 |
RAISE EXCEPTION '% cannot have null salary', NEW.empname; |
| 4341 |
END IF; |
| 4342 |
|
| 4343 |
-- Who works for us when they must pay for it? |
| 4344 |
IF NEW.salary < 0 THEN |
| 4345 |
RAISE EXCEPTION '% cannot have a negative salary', NEW.empname; |
| 4346 |
END IF; |
| 4347 |
|
| 4348 |
-- Remember who changed the payroll when |
| 4349 |
NEW.last_date := current_timestamp; |
| 4350 |
NEW.last_user := current_user; |
| 4351 |
RETURN NEW; |
| 4352 |
END; |
| 4353 |
$emp_stamp$ LANGUAGE plpgsql; |
| 4354 |
|
| 4355 |
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp |
| 4356 |
FOR EACH ROW EXECUTE FUNCTION emp_stamp(); |
| 4357 |
</programlisting> |
| 4358 |
</example> |
| 4359 |
|
| 4360 |
<para> |
| 4361 |
Another way to log changes to a table involves creating a new table that |
| 4362 |
holds a row for each insert, update, or delete that occurs. This approach |
| 4363 |
can be thought of as auditing changes to a table. |
| 4364 |
<xref linkend="plpgsql-trigger-audit-example"/> shows an example of an |
| 4365 |
audit trigger function in <application>PL/pgSQL</application>. |
| 4366 |
</para> |
| 4367 |
|
| 4368 |
<example id="plpgsql-trigger-audit-example"> |
| 4369 |
<title>A <application>PL/pgSQL</application> Trigger Function for Auditing</title> |
| 4370 |
|
| 4371 |
<para> |
| 4372 |
This example trigger ensures that any insert, update or delete of a row |
| 4373 |
in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table. |
| 4374 |
The current time and user name are stamped into the row, together with |
| 4375 |
the type of operation performed on it. |
| 4376 |
</para> |
| 4377 |
|
| 4378 |
<programlisting> |
| 4379 |
CREATE TABLE emp ( |
| 4380 |
empname text NOT NULL, |
| 4381 |
salary integer |
| 4382 |
); |
| 4383 |
|
| 4384 |
CREATE TABLE emp_audit( |
| 4385 |
operation char(1) NOT NULL, |
| 4386 |
stamp timestamp NOT NULL, |
| 4387 |
userid text NOT NULL, |
| 4388 |
empname text NOT NULL, |
| 4389 |
salary integer |
| 4390 |
); |
| 4391 |
|
| 4392 |
CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$ |
| 4393 |
BEGIN |
| 4394 |
-- |
| 4395 |
-- Create a row in emp_audit to reflect the operation performed on emp, |
| 4396 |
-- making use of the special variable TG_OP to work out the operation. |
| 4397 |
-- |
| 4398 |
IF (TG_OP = 'DELETE') THEN |
| 4399 |
INSERT INTO emp_audit SELECT 'D', now(), current_user, OLD.*; |
| 4400 |
ELSIF (TG_OP = 'UPDATE') THEN |
| 4401 |
INSERT INTO emp_audit SELECT 'U', now(), current_user, NEW.*; |
| 4402 |
ELSIF (TG_OP = 'INSERT') THEN |
| 4403 |
INSERT INTO emp_audit SELECT 'I', now(), current_user, NEW.*; |
| 4404 |
END IF; |
| 4405 |
RETURN NULL; -- result is ignored since this is an AFTER trigger |
| 4406 |
END; |
| 4407 |
$emp_audit$ LANGUAGE plpgsql; |
| 4408 |
|
| 4409 |
CREATE TRIGGER emp_audit |
| 4410 |
AFTER INSERT OR UPDATE OR DELETE ON emp |
| 4411 |
FOR EACH ROW EXECUTE FUNCTION process_emp_audit(); |
| 4412 |
</programlisting> |
| 4413 |
</example> |
| 4414 |
|
| 4415 |
<para> |
| 4416 |
A variation of the previous example uses a view joining the main table |
| 4417 |
to the audit table, to show when each entry was last modified. This |
| 4418 |
approach still records the full audit trail of changes to the table, |
| 4419 |
but also presents a simplified view of the audit trail, showing just |
| 4420 |
the last modified timestamp derived from the audit trail for each entry. |
| 4421 |
<xref linkend="plpgsql-view-trigger-audit-example"/> shows an example |
| 4422 |
of an audit trigger on a view in <application>PL/pgSQL</application>. |
| 4423 |
</para> |
| 4424 |
|
| 4425 |
<example id="plpgsql-view-trigger-audit-example"> |
| 4426 |
<title>A <application>PL/pgSQL</application> View Trigger Function for Auditing</title> |
| 4427 |
|
| 4428 |
<para> |
| 4429 |
This example uses a trigger on the view to make it updatable, and |
| 4430 |
ensure that any insert, update or delete of a row in the view is |
| 4431 |
recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time |
| 4432 |
and user name are recorded, together with the type of operation |
| 4433 |
performed, and the view displays the last modified time of each row. |
| 4434 |
</para> |
| 4435 |
|
| 4436 |
<programlisting> |
| 4437 |
CREATE TABLE emp ( |
| 4438 |
empname text PRIMARY KEY, |
| 4439 |
salary integer |
| 4440 |
); |
| 4441 |
|
| 4442 |
CREATE TABLE emp_audit( |
| 4443 |
operation char(1) NOT NULL, |
| 4444 |
userid text NOT NULL, |
| 4445 |
empname text NOT NULL, |
| 4446 |
salary integer, |
| 4447 |
stamp timestamp NOT NULL |
| 4448 |
); |
| 4449 |
|
| 4450 |
CREATE VIEW emp_view AS |
| 4451 |
SELECT e.empname, |
| 4452 |
e.salary, |
| 4453 |
max(ea.stamp) AS last_updated |
| 4454 |
FROM emp e |
| 4455 |
LEFT JOIN emp_audit ea ON ea.empname = e.empname |
| 4456 |
GROUP BY 1, 2; |
| 4457 |
|
| 4458 |
CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$ |
| 4459 |
BEGIN |
| 4460 |
-- |
| 4461 |
-- Perform the required operation on emp, and create a row in emp_audit |
| 4462 |
-- to reflect the change made to emp. |
| 4463 |
-- |
| 4464 |
IF (TG_OP = 'DELETE') THEN |
| 4465 |
DELETE FROM emp WHERE empname = OLD.empname; |
| 4466 |
IF NOT FOUND THEN RETURN NULL; END IF; |
| 4467 |
|
| 4468 |
OLD.last_updated = now(); |
| 4469 |
INSERT INTO emp_audit VALUES('D', current_user, OLD.*); |
| 4470 |
RETURN OLD; |
| 4471 |
ELSIF (TG_OP = 'UPDATE') THEN |
| 4472 |
UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname; |
| 4473 |
IF NOT FOUND THEN RETURN NULL; END IF; |
| 4474 |
|
| 4475 |
NEW.last_updated = now(); |
| 4476 |
INSERT INTO emp_audit VALUES('U', current_user, NEW.*); |
| 4477 |
RETURN NEW; |
| 4478 |
ELSIF (TG_OP = 'INSERT') THEN |
| 4479 |
INSERT INTO emp VALUES(NEW.empname, NEW.salary); |
| 4480 |
|
| 4481 |
NEW.last_updated = now(); |
| 4482 |
INSERT INTO emp_audit VALUES('I', current_user, NEW.*); |
| 4483 |
RETURN NEW; |
| 4484 |
END IF; |
| 4485 |
END; |
| 4486 |
$$ LANGUAGE plpgsql; |
| 4487 |
|
| 4488 |
CREATE TRIGGER emp_audit |
| 4489 |
INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view |
| 4490 |
FOR EACH ROW EXECUTE FUNCTION update_emp_view(); |
| 4491 |
</programlisting> |
| 4492 |
</example> |
| 4493 |
|
| 4494 |
<para> |
| 4495 |
One use of triggers is to maintain a summary table |
| 4496 |
of another table. The resulting summary can be used in place of the |
| 4497 |
original table for certain queries — often with vastly reduced run |
| 4498 |
times. |
| 4499 |
This technique is commonly used in Data Warehousing, where the tables |
| 4500 |
of measured or observed data (called fact tables) might be extremely large. |
| 4501 |
<xref linkend="plpgsql-trigger-summary-example"/> shows an example of a |
| 4502 |
trigger function in <application>PL/pgSQL</application> that maintains |
| 4503 |
a summary table for a fact table in a data warehouse. |
| 4504 |
</para> |
| 4505 |
|
| 4506 |
|
| 4507 |
<example id="plpgsql-trigger-summary-example"> |
| 4508 |
<title>A <application>PL/pgSQL</application> Trigger Function for Maintaining a Summary Table</title> |
| 4509 |
|
| 4510 |
<para> |
| 4511 |
The schema detailed here is partly based on the <emphasis>Grocery Store |
| 4512 |
</emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis> |
| 4513 |
by Ralph Kimball. |
| 4514 |
</para> |
| 4515 |
|
| 4516 |
<programlisting> |
| 4517 |
-- |
| 4518 |
-- Main tables - time dimension and sales fact. |
| 4519 |
-- |
| 4520 |
CREATE TABLE time_dimension ( |
| 4521 |
time_key integer NOT NULL, |
| 4522 |
day_of_week integer NOT NULL, |
| 4523 |
day_of_month integer NOT NULL, |
| 4524 |
month integer NOT NULL, |
| 4525 |
quarter integer NOT NULL, |
| 4526 |
year integer NOT NULL |
| 4527 |
); |
| 4528 |
CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key); |
| 4529 |
|
| 4530 |
CREATE TABLE sales_fact ( |
| 4531 |
time_key integer NOT NULL, |
| 4532 |
product_key integer NOT NULL, |
| 4533 |
store_key integer NOT NULL, |
| 4534 |
amount_sold numeric(12,2) NOT NULL, |
| 4535 |
units_sold integer NOT NULL, |
| 4536 |
amount_cost numeric(12,2) NOT NULL |
| 4537 |
); |
| 4538 |
CREATE INDEX sales_fact_time ON sales_fact(time_key); |
| 4539 |
|
| 4540 |
-- |
| 4541 |
-- Summary table - sales by time. |
| 4542 |
-- |
| 4543 |
CREATE TABLE sales_summary_bytime ( |
| 4544 |
time_key integer NOT NULL, |
| 4545 |
amount_sold numeric(15,2) NOT NULL, |
| 4546 |
units_sold numeric(12) NOT NULL, |
| 4547 |
amount_cost numeric(15,2) NOT NULL |
| 4548 |
); |
| 4549 |
CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key); |
| 4550 |
|
| 4551 |
-- |
| 4552 |
-- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE. |
| 4553 |
-- |
| 4554 |
CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER |
| 4555 |
AS $maint_sales_summary_bytime$ |
| 4556 |
DECLARE |
| 4557 |
delta_time_key integer; |
| 4558 |
delta_amount_sold numeric(15,2); |
| 4559 |
delta_units_sold numeric(12); |
| 4560 |
delta_amount_cost numeric(15,2); |
| 4561 |
BEGIN |
| 4562 |
|
| 4563 |
-- Work out the increment/decrement amount(s). |
| 4564 |
IF (TG_OP = 'DELETE') THEN |
| 4565 |
|
| 4566 |
delta_time_key = OLD.time_key; |
| 4567 |
delta_amount_sold = -1 * OLD.amount_sold; |
| 4568 |
delta_units_sold = -1 * OLD.units_sold; |
| 4569 |
delta_amount_cost = -1 * OLD.amount_cost; |
| 4570 |
|
| 4571 |
ELSIF (TG_OP = 'UPDATE') THEN |
| 4572 |
|
| 4573 |
-- forbid updates that change the time_key - |
| 4574 |
-- (probably not too onerous, as DELETE + INSERT is how most |
| 4575 |
-- changes will be made). |
| 4576 |
IF ( OLD.time_key != NEW.time_key) THEN |
| 4577 |
RAISE EXCEPTION 'Update of time_key : % -> % not allowed', |
| 4578 |
OLD.time_key, NEW.time_key; |
| 4579 |
END IF; |
| 4580 |
|
| 4581 |
delta_time_key = OLD.time_key; |
| 4582 |
delta_amount_sold = NEW.amount_sold - OLD.amount_sold; |
| 4583 |
delta_units_sold = NEW.units_sold - OLD.units_sold; |
| 4584 |
delta_amount_cost = NEW.amount_cost - OLD.amount_cost; |
| 4585 |
|
| 4586 |
ELSIF (TG_OP = 'INSERT') THEN |
| 4587 |
|
| 4588 |
delta_time_key = NEW.time_key; |
| 4589 |
delta_amount_sold = NEW.amount_sold; |
| 4590 |
delta_units_sold = NEW.units_sold; |
| 4591 |
delta_amount_cost = NEW.amount_cost; |
| 4592 |
|
| 4593 |
END IF; |
| 4594 |
|
| 4595 |
|
| 4596 |
-- Insert or update the summary row with the new values. |
| 4597 |
<<insert_update>> |
| 4598 |
LOOP |
| 4599 |
UPDATE sales_summary_bytime |
| 4600 |
SET amount_sold = amount_sold + delta_amount_sold, |
| 4601 |
units_sold = units_sold + delta_units_sold, |
| 4602 |
amount_cost = amount_cost + delta_amount_cost |
| 4603 |
WHERE time_key = delta_time_key; |
| 4604 |
|
| 4605 |
EXIT insert_update WHEN found; |
| 4606 |
|
| 4607 |
BEGIN |
| 4608 |
INSERT INTO sales_summary_bytime ( |
| 4609 |
time_key, |
| 4610 |
amount_sold, |
| 4611 |
units_sold, |
| 4612 |
amount_cost) |
| 4613 |
VALUES ( |
| 4614 |
delta_time_key, |
| 4615 |
delta_amount_sold, |
| 4616 |
delta_units_sold, |
| 4617 |
delta_amount_cost |
| 4618 |
); |
| 4619 |
|
| 4620 |
EXIT insert_update; |
| 4621 |
|
| 4622 |
EXCEPTION |
| 4623 |
WHEN UNIQUE_VIOLATION THEN |
| 4624 |
-- do nothing |
| 4625 |
END; |
| 4626 |
END LOOP insert_update; |
| 4627 |
|
| 4628 |
RETURN NULL; |
| 4629 |
|
| 4630 |
END; |
| 4631 |
$maint_sales_summary_bytime$ LANGUAGE plpgsql; |
| 4632 |
|
| 4633 |
CREATE TRIGGER maint_sales_summary_bytime |
| 4634 |
AFTER INSERT OR UPDATE OR DELETE ON sales_fact |
| 4635 |
FOR EACH ROW EXECUTE FUNCTION maint_sales_summary_bytime(); |
| 4636 |
|
| 4637 |
INSERT INTO sales_fact VALUES(1,1,1,10,3,15); |
| 4638 |
INSERT INTO sales_fact VALUES(1,2,1,20,5,35); |
| 4639 |
INSERT INTO sales_fact VALUES(2,2,1,40,15,135); |
| 4640 |
INSERT INTO sales_fact VALUES(2,3,1,10,1,13); |
| 4641 |
SELECT * FROM sales_summary_bytime; |
| 4642 |
DELETE FROM sales_fact WHERE product_key = 1; |
| 4643 |
SELECT * FROM sales_summary_bytime; |
| 4644 |
UPDATE sales_fact SET units_sold = units_sold * 2; |
| 4645 |
SELECT * FROM sales_summary_bytime; |
| 4646 |
</programlisting> |
| 4647 |
</example> |
| 4648 |
|
| 4649 |
<para> |
| 4650 |
<literal>AFTER</literal> triggers can also make use of <firstterm>transition |
| 4651 |
tables</firstterm> to inspect the entire set of rows changed by the triggering |
| 4652 |
statement. The <command>CREATE TRIGGER</command> command assigns names to one |
| 4653 |
or both transition tables, and then the function can refer to those names |
| 4654 |
as though they were read-only temporary tables. |
| 4655 |
<xref linkend="plpgsql-trigger-audit-transition-example"/> shows an example. |
| 4656 |
</para> |
| 4657 |
|
| 4658 |
<example id="plpgsql-trigger-audit-transition-example"> |
| 4659 |
<title>Auditing with Transition Tables</title> |
| 4660 |
|
| 4661 |
<para> |
| 4662 |
This example produces the same results as |
| 4663 |
<xref linkend="plpgsql-trigger-audit-example"/>, but instead of using a |
| 4664 |
trigger that fires for every row, it uses a trigger that fires once |
| 4665 |
per statement, after collecting the relevant information in a transition |
| 4666 |
table. This can be significantly faster than the row-trigger approach |
| 4667 |
when the invoking statement has modified many rows. Notice that we must |
| 4668 |
make a separate trigger declaration for each kind of event, since the |
| 4669 |
<literal>REFERENCING</literal> clauses must be different for each case. But |
| 4670 |
this does not stop us from using a single trigger function if we choose. |
| 4671 |
(In practice, it might be better to use three separate functions and |
| 4672 |
avoid the run-time tests on <varname>TG_OP</varname>.) |
| 4673 |
</para> |
| 4674 |
|
| 4675 |
<programlisting> |
| 4676 |
CREATE TABLE emp ( |
| 4677 |
empname text NOT NULL, |
| 4678 |
salary integer |
| 4679 |
); |
| 4680 |
|
| 4681 |
CREATE TABLE emp_audit( |
| 4682 |
operation char(1) NOT NULL, |
| 4683 |
stamp timestamp NOT NULL, |
| 4684 |
userid text NOT NULL, |
| 4685 |
empname text NOT NULL, |
| 4686 |
salary integer |
| 4687 |
); |
| 4688 |
|
| 4689 |
CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$ |
| 4690 |
BEGIN |
| 4691 |
-- |
| 4692 |
-- Create rows in emp_audit to reflect the operations performed on emp, |
| 4693 |
-- making use of the special variable TG_OP to work out the operation. |
| 4694 |
-- |
| 4695 |
IF (TG_OP = 'DELETE') THEN |
| 4696 |
INSERT INTO emp_audit |
| 4697 |
SELECT 'D', now(), current_user, o.* FROM old_table o; |
| 4698 |
ELSIF (TG_OP = 'UPDATE') THEN |
| 4699 |
INSERT INTO emp_audit |
| 4700 |
SELECT 'U', now(), current_user, n.* FROM new_table n; |
| 4701 |
ELSIF (TG_OP = 'INSERT') THEN |
| 4702 |
INSERT INTO emp_audit |
| 4703 |
SELECT 'I', now(), current_user, n.* FROM new_table n; |
| 4704 |
END IF; |
| 4705 |
RETURN NULL; -- result is ignored since this is an AFTER trigger |
| 4706 |
END; |
| 4707 |
$emp_audit$ LANGUAGE plpgsql; |
| 4708 |
|
| 4709 |
CREATE TRIGGER emp_audit_ins |
| 4710 |
AFTER INSERT ON emp |
| 4711 |
REFERENCING NEW TABLE AS new_table |
| 4712 |
FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit(); |
| 4713 |
CREATE TRIGGER emp_audit_upd |
| 4714 |
AFTER UPDATE ON emp |
| 4715 |
REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table |
| 4716 |
FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit(); |
| 4717 |
CREATE TRIGGER emp_audit_del |
| 4718 |
AFTER DELETE ON emp |
| 4719 |
REFERENCING OLD TABLE AS old_table |
| 4720 |
FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit(); |
| 4721 |
</programlisting> |
| 4722 |
</example> |
| 4723 |
|
| 4724 |
</sect2> |
| 4725 |
|
| 4726 |
<sect2 id="plpgsql-event-trigger"> |
| 4727 |
<title>Triggers on Events</title> |
| 4728 |
|
| 4729 |
<para> |
| 4730 |
<application>PL/pgSQL</application> can be used to define |
| 4731 |
<link linkend="event-triggers">event triggers</link>. |
| 4732 |
<productname>PostgreSQL</productname> requires that a function that |
| 4733 |
is to be called as an event trigger must be declared as a function with |
| 4734 |
no arguments and a return type of <literal>event_trigger</literal>. |
| 4735 |
</para> |
| 4736 |
|
| 4737 |
<para> |
| 4738 |
When a <application>PL/pgSQL</application> function is called as an |
| 4739 |
event trigger, several special variables are created automatically |
| 4740 |
in the top-level block. They are: |
| 4741 |
|
| 4742 |
<variablelist> |
| 4743 |
<varlistentry id="plpgsql-event-trigger-tg-event"> |
| 4744 |
<term><varname>TG_EVENT</varname> <type>text</type></term> |
| 4745 |
<listitem> |
| 4746 |
<para> |
| 4747 |
event the trigger is fired for. |
| 4748 |
</para> |
| 4749 |
</listitem> |
| 4750 |
</varlistentry> |
| 4751 |
|
| 4752 |
<varlistentry id="plpgsql-event-trigger-tg-tag"> |
| 4753 |
<term><varname>TG_TAG</varname> <type>text</type></term> |
| 4754 |
<listitem> |
| 4755 |
<para> |
| 4756 |
command tag for which the trigger is fired. |
| 4757 |
</para> |
| 4758 |
</listitem> |
| 4759 |
</varlistentry> |
| 4760 |
</variablelist> |
| 4761 |
</para> |
| 4762 |
|
| 4763 |
<para> |
| 4764 |
<xref linkend="plpgsql-event-trigger-example"/> shows an example of an |
| 4765 |
event trigger function in <application>PL/pgSQL</application>. |
| 4766 |
</para> |
| 4767 |
|
| 4768 |
<example id="plpgsql-event-trigger-example"> |
| 4769 |
<title>A <application>PL/pgSQL</application> Event Trigger Function</title> |
| 4770 |
|
| 4771 |
<para> |
| 4772 |
This example trigger simply raises a <literal>NOTICE</literal> message |
| 4773 |
each time a supported command is executed. |
| 4774 |
</para> |
| 4775 |
|
| 4776 |
<programlisting> |
| 4777 |
CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$ |
| 4778 |
BEGIN |
| 4779 |
RAISE NOTICE 'snitch: % %', tg_event, tg_tag; |
| 4780 |
END; |
| 4781 |
$$ LANGUAGE plpgsql; |
| 4782 |
|
| 4783 |
CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE FUNCTION snitch(); |
| 4784 |
</programlisting> |
| 4785 |
</example> |
| 4786 |
</sect2> |
| 4787 |
|
| 4788 |
</sect1> |
| 4789 |
|
| 4790 |
<sect1 id="plpgsql-implementation"> |
| 4791 |
<title><application>PL/pgSQL</application> under the Hood</title> |
| 4792 |
|
| 4793 |
<para> |
| 4794 |
This section discusses some implementation details that are |
| 4795 |
frequently important for <application>PL/pgSQL</application> users to know. |
| 4796 |
</para> |
| 4797 |
|
| 4798 |
<sect2 id="plpgsql-var-subst"> |
| 4799 |
<title>Variable Substitution</title> |
| 4800 |
|
| 4801 |
<para> |
| 4802 |
SQL statements and expressions within a <application>PL/pgSQL</application> function |
| 4803 |
can refer to variables and parameters of the function. Behind the scenes, |
| 4804 |
<application>PL/pgSQL</application> substitutes query parameters for such references. |
| 4805 |
Query parameters will only be substituted in places where they are |
| 4806 |
syntactically permissible. As an extreme case, consider |
| 4807 |
this example of poor programming style: |
| 4808 |
<programlisting> |
| 4809 |
INSERT INTO foo (foo) VALUES (foo(foo)); |
| 4810 |
</programlisting> |
| 4811 |
The first occurrence of <literal>foo</literal> must syntactically be a table |
| 4812 |
name, so it will not be substituted, even if the function has a variable |
| 4813 |
named <literal>foo</literal>. The second occurrence must be the name of a |
| 4814 |
column of that table, so it will not be substituted either. Likewise |
| 4815 |
the third occurrence must be a function name, so it also will not be |
| 4816 |
substituted for. Only the last occurrence is a candidate to be a |
| 4817 |
reference to a variable of the <application>PL/pgSQL</application> |
| 4818 |
function. |
| 4819 |
</para> |
| 4820 |
|
| 4821 |
<para> |
| 4822 |
Another way to understand this is that variable substitution can only |
| 4823 |
insert data values into an SQL command; it cannot dynamically change which |
| 4824 |
database objects are referenced by the command. (If you want to do |
| 4825 |
that, you must build a command string dynamically, as explained in |
| 4826 |
<xref linkend="plpgsql-statements-executing-dyn"/>.) |
| 4827 |
</para> |
| 4828 |
|
| 4829 |
<para> |
| 4830 |
Since the names of variables are syntactically no different from the names |
| 4831 |
of table columns, there can be ambiguity in statements that also refer to |
| 4832 |
tables: is a given name meant to refer to a table column, or a variable? |
| 4833 |
Let's change the previous example to |
| 4834 |
<programlisting> |
| 4835 |
INSERT INTO dest (col) SELECT foo + bar FROM src; |
| 4836 |
</programlisting> |
| 4837 |
Here, <literal>dest</literal> and <literal>src</literal> must be table names, and |
| 4838 |
<literal>col</literal> must be a column of <literal>dest</literal>, but <literal>foo</literal> |
| 4839 |
and <literal>bar</literal> might reasonably be either variables of the function |
| 4840 |
or columns of <literal>src</literal>. |
| 4841 |
</para> |
| 4842 |
|
| 4843 |
<para> |
| 4844 |
By default, <application>PL/pgSQL</application> will report an error if a name |
| 4845 |
in an SQL statement could refer to either a variable or a table column. |
| 4846 |
You can fix such a problem by renaming the variable or column, |
| 4847 |
or by qualifying the ambiguous reference, or by telling |
| 4848 |
<application>PL/pgSQL</application> which interpretation to prefer. |
| 4849 |
</para> |
| 4850 |
|
| 4851 |
<para> |
| 4852 |
The simplest solution is to rename the variable or column. |
| 4853 |
A common coding rule is to use a |
| 4854 |
different naming convention for <application>PL/pgSQL</application> |
| 4855 |
variables than you use for column names. For example, |
| 4856 |
if you consistently name function variables |
| 4857 |
<literal>v_<replaceable>something</replaceable></literal> while none of your |
| 4858 |
column names start with <literal>v_</literal>, no conflicts will occur. |
| 4859 |
</para> |
| 4860 |
|
| 4861 |
<para> |
| 4862 |
Alternatively you can qualify ambiguous references to make them clear. |
| 4863 |
In the above example, <literal>src.foo</literal> would be an unambiguous reference |
| 4864 |
to the table column. To create an unambiguous reference to a variable, |
| 4865 |
declare it in a labeled block and use the block's label |
| 4866 |
(see <xref linkend="plpgsql-structure"/>). For example, |
| 4867 |
<programlisting> |
| 4868 |
<<block>> |
| 4869 |
DECLARE |
| 4870 |
foo int; |
| 4871 |
BEGIN |
| 4872 |
foo := ...; |
| 4873 |
INSERT INTO dest (col) SELECT block.foo + bar FROM src; |
| 4874 |
</programlisting> |
| 4875 |
Here <literal>block.foo</literal> means the variable even if there is a column |
| 4876 |
<literal>foo</literal> in <literal>src</literal>. Function parameters, as well as |
| 4877 |
special variables such as <literal>FOUND</literal>, can be qualified by the |
| 4878 |
function's name, because they are implicitly declared in an outer block |
| 4879 |
labeled with the function's name. |
| 4880 |
</para> |
| 4881 |
|
| 4882 |
<para> |
| 4883 |
Sometimes it is impractical to fix all the ambiguous references in a |
| 4884 |
large body of <application>PL/pgSQL</application> code. In such cases you can |
| 4885 |
specify that <application>PL/pgSQL</application> should resolve ambiguous references |
| 4886 |
as the variable (which is compatible with <application>PL/pgSQL</application>'s |
| 4887 |
behavior before <productname>PostgreSQL</productname> 9.0), or as the |
| 4888 |
table column (which is compatible with some other systems such as |
| 4889 |
<productname>Oracle</productname>). |
| 4890 |
</para> |
| 4891 |
|
| 4892 |
<indexterm> |
| 4893 |
<primary><varname>plpgsql.variable_conflict</varname> configuration parameter</primary> |
| 4894 |
</indexterm> |
| 4895 |
|
| 4896 |
<para> |
| 4897 |
To change this behavior on a system-wide basis, set the configuration |
| 4898 |
parameter <literal>plpgsql.variable_conflict</literal> to one of |
| 4899 |
<literal>error</literal>, <literal>use_variable</literal>, or |
| 4900 |
<literal>use_column</literal> (where <literal>error</literal> is the factory default). |
| 4901 |
This parameter affects subsequent compilations |
| 4902 |
of statements in <application>PL/pgSQL</application> functions, but not statements |
| 4903 |
already compiled in the current session. |
| 4904 |
Because changing this setting |
| 4905 |
can cause unexpected changes in the behavior of <application>PL/pgSQL</application> |
| 4906 |
functions, it can only be changed by a superuser. |
| 4907 |
</para> |
| 4908 |
|
| 4909 |
<para> |
| 4910 |
You can also set the behavior on a function-by-function basis, by |
| 4911 |
inserting one of these special commands at the start of the function |
| 4912 |
text: |
| 4913 |
<programlisting> |
| 4914 |
#variable_conflict error |
| 4915 |
#variable_conflict use_variable |
| 4916 |
#variable_conflict use_column |
| 4917 |
</programlisting> |
| 4918 |
These commands affect only the function they are written in, and override |
| 4919 |
the setting of <literal>plpgsql.variable_conflict</literal>. An example is |
| 4920 |
<programlisting> |
| 4921 |
CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$ |
| 4922 |
#variable_conflict use_variable |
| 4923 |
DECLARE |
| 4924 |
curtime timestamp := now(); |
| 4925 |
BEGIN |
| 4926 |
UPDATE users SET last_modified = curtime, comment = comment |
| 4927 |
WHERE users.id = id; |
| 4928 |
END; |
| 4929 |
$$ LANGUAGE plpgsql; |
| 4930 |
</programlisting> |
| 4931 |
In the <literal>UPDATE</literal> command, <literal>curtime</literal>, <literal>comment</literal>, |
| 4932 |
and <literal>id</literal> will refer to the function's variable and parameters |
| 4933 |
whether or not <literal>users</literal> has columns of those names. Notice |
| 4934 |
that we had to qualify the reference to <literal>users.id</literal> in the |
| 4935 |
<literal>WHERE</literal> clause to make it refer to the table column. |
| 4936 |
But we did not have to qualify the reference to <literal>comment</literal> |
| 4937 |
as a target in the <literal>UPDATE</literal> list, because syntactically |
| 4938 |
that must be a column of <literal>users</literal>. We could write the same |
| 4939 |
function without depending on the <literal>variable_conflict</literal> setting |
| 4940 |
in this way: |
| 4941 |
<programlisting> |
| 4942 |
CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$ |
| 4943 |
<<fn>> |
| 4944 |
DECLARE |
| 4945 |
curtime timestamp := now(); |
| 4946 |
BEGIN |
| 4947 |
UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment |
| 4948 |
WHERE users.id = stamp_user.id; |
| 4949 |
END; |
| 4950 |
$$ LANGUAGE plpgsql; |
| 4951 |
</programlisting> |
| 4952 |
</para> |
| 4953 |
|
| 4954 |
<para> |
| 4955 |
Variable substitution does not happen in a command string given |
| 4956 |
to <command>EXECUTE</command> or one of its variants. If you need to |
| 4957 |
insert a varying value into such a command, do so as part of |
| 4958 |
constructing the string value, or use <literal>USING</literal>, as illustrated in |
| 4959 |
<xref linkend="plpgsql-statements-executing-dyn"/>. |
| 4960 |
</para> |
| 4961 |
|
| 4962 |
<para> |
| 4963 |
Variable substitution currently works only in <command>SELECT</command>, |
| 4964 |
<command>INSERT</command>, <command>UPDATE</command>, |
| 4965 |
<command>DELETE</command>, <command>MERGE</command> and commands |
| 4966 |
containing one of these (such as <command>EXPLAIN</command> and |
| 4967 |
<command>CREATE TABLE ... AS SELECT</command>), because the main SQL |
| 4968 |
engine allows query parameters only in these commands. To use a |
| 4969 |
non-constant name or value in other statement types (generically called |
| 4970 |
utility statements), you must construct the utility statement as a string |
| 4971 |
and <command>EXECUTE</command> it. |
| 4972 |
</para> |
| 4973 |
|
| 4974 |
</sect2> |
| 4975 |
|
| 4976 |
<sect2 id="plpgsql-plan-caching"> |
| 4977 |
<title>Plan Caching</title> |
| 4978 |
|
| 4979 |
<para> |
| 4980 |
The <application>PL/pgSQL</application> interpreter parses the function's source |
| 4981 |
text and produces an internal binary instruction tree the first time the |
| 4982 |
function is called (within each session). The instruction tree |
| 4983 |
fully translates the |
| 4984 |
<application>PL/pgSQL</application> statement structure, but individual |
| 4985 |
<acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands |
| 4986 |
used in the function are not translated immediately. |
| 4987 |
</para> |
| 4988 |
|
| 4989 |
<para> |
| 4990 |
<indexterm> |
| 4991 |
<primary>preparing a query</primary> |
| 4992 |
<secondary>in PL/pgSQL</secondary> |
| 4993 |
</indexterm> |
| 4994 |
As each expression and <acronym>SQL</acronym> command is first |
| 4995 |
executed in the function, the <application>PL/pgSQL</application> interpreter |
| 4996 |
parses and analyzes the command to create a prepared statement, |
| 4997 |
using the <acronym>SPI</acronym> manager's |
| 4998 |
<function>SPI_prepare</function> function. |
| 4999 |
Subsequent visits to that expression or command |
| 5000 |
reuse the prepared statement. Thus, a function with conditional code |
| 5001 |
paths that are seldom visited will never incur the overhead of |
| 5002 |
analyzing those commands that are never executed within the current |
| 5003 |
session. A disadvantage is that errors |
| 5004 |
in a specific expression or command cannot be detected until that |
| 5005 |
part of the function is reached in execution. (Trivial syntax |
| 5006 |
errors will be detected during the initial parsing pass, but |
| 5007 |
anything deeper will not be detected until execution.) |
| 5008 |
</para> |
| 5009 |
|
| 5010 |
<para> |
| 5011 |
<application>PL/pgSQL</application> (or more precisely, the SPI manager) can |
| 5012 |
furthermore attempt to cache the execution plan associated with any |
| 5013 |
particular prepared statement. If a cached plan is not used, then |
| 5014 |
a fresh execution plan is generated on each visit to the statement, |
| 5015 |
and the current parameter values (that is, <application>PL/pgSQL</application> |
| 5016 |
variable values) can be used to optimize the selected plan. If the |
| 5017 |
statement has no parameters, or is executed many times, the SPI manager |
| 5018 |
will consider creating a <firstterm>generic</firstterm> plan that is not dependent |
| 5019 |
on specific parameter values, and caching that for re-use. Typically |
| 5020 |
this will happen only if the execution plan is not very sensitive to |
| 5021 |
the values of the <application>PL/pgSQL</application> variables referenced in it. |
| 5022 |
If it is, generating a plan each time is a net win. See <xref |
| 5023 |
linkend="sql-prepare"/> for more information about the behavior of |
| 5024 |
prepared statements. |
| 5025 |
</para> |
| 5026 |
|
| 5027 |
<para> |
| 5028 |
Because <application>PL/pgSQL</application> saves prepared statements |
| 5029 |
and sometimes execution plans in this way, |
| 5030 |
SQL commands that appear directly in a |
| 5031 |
<application>PL/pgSQL</application> function must refer to the |
| 5032 |
same tables and columns on every execution; that is, you cannot use |
| 5033 |
a parameter as the name of a table or column in an SQL command. To get |
| 5034 |
around this restriction, you can construct dynamic commands using |
| 5035 |
the <application>PL/pgSQL</application> <command>EXECUTE</command> |
| 5036 |
statement — at the price of performing new parse analysis and |
| 5037 |
constructing a new execution plan on every execution. |
| 5038 |
</para> |
| 5039 |
|
| 5040 |
<para> |
| 5041 |
The mutable nature of record variables presents another problem in this |
| 5042 |
connection. When fields of a record variable are used in |
| 5043 |
expressions or statements, the data types of the fields must not |
| 5044 |
change from one call of the function to the next, since each |
| 5045 |
expression will be analyzed using the data type that is present |
| 5046 |
when the expression is first reached. <command>EXECUTE</command> can be |
| 5047 |
used to get around this problem when necessary. |
| 5048 |
</para> |
| 5049 |
|
| 5050 |
<para> |
| 5051 |
If the same function is used as a trigger for more than one table, |
| 5052 |
<application>PL/pgSQL</application> prepares and caches statements |
| 5053 |
independently for each such table — that is, there is a cache |
| 5054 |
for each trigger function and table combination, not just for each |
| 5055 |
function. This alleviates some of the problems with varying |
| 5056 |
data types; for instance, a trigger function will be able to work |
| 5057 |
successfully with a column named <literal>key</literal> even if it happens |
| 5058 |
to have different types in different tables. |
| 5059 |
</para> |
| 5060 |
|
| 5061 |
<para> |
| 5062 |
Likewise, functions having polymorphic argument types have a separate |
| 5063 |
statement cache for each combination of actual argument types they have |
| 5064 |
been invoked for, so that data type differences do not cause unexpected |
| 5065 |
failures. |
| 5066 |
</para> |
| 5067 |
|
| 5068 |
<para> |
| 5069 |
Statement caching can sometimes have surprising effects on the |
| 5070 |
interpretation of time-sensitive values. For example there |
| 5071 |
is a difference between what these two functions do: |
| 5072 |
|
| 5073 |
<programlisting> |
| 5074 |
CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$ |
| 5075 |
BEGIN |
| 5076 |
INSERT INTO logtable VALUES (logtxt, 'now'); |
| 5077 |
END; |
| 5078 |
$$ LANGUAGE plpgsql; |
| 5079 |
</programlisting> |
| 5080 |
|
| 5081 |
and: |
| 5082 |
|
| 5083 |
<programlisting> |
| 5084 |
CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$ |
| 5085 |
DECLARE |
| 5086 |
curtime timestamp; |
| 5087 |
BEGIN |
| 5088 |
curtime := 'now'; |
| 5089 |
INSERT INTO logtable VALUES (logtxt, curtime); |
| 5090 |
END; |
| 5091 |
$$ LANGUAGE plpgsql; |
| 5092 |
</programlisting> |
| 5093 |
</para> |
| 5094 |
|
| 5095 |
<para> |
| 5096 |
In the case of <function>logfunc1</function>, the |
| 5097 |
<productname>PostgreSQL</productname> main parser knows when |
| 5098 |
analyzing the <command>INSERT</command> that the |
| 5099 |
string <literal>'now'</literal> should be interpreted as |
| 5100 |
<type>timestamp</type>, because the target column of |
| 5101 |
<classname>logtable</classname> is of that type. Thus, |
| 5102 |
<literal>'now'</literal> will be converted to a <type>timestamp</type> |
| 5103 |
constant when the |
| 5104 |
<command>INSERT</command> is analyzed, and then used in all |
| 5105 |
invocations of <function>logfunc1</function> during the lifetime |
| 5106 |
of the session. Needless to say, this isn't what the programmer |
| 5107 |
wanted. A better idea is to use the <literal>now()</literal> or |
| 5108 |
<literal>current_timestamp</literal> function. |
| 5109 |
</para> |
| 5110 |
|
| 5111 |
<para> |
| 5112 |
In the case of <function>logfunc2</function>, the |
| 5113 |
<productname>PostgreSQL</productname> main parser does not know |
| 5114 |
what type <literal>'now'</literal> should become and therefore |
| 5115 |
it returns a data value of type <type>text</type> containing the string |
| 5116 |
<literal>now</literal>. During the ensuing assignment |
| 5117 |
to the local variable <varname>curtime</varname>, the |
| 5118 |
<application>PL/pgSQL</application> interpreter casts this |
| 5119 |
string to the <type>timestamp</type> type by calling the |
| 5120 |
<function>textout</function> and <function>timestamp_in</function> |
| 5121 |
functions for the conversion. So, the computed time stamp is updated |
| 5122 |
on each execution as the programmer expects. Even though this |
| 5123 |
happens to work as expected, it's not terribly efficient, so |
| 5124 |
use of the <literal>now()</literal> function would still be a better idea. |
| 5125 |
</para> |
| 5126 |
|
| 5127 |
</sect2> |
| 5128 |
|
| 5129 |
</sect1> |
| 5130 |
|
| 5131 |
<sect1 id="plpgsql-development-tips"> |
| 5132 |
<title>Tips for Developing in <application>PL/pgSQL</application></title> |
| 5133 |
|
| 5134 |
<para> |
| 5135 |
One good way to develop in |
| 5136 |
<application>PL/pgSQL</application> is to use the text editor of your |
| 5137 |
choice to create your functions, and in another window, use |
| 5138 |
<application>psql</application> to load and test those functions. |
| 5139 |
If you are doing it this way, it |
| 5140 |
is a good idea to write the function using <command>CREATE OR |
| 5141 |
REPLACE FUNCTION</command>. That way you can just reload the file to update |
| 5142 |
the function definition. For example: |
| 5143 |
<programlisting> |
| 5144 |
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$ |
| 5145 |
.... |
| 5146 |
$$ LANGUAGE plpgsql; |
| 5147 |
</programlisting> |
| 5148 |
</para> |
| 5149 |
|
| 5150 |
<para> |
| 5151 |
While running <application>psql</application>, you can load or reload such |
| 5152 |
a function definition file with: |
| 5153 |
<programlisting> |
| 5154 |
\i filename.sql |
| 5155 |
</programlisting> |
| 5156 |
and then immediately issue SQL commands to test the function. |
| 5157 |
</para> |
| 5158 |
|
| 5159 |
<para> |
| 5160 |
Another good way to develop in <application>PL/pgSQL</application> is with a |
| 5161 |
GUI database access tool that facilitates development in a |
| 5162 |
procedural language. One example of such a tool is |
| 5163 |
<application>pgAdmin</application>, although others exist. These tools often |
| 5164 |
provide convenient features such as escaping single quotes and |
| 5165 |
making it easier to recreate and debug functions. |
| 5166 |
</para> |
| 5167 |
|
| 5168 |
<sect2 id="plpgsql-quote-tips"> |
| 5169 |
<title>Handling of Quotation Marks</title> |
| 5170 |
|
| 5171 |
<para> |
| 5172 |
The code of a <application>PL/pgSQL</application> function is specified in |
| 5173 |
<command>CREATE FUNCTION</command> as a string literal. If you |
| 5174 |
write the string literal in the ordinary way with surrounding |
| 5175 |
single quotes, then any single quotes inside the function body |
| 5176 |
must be doubled; likewise any backslashes must be doubled (assuming |
| 5177 |
escape string syntax is used). |
| 5178 |
Doubling quotes is at best tedious, and in more complicated cases |
| 5179 |
the code can become downright incomprehensible, because you can |
| 5180 |
easily find yourself needing half a dozen or more adjacent quote marks. |
| 5181 |
It's recommended that you instead write the function body as a |
| 5182 |
<quote>dollar-quoted</quote> string literal (see <xref |
| 5183 |
linkend="sql-syntax-dollar-quoting"/>). In the dollar-quoting |
| 5184 |
approach, you never double any quote marks, but instead take care to |
| 5185 |
choose a different dollar-quoting delimiter for each level of |
| 5186 |
nesting you need. For example, you might write the <command>CREATE |
| 5187 |
FUNCTION</command> command as: |
| 5188 |
<programlisting> |
| 5189 |
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$ |
| 5190 |
.... |
| 5191 |
$PROC$ LANGUAGE plpgsql; |
| 5192 |
</programlisting> |
| 5193 |
Within this, you might use quote marks for simple literal strings in |
| 5194 |
SQL commands and <literal>$$</literal> to delimit fragments of SQL commands |
| 5195 |
that you are assembling as strings. If you need to quote text that |
| 5196 |
includes <literal>$$</literal>, you could use <literal>$Q$</literal>, and so on. |
| 5197 |
</para> |
| 5198 |
|
| 5199 |
<para> |
| 5200 |
The following chart shows what you have to do when writing quote |
| 5201 |
marks without dollar quoting. It might be useful when translating |
| 5202 |
pre-dollar quoting code into something more comprehensible. |
| 5203 |
</para> |
| 5204 |
|
| 5205 |
<variablelist> |
| 5206 |
<varlistentry id="plpgsql-quote-tips-1-quot"> |
| 5207 |
<term>1 quotation mark</term> |
| 5208 |
<listitem> |
| 5209 |
<para> |
| 5210 |
To begin and end the function body, for example: |
| 5211 |
<programlisting> |
| 5212 |
CREATE FUNCTION foo() RETURNS integer AS ' |
| 5213 |
.... |
| 5214 |
' LANGUAGE plpgsql; |
| 5215 |
</programlisting> |
| 5216 |
Anywhere within a single-quoted function body, quote marks |
| 5217 |
<emphasis>must</emphasis> appear in pairs. |
| 5218 |
</para> |
| 5219 |
</listitem> |
| 5220 |
</varlistentry> |
| 5221 |
|
| 5222 |
<varlistentry id="plpgsql-quote-tips-2-quot"> |
| 5223 |
<term>2 quotation marks</term> |
| 5224 |
<listitem> |
| 5225 |
<para> |
| 5226 |
For string literals inside the function body, for example: |
| 5227 |
<programlisting> |
| 5228 |
a_output := ''Blah''; |
| 5229 |
SELECT * FROM users WHERE f_name=''foobar''; |
| 5230 |
</programlisting> |
| 5231 |
In the dollar-quoting approach, you'd just write: |
| 5232 |
<programlisting> |
| 5233 |
a_output := 'Blah'; |
| 5234 |
SELECT * FROM users WHERE f_name='foobar'; |
| 5235 |
</programlisting> |
| 5236 |
which is exactly what the <application>PL/pgSQL</application> parser would see |
| 5237 |
in either case. |
| 5238 |
</para> |
| 5239 |
</listitem> |
| 5240 |
</varlistentry> |
| 5241 |
|
| 5242 |
<varlistentry id="plpgsql-quote-tips-4-quot"> |
| 5243 |
<term>4 quotation marks</term> |
| 5244 |
<listitem> |
| 5245 |
<para> |
| 5246 |
When you need a single quotation mark in a string constant inside the |
| 5247 |
function body, for example: |
| 5248 |
<programlisting> |
| 5249 |
a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz'' |
| 5250 |
</programlisting> |
| 5251 |
The value actually appended to <literal>a_output</literal> would be: |
| 5252 |
<literal> AND name LIKE 'foobar' AND xyz</literal>. |
| 5253 |
</para> |
| 5254 |
<para> |
| 5255 |
In the dollar-quoting approach, you'd write: |
| 5256 |
<programlisting> |
| 5257 |
a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$ |
| 5258 |
</programlisting> |
| 5259 |
being careful that any dollar-quote delimiters around this are not |
| 5260 |
just <literal>$$</literal>. |
| 5261 |
</para> |
| 5262 |
</listitem> |
| 5263 |
</varlistentry> |
| 5264 |
|
| 5265 |
<varlistentry id="plpgsql-quote-tips-6-quot"> |
| 5266 |
<term>6 quotation marks</term> |
| 5267 |
<listitem> |
| 5268 |
<para> |
| 5269 |
When a single quotation mark in a string inside the function body is |
| 5270 |
adjacent to the end of that string constant, for example: |
| 5271 |
<programlisting> |
| 5272 |
a_output := a_output || '' AND name LIKE ''''foobar'''''' |
| 5273 |
</programlisting> |
| 5274 |
The value appended to <literal>a_output</literal> would then be: |
| 5275 |
<literal> AND name LIKE 'foobar'</literal>. |
| 5276 |
</para> |
| 5277 |
<para> |
| 5278 |
In the dollar-quoting approach, this becomes: |
| 5279 |
<programlisting> |
| 5280 |
a_output := a_output || $$ AND name LIKE 'foobar'$$ |
| 5281 |
</programlisting> |
| 5282 |
</para> |
| 5283 |
</listitem> |
| 5284 |
</varlistentry> |
| 5285 |
|
| 5286 |
<varlistentry id="plpgsql-quote-tips-10-quot"> |
| 5287 |
<term>10 quotation marks</term> |
| 5288 |
<listitem> |
| 5289 |
<para> |
| 5290 |
When you want two single quotation marks in a string constant (which |
| 5291 |
accounts for 8 quotation marks) and this is adjacent to the end of that |
| 5292 |
string constant (2 more). You will probably only need that if |
| 5293 |
you are writing a function that generates other functions, as in |
| 5294 |
<xref linkend="plpgsql-porting-ex2"/>. |
| 5295 |
For example: |
| 5296 |
<programlisting> |
| 5297 |
a_output := a_output || '' if v_'' || |
| 5298 |
referrer_keys.kind || '' like '''''''''' |
| 5299 |
|| referrer_keys.key_string || '''''''''' |
| 5300 |
then return '''''' || referrer_keys.referrer_type |
| 5301 |
|| ''''''; end if;''; |
| 5302 |
</programlisting> |
| 5303 |
The value of <literal>a_output</literal> would then be: |
| 5304 |
<programlisting> |
| 5305 |
if v_... like ''...'' then return ''...''; end if; |
| 5306 |
</programlisting> |
| 5307 |
</para> |
| 5308 |
<para> |
| 5309 |
In the dollar-quoting approach, this becomes: |
| 5310 |
<programlisting> |
| 5311 |
a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$ |
| 5312 |
|| referrer_keys.key_string || $$' |
| 5313 |
then return '$$ || referrer_keys.referrer_type |
| 5314 |
|| $$'; end if;$$; |
| 5315 |
</programlisting> |
| 5316 |
where we assume we only need to put single quote marks into |
| 5317 |
<literal>a_output</literal>, because it will be re-quoted before use. |
| 5318 |
</para> |
| 5319 |
</listitem> |
| 5320 |
</varlistentry> |
| 5321 |
</variablelist> |
| 5322 |
|
| 5323 |
</sect2> |
| 5324 |
<sect2 id="plpgsql-extra-checks"> |
| 5325 |
<title>Additional Compile-Time and Run-Time Checks</title> |
| 5326 |
|
| 5327 |
<para> |
| 5328 |
To aid the user in finding instances of simple but common problems before |
| 5329 |
they cause harm, <application>PL/pgSQL</application> provides additional |
| 5330 |
<replaceable>checks</replaceable>. When enabled, depending on the configuration, they |
| 5331 |
can be used to emit either a <literal>WARNING</literal> or an <literal>ERROR</literal> |
| 5332 |
during the compilation of a function. A function which has received |
| 5333 |
a <literal>WARNING</literal> can be executed without producing further messages, |
| 5334 |
so you are advised to test in a separate development environment. |
| 5335 |
</para> |
| 5336 |
|
| 5337 |
<para> |
| 5338 |
Setting <varname>plpgsql.extra_warnings</varname>, or |
| 5339 |
<varname>plpgsql.extra_errors</varname>, as appropriate, to <literal>"all"</literal> |
| 5340 |
is encouraged in development and/or testing environments. |
| 5341 |
</para> |
| 5342 |
|
| 5343 |
<para> |
| 5344 |
These additional checks are enabled through the configuration variables |
| 5345 |
<varname>plpgsql.extra_warnings</varname> for warnings and |
| 5346 |
<varname>plpgsql.extra_errors</varname> for errors. Both can be set either to |
| 5347 |
a comma-separated list of checks, <literal>"none"</literal> or |
| 5348 |
<literal>"all"</literal>. The default is <literal>"none"</literal>. Currently |
| 5349 |
the list of available checks includes: |
| 5350 |
<variablelist> |
| 5351 |
<varlistentry id="plpgsql-extra-checks-shadowed-variables"> |
| 5352 |
<term><varname>shadowed_variables</varname></term> |
| 5353 |
<listitem> |
| 5354 |
<para> |
| 5355 |
Checks if a declaration shadows a previously defined variable. |
| 5356 |
</para> |
| 5357 |
</listitem> |
| 5358 |
</varlistentry> |
| 5359 |
|
| 5360 |
<varlistentry id="plpgsql-extra-checks-strict-multi-assignment"> |
| 5361 |
<term><varname>strict_multi_assignment</varname></term> |
| 5362 |
<listitem> |
| 5363 |
<para> |
| 5364 |
Some <application>PL/pgSQL</application> commands allow assigning |
| 5365 |
values to more than one variable at a time, such as |
| 5366 |
<command>SELECT INTO</command>. Typically, the number of target |
| 5367 |
variables and the number of source variables should match, though |
| 5368 |
<application>PL/pgSQL</application> will use <literal>NULL</literal> |
| 5369 |
for missing values and extra variables are ignored. Enabling this |
| 5370 |
check will cause <application>PL/pgSQL</application> to throw a |
| 5371 |
<literal>WARNING</literal> or <literal>ERROR</literal> whenever the |
| 5372 |
number of target variables and the number of source variables are |
| 5373 |
different. |
| 5374 |
</para> |
| 5375 |
</listitem> |
| 5376 |
</varlistentry> |
| 5377 |
|
| 5378 |
<varlistentry id="plpgsql-extra-checks-too-many-rows"> |
| 5379 |
<term><varname>too_many_rows</varname></term> |
| 5380 |
<listitem> |
| 5381 |
<para> |
| 5382 |
Enabling this check will cause <application>PL/pgSQL</application> to |
| 5383 |
check if a given query returns more than one row when an |
| 5384 |
<literal>INTO</literal> clause is used. As an <literal>INTO</literal> |
| 5385 |
statement will only ever use one row, having a query return multiple |
| 5386 |
rows is generally either inefficient and/or nondeterministic and |
| 5387 |
therefore is likely an error. |
| 5388 |
</para> |
| 5389 |
</listitem> |
| 5390 |
</varlistentry> |
| 5391 |
</variablelist> |
| 5392 |
|
| 5393 |
The following example shows the effect of <varname>plpgsql.extra_warnings</varname> |
| 5394 |
set to <varname>shadowed_variables</varname>: |
| 5395 |
<programlisting> |
| 5396 |
SET plpgsql.extra_warnings TO 'shadowed_variables'; |
| 5397 |
|
| 5398 |
CREATE FUNCTION foo(f1 int) RETURNS int AS $$ |
| 5399 |
DECLARE |
| 5400 |
f1 int; |
| 5401 |
BEGIN |
| 5402 |
RETURN f1; |
| 5403 |
END; |
| 5404 |
$$ LANGUAGE plpgsql; |
| 5405 |
WARNING: variable "f1" shadows a previously defined variable |
| 5406 |
LINE 3: f1 int; |
| 5407 |
^ |
| 5408 |
CREATE FUNCTION |
| 5409 |
</programlisting> |
| 5410 |
The below example shows the effects of setting |
| 5411 |
<varname>plpgsql.extra_warnings</varname> to |
| 5412 |
<varname>strict_multi_assignment</varname>: |
| 5413 |
<programlisting> |
| 5414 |
SET plpgsql.extra_warnings TO 'strict_multi_assignment'; |
| 5415 |
|
| 5416 |
CREATE OR REPLACE FUNCTION public.foo() |
| 5417 |
RETURNS void |
| 5418 |
LANGUAGE plpgsql |
| 5419 |
AS $$ |
| 5420 |
DECLARE |
| 5421 |
x int; |
| 5422 |
y int; |
| 5423 |
BEGIN |
| 5424 |
SELECT 1 INTO x, y; |
| 5425 |
SELECT 1, 2 INTO x, y; |
| 5426 |
SELECT 1, 2, 3 INTO x, y; |
| 5427 |
END; |
| 5428 |
$$; |
| 5429 |
|
| 5430 |
SELECT foo(); |
| 5431 |
WARNING: number of source and target fields in assignment does not match |
| 5432 |
DETAIL: strict_multi_assignment check of extra_warnings is active. |
| 5433 |
HINT: Make sure the query returns the exact list of columns. |
| 5434 |
WARNING: number of source and target fields in assignment does not match |
| 5435 |
DETAIL: strict_multi_assignment check of extra_warnings is active. |
| 5436 |
HINT: Make sure the query returns the exact list of columns. |
| 5437 |
|
| 5438 |
foo |
| 5439 |
----- |
| 5440 |
|
| 5441 |
(1 row) |
| 5442 |
</programlisting> |
| 5443 |
</para> |
| 5444 |
</sect2> |
| 5445 |
</sect1> |
| 5446 |
|
| 5447 |
<!-- **** Porting from Oracle PL/SQL **** --> |
| 5448 |
|
| 5449 |
<sect1 id="plpgsql-porting"> |
| 5450 |
<title>Porting from <productname>Oracle</productname> PL/SQL</title> |
| 5451 |
|
| 5452 |
<indexterm zone="plpgsql-porting"> |
| 5453 |
<primary>Oracle</primary> |
| 5454 |
<secondary>porting from PL/SQL to PL/pgSQL</secondary> |
| 5455 |
</indexterm> |
| 5456 |
|
| 5457 |
<indexterm zone="plpgsql-porting"> |
| 5458 |
<primary>PL/SQL (Oracle)</primary> |
| 5459 |
<secondary>porting to PL/pgSQL</secondary> |
| 5460 |
</indexterm> |
| 5461 |
|
| 5462 |
<para> |
| 5463 |
This section explains differences between |
| 5464 |
<productname>PostgreSQL</productname>'s <application>PL/pgSQL</application> |
| 5465 |
language and Oracle's <application>PL/SQL</application> language, |
| 5466 |
to help developers who port applications from |
| 5467 |
<trademark class="registered">Oracle</trademark> to <productname>PostgreSQL</productname>. |
| 5468 |
</para> |
| 5469 |
|
| 5470 |
<para> |
| 5471 |
<application>PL/pgSQL</application> is similar to PL/SQL in many |
| 5472 |
aspects. It is a block-structured, imperative language, and all |
| 5473 |
variables have to be declared. Assignments, loops, and conditionals |
| 5474 |
are similar. The main differences you should keep in mind when |
| 5475 |
porting from <application>PL/SQL</application> to |
| 5476 |
<application>PL/pgSQL</application> are: |
| 5477 |
|
| 5478 |
<itemizedlist> |
| 5479 |
<listitem> |
| 5480 |
<para> |
| 5481 |
If a name used in an SQL command could be either a column name of a |
| 5482 |
table used in the command or a reference to a variable of the function, |
| 5483 |
<application>PL/SQL</application> treats it as a column name. |
| 5484 |
By default, <application>PL/pgSQL</application> will throw an error |
| 5485 |
complaining that the name is ambiguous. You can specify |
| 5486 |
<literal>plpgsql.variable_conflict</literal> = <literal>use_column</literal> |
| 5487 |
to change this behavior to match <application>PL/SQL</application>, |
| 5488 |
as explained in <xref linkend="plpgsql-var-subst"/>. |
| 5489 |
It's often best to avoid such ambiguities in the first place, |
| 5490 |
but if you have to port a large amount of code that depends on |
| 5491 |
this behavior, setting <literal>variable_conflict</literal> may be the |
| 5492 |
best solution. |
| 5493 |
</para> |
| 5494 |
</listitem> |
| 5495 |
|
| 5496 |
<listitem> |
| 5497 |
<para> |
| 5498 |
In <productname>PostgreSQL</productname> the function body must be written as |
| 5499 |
a string literal. Therefore you need to use dollar quoting or escape |
| 5500 |
single quotes in the function body. (See <xref |
| 5501 |
linkend="plpgsql-quote-tips"/>.) |
| 5502 |
</para> |
| 5503 |
</listitem> |
| 5504 |
|
| 5505 |
<listitem> |
| 5506 |
<para> |
| 5507 |
Data type names often need translation. For example, in Oracle string |
| 5508 |
values are commonly declared as being of type <type>varchar2</type>, which |
| 5509 |
is a non-SQL-standard type. In <productname>PostgreSQL</productname>, |
| 5510 |
use type <type>varchar</type> or <type>text</type> instead. Similarly, replace |
| 5511 |
type <type>number</type> with <type>numeric</type>, or use some other numeric |
| 5512 |
data type if there's a more appropriate one. |
| 5513 |
</para> |
| 5514 |
</listitem> |
| 5515 |
|
| 5516 |
<listitem> |
| 5517 |
<para> |
| 5518 |
Instead of packages, use schemas to organize your functions |
| 5519 |
into groups. |
| 5520 |
</para> |
| 5521 |
</listitem> |
| 5522 |
|
| 5523 |
<listitem> |
| 5524 |
<para> |
| 5525 |
Since there are no packages, there are no package-level variables |
| 5526 |
either. This is somewhat annoying. You can keep per-session state |
| 5527 |
in temporary tables instead. |
| 5528 |
</para> |
| 5529 |
</listitem> |
| 5530 |
|
| 5531 |
<listitem> |
| 5532 |
<para> |
| 5533 |
Integer <command>FOR</command> loops with <literal>REVERSE</literal> work |
| 5534 |
differently: <application>PL/SQL</application> counts down from the second |
| 5535 |
number to the first, while <application>PL/pgSQL</application> counts down |
| 5536 |
from the first number to the second, requiring the loop bounds |
| 5537 |
to be swapped when porting. This incompatibility is unfortunate |
| 5538 |
but is unlikely to be changed. (See <xref |
| 5539 |
linkend="plpgsql-integer-for"/>.) |
| 5540 |
</para> |
| 5541 |
</listitem> |
| 5542 |
|
| 5543 |
<listitem> |
| 5544 |
<para> |
| 5545 |
<command>FOR</command> loops over queries (other than cursors) also work |
| 5546 |
differently: the target variable(s) must have been declared, |
| 5547 |
whereas <application>PL/SQL</application> always declares them implicitly. |
| 5548 |
An advantage of this is that the variable values are still accessible |
| 5549 |
after the loop exits. |
| 5550 |
</para> |
| 5551 |
</listitem> |
| 5552 |
|
| 5553 |
<listitem> |
| 5554 |
<para> |
| 5555 |
There are various notational differences for the use of cursor |
| 5556 |
variables. |
| 5557 |
</para> |
| 5558 |
</listitem> |
| 5559 |
|
| 5560 |
</itemizedlist> |
| 5561 |
</para> |
| 5562 |
|
| 5563 |
<sect2 id="plpgsql-porting-examples"> |
| 5564 |
<title>Porting Examples</title> |
| 5565 |
|
| 5566 |
<para> |
| 5567 |
<xref linkend="pgsql-porting-ex1"/> shows how to port a simple |
| 5568 |
function from <application>PL/SQL</application> to <application>PL/pgSQL</application>. |
| 5569 |
</para> |
| 5570 |
|
| 5571 |
<example id="pgsql-porting-ex1"> |
| 5572 |
<title>Porting a Simple Function from <application>PL/SQL</application> to <application>PL/pgSQL</application></title> |
| 5573 |
|
| 5574 |
<para> |
| 5575 |
Here is an <productname>Oracle</productname> <application>PL/SQL</application> function: |
| 5576 |
<programlisting> |
| 5577 |
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar2, |
| 5578 |
v_version varchar2) |
| 5579 |
RETURN varchar2 IS |
| 5580 |
BEGIN |
| 5581 |
IF v_version IS NULL THEN |
| 5582 |
RETURN v_name; |
| 5583 |
END IF; |
| 5584 |
RETURN v_name || '/' || v_version; |
| 5585 |
END; |
| 5586 |
/ |
| 5587 |
show errors; |
| 5588 |
</programlisting> |
| 5589 |
</para> |
| 5590 |
|
| 5591 |
<para> |
| 5592 |
Let's go through this function and see the differences compared to |
| 5593 |
<application>PL/pgSQL</application>: |
| 5594 |
|
| 5595 |
<itemizedlist> |
| 5596 |
<listitem> |
| 5597 |
<para> |
| 5598 |
The type name <type>varchar2</type> has to be changed to <type>varchar</type> |
| 5599 |
or <type>text</type>. In the examples in this section, we'll |
| 5600 |
use <type>varchar</type>, but <type>text</type> is often a better choice if |
| 5601 |
you do not need specific string length limits. |
| 5602 |
</para> |
| 5603 |
</listitem> |
| 5604 |
|
| 5605 |
<listitem> |
| 5606 |
<para> |
| 5607 |
The <literal>RETURN</literal> key word in the function |
| 5608 |
prototype (not the function body) becomes |
| 5609 |
<literal>RETURNS</literal> in |
| 5610 |
<productname>PostgreSQL</productname>. |
| 5611 |
Also, <literal>IS</literal> becomes <literal>AS</literal>, and you need to |
| 5612 |
add a <literal>LANGUAGE</literal> clause because <application>PL/pgSQL</application> |
| 5613 |
is not the only possible function language. |
| 5614 |
</para> |
| 5615 |
</listitem> |
| 5616 |
|
| 5617 |
<listitem> |
| 5618 |
<para> |
| 5619 |
In <productname>PostgreSQL</productname>, the function body is considered |
| 5620 |
to be a string literal, so you need to use quote marks or dollar |
| 5621 |
quotes around it. This substitutes for the terminating <literal>/</literal> |
| 5622 |
in the Oracle approach. |
| 5623 |
</para> |
| 5624 |
</listitem> |
| 5625 |
|
| 5626 |
<listitem> |
| 5627 |
<para> |
| 5628 |
The <literal>show errors</literal> command does not exist in |
| 5629 |
<productname>PostgreSQL</productname>, and is not needed since errors are |
| 5630 |
reported automatically. |
| 5631 |
</para> |
| 5632 |
</listitem> |
| 5633 |
</itemizedlist> |
| 5634 |
</para> |
| 5635 |
|
| 5636 |
<para> |
| 5637 |
This is how this function would look when ported to |
| 5638 |
<productname>PostgreSQL</productname>: |
| 5639 |
|
| 5640 |
<programlisting> |
| 5641 |
CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar, |
| 5642 |
v_version varchar) |
| 5643 |
RETURNS varchar AS $$ |
| 5644 |
BEGIN |
| 5645 |
IF v_version IS NULL THEN |
| 5646 |
RETURN v_name; |
| 5647 |
END IF; |
| 5648 |
RETURN v_name || '/' || v_version; |
| 5649 |
END; |
| 5650 |
$$ LANGUAGE plpgsql; |
| 5651 |
</programlisting> |
| 5652 |
</para> |
| 5653 |
</example> |
| 5654 |
|
| 5655 |
<para> |
| 5656 |
<xref linkend="plpgsql-porting-ex2"/> shows how to port a |
| 5657 |
function that creates another function and how to handle the |
| 5658 |
ensuing quoting problems. |
| 5659 |
</para> |
| 5660 |
|
| 5661 |
<example id="plpgsql-porting-ex2"> |
| 5662 |
<title>Porting a Function that Creates Another Function from <application>PL/SQL</application> to <application>PL/pgSQL</application></title> |
| 5663 |
|
| 5664 |
<para> |
| 5665 |
The following procedure grabs rows from a |
| 5666 |
<command>SELECT</command> statement and builds a large function |
| 5667 |
with the results in <literal>IF</literal> statements, for the |
| 5668 |
sake of efficiency. |
| 5669 |
</para> |
| 5670 |
|
| 5671 |
<para> |
| 5672 |
This is the Oracle version: |
| 5673 |
<programlisting> |
| 5674 |
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS |
| 5675 |
CURSOR referrer_keys IS |
| 5676 |
SELECT * FROM cs_referrer_keys |
| 5677 |
ORDER BY try_order; |
| 5678 |
func_cmd VARCHAR(4000); |
| 5679 |
BEGIN |
| 5680 |
func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR2, |
| 5681 |
v_domain IN VARCHAR2, v_url IN VARCHAR2) RETURN VARCHAR2 IS BEGIN'; |
| 5682 |
|
| 5683 |
FOR referrer_key IN referrer_keys LOOP |
| 5684 |
func_cmd := func_cmd || |
| 5685 |
' IF v_' || referrer_key.kind |
| 5686 |
|| ' LIKE ''' || referrer_key.key_string |
| 5687 |
|| ''' THEN RETURN ''' || referrer_key.referrer_type |
| 5688 |
|| '''; END IF;'; |
| 5689 |
END LOOP; |
| 5690 |
|
| 5691 |
func_cmd := func_cmd || ' RETURN NULL; END;'; |
| 5692 |
|
| 5693 |
EXECUTE IMMEDIATE func_cmd; |
| 5694 |
END; |
| 5695 |
/ |
| 5696 |
show errors; |
| 5697 |
</programlisting> |
| 5698 |
</para> |
| 5699 |
|
| 5700 |
<para> |
| 5701 |
Here is how this function would end up in <productname>PostgreSQL</productname>: |
| 5702 |
<programlisting> |
| 5703 |
CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$ |
| 5704 |
DECLARE |
| 5705 |
referrer_keys CURSOR IS |
| 5706 |
SELECT * FROM cs_referrer_keys |
| 5707 |
ORDER BY try_order; |
| 5708 |
func_body text; |
| 5709 |
func_cmd text; |
| 5710 |
BEGIN |
| 5711 |
func_body := 'BEGIN'; |
| 5712 |
|
| 5713 |
FOR referrer_key IN referrer_keys LOOP |
| 5714 |
func_body := func_body || |
| 5715 |
' IF v_' || referrer_key.kind |
| 5716 |
|| ' LIKE ' || quote_literal(referrer_key.key_string) |
| 5717 |
|| ' THEN RETURN ' || quote_literal(referrer_key.referrer_type) |
| 5718 |
|| '; END IF;' ; |
| 5719 |
END LOOP; |
| 5720 |
|
| 5721 |
func_body := func_body || ' RETURN NULL; END;'; |
| 5722 |
|
| 5723 |
func_cmd := |
| 5724 |
'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar, |
| 5725 |
v_domain varchar, |
| 5726 |
v_url varchar) |
| 5727 |
RETURNS varchar AS ' |
| 5728 |
|| quote_literal(func_body) |
| 5729 |
|| ' LANGUAGE plpgsql;' ; |
| 5730 |
|
| 5731 |
EXECUTE func_cmd; |
| 5732 |
END; |
| 5733 |
$func$ LANGUAGE plpgsql; |
| 5734 |
</programlisting> |
| 5735 |
Notice how the body of the function is built separately and passed |
| 5736 |
through <literal>quote_literal</literal> to double any quote marks in it. This |
| 5737 |
technique is needed because we cannot safely use dollar quoting for |
| 5738 |
defining the new function: we do not know for sure what strings will |
| 5739 |
be interpolated from the <structfield>referrer_key.key_string</structfield> field. |
| 5740 |
(We are assuming here that <structfield>referrer_key.kind</structfield> can be |
| 5741 |
trusted to always be <literal>host</literal>, <literal>domain</literal>, or |
| 5742 |
<literal>url</literal>, but <structfield>referrer_key.key_string</structfield> might be |
| 5743 |
anything, in particular it might contain dollar signs.) This function |
| 5744 |
is actually an improvement on the Oracle original, because it will |
| 5745 |
not generate broken code when <structfield>referrer_key.key_string</structfield> or |
| 5746 |
<structfield>referrer_key.referrer_type</structfield> contain quote marks. |
| 5747 |
</para> |
| 5748 |
</example> |
| 5749 |
|
| 5750 |
<para> |
| 5751 |
<xref linkend="plpgsql-porting-ex3"/> shows how to port a function |
| 5752 |
with <literal>OUT</literal> parameters and string manipulation. |
| 5753 |
<productname>PostgreSQL</productname> does not have a built-in |
| 5754 |
<function>instr</function> function, but you can create one |
| 5755 |
using a combination of other |
| 5756 |
functions. In <xref linkend="plpgsql-porting-appendix"/> there is a |
| 5757 |
<application>PL/pgSQL</application> implementation of |
| 5758 |
<function>instr</function> that you can use to make your porting |
| 5759 |
easier. |
| 5760 |
</para> |
| 5761 |
|
| 5762 |
<example id="plpgsql-porting-ex3"> |
| 5763 |
<title>Porting a Procedure With String Manipulation and |
| 5764 |
<literal>OUT</literal> Parameters from <application>PL/SQL</application> to |
| 5765 |
<application>PL/pgSQL</application></title> |
| 5766 |
|
| 5767 |
<para> |
| 5768 |
The following <productname>Oracle</productname> PL/SQL procedure is used |
| 5769 |
to parse a URL and return several elements (host, path, and query). |
| 5770 |
</para> |
| 5771 |
|
| 5772 |
<para> |
| 5773 |
This is the Oracle version: |
| 5774 |
<programlisting> |
| 5775 |
CREATE OR REPLACE PROCEDURE cs_parse_url( |
| 5776 |
v_url IN VARCHAR2, |
| 5777 |
v_host OUT VARCHAR2, -- This will be passed back |
| 5778 |
v_path OUT VARCHAR2, -- This one too |
| 5779 |
v_query OUT VARCHAR2) -- And this one |
| 5780 |
IS |
| 5781 |
a_pos1 INTEGER; |
| 5782 |
a_pos2 INTEGER; |
| 5783 |
BEGIN |
| 5784 |
v_host := NULL; |
| 5785 |
v_path := NULL; |
| 5786 |
v_query := NULL; |
| 5787 |
a_pos1 := instr(v_url, '//'); |
| 5788 |
|
| 5789 |
IF a_pos1 = 0 THEN |
| 5790 |
RETURN; |
| 5791 |
END IF; |
| 5792 |
a_pos2 := instr(v_url, '/', a_pos1 + 2); |
| 5793 |
IF a_pos2 = 0 THEN |
| 5794 |
v_host := substr(v_url, a_pos1 + 2); |
| 5795 |
v_path := '/'; |
| 5796 |
RETURN; |
| 5797 |
END IF; |
| 5798 |
|
| 5799 |
v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2); |
| 5800 |
a_pos1 := instr(v_url, '?', a_pos2 + 1); |
| 5801 |
|
| 5802 |
IF a_pos1 = 0 THEN |
| 5803 |
v_path := substr(v_url, a_pos2); |
| 5804 |
RETURN; |
| 5805 |
END IF; |
| 5806 |
|
| 5807 |
v_path := substr(v_url, a_pos2, a_pos1 - a_pos2); |
| 5808 |
v_query := substr(v_url, a_pos1 + 1); |
| 5809 |
END; |
| 5810 |
/ |
| 5811 |
show errors; |
| 5812 |
</programlisting> |
| 5813 |
</para> |
| 5814 |
|
| 5815 |
<para> |
| 5816 |
Here is a possible translation into <application>PL/pgSQL</application>: |
| 5817 |
<programlisting> |
| 5818 |
CREATE OR REPLACE FUNCTION cs_parse_url( |
| 5819 |
v_url IN VARCHAR, |
| 5820 |
v_host OUT VARCHAR, -- This will be passed back |
| 5821 |
v_path OUT VARCHAR, -- This one too |
| 5822 |
v_query OUT VARCHAR) -- And this one |
| 5823 |
AS $$ |
| 5824 |
DECLARE |
| 5825 |
a_pos1 INTEGER; |
| 5826 |
a_pos2 INTEGER; |
| 5827 |
BEGIN |
| 5828 |
v_host := NULL; |
| 5829 |
v_path := NULL; |
| 5830 |
v_query := NULL; |
| 5831 |
a_pos1 := instr(v_url, '//'); |
| 5832 |
|
| 5833 |
IF a_pos1 = 0 THEN |
| 5834 |
RETURN; |
| 5835 |
END IF; |
| 5836 |
a_pos2 := instr(v_url, '/', a_pos1 + 2); |
| 5837 |
IF a_pos2 = 0 THEN |
| 5838 |
v_host := substr(v_url, a_pos1 + 2); |
| 5839 |
v_path := '/'; |
| 5840 |
RETURN; |
| 5841 |
END IF; |
| 5842 |
|
| 5843 |
v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2); |
| 5844 |
a_pos1 := instr(v_url, '?', a_pos2 + 1); |
| 5845 |
|
| 5846 |
IF a_pos1 = 0 THEN |
| 5847 |
v_path := substr(v_url, a_pos2); |
| 5848 |
RETURN; |
| 5849 |
END IF; |
| 5850 |
|
| 5851 |
v_path := substr(v_url, a_pos2, a_pos1 - a_pos2); |
| 5852 |
v_query := substr(v_url, a_pos1 + 1); |
| 5853 |
END; |
| 5854 |
$$ LANGUAGE plpgsql; |
| 5855 |
</programlisting> |
| 5856 |
|
| 5857 |
This function could be used like this: |
| 5858 |
<programlisting> |
| 5859 |
SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz'); |
| 5860 |
</programlisting> |
| 5861 |
</para> |
| 5862 |
</example> |
| 5863 |
|
| 5864 |
<para> |
| 5865 |
<xref linkend="plpgsql-porting-ex4"/> shows how to port a procedure |
| 5866 |
that uses numerous features that are specific to Oracle. |
| 5867 |
</para> |
| 5868 |
|
| 5869 |
<example id="plpgsql-porting-ex4"> |
| 5870 |
<title>Porting a Procedure from <application>PL/SQL</application> to <application>PL/pgSQL</application></title> |
| 5871 |
|
| 5872 |
<para> |
| 5873 |
The Oracle version: |
| 5874 |
|
| 5875 |
<programlisting> |
| 5876 |
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS |
| 5877 |
a_running_job_count INTEGER; |
| 5878 |
BEGIN |
| 5879 |
LOCK TABLE cs_jobs IN EXCLUSIVE MODE; |
| 5880 |
|
| 5881 |
SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL; |
| 5882 |
|
| 5883 |
IF a_running_job_count > 0 THEN |
| 5884 |
COMMIT; -- free lock |
| 5885 |
raise_application_error(-20000, |
| 5886 |
'Unable to create a new job: a job is currently running.'); |
| 5887 |
END IF; |
| 5888 |
|
| 5889 |
DELETE FROM cs_active_job; |
| 5890 |
INSERT INTO cs_active_job(job_id) VALUES (v_job_id); |
| 5891 |
|
| 5892 |
BEGIN |
| 5893 |
INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now()); |
| 5894 |
EXCEPTION |
| 5895 |
WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists |
| 5896 |
END; |
| 5897 |
COMMIT; |
| 5898 |
END; |
| 5899 |
/ |
| 5900 |
show errors |
| 5901 |
</programlisting> |
| 5902 |
</para> |
| 5903 |
|
| 5904 |
<para> |
| 5905 |
This is how we could port this procedure to <application>PL/pgSQL</application>: |
| 5906 |
|
| 5907 |
<programlisting> |
| 5908 |
CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id integer) AS $$ |
| 5909 |
DECLARE |
| 5910 |
a_running_job_count integer; |
| 5911 |
BEGIN |
| 5912 |
LOCK TABLE cs_jobs IN EXCLUSIVE MODE; |
| 5913 |
|
| 5914 |
SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL; |
| 5915 |
|
| 5916 |
IF a_running_job_count > 0 THEN |
| 5917 |
COMMIT; -- free lock |
| 5918 |
RAISE EXCEPTION 'Unable to create a new job: a job is currently running'; -- <co id="co.plpgsql-porting-raise"/> |
| 5919 |
END IF; |
| 5920 |
|
| 5921 |
DELETE FROM cs_active_job; |
| 5922 |
INSERT INTO cs_active_job(job_id) VALUES (v_job_id); |
| 5923 |
|
| 5924 |
BEGIN |
| 5925 |
INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now()); |
| 5926 |
EXCEPTION |
| 5927 |
WHEN unique_violation THEN -- <co id="co.plpgsql-porting-exception"/> |
| 5928 |
-- don't worry if it already exists |
| 5929 |
END; |
| 5930 |
COMMIT; |
| 5931 |
END; |
| 5932 |
$$ LANGUAGE plpgsql; |
| 5933 |
</programlisting> |
| 5934 |
|
| 5935 |
<calloutlist> |
| 5936 |
<callout arearefs="co.plpgsql-porting-raise"> |
| 5937 |
<para> |
| 5938 |
The syntax of <literal>RAISE</literal> is considerably different from |
| 5939 |
Oracle's statement, although the basic case <literal>RAISE</literal> |
| 5940 |
<replaceable class="parameter">exception_name</replaceable> works |
| 5941 |
similarly. |
| 5942 |
</para> |
| 5943 |
</callout> |
| 5944 |
<callout arearefs="co.plpgsql-porting-exception"> |
| 5945 |
<para> |
| 5946 |
The exception names supported by <application>PL/pgSQL</application> are |
| 5947 |
different from Oracle's. The set of built-in exception names |
| 5948 |
is much larger (see <xref linkend="errcodes-appendix"/>). There |
| 5949 |
is not currently a way to declare user-defined exception names, |
| 5950 |
although you can throw user-chosen SQLSTATE values instead. |
| 5951 |
</para> |
| 5952 |
</callout> |
| 5953 |
</calloutlist> |
| 5954 |
</para> |
| 5955 |
</example> |
| 5956 |
</sect2> |
| 5957 |
|
| 5958 |
<sect2 id="plpgsql-porting-other"> |
| 5959 |
<title>Other Things to Watch For</title> |
| 5960 |
|
| 5961 |
<para> |
| 5962 |
This section explains a few other things to watch for when porting |
| 5963 |
Oracle <application>PL/SQL</application> functions to |
| 5964 |
<productname>PostgreSQL</productname>. |
| 5965 |
</para> |
| 5966 |
|
| 5967 |
<sect3 id="plpgsql-porting-exceptions"> |
| 5968 |
<title>Implicit Rollback after Exceptions</title> |
| 5969 |
|
| 5970 |
<para> |
| 5971 |
In <application>PL/pgSQL</application>, when an exception is caught by an |
| 5972 |
<literal>EXCEPTION</literal> clause, all database changes since the block's |
| 5973 |
<literal>BEGIN</literal> are automatically rolled back. That is, the behavior |
| 5974 |
is equivalent to what you'd get in Oracle with: |
| 5975 |
|
| 5976 |
<programlisting> |
| 5977 |
BEGIN |
| 5978 |
SAVEPOINT s1; |
| 5979 |
... code here ... |
| 5980 |
EXCEPTION |
| 5981 |
WHEN ... THEN |
| 5982 |
ROLLBACK TO s1; |
| 5983 |
... code here ... |
| 5984 |
WHEN ... THEN |
| 5985 |
ROLLBACK TO s1; |
| 5986 |
... code here ... |
| 5987 |
END; |
| 5988 |
</programlisting> |
| 5989 |
|
| 5990 |
If you are translating an Oracle procedure that uses |
| 5991 |
<command>SAVEPOINT</command> and <command>ROLLBACK TO</command> in this style, |
| 5992 |
your task is easy: just omit the <command>SAVEPOINT</command> and |
| 5993 |
<command>ROLLBACK TO</command>. If you have a procedure that uses |
| 5994 |
<command>SAVEPOINT</command> and <command>ROLLBACK TO</command> in a different way |
| 5995 |
then some actual thought will be required. |
| 5996 |
</para> |
| 5997 |
</sect3> |
| 5998 |
|
| 5999 |
<sect3 id="plpgsql-porting-other-execute"> |
| 6000 |
<title><command>EXECUTE</command></title> |
| 6001 |
|
| 6002 |
<para> |
| 6003 |
The <application>PL/pgSQL</application> version of |
| 6004 |
<command>EXECUTE</command> works similarly to the |
| 6005 |
<application>PL/SQL</application> version, but you have to remember to use |
| 6006 |
<function>quote_literal</function> and |
| 6007 |
<function>quote_ident</function> as described in <xref |
| 6008 |
linkend="plpgsql-statements-executing-dyn"/>. Constructs of the |
| 6009 |
type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work |
| 6010 |
reliably unless you use these functions. |
| 6011 |
</para> |
| 6012 |
</sect3> |
| 6013 |
|
| 6014 |
<sect3 id="plpgsql-porting-optimization"> |
| 6015 |
<title>Optimizing <application>PL/pgSQL</application> Functions</title> |
| 6016 |
|
| 6017 |
<para> |
| 6018 |
<productname>PostgreSQL</productname> gives you two function creation |
| 6019 |
modifiers to optimize execution: <quote>volatility</quote> (whether |
| 6020 |
the function always returns the same result when given the same |
| 6021 |
arguments) and <quote>strictness</quote> (whether the function |
| 6022 |
returns null if any argument is null). Consult the <xref |
| 6023 |
linkend="sql-createfunction"/> |
| 6024 |
reference page for details. |
| 6025 |
</para> |
| 6026 |
|
| 6027 |
<para> |
| 6028 |
When making use of these optimization attributes, your |
| 6029 |
<command>CREATE FUNCTION</command> statement might look something |
| 6030 |
like this: |
| 6031 |
|
| 6032 |
<programlisting> |
| 6033 |
CREATE FUNCTION foo(...) RETURNS integer AS $$ |
| 6034 |
... |
| 6035 |
$$ LANGUAGE plpgsql STRICT IMMUTABLE; |
| 6036 |
</programlisting> |
| 6037 |
</para> |
| 6038 |
</sect3> |
| 6039 |
</sect2> |
| 6040 |
|
| 6041 |
<sect2 id="plpgsql-porting-appendix"> |
| 6042 |
<title>Appendix</title> |
| 6043 |
|
| 6044 |
<para> |
| 6045 |
This section contains the code for a set of Oracle-compatible |
| 6046 |
<function>instr</function> functions that you can use to simplify |
| 6047 |
your porting efforts. |
| 6048 |
</para> |
| 6049 |
|
| 6050 |
<indexterm> |
| 6051 |
<primary><function>instr</function> function</primary> |
| 6052 |
</indexterm> |
| 6053 |
|
| 6054 |
<programlisting><![CDATA[ |
| 6055 |
-- |
| 6056 |
-- instr functions that mimic Oracle's counterpart |
| 6057 |
-- Syntax: instr(string1, string2 [, n [, m]]) |
| 6058 |
-- where [] denotes optional parameters. |
| 6059 |
-- |
| 6060 |
-- Search string1, beginning at the nth character, for the mth occurrence |
| 6061 |
-- of string2. If n is negative, search backwards, starting at the abs(n)'th |
| 6062 |
-- character from the end of string1. |
| 6063 |
-- If n is not passed, assume 1 (search starts at first character). |
| 6064 |
-- If m is not passed, assume 1 (find first occurrence). |
| 6065 |
-- Returns starting index of string2 in string1, or 0 if string2 is not found. |
| 6066 |
-- |
| 6067 |
|
| 6068 |
CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$ |
| 6069 |
BEGIN |
| 6070 |
RETURN instr($1, $2, 1); |
| 6071 |
END; |
| 6072 |
$$ LANGUAGE plpgsql STRICT IMMUTABLE; |
| 6073 |
|
| 6074 |
|
| 6075 |
CREATE FUNCTION instr(string varchar, string_to_search_for varchar, |
| 6076 |
beg_index integer) |
| 6077 |
RETURNS integer AS $$ |
| 6078 |
DECLARE |
| 6079 |
pos integer NOT NULL DEFAULT 0; |
| 6080 |
temp_str varchar; |
| 6081 |
beg integer; |
| 6082 |
length integer; |
| 6083 |
ss_length integer; |
| 6084 |
BEGIN |
| 6085 |
IF beg_index > 0 THEN |
| 6086 |
temp_str := substring(string FROM beg_index); |
| 6087 |
pos := position(string_to_search_for IN temp_str); |
| 6088 |
|
| 6089 |
IF pos = 0 THEN |
| 6090 |
RETURN 0; |
| 6091 |
ELSE |
| 6092 |
RETURN pos + beg_index - 1; |
| 6093 |
END IF; |
| 6094 |
ELSIF beg_index < 0 THEN |
| 6095 |
ss_length := char_length(string_to_search_for); |
| 6096 |
length := char_length(string); |
| 6097 |
beg := length + 1 + beg_index; |
| 6098 |
|
| 6099 |
WHILE beg > 0 LOOP |
| 6100 |
temp_str := substring(string FROM beg FOR ss_length); |
| 6101 |
IF string_to_search_for = temp_str THEN |
| 6102 |
RETURN beg; |
| 6103 |
END IF; |
| 6104 |
|
| 6105 |
beg := beg - 1; |
| 6106 |
END LOOP; |
| 6107 |
|
| 6108 |
RETURN 0; |
| 6109 |
ELSE |
| 6110 |
RETURN 0; |
| 6111 |
END IF; |
| 6112 |
END; |
| 6113 |
$$ LANGUAGE plpgsql STRICT IMMUTABLE; |
| 6114 |
|
| 6115 |
|
| 6116 |
CREATE FUNCTION instr(string varchar, string_to_search_for varchar, |
| 6117 |
beg_index integer, occur_index integer) |
| 6118 |
RETURNS integer AS $$ |
| 6119 |
DECLARE |
| 6120 |
pos integer NOT NULL DEFAULT 0; |
| 6121 |
occur_number integer NOT NULL DEFAULT 0; |
| 6122 |
temp_str varchar; |
| 6123 |
beg integer; |
| 6124 |
i integer; |
| 6125 |
length integer; |
| 6126 |
ss_length integer; |
| 6127 |
BEGIN |
| 6128 |
IF occur_index <= 0 THEN |
| 6129 |
RAISE 'argument ''%'' is out of range', occur_index |
| 6130 |
USING ERRCODE = '22003'; |
| 6131 |
END IF; |
| 6132 |
|
| 6133 |
IF beg_index > 0 THEN |
| 6134 |
beg := beg_index - 1; |
| 6135 |
FOR i IN 1..occur_index LOOP |
| 6136 |
temp_str := substring(string FROM beg + 1); |
| 6137 |
pos := position(string_to_search_for IN temp_str); |
| 6138 |
IF pos = 0 THEN |
| 6139 |
RETURN 0; |
| 6140 |
END IF; |
| 6141 |
beg := beg + pos; |
| 6142 |
END LOOP; |
| 6143 |
|
| 6144 |
RETURN beg; |
| 6145 |
ELSIF beg_index < 0 THEN |
| 6146 |
ss_length := char_length(string_to_search_for); |
| 6147 |
length := char_length(string); |
| 6148 |
beg := length + 1 + beg_index; |
| 6149 |
|
| 6150 |
WHILE beg > 0 LOOP |
| 6151 |
temp_str := substring(string FROM beg FOR ss_length); |
| 6152 |
IF string_to_search_for = temp_str THEN |
| 6153 |
occur_number := occur_number + 1; |
| 6154 |
IF occur_number = occur_index THEN |
| 6155 |
RETURN beg; |
| 6156 |
END IF; |
| 6157 |
END IF; |
| 6158 |
|
| 6159 |
beg := beg - 1; |
| 6160 |
END LOOP; |
| 6161 |
|
| 6162 |
RETURN 0; |
| 6163 |
ELSE |
| 6164 |
RETURN 0; |
| 6165 |
END IF; |
| 6166 |
END; |
| 6167 |
$$ LANGUAGE plpgsql STRICT IMMUTABLE; |
| 6168 |
]]> |
| 6169 |
</programlisting> |
| 6170 |
</sect2> |
| 6171 |
|
| 6172 |
</sect1> |
| 6173 |
|
| 6174 |
</chapter> |