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.

493 lines
36KB

  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>CREATE FUNCTION</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="sql-createforeigntable.html" title="CREATE FOREIGN TABLE" /><link rel="next" href="sql-creategroup.html" title="CREATE GROUP" /></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">CREATE FUNCTION</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="sql-createforeigntable.html" title="CREATE FOREIGN TABLE">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><th width="60%" align="center">SQL Commands</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="sql-creategroup.html" title="CREATE GROUP">Next</a></td></tr></table><hr></hr></div><div class="refentry" id="SQL-CREATEFUNCTION"><div class="titlepage"></div><a id="id-1.9.3.67.1" class="indexterm"></a><div class="refnamediv"><h2><span class="refentrytitle">CREATE FUNCTION</span></h2><p>CREATE FUNCTION — define a new function</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><pre class="synopsis">
  3. CREATE [ OR REPLACE ] FUNCTION
  4. <em class="replaceable"><code>name</code></em> ( [ [ <em class="replaceable"><code>argmode</code></em> ] [ <em class="replaceable"><code>argname</code></em> ] <em class="replaceable"><code>argtype</code></em> [ { DEFAULT | = } <em class="replaceable"><code>default_expr</code></em> ] [, ...] ] )
  5. [ RETURNS <em class="replaceable"><code>rettype</code></em>
  6. | RETURNS TABLE ( <em class="replaceable"><code>column_name</code></em> <em class="replaceable"><code>column_type</code></em> [, ...] ) ]
  7. { LANGUAGE <em class="replaceable"><code>lang_name</code></em>
  8. | TRANSFORM { FOR TYPE <em class="replaceable"><code>type_name</code></em> } [, ... ]
  9. | WINDOW
  10. | IMMUTABLE | STABLE | VOLATILE | [ NOT ] LEAKPROOF
  11. | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
  12. | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
  13. | PARALLEL { UNSAFE | RESTRICTED | SAFE }
  14. | COST <em class="replaceable"><code>execution_cost</code></em>
  15. | ROWS <em class="replaceable"><code>result_rows</code></em>
  16. | SUPPORT <em class="replaceable"><code>support_function</code></em>
  17. | SET <em class="replaceable"><code>configuration_parameter</code></em> { TO <em class="replaceable"><code>value</code></em> | = <em class="replaceable"><code>value</code></em> | FROM CURRENT }
  18. | AS '<em class="replaceable"><code>definition</code></em>'
  19. | AS '<em class="replaceable"><code>obj_file</code></em>', '<em class="replaceable"><code>link_symbol</code></em>'
  20. } ...
  21. </pre></div><div class="refsect1" id="SQL-CREATEFUNCTION-DESCRIPTION"><h2>Description</h2><p>
  22. <code class="command">CREATE FUNCTION</code> defines a new function.
  23. <code class="command">CREATE OR REPLACE FUNCTION</code> will either create a
  24. new function, or replace an existing definition.
  25. To be able to define a function, the user must have the
  26. <code class="literal">USAGE</code> privilege on the language.
  27. </p><p>
  28. If a schema name is included, then the function is created in the
  29. specified schema. Otherwise it is created in the current schema.
  30. The name of the new function must not match any existing function or procedure
  31. with the same input argument types in the same schema. However,
  32. functions and procedures of different argument types can share a name (this is
  33. called <em class="firstterm">overloading</em>).
  34. </p><p>
  35. To replace the current definition of an existing function, use
  36. <code class="command">CREATE OR REPLACE FUNCTION</code>. It is not possible
  37. to change the name or argument types of a function this way (if you
  38. tried, you would actually be creating a new, distinct function).
  39. Also, <code class="command">CREATE OR REPLACE FUNCTION</code> will not let
  40. you change the return type of an existing function. To do that,
  41. you must drop and recreate the function. (When using <code class="literal">OUT</code>
  42. parameters, that means you cannot change the types of any
  43. <code class="literal">OUT</code> parameters except by dropping the function.)
  44. </p><p>
  45. When <code class="command">CREATE OR REPLACE FUNCTION</code> is used to replace an
  46. existing function, the ownership and permissions of the function
  47. do not change. All other function properties are assigned the
  48. values specified or implied in the command. You must own the function
  49. to replace it (this includes being a member of the owning role).
  50. </p><p>
  51. If you drop and then recreate a function, the new function is not
  52. the same entity as the old; you will have to drop existing rules, views,
  53. triggers, etc. that refer to the old function. Use
  54. <code class="command">CREATE OR REPLACE FUNCTION</code> to change a function
  55. definition without breaking objects that refer to the function.
  56. Also, <code class="command">ALTER FUNCTION</code> can be used to change most of the
  57. auxiliary properties of an existing function.
  58. </p><p>
  59. The user that creates the function becomes the owner of the function.
  60. </p><p>
  61. To be able to create a function, you must have <code class="literal">USAGE</code>
  62. privilege on the argument types and the return type.
  63. </p></div><div class="refsect1" id="id-1.9.3.67.6"><h2>Parameters</h2><div class="variablelist"><dl class="variablelist"><dt><span class="term"><em class="replaceable"><code>name</code></em></span></dt><dd><p>
  64. The name (optionally schema-qualified) of the function to create.
  65. </p></dd><dt><span class="term"><em class="replaceable"><code>argmode</code></em></span></dt><dd><p>
  66. The mode of an argument: <code class="literal">IN</code>, <code class="literal">OUT</code>,
  67. <code class="literal">INOUT</code>, or <code class="literal">VARIADIC</code>.
  68. If omitted, the default is <code class="literal">IN</code>.
  69. Only <code class="literal">OUT</code> arguments can follow a <code class="literal">VARIADIC</code> one.
  70. Also, <code class="literal">OUT</code> and <code class="literal">INOUT</code> arguments cannot be used
  71. together with the <code class="literal">RETURNS TABLE</code> notation.
  72. </p></dd><dt><span class="term"><em class="replaceable"><code>argname</code></em></span></dt><dd><p>
  73. The name of an argument. Some languages (including SQL and PL/pgSQL)
  74. let you use the name in the function body. For other languages the
  75. name of an input argument is just extra documentation, so far as
  76. the function itself is concerned; but you can use input argument names
  77. when calling a function to improve readability (see <a class="xref" href="sql-syntax-calling-funcs.html" title="4.3. Calling Functions">Section 4.3</a>). In any case, the name
  78. of an output argument is significant, because it defines the column
  79. name in the result row type. (If you omit the name for an output
  80. argument, the system will choose a default column name.)
  81. </p></dd><dt><span class="term"><em class="replaceable"><code>argtype</code></em></span></dt><dd><p>
  82. The data type(s) of the function's arguments (optionally
  83. schema-qualified), if any. The argument types can be base, composite,
  84. or domain types, or can reference the type of a table column.
  85. </p><p>
  86. Depending on the implementation language it might also be allowed
  87. to specify <span class="quote">“<span class="quote">pseudo-types</span>”</span> such as <code class="type">cstring</code>.
  88. Pseudo-types indicate that the actual argument type is either
  89. incompletely specified, or outside the set of ordinary SQL data types.
  90. </p><p>
  91. The type of a column is referenced by writing
  92. <code class="literal"><em class="replaceable"><code>table_name</code></em>.<em class="replaceable"><code>column_name</code></em>%TYPE</code>.
  93. Using this feature can sometimes help make a function independent of
  94. changes to the definition of a table.
  95. </p></dd><dt><span class="term"><em class="replaceable"><code>default_expr</code></em></span></dt><dd><p>
  96. An expression to be used as default value if the parameter is
  97. not specified. The expression has to be coercible to the
  98. argument type of the parameter.
  99. Only input (including <code class="literal">INOUT</code>) parameters can have a default
  100. value. All input parameters following a
  101. parameter with a default value must have default values as well.
  102. </p></dd><dt><span class="term"><em class="replaceable"><code>rettype</code></em></span></dt><dd><p>
  103. The return data type (optionally schema-qualified). The return type
  104. can be a base, composite, or domain type,
  105. or can reference the type of a table column.
  106. Depending on the implementation language it might also be allowed
  107. to specify <span class="quote">“<span class="quote">pseudo-types</span>”</span> such as <code class="type">cstring</code>.
  108. If the function is not supposed to return a value, specify
  109. <code class="type">void</code> as the return type.
  110. </p><p>
  111. When there are <code class="literal">OUT</code> or <code class="literal">INOUT</code> parameters,
  112. the <code class="literal">RETURNS</code> clause can be omitted. If present, it
  113. must agree with the result type implied by the output parameters:
  114. <code class="literal">RECORD</code> if there are multiple output parameters, or
  115. the same type as the single output parameter.
  116. </p><p>
  117. The <code class="literal">SETOF</code>
  118. modifier indicates that the function will return a set of
  119. items, rather than a single item.
  120. </p><p>
  121. The type of a column is referenced by writing
  122. <code class="literal"><em class="replaceable"><code>table_name</code></em>.<em class="replaceable"><code>column_name</code></em>%TYPE</code>.
  123. </p></dd><dt><span class="term"><em class="replaceable"><code>column_name</code></em></span></dt><dd><p>
  124. The name of an output column in the <code class="literal">RETURNS TABLE</code>
  125. syntax. This is effectively another way of declaring a named
  126. <code class="literal">OUT</code> parameter, except that <code class="literal">RETURNS TABLE</code>
  127. also implies <code class="literal">RETURNS SETOF</code>.
  128. </p></dd><dt><span class="term"><em class="replaceable"><code>column_type</code></em></span></dt><dd><p>
  129. The data type of an output column in the <code class="literal">RETURNS TABLE</code>
  130. syntax.
  131. </p></dd><dt><span class="term"><em class="replaceable"><code>lang_name</code></em></span></dt><dd><p>
  132. The name of the language that the function is implemented in.
  133. It can be <code class="literal">sql</code>, <code class="literal">c</code>,
  134. <code class="literal">internal</code>, or the name of a user-defined
  135. procedural language, e.g. <code class="literal">plpgsql</code>. Enclosing the
  136. name in single quotes is deprecated and requires matching case.
  137. </p></dd><dt><span class="term"><code class="literal">TRANSFORM { FOR TYPE <em class="replaceable"><code>type_name</code></em> } [, ... ] }</code></span></dt><dd><p>
  138. Lists which transforms a call to the function should apply. Transforms
  139. convert between SQL types and language-specific data types;
  140. see <a class="xref" href="sql-createtransform.html" title="CREATE TRANSFORM"><span class="refentrytitle">CREATE TRANSFORM</span></a>. Procedural language
  141. implementations usually have hardcoded knowledge of the built-in types,
  142. so those don't need to be listed here. If a procedural language
  143. implementation does not know how to handle a type and no transform is
  144. supplied, it will fall back to a default behavior for converting data
  145. types, but this depends on the implementation.
  146. </p></dd><dt><span class="term"><code class="literal">WINDOW</code></span></dt><dd><p><code class="literal">WINDOW</code> indicates that the function is a
  147. <em class="firstterm">window function</em> rather than a plain function.
  148. This is currently only useful for functions written in C.
  149. The <code class="literal">WINDOW</code> attribute cannot be changed when
  150. replacing an existing function definition.
  151. </p></dd><dt><span class="term"><code class="literal">IMMUTABLE</code><br /></span><span class="term"><code class="literal">STABLE</code><br /></span><span class="term"><code class="literal">VOLATILE</code></span></dt><dd><p>
  152. These attributes inform the query optimizer about the behavior
  153. of the function. At most one choice
  154. can be specified. If none of these appear,
  155. <code class="literal">VOLATILE</code> is the default assumption.
  156. </p><p><code class="literal">IMMUTABLE</code> indicates that the function
  157. cannot modify the database and always
  158. returns the same result when given the same argument values; that
  159. is, it does not do database lookups or otherwise use information not
  160. directly present in its argument list. If this option is given,
  161. any call of the function with all-constant arguments can be
  162. immediately replaced with the function value.
  163. </p><p><code class="literal">STABLE</code> indicates that the function
  164. cannot modify the database,
  165. and that within a single table scan it will consistently
  166. return the same result for the same argument values, but that its
  167. result could change across SQL statements. This is the appropriate
  168. selection for functions whose results depend on database lookups,
  169. parameter variables (such as the current time zone), etc. (It is
  170. inappropriate for <code class="literal">AFTER</code> triggers that wish to
  171. query rows modified by the current command.) Also note
  172. that the <code class="function">current_timestamp</code> family of functions qualify
  173. as stable, since their values do not change within a transaction.
  174. </p><p><code class="literal">VOLATILE</code> indicates that the function value can
  175. change even within a single table scan, so no optimizations can be
  176. made. Relatively few database functions are volatile in this sense;
  177. some examples are <code class="literal">random()</code>, <code class="literal">currval()</code>,
  178. <code class="literal">timeofday()</code>. But note that any function that has
  179. side-effects must be classified volatile, even if its result is quite
  180. predictable, to prevent calls from being optimized away; an example is
  181. <code class="literal">setval()</code>.
  182. </p><p>
  183. For additional details see <a class="xref" href="xfunc-volatility.html" title="37.7. Function Volatility Categories">Section 37.7</a>.
  184. </p></dd><dt><span class="term"><code class="literal">LEAKPROOF</code></span></dt><dd><p>
  185. <code class="literal">LEAKPROOF</code> indicates that the function has no side
  186. effects. It reveals no information about its arguments other than by
  187. its return value. For example, a function which throws an error message
  188. for some argument values but not others, or which includes the argument
  189. values in any error message, is not leakproof. This affects how the
  190. system executes queries against views created with the
  191. <code class="literal">security_barrier</code> option or tables with row level
  192. security enabled. The system will enforce conditions from security
  193. policies and security barrier views before any user-supplied conditions
  194. from the query itself that contain non-leakproof functions, in order to
  195. prevent the inadvertent exposure of data. Functions and operators
  196. marked as leakproof are assumed to be trustworthy, and may be executed
  197. before conditions from security policies and security barrier views.
  198. In addition, functions which do not take arguments or which are not
  199. passed any arguments from the security barrier view or table do not have
  200. to be marked as leakproof to be executed before security conditions. See
  201. <a class="xref" href="sql-createview.html" title="CREATE VIEW"><span class="refentrytitle">CREATE VIEW</span></a> and <a class="xref" href="rules-privileges.html" title="40.5. Rules and Privileges">Section 40.5</a>.
  202. This option can only be set by the superuser.
  203. </p></dd><dt><span class="term"><code class="literal">CALLED ON NULL INPUT</code><br /></span><span class="term"><code class="literal">RETURNS NULL ON NULL INPUT</code><br /></span><span class="term"><code class="literal">STRICT</code></span></dt><dd><p><code class="literal">CALLED ON NULL INPUT</code> (the default) indicates
  204. that the function will be called normally when some of its
  205. arguments are null. It is then the function author's
  206. responsibility to check for null values if necessary and respond
  207. appropriately.
  208. </p><p><code class="literal">RETURNS NULL ON NULL INPUT</code> or
  209. <code class="literal">STRICT</code> indicates that the function always
  210. returns null whenever any of its arguments are null. If this
  211. parameter is specified, the function is not executed when there
  212. are null arguments; instead a null result is assumed
  213. automatically.
  214. </p></dd><dt><span class="term"><code class="literal">[<span class="optional">EXTERNAL</span>] SECURITY INVOKER</code><br /></span><span class="term"><code class="literal">[<span class="optional">EXTERNAL</span>] SECURITY DEFINER</code></span></dt><dd><p><code class="literal">SECURITY INVOKER</code> indicates that the function
  215. is to be executed with the privileges of the user that calls it.
  216. That is the default. <code class="literal">SECURITY DEFINER</code>
  217. specifies that the function is to be executed with the
  218. privileges of the user that owns it.
  219. </p><p>
  220. The key word <code class="literal">EXTERNAL</code> is allowed for SQL
  221. conformance, but it is optional since, unlike in SQL, this feature
  222. applies to all functions not only external ones.
  223. </p></dd><dt><span class="term"><code class="literal">PARALLEL</code></span></dt><dd><p><code class="literal">PARALLEL UNSAFE</code> indicates that the function
  224. can't be executed in parallel mode and the presence of such a
  225. function in an SQL statement forces a serial execution plan. This is
  226. the default. <code class="literal">PARALLEL RESTRICTED</code> indicates that
  227. the function can be executed in parallel mode, but the execution is
  228. restricted to parallel group leader. <code class="literal">PARALLEL SAFE</code>
  229. indicates that the function is safe to run in parallel mode without
  230. restriction.
  231. </p><p>
  232. Functions should be labeled parallel unsafe if they modify any database
  233. state, or if they make changes to the transaction such as using
  234. sub-transactions, or if they access sequences or attempt to make
  235. persistent changes to settings (e.g. <code class="literal">setval</code>). They should
  236. be labeled as parallel restricted if they access temporary tables,
  237. client connection state, cursors, prepared statements, or miscellaneous
  238. backend-local state which the system cannot synchronize in parallel mode
  239. (e.g. <code class="literal">setseed</code> cannot be executed other than by the group
  240. leader because a change made by another process would not be reflected
  241. in the leader). In general, if a function is labeled as being safe when
  242. it is restricted or unsafe, or if it is labeled as being restricted when
  243. it is in fact unsafe, it may throw errors or produce wrong answers
  244. when used in a parallel query. C-language functions could in theory
  245. exhibit totally undefined behavior if mislabeled, since there is no way
  246. for the system to protect itself against arbitrary C code, but in most
  247. likely cases the result will be no worse than for any other function.
  248. If in doubt, functions should be labeled as <code class="literal">UNSAFE</code>, which is
  249. the default.
  250. </p></dd><dt><span class="term"><code class="literal">COST</code> <em class="replaceable"><code>execution_cost</code></em></span></dt><dd><p>
  251. A positive number giving the estimated execution cost for the function,
  252. in units of <a class="xref" href="runtime-config-query.html#GUC-CPU-OPERATOR-COST">cpu_operator_cost</a>. If the function
  253. returns a set, this is the cost per returned row. If the cost is
  254. not specified, 1 unit is assumed for C-language and internal functions,
  255. and 100 units for functions in all other languages. Larger values
  256. cause the planner to try to avoid evaluating the function more often
  257. than necessary.
  258. </p></dd><dt><span class="term"><code class="literal">ROWS</code> <em class="replaceable"><code>result_rows</code></em></span></dt><dd><p>
  259. A positive number giving the estimated number of rows that the planner
  260. should expect the function to return. This is only allowed when the
  261. function is declared to return a set. The default assumption is
  262. 1000 rows.
  263. </p></dd><dt><span class="term"><code class="literal">SUPPORT</code> <em class="replaceable"><code>support_function</code></em></span></dt><dd><p>
  264. The name (optionally schema-qualified) of a <em class="firstterm">planner support
  265. function</em> to use for this function. See
  266. <a class="xref" href="xfunc-optimization.html" title="37.11. Function Optimization Information">Section 37.11</a> for details.
  267. You must be superuser to use this option.
  268. </p></dd><dt><span class="term"><em class="replaceable"><code>configuration_parameter</code></em><br /></span><span class="term"><em class="replaceable"><code>value</code></em></span></dt><dd><p>
  269. The <code class="literal">SET</code> clause causes the specified configuration
  270. parameter to be set to the specified value when the function is
  271. entered, and then restored to its prior value when the function exits.
  272. <code class="literal">SET FROM CURRENT</code> saves the value of the parameter that
  273. is current when <code class="command">CREATE FUNCTION</code> is executed as the value
  274. to be applied when the function is entered.
  275. </p><p>
  276. If a <code class="literal">SET</code> clause is attached to a function, then
  277. the effects of a <code class="command">SET LOCAL</code> command executed inside the
  278. function for the same variable are restricted to the function: the
  279. configuration parameter's prior value is still restored at function exit.
  280. However, an ordinary
  281. <code class="command">SET</code> command (without <code class="literal">LOCAL</code>) overrides the
  282. <code class="literal">SET</code> clause, much as it would do for a previous <code class="command">SET
  283. LOCAL</code> command: the effects of such a command will persist after
  284. function exit, unless the current transaction is rolled back.
  285. </p><p>
  286. See <a class="xref" href="sql-set.html" title="SET"><span class="refentrytitle">SET</span></a> and
  287. <a class="xref" href="runtime-config.html" title="Chapter 19. Server Configuration">Chapter 19</a>
  288. for more information about allowed parameter names and values.
  289. </p></dd><dt><span class="term"><em class="replaceable"><code>definition</code></em></span></dt><dd><p>
  290. A string constant defining the function; the meaning depends on the
  291. language. It can be an internal function name, the path to an
  292. object file, an SQL command, or text in a procedural language.
  293. </p><p>
  294. It is often helpful 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>) to write the function definition
  295. string, rather than the normal single quote syntax. Without dollar
  296. quoting, any single quotes or backslashes in the function definition must
  297. be escaped by doubling them.
  298. </p></dd><dt><span class="term"><code class="literal"><em class="replaceable"><code>obj_file</code></em>, <em class="replaceable"><code>link_symbol</code></em></code></span></dt><dd><p>
  299. This form of the <code class="literal">AS</code> clause is used for
  300. dynamically loadable C language functions when the function name
  301. in the C language source code is not the same as the name of
  302. the SQL function. The string <em class="replaceable"><code>obj_file</code></em> is the name of the shared
  303. library file containing the compiled C function, and is interpreted
  304. as for the <a class="xref" href="sql-load.html" title="LOAD"><span class="refentrytitle">LOAD</span></a> command. The string
  305. <em class="replaceable"><code>link_symbol</code></em> is the
  306. function's link symbol, that is, the name of the function in the C
  307. language source code. If the link symbol is omitted, it is assumed to
  308. be the same as the name of the SQL function being defined. The C names
  309. of all functions must be different, so you must give overloaded C
  310. functions different C names (for example, use the argument types as
  311. part of the C names).
  312. </p><p>
  313. When repeated <code class="command">CREATE FUNCTION</code> calls refer to
  314. the same object file, the file is only loaded once per session.
  315. To unload and
  316. reload the file (perhaps during development), start a new session.
  317. </p></dd></dl></div><p>
  318. Refer to <a class="xref" href="xfunc.html" title="37.3. User-Defined Functions">Section 37.3</a> for further information on writing
  319. functions.
  320. </p></div><div class="refsect1" id="SQL-CREATEFUNCTION-OVERLOADING"><h2>Overloading</h2><p>
  321. <span class="productname">PostgreSQL</span> allows function
  322. <em class="firstterm">overloading</em>; that is, the same name can be
  323. used for several different functions so long as they have distinct
  324. input argument types. Whether or not you use it, this capability entails
  325. security precautions when calling functions in databases where some users
  326. mistrust other users; see <a class="xref" href="typeconv-func.html" title="10.3. Functions">Section 10.3</a>.
  327. </p><p>
  328. Two functions are considered the same if they have the same names and
  329. <span class="emphasis"><em>input</em></span> argument types, ignoring any <code class="literal">OUT</code>
  330. parameters. Thus for example these declarations conflict:
  331. </p><pre class="programlisting">
  332. CREATE FUNCTION foo(int) ...
  333. CREATE FUNCTION foo(int, out text) ...
  334. </pre><p>
  335. </p><p>
  336. Functions that have different argument type lists will not be considered
  337. to conflict at creation time, but if defaults are provided they might
  338. conflict in use. For example, consider
  339. </p><pre class="programlisting">
  340. CREATE FUNCTION foo(int) ...
  341. CREATE FUNCTION foo(int, int default 42) ...
  342. </pre><p>
  343. A call <code class="literal">foo(10)</code> will fail due to the ambiguity about which
  344. function should be called.
  345. </p></div><div class="refsect1" id="SQL-CREATEFUNCTION-NOTES"><h2>Notes</h2><p>
  346. The full <acronym class="acronym">SQL</acronym> type syntax is allowed for
  347. declaring a function's arguments and return value. However,
  348. parenthesized type modifiers (e.g., the precision field for
  349. type <code class="type">numeric</code>) are discarded by <code class="command">CREATE FUNCTION</code>.
  350. Thus for example
  351. <code class="literal">CREATE FUNCTION foo (varchar(10)) ...</code>
  352. is exactly the same as
  353. <code class="literal">CREATE FUNCTION foo (varchar) ...</code>.
  354. </p><p>
  355. When replacing an existing function with <code class="command">CREATE OR REPLACE
  356. FUNCTION</code>, there are restrictions on changing parameter names.
  357. You cannot change the name already assigned to any input parameter
  358. (although you can add names to parameters that had none before).
  359. If there is more than one output parameter, you cannot change the
  360. names of the output parameters, because that would change the
  361. column names of the anonymous composite type that describes the
  362. function's result. These restrictions are made to ensure that
  363. existing calls of the function do not stop working when it is replaced.
  364. </p><p>
  365. If a function is declared <code class="literal">STRICT</code> with a <code class="literal">VARIADIC</code>
  366. argument, the strictness check tests that the variadic array <span class="emphasis"><em>as
  367. a whole</em></span> is non-null. The function will still be called if the
  368. array has null elements.
  369. </p></div><div class="refsect1" id="SQL-CREATEFUNCTION-EXAMPLES"><h2>Examples</h2><p>
  370. Here are some trivial examples to help you get started. For more
  371. information and examples, see <a class="xref" href="xfunc.html" title="37.3. User-Defined Functions">Section 37.3</a>.
  372. </p><pre class="programlisting">
  373. CREATE FUNCTION add(integer, integer) RETURNS integer
  374. AS 'select $1 + $2;'
  375. LANGUAGE SQL
  376. IMMUTABLE
  377. RETURNS NULL ON NULL INPUT;
  378. </pre><p>
  379. </p><p>
  380. Increment an integer, making use of an argument name, in
  381. <span class="application">PL/pgSQL</span>:
  382. </p><pre class="programlisting">
  383. CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
  384. BEGIN
  385. RETURN i + 1;
  386. END;
  387. $$ LANGUAGE plpgsql;
  388. </pre><p>
  389. </p><p>
  390. Return a record containing multiple output parameters:
  391. </p><pre class="programlisting">
  392. CREATE FUNCTION dup(in int, out f1 int, out f2 text)
  393. AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
  394. LANGUAGE SQL;
  395. SELECT * FROM dup(42);
  396. </pre><p>
  397. You can do the same thing more verbosely with an explicitly named
  398. composite type:
  399. </p><pre class="programlisting">
  400. CREATE TYPE dup_result AS (f1 int, f2 text);
  401. CREATE FUNCTION dup(int) RETURNS dup_result
  402. AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
  403. LANGUAGE SQL;
  404. SELECT * FROM dup(42);
  405. </pre><p>
  406. Another way to return multiple columns is to use a <code class="literal">TABLE</code>
  407. function:
  408. </p><pre class="programlisting">
  409. CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
  410. AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
  411. LANGUAGE SQL;
  412. SELECT * FROM dup(42);
  413. </pre><p>
  414. However, a <code class="literal">TABLE</code> function is different from the
  415. preceding examples, because it actually returns a <span class="emphasis"><em>set</em></span>
  416. of records, not just one record.
  417. </p></div><div class="refsect1" id="SQL-CREATEFUNCTION-SECURITY"><h2>Writing <code class="literal">SECURITY DEFINER</code> Functions Safely</h2><a id="id-1.9.3.67.10.2" class="indexterm"></a><p>
  418. Because a <code class="literal">SECURITY DEFINER</code> function is executed
  419. with the privileges of the user that owns it, care is needed to
  420. ensure that the function cannot be misused. For security,
  421. <a class="xref" href="runtime-config-client.html#GUC-SEARCH-PATH">search_path</a> should be set to exclude any schemas
  422. writable by untrusted users. This prevents
  423. malicious users from creating objects (e.g., tables, functions, and
  424. operators) that mask objects intended to be used by the function.
  425. Particularly important in this regard is the
  426. temporary-table schema, which is searched first by default, and
  427. is normally writable by anyone. A secure arrangement can be obtained
  428. by forcing the temporary schema to be searched last. To do this,
  429. write <code class="literal">pg_temp</code><a id="id-1.9.3.67.10.3.4" class="indexterm"></a> as the last entry in <code class="varname">search_path</code>.
  430. This function illustrates safe usage:
  431. </p><pre class="programlisting">
  432. CREATE FUNCTION check_password(uname TEXT, pass TEXT)
  433. RETURNS BOOLEAN AS $$
  434. DECLARE passed BOOLEAN;
  435. BEGIN
  436. SELECT (pwd = $2) INTO passed
  437. FROM pwds
  438. WHERE username = $1;
  439. RETURN passed;
  440. END;
  441. $$ LANGUAGE plpgsql
  442. SECURITY DEFINER
  443. -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
  444. SET search_path = admin, pg_temp;
  445. </pre><p>
  446. This function's intention is to access a table <code class="literal">admin.pwds</code>.
  447. But without the <code class="literal">SET</code> clause, or with a <code class="literal">SET</code> clause
  448. mentioning only <code class="literal">admin</code>, the function could be subverted by
  449. creating a temporary table named <code class="literal">pwds</code>.
  450. </p><p>
  451. Before <span class="productname">PostgreSQL</span> version 8.3, the
  452. <code class="literal">SET</code> clause was not available, and so older functions may
  453. contain rather complicated logic to save, set, and restore
  454. <code class="varname">search_path</code>. The <code class="literal">SET</code> clause is far easier
  455. to use for this purpose.
  456. </p><p>
  457. Another point to keep in mind is that by default, execute privilege
  458. is granted to <code class="literal">PUBLIC</code> for newly created functions
  459. (see <a class="xref" href="ddl-priv.html" title="5.7. Privileges">Section 5.7</a> for more
  460. information). Frequently you will wish to restrict use of a security
  461. definer function to only some users. To do that, you must revoke
  462. the default <code class="literal">PUBLIC</code> privileges and then grant execute
  463. privilege selectively. To avoid having a window where the new function
  464. is accessible to all, create it and set the privileges within a single
  465. transaction. For example:
  466. </p><pre class="programlisting">
  467. BEGIN;
  468. CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
  469. REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
  470. GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
  471. COMMIT;
  472. </pre></div><div class="refsect1" id="SQL-CREATEFUNCTION-COMPAT"><h2>Compatibility</h2><p>
  473. A <code class="command">CREATE FUNCTION</code> command is defined in the SQL standard.
  474. The <span class="productname">PostgreSQL</span> version is similar but
  475. not fully compatible. The attributes are not portable, neither are the
  476. different available languages.
  477. </p><p>
  478. For compatibility with some other database systems,
  479. <em class="replaceable"><code>argmode</code></em> can be written
  480. either before or after <em class="replaceable"><code>argname</code></em>.
  481. But only the first way is standard-compliant.
  482. </p><p>
  483. For parameter defaults, the SQL standard specifies only the syntax with
  484. the <code class="literal">DEFAULT</code> key word. The syntax
  485. with <code class="literal">=</code> is used in T-SQL and Firebird.
  486. </p></div><div class="refsect1" id="id-1.9.3.67.12"><h2>See Also</h2><span class="simplelist"><a class="xref" href="sql-alterfunction.html" title="ALTER FUNCTION"><span class="refentrytitle">ALTER FUNCTION</span></a>, <a class="xref" href="sql-dropfunction.html" title="DROP FUNCTION"><span class="refentrytitle">DROP FUNCTION</span></a>, <a class="xref" href="sql-grant.html" title="GRANT"><span class="refentrytitle">GRANT</span></a>, <a class="xref" href="sql-load.html" title="LOAD"><span class="refentrytitle">LOAD</span></a>, <a class="xref" href="sql-revoke.html" title="REVOKE"><span class="refentrytitle">REVOKE</span></a></span></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="sql-createforeigntable.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="sql-commands.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sql-creategroup.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">CREATE FOREIGN TABLE </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> CREATE GROUP</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1