codekingpro/portable-devtools
115k
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>45.1. PL/Perl Functions and Arguments</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="plperl.html" title="Chapter 45. PL/Perl — Perl Procedural Language" /><link rel="next" href="plperl-data.html" title="45.2. Data Values in PL/Perl" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">45.1. PL/Perl Functions and Arguments</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plperl.html" title="Chapter 45. PL/Perl — Perl Procedural Language">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plperl.html" title="Chapter 45. PL/Perl — Perl Procedural Language">Up</a></td><th width="60%" align="center">Chapter 45. PL/Perl — Perl Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plperl-data.html" title="45.2. Data Values in PL/Perl">Next</a></td></tr></table><hr /></div><div class="sect1" id="PLPERL-FUNCS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">45.1. PL/Perl Functions and Arguments <a href="#PLPERL-FUNCS" class="id_link">#</a></h2></div></div></div><p>3 To create a function in the PL/Perl language, use the standard4 <a class="xref" href="sql-createfunction.html" title="CREATE FUNCTION"><span class="refentrytitle">CREATE FUNCTION</span></a>5 syntax:6 7</p><pre class="programlisting">8CREATE FUNCTION <em class="replaceable"><code>funcname</code></em> (<em class="replaceable"><code>argument-types</code></em>)9RETURNS <em class="replaceable"><code>return-type</code></em>10-- function attributes can go here11AS $$12 # PL/Perl function body goes here13$$ LANGUAGE plperl;14</pre><p>15 16 The body of the function is ordinary Perl code. In fact, the PL/Perl17 glue code wraps it inside a Perl subroutine. A PL/Perl function is18 called in a scalar context, so it can't return a list. You can return19 non-scalar values (arrays, records, and sets) by returning a reference,20 as discussed below.21 </p><p>22 In a PL/Perl procedure, any return value from the Perl code is ignored.23 </p><p>24 PL/Perl also supports anonymous code blocks called with the25 <a class="xref" href="sql-do.html" title="DO"><span class="refentrytitle">DO</span></a> statement:26 27</p><pre class="programlisting">28DO $$29 # PL/Perl code30$$ LANGUAGE plperl;31</pre><p>32 33 An anonymous code block receives no arguments, and whatever value it34 might return is discarded. Otherwise it behaves just like a function.35 </p><div class="note"><h3 class="title">Note</h3><p>36 The use of named nested subroutines is dangerous in Perl, especially if37 they refer to lexical variables in the enclosing scope. Because a PL/Perl38 function is wrapped in a subroutine, any named subroutine you place inside39 one will be nested. In general, it is far safer to create anonymous40 subroutines which you call via a coderef. For more information, see the41 entries for <code class="literal">Variable "%s" will not stay shared</code> and42 <code class="literal">Variable "%s" is not available</code> in the43 <span class="citerefentry"><span class="refentrytitle">perldiag</span></span> man page, or44 search the Internet for <span class="quote">“<span class="quote">perl nested named subroutine</span>”</span>.45 </p></div><p>46 The syntax of the <code class="command">CREATE FUNCTION</code> command requires47 the function body to be written as a string constant. It is usually48 most convenient to use dollar quoting (see <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" title="4.1.2.4. Dollar-Quoted String Constants">Section 4.1.2.4</a>) for the string constant.49 If you choose to use escape string syntax <code class="literal">E''</code>,50 you must double any single quote marks (<code class="literal">'</code>) and backslashes51 (<code class="literal">\</code>) used in the body of the function52 (see <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-STRINGS" title="4.1.2.1. String Constants">Section 4.1.2.1</a>).53 </p><p>54 Arguments and results are handled as in any other Perl subroutine:55 arguments are passed in <code class="varname">@_</code>, and a result value56 is returned with <code class="literal">return</code> or as the last expression57 evaluated in the function.58 </p><p>59 For example, a function returning the greater of two integer values60 could be defined as:61 62</p><pre class="programlisting">63CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$64 if ($_[0] > $_[1]) { return $_[0]; }65 return $_[1];66$$ LANGUAGE plperl;67</pre><p>68 </p><div class="note"><h3 class="title">Note</h3><p>69 Arguments will be converted from the database's encoding to UTF-870 for use inside PL/Perl, and then converted from UTF-8 back to the71 database encoding upon return.72 </p></div><p>73 If an SQL null value<a id="id-1.8.10.9.10.1" class="indexterm"></a> is passed to a function,74 the argument value will appear as <span class="quote">“<span class="quote">undefined</span>”</span> in Perl. The75 above function definition will not behave very nicely with null76 inputs (in fact, it will act as though they are zeroes). We could77 add <code class="literal">STRICT</code> to the function definition to make78 <span class="productname">PostgreSQL</span> do something more reasonable:79 if a null value is passed, the function will not be called at all,80 but will just return a null result automatically. Alternatively,81 we could check for undefined inputs in the function body. For82 example, suppose that we wanted <code class="function">perl_max</code> with83 one null and one nonnull argument to return the nonnull argument,84 rather than a null value:85 86</p><pre class="programlisting">87CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$88 my ($x, $y) = @_;89 if (not defined $x) {90 return undef if not defined $y;91 return $y;92 }93 return $x if not defined $y;94 return $x if $x > $y;95 return $y;96$$ LANGUAGE plperl;97</pre><p>98 As shown above, to return an SQL null value from a PL/Perl99 function, return an undefined value. This can be done whether the100 function is strict or not.101 </p><p>102 Anything in a function argument that is not a reference is103 a string, which is in the standard <span class="productname">PostgreSQL</span>104 external text representation for the relevant data type. In the case of105 ordinary numeric or text types, Perl will just do the right thing and106 the programmer will normally not have to worry about it. However, in107 other cases the argument will need to be converted into a form that is108 more usable in Perl. For example, the <code class="function">decode_bytea</code>109 function can be used to convert an argument of110 type <code class="type">bytea</code> into unescaped binary.111 </p><p>112 Similarly, values passed back to <span class="productname">PostgreSQL</span>113 must be in the external text representation format. For example, the114 <code class="function">encode_bytea</code> function can be used to115 escape binary data for a return value of type <code class="type">bytea</code>.116 </p><p>117 One case that is particularly important is boolean values. As just118 stated, the default behavior for <code class="type">bool</code> values is that they119 are passed to Perl as text, thus either <code class="literal">'t'</code>120 or <code class="literal">'f'</code>. This is problematic, since Perl will not121 treat <code class="literal">'f'</code> as false! It is possible to improve matters122 by using a <span class="quote">“<span class="quote">transform</span>”</span> (see123 <a class="xref" href="sql-createtransform.html" title="CREATE TRANSFORM"><span class="refentrytitle">CREATE TRANSFORM</span></a>). Suitable transforms are provided124 by the <code class="filename">bool_plperl</code> extension. To use it, install125 the extension:126</p><pre class="programlisting">127CREATE EXTENSION bool_plperl; -- or bool_plperlu for PL/PerlU128</pre><p>129 Then use the <code class="literal">TRANSFORM</code> function attribute for a130 PL/Perl function that takes or returns <code class="type">bool</code>, for example:131</p><pre class="programlisting">132CREATE FUNCTION perl_and(bool, bool) RETURNS bool133TRANSFORM FOR TYPE bool134AS $$135 my ($a, $b) = @_;136 return $a && $b;137$$ LANGUAGE plperl;138</pre><p>139 When this transform is applied, <code class="type">bool</code> arguments will be seen140 by Perl as being <code class="literal">1</code> or empty, thus properly true or141 false. If the function result is type <code class="type">bool</code>, it will be true142 or false according to whether Perl would evaluate the returned value as143 true.144 Similar transformations are also performed for boolean query arguments145 and results of SPI queries performed inside the function146 (<a class="xref" href="plperl-builtins.html#PLPERL-DATABASE" title="45.3.1. Database Access from PL/Perl">Section 45.3.1</a>).147 </p><p>148 Perl can return <span class="productname">PostgreSQL</span> arrays as149 references to Perl arrays. Here is an example:150 151</p><pre class="programlisting">152CREATE OR REPLACE function returns_array()153RETURNS text[][] AS $$154 return [['a"b','c,d'],['e\\f','g']];155$$ LANGUAGE plperl;156 157select returns_array();158</pre><p>159 </p><p>160 Perl passes <span class="productname">PostgreSQL</span> arrays as a blessed161 <code class="type">PostgreSQL::InServer::ARRAY</code> object. This object may be treated as an array162 reference or a string, allowing for backward compatibility with Perl163 code written for <span class="productname">PostgreSQL</span> versions below 9.1 to164 run. For example:165 166</p><pre class="programlisting">167CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$168 my $arg = shift;169 my $result = "";170 return undef if (!defined $arg);171 172 # as an array reference173 for (@$arg) {174 $result .= $_;175 }176 177 # also works as a string178 $result .= $arg;179 180 return $result;181$$ LANGUAGE plperl;182 183SELECT concat_array_elements(ARRAY['PL','/','Perl']);184</pre><p>185 186 </p><div class="note"><h3 class="title">Note</h3><p>187 Multidimensional arrays are represented as references to188 lower-dimensional arrays of references in a way common to every Perl189 programmer.190 </p></div><p>191 </p><p>192 Composite-type arguments are passed to the function as references193 to hashes. The keys of the hash are the attribute names of the194 composite type. Here is an example:195 196</p><pre class="programlisting">197CREATE TABLE employee (198 name text,199 basesalary integer,200 bonus integer201);202 203CREATE FUNCTION empcomp(employee) RETURNS integer AS $$204 my ($emp) = @_;205 return $emp->{basesalary} + $emp->{bonus};206$$ LANGUAGE plperl;207 208SELECT name, empcomp(employee.*) FROM employee;209</pre><p>210 </p><p>211 A PL/Perl function can return a composite-type result using the same212 approach: return a reference to a hash that has the required attributes.213 For example:214 215</p><pre class="programlisting">216CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);217 218CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$219 return {f2 => 'hello', f1 => 1, f3 => 'world'};220$$ LANGUAGE plperl;221 222SELECT * FROM perl_row();223</pre><p>224 225 Any columns in the declared result data type that are not present in the226 hash will be returned as null values.227 </p><p>228 Similarly, output arguments of procedures can be returned as a hash229 reference:230 231</p><pre class="programlisting">232CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$233 my ($a, $b) = @_;234 return {a => $a * 3, b => $b * 3};235$$ LANGUAGE plperl;236 237CALL perl_triple(5, 10);238</pre><p>239 </p><p>240 PL/Perl functions can also return sets of either scalar or241 composite types. Usually you'll want to return rows one at a242 time, both to speed up startup time and to keep from queuing up243 the entire result set in memory. You can do this with244 <code class="function">return_next</code> as illustrated below. Note that245 after the last <code class="function">return_next</code>, you must put246 either <code class="literal">return</code> or (better) <code class="literal">return247 undef</code>.248 249</p><pre class="programlisting">250CREATE OR REPLACE FUNCTION perl_set_int(int)251RETURNS SETOF INTEGER AS $$252 foreach (0..$_[0]) {253 return_next($_);254 }255 return undef;256$$ LANGUAGE plperl;257 258SELECT * FROM perl_set_int(5);259 260CREATE OR REPLACE FUNCTION perl_set()261RETURNS SETOF testrowperl AS $$262 return_next({ f1 => 1, f2 => 'Hello', f3 => 'World' });263 return_next({ f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' });264 return_next({ f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' });265 return undef;266$$ LANGUAGE plperl;267</pre><p>268 269 For small result sets, you can return a reference to an array that270 contains either scalars, references to arrays, or references to271 hashes for simple types, array types, and composite types,272 respectively. Here are some simple examples of returning the entire273 result set as an array reference:274 275</p><pre class="programlisting">276CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$277 return [0..$_[0]];278$$ LANGUAGE plperl;279 280SELECT * FROM perl_set_int(5);281 282CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$283 return [284 { f1 => 1, f2 => 'Hello', f3 => 'World' },285 { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' },286 { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' }287 ];288$$ LANGUAGE plperl;289 290SELECT * FROM perl_set();291</pre><p>292 </p><p>293 If you wish to use the <code class="literal">strict</code> pragma with your code you294 have a few options. For temporary global use you can <code class="command">SET</code>295 <code class="literal">plperl.use_strict</code> to true.296 This will affect subsequent compilations of <span class="application">PL/Perl</span>297 functions, but not functions already compiled in the current session.298 For permanent global use you can set <code class="literal">plperl.use_strict</code>299 to true in the <code class="filename">postgresql.conf</code> file.300 </p><p>301 For permanent use in specific functions you can simply put:302</p><pre class="programlisting">303use strict;304</pre><p>305 at the top of the function body.306 </p><p>307 The <code class="literal">feature</code> pragma is also available to <code class="function">use</code> if your Perl is version 5.10.0 or higher.308 </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plperl.html" title="Chapter 45. PL/Perl — Perl Procedural Language">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plperl.html" title="Chapter 45. PL/Perl — Perl Procedural Language">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plperl-data.html" title="45.2. Data Values in PL/Perl">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 45. PL/Perl — Perl Procedural Language </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 45.2. Data Values in PL/Perl</td></tr></table></div></body></html>