2 43.1. PL/Perl Functions and Arguments #
4 To create a function in the PL/Perl language, use the standard CREATE
6 CREATE FUNCTION funcname (argument-types)
8 -- function attributes can go here
10 # PL/Perl function body goes here
13 The body of the function is ordinary Perl code. In fact, the PL/Perl
14 glue code wraps it inside a Perl subroutine. A PL/Perl function is
15 called in a scalar context, so it can't return a list. You can return
16 non-scalar values (arrays, records, and sets) by returning a reference,
19 In a PL/Perl procedure, any return value from the Perl code is ignored.
21 PL/Perl also supports anonymous code blocks called with the DO
27 An anonymous code block receives no arguments, and whatever value it
28 might return is discarded. Otherwise it behaves just like a function.
32 The use of named nested subroutines is dangerous in Perl, especially if
33 they refer to lexical variables in the enclosing scope. Because a
34 PL/Perl function is wrapped in a subroutine, any named subroutine you
35 place inside one will be nested. In general, it is far safer to create
36 anonymous subroutines which you call via a coderef. For more
37 information, see the entries for Variable "%s" will not stay shared and
38 Variable "%s" is not available in the perldiag man page, or search the
39 Internet for “perl nested named subroutine”.
41 The syntax of the CREATE FUNCTION command requires the function body to
42 be written as a string constant. It is usually most convenient to use
43 dollar quoting (see Section 4.1.2.4) for the string constant. If you
44 choose to use escape string syntax E'', you must double any single
45 quote marks (') and backslashes (\) used in the body of the function
46 (see Section 4.1.2.1).
48 Arguments and results are handled as in any other Perl subroutine:
49 arguments are passed in @_, and a result value is returned with return
50 or as the last expression evaluated in the function.
52 For example, a function returning the greater of two integer values
54 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
55 if ($_[0] > $_[1]) { return $_[0]; }
61 Arguments will be converted from the database's encoding to UTF-8 for
62 use inside PL/Perl, and then converted from UTF-8 back to the database
65 If an SQL null value is passed to a function, the argument value will
66 appear as “undefined” in Perl. The above function definition will not
67 behave very nicely with null inputs (in fact, it will act as though
68 they are zeroes). We could add STRICT to the function definition to
69 make PostgreSQL do something more reasonable: if a null value is
70 passed, the function will not be called at all, but will just return a
71 null result automatically. Alternatively, we could check for undefined
72 inputs in the function body. For example, suppose that we wanted
73 perl_max with one null and one nonnull argument to return the nonnull
74 argument, rather than a null value:
75 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
78 return undef if not defined $y;
81 return $x if not defined $y;
86 As shown above, to return an SQL null value from a PL/Perl function,
87 return an undefined value. This can be done whether the function is
90 Anything in a function argument that is not a reference is a string,
91 which is in the standard PostgreSQL external text representation for
92 the relevant data type. In the case of ordinary numeric or text types,
93 Perl will just do the right thing and the programmer will normally not
94 have to worry about it. However, in other cases the argument will need
95 to be converted into a form that is more usable in Perl. For example,
96 the decode_bytea function can be used to convert an argument of type
97 bytea into unescaped binary.
99 Similarly, values passed back to PostgreSQL must be in the external
100 text representation format. For example, the encode_bytea function can
101 be used to escape binary data for a return value of type bytea.
103 One case that is particularly important is boolean values. As just
104 stated, the default behavior for bool values is that they are passed to
105 Perl as text, thus either 't' or 'f'. This is problematic, since Perl
106 will not treat 'f' as false! It is possible to improve matters by using
107 a “transform” (see CREATE TRANSFORM). Suitable transforms are provided
108 by the bool_plperl extension. To use it, install the extension:
109 CREATE EXTENSION bool_plperl; -- or bool_plperlu for PL/PerlU
111 Then use the TRANSFORM function attribute for a PL/Perl function that
112 takes or returns bool, for example:
113 CREATE FUNCTION perl_and(bool, bool) RETURNS bool
114 TRANSFORM FOR TYPE bool
120 When this transform is applied, bool arguments will be seen by Perl as
121 being 1 or empty, thus properly true or false. If the function result
122 is type bool, it will be true or false according to whether Perl would
123 evaluate the returned value as true. Similar transformations are also
124 performed for boolean query arguments and results of SPI queries
125 performed inside the function (Section 43.3.1).
127 Perl can return PostgreSQL arrays as references to Perl arrays. Here is
129 CREATE OR REPLACE function returns_array()
130 RETURNS text[][] AS $$
131 return [['a"b','c,d'],['e\\f','g']];
134 select returns_array();
136 Perl passes PostgreSQL arrays as a blessed PostgreSQL::InServer::ARRAY
137 object. This object may be treated as an array reference or a string,
138 allowing for backward compatibility with Perl code written for
139 PostgreSQL versions below 9.1 to run. For example:
140 CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$
143 return undef if (!defined $arg);
145 # as an array reference
150 # also works as a string
156 SELECT concat_array_elements(ARRAY['PL','/','Perl']);
160 Multidimensional arrays are represented as references to
161 lower-dimensional arrays of references in a way common to every Perl
164 Composite-type arguments are passed to the function as references to
165 hashes. The keys of the hash are the attribute names of the composite
166 type. Here is an example:
167 CREATE TABLE employee (
173 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
175 return $emp->{basesalary} + $emp->{bonus};
178 SELECT name, empcomp(employee.*) FROM employee;
180 A PL/Perl function can return a composite-type result using the same
181 approach: return a reference to a hash that has the required
182 attributes. For example:
183 CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
185 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
186 return {f2 => 'hello', f1 => 1, f3 => 'world'};
189 SELECT * FROM perl_row();
191 Any columns in the declared result data type that are not present in
192 the hash will be returned as null values.
194 Similarly, output arguments of procedures can be returned as a hash
196 CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$
198 return {a => $a * 3, b => $b * 3};
201 CALL perl_triple(5, 10);
203 PL/Perl functions can also return sets of either scalar or composite
204 types. Usually you'll want to return rows one at a time, both to speed
205 up startup time and to keep from queuing up the entire result set in
206 memory. You can do this with return_next as illustrated below. Note
207 that after the last return_next, you must put either return or (better)
209 CREATE OR REPLACE FUNCTION perl_set_int(int)
210 RETURNS SETOF INTEGER AS $$
217 SELECT * FROM perl_set_int(5);
219 CREATE OR REPLACE FUNCTION perl_set()
220 RETURNS SETOF testrowperl AS $$
221 return_next({ f1 => 1, f2 => 'Hello', f3 => 'World' });
222 return_next({ f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' });
223 return_next({ f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' });
227 For small result sets, you can return a reference to an array that
228 contains either scalars, references to arrays, or references to hashes
229 for simple types, array types, and composite types, respectively. Here
230 are some simple examples of returning the entire result set as an array
232 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
236 SELECT * FROM perl_set_int(5);
238 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
240 { f1 => 1, f2 => 'Hello', f3 => 'World' },
241 { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' },
242 { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' }
246 SELECT * FROM perl_set();
248 If you wish to use the strict pragma with your code you have a few
249 options. For temporary global use you can SET plperl.use_strict to
250 true. This will affect subsequent compilations of PL/Perl functions,
251 but not functions already compiled in the current session. For
252 permanent global use you can set plperl.use_strict to true in the
253 postgresql.conf file.
255 For permanent use in specific functions you can simply put:
258 at the top of the function body.
260 The feature pragma is also available to use if your Perl is version