]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plperl.sgml
c6fdb3bae2b66da6a0a828956eb517b7543ca05d
[postgresql] / doc / src / sgml / plperl.sgml
1 <!--
2 $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.41 2005/06/05 03:16:29 momjian Exp $
3 -->
4
5  <chapter id="plperl">
6   <title>PL/Perl - Perl Procedural Language</title>
7
8   <indexterm zone="plperl">
9    <primary>PL/Perl</primary>
10   </indexterm>
11
12   <indexterm zone="plperl">
13    <primary>Perl</primary>
14   </indexterm>
15
16   <para>
17    PL/Perl is a loadable procedural language that enables you to write
18    <productname>PostgreSQL</productname> functions in the 
19    <ulink url="http://www.perl.com">Perl programming language</ulink>.
20   </para>
21
22   <para>
23    To install PL/Perl in a particular database, use
24    <literal>createlang plperl <replaceable>dbname</></literal>.
25   </para>
26
27   <tip>
28    <para>
29     If a language is installed into <literal>template1</>, all subsequently
30     created databases will have the language installed automatically.
31    </para>
32   </tip>
33
34   <note>
35    <para>
36     Users of source packages must specially enable the build of
37     PL/Perl during the installation process.  (Refer to <xref
38     linkend="install-short"> for more information.)  Users of
39     binary packages might find PL/Perl in a separate subpackage.
40    </para>
41   </note>
42
43  <sect1 id="plperl-funcs">
44   <title>PL/Perl Functions and Arguments</title>
45
46   <para>
47    To create a function in the PL/Perl language, use the standard
48    <xref linkend="sql-createfunction" endterm="sql-createfunction-title">
49    syntax:
50 <programlisting>
51 CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
52     # PL/Perl function body
53 $$ LANGUAGE plperl;
54 </programlisting>
55    The body of the function is ordinary Perl code.
56   </para>
57
58    <para>
59     The syntax of the <command>CREATE FUNCTION</command> command requires
60     the function body to be written as a string constant.  It is usually
61     most convenient to use dollar quoting (see <xref
62     linkend="sql-syntax-dollar-quoting">) for the string constant.
63     If you choose to use regular single-quoted string constant syntax,
64     you must escape single quote marks (<literal>'</>) and backslashes
65     (<literal>\</>) used in the body of the function, typically by
66     doubling them (see <xref linkend="sql-syntax-strings">).
67    </para>
68
69   <para>
70    Arguments and results are handled as in any other Perl subroutine:
71    arguments are passed in <varname>@_</varname>, and a result value
72    is returned with <literal>return</> or as the last expression
73    evaluated in the function.
74   </para>
75
76   <para>
77    For example, a function returning the greater of two integer values
78    could be defined as:
79
80 <programlisting>
81 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
82     if ($_[0] &gt; $_[1]) { return $_[0]; }
83     return $_[1];
84 $$ LANGUAGE plperl;
85 </programlisting>
86   </para>
87
88   <para>
89    If an SQL null value<indexterm><primary>null value</><secondary
90    sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
91    the argument value will appear as <quote>undefined</> in Perl.  The
92    above function definition will not behave very nicely with null
93    inputs (in fact, it will act as though they are zeroes).  We could
94    add <literal>STRICT</> to the function definition to make
95    <productname>PostgreSQL</productname> do something more reasonable:
96    if a null value is passed, the function will not be called at all,
97    but will just return a null result automatically.  Alternatively,
98    we could check for undefined inputs in the function body.  For
99    example, suppose that we wanted <function>perl_max</function> with
100    one null and one nonnull argument to return the nonnull argument,
101    rather than a null value:
102
103 <programlisting>
104 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
105     my ($a,$b) = @_;
106     if (! defined $a) {
107         if (! defined $b) { return undef; }
108         return $b;
109     }
110     if (! defined $b) { return $a; }
111     if ($a &gt; $b) { return $a; }
112     return $b;
113 $$ LANGUAGE plperl;
114 </programlisting>
115    As shown above, to return an SQL null value from a PL/Perl
116    function, return an undefined value.  This can be done whether the
117    function is strict or not.
118   </para>
119
120   <para>
121    Composite-type arguments are passed to the function as references
122    to hashes.  The keys of the hash are the attribute names of the
123    composite type.  Here is an example:
124
125 <programlisting>
126 CREATE TABLE employee (
127     name text,
128     basesalary integer,
129     bonus integer
130 );
131
132 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
133     my ($emp) = @_;
134     return $emp-&gt;{basesalary} + $emp-&gt;{bonus};
135 $$ LANGUAGE plperl;
136
137 SELECT name, empcomp(employee.*) FROM employee;
138 </programlisting>
139   </para>
140
141   <para>
142    A PL/Perl function can return a composite-type result using the same
143    approach: return a reference to a hash that has the required attributes.
144    For example,
145
146 <programlisting>
147 CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
148
149 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
150     return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
151 $$ LANGUAGE plperl;
152
153 SELECT * FROM perl_row();
154 </programlisting>
155
156    Any columns in the declared result data type that are not present in the
157    hash will be returned as NULLs.
158   </para>
159
160   <para>
161    PL/Perl functions can also return sets of either scalar or composite
162    types.  To do this, return a reference to an array that contains
163    either scalars or references to hashes, respectively.  Here are
164    some simple examples:
165
166 <programlisting>
167 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
168 return [0..$_[0]];
169 $$ LANGUAGE plperl;
170
171 SELECT * FROM perl_set_int(5);
172
173
174 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
175     return [
176         { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' },
177         { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' },
178         { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' }
179     ];
180 $$  LANGUAGE plperl;
181
182 SELECT * FROM perl_set();
183 </programlisting>
184
185    When you do this, Perl will have to build the entire array in memory;
186    therefore the technique does not scale to very large result sets. You
187    can instead call <function>return_next</function> for each element of
188    the result set, passing it either a scalar or a reference to a hash,
189    as appropriate to your function's return type.
190   </para>
191
192     <para>
193      <application>PL/Perl</> does not currently have full support for
194      domain types: it treats a domain the same as the underlying scalar
195      type.  This means that constraints associated with the domain will
196      not be enforced.  This is not an issue for function arguments, but
197      it is a hazard if you declare a <application>PL/Perl</> function
198      as returning a domain type.
199     </para>
200  </sect1>
201
202  <sect1 id="plperl-database">
203   <title>Database Access from PL/Perl</title>
204
205   <para>
206    Access to the database itself from your Perl function can be done
207    via the function <function>spi_exec_query</function> described
208    below, or via an experimental module 
209    <ulink url="http://www.cpan.org/modules/by-module/DBD/APILOS/">
210    <literal>DBD::PgSPI</literal></ulink>
211    (also available at <ulink url="http://www.cpan.org/SITES.html">
212    <acronym>CPAN mirror sites</></ulink>).  This module makes available a
213    <acronym>DBI</>-compliant database-handle named
214    <varname>$pg_dbh</varname> that can be used to perform queries with
215    normal <acronym>DBI</>
216    syntax.<indexterm><primary>DBI</></indexterm>
217   </para>
218
219   <para>
220    PL/Perl itself presently provides two additional Perl commands:
221
222    <variablelist>
223     <varlistentry>
224      <indexterm>
225       <primary>spi_exec_query</primary>
226       <secondary>in PL/Perl</secondary>
227      </indexterm>
228
229      <term><literal><function>spi_exec_query</>(<replaceable>query</replaceable> [, <replaceable>max-rows</replaceable>])</literal></term>
230      <term><literal><function>spi_exec_query</>(<replaceable>command</replaceable>)</literal></term>
231      <listitem>
232       <para>
233        Executes an SQL command.  Here is an example of a query
234        (<command>SELECT</command> command) with the optional maximum
235        number of rows:
236 <programlisting>
237 $rv = spi_exec_query('SELECT * FROM my_table', 5);
238 </programlisting>
239         This returns up to 5 rows from the table
240         <literal>my_table</literal>.  If <literal>my_table</literal>
241         has a column <literal>my_column</literal>, you can get that
242         value from row <literal>$i</literal> of the result like this:
243 <programlisting>
244 $foo = $rv-&gt;{rows}[$i]-&gt;{my_column};
245 </programlisting>
246        The total number of rows returned from a <command>SELECT</command>
247        query can be accessed like this:
248 <programlisting>
249 $nrows = $rv-&gt;{processed}
250 </programlisting>
251       </para>
252
253       <para>
254        Here is an example using a different command type:
255 <programlisting>
256 $query = "INSERT INTO my_table VALUES (1, 'test')";
257 $rv = spi_exec_query($query);
258 </programlisting>
259        You can then access the command status (e.g.,
260        <literal>SPI_OK_INSERT</literal>) like this:
261 <programlisting>
262 $res = $rv-&gt;{status};
263 </programlisting>
264        To get the number of rows affected, do:
265 <programlisting>
266 $nrows = $rv-&gt;{processed};
267 </programlisting>
268       </para>
269
270       <para>
271        Here is a complete example:
272 <programlisting>
273 CREATE TABLE test (
274     i int,
275     v varchar
276 );
277
278 INSERT INTO test (i, v) VALUES (1, 'first line');
279 INSERT INTO test (i, v) VALUES (2, 'second line');
280 INSERT INTO test (i, v) VALUES (3, 'third line');
281 INSERT INTO test (i, v) VALUES (4, 'immortal');
282
283 CREATE FUNCTION test_munge() RETURNS SETOF test AS $$
284     my $res = [];
285     my $rv = spi_exec_query('select i, v from test;');
286     my $status = $rv-&gt;{status};
287     my $nrows = $rv-&gt;{processed};
288     foreach my $rn (0 .. $nrows - 1) {
289         my $row = $rv-&gt;{rows}[$rn];
290         $row-&gt;{i} += 200 if defined($row-&gt;{i});
291         $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
292         push @$res, $row;
293     }
294     return $res;
295 $$ LANGUAGE plperl;
296
297 SELECT * FROM test_munge();
298 </programlisting>
299       </para>
300      </listitem>
301     </varlistentry>
302
303     <varlistentry>
304      <indexterm>
305       <primary>elog</primary>
306       <secondary>in PL/Perl</secondary>
307      </indexterm>
308
309      <term><literal><function>elog</>(<replaceable>level</replaceable>, <replaceable>msg</replaceable>)</literal></term>
310      <listitem>
311       <para>
312        Emit a log or error message. Possible levels are
313        <literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
314        <literal>NOTICE</>, <literal>WARNING</>, and <literal>ERROR</>.
315        <literal>ERROR</>
316         raises an error condition; if this is not trapped by the surrounding
317         Perl code, the error propagates out to the calling query, causing
318         the current transaction or subtransaction to be aborted.  This
319         is effectively the same as the Perl <literal>die</> command.
320         The other levels only generate messages of different
321         priority levels.
322         Whether messages of a particular priority are reported to the client,
323         written to the server log, or both is controlled by the
324         <xref linkend="guc-log-min-messages"> and
325         <xref linkend="guc-client-min-messages"> configuration
326         variables. See <xref linkend="runtime-config"> for more
327         information.
328       </para>
329      </listitem>
330     </varlistentry>
331    </variablelist>
332   </para>
333  </sect1>
334
335  <sect1 id="plperl-data">
336   <title>Data Values in PL/Perl</title>
337
338   <para>
339    The argument values supplied to a PL/Perl function's code are
340    simply the input arguments converted to text form (just as if they
341    had been displayed by a <command>SELECT</command> statement).
342    Conversely, the <literal>return</> command will accept any string
343    that is acceptable input format for the function's declared return
344    type.  So, within the PL/Perl function,
345    all values are just text strings.
346   </para>
347  </sect1>
348
349  <sect1 id="plperl-global">
350   <title>Global Values in PL/Perl</title>
351
352   <para>
353     You can use the global hash <varname>%_SHARED</varname> to store
354     data, including code references, between function calls for the
355     lifetime of the current session.
356   </para>
357
358   <para>
359     Here is a simple example for shared data:
360 <programlisting>
361 CREATE OR REPLACE FUNCTION set_var(name text, val text) RETURNS text AS $$
362     if ($_SHARED{$_[0]} = $_[1]) {
363         return 'ok';
364     } else {
365         return "can't set shared variable $_[0] to $_[1]";
366     }
367 $$ LANGUAGE plperl;
368
369 CREATE OR REPLACE FUNCTION get_var(name text) RETURNS text AS $$
370     return $_SHARED{$_[0]};
371 $$ LANGUAGE plperl;
372
373 SELECT set_var('sample', 'Hello, PL/Perl!  How's tricks?');
374 SELECT get_var('sample');
375 </programlisting>
376   </para>
377
378   <para>
379    Here is a slightly more complicated example using a code reference:
380
381 <programlisting>
382 CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
383     $_SHARED{myquote} = sub {
384         my $arg = shift;
385         $arg =~ s/(['\\])/\\$1/g;
386         return "'$arg'";
387     };
388 $$ LANGUAGE plperl;
389
390 SELECT myfuncs(); /* initializes the function */
391
392 /* Set up a function that uses the quote function */
393
394 CREATE OR REPLACE FUNCTION use_quote(TEXT) RETURNS text AS $$
395     my $text_to_quote = shift;
396     my $qfunc = $_SHARED{myquote};
397     return &amp;$qfunc($text_to_quote);
398 $$ LANGUAGE plperl;
399 </programlisting>
400
401    (You could have replaced the above with the one-liner
402    <literal>return $_SHARED{myquote}-&gt;($_[0]);</literal>
403    at the expense of readability.)
404   </para>
405  </sect1>
406
407  <sect1 id="plperl-trusted">
408   <title>Trusted and Untrusted PL/Perl</title>
409
410   <indexterm zone="plperl-trusted">
411    <primary>trusted</primary>
412    <secondary>PL/Perl</secondary>
413   </indexterm>
414
415   <para>
416    Normally, PL/Perl is installed as a <quote>trusted</> programming
417    language named <literal>plperl</>.  In this setup, certain Perl
418    operations are disabled to preserve security.  In general, the
419    operations that are restricted are those that interact with the
420    environment. This includes file handle operations,
421    <literal>require</literal>, and <literal>use</literal> (for
422    external modules).  There is no way to access internals of the
423    database server process or to gain OS-level access with the
424    permissions of the server process,
425    as a C function can do.  Thus, any unprivileged database user may
426    be permitted to use this language.
427   </para>
428
429   <para>
430    Here is an example of a function that will not work because file
431    system operations are not allowed for security reasons:
432 <programlisting>
433 CREATE FUNCTION badfunc() RETURNS integer AS $$
434     open(TEMP, "&gt;/tmp/badfile");
435     print TEMP "Gotcha!\n";
436     return 1;
437 $$ LANGUAGE plperl;
438 </programlisting>
439    The creation of the function will succeed, but executing it will not.
440   </para>
441
442   <para>
443    Sometimes it is desirable to write Perl functions that are not
444    restricted.  For example, one might want a Perl function that sends
445    mail.  To handle these cases, PL/Perl can also be installed as an
446    <quote>untrusted</> language (usually called
447    <application>PL/PerlU</application><indexterm><primary>PL/PerlU</></indexterm>).
448    In this case the full Perl language is available.  If the
449    <command>createlang</command> program is used to install the
450    language, the language name <literal>plperlu</literal> will select
451    the untrusted PL/Perl variant.
452   </para>
453
454   <para>
455    The writer of a <application>PL/PerlU</> function must take care that the function
456    cannot be used to do anything unwanted, since it will be able to do
457    anything that could be done by a user logged in as the database
458    administrator.  Note that the database system allows only database
459    superusers to create functions in untrusted languages.
460   </para>
461
462   <para>
463    If the above function was created by a superuser using the language
464    <literal>plperlu</>, execution would succeed.
465   </para>
466  </sect1>
467
468  <sect1 id="plperl-triggers">
469   <title>PL/Perl Triggers</title>
470
471   <para>
472    PL/Perl can be used to write trigger functions.  In a trigger function,
473    the hash reference <varname>$_TD</varname> contains information about the
474    current trigger event.  The fields of the <varname>$_TD</varname> hash
475    reference are:
476
477    <variablelist>
478     <varlistentry>
479      <term><literal>$_TD-&gt;{new}{foo}</literal></term>
480      <listitem>
481       <para>
482        <literal>NEW</literal> value of column <literal>foo</literal>
483       </para>
484      </listitem>
485     </varlistentry>
486
487     <varlistentry>
488      <term><literal>$_TD-&gt;{old}{foo}</literal></term>
489      <listitem>
490       <para>
491        <literal>OLD</literal> value of column <literal>foo</literal>
492       </para>
493      </listitem>
494     </varlistentry>
495
496     <varlistentry>
497      <term><literal>$_TD-&gt;{name}</literal></term>
498      <listitem>
499       <para>
500        Name of the trigger being called
501       </para>
502      </listitem>
503     </varlistentry>
504
505     <varlistentry>
506      <term><literal>$_TD-&gt;{event}</literal></term>
507      <listitem>
508       <para>
509        Trigger event: <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>, or <literal>UNKNOWN</>
510       </para>
511      </listitem>
512     </varlistentry>
513
514     <varlistentry>
515      <term><literal>$_TD-&gt;{when}</literal></term>
516      <listitem>
517       <para>
518        When the trigger was called: <literal>BEFORE</literal>, <literal>AFTER</literal>, or <literal>UNKNOWN</literal>
519       </para>
520      </listitem>
521     </varlistentry>
522
523     <varlistentry>
524      <term><literal>$_TD-&gt;{level}</literal></term>
525      <listitem>
526       <para>
527        The trigger level: <literal>ROW</literal>, <literal>STATEMENT</literal>, or <literal>UNKNOWN</literal>
528       </para>
529      </listitem>
530     </varlistentry>
531
532     <varlistentry>
533      <term><literal>$_TD-&gt;{relid}</literal></term>
534      <listitem>
535       <para>
536        OID of the table on which the trigger fired
537       </para>
538      </listitem>
539     </varlistentry>
540
541     <varlistentry>
542      <term><literal>$_TD-&gt;{relname}</literal></term>
543      <listitem>
544       <para>
545        Name of the table on which the trigger fired
546       </para>
547      </listitem>
548     </varlistentry>
549
550     <varlistentry>
551      <term><literal>$_TD-&gt;{argc}</literal></term>
552      <listitem>
553       <para>
554        Number of arguments of the trigger function
555       </para>
556      </listitem>
557     </varlistentry>
558
559     <varlistentry>
560      <term><literal>@{$_TD-&gt;{args}}</literal></term>
561      <listitem>
562       <para>
563        Arguments of the trigger function.  Does not exist if $_TD-&gt;{argc} is 0.
564       </para>
565      </listitem>
566     </varlistentry>
567
568    </variablelist>
569   </para>
570
571   <para>
572    Triggers can return one of the following:
573
574    <variablelist>
575     <varlistentry>
576      <term><literal>return;</literal></term>
577      <listitem>
578       <para>
579        Execute the statement
580       </para>
581      </listitem>
582     </varlistentry>
583
584     <varlistentry>
585      <term><literal>"SKIP"</literal></term>
586      <listitem>
587       <para>
588        Don't execute the statement
589       </para>
590      </listitem>
591     </varlistentry>
592
593     <varlistentry>
594      <term><literal>"MODIFY"</literal></term>
595      <listitem>
596       <para>
597        Indicates that the <literal>NEW</literal> row was modified by
598        the trigger function
599       </para>
600      </listitem>
601     </varlistentry>
602    </variablelist>
603   </para>
604
605   <para>
606    Here is an example of a trigger function, illustrating some of the
607    above:
608 <programlisting>
609 CREATE TABLE test (
610     i int,
611     v varchar
612 );
613
614 CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
615     if (($_TD-&gt;{new}{i} &gt;= 100) || ($_TD-&gt;{new}{i} &lt;= 0)) {
616         return "SKIP";    # skip INSERT/UPDATE command
617     } elsif ($_TD-&gt;{new}{v} ne "immortal") {
618         $_TD-&gt;{new}{v} .= "(modified by trigger)";
619         return "MODIFY";  # modify row and execute INSERT/UPDATE command
620     } else {
621         return;           # execute INSERT/UPDATE command
622     }
623 $$ LANGUAGE plperl;
624
625 CREATE TRIGGER test_valid_id_trig
626     BEFORE INSERT OR UPDATE ON test
627     FOR EACH ROW EXECUTE PROCEDURE valid_id();
628 </programlisting>
629   </para>
630  </sect1>
631
632  <sect1 id="plperl-missing">
633   <title>Limitations and Missing Features</title>
634
635   <para>
636    The following features are currently missing from PL/Perl, but they
637    would make welcome contributions.
638
639    <itemizedlist>
640     <listitem>
641      <para>
642       PL/Perl functions cannot call each other directly (because they
643       are anonymous subroutines inside Perl).
644      </para>
645     </listitem>
646
647     <listitem>
648      <para>
649       SPI is not yet fully implemented.
650      </para>
651     </listitem>
652
653     <listitem>
654      <para>
655       In the current implementation, if you are fetching or returning
656       very large data sets, you should be aware that these will all go
657       into memory.
658      </para>
659     </listitem>
660    </itemizedlist>
661   </para>
662  </sect1>
663
664 </chapter>
665
666 <!-- Keep this comment at the end of the file
667 Local variables:
668 mode:sgml
669 sgml-omittag:nil
670 sgml-shorttag:t
671 sgml-minimize-attributes:nil
672 sgml-always-quote-attributes:t
673 sgml-indent-step:1
674 sgml-indent-data:t
675 sgml-parent-document:nil
676 sgml-default-dtd-file:"./reference.ced"
677 sgml-exposed-tags:nil
678 sgml-local-catalogs:("/usr/lib/sgml/catalog")
679 sgml-local-ecat-files:nil
680 End:
681 -->