]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plperl.sgml
d6f42f294a5023ccf54c7c8134506db9402728f4
[postgresql] / doc / src / sgml / plperl.sgml
1 <!--
2 $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.47 2005/10/18 22:53:54 adunstan 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
51 <programlisting>
52 CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
53     # PL/Perl function body
54 $$ LANGUAGE plperl;
55 </programlisting>
56    The body of the function is ordinary Perl code. In fact, the PL/Perl
57    glue code wraps it inside a Perl subroutine. A PL/Perl function must
58    always return a scalar value.  You can return more complex structures
59    (arrays, records, and sets) by returning a reference, as discussed below.
60    Never return a list.
61   </para>
62
63   <note>
64    <para>
65     The use of named nested subroutines is dangerous in Perl, especially if
66     they refer to lexical variables in the enclosing scope. Because a PL/Perl
67     function is wrapped in a subroutine, any named subroutine you create will
68     be nested. In general, it is far safer to create anonymous subroutines
69     which you call via a coderef. See the <literal>perldiag</literal>
70     man page for more details.
71    </para>
72   </note>
73
74   <para>
75    The syntax of the <command>CREATE FUNCTION</command> command requires
76    the function body to be written as a string constant.  It is usually
77    most convenient to use dollar quoting (see <xref
78    linkend="sql-syntax-dollar-quoting">) for the string constant.
79    If you choose to use regular single-quoted string constant syntax,
80    you must escape single quote marks (<literal>'</>) and backslashes
81    (<literal>\</>) used in the body of the function, typically by
82    doubling them (see <xref linkend="sql-syntax-strings">).
83   </para>
84
85   <para>
86    Arguments and results are handled as in any other Perl subroutine:
87    arguments are passed in <varname>@_</varname>, and a result value
88    is returned with <literal>return</> or as the last expression
89    evaluated in the function.
90   </para>
91
92   <para>
93    For example, a function returning the greater of two integer values
94    could be defined as:
95
96 <programlisting>
97 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
98     if ($_[0] &gt; $_[1]) { return $_[0]; }
99     return $_[1];
100 $$ LANGUAGE plperl;
101 </programlisting>
102   </para>
103
104   <para>
105    If an SQL null value<indexterm><primary>null value</><secondary
106    sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
107    the argument value will appear as <quote>undefined</> in Perl.  The
108    above function definition will not behave very nicely with null
109    inputs (in fact, it will act as though they are zeroes).  We could
110    add <literal>STRICT</> to the function definition to make
111    <productname>PostgreSQL</productname> do something more reasonable:
112    if a null value is passed, the function will not be called at all,
113    but will just return a null result automatically.  Alternatively,
114    we could check for undefined inputs in the function body.  For
115    example, suppose that we wanted <function>perl_max</function> with
116    one null and one nonnull argument to return the nonnull argument,
117    rather than a null value:
118
119 <programlisting>
120 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
121     my ($x,$y) = @_;
122     if (! defined $x) {
123         if (! defined $y) { return undef; }
124         return $y;
125     }
126     if (! defined $y) { return $x; }
127     if ($x &gt; $y) { return $x; }
128     return $y;
129 $$ LANGUAGE plperl;
130 </programlisting>
131    As shown above, to return an SQL null value from a PL/Perl
132    function, return an undefined value.  This can be done whether the
133    function is strict or not.
134   </para>
135
136   <para>
137    Perl can return <productname>PostgreSQL</productname> arrays as
138    references to Perl arrays.  Here is an example:
139
140 <programlisting>
141 CREATE OR REPLACE function returns_array()
142 RETURNS text[][] AS $$
143     return [['a"b','c,d'],['e\\f','g']];
144 $$ LANGUAGE plperl;
145
146 select returns_array();
147 </programlisting>
148   </para>
149
150   <para>
151    Composite-type arguments are passed to the function as references
152    to hashes.  The keys of the hash are the attribute names of the
153    composite type.  Here is an example:
154
155 <programlisting>
156 CREATE TABLE employee (
157     name text,
158     basesalary integer,
159     bonus integer
160 );
161
162 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
163     my ($emp) = @_;
164     return $emp-&gt;{basesalary} + $emp-&gt;{bonus};
165 $$ LANGUAGE plperl;
166
167 SELECT name, empcomp(employee.*) FROM employee;
168 </programlisting>
169   </para>
170
171   <para>
172    A PL/Perl function can return a composite-type result using the same
173    approach: return a reference to a hash that has the required attributes.
174    For example,
175
176 <programlisting>
177 CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
178
179 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
180     return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
181 $$ LANGUAGE plperl;
182
183 SELECT * FROM perl_row();
184 </programlisting>
185
186    Any columns in the declared result data type that are not present in the
187    hash will be returned as NULLs.
188   </para>
189
190   <para>
191     PL/Perl functions can also return sets of either scalar or
192     composite types.  Usually you'll want to return rows one at a
193     time, both to speed up startup time and to keep from queueing up
194     the entire result set in memory.  You can do this with
195     <function>return_next</function> as illustrated below.  Note that
196     after the last <function>return_next</function>, you must put
197     either <literal>return</literal> or (better) <literal>return
198     undef</literal>.
199
200 <programlisting>
201 CREATE OR REPLACE FUNCTION perl_set_int(int)
202 RETURNS SETOF INTEGER AS $$
203     foreach (0..$_[0]) {
204         return_next($_);
205     }
206     return undef;
207 $$ LANGUAGE plperl;
208
209 SELECT * FROM perl_set_int(5);
210
211 CREATE OR REPLACE FUNCTION perl_set()
212 RETURNS SETOF testrowperl AS $$
213     return_next({ f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' });
214     return_next({ f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' });
215     return_next({ f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' });
216     return undef;
217 $$ LANGUAGE plperl;
218 </programlisting>
219
220     For small result sets, you can return a reference to an array that
221     contains either scalars, references to arrays, or references to
222     hashes for simple types, array types, and composite types,
223     respectively.  Here are some simple examples of returning the entire
224     result set as an array reference:
225
226 <programlisting>
227 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
228     return [0..$_[0]];
229 $$ LANGUAGE plperl;
230
231 SELECT * FROM perl_set_int(5);
232
233 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
234     return [
235         { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' },
236         { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' },
237         { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' }
238     ];
239 $$ LANGUAGE plperl;
240
241 SELECT * FROM perl_set();
242 </programlisting>
243
244   </para>
245
246     <para>
247      <application>PL/Perl</> does not currently have full support for
248      domain types: it treats a domain the same as the underlying scalar
249      type.  This means that constraints associated with the domain will
250      not be enforced.  This is not an issue for function arguments, but
251      it is a hazard if you declare a <application>PL/Perl</> function
252      as returning a domain type.
253     </para>
254
255   <para>
256    If you wish to use the <literal>strict</> pragma with your code,
257    the easiest way to do so is to <command>SET</>
258    <literal>plperl.use_strict</literal> to true.  This parameter affects
259    subsequent compilations of <application>PL/Perl</> functions, but not
260    functions already compiled in the current session.  To set the
261    parameter before <application>PL/Perl</> has been loaded, it is
262    necessary to have added <quote><literal>plperl</></> to the <xref
263    linkend="guc-custom-variable-classes"> list in
264    <filename>postgresql.conf</filename>.
265   </para>
266
267   <para>
268    Another way to use the <literal>strict</> pragma is to put
269 <programlisting>
270 use strict;
271 </programlisting>
272    in the function body.  But this only works in <application>PL/PerlU</>
273    functions, since <literal>use</> is not a trusted operation.  In
274    <application>PL/Perl</> functions you can instead do
275 <programlisting>
276 BEGIN { strict->import(); }
277 </programlisting>
278   </para>
279  </sect1>
280
281  <sect1 id="plperl-database">
282   <title>Database Access from PL/Perl</title>
283
284   <para>
285    Access to the database itself from your Perl function can be done
286    via the function <function>spi_exec_query</function> described
287    below, or via an experimental module 
288    <ulink url="http://www.cpan.org/modules/by-module/DBD/APILOS/">
289    <literal>DBD::PgSPI</literal></ulink>
290    (also available at <ulink url="http://www.cpan.org/SITES.html">
291    <acronym>CPAN mirror sites</></ulink>).  This module makes available a
292    <acronym>DBI</>-compliant database-handle named
293    <varname>$pg_dbh</varname> that can be used to perform queries with
294    normal <acronym>DBI</>
295    syntax.<indexterm><primary>DBI</></indexterm>
296   </para>
297
298   <para>
299    PL/Perl provides three additional Perl commands:
300
301    <variablelist>
302     <varlistentry>
303      <indexterm>
304       <primary>spi_exec_query</primary>
305       <secondary>in PL/Perl</secondary>
306      </indexterm>
307
308      <term><literal><function>spi_exec_query</>(<replaceable>query</replaceable> [, <replaceable>max-rows</replaceable>])</literal></term>
309      <term><literal><function>spi_exec_query</>(<replaceable>command</replaceable>)</literal></term>
310      <term><literal><function>spi_query</>(<replaceable>command</replaceable>)</literal></term>
311      <term><literal><function>spi_fetchrow</>(<replaceable>command</replaceable>)</literal></term>
312
313      <listitem>
314       <para>
315        <literal>spi_exec_query</literal> executes an SQL command and
316 returns the entire rowset as a reference to an array of hash
317 references.  <emphasis>You should only use this command when you know
318 that the result set will be relatively small.</emphasis>  Here is an
319 example of a query (<command>SELECT</command> command) with the
320 optional maximum number of rows:
321
322 <programlisting>
323 $rv = spi_exec_query('SELECT * FROM my_table', 5);
324 </programlisting>
325         This returns up to 5 rows from the table
326         <literal>my_table</literal>.  If <literal>my_table</literal>
327         has a column <literal>my_column</literal>, you can get that
328         value from row <literal>$i</literal> of the result like this:
329 <programlisting>
330 $foo = $rv-&gt;{rows}[$i]-&gt;{my_column};
331 </programlisting>
332        The total number of rows returned from a <command>SELECT</command>
333        query can be accessed like this:
334 <programlisting>
335 $nrows = $rv-&gt;{processed}
336 </programlisting>
337       </para>
338
339       <para>
340        Here is an example using a different command type:
341 <programlisting>
342 $query = "INSERT INTO my_table VALUES (1, 'test')";
343 $rv = spi_exec_query($query);
344 </programlisting>
345        You can then access the command status (e.g.,
346        <literal>SPI_OK_INSERT</literal>) like this:
347 <programlisting>
348 $res = $rv-&gt;{status};
349 </programlisting>
350        To get the number of rows affected, do:
351 <programlisting>
352 $nrows = $rv-&gt;{processed};
353 </programlisting>
354       </para>
355
356       <para>
357        Here is a complete example:
358 <programlisting>
359 CREATE TABLE test (
360     i int,
361     v varchar
362 );
363
364 INSERT INTO test (i, v) VALUES (1, 'first line');
365 INSERT INTO test (i, v) VALUES (2, 'second line');
366 INSERT INTO test (i, v) VALUES (3, 'third line');
367 INSERT INTO test (i, v) VALUES (4, 'immortal');
368
369 CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
370     my $rv = spi_exec_query('select i, v from test;');
371     my $status = $rv-&gt;{status};
372     my $nrows = $rv-&gt;{processed};
373     foreach my $rn (0 .. $nrows - 1) {
374         my $row = $rv-&gt;{rows}[$rn];
375         $row-&gt;{i} += 200 if defined($row-&gt;{i});
376         $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
377         return_next($row);
378     }
379     return undef;
380 $$ LANGUAGE plperl;
381
382 SELECT * FROM test_munge();
383 </programlisting>
384     </para>
385     <para>
386     <literal>spi_query</literal> and <literal>spi_fetchrow</literal>
387     work together as a pair for rowsets which may be large, or for cases
388     where you wish to return rows as they arrive.
389     <literal>spi_fetchrow</literal> works <emphasis>only</emphasis> with
390     <literal>spi_query</literal>. The following example illustrates how
391     you use them together:
392
393 <programlisting>
394 CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
395
396 CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
397     use Digest::MD5 qw(md5_hex);
398     my $file = '/usr/share/dict/words';
399     my $t = localtime;
400     elog(NOTICE, "opening file $file at $t" );
401     open my $fh, '&lt;', $file # ooh, it's a file access!
402         or elog(ERROR, "Can't open $file for reading: $!");
403     my @words = &lt;$fh&gt;;
404     close $fh;
405     $t = localtime;
406     elog(NOTICE, "closed file $file at $t");
407     chomp(@words);
408     my $row;
409     my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
410     while (defined ($row = spi_fetchrow($sth))) {
411         return_next({
412             the_num =&gt; $row-&gt;{a},
413             the_text =&gt; md5_hex($words[rand @words])
414         });
415     }
416     return;
417 $$ LANGUAGE plperlu;
418
419 SELECT * from lotsa_md5(500);
420 </programlisting>
421     </para>
422
423      </listitem>
424     </varlistentry>
425
426     <varlistentry>
427      <indexterm>
428       <primary>elog</primary>
429       <secondary>in PL/Perl</secondary>
430      </indexterm>
431
432      <term><literal><function>elog</>(<replaceable>level</replaceable>, <replaceable>msg</replaceable>)</literal></term>
433      <listitem>
434       <para>
435        Emit a log or error message. Possible levels are
436        <literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
437        <literal>NOTICE</>, <literal>WARNING</>, and <literal>ERROR</>.
438        <literal>ERROR</>
439         raises an error condition; if this is not trapped by the surrounding
440         Perl code, the error propagates out to the calling query, causing
441         the current transaction or subtransaction to be aborted.  This
442         is effectively the same as the Perl <literal>die</> command.
443         The other levels only generate messages of different
444         priority levels.
445         Whether messages of a particular priority are reported to the client,
446         written to the server log, or both is controlled by the
447         <xref linkend="guc-log-min-messages"> and
448         <xref linkend="guc-client-min-messages"> configuration
449         variables. See <xref linkend="runtime-config"> for more
450         information.
451       </para>
452      </listitem>
453     </varlistentry>
454    </variablelist>
455   </para>
456  </sect1>
457
458  <sect1 id="plperl-data">
459   <title>Data Values in PL/Perl</title>
460
461   <para>
462    The argument values supplied to a PL/Perl function's code are
463    simply the input arguments converted to text form (just as if they
464    had been displayed by a <command>SELECT</command> statement).
465    Conversely, the <literal>return</> command will accept any string
466    that is acceptable input format for the function's declared return
467    type.  So, within the PL/Perl function,
468    all values are just text strings.
469   </para>
470  </sect1>
471
472  <sect1 id="plperl-global">
473   <title>Global Values in PL/Perl</title>
474
475   <para>
476     You can use the global hash <varname>%_SHARED</varname> to store
477     data, including code references, between function calls for the
478     lifetime of the current session.
479   </para>
480
481   <para>
482     Here is a simple example for shared data:
483 <programlisting>
484 CREATE OR REPLACE FUNCTION set_var(name text, val text) RETURNS text AS $$
485     if ($_SHARED{$_[0]} = $_[1]) {
486         return 'ok';
487     } else {
488         return "can't set shared variable $_[0] to $_[1]";
489     }
490 $$ LANGUAGE plperl;
491
492 CREATE OR REPLACE FUNCTION get_var(name text) RETURNS text AS $$
493     return $_SHARED{$_[0]};
494 $$ LANGUAGE plperl;
495
496 SELECT set_var('sample', 'Hello, PL/Perl!  How's tricks?');
497 SELECT get_var('sample');
498 </programlisting>
499   </para>
500
501   <para>
502    Here is a slightly more complicated example using a code reference:
503
504 <programlisting>
505 CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
506     $_SHARED{myquote} = sub {
507         my $arg = shift;
508         $arg =~ s/(['\\])/\\$1/g;
509         return "'$arg'";
510     };
511 $$ LANGUAGE plperl;
512
513 SELECT myfuncs(); /* initializes the function */
514
515 /* Set up a function that uses the quote function */
516
517 CREATE OR REPLACE FUNCTION use_quote(TEXT) RETURNS text AS $$
518     my $text_to_quote = shift;
519     my $qfunc = $_SHARED{myquote};
520     return &amp;$qfunc($text_to_quote);
521 $$ LANGUAGE plperl;
522 </programlisting>
523
524    (You could have replaced the above with the one-liner
525    <literal>return $_SHARED{myquote}-&gt;($_[0]);</literal>
526    at the expense of readability.)
527   </para>
528  </sect1>
529
530  <sect1 id="plperl-trusted">
531   <title>Trusted and Untrusted PL/Perl</title>
532
533   <indexterm zone="plperl-trusted">
534    <primary>trusted</primary>
535    <secondary>PL/Perl</secondary>
536   </indexterm>
537
538   <para>
539    Normally, PL/Perl is installed as a <quote>trusted</> programming
540    language named <literal>plperl</>.  In this setup, certain Perl
541    operations are disabled to preserve security.  In general, the
542    operations that are restricted are those that interact with the
543    environment. This includes file handle operations,
544    <literal>require</literal>, and <literal>use</literal> (for
545    external modules).  There is no way to access internals of the
546    database server process or to gain OS-level access with the
547    permissions of the server process,
548    as a C function can do.  Thus, any unprivileged database user may
549    be permitted to use this language.
550   </para>
551
552   <para>
553    Here is an example of a function that will not work because file
554    system operations are not allowed for security reasons:
555 <programlisting>
556 CREATE FUNCTION badfunc() RETURNS integer AS $$
557     open(TEMP, "&gt;/tmp/badfile");
558     print TEMP "Gotcha!\n";
559     return 1;
560 $$ LANGUAGE plperl;
561 </programlisting>
562    The creation of the function will succeed, but executing it will not.
563   </para>
564
565   <para>
566    Sometimes it is desirable to write Perl functions that are not
567    restricted.  For example, one might want a Perl function that sends
568    mail.  To handle these cases, PL/Perl can also be installed as an
569    <quote>untrusted</> language (usually called
570    <application>PL/PerlU</application><indexterm><primary>PL/PerlU</></indexterm>).
571    In this case the full Perl language is available.  If the
572    <command>createlang</command> program is used to install the
573    language, the language name <literal>plperlu</literal> will select
574    the untrusted PL/Perl variant.
575   </para>
576
577   <para>
578    The writer of a <application>PL/PerlU</> function must take care that the function
579    cannot be used to do anything unwanted, since it will be able to do
580    anything that could be done by a user logged in as the database
581    administrator.  Note that the database system allows only database
582    superusers to create functions in untrusted languages.
583   </para>
584
585   <para>
586    If the above function was created by a superuser using the language
587    <literal>plperlu</>, execution would succeed.
588   </para>
589  </sect1>
590
591  <sect1 id="plperl-triggers">
592   <title>PL/Perl Triggers</title>
593
594   <para>
595    PL/Perl can be used to write trigger functions.  In a trigger function,
596    the hash reference <varname>$_TD</varname> contains information about the
597    current trigger event.  The fields of the <varname>$_TD</varname> hash
598    reference are:
599
600    <variablelist>
601     <varlistentry>
602      <term><literal>$_TD-&gt;{new}{foo}</literal></term>
603      <listitem>
604       <para>
605        <literal>NEW</literal> value of column <literal>foo</literal>
606       </para>
607      </listitem>
608     </varlistentry>
609
610     <varlistentry>
611      <term><literal>$_TD-&gt;{old}{foo}</literal></term>
612      <listitem>
613       <para>
614        <literal>OLD</literal> value of column <literal>foo</literal>
615       </para>
616      </listitem>
617     </varlistentry>
618
619     <varlistentry>
620      <term><literal>$_TD-&gt;{name}</literal></term>
621      <listitem>
622       <para>
623        Name of the trigger being called
624       </para>
625      </listitem>
626     </varlistentry>
627
628     <varlistentry>
629      <term><literal>$_TD-&gt;{event}</literal></term>
630      <listitem>
631       <para>
632        Trigger event: <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>, or <literal>UNKNOWN</>
633       </para>
634      </listitem>
635     </varlistentry>
636
637     <varlistentry>
638      <term><literal>$_TD-&gt;{when}</literal></term>
639      <listitem>
640       <para>
641        When the trigger was called: <literal>BEFORE</literal>, <literal>AFTER</literal>, or <literal>UNKNOWN</literal>
642       </para>
643      </listitem>
644     </varlistentry>
645
646     <varlistentry>
647      <term><literal>$_TD-&gt;{level}</literal></term>
648      <listitem>
649       <para>
650        The trigger level: <literal>ROW</literal>, <literal>STATEMENT</literal>, or <literal>UNKNOWN</literal>
651       </para>
652      </listitem>
653     </varlistentry>
654
655     <varlistentry>
656      <term><literal>$_TD-&gt;{relid}</literal></term>
657      <listitem>
658       <para>
659        OID of the table on which the trigger fired
660       </para>
661      </listitem>
662     </varlistentry>
663
664     <varlistentry>
665      <term><literal>$_TD-&gt;{relname}</literal></term>
666      <listitem>
667       <para>
668        Name of the table on which the trigger fired
669       </para>
670      </listitem>
671     </varlistentry>
672
673     <varlistentry>
674      <term><literal>$_TD-&gt;{argc}</literal></term>
675      <listitem>
676       <para>
677        Number of arguments of the trigger function
678       </para>
679      </listitem>
680     </varlistentry>
681
682     <varlistentry>
683      <term><literal>@{$_TD-&gt;{args}}</literal></term>
684      <listitem>
685       <para>
686        Arguments of the trigger function.  Does not exist if $_TD-&gt;{argc} is 0.
687       </para>
688      </listitem>
689     </varlistentry>
690
691    </variablelist>
692   </para>
693
694   <para>
695    Triggers can return one of the following:
696
697    <variablelist>
698     <varlistentry>
699      <term><literal>return;</literal></term>
700      <listitem>
701       <para>
702        Execute the statement
703       </para>
704      </listitem>
705     </varlistentry>
706
707     <varlistentry>
708      <term><literal>"SKIP"</literal></term>
709      <listitem>
710       <para>
711        Don't execute the statement
712       </para>
713      </listitem>
714     </varlistentry>
715
716     <varlistentry>
717      <term><literal>"MODIFY"</literal></term>
718      <listitem>
719       <para>
720        Indicates that the <literal>NEW</literal> row was modified by
721        the trigger function
722       </para>
723      </listitem>
724     </varlistentry>
725    </variablelist>
726   </para>
727
728   <para>
729    Here is an example of a trigger function, illustrating some of the
730    above:
731 <programlisting>
732 CREATE TABLE test (
733     i int,
734     v varchar
735 );
736
737 CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
738     if (($_TD-&gt;{new}{i} &gt;= 100) || ($_TD-&gt;{new}{i} &lt;= 0)) {
739         return "SKIP";    # skip INSERT/UPDATE command
740     } elsif ($_TD-&gt;{new}{v} ne "immortal") {
741         $_TD-&gt;{new}{v} .= "(modified by trigger)";
742         return "MODIFY";  # modify row and execute INSERT/UPDATE command
743     } else {
744         return;           # execute INSERT/UPDATE command
745     }
746 $$ LANGUAGE plperl;
747
748 CREATE TRIGGER test_valid_id_trig
749     BEFORE INSERT OR UPDATE ON test
750     FOR EACH ROW EXECUTE PROCEDURE valid_id();
751 </programlisting>
752   </para>
753  </sect1>
754
755  <sect1 id="plperl-missing">
756   <title>Limitations and Missing Features</title>
757
758   <para>
759    The following features are currently missing from PL/Perl, but they
760    would make welcome contributions.
761
762    <itemizedlist>
763     <listitem>
764      <para>
765       PL/Perl functions cannot call each other directly (because they
766       are anonymous subroutines inside Perl).
767      </para>
768     </listitem>
769
770     <listitem>
771      <para>
772       SPI is not yet fully implemented.
773      </para>
774     </listitem>
775
776     <listitem>
777      <para>
778       If you are fetching very large data sets using
779       <literal>spi_exec_query</literal>, you should be aware that
780       these will all go into memory.  You can avoid this by using
781       <literal>spi_query</literal>/<literal>spi_fetchrow</literal> as
782       illustrated earlier.
783      </para>
784      <para>
785         A similar problem occurs if a set-returning function passes a
786         large set of rows back to postgres via <literal>return</literal>. You
787         can avoid this problem too by instead using
788         <literal>return_next</literal> for each row returned, as shown
789         previously.
790      </para>
791
792     </listitem>
793    </itemizedlist>
794   </para>
795  </sect1>
796
797 </chapter>
798
799 <!-- Keep this comment at the end of the file
800 Local variables:
801 mode:sgml
802 sgml-omittag:nil
803 sgml-shorttag:t
804 sgml-minimize-attributes:nil
805 sgml-always-quote-attributes:t
806 sgml-indent-step:1
807 sgml-indent-data:t
808 sgml-parent-document:nil
809 sgml-default-dtd-file:"./reference.ced"
810 sgml-exposed-tags:nil
811 sgml-local-catalogs:("/usr/lib/sgml/catalog")
812 sgml-local-ecat-files:nil
813 End:
814 -->