]> begriffs open source - ai-pg/blob - full-docs/txt/plperl-funcs.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / plperl-funcs.txt
1
2 43.1. PL/Perl Functions and Arguments #
3
4    To create a function in the PL/Perl language, use the standard CREATE
5    FUNCTION syntax:
6 CREATE FUNCTION funcname (argument-types)
7 RETURNS return-type
8 -- function attributes can go here
9 AS $$
10     # PL/Perl function body goes here
11 $$ LANGUAGE plperl;
12
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,
17    as discussed below.
18
19    In a PL/Perl procedure, any return value from the Perl code is ignored.
20
21    PL/Perl also supports anonymous code blocks called with the DO
22    statement:
23 DO $$
24     # PL/Perl code
25 $$ LANGUAGE plperl;
26
27    An anonymous code block receives no arguments, and whatever value it
28    might return is discarded. Otherwise it behaves just like a function.
29
30 Note
31
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”.
40
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).
47
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.
51
52    For example, a function returning the greater of two integer values
53    could be defined as:
54 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
55     if ($_[0] > $_[1]) { return $_[0]; }
56     return $_[1];
57 $$ LANGUAGE plperl;
58
59 Note
60
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
63    encoding upon return.
64
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 $$
76     my ($x, $y) = @_;
77     if (not defined $x) {
78         return undef if not defined $y;
79         return $y;
80     }
81     return $x if not defined $y;
82     return $x if $x > $y;
83     return $y;
84 $$ LANGUAGE plperl;
85
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
88    strict or not.
89
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.
98
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.
102
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
110
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
115 AS $$
116   my ($a, $b) = @_;
117   return $a && $b;
118 $$ LANGUAGE plperl;
119
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).
126
127    Perl can return PostgreSQL arrays as references to Perl arrays. Here is
128    an example:
129 CREATE OR REPLACE function returns_array()
130 RETURNS text[][] AS $$
131     return [['a"b','c,d'],['e\\f','g']];
132 $$ LANGUAGE plperl;
133
134 select returns_array();
135
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 $$
141     my $arg = shift;
142     my $result = "";
143     return undef if (!defined $arg);
144
145     # as an array reference
146     for (@$arg) {
147         $result .= $_;
148     }
149
150     # also works as a string
151     $result .= $arg;
152
153     return $result;
154 $$ LANGUAGE plperl;
155
156 SELECT concat_array_elements(ARRAY['PL','/','Perl']);
157
158 Note
159
160    Multidimensional arrays are represented as references to
161    lower-dimensional arrays of references in a way common to every Perl
162    programmer.
163
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 (
168     name text,
169     basesalary integer,
170     bonus integer
171 );
172
173 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
174     my ($emp) = @_;
175     return $emp->{basesalary} + $emp->{bonus};
176 $$ LANGUAGE plperl;
177
178 SELECT name, empcomp(employee.*) FROM employee;
179
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);
184
185 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
186     return {f2 => 'hello', f1 => 1, f3 => 'world'};
187 $$ LANGUAGE plperl;
188
189 SELECT * FROM perl_row();
190
191    Any columns in the declared result data type that are not present in
192    the hash will be returned as null values.
193
194    Similarly, output arguments of procedures can be returned as a hash
195    reference:
196 CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$
197     my ($a, $b) = @_;
198     return {a => $a * 3, b => $b * 3};
199 $$ LANGUAGE plperl;
200
201 CALL perl_triple(5, 10);
202
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)
208    return undef.
209 CREATE OR REPLACE FUNCTION perl_set_int(int)
210 RETURNS SETOF INTEGER AS $$
211     foreach (0..$_[0]) {
212         return_next($_);
213     }
214     return undef;
215 $$ LANGUAGE plperl;
216
217 SELECT * FROM perl_set_int(5);
218
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' });
224     return undef;
225 $$ LANGUAGE plperl;
226
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
231    reference:
232 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
233     return [0..$_[0]];
234 $$ LANGUAGE plperl;
235
236 SELECT * FROM perl_set_int(5);
237
238 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
239     return [
240         { f1 => 1, f2 => 'Hello', f3 => 'World' },
241         { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' },
242         { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' }
243     ];
244 $$ LANGUAGE plperl;
245
246 SELECT * FROM perl_set();
247
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.
254
255    For permanent use in specific functions you can simply put:
256 use strict;
257
258    at the top of the function body.
259
260    The feature pragma is also available to use if your Perl is version
261    5.10.0 or higher.