gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

274 行
14KB

  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>44.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 V1.79.1" /><link rel="prev" href="plperl.html" title="Chapter 44. PL/Perl - Perl Procedural Language" /><link rel="next" href="plperl-data.html" title="44.2. Data Values in PL/Perl" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">44.1. PL/Perl Functions and Arguments</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plperl.html" title="Chapter 44. PL/Perl - Perl Procedural Language">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plperl.html" title="Chapter 44. PL/Perl - Perl Procedural Language">Up</a></td><th width="60%" align="center">Chapter 44. PL/Perl - Perl Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plperl-data.html" title="44.2. Data Values in PL/Perl">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="PLPERL-FUNCS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">44.1. PL/Perl Functions and Arguments</h2></div></div></div><p>
  3. To create a function in the PL/Perl language, use the standard
  4. <a class="xref" href="sql-createfunction.html" title="CREATE FUNCTION"><span class="refentrytitle">CREATE FUNCTION</span></a>
  5. syntax:
  6. </p><pre class="programlisting">
  7. CREATE FUNCTION <em class="replaceable"><code>funcname</code></em> (<em class="replaceable"><code>argument-types</code></em>) RETURNS <em class="replaceable"><code>return-type</code></em> AS $$
  8. # PL/Perl function body
  9. $$ LANGUAGE plperl;
  10. </pre><p>
  11. The body of the function is ordinary Perl code. In fact, the PL/Perl
  12. glue code wraps it inside a Perl subroutine. A PL/Perl function is
  13. called in a scalar context, so it can't return a list. You can return
  14. non-scalar values (arrays, records, and sets) by returning a reference,
  15. as discussed below.
  16. </p><p>
  17. In a PL/Perl procedure, any return value from the Perl code is ignored.
  18. </p><p>
  19. PL/Perl also supports anonymous code blocks called with the
  20. <a class="xref" href="sql-do.html" title="DO"><span class="refentrytitle">DO</span></a> statement:
  21. </p><pre class="programlisting">
  22. DO $$
  23. # PL/Perl code
  24. $$ LANGUAGE plperl;
  25. </pre><p>
  26. An anonymous code block receives no arguments, and whatever value it
  27. might return is discarded. Otherwise it behaves just like a function.
  28. </p><div class="note"><h3 class="title">Note</h3><p>
  29. The use of named nested subroutines is dangerous in Perl, especially if
  30. they refer to lexical variables in the enclosing scope. Because a PL/Perl
  31. function is wrapped in a subroutine, any named subroutine you place inside
  32. one will be nested. In general, it is far safer to create anonymous
  33. subroutines which you call via a coderef. For more information, see the
  34. entries for <code class="literal">Variable "%s" will not stay shared</code> and
  35. <code class="literal">Variable "%s" is not available</code> in the
  36. <span class="citerefentry"><span class="refentrytitle">perldiag</span></span> man page, or
  37. search the Internet for <span class="quote">“<span class="quote">perl nested named subroutine</span>”</span>.
  38. </p></div><p>
  39. The syntax of the <code class="command">CREATE FUNCTION</code> command requires
  40. the function body to be written as a string constant. It is usually
  41. 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.
  42. If you choose to use escape string syntax <code class="literal">E''</code>,
  43. you must double any single quote marks (<code class="literal">'</code>) and backslashes
  44. (<code class="literal">\</code>) used in the body of the function
  45. (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>).
  46. </p><p>
  47. Arguments and results are handled as in any other Perl subroutine:
  48. arguments are passed in <code class="varname">@_</code>, and a result value
  49. is returned with <code class="literal">return</code> or as the last expression
  50. evaluated in the function.
  51. </p><p>
  52. For example, a function returning the greater of two integer values
  53. could be defined as:
  54. </p><pre class="programlisting">
  55. CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
  56. if ($_[0] &gt; $_[1]) { return $_[0]; }
  57. return $_[1];
  58. $$ LANGUAGE plperl;
  59. </pre><p>
  60. </p><div class="note"><h3 class="title">Note</h3><p>
  61. Arguments will be converted from the database's encoding to UTF-8
  62. for use inside PL/Perl, and then converted from UTF-8 back to the
  63. database encoding upon return.
  64. </p></div><p>
  65. If an SQL null value<a id="id-1.8.10.9.10.1" class="indexterm"></a> is passed to a function,
  66. the argument value will appear as <span class="quote">“<span class="quote">undefined</span>”</span> in Perl. The
  67. above function definition will not behave very nicely with null
  68. inputs (in fact, it will act as though they are zeroes). We could
  69. add <code class="literal">STRICT</code> to the function definition to make
  70. <span class="productname">PostgreSQL</span> do something more reasonable:
  71. if a null value is passed, the function will not be called at all,
  72. but will just return a null result automatically. Alternatively,
  73. we could check for undefined inputs in the function body. For
  74. example, suppose that we wanted <code class="function">perl_max</code> with
  75. one null and one nonnull argument to return the nonnull argument,
  76. rather than a null value:
  77. </p><pre class="programlisting">
  78. CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
  79. my ($x, $y) = @_;
  80. if (not defined $x) {
  81. return undef if not defined $y;
  82. return $y;
  83. }
  84. return $x if not defined $y;
  85. return $x if $x &gt; $y;
  86. return $y;
  87. $$ LANGUAGE plperl;
  88. </pre><p>
  89. As shown above, to return an SQL null value from a PL/Perl
  90. function, return an undefined value. This can be done whether the
  91. function is strict or not.
  92. </p><p>
  93. Anything in a function argument that is not a reference is
  94. a string, which is in the standard <span class="productname">PostgreSQL</span>
  95. external text representation for the relevant data type. In the case of
  96. ordinary numeric or text types, Perl will just do the right thing and
  97. the programmer will normally not have to worry about it. However, in
  98. other cases the argument will need to be converted into a form that is
  99. more usable in Perl. For example, the <code class="function">decode_bytea</code>
  100. function can be used to convert an argument of
  101. type <code class="type">bytea</code> into unescaped binary.
  102. </p><p>
  103. Similarly, values passed back to <span class="productname">PostgreSQL</span>
  104. must be in the external text representation format. For example, the
  105. <code class="function">encode_bytea</code> function can be used to
  106. escape binary data for a return value of type <code class="type">bytea</code>.
  107. </p><p>
  108. Perl can return <span class="productname">PostgreSQL</span> arrays as
  109. references to Perl arrays. Here is an example:
  110. </p><pre class="programlisting">
  111. CREATE OR REPLACE function returns_array()
  112. RETURNS text[][] AS $$
  113. return [['a"b','c,d'],['e\\f','g']];
  114. $$ LANGUAGE plperl;
  115. select returns_array();
  116. </pre><p>
  117. </p><p>
  118. Perl passes <span class="productname">PostgreSQL</span> arrays as a blessed
  119. <code class="type">PostgreSQL::InServer::ARRAY</code> object. This object may be treated as an array
  120. reference or a string, allowing for backward compatibility with Perl
  121. code written for <span class="productname">PostgreSQL</span> versions below 9.1 to
  122. run. For example:
  123. </p><pre class="programlisting">
  124. CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$
  125. my $arg = shift;
  126. my $result = "";
  127. return undef if (!defined $arg);
  128. # as an array reference
  129. for (@$arg) {
  130. $result .= $_;
  131. }
  132. # also works as a string
  133. $result .= $arg;
  134. return $result;
  135. $$ LANGUAGE plperl;
  136. SELECT concat_array_elements(ARRAY['PL','/','Perl']);
  137. </pre><p>
  138. </p><div class="note"><h3 class="title">Note</h3><p>
  139. Multidimensional arrays are represented as references to
  140. lower-dimensional arrays of references in a way common to every Perl
  141. programmer.
  142. </p></div><p>
  143. </p><p>
  144. Composite-type arguments are passed to the function as references
  145. to hashes. The keys of the hash are the attribute names of the
  146. composite type. Here is an example:
  147. </p><pre class="programlisting">
  148. CREATE TABLE employee (
  149. name text,
  150. basesalary integer,
  151. bonus integer
  152. );
  153. CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
  154. my ($emp) = @_;
  155. return $emp-&gt;{basesalary} + $emp-&gt;{bonus};
  156. $$ LANGUAGE plperl;
  157. SELECT name, empcomp(employee.*) FROM employee;
  158. </pre><p>
  159. </p><p>
  160. A PL/Perl function can return a composite-type result using the same
  161. approach: return a reference to a hash that has the required attributes.
  162. For example:
  163. </p><pre class="programlisting">
  164. CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
  165. CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
  166. return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
  167. $$ LANGUAGE plperl;
  168. SELECT * FROM perl_row();
  169. </pre><p>
  170. Any columns in the declared result data type that are not present in the
  171. hash will be returned as null values.
  172. </p><p>
  173. Similarly, output arguments of procedures can be returned as a hash
  174. reference:
  175. </p><pre class="programlisting">
  176. CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$
  177. my ($a, $b) = @_;
  178. return {a =&gt; $a * 3, b =&gt; $b * 3};
  179. $$ LANGUAGE plperl;
  180. CALL perl_triple(5, 10);
  181. </pre><p>
  182. </p><p>
  183. PL/Perl functions can also return sets of either scalar or
  184. composite types. Usually you'll want to return rows one at a
  185. time, both to speed up startup time and to keep from queuing up
  186. the entire result set in memory. You can do this with
  187. <code class="function">return_next</code> as illustrated below. Note that
  188. after the last <code class="function">return_next</code>, you must put
  189. either <code class="literal">return</code> or (better) <code class="literal">return
  190. undef</code>.
  191. </p><pre class="programlisting">
  192. CREATE OR REPLACE FUNCTION perl_set_int(int)
  193. RETURNS SETOF INTEGER AS $$
  194. foreach (0..$_[0]) {
  195. return_next($_);
  196. }
  197. return undef;
  198. $$ LANGUAGE plperl;
  199. SELECT * FROM perl_set_int(5);
  200. CREATE OR REPLACE FUNCTION perl_set()
  201. RETURNS SETOF testrowperl AS $$
  202. return_next({ f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' });
  203. return_next({ f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' });
  204. return_next({ f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' });
  205. return undef;
  206. $$ LANGUAGE plperl;
  207. </pre><p>
  208. For small result sets, you can return a reference to an array that
  209. contains either scalars, references to arrays, or references to
  210. hashes for simple types, array types, and composite types,
  211. respectively. Here are some simple examples of returning the entire
  212. result set as an array reference:
  213. </p><pre class="programlisting">
  214. CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
  215. return [0..$_[0]];
  216. $$ LANGUAGE plperl;
  217. SELECT * FROM perl_set_int(5);
  218. CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
  219. return [
  220. { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' },
  221. { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' },
  222. { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' }
  223. ];
  224. $$ LANGUAGE plperl;
  225. SELECT * FROM perl_set();
  226. </pre><p>
  227. </p><p>
  228. If you wish to use the <code class="literal">strict</code> pragma with your code you
  229. have a few options. For temporary global use you can <code class="command">SET</code>
  230. <code class="literal">plperl.use_strict</code> to true.
  231. This will affect subsequent compilations of <span class="application">PL/Perl</span>
  232. functions, but not functions already compiled in the current session.
  233. For permanent global use you can set <code class="literal">plperl.use_strict</code>
  234. to true in the <code class="filename">postgresql.conf</code> file.
  235. </p><p>
  236. For permanent use in specific functions you can simply put:
  237. </p><pre class="programlisting">
  238. use strict;
  239. </pre><p>
  240. at the top of the function body.
  241. </p><p>
  242. 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.
  243. </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plperl.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plperl.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plperl-data.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 44. PL/Perl - Perl Procedural Language </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 44.2. Data Values in PL/Perl</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1