1 <!-- doc/src/sgml/plperl.sgml -->
4 <title>PL/Perl
— Perl Procedural Language
</title>
6 <indexterm zone=
"plperl">
7 <primary>PL/Perl
</primary>
10 <indexterm zone=
"plperl">
11 <primary>Perl
</primary>
15 PL/Perl is a loadable procedural language that enables you to write
16 <productname>PostgreSQL
</productname> functions and procedures in the
17 <ulink url=
"https://www.perl.org">Perl programming language
</ulink>.
21 The main advantage to using PL/Perl is that this allows use,
22 within stored functions and procedures, of the manyfold
<quote>string
23 munging
</quote> operators and functions available for Perl. Parsing
24 complex strings might be easier using Perl than it is with the
25 string functions and control structures provided in PL/pgSQL.
29 To install PL/Perl in a particular database, use
30 <literal>CREATE EXTENSION plperl
</literal>.
35 If a language is installed into
<literal>template1
</literal>, all subsequently
36 created databases will have the language installed automatically.
42 Users of source packages must specially enable the build of
43 PL/Perl during the installation process. (Refer to
<xref
44 linkend=
"installation"/> for more information.) Users of
45 binary packages might find PL/Perl in a separate subpackage.
49 <sect1 id=
"plperl-funcs">
50 <title>PL/Perl Functions and Arguments
</title>
53 To create a function in the PL/Perl language, use the standard
54 <xref linkend=
"sql-createfunction"/>
58 CREATE FUNCTION
<replaceable>funcname
</replaceable> (
<replaceable>argument-types
</replaceable>)
59 RETURNS
<replaceable>return-type
</replaceable>
60 -- function attributes can go here
62 # PL/Perl function body goes here
66 The body of the function is ordinary Perl code. In fact, the PL/Perl
67 glue code wraps it inside a Perl subroutine. A PL/Perl function is
68 called in a scalar context, so it can't return a list. You can return
69 non-scalar values (arrays, records, and sets) by returning a reference,
74 In a PL/Perl procedure, any return value from the Perl code is ignored.
78 PL/Perl also supports anonymous code blocks called with the
79 <xref linkend=
"sql-do"/> statement:
87 An anonymous code block receives no arguments, and whatever value it
88 might return is discarded. Otherwise it behaves just like a function.
93 The use of named nested subroutines is dangerous in Perl, especially if
94 they refer to lexical variables in the enclosing scope. Because a PL/Perl
95 function is wrapped in a subroutine, any named subroutine you place inside
96 one will be nested. In general, it is far safer to create anonymous
97 subroutines which you call via a coderef. For more information, see the
98 entries for
<literal>Variable
"%s" will not stay shared
</literal> and
99 <literal>Variable
"%s" is not available
</literal> in the
100 <citerefentry><refentrytitle>perldiag
</refentrytitle></citerefentry> man page, or
101 search the Internet for
<quote>perl nested named subroutine
</quote>.
106 The syntax of the
<command>CREATE FUNCTION
</command> command requires
107 the function body to be written as a string constant. It is usually
108 most convenient to use dollar quoting (see
<xref
109 linkend=
"sql-syntax-dollar-quoting"/>) for the string constant.
110 If you choose to use escape string syntax
<literal>E''
</literal>,
111 you must double any single quote marks (
<literal>'
</literal>) and backslashes
112 (
<literal>\
</literal>) used in the body of the function
113 (see
<xref linkend=
"sql-syntax-strings"/>).
117 Arguments and results are handled as in any other Perl subroutine:
118 arguments are passed in
<varname>@_
</varname>, and a result value
119 is returned with
<literal>return
</literal> or as the last expression
120 evaluated in the function.
124 For example, a function returning the greater of two integer values
128 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
129 if ($_[
0]
> $_[
1]) { return $_[
0]; }
137 Arguments will be converted from the database's encoding to UTF-
8
138 for use inside PL/Perl, and then converted from UTF-
8 back to the
139 database encoding upon return.
144 If an SQL null value
<indexterm><primary>null value
</primary><secondary
145 sortas=
"PL/Perl">in PL/Perl
</secondary></indexterm> is passed to a function,
146 the argument value will appear as
<quote>undefined
</quote> in Perl. The
147 above function definition will not behave very nicely with null
148 inputs (in fact, it will act as though they are zeroes). We could
149 add
<literal>STRICT
</literal> to the function definition to make
150 <productname>PostgreSQL
</productname> do something more reasonable:
151 if a null value is passed, the function will not be called at all,
152 but will just return a null result automatically. Alternatively,
153 we could check for undefined inputs in the function body. For
154 example, suppose that we wanted
<function>perl_max
</function> with
155 one null and one nonnull argument to return the nonnull argument,
156 rather than a null value:
159 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
161 if (not defined $x) {
162 return undef if not defined $y;
165 return $x if not defined $y;
166 return $x if $x
> $y;
170 As shown above, to return an SQL null value from a PL/Perl
171 function, return an undefined value. This can be done whether the
172 function is strict or not.
176 Anything in a function argument that is not a reference is
177 a string, which is in the standard
<productname>PostgreSQL
</productname>
178 external text representation for the relevant data type. In the case of
179 ordinary numeric or text types, Perl will just do the right thing and
180 the programmer will normally not have to worry about it. However, in
181 other cases the argument will need to be converted into a form that is
182 more usable in Perl. For example, the
<function>decode_bytea
</function>
183 function can be used to convert an argument of
184 type
<type>bytea
</type> into unescaped binary.
188 Similarly, values passed back to
<productname>PostgreSQL
</productname>
189 must be in the external text representation format. For example, the
190 <function>encode_bytea
</function> function can be used to
191 escape binary data for a return value of type
<type>bytea
</type>.
195 One case that is particularly important is boolean values. As just
196 stated, the default behavior for
<type>bool
</type> values is that they
197 are passed to Perl as text, thus either
<literal>'t'
</literal>
198 or
<literal>'f'
</literal>. This is problematic, since Perl will not
199 treat
<literal>'f'
</literal> as false! It is possible to improve matters
200 by using a
<quote>transform
</quote> (see
201 <xref linkend=
"sql-createtransform"/>). Suitable transforms are provided
202 by the
<filename>bool_plperl
</filename> extension. To use it, install
205 CREATE EXTENSION bool_plperl; -- or bool_plperlu for PL/PerlU
207 Then use the
<literal>TRANSFORM
</literal> function attribute for a
208 PL/Perl function that takes or returns
<type>bool
</type>, for example:
210 CREATE FUNCTION perl_and(bool, bool) RETURNS bool
211 TRANSFORM FOR TYPE bool
214 return $a
&& $b;
217 When this transform is applied,
<type>bool
</type> arguments will be seen
218 by Perl as being
<literal>1</literal> or empty, thus properly true or
219 false. If the function result is type
<type>bool
</type>, it will be true
220 or false according to whether Perl would evaluate the returned value as
222 Similar transformations are also performed for boolean query arguments
223 and results of SPI queries performed inside the function
224 (
<xref linkend=
"plperl-database"/>).
228 Perl can return
<productname>PostgreSQL
</productname> arrays as
229 references to Perl arrays. Here is an example:
232 CREATE OR REPLACE function returns_array()
233 RETURNS text[][] AS $$
234 return [['a
"b','c,d'],['e\\f','g']];
237 select returns_array();
242 Perl passes
<productname>PostgreSQL
</productname> arrays as a blessed
243 <type>PostgreSQL::InServer::ARRAY
</type> object. This object may be treated as an array
244 reference or a string, allowing for backward compatibility with Perl
245 code written for
<productname>PostgreSQL
</productname> versions below
9.1 to
249 CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$
252 return undef if (!defined $arg);
254 # as an array reference
259 # also works as a string
265 SELECT concat_array_elements(ARRAY['PL','/','Perl']);
270 Multidimensional arrays are represented as references to
271 lower-dimensional arrays of references in a way common to every Perl
278 Composite-type arguments are passed to the function as references
279 to hashes. The keys of the hash are the attribute names of the
280 composite type. Here is an example:
283 CREATE TABLE employee (
289 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
291 return $emp-
>{basesalary} + $emp-
>{bonus};
294 SELECT name, empcomp(employee.*) FROM employee;
299 A PL/Perl function can return a composite-type result using the same
300 approach: return a reference to a hash that has the required attributes.
304 CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
306 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
307 return {f2 =
> 'hello', f1 =
> 1, f3 =
> 'world'};
310 SELECT * FROM perl_row();
313 Any columns in the declared result data type that are not present in the
314 hash will be returned as null values.
318 Similarly, output arguments of procedures can be returned as a hash
322 CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$
324 return {a =
> $a *
3, b =
> $b *
3};
327 CALL perl_triple(
5,
10);
332 PL/Perl functions can also return sets of either scalar or
333 composite types. Usually you'll want to return rows one at a
334 time, both to speed up startup time and to keep from queuing up
335 the entire result set in memory. You can do this with
336 <function>return_next
</function> as illustrated below. Note that
337 after the last
<function>return_next
</function>, you must put
338 either
<literal>return
</literal> or (better)
<literal>return
342 CREATE OR REPLACE FUNCTION perl_set_int(int)
343 RETURNS SETOF INTEGER AS $$
350 SELECT * FROM perl_set_int(
5);
352 CREATE OR REPLACE FUNCTION perl_set()
353 RETURNS SETOF testrowperl AS $$
354 return_next({ f1 =
> 1, f2 =
> 'Hello', f3 =
> 'World' });
355 return_next({ f1 =
> 2, f2 =
> 'Hello', f3 =
> 'PostgreSQL' });
356 return_next({ f1 =
> 3, f2 =
> 'Hello', f3 =
> 'PL/Perl' });
361 For small result sets, you can return a reference to an array that
362 contains either scalars, references to arrays, or references to
363 hashes for simple types, array types, and composite types,
364 respectively. Here are some simple examples of returning the entire
365 result set as an array reference:
368 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
372 SELECT * FROM perl_set_int(
5);
374 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
376 { f1 =
> 1, f2 =
> 'Hello', f3 =
> 'World' },
377 { f1 =
> 2, f2 =
> 'Hello', f3 =
> 'PostgreSQL' },
378 { f1 =
> 3, f2 =
> 'Hello', f3 =
> 'PL/Perl' }
382 SELECT * FROM perl_set();
387 If you wish to use the
<literal>strict
</literal> pragma with your code you
388 have a few options. For temporary global use you can
<command>SET
</command>
389 <literal>plperl.use_strict
</literal> to true.
390 This will affect subsequent compilations of
<application>PL/Perl
</application>
391 functions, but not functions already compiled in the current session.
392 For permanent global use you can set
<literal>plperl.use_strict
</literal>
393 to true in the
<filename>postgresql.conf
</filename> file.
397 For permanent use in specific functions you can simply put:
401 at the top of the function body.
405 The
<literal>feature
</literal> pragma is also available to
<function>use
</function> if your Perl is version
5.10.0 or higher.
410 <sect1 id=
"plperl-data">
411 <title>Data Values in PL/Perl
</title>
414 The argument values supplied to a PL/Perl function's code are
415 simply the input arguments converted to text form (just as if they
416 had been displayed by a
<command>SELECT
</command> statement).
417 Conversely, the
<function>return
</function> and
<function>return_next
</function>
418 commands will accept any string that is acceptable input format
419 for the function's declared return type.
423 If this behavior is inconvenient for a particular case, it can be
424 improved by using a transform, as already illustrated
425 for
<type>bool
</type> values. Several examples of transform modules
426 are included in the
<productname>PostgreSQL
</productname> distribution.
430 <sect1 id=
"plperl-builtins">
431 <title>Built-in Functions
</title>
433 <sect2 id=
"plperl-database">
434 <title>Database Access from PL/Perl
</title>
437 Access to the database itself from your Perl function can be done
438 via the following functions:
444 <literal><function>spi_exec_query
</function>(
<replaceable>query
</replaceable> [,
<replaceable>limit
</replaceable>])
</literal>
446 <primary>spi_exec_query
</primary>
447 <secondary>in PL/Perl
</secondary>
452 <function>spi_exec_query
</function> executes an SQL command and
453 returns the entire row set as a reference to an array of hash references.
454 If
<replaceable>limit
</replaceable> is specified and is greater than zero,
455 then
<function>spi_exec_query
</function> retrieves at
456 most
<replaceable>limit
</replaceable> rows, much as if the query included
457 a
<literal>LIMIT
</literal> clause. Omitting
<replaceable>limit
</replaceable>
458 or specifying it as zero results in no row limit.
462 <emphasis>You should only use this command when you know
463 that the result set will be relatively small.
</emphasis> Here is an
464 example of a query (
<command>SELECT
</command> command) with the
465 optional maximum number of rows:
468 $rv = spi_exec_query('SELECT * FROM my_table',
5);
470 This returns up to
5 rows from the table
471 <literal>my_table
</literal>. If
<literal>my_table
</literal>
472 has a column
<literal>my_column
</literal>, you can get that
473 value from row
<literal>$i
</literal> of the result like this:
475 $foo = $rv-
>{rows}[$i]-
>{my_column};
477 The total number of rows returned from a
<command>SELECT
</command>
478 query can be accessed like this:
480 $nrows = $rv-
>{processed}
485 Here is an example using a different command type:
487 $query =
"INSERT INTO my_table VALUES (1, 'test')";
488 $rv = spi_exec_query($query);
490 You can then access the command status (e.g.,
491 <literal>SPI_OK_INSERT
</literal>) like this:
493 $res = $rv-
>{status};
495 To get the number of rows affected, do:
497 $nrows = $rv-
>{processed};
502 Here is a complete example:
509 INSERT INTO test (i, v) VALUES (
1, 'first line');
510 INSERT INTO test (i, v) VALUES (
2, 'second line');
511 INSERT INTO test (i, v) VALUES (
3, 'third line');
512 INSERT INTO test (i, v) VALUES (
4, 'immortal');
514 CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
515 my $rv = spi_exec_query('select i, v from test;');
516 my $status = $rv-
>{status};
517 my $nrows = $rv-
>{processed};
518 foreach my $rn (
0 .. $nrows -
1) {
519 my $row = $rv-
>{rows}[$rn];
520 $row-
>{i} +=
200 if defined($row-
>{i});
521 $row-
>{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-
>{v}));
527 SELECT * FROM test_munge();
535 <literal><function>spi_query(
<replaceable>command
</replaceable>)
</function></literal>
537 <primary>spi_query
</primary>
538 <secondary>in PL/Perl
</secondary>
542 <literal><function>spi_fetchrow(
<replaceable>cursor
</replaceable>)
</function></literal>
544 <primary>spi_fetchrow
</primary>
545 <secondary>in PL/Perl
</secondary>
549 <literal><function>spi_cursor_close(
<replaceable>cursor
</replaceable>)
</function></literal>
551 <primary>spi_cursor_close
</primary>
552 <secondary>in PL/Perl
</secondary>
558 <literal>spi_query
</literal> and
<literal>spi_fetchrow
</literal>
559 work together as a pair for row sets which might be large, or for cases
560 where you wish to return rows as they arrive.
561 <literal>spi_fetchrow
</literal> works
<emphasis>only
</emphasis> with
562 <literal>spi_query
</literal>. The following example illustrates how
563 you use them together:
566 CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
568 CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
569 use Digest::MD5 qw(md5_hex);
570 my $file = '/usr/share/dict/words';
572 elog(NOTICE,
"opening file $file at $t" );
573 open my $fh, '
<', $file # ooh, it's a file access!
574 or elog(ERROR,
"cannot open $file for reading: $!");
575 my @words =
<$fh
>;
578 elog(NOTICE,
"closed file $file at $t");
581 my $sth = spi_query(
"SELECT * FROM generate_series(1,$_[0]) AS b(a)");
582 while (defined ($row = spi_fetchrow($sth))) {
584 the_num =
> $row-
>{a},
585 the_text =
> md5_hex($words[rand @words])
591 SELECT * from lotsa_md5(
500);
596 Normally,
<function>spi_fetchrow
</function> should be repeated until it
597 returns
<literal>undef
</literal>, indicating that there are no more
598 rows to read. The cursor returned by
<literal>spi_query
</literal>
599 is automatically freed when
600 <function>spi_fetchrow
</function> returns
<literal>undef
</literal>.
601 If you do not wish to read all the rows, instead call
602 <function>spi_cursor_close
</function> to free the cursor.
603 Failure to do so will result in memory leaks.
611 <literal><function>spi_prepare(
<replaceable>command
</replaceable>,
<replaceable>argument types
</replaceable>)
</function></literal>
613 <primary>spi_prepare
</primary>
614 <secondary>in PL/Perl
</secondary>
618 <literal><function>spi_query_prepared(
<replaceable>plan
</replaceable>,
<replaceable>arguments
</replaceable>)
</function></literal>
620 <primary>spi_query_prepared
</primary>
621 <secondary>in PL/Perl
</secondary>
625 <literal><function>spi_exec_prepared(
<replaceable>plan
</replaceable> [,
<replaceable>attributes
</replaceable>],
<replaceable>arguments
</replaceable>)
</function></literal>
627 <primary>spi_exec_prepared
</primary>
628 <secondary>in PL/Perl
</secondary>
632 <literal><function>spi_freeplan(
<replaceable>plan
</replaceable>)
</function></literal>
634 <primary>spi_freeplan
</primary>
635 <secondary>in PL/Perl
</secondary>
641 <literal>spi_prepare
</literal>,
<literal>spi_query_prepared
</literal>,
<literal>spi_exec_prepared
</literal>,
642 and
<literal>spi_freeplan
</literal> implement the same functionality but for prepared queries.
643 <literal>spi_prepare
</literal> accepts a query string with numbered argument placeholders ($
1, $
2, etc.)
644 and a string list of argument types:
646 $plan = spi_prepare('SELECT * FROM test WHERE id
> $
1 AND name = $
2',
649 Once a query plan is prepared by a call to
<literal>spi_prepare
</literal>, the plan can be used instead
650 of the string query, either in
<literal>spi_exec_prepared
</literal>, where the result is the same as returned
651 by
<literal>spi_exec_query
</literal>, or in
<literal>spi_query_prepared
</literal> which returns a cursor
652 exactly as
<literal>spi_query
</literal> does, which can be later passed to
<literal>spi_fetchrow
</literal>.
653 The optional second parameter to
<literal>spi_exec_prepared
</literal> is a hash reference of attributes;
654 the only attribute currently supported is
<literal>limit
</literal>, which
655 sets the maximum number of rows returned from the query.
656 Omitting
<literal>limit
</literal> or specifying it as zero results in no
661 The advantage of prepared queries is that is it possible to use one prepared plan for more
662 than one query execution. After the plan is not needed anymore, it can be freed with
663 <literal>spi_freeplan
</literal>:
665 CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
666 $_SHARED{my_plan} = spi_prepare('SELECT (now() + $
1)::date AS now',
670 CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$
671 return spi_exec_prepared(
674 )-
>{rows}-
>[
0]-
>{now};
677 CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
678 spi_freeplan( $_SHARED{my_plan});
679 undef $_SHARED{my_plan};
683 SELECT add_time('
1 day'), add_time('
2 days'), add_time('
3 days');
686 add_time | add_time | add_time
687 ------------+------------+------------
688 2005-
12-
10 |
2005-
12-
11 |
2005-
12-
12
690 Note that the parameter subscript in
<literal>spi_prepare
</literal> is defined via
691 $
1, $
2, $
3, etc., so avoid declaring query strings in double quotes that might easily
692 lead to hard-to-catch bugs.
696 Another example illustrates usage of an optional parameter in
<literal>spi_exec_prepared
</literal>:
698 CREATE TABLE hosts AS SELECT id, ('
192.168.1.'||id)::inet AS address
699 FROM generate_series(
1,
3) AS id;
701 CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
702 $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
703 WHERE address
<< $
1', 'inet');
706 CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
707 return spi_exec_prepared(
714 CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
715 spi_freeplan($_SHARED{plan});
716 undef $_SHARED{plan};
719 SELECT init_hosts_query();
720 SELECT query_hosts('
192.168.1.0/
30');
721 SELECT release_hosts_query();
735 <literal><function>spi_commit()
</function></literal>
737 <primary>spi_commit
</primary>
738 <secondary>in PL/Perl
</secondary>
742 <literal><function>spi_rollback()
</function></literal>
744 <primary>spi_rollback
</primary>
745 <secondary>in PL/Perl
</secondary>
750 Commit or roll back the current transaction. This can only be called
751 in a procedure or anonymous code block (
<command>DO
</command> command)
752 called from the top level. (Note that it is not possible to run the
753 SQL commands
<command>COMMIT
</command> or
<command>ROLLBACK
</command>
754 via
<function>spi_exec_query
</function> or similar. It has to be done
755 using these functions.) After a transaction is ended, a new
756 transaction is automatically started, so there is no separate function
763 CREATE PROCEDURE transaction_test1()
766 foreach my $i (
0.
.9) {
767 spi_exec_query(
"INSERT INTO test1 (a) VALUES ($i)");
776 CALL transaction_test1();
784 <sect2 id=
"plperl-utility-functions">
785 <title>Utility Functions in PL/Perl
</title>
790 <literal><function>elog(
<replaceable>level
</replaceable>,
<replaceable>msg
</replaceable>)
</function></literal>
792 <primary>elog
</primary>
793 <secondary>in PL/Perl
</secondary>
798 Emit a log or error message. Possible levels are
799 <literal>DEBUG
</literal>,
<literal>LOG
</literal>,
<literal>INFO
</literal>,
800 <literal>NOTICE
</literal>,
<literal>WARNING
</literal>, and
<literal>ERROR
</literal>.
801 <literal>ERROR
</literal>
802 raises an error condition; if this is not trapped by the surrounding
803 Perl code, the error propagates out to the calling query, causing
804 the current transaction or subtransaction to be aborted. This
805 is effectively the same as the Perl
<literal>die
</literal> command.
806 The other levels only generate messages of different
808 Whether messages of a particular priority are reported to the client,
809 written to the server log, or both is controlled by the
810 <xref linkend=
"guc-log-min-messages"/> and
811 <xref linkend=
"guc-client-min-messages"/> configuration
812 variables. See
<xref linkend=
"runtime-config"/> for more
820 <literal><function>quote_literal(
<replaceable>string
</replaceable>)
</function></literal>
822 <primary>quote_literal
</primary>
823 <secondary>in PL/Perl
</secondary>
828 Return the given string suitably quoted to be used as a string literal in an SQL
829 statement string. Embedded single-quotes and backslashes are properly doubled.
830 Note that
<function>quote_literal
</function> returns undef on undef input; if the argument
831 might be undef,
<function>quote_nullable
</function> is often more suitable.
838 <literal><function>quote_nullable(
<replaceable>string
</replaceable>)
</function></literal>
840 <primary>quote_nullable
</primary>
841 <secondary>in PL/Perl
</secondary>
846 Return the given string suitably quoted to be used as a string literal in an SQL
847 statement string; or, if the argument is undef, return the unquoted string
"NULL".
848 Embedded single-quotes and backslashes are properly doubled.
855 <literal><function>quote_ident(
<replaceable>string
</replaceable>)
</function></literal>
857 <primary>quote_ident
</primary>
858 <secondary>in PL/Perl
</secondary>
863 Return the given string suitably quoted to be used as an identifier in
864 an SQL statement string. Quotes are added only if necessary (i.e., if
865 the string contains non-identifier characters or would be case-folded).
866 Embedded quotes are properly doubled.
873 <literal><function>decode_bytea(
<replaceable>string
</replaceable>)
</function></literal>
875 <primary>decode_bytea
</primary>
876 <secondary>in PL/Perl
</secondary>
881 Return the unescaped binary data represented by the contents of the given string,
882 which should be
<type>bytea
</type> encoded.
889 <literal><function>encode_bytea(
<replaceable>string
</replaceable>)
</function></literal>
891 <primary>encode_bytea
</primary>
892 <secondary>in PL/Perl
</secondary>
897 Return the
<type>bytea
</type> encoded form of the binary data contents of the given string.
904 <literal><function>encode_array_literal(
<replaceable>array
</replaceable>)
</function></literal>
906 <primary>encode_array_literal
</primary>
907 <secondary>in PL/Perl
</secondary>
911 <literal><function>encode_array_literal(
<replaceable>array
</replaceable>,
<replaceable>delimiter
</replaceable>)
</function></literal>
915 Returns the contents of the referenced array as a string in array literal format
916 (see
<xref linkend=
"arrays-input"/>).
917 Returns the argument value unaltered if it's not a reference to an array.
918 The delimiter used between elements of the array literal defaults to
"<literal>, </literal>"
919 if a delimiter is not specified or is undef.
926 <literal><function>encode_typed_literal(
<replaceable>value
</replaceable>,
<replaceable>typename
</replaceable>)
</function></literal>
928 <primary>encode_typed_literal
</primary>
929 <secondary>in PL/Perl
</secondary>
934 Converts a Perl variable to the value of the data type passed as a
935 second argument and returns a string representation of this value.
936 Correctly handles nested arrays and values of composite types.
943 <literal><function>encode_array_constructor(
<replaceable>array
</replaceable>)
</function></literal>
945 <primary>encode_array_constructor
</primary>
946 <secondary>in PL/Perl
</secondary>
951 Returns the contents of the referenced array as a string in array constructor format
952 (see
<xref linkend=
"sql-syntax-array-constructors"/>).
953 Individual values are quoted using
<function>quote_nullable
</function>.
954 Returns the argument value, quoted using
<function>quote_nullable
</function>,
955 if it's not a reference to an array.
962 <literal><function>looks_like_number(
<replaceable>string
</replaceable>)
</function></literal>
964 <primary>looks_like_number
</primary>
965 <secondary>in PL/Perl
</secondary>
970 Returns a true value if the content of the given string looks like a
971 number, according to Perl, returns false otherwise.
972 Returns undef if the argument is undef. Leading and trailing space is
973 ignored.
<literal>Inf
</literal> and
<literal>Infinity
</literal> are regarded as numbers.
980 <literal><function>is_array_ref(
<replaceable>argument
</replaceable>)
</function></literal>
982 <primary>is_array_ref
</primary>
983 <secondary>in PL/Perl
</secondary>
988 Returns a true value if the given argument may be treated as an
989 array reference, that is, if ref of the argument is
<literal>ARRAY
</literal> or
990 <literal>PostgreSQL::InServer::ARRAY
</literal>. Returns false otherwise.
999 <sect1 id=
"plperl-global">
1000 <title>Global Values in PL/Perl
</title>
1003 You can use the global hash
<varname>%_SHARED
</varname> to store
1004 data, including code references, between function calls for the
1005 lifetime of the current session.
1009 Here is a simple example for shared data:
1011 CREATE OR REPLACE FUNCTION set_var(name text, val text) RETURNS text AS $$
1012 if ($_SHARED{$_[
0]} = $_[
1]) {
1015 return
"cannot set shared variable $_[0] to $_[1]";
1019 CREATE OR REPLACE FUNCTION get_var(name text) RETURNS text AS $$
1020 return $_SHARED{$_[
0]};
1023 SELECT set_var('sample', 'Hello, PL/Perl! How''s tricks?');
1024 SELECT get_var('sample');
1029 Here is a slightly more complicated example using a code reference:
1032 CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
1033 $_SHARED{myquote} = sub {
1035 $arg =~ s/(['\\])/\\$
1/g;
1040 SELECT myfuncs(); /* initializes the function */
1042 /* Set up a function that uses the quote function */
1044 CREATE OR REPLACE FUNCTION use_quote(TEXT) RETURNS text AS $$
1045 my $text_to_quote = shift;
1046 my $qfunc = $_SHARED{myquote};
1047 return
&$qfunc($text_to_quote);
1051 (You could have replaced the above with the one-liner
1052 <literal>return $_SHARED{myquote}-
>($_[
0]);
</literal>
1053 at the expense of readability.)
1057 For security reasons, PL/Perl executes functions called by any one SQL role
1058 in a separate Perl interpreter for that role. This prevents accidental or
1059 malicious interference by one user with the behavior of another user's
1060 PL/Perl functions. Each such interpreter has its own value of the
1061 <varname>%_SHARED
</varname> variable and other global state. Thus, two
1062 PL/Perl functions will share the same value of
<varname>%_SHARED
</varname>
1063 if and only if they are executed by the same SQL role. In an application
1064 wherein a single session executes code under multiple SQL roles (via
1065 <literal>SECURITY DEFINER
</literal> functions, use of
<command>SET ROLE
</command>, etc.)
1066 you may need to take explicit steps to ensure that PL/Perl functions can
1067 share data via
<varname>%_SHARED
</varname>. To do that, make sure that
1068 functions that should communicate are owned by the same user, and mark
1069 them
<literal>SECURITY DEFINER
</literal>. You must of course take care that
1070 such functions can't be used to do anything unintended.
1074 <sect1 id=
"plperl-trusted">
1075 <title>Trusted and Untrusted PL/Perl
</title>
1077 <indexterm zone=
"plperl-trusted">
1078 <primary>trusted
</primary>
1079 <secondary>PL/Perl
</secondary>
1083 Normally, PL/Perl is installed as a
<quote>trusted
</quote> programming
1084 language named
<literal>plperl
</literal>. In this setup, certain Perl
1085 operations are disabled to preserve security. In general, the
1086 operations that are restricted are those that interact with the
1087 environment. This includes file handle operations,
1088 <literal>require
</literal>, and
<literal>use
</literal> (for
1089 external modules). There is no way to access internals of the
1090 database server process or to gain OS-level access with the
1091 permissions of the server process,
1092 as a C function can do. Thus, any unprivileged database user can
1093 be permitted to use this language.
1098 Trusted PL/Perl relies on the Perl
<literal>Opcode
</literal> module to
1101 <ulink url=
"https://perldoc.perl.org/Opcode#WARNING">documents
</ulink>
1102 that the module is not effective for the trusted PL/Perl use case. If
1103 your security needs are incompatible with the uncertainty in that warning,
1104 consider executing
<literal>REVOKE USAGE ON LANGUAGE plperl FROM
1110 Here is an example of a function that will not work because file
1111 system operations are not allowed for security reasons:
1113 CREATE FUNCTION badfunc() RETURNS integer AS $$
1114 my $tmpfile =
"/tmp/badfile";
1115 open my $fh, '
>', $tmpfile
1116 or elog(ERROR, qq{could not open the file
"$tmpfile": $!});
1117 print $fh
"Testing writing to a file\n";
1118 close $fh or elog(ERROR, qq{could not close the file
"$tmpfile": $!});
1122 The creation of this function will fail as its use of a forbidden
1123 operation will be caught by the validator.
1127 Sometimes it is desirable to write Perl functions that are not
1128 restricted. For example, one might want a Perl function that sends
1129 mail. To handle these cases, PL/Perl can also be installed as an
1130 <quote>untrusted
</quote> language (usually called
1131 <application>PL/PerlU
</application><indexterm><primary>PL/PerlU
</primary></indexterm>).
1132 In this case the full Perl language is available. When installing the
1133 language, the language name
<literal>plperlu
</literal> will select
1134 the untrusted PL/Perl variant.
1138 The writer of a
<application>PL/PerlU
</application> function must take care that the function
1139 cannot be used to do anything unwanted, since it will be able to do
1140 anything that could be done by a user logged in as the database
1141 administrator. Note that the database system allows only database
1142 superusers to create functions in untrusted languages.
1146 If the above function was created by a superuser using the language
1147 <literal>plperlu
</literal>, execution would succeed.
1151 In the same way, anonymous code blocks written in Perl can use
1152 restricted operations if the language is specified as
1153 <literal>plperlu
</literal> rather than
<literal>plperl
</literal>, but the caller
1154 must be a superuser.
1159 While
<application>PL/Perl
</application> functions run in a separate Perl
1160 interpreter for each SQL role, all
<application>PL/PerlU
</application> functions
1161 executed in a given session run in a single Perl interpreter (which is
1162 not any of the ones used for
<application>PL/Perl
</application> functions).
1163 This allows
<application>PL/PerlU
</application> functions to share data freely,
1164 but no communication can occur between
<application>PL/Perl
</application> and
1165 <application>PL/PerlU
</application> functions.
1171 Perl cannot support multiple interpreters within one process unless
1172 it was built with the appropriate flags, namely either
1173 <literal>usemultiplicity
</literal> or
<literal>useithreads
</literal>.
1174 (
<literal>usemultiplicity
</literal> is preferred unless you actually need
1175 to use threads. For more details, see the
1176 <citerefentry><refentrytitle>perlembed
</refentrytitle></citerefentry> man page.)
1177 If
<application>PL/Perl
</application> is used with a copy of Perl that was not built
1178 this way, then it is only possible to have one Perl interpreter per
1179 session, and so any one session can only execute either
1180 <application>PL/PerlU
</application> functions, or
<application>PL/Perl
</application> functions
1181 that are all called by the same SQL role.
1187 <sect1 id=
"plperl-triggers">
1188 <title>PL/Perl Triggers
</title>
1191 PL/Perl can be used to write trigger functions. In a trigger function,
1192 the hash reference
<varname>$_TD
</varname> contains information about the
1193 current trigger event.
<varname>$_TD
</varname> is a global variable,
1194 which gets a separate local value for each invocation of the trigger.
1195 The fields of the
<varname>$_TD
</varname> hash reference are:
1199 <term><literal>$_TD-
>{new}{foo}
</literal></term>
1202 <literal>NEW
</literal> value of column
<literal>foo
</literal>
1208 <term><literal>$_TD-
>{old}{foo}
</literal></term>
1211 <literal>OLD
</literal> value of column
<literal>foo
</literal>
1217 <term><literal>$_TD-
>{name}
</literal></term>
1220 Name of the trigger being called
1226 <term><literal>$_TD-
>{event}
</literal></term>
1229 Trigger event:
<literal>INSERT
</literal>,
<literal>UPDATE
</literal>,
1230 <literal>DELETE
</literal>,
<literal>TRUNCATE
</literal>, or
<literal>UNKNOWN
</literal>
1236 <term><literal>$_TD-
>{when}
</literal></term>
1239 When the trigger was called:
<literal>BEFORE
</literal>,
1240 <literal>AFTER
</literal>,
<literal>INSTEAD OF
</literal>, or
1241 <literal>UNKNOWN
</literal>
1247 <term><literal>$_TD-
>{level}
</literal></term>
1250 The trigger level:
<literal>ROW
</literal>,
<literal>STATEMENT
</literal>, or
<literal>UNKNOWN
</literal>
1256 <term><literal>$_TD-
>{relid}
</literal></term>
1259 OID of the table on which the trigger fired
1265 <term><literal>$_TD-
>{table_name}
</literal></term>
1268 Name of the table on which the trigger fired
1274 <term><literal>$_TD-
>{relname}
</literal></term>
1277 Name of the table on which the trigger fired. This has been deprecated,
1278 and could be removed in a future release.
1279 Please use $_TD-
>{table_name} instead.
1285 <term><literal>$_TD-
>{table_schema}
</literal></term>
1288 Name of the schema in which the table on which the trigger fired, is
1294 <term><literal>$_TD-
>{argc}
</literal></term>
1297 Number of arguments of the trigger function
1303 <term><literal>@{$_TD-
>{args}}
</literal></term>
1306 Arguments of the trigger function. Does not exist if
<literal>$_TD-
>{argc}
</literal> is
0.
1315 Row-level triggers can return one of the following:
1319 <term><literal>return;
</literal></term>
1322 Execute the operation
1328 <term><literal>"SKIP"</literal></term>
1331 Don't execute the operation
1337 <term><literal>"MODIFY"</literal></term>
1340 Indicates that the
<literal>NEW
</literal> row was modified by
1341 the trigger function
1349 Here is an example of a trigger function, illustrating some of the
1357 CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
1358 if (($_TD-
>{new}{i}
>=
100) || ($_TD-
>{new}{i}
<=
0)) {
1359 return
"SKIP"; # skip INSERT/UPDATE command
1360 } elsif ($_TD-
>{new}{v} ne
"immortal") {
1361 $_TD-
>{new}{v} .=
"(modified by trigger)";
1362 return
"MODIFY"; # modify row and execute INSERT/UPDATE command
1364 return; # execute INSERT/UPDATE command
1368 CREATE TRIGGER test_valid_id_trig
1369 BEFORE INSERT OR UPDATE ON test
1370 FOR EACH ROW EXECUTE FUNCTION valid_id();
1375 <sect1 id=
"plperl-event-triggers">
1376 <title>PL/Perl Event Triggers
</title>
1379 PL/Perl can be used to write event trigger functions. In an event trigger
1380 function, the hash reference
<varname>$_TD
</varname> contains information
1381 about the current trigger event.
<varname>$_TD
</varname> is a global variable,
1382 which gets a separate local value for each invocation of the trigger. The
1383 fields of the
<varname>$_TD
</varname> hash reference are:
1387 <term><literal>$_TD-
>{event}
</literal></term>
1390 The name of the event the trigger is fired for.
1396 <term><literal>$_TD-
>{tag}
</literal></term>
1399 The command tag for which the trigger is fired.
1407 The return value of the trigger function is ignored.
1411 Here is an example of an event trigger function, illustrating some of the
1414 CREATE OR REPLACE FUNCTION perlsnitch() RETURNS event_trigger AS $$
1415 elog(NOTICE,
"perlsnitch: " . $_TD-
>{event} .
" " . $_TD-
>{tag} .
" ");
1418 CREATE EVENT TRIGGER perl_a_snitch
1419 ON ddl_command_start
1420 EXECUTE FUNCTION perlsnitch();
1425 <sect1 id=
"plperl-under-the-hood">
1426 <title>PL/Perl Under the Hood
</title>
1428 <sect2 id=
"plperl-config">
1429 <title>Configuration
</title>
1432 This section lists configuration parameters that affect
<application>PL/Perl
</application>.
1437 <varlistentry id=
"guc-plperl-on-init" xreflabel=
"plperl.on_init">
1439 <varname>plperl.on_init
</varname> (
<type>string
</type>)
1441 <primary><varname>plperl.on_init
</varname> configuration parameter
</primary>
1446 Specifies Perl code to be executed when a Perl interpreter is first
1447 initialized, before it is specialized for use by
<literal>plperl
</literal> or
1448 <literal>plperlu
</literal>.
1449 The SPI functions are not available when this code is executed.
1450 If the code fails with an error it will abort the initialization of
1451 the interpreter and propagate out to the calling query, causing the
1452 current transaction or subtransaction to be aborted.
1455 The Perl code is limited to a single string. Longer code can be placed
1456 into a module and loaded by the
<literal>on_init
</literal> string.
1459 plperl.on_init = 'require
"plperlinit.pl"'
1460 plperl.on_init = 'use lib
"/my/app"; use MyApp::PgInit;'
1464 Any modules loaded by
<literal>plperl.on_init
</literal>, either directly or
1465 indirectly, will be available for use by
<literal>plperl
</literal>. This may
1466 create a security risk. To see what modules have been loaded you can use:
1468 DO 'elog(WARNING, join
", ", sort keys %INC)' LANGUAGE plperl;
1472 Initialization will happen in the postmaster if the
<literal>plperl
</literal> library is
1473 included in
<xref linkend=
"guc-shared-preload-libraries"/>, in which
1474 case extra consideration should be given to the risk of destabilizing
1475 the postmaster. The principal reason for making use of this feature
1476 is that Perl modules loaded by
<literal>plperl.on_init
</literal> need be
1477 loaded only at postmaster start, and will be instantly available
1478 without loading overhead in individual database sessions. However,
1479 keep in mind that the overhead is avoided only for the first Perl
1480 interpreter used by a database session
— either PL/PerlU, or
1481 PL/Perl for the first SQL role that calls a PL/Perl function. Any
1482 additional Perl interpreters created in a database session will have
1483 to execute
<literal>plperl.on_init
</literal> afresh. Also, on Windows there
1484 will be no savings whatsoever from preloading, since the Perl
1485 interpreter created in the postmaster process does not propagate to
1489 This parameter can only be set in the
<filename>postgresql.conf
</filename> file or on the server command line.
1494 <varlistentry id=
"guc-plperl-on-plperl-init" xreflabel=
"plperl.on_plperl_init">
1496 <varname>plperl.on_plperl_init
</varname> (
<type>string
</type>)
1498 <primary><varname>plperl.on_plperl_init
</varname> configuration parameter
</primary>
1502 <varname>plperl.on_plperlu_init
</varname> (
<type>string
</type>)
1504 <primary><varname>plperl.on_plperlu_init
</varname> configuration parameter
</primary>
1509 These parameters specify Perl code to be executed when a Perl
1510 interpreter is specialized for
<literal>plperl
</literal> or
1511 <literal>plperlu
</literal> respectively. This will happen when a PL/Perl or
1512 PL/PerlU function is first executed in a database session, or when
1513 an additional interpreter has to be created because the other language
1514 is called or a PL/Perl function is called by a new SQL role. This
1515 follows any initialization done by
<literal>plperl.on_init
</literal>.
1516 The SPI functions are not available when this code is executed.
1517 The Perl code in
<literal>plperl.on_plperl_init
</literal> is executed after
1518 <quote>locking down
</quote> the interpreter, and thus it can only perform
1522 If the code fails with an error it will abort the initialization and
1523 propagate out to the calling query, causing the current transaction or
1524 subtransaction to be aborted. Any actions already done within Perl
1525 won't be undone; however, that interpreter won't be used again.
1526 If the language is used again the initialization will be attempted
1527 again within a fresh Perl interpreter.
1530 Only superusers can change these settings. Although these settings
1531 can be changed within a session, such changes will not affect Perl
1532 interpreters that have already been used to execute functions.
1537 <varlistentry id=
"guc-plperl-use-strict" xreflabel=
"plperl.use_strict">
1539 <varname>plperl.use_strict
</varname> (
<type>boolean
</type>)
1541 <primary><varname>plperl.use_strict
</varname> configuration parameter
</primary>
1546 When set true subsequent compilations of PL/Perl functions will have
1547 the
<literal>strict
</literal> pragma enabled. This parameter does not affect
1548 functions already compiled in the current session.
1556 <sect2 id=
"plperl-missing">
1557 <title>Limitations and Missing Features
</title>
1560 The following features are currently missing from PL/Perl, but they
1561 would make welcome contributions.
1566 PL/Perl functions cannot call each other directly.
1572 SPI is not yet fully implemented.
1578 If you are fetching very large data sets using
1579 <literal>spi_exec_query
</literal>, you should be aware that
1580 these will all go into memory. You can avoid this by using
1581 <literal>spi_query
</literal>/
<literal>spi_fetchrow
</literal> as
1582 illustrated earlier.
1585 A similar problem occurs if a set-returning function passes a
1586 large set of rows back to PostgreSQL via
<literal>return
</literal>. You
1587 can avoid this problem too by instead using
1588 <literal>return_next
</literal> for each row returned, as shown
1595 When a session ends normally, not due to a fatal error, any
1596 <literal>END
</literal> blocks that have been defined are executed.
1597 Currently no other actions are performed. Specifically,
1598 file handles are not automatically flushed and objects are
1599 not automatically destroyed.