gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
18KB

  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>42.11. PL/pgSQL under the Hood</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="plpgsql-trigger.html" title="42.10. Trigger Functions" /><link rel="next" href="plpgsql-development-tips.html" title="42.12. Tips for Developing in PL/pgSQL" /></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">42.11. <span xmlns="http://www.w3.org/1999/xhtml" class="application">PL/pgSQL</span> under the Hood</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plpgsql-trigger.html" title="42.10. Trigger Functions">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plpgsql.html" title="Chapter 42. PL/pgSQL - SQL Procedural Language">Up</a></td><th width="60%" align="center">Chapter 42. <span xmlns="http://www.w3.org/1999/xhtml" class="application">PL/pgSQL</span> - <acronym xmlns="http://www.w3.org/1999/xhtml" class="acronym">SQL</acronym> 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="plpgsql-development-tips.html" title="42.12. Tips for Developing in PL/pgSQL">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="PLPGSQL-IMPLEMENTATION"><div class="titlepage"><div><div><h2 class="title" style="clear: both">42.11. <span class="application">PL/pgSQL</span> under the Hood</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="plpgsql-implementation.html#PLPGSQL-VAR-SUBST">42.11.1. Variable Substitution</a></span></dt><dt><span class="sect2"><a href="plpgsql-implementation.html#PLPGSQL-PLAN-CACHING">42.11.2. Plan Caching</a></span></dt></dl></div><p>
  3. This section discusses some implementation details that are
  4. frequently important for <span class="application">PL/pgSQL</span> users to know.
  5. </p><div class="sect2" id="PLPGSQL-VAR-SUBST"><div class="titlepage"><div><div><h3 class="title">42.11.1. Variable Substitution</h3></div></div></div><p>
  6. SQL statements and expressions within a <span class="application">PL/pgSQL</span> function
  7. can refer to variables and parameters of the function. Behind the scenes,
  8. <span class="application">PL/pgSQL</span> substitutes query parameters for such references.
  9. Parameters will only be substituted in places where a parameter or
  10. column reference is syntactically allowed. As an extreme case, consider
  11. this example of poor programming style:
  12. </p><pre class="programlisting">
  13. INSERT INTO foo (foo) VALUES (foo);
  14. </pre><p>
  15. The first occurrence of <code class="literal">foo</code> must syntactically be a table
  16. name, so it will not be substituted, even if the function has a variable
  17. named <code class="literal">foo</code>. The second occurrence must be the name of a
  18. column of the table, so it will not be substituted either. Only the
  19. third occurrence is a candidate to be a reference to the function's
  20. variable.
  21. </p><div class="note"><h3 class="title">Note</h3><p>
  22. <span class="productname">PostgreSQL</span> versions before 9.0 would try
  23. to substitute the variable in all three cases, leading to syntax errors.
  24. </p></div><p>
  25. Since the names of variables are syntactically no different from the names
  26. of table columns, there can be ambiguity in statements that also refer to
  27. tables: is a given name meant to refer to a table column, or a variable?
  28. Let's change the previous example to
  29. </p><pre class="programlisting">
  30. INSERT INTO dest (col) SELECT foo + bar FROM src;
  31. </pre><p>
  32. Here, <code class="literal">dest</code> and <code class="literal">src</code> must be table names, and
  33. <code class="literal">col</code> must be a column of <code class="literal">dest</code>, but <code class="literal">foo</code>
  34. and <code class="literal">bar</code> might reasonably be either variables of the function
  35. or columns of <code class="literal">src</code>.
  36. </p><p>
  37. By default, <span class="application">PL/pgSQL</span> will report an error if a name
  38. in a SQL statement could refer to either a variable or a table column.
  39. You can fix such a problem by renaming the variable or column,
  40. or by qualifying the ambiguous reference, or by telling
  41. <span class="application">PL/pgSQL</span> which interpretation to prefer.
  42. </p><p>
  43. The simplest solution is to rename the variable or column.
  44. A common coding rule is to use a
  45. different naming convention for <span class="application">PL/pgSQL</span>
  46. variables than you use for column names. For example,
  47. if you consistently name function variables
  48. <code class="literal">v_<em class="replaceable"><code>something</code></em></code> while none of your
  49. column names start with <code class="literal">v_</code>, no conflicts will occur.
  50. </p><p>
  51. Alternatively you can qualify ambiguous references to make them clear.
  52. In the above example, <code class="literal">src.foo</code> would be an unambiguous reference
  53. to the table column. To create an unambiguous reference to a variable,
  54. declare it in a labeled block and use the block's label
  55. (see <a class="xref" href="plpgsql-structure.html" title="42.2. Structure of PL/pgSQL">Section 42.2</a>). For example,
  56. </p><pre class="programlisting">
  57. &lt;&lt;block&gt;&gt;
  58. DECLARE
  59. foo int;
  60. BEGIN
  61. foo := ...;
  62. INSERT INTO dest (col) SELECT block.foo + bar FROM src;
  63. </pre><p>
  64. Here <code class="literal">block.foo</code> means the variable even if there is a column
  65. <code class="literal">foo</code> in <code class="literal">src</code>. Function parameters, as well as
  66. special variables such as <code class="literal">FOUND</code>, can be qualified by the
  67. function's name, because they are implicitly declared in an outer block
  68. labeled with the function's name.
  69. </p><p>
  70. Sometimes it is impractical to fix all the ambiguous references in a
  71. large body of <span class="application">PL/pgSQL</span> code. In such cases you can
  72. specify that <span class="application">PL/pgSQL</span> should resolve ambiguous references
  73. as the variable (which is compatible with <span class="application">PL/pgSQL</span>'s
  74. behavior before <span class="productname">PostgreSQL</span> 9.0), or as the
  75. table column (which is compatible with some other systems such as
  76. <span class="productname">Oracle</span>).
  77. </p><a id="id-1.8.8.13.3.9" class="indexterm"></a><p>
  78. To change this behavior on a system-wide basis, set the configuration
  79. parameter <code class="literal">plpgsql.variable_conflict</code> to one of
  80. <code class="literal">error</code>, <code class="literal">use_variable</code>, or
  81. <code class="literal">use_column</code> (where <code class="literal">error</code> is the factory default).
  82. This parameter affects subsequent compilations
  83. of statements in <span class="application">PL/pgSQL</span> functions, but not statements
  84. already compiled in the current session.
  85. Because changing this setting
  86. can cause unexpected changes in the behavior of <span class="application">PL/pgSQL</span>
  87. functions, it can only be changed by a superuser.
  88. </p><p>
  89. You can also set the behavior on a function-by-function basis, by
  90. inserting one of these special commands at the start of the function
  91. text:
  92. </p><pre class="programlisting">
  93. #variable_conflict error
  94. #variable_conflict use_variable
  95. #variable_conflict use_column
  96. </pre><p>
  97. These commands affect only the function they are written in, and override
  98. the setting of <code class="literal">plpgsql.variable_conflict</code>. An example is
  99. </p><pre class="programlisting">
  100. CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
  101. #variable_conflict use_variable
  102. DECLARE
  103. curtime timestamp := now();
  104. BEGIN
  105. UPDATE users SET last_modified = curtime, comment = comment
  106. WHERE users.id = id;
  107. END;
  108. $$ LANGUAGE plpgsql;
  109. </pre><p>
  110. In the <code class="literal">UPDATE</code> command, <code class="literal">curtime</code>, <code class="literal">comment</code>,
  111. and <code class="literal">id</code> will refer to the function's variable and parameters
  112. whether or not <code class="literal">users</code> has columns of those names. Notice
  113. that we had to qualify the reference to <code class="literal">users.id</code> in the
  114. <code class="literal">WHERE</code> clause to make it refer to the table column.
  115. But we did not have to qualify the reference to <code class="literal">comment</code>
  116. as a target in the <code class="literal">UPDATE</code> list, because syntactically
  117. that must be a column of <code class="literal">users</code>. We could write the same
  118. function without depending on the <code class="literal">variable_conflict</code> setting
  119. in this way:
  120. </p><pre class="programlisting">
  121. CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
  122. &lt;&lt;fn&gt;&gt;
  123. DECLARE
  124. curtime timestamp := now();
  125. BEGIN
  126. UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
  127. WHERE users.id = stamp_user.id;
  128. END;
  129. $$ LANGUAGE plpgsql;
  130. </pre><p>
  131. </p><p>
  132. Variable substitution does not happen in the command string given
  133. to <code class="command">EXECUTE</code> or one of its variants. If you need to
  134. insert a varying value into such a command, do so as part of
  135. constructing the string value, or use <code class="literal">USING</code>, as illustrated in
  136. <a class="xref" href="plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" title="42.5.4. Executing Dynamic Commands">Section 42.5.4</a>.
  137. </p><p>
  138. Variable substitution currently works only in <code class="command">SELECT</code>,
  139. <code class="command">INSERT</code>, <code class="command">UPDATE</code>, and <code class="command">DELETE</code> commands,
  140. because the main SQL engine allows query parameters only in these
  141. commands. To use a non-constant name or value in other statement
  142. types (generically called utility statements), you must construct
  143. the utility statement as a string and <code class="command">EXECUTE</code> it.
  144. </p></div><div class="sect2" id="PLPGSQL-PLAN-CACHING"><div class="titlepage"><div><div><h3 class="title">42.11.2. Plan Caching</h3></div></div></div><p>
  145. The <span class="application">PL/pgSQL</span> interpreter parses the function's source
  146. text and produces an internal binary instruction tree the first time the
  147. function is called (within each session). The instruction tree
  148. fully translates the
  149. <span class="application">PL/pgSQL</span> statement structure, but individual
  150. <acronym class="acronym">SQL</acronym> expressions and <acronym class="acronym">SQL</acronym> commands
  151. used in the function are not translated immediately.
  152. </p><p>
  153. <a id="id-1.8.8.13.4.3.1" class="indexterm"></a>
  154. As each expression and <acronym class="acronym">SQL</acronym> command is first
  155. executed in the function, the <span class="application">PL/pgSQL</span> interpreter
  156. parses and analyzes the command to create a prepared statement,
  157. using the <acronym class="acronym">SPI</acronym> manager's
  158. <code class="function">SPI_prepare</code> function.
  159. Subsequent visits to that expression or command
  160. reuse the prepared statement. Thus, a function with conditional code
  161. paths that are seldom visited will never incur the overhead of
  162. analyzing those commands that are never executed within the current
  163. session. A disadvantage is that errors
  164. in a specific expression or command cannot be detected until that
  165. part of the function is reached in execution. (Trivial syntax
  166. errors will be detected during the initial parsing pass, but
  167. anything deeper will not be detected until execution.)
  168. </p><p>
  169. <span class="application">PL/pgSQL</span> (or more precisely, the SPI manager) can
  170. furthermore attempt to cache the execution plan associated with any
  171. particular prepared statement. If a cached plan is not used, then
  172. a fresh execution plan is generated on each visit to the statement,
  173. and the current parameter values (that is, <span class="application">PL/pgSQL</span>
  174. variable values) can be used to optimize the selected plan. If the
  175. statement has no parameters, or is executed many times, the SPI manager
  176. will consider creating a <em class="firstterm">generic</em> plan that is not dependent
  177. on specific parameter values, and caching that for re-use. Typically
  178. this will happen only if the execution plan is not very sensitive to
  179. the values of the <span class="application">PL/pgSQL</span> variables referenced in it.
  180. If it is, generating a plan each time is a net win. See <a class="xref" href="sql-prepare.html" title="PREPARE"><span class="refentrytitle">PREPARE</span></a> for more information about the behavior of
  181. prepared statements.
  182. </p><p>
  183. Because <span class="application">PL/pgSQL</span> saves prepared statements
  184. and sometimes execution plans in this way,
  185. SQL commands that appear directly in a
  186. <span class="application">PL/pgSQL</span> function must refer to the
  187. same tables and columns on every execution; that is, you cannot use
  188. a parameter as the name of a table or column in an SQL command. To get
  189. around this restriction, you can construct dynamic commands using
  190. the <span class="application">PL/pgSQL</span> <code class="command">EXECUTE</code>
  191. statement — at the price of performing new parse analysis and
  192. constructing a new execution plan on every execution.
  193. </p><p>
  194. The mutable nature of record variables presents another problem in this
  195. connection. When fields of a record variable are used in
  196. expressions or statements, the data types of the fields must not
  197. change from one call of the function to the next, since each
  198. expression will be analyzed using the data type that is present
  199. when the expression is first reached. <code class="command">EXECUTE</code> can be
  200. used to get around this problem when necessary.
  201. </p><p>
  202. If the same function is used as a trigger for more than one table,
  203. <span class="application">PL/pgSQL</span> prepares and caches statements
  204. independently for each such table — that is, there is a cache
  205. for each trigger function and table combination, not just for each
  206. function. This alleviates some of the problems with varying
  207. data types; for instance, a trigger function will be able to work
  208. successfully with a column named <code class="literal">key</code> even if it happens
  209. to have different types in different tables.
  210. </p><p>
  211. Likewise, functions having polymorphic argument types have a separate
  212. statement cache for each combination of actual argument types they have
  213. been invoked for, so that data type differences do not cause unexpected
  214. failures.
  215. </p><p>
  216. Statement caching can sometimes have surprising effects on the
  217. interpretation of time-sensitive values. For example there
  218. is a difference between what these two functions do:
  219. </p><pre class="programlisting">
  220. CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
  221. BEGIN
  222. INSERT INTO logtable VALUES (logtxt, 'now');
  223. END;
  224. $$ LANGUAGE plpgsql;
  225. </pre><p>
  226. and:
  227. </p><pre class="programlisting">
  228. CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
  229. DECLARE
  230. curtime timestamp;
  231. BEGIN
  232. curtime := 'now';
  233. INSERT INTO logtable VALUES (logtxt, curtime);
  234. END;
  235. $$ LANGUAGE plpgsql;
  236. </pre><p>
  237. </p><p>
  238. In the case of <code class="function">logfunc1</code>, the
  239. <span class="productname">PostgreSQL</span> main parser knows when
  240. analyzing the <code class="command">INSERT</code> that the
  241. string <code class="literal">'now'</code> should be interpreted as
  242. <code class="type">timestamp</code>, because the target column of
  243. <code class="classname">logtable</code> is of that type. Thus,
  244. <code class="literal">'now'</code> will be converted to a <code class="type">timestamp</code>
  245. constant when the
  246. <code class="command">INSERT</code> is analyzed, and then used in all
  247. invocations of <code class="function">logfunc1</code> during the lifetime
  248. of the session. Needless to say, this isn't what the programmer
  249. wanted. A better idea is to use the <code class="literal">now()</code> or
  250. <code class="literal">current_timestamp</code> function.
  251. </p><p>
  252. In the case of <code class="function">logfunc2</code>, the
  253. <span class="productname">PostgreSQL</span> main parser does not know
  254. what type <code class="literal">'now'</code> should become and therefore
  255. it returns a data value of type <code class="type">text</code> containing the string
  256. <code class="literal">now</code>. During the ensuing assignment
  257. to the local variable <code class="varname">curtime</code>, the
  258. <span class="application">PL/pgSQL</span> interpreter casts this
  259. string to the <code class="type">timestamp</code> type by calling the
  260. <code class="function">textout</code> and <code class="function">timestamp_in</code>
  261. functions for the conversion. So, the computed time stamp is updated
  262. on each execution as the programmer expects. Even though this
  263. happens to work as expected, it's not terribly efficient, so
  264. use of the <code class="literal">now()</code> function would still be a better idea.
  265. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plpgsql-trigger.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plpgsql.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plpgsql-development-tips.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">42.10. Trigger Functions </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 42.12. Tips for Developing in <span class="application">PL/pgSQL</span></td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1