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

351 行
21KB

  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.3. Built-in Functions</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-data.html" title="44.2. Data Values in PL/Perl" /><link rel="next" href="plperl-global.html" title="44.4. Global 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.3. Built-in Functions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plperl-data.html" title="44.2. Data Values in PL/Perl">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-global.html" title="44.4. Global Values in PL/Perl">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="PLPERL-BUILTINS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">44.3. Built-in Functions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="plperl-builtins.html#PLPERL-DATABASE">44.3.1. Database Access from PL/Perl</a></span></dt><dt><span class="sect2"><a href="plperl-builtins.html#PLPERL-UTILITY-FUNCTIONS">44.3.2. Utility Functions in PL/Perl</a></span></dt></dl></div><div class="sect2" id="PLPERL-DATABASE"><div class="titlepage"><div><div><h3 class="title">44.3.1. Database Access from PL/Perl</h3></div></div></div><p>
  3. Access to the database itself from your Perl function can be done
  4. via the following functions:
  5. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">
  6. <code class="literal"><code class="function">spi_exec_query</code>(<em class="replaceable"><code>query</code></em> [, <em class="replaceable"><code>max-rows</code></em>])</code>
  7. <a id="id-1.8.10.11.2.3.1.1.2" class="indexterm"></a>
  8. </span></dt><dd><p>
  9. <code class="literal">spi_exec_query</code> executes an SQL command and
  10. returns the entire row set as a reference to an array of hash
  11. references. <span class="emphasis"><em>You should only use this command when you know
  12. that the result set will be relatively small.</em></span> Here is an
  13. example of a query (<code class="command">SELECT</code> command) with the
  14. optional maximum number of rows:
  15. </p><pre class="programlisting">
  16. $rv = spi_exec_query('SELECT * FROM my_table', 5);
  17. </pre><p>
  18. This returns up to 5 rows from the table
  19. <code class="literal">my_table</code>. If <code class="literal">my_table</code>
  20. has a column <code class="literal">my_column</code>, you can get that
  21. value from row <code class="literal">$i</code> of the result like this:
  22. </p><pre class="programlisting">
  23. $foo = $rv-&gt;{rows}[$i]-&gt;{my_column};
  24. </pre><p>
  25. The total number of rows returned from a <code class="command">SELECT</code>
  26. query can be accessed like this:
  27. </p><pre class="programlisting">
  28. $nrows = $rv-&gt;{processed}
  29. </pre><p>
  30. </p><p>
  31. Here is an example using a different command type:
  32. </p><pre class="programlisting">
  33. $query = "INSERT INTO my_table VALUES (1, 'test')";
  34. $rv = spi_exec_query($query);
  35. </pre><p>
  36. You can then access the command status (e.g.,
  37. <code class="literal">SPI_OK_INSERT</code>) like this:
  38. </p><pre class="programlisting">
  39. $res = $rv-&gt;{status};
  40. </pre><p>
  41. To get the number of rows affected, do:
  42. </p><pre class="programlisting">
  43. $nrows = $rv-&gt;{processed};
  44. </pre><p>
  45. </p><p>
  46. Here is a complete example:
  47. </p><pre class="programlisting">
  48. CREATE TABLE test (
  49. i int,
  50. v varchar
  51. );
  52. INSERT INTO test (i, v) VALUES (1, 'first line');
  53. INSERT INTO test (i, v) VALUES (2, 'second line');
  54. INSERT INTO test (i, v) VALUES (3, 'third line');
  55. INSERT INTO test (i, v) VALUES (4, 'immortal');
  56. CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
  57. my $rv = spi_exec_query('select i, v from test;');
  58. my $status = $rv-&gt;{status};
  59. my $nrows = $rv-&gt;{processed};
  60. foreach my $rn (0 .. $nrows - 1) {
  61. my $row = $rv-&gt;{rows}[$rn];
  62. $row-&gt;{i} += 200 if defined($row-&gt;{i});
  63. $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
  64. return_next($row);
  65. }
  66. return undef;
  67. $$ LANGUAGE plperl;
  68. SELECT * FROM test_munge();
  69. </pre><p>
  70. </p></dd><dt><span class="term">
  71. <code class="literal"><code class="function">spi_query(<em class="replaceable"><code>command</code></em>)</code></code>
  72. <a id="id-1.8.10.11.2.3.2.1.2" class="indexterm"></a>
  73. <br /></span><span class="term">
  74. <code class="literal"><code class="function">spi_fetchrow(<em class="replaceable"><code>cursor</code></em>)</code></code>
  75. <a id="id-1.8.10.11.2.3.2.2.2" class="indexterm"></a>
  76. <br /></span><span class="term">
  77. <code class="literal"><code class="function">spi_cursor_close(<em class="replaceable"><code>cursor</code></em>)</code></code>
  78. <a id="id-1.8.10.11.2.3.2.3.2" class="indexterm"></a>
  79. </span></dt><dd><p>
  80. <code class="literal">spi_query</code> and <code class="literal">spi_fetchrow</code>
  81. work together as a pair for row sets which might be large, or for cases
  82. where you wish to return rows as they arrive.
  83. <code class="literal">spi_fetchrow</code> works <span class="emphasis"><em>only</em></span> with
  84. <code class="literal">spi_query</code>. The following example illustrates how
  85. you use them together:
  86. </p><pre class="programlisting">
  87. CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
  88. CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
  89. use Digest::MD5 qw(md5_hex);
  90. my $file = '/usr/share/dict/words';
  91. my $t = localtime;
  92. elog(NOTICE, "opening file $file at $t" );
  93. open my $fh, '&lt;', $file # ooh, it's a file access!
  94. or elog(ERROR, "cannot open $file for reading: $!");
  95. my @words = &lt;$fh&gt;;
  96. close $fh;
  97. $t = localtime;
  98. elog(NOTICE, "closed file $file at $t");
  99. chomp(@words);
  100. my $row;
  101. my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
  102. while (defined ($row = spi_fetchrow($sth))) {
  103. return_next({
  104. the_num =&gt; $row-&gt;{a},
  105. the_text =&gt; md5_hex($words[rand @words])
  106. });
  107. }
  108. return;
  109. $$ LANGUAGE plperlu;
  110. SELECT * from lotsa_md5(500);
  111. </pre><p>
  112. </p><p>
  113. Normally, <code class="function">spi_fetchrow</code> should be repeated until it
  114. returns <code class="literal">undef</code>, indicating that there are no more
  115. rows to read. The cursor returned by <code class="literal">spi_query</code>
  116. is automatically freed when
  117. <code class="function">spi_fetchrow</code> returns <code class="literal">undef</code>.
  118. If you do not wish to read all the rows, instead call
  119. <code class="function">spi_cursor_close</code> to free the cursor.
  120. Failure to do so will result in memory leaks.
  121. </p></dd><dt><span class="term">
  122. <code class="literal"><code class="function">spi_prepare(<em class="replaceable"><code>command</code></em>, <em class="replaceable"><code>argument types</code></em>)</code></code>
  123. <a id="id-1.8.10.11.2.3.3.1.2" class="indexterm"></a>
  124. <br /></span><span class="term">
  125. <code class="literal"><code class="function">spi_query_prepared(<em class="replaceable"><code>plan</code></em>, <em class="replaceable"><code>arguments</code></em>)</code></code>
  126. <a id="id-1.8.10.11.2.3.3.2.2" class="indexterm"></a>
  127. <br /></span><span class="term">
  128. <code class="literal"><code class="function">spi_exec_prepared(<em class="replaceable"><code>plan</code></em> [, <em class="replaceable"><code>attributes</code></em>], <em class="replaceable"><code>arguments</code></em>)</code></code>
  129. <a id="id-1.8.10.11.2.3.3.3.2" class="indexterm"></a>
  130. <br /></span><span class="term">
  131. <code class="literal"><code class="function">spi_freeplan(<em class="replaceable"><code>plan</code></em>)</code></code>
  132. <a id="id-1.8.10.11.2.3.3.4.2" class="indexterm"></a>
  133. </span></dt><dd><p>
  134. <code class="literal">spi_prepare</code>, <code class="literal">spi_query_prepared</code>, <code class="literal">spi_exec_prepared</code>,
  135. and <code class="literal">spi_freeplan</code> implement the same functionality but for prepared queries.
  136. <code class="literal">spi_prepare</code> accepts a query string with numbered argument placeholders ($1, $2, etc)
  137. and a string list of argument types:
  138. </p><pre class="programlisting">
  139. $plan = spi_prepare('SELECT * FROM test WHERE id &gt; $1 AND name = $2',
  140. 'INTEGER', 'TEXT');
  141. </pre><p>
  142. Once a query plan is prepared by a call to <code class="literal">spi_prepare</code>, the plan can be used instead
  143. of the string query, either in <code class="literal">spi_exec_prepared</code>, where the result is the same as returned
  144. by <code class="literal">spi_exec_query</code>, or in <code class="literal">spi_query_prepared</code> which returns a cursor
  145. exactly as <code class="literal">spi_query</code> does, which can be later passed to <code class="literal">spi_fetchrow</code>.
  146. The optional second parameter to <code class="literal">spi_exec_prepared</code> is a hash reference of attributes;
  147. the only attribute currently supported is <code class="literal">limit</code>, which sets the maximum number of rows returned by a query.
  148. </p><p>
  149. The advantage of prepared queries is that is it possible to use one prepared plan for more
  150. than one query execution. After the plan is not needed anymore, it can be freed with
  151. <code class="literal">spi_freeplan</code>:
  152. </p><pre class="programlisting">
  153. CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
  154. $_SHARED{my_plan} = spi_prepare('SELECT (now() + $1)::date AS now',
  155. 'INTERVAL');
  156. $$ LANGUAGE plperl;
  157. CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$
  158. return spi_exec_prepared(
  159. $_SHARED{my_plan},
  160. $_[0]
  161. )-&gt;{rows}-&gt;[0]-&gt;{now};
  162. $$ LANGUAGE plperl;
  163. CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
  164. spi_freeplan( $_SHARED{my_plan});
  165. undef $_SHARED{my_plan};
  166. $$ LANGUAGE plperl;
  167. SELECT init();
  168. SELECT add_time('1 day'), add_time('2 days'), add_time('3 days');
  169. SELECT done();
  170. add_time | add_time | add_time
  171. ------------+------------+------------
  172. 2005-12-10 | 2005-12-11 | 2005-12-12
  173. </pre><p>
  174. Note that the parameter subscript in <code class="literal">spi_prepare</code> is defined via
  175. $1, $2, $3, etc, so avoid declaring query strings in double quotes that might easily
  176. lead to hard-to-catch bugs.
  177. </p><p>
  178. Another example illustrates usage of an optional parameter in <code class="literal">spi_exec_prepared</code>:
  179. </p><pre class="programlisting">
  180. CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address
  181. FROM generate_series(1,3) AS id;
  182. CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
  183. $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
  184. WHERE address &lt;&lt; $1', 'inet');
  185. $$ LANGUAGE plperl;
  186. CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
  187. return spi_exec_prepared(
  188. $_SHARED{plan},
  189. {limit =&gt; 2},
  190. $_[0]
  191. )-&gt;{rows};
  192. $$ LANGUAGE plperl;
  193. CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
  194. spi_freeplan($_SHARED{plan});
  195. undef $_SHARED{plan};
  196. $$ LANGUAGE plperl;
  197. SELECT init_hosts_query();
  198. SELECT query_hosts('192.168.1.0/30');
  199. SELECT release_hosts_query();
  200. query_hosts
  201. -----------------
  202. (1,192.168.1.1)
  203. (2,192.168.1.2)
  204. (2 rows)
  205. </pre><p>
  206. </p></dd><dt><span class="term">
  207. <code class="literal"><code class="function">spi_commit()</code></code>
  208. <a id="id-1.8.10.11.2.3.4.1.2" class="indexterm"></a>
  209. <br /></span><span class="term">
  210. <code class="literal"><code class="function">spi_rollback()</code></code>
  211. <a id="id-1.8.10.11.2.3.4.2.2" class="indexterm"></a>
  212. </span></dt><dd><p>
  213. Commit or roll back the current transaction. This can only be called
  214. in a procedure or anonymous code block (<code class="command">DO</code> command)
  215. called from the top level. (Note that it is not possible to run the
  216. SQL commands <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code>
  217. via <code class="function">spi_exec_query</code> or similar. It has to be done
  218. using these functions.) After a transaction is ended, a new
  219. transaction is automatically started, so there is no separate function
  220. for that.
  221. </p><p>
  222. Here is an example:
  223. </p><pre class="programlisting">
  224. CREATE PROCEDURE transaction_test1()
  225. LANGUAGE plperl
  226. AS $$
  227. foreach my $i (0..9) {
  228. spi_exec_query("INSERT INTO test1 (a) VALUES ($i)");
  229. if ($i % 2 == 0) {
  230. spi_commit();
  231. } else {
  232. spi_rollback();
  233. }
  234. }
  235. $$;
  236. CALL transaction_test1();
  237. </pre><p>
  238. </p></dd></dl></div></div><div class="sect2" id="PLPERL-UTILITY-FUNCTIONS"><div class="titlepage"><div><div><h3 class="title">44.3.2. Utility Functions in PL/Perl</h3></div></div></div><div class="variablelist"><dl class="variablelist"><dt><span class="term">
  239. <code class="literal"><code class="function">elog(<em class="replaceable"><code>level</code></em>, <em class="replaceable"><code>msg</code></em>)</code></code>
  240. <a id="id-1.8.10.11.3.2.1.1.2" class="indexterm"></a>
  241. </span></dt><dd><p>
  242. Emit a log or error message. Possible levels are
  243. <code class="literal">DEBUG</code>, <code class="literal">LOG</code>, <code class="literal">INFO</code>,
  244. <code class="literal">NOTICE</code>, <code class="literal">WARNING</code>, and <code class="literal">ERROR</code>.
  245. <code class="literal">ERROR</code>
  246. raises an error condition; if this is not trapped by the surrounding
  247. Perl code, the error propagates out to the calling query, causing
  248. the current transaction or subtransaction to be aborted. This
  249. is effectively the same as the Perl <code class="literal">die</code> command.
  250. The other levels only generate messages of different
  251. priority levels.
  252. Whether messages of a particular priority are reported to the client,
  253. written to the server log, or both is controlled by the
  254. <a class="xref" href="runtime-config-logging.html#GUC-LOG-MIN-MESSAGES">log_min_messages</a> and
  255. <a class="xref" href="runtime-config-client.html#GUC-CLIENT-MIN-MESSAGES">client_min_messages</a> configuration
  256. variables. See <a class="xref" href="runtime-config.html" title="Chapter 19. Server Configuration">Chapter 19</a> for more
  257. information.
  258. </p></dd><dt><span class="term">
  259. <code class="literal"><code class="function">quote_literal(<em class="replaceable"><code>string</code></em>)</code></code>
  260. <a id="id-1.8.10.11.3.2.2.1.2" class="indexterm"></a>
  261. </span></dt><dd><p>
  262. Return the given string suitably quoted to be used as a string literal in an SQL
  263. statement string. Embedded single-quotes and backslashes are properly doubled.
  264. Note that <code class="function">quote_literal</code> returns undef on undef input; if the argument
  265. might be undef, <code class="function">quote_nullable</code> is often more suitable.
  266. </p></dd><dt><span class="term">
  267. <code class="literal"><code class="function">quote_nullable(<em class="replaceable"><code>string</code></em>)</code></code>
  268. <a id="id-1.8.10.11.3.2.3.1.2" class="indexterm"></a>
  269. </span></dt><dd><p>
  270. Return the given string suitably quoted to be used as a string literal in an SQL
  271. statement string; or, if the argument is undef, return the unquoted string "NULL".
  272. Embedded single-quotes and backslashes are properly doubled.
  273. </p></dd><dt><span class="term">
  274. <code class="literal"><code class="function">quote_ident(<em class="replaceable"><code>string</code></em>)</code></code>
  275. <a id="id-1.8.10.11.3.2.4.1.2" class="indexterm"></a>
  276. </span></dt><dd><p>
  277. Return the given string suitably quoted to be used as an identifier in
  278. an SQL statement string. Quotes are added only if necessary (i.e., if
  279. the string contains non-identifier characters or would be case-folded).
  280. Embedded quotes are properly doubled.
  281. </p></dd><dt><span class="term">
  282. <code class="literal"><code class="function">decode_bytea(<em class="replaceable"><code>string</code></em>)</code></code>
  283. <a id="id-1.8.10.11.3.2.5.1.2" class="indexterm"></a>
  284. </span></dt><dd><p>
  285. Return the unescaped binary data represented by the contents of the given string,
  286. which should be <code class="type">bytea</code> encoded.
  287. </p></dd><dt><span class="term">
  288. <code class="literal"><code class="function">encode_bytea(<em class="replaceable"><code>string</code></em>)</code></code>
  289. <a id="id-1.8.10.11.3.2.6.1.2" class="indexterm"></a>
  290. </span></dt><dd><p>
  291. Return the <code class="type">bytea</code> encoded form of the binary data contents of the given string.
  292. </p></dd><dt><span class="term">
  293. <code class="literal"><code class="function">encode_array_literal(<em class="replaceable"><code>array</code></em>)</code></code>
  294. <a id="id-1.8.10.11.3.2.7.1.2" class="indexterm"></a>
  295. <br /></span><span class="term">
  296. <code class="literal"><code class="function">encode_array_literal(<em class="replaceable"><code>array</code></em>, <em class="replaceable"><code>delimiter</code></em>)</code></code>
  297. </span></dt><dd><p>
  298. Returns the contents of the referenced array as a string in array literal format
  299. (see <a class="xref" href="arrays.html#ARRAYS-INPUT" title="8.15.2. Array Value Input">Section 8.15.2</a>).
  300. Returns the argument value unaltered if it's not a reference to an array.
  301. The delimiter used between elements of the array literal defaults to "<code class="literal">, </code>"
  302. if a delimiter is not specified or is undef.
  303. </p></dd><dt><span class="term">
  304. <code class="literal"><code class="function">encode_typed_literal(<em class="replaceable"><code>value</code></em>, <em class="replaceable"><code>typename</code></em>)</code></code>
  305. <a id="id-1.8.10.11.3.2.8.1.2" class="indexterm"></a>
  306. </span></dt><dd><p>
  307. Converts a Perl variable to the value of the data type passed as a
  308. second argument and returns a string representation of this value.
  309. Correctly handles nested arrays and values of composite types.
  310. </p></dd><dt><span class="term">
  311. <code class="literal"><code class="function">encode_array_constructor(<em class="replaceable"><code>array</code></em>)</code></code>
  312. <a id="id-1.8.10.11.3.2.9.1.2" class="indexterm"></a>
  313. </span></dt><dd><p>
  314. Returns the contents of the referenced array as a string in array constructor format
  315. (see <a class="xref" href="sql-expressions.html#SQL-SYNTAX-ARRAY-CONSTRUCTORS" title="4.2.12. Array Constructors">Section 4.2.12</a>).
  316. Individual values are quoted using <code class="function">quote_nullable</code>.
  317. Returns the argument value, quoted using <code class="function">quote_nullable</code>,
  318. if it's not a reference to an array.
  319. </p></dd><dt><span class="term">
  320. <code class="literal"><code class="function">looks_like_number(<em class="replaceable"><code>string</code></em>)</code></code>
  321. <a id="id-1.8.10.11.3.2.10.1.2" class="indexterm"></a>
  322. </span></dt><dd><p>
  323. Returns a true value if the content of the given string looks like a
  324. number, according to Perl, returns false otherwise.
  325. Returns undef if the argument is undef. Leading and trailing space is
  326. ignored. <code class="literal">Inf</code> and <code class="literal">Infinity</code> are regarded as numbers.
  327. </p></dd><dt><span class="term">
  328. <code class="literal"><code class="function">is_array_ref(<em class="replaceable"><code>argument</code></em>)</code></code>
  329. <a id="id-1.8.10.11.3.2.11.1.2" class="indexterm"></a>
  330. </span></dt><dd><p>
  331. Returns a true value if the given argument may be treated as an
  332. array reference, that is, if ref of the argument is <code class="literal">ARRAY</code> or
  333. <code class="literal">PostgreSQL::InServer::ARRAY</code>. Returns false otherwise.
  334. </p></dd></dl></div></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plperl-data.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-global.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">44.2. Data Values in PL/Perl </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 44.4. Global Values in PL/Perl</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1