OSDN Git Service

Spellchecking run, final cleanups
[pg-rex/syncrep.git] / doc / src / sgml / plperl.sgml
1 <!--
2 $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.49 2005/11/04 23:14:00 petere 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 row set 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 row sets 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     my $tmpfile = "/tmp/badfile";
558     open my $fh, '&gt;', $tmpfile
559         or elog(ERROR, qq{Could not open the file "$tmpfile": $!});
560     print $fh "Testing writing to a file\n";
561     close $fh or elog(ERROR, qq{Could not close the file "$tmpfile": $!});
562     return 1;
563 $$ LANGUAGE plperl;
564 </programlisting>
565         The creation of this function will fail as its use of a forbidden
566         operation will be be caught by the validator.
567   </para>
568
569   <para>
570    Sometimes it is desirable to write Perl functions that are not
571    restricted.  For example, one might want a Perl function that sends
572    mail.  To handle these cases, PL/Perl can also be installed as an
573    <quote>untrusted</> language (usually called
574    <application>PL/PerlU</application><indexterm><primary>PL/PerlU</></indexterm>).
575    In this case the full Perl language is available.  If the
576    <command>createlang</command> program is used to install the
577    language, the language name <literal>plperlu</literal> will select
578    the untrusted PL/Perl variant.
579   </para>
580
581   <para>
582    The writer of a <application>PL/PerlU</> function must take care that the function
583    cannot be used to do anything unwanted, since it will be able to do
584    anything that could be done by a user logged in as the database
585    administrator.  Note that the database system allows only database
586    superusers to create functions in untrusted languages.
587   </para>
588
589   <para>
590    If the above function was created by a superuser using the language
591    <literal>plperlu</>, execution would succeed.
592   </para>
593  </sect1>
594
595  <sect1 id="plperl-triggers">
596   <title>PL/Perl Triggers</title>
597
598   <para>
599    PL/Perl can be used to write trigger functions.  In a trigger function,
600    the hash reference <varname>$_TD</varname> contains information about the
601    current trigger event.  The fields of the <varname>$_TD</varname> hash
602    reference are:
603
604    <variablelist>
605     <varlistentry>
606      <term><literal>$_TD-&gt;{new}{foo}</literal></term>
607      <listitem>
608       <para>
609        <literal>NEW</literal> value of column <literal>foo</literal>
610       </para>
611      </listitem>
612     </varlistentry>
613
614     <varlistentry>
615      <term><literal>$_TD-&gt;{old}{foo}</literal></term>
616      <listitem>
617       <para>
618        <literal>OLD</literal> value of column <literal>foo</literal>
619       </para>
620      </listitem>
621     </varlistentry>
622
623     <varlistentry>
624      <term><literal>$_TD-&gt;{name}</literal></term>
625      <listitem>
626       <para>
627        Name of the trigger being called
628       </para>
629      </listitem>
630     </varlistentry>
631
632     <varlistentry>
633      <term><literal>$_TD-&gt;{event}</literal></term>
634      <listitem>
635       <para>
636        Trigger event: <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>, or <literal>UNKNOWN</>
637       </para>
638      </listitem>
639     </varlistentry>
640
641     <varlistentry>
642      <term><literal>$_TD-&gt;{when}</literal></term>
643      <listitem>
644       <para>
645        When the trigger was called: <literal>BEFORE</literal>, <literal>AFTER</literal>, or <literal>UNKNOWN</literal>
646       </para>
647      </listitem>
648     </varlistentry>
649
650     <varlistentry>
651      <term><literal>$_TD-&gt;{level}</literal></term>
652      <listitem>
653       <para>
654        The trigger level: <literal>ROW</literal>, <literal>STATEMENT</literal>, or <literal>UNKNOWN</literal>
655       </para>
656      </listitem>
657     </varlistentry>
658
659     <varlistentry>
660      <term><literal>$_TD-&gt;{relid}</literal></term>
661      <listitem>
662       <para>
663        OID of the table on which the trigger fired
664       </para>
665      </listitem>
666     </varlistentry>
667
668     <varlistentry>
669      <term><literal>$_TD-&gt;{relname}</literal></term>
670      <listitem>
671       <para>
672        Name of the table on which the trigger fired
673       </para>
674      </listitem>
675     </varlistentry>
676
677     <varlistentry>
678      <term><literal>$_TD-&gt;{argc}</literal></term>
679      <listitem>
680       <para>
681        Number of arguments of the trigger function
682       </para>
683      </listitem>
684     </varlistentry>
685
686     <varlistentry>
687      <term><literal>@{$_TD-&gt;{args}}</literal></term>
688      <listitem>
689       <para>
690        Arguments of the trigger function.  Does not exist if <literal>$_TD-&gt;{argc}</literal> is 0.
691       </para>
692      </listitem>
693     </varlistentry>
694
695    </variablelist>
696   </para>
697
698   <para>
699    Triggers can return one of the following:
700
701    <variablelist>
702     <varlistentry>
703      <term><literal>return;</literal></term>
704      <listitem>
705       <para>
706        Execute the statement
707       </para>
708      </listitem>
709     </varlistentry>
710
711     <varlistentry>
712      <term><literal>"SKIP"</literal></term>
713      <listitem>
714       <para>
715        Don't execute the statement
716       </para>
717      </listitem>
718     </varlistentry>
719
720     <varlistentry>
721      <term><literal>"MODIFY"</literal></term>
722      <listitem>
723       <para>
724        Indicates that the <literal>NEW</literal> row was modified by
725        the trigger function
726       </para>
727      </listitem>
728     </varlistentry>
729    </variablelist>
730   </para>
731
732   <para>
733    Here is an example of a trigger function, illustrating some of the
734    above:
735 <programlisting>
736 CREATE TABLE test (
737     i int,
738     v varchar
739 );
740
741 CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
742     if (($_TD-&gt;{new}{i} &gt;= 100) || ($_TD-&gt;{new}{i} &lt;= 0)) {
743         return "SKIP";    # skip INSERT/UPDATE command
744     } elsif ($_TD-&gt;{new}{v} ne "immortal") {
745         $_TD-&gt;{new}{v} .= "(modified by trigger)";
746         return "MODIFY";  # modify row and execute INSERT/UPDATE command
747     } else {
748         return;           # execute INSERT/UPDATE command
749     }
750 $$ LANGUAGE plperl;
751
752 CREATE TRIGGER test_valid_id_trig
753     BEFORE INSERT OR UPDATE ON test
754     FOR EACH ROW EXECUTE PROCEDURE valid_id();
755 </programlisting>
756   </para>
757  </sect1>
758
759  <sect1 id="plperl-missing">
760   <title>Limitations and Missing Features</title>
761
762   <para>
763    The following features are currently missing from PL/Perl, but they
764    would make welcome contributions.
765
766    <itemizedlist>
767     <listitem>
768      <para>
769       PL/Perl functions cannot call each other directly (because they
770       are anonymous subroutines inside Perl).
771      </para>
772     </listitem>
773
774     <listitem>
775      <para>
776       SPI is not yet fully implemented.
777      </para>
778     </listitem>
779
780     <listitem>
781      <para>
782       If you are fetching very large data sets using
783       <literal>spi_exec_query</literal>, you should be aware that
784       these will all go into memory.  You can avoid this by using
785       <literal>spi_query</literal>/<literal>spi_fetchrow</literal> as
786       illustrated earlier.
787      </para>
788      <para>
789         A similar problem occurs if a set-returning function passes a
790         large set of rows back to PostgreSQL via <literal>return</literal>. You
791         can avoid this problem too by instead using
792         <literal>return_next</literal> for each row returned, as shown
793         previously.
794      </para>
795
796     </listitem>
797    </itemizedlist>
798   </para>
799  </sect1>
800
801 </chapter>
802
803 <!-- Keep this comment at the end of the file
804 Local variables:
805 mode:sgml
806 sgml-omittag:nil
807 sgml-shorttag:t
808 sgml-minimize-attributes:nil
809 sgml-always-quote-attributes:t
810 sgml-indent-step:1
811 sgml-indent-data:t
812 sgml-parent-document:nil
813 sgml-default-dtd-file:"./reference.ced"
814 sgml-exposed-tags:nil
815 sgml-local-catalogs:("/usr/lib/sgml/catalog")
816 sgml-local-ecat-files:nil
817 End:
818 -->