]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_function.sgml
Trim trailing whitespace
[postgresql] / doc / src / sgml / ref / create_function.sgml
1 <!--
2 doc/src/sgml/ref/create_function.sgml
3 -->
4
5 <refentry id="SQL-CREATEFUNCTION">
6  <indexterm zone="sql-createfunction">
7   <primary>CREATE FUNCTION</primary>
8  </indexterm>
9
10  <refmeta>
11   <refentrytitle>CREATE FUNCTION</refentrytitle>
12   <manvolnum>7</manvolnum>
13   <refmiscinfo>SQL - Language Statements</refmiscinfo>
14  </refmeta>
15
16  <refnamediv>
17   <refname>CREATE FUNCTION</refname>
18   <refpurpose>define a new function</refpurpose>
19  </refnamediv>
20
21  <refsynopsisdiv>
22 <synopsis>
23 CREATE [ OR REPLACE ] FUNCTION
24     <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [ { DEFAULT | = } <replaceable class="parameter">default_expr</replaceable> ] [, ...] ] )
25     [ RETURNS <replaceable class="parameter">rettype</replaceable>
26       | RETURNS TABLE ( <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">column_type</replaceable> [, ...] ) ]
27   { LANGUAGE <replaceable class="parameter">lang_name</replaceable>
28     | TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ]
29     | WINDOW
30     | IMMUTABLE | STABLE | VOLATILE | [ NOT ] LEAKPROOF
31     | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
32     | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
33     | PARALLEL { UNSAFE | RESTRICTED | SAFE }
34     | COST <replaceable class="parameter">execution_cost</replaceable>
35     | ROWS <replaceable class="parameter">result_rows</replaceable>
36     | SET <replaceable class="parameter">configuration_parameter</replaceable> { TO <replaceable class="parameter">value</replaceable> | = <replaceable class="parameter">value</replaceable> | FROM CURRENT }
37     | AS '<replaceable class="parameter">definition</replaceable>'
38     | AS '<replaceable class="parameter">obj_file</replaceable>', '<replaceable class="parameter">link_symbol</replaceable>'
39   } ...
40     [ WITH ( <replaceable class="parameter">attribute</replaceable> [, ...] ) ]
41 </synopsis>
42  </refsynopsisdiv>
43
44  <refsect1 id="sql-createfunction-description">
45   <title>Description</title>
46
47   <para>
48    <command>CREATE FUNCTION</command> defines a new function.
49    <command>CREATE OR REPLACE FUNCTION</command> will either create a
50    new function, or replace an existing definition.
51    To be able to define a function, the user must have the
52    <literal>USAGE</literal> privilege on the language.
53   </para>
54
55   <para>
56    If a schema name is included, then the function is created in the
57    specified schema.  Otherwise it is created in the current schema.
58    The name of the new function must not match any existing function
59    with the same input argument types in the same schema.  However,
60    functions of different argument types can share a name (this is
61    called <firstterm>overloading</>).
62   </para>
63
64   <para>
65    To replace the current definition of an existing function, use
66    <command>CREATE OR REPLACE FUNCTION</command>.  It is not possible
67    to change the name or argument types of a function this way (if you
68    tried, you would actually be creating a new, distinct function).
69    Also, <command>CREATE OR REPLACE FUNCTION</command> will not let
70    you change the return type of an existing function.  To do that,
71    you must drop and recreate the function.  (When using <literal>OUT</>
72    parameters, that means you cannot change the types of any
73    <literal>OUT</> parameters except by dropping the function.)
74   </para>
75
76   <para>
77    When <command>CREATE OR REPLACE FUNCTION</> is used to replace an
78    existing function, the ownership and permissions of the function
79    do not change.  All other function properties are assigned the
80    values specified or implied in the command.  You must own the function
81    to replace it (this includes being a member of the owning role).
82   </para>
83
84   <para>
85    If you drop and then recreate a function, the new function is not
86    the same entity as the old; you will have to drop existing rules, views,
87    triggers, etc. that refer to the old function.  Use
88    <command>CREATE OR REPLACE FUNCTION</command> to change a function
89    definition without breaking objects that refer to the function.
90    Also, <command>ALTER FUNCTION</> can be used to change most of the
91    auxiliary properties of an existing function.
92   </para>
93
94   <para>
95    The user that creates the function becomes the owner of the function.
96   </para>
97
98   <para>
99    To be able to create a function, you must have <literal>USAGE</literal>
100    privilege on the argument types and the return type.
101   </para>
102  </refsect1>
103
104  <refsect1>
105   <title>Parameters</title>
106
107    <variablelist>
108
109     <varlistentry>
110      <term><replaceable class="parameter">name</replaceable></term>
111
112      <listitem>
113       <para>
114        The name (optionally schema-qualified) of the function to create.
115       </para>
116      </listitem>
117     </varlistentry>
118
119     <varlistentry>
120      <term><replaceable class="parameter">argmode</replaceable></term>
121
122      <listitem>
123       <para>
124        The mode of an argument: <literal>IN</>, <literal>OUT</>,
125        <literal>INOUT</>, or <literal>VARIADIC</>.
126        If omitted, the default is <literal>IN</>.
127        Only <literal>OUT</> arguments can follow a <literal>VARIADIC</> one.
128        Also, <literal>OUT</> and <literal>INOUT</> arguments cannot be used
129        together with the <literal>RETURNS TABLE</> notation.
130       </para>
131      </listitem>
132     </varlistentry>
133
134     <varlistentry>
135      <term><replaceable class="parameter">argname</replaceable></term>
136
137      <listitem>
138       <para>
139        The name of an argument. Some languages (including SQL and PL/pgSQL)
140        let you use the name in the function body.  For other languages the
141        name of an input argument is just extra documentation, so far as
142        the function itself is concerned; but you can use input argument names
143        when calling a function to improve readability (see <xref
144        linkend="sql-syntax-calling-funcs">).  In any case, the name
145        of an output argument is significant, because it defines the column
146        name in the result row type.  (If you omit the name for an output
147        argument, the system will choose a default column name.)
148       </para>
149      </listitem>
150     </varlistentry>
151
152     <varlistentry>
153      <term><replaceable class="parameter">argtype</replaceable></term>
154
155      <listitem>
156       <para>
157        The data type(s) of the function's arguments (optionally
158        schema-qualified), if any. The argument types can be base, composite,
159        or domain types, or can reference the type of a table column.
160       </para>
161       <para>
162        Depending on the implementation language it might also be allowed
163        to specify <quote>pseudo-types</> such as <type>cstring</>.
164        Pseudo-types indicate that the actual argument type is either
165        incompletely specified, or outside the set of ordinary SQL data types.
166       </para>
167       <para>
168        The type of a column is referenced by writing
169        <literal><replaceable
170        class="parameter">table_name</replaceable>.<replaceable
171        class="parameter">column_name</replaceable>%TYPE</literal>.
172        Using this feature can sometimes help make a function independent of
173        changes to the definition of a table.
174       </para>
175      </listitem>
176     </varlistentry>
177
178     <varlistentry>
179      <term><replaceable class="parameter">default_expr</replaceable></term>
180
181      <listitem>
182       <para>
183        An expression to be used as default value if the parameter is
184        not specified.  The expression has to be coercible to the
185        argument type of the parameter.
186        Only input (including <literal>INOUT</>) parameters can have a default
187         value.  All input parameters following a
188        parameter with a default value must have default values as well.
189       </para>
190      </listitem>
191     </varlistentry>
192
193     <varlistentry>
194      <term><replaceable class="parameter">rettype</replaceable></term>
195
196      <listitem>
197       <para>
198        The return data type (optionally schema-qualified). The return type
199        can be a base, composite, or domain type,
200        or can reference the type of a table column.
201        Depending on the implementation language it might also be allowed
202        to specify <quote>pseudo-types</> such as <type>cstring</>.
203        If the function is not supposed to return a value, specify
204        <type>void</> as the return type.
205       </para>
206       <para>
207        When there are <literal>OUT</> or <literal>INOUT</> parameters,
208        the <literal>RETURNS</> clause can be omitted.  If present, it
209        must agree with the result type implied by the output parameters:
210        <literal>RECORD</> if there are multiple output parameters, or
211        the same type as the single output parameter.
212       </para>
213       <para>
214        The <literal>SETOF</literal>
215        modifier indicates that the function will return a set of
216        items, rather than a single item.
217       </para>
218       <para>
219        The type of a column is referenced by writing
220        <literal><replaceable
221        class="parameter">table_name</replaceable>.<replaceable
222        class="parameter">column_name</replaceable>%TYPE</literal>.
223       </para>
224      </listitem>
225     </varlistentry>
226
227     <varlistentry>
228      <term><replaceable class="parameter">column_name</replaceable></term>
229
230      <listitem>
231       <para>
232        The name of an output column in the <literal>RETURNS TABLE</>
233        syntax.  This is effectively another way of declaring a named
234        <literal>OUT</> parameter, except that <literal>RETURNS TABLE</>
235        also implies <literal>RETURNS SETOF</>.
236       </para>
237      </listitem>
238     </varlistentry>
239
240     <varlistentry>
241      <term><replaceable class="parameter">column_type</replaceable></term>
242
243      <listitem>
244       <para>
245        The data type of an output column in the <literal>RETURNS TABLE</>
246        syntax.
247       </para>
248      </listitem>
249     </varlistentry>
250
251     <varlistentry>
252      <term><replaceable class="parameter">lang_name</replaceable></term>
253
254      <listitem>
255       <para>
256        The name of the language that the function is implemented in.
257        It can be <literal>sql</literal>, <literal>c</literal>,
258        <literal>internal</literal>, or the name of a user-defined
259        procedural language, e.g. <literal>plpgsql</literal>.  Enclosing the
260        name in single quotes is deprecated and requires matching case.
261       </para>
262      </listitem>
263     </varlistentry>
264
265     <varlistentry>
266      <term><literal>TRANSFORM { FOR TYPE <replaceable class="parameter">type_name</replaceable> } [, ... ] }</literal></term>
267
268      <listitem>
269       <para>
270        Lists which transforms a call to the function should apply.  Transforms
271        convert between SQL types and language-specific data types;
272        see <xref linkend="sql-createtransform">.  Procedural language
273        implementations usually have hardcoded knowledge of the built-in types,
274        so those don't need to be listed here.  If a procedural language
275        implementation does not know how to handle a type and no transform is
276        supplied, it will fall back to a default behavior for converting data
277        types, but this depends on the implementation.
278       </para>
279      </listitem>
280     </varlistentry>
281
282     <varlistentry>
283      <term><literal>WINDOW</literal></term>
284
285      <listitem>
286       <para><literal>WINDOW</literal> indicates that the function is a
287        <firstterm>window function</> rather than a plain function.
288        This is currently only useful for functions written in C.
289        The <literal>WINDOW</> attribute cannot be changed when
290        replacing an existing function definition.
291       </para>
292      </listitem>
293     </varlistentry>
294
295     <varlistentry>
296      <term><literal>IMMUTABLE</literal></term>
297      <term><literal>STABLE</literal></term>
298      <term><literal>VOLATILE</literal></term>
299
300      <listitem>
301       <para>
302        These attributes inform the query optimizer about the behavior
303        of the function.  At most one choice
304        can be specified.  If none of these appear,
305        <literal>VOLATILE</literal> is the default assumption.
306       </para>
307
308       <para><literal>IMMUTABLE</literal> indicates that the function
309        cannot modify the database and always
310        returns the same result when given the same argument values; that
311        is, it does not do database lookups or otherwise use information not
312        directly present in its argument list.  If this option is given,
313        any call of the function with all-constant arguments can be
314        immediately replaced with the function value.
315       </para>
316
317       <para><literal>STABLE</literal> indicates that the function
318        cannot modify the database,
319        and that within a single table scan it will consistently
320        return the same result for the same argument values, but that its
321        result could change across SQL statements.  This is the appropriate
322        selection for functions whose results depend on database lookups,
323        parameter variables (such as the current time zone), etc.  (It is
324        inappropriate for <literal>AFTER</> triggers that wish to
325        query rows modified by the current command.)  Also note
326        that the <function>current_timestamp</> family of functions qualify
327        as stable, since their values do not change within a transaction.
328       </para>
329
330       <para><literal>VOLATILE</literal> indicates that the function value can
331        change even within a single table scan, so no optimizations can be
332        made.  Relatively few database functions are volatile in this sense;
333        some examples are <literal>random()</>, <literal>currval()</>,
334        <literal>timeofday()</>.  But note that any function that has
335        side-effects must be classified volatile, even if its result is quite
336        predictable, to prevent calls from being optimized away; an example is
337        <literal>setval()</>.
338       </para>
339
340       <para>
341        For additional details see <xref linkend="xfunc-volatility">.
342       </para>
343      </listitem>
344     </varlistentry>
345
346     <varlistentry>
347      <term><literal>LEAKPROOF</literal></term>
348      <listitem>
349       <para>
350        <literal>LEAKPROOF</literal> indicates that the function has no side
351        effects.  It reveals no information about its arguments other than by
352        its return value.  For example, a function which throws an error message
353        for some argument values but not others, or which includes the argument
354        values in any error message, is not leakproof.  This affects how the
355        system executes queries against views created with the
356        <literal>security_barrier</literal> option or tables with row level
357        security enabled.  The system will enforce conditions from security
358        policies and security barrier views before any user-supplied conditions
359        from the query itself that contain non-leakproof functions, in order to
360        prevent the inadvertent exposure of data.  Functions and operators
361        marked as leakproof are assumed to be trustworthy, and may be executed
362        before conditions from security policies and security barrier views.
363        In addition, functions which do not take arguments or which are not
364        passed any arguments from the security barrier view or table do not have
365        to be marked as leakproof to be executed before security conditions.  See
366        <xref linkend="sql-createview"> and <xref linkend="rules-privileges">.
367        This option can only be set by the superuser.
368       </para>
369      </listitem>
370     </varlistentry>
371
372     <varlistentry>
373      <term><literal>CALLED ON NULL INPUT</literal></term>
374      <term><literal>RETURNS NULL ON NULL INPUT</literal></term>
375      <term><literal>STRICT</literal></term>
376
377      <listitem>
378       <para><literal>CALLED ON NULL INPUT</literal> (the default) indicates
379        that the function will be called normally when some of its
380        arguments are null.  It is then the function author's
381        responsibility to check for null values if necessary and respond
382        appropriately.
383       </para>
384
385       <para><literal>RETURNS NULL ON NULL INPUT</literal> or
386        <literal>STRICT</literal> indicates that the function always
387        returns null whenever any of its arguments are null.  If this
388        parameter is specified, the function is not executed when there
389        are null arguments; instead a null result is assumed
390        automatically.
391       </para>
392      </listitem>
393     </varlistentry>
394
395    <varlistentry>
396     <term><literal><optional>EXTERNAL</optional> SECURITY INVOKER</literal></term>
397     <term><literal><optional>EXTERNAL</optional> SECURITY DEFINER</literal></term>
398
399     <listitem>
400      <para><literal>SECURITY INVOKER</literal> indicates that the function
401       is to be executed with the privileges of the user that calls it.
402       That is the default.  <literal>SECURITY DEFINER</literal>
403       specifies that the function is to be executed with the
404       privileges of the user that owns it.
405      </para>
406
407      <para>
408       The key word <literal>EXTERNAL</literal> is allowed for SQL
409       conformance, but it is optional since, unlike in SQL, this feature
410       applies to all functions not only external ones.
411      </para>
412     </listitem>
413    </varlistentry>
414
415    <varlistentry>
416     <term><literal>PARALLEL</literal></term>
417
418     <listitem>
419      <para><literal>PARALLEL UNSAFE</literal> indicates that the function
420       can't be executed in parallel mode and the presence of such a
421       function in an SQL statement forces a serial execution plan.  This is
422       the default.  <literal>PARALLEL RESTRICTED</literal> indicates that
423       the function can be executed in parallel mode, but the execution is
424       restricted to parallel group leader.  <literal>PARALLEL SAFE</literal>
425       indicates that the function is safe to run in parallel mode without
426       restriction.
427      </para>
428
429      <para>
430       Functions should be labeled parallel unsafe if they modify any database
431       state, or if they make changes to the transaction such as using
432       sub-transactions, or if they access sequences or attempt to make
433       persistent changes to settings (e.g. <literal>setval</>).  They should
434       be labeled as parallel restricted if they access temporary tables,
435       client connection state, cursors, prepared statements, or miscellaneous
436       backend-local state which the system cannot synchronize in parallel mode
437       (e.g.  <literal>setseed</> cannot be executed other than by the group
438       leader because a change made by another process would not be reflected
439       in the leader).  In general, if a function is labeled as being safe when
440       it is restricted or unsafe, or if it is labeled as being restricted when
441       it is in fact unsafe, it may throw errors or produce wrong answers
442       when used in a parallel query.  C-language functions could in theory
443       exhibit totally undefined behavior if mislabeled, since there is no way
444       for the system to protect itself against arbitrary C code, but in most
445       likely cases the result will be no worse than for any other function.
446       If in doubt, functions should be labeled as <literal>UNSAFE</>, which is
447       the default.
448      </para>
449     </listitem>
450    </varlistentry>
451
452     <varlistentry>
453      <term><replaceable class="parameter">execution_cost</replaceable></term>
454
455      <listitem>
456       <para>
457        A positive number giving the estimated execution cost for the function,
458        in units of <xref linkend="guc-cpu-operator-cost">.  If the function
459        returns a set, this is the cost per returned row.  If the cost is
460        not specified, 1 unit is assumed for C-language and internal functions,
461        and 100 units for functions in all other languages.  Larger values
462        cause the planner to try to avoid evaluating the function more often
463        than necessary.
464       </para>
465      </listitem>
466     </varlistentry>
467
468     <varlistentry>
469      <term><replaceable class="parameter">result_rows</replaceable></term>
470
471      <listitem>
472       <para>
473        A positive number giving the estimated number of rows that the planner
474        should expect the function to return.  This is only allowed when the
475        function is declared to return a set.  The default assumption is
476        1000 rows.
477       </para>
478      </listitem>
479     </varlistentry>
480
481     <varlistentry>
482      <term><replaceable>configuration_parameter</replaceable></term>
483      <term><replaceable>value</replaceable></term>
484      <listitem>
485       <para>
486        The <literal>SET</> clause causes the specified configuration
487        parameter to be set to the specified value when the function is
488        entered, and then restored to its prior value when the function exits.
489        <literal>SET FROM CURRENT</> saves the value of the parameter that
490        is current when <command>CREATE FUNCTION</> is executed as the value
491        to be applied when the function is entered.
492       </para>
493
494       <para>
495        If a <literal>SET</> clause is attached to a function, then
496        the effects of a <command>SET LOCAL</> command executed inside the
497        function for the same variable are restricted to the function: the
498        configuration parameter's prior value is still restored at function exit.
499        However, an ordinary
500        <command>SET</> command (without <literal>LOCAL</>) overrides the
501        <literal>SET</> clause, much as it would do for a previous <command>SET
502        LOCAL</> command: the effects of such a command will persist after
503        function exit, unless the current transaction is rolled back.
504       </para>
505
506       <para>
507        See <xref linkend="sql-set"> and
508        <xref linkend="runtime-config">
509        for more information about allowed parameter names and values.
510       </para>
511      </listitem>
512     </varlistentry>
513
514     <varlistentry>
515      <term><replaceable class="parameter">definition</replaceable></term>
516
517      <listitem>
518       <para>
519        A string constant defining the function; the meaning depends on the
520        language.  It can be an internal function name, the path to an
521        object file, an SQL command, or text in a procedural language.
522       </para>
523
524       <para>
525        It is often helpful to use dollar quoting (see <xref
526        linkend="sql-syntax-dollar-quoting">) to write the function definition
527        string, rather than the normal single quote syntax.  Without dollar
528        quoting, any single quotes or backslashes in the function definition must
529        be escaped by doubling them.
530       </para>
531
532      </listitem>
533     </varlistentry>
534
535     <varlistentry>
536      <term><literal><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></literal></term>
537
538      <listitem>
539       <para>
540        This form of the <literal>AS</literal> clause is used for
541        dynamically loadable C language functions when the function name
542        in the C language source code is not the same as the name of
543        the SQL function. The string <replaceable
544        class="parameter">obj_file</replaceable> is the name of the
545        file containing the dynamically loadable object, and
546        <replaceable class="parameter">link_symbol</replaceable> is the
547        function's link symbol, that is, the name of the function in the C
548        language source code.  If the link symbol is omitted, it is assumed
549        to be the same as the name of the SQL function being defined.
550       </para>
551
552       <para>
553        When repeated <command>CREATE FUNCTION</command> calls refer to
554        the same object file, the file is only loaded once per session.
555        To unload and
556        reload the file (perhaps during development), start a new session.
557       </para>
558
559      </listitem>
560     </varlistentry>
561
562     <varlistentry>
563      <term><replaceable class="parameter">attribute</replaceable></term>
564
565      <listitem>
566       <para>
567        The historical way to specify optional pieces of information
568        about the function.  The following attributes can appear here:
569
570       <variablelist>
571        <varlistentry>
572         <term><literal>isStrict</></term>
573         <listitem>
574          <para>
575           Equivalent to <literal>STRICT</literal> or <literal>RETURNS NULL ON NULL INPUT</literal>.
576          </para>
577         </listitem>
578        </varlistentry>
579
580        <varlistentry>
581         <term><literal>isCachable</></term>
582         <listitem>
583          <para><literal>isCachable</literal> is an obsolete equivalent of
584           <literal>IMMUTABLE</literal>; it's still accepted for
585           backwards-compatibility reasons.
586          </para>
587         </listitem>
588        </varlistentry>
589
590       </variablelist>
591
592       Attribute names are not case-sensitive.
593      </para>
594     </listitem>
595    </varlistentry>
596
597    </variablelist>
598
599    <para>
600     Refer to <xref linkend="xfunc"> for further information on writing
601     functions.
602    </para>
603
604  </refsect1>
605
606  <refsect1 id="sql-createfunction-overloading">
607   <title>Overloading</title>
608
609    <para>
610     <productname>PostgreSQL</productname> allows function
611     <firstterm>overloading</firstterm>; that is, the same name can be
612     used for several different functions so long as they have distinct
613     input argument types.  However, the C names of all functions must be
614     different, so you must give overloaded C functions different C
615     names (for example, use the argument types as part of the C
616     names).
617    </para>
618
619    <para>
620     Two functions are considered the same if they have the same names and
621     <emphasis>input</> argument types, ignoring any <literal>OUT</>
622     parameters.  Thus for example these declarations conflict:
623 <programlisting>
624 CREATE FUNCTION foo(int) ...
625 CREATE FUNCTION foo(int, out text) ...
626 </programlisting>
627    </para>
628
629    <para>
630     Functions that have different argument type lists will not be considered
631     to conflict at creation time, but if defaults are provided they might
632     conflict in use.  For example, consider
633 <programlisting>
634 CREATE FUNCTION foo(int) ...
635 CREATE FUNCTION foo(int, int default 42) ...
636 </programlisting>
637     A call <literal>foo(10)</> will fail due to the ambiguity about which
638     function should be called.
639    </para>
640
641  </refsect1>
642
643  <refsect1 id="sql-createfunction-notes">
644   <title>Notes</title>
645
646    <para>
647     The full <acronym>SQL</acronym> type syntax is allowed for
648     declaring a function's arguments and return value.  However,
649     parenthesized type modifiers (e.g., the precision field for
650     type <type>numeric</type>) are discarded by <command>CREATE FUNCTION</>.
651     Thus for example
652     <literal>CREATE FUNCTION foo (varchar(10)) ...</>
653     is exactly the same as
654     <literal>CREATE FUNCTION foo (varchar) ...</>.
655    </para>
656
657    <para>
658     When replacing an existing function with <command>CREATE OR REPLACE
659     FUNCTION</>, there are restrictions on changing parameter names.
660     You cannot change the name already assigned to any input parameter
661     (although you can add names to parameters that had none before).
662     If there is more than one output parameter, you cannot change the
663     names of the output parameters, because that would change the
664     column names of the anonymous composite type that describes the
665     function's result.  These restrictions are made to ensure that
666     existing calls of the function do not stop working when it is replaced.
667    </para>
668
669    <para>
670     If a function is declared <literal>STRICT</> with a <literal>VARIADIC</>
671     argument, the strictness check tests that the variadic array <emphasis>as
672     a whole</> is non-null.  The function will still be called if the
673     array has null elements.
674    </para>
675
676  </refsect1>
677
678  <refsect1 id="sql-createfunction-examples">
679   <title>Examples</title>
680
681   <para>
682    Here are some trivial examples to help you get started.  For more
683    information and examples, see <xref linkend="xfunc">.
684 <programlisting>
685 CREATE FUNCTION add(integer, integer) RETURNS integer
686     AS 'select $1 + $2;'
687     LANGUAGE SQL
688     IMMUTABLE
689     RETURNS NULL ON NULL INPUT;
690 </programlisting>
691   </para>
692
693   <para>
694    Increment an integer, making use of an argument name, in
695    <application>PL/pgSQL</application>:
696 <programlisting>
697 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
698         BEGIN
699                 RETURN i + 1;
700         END;
701 $$ LANGUAGE plpgsql;
702 </programlisting>
703   </para>
704
705   <para>
706    Return a record containing multiple output parameters:
707 <programlisting>
708 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
709     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
710     LANGUAGE SQL;
711
712 SELECT * FROM dup(42);
713 </programlisting>
714    You can do the same thing more verbosely with an explicitly named
715    composite type:
716 <programlisting>
717 CREATE TYPE dup_result AS (f1 int, f2 text);
718
719 CREATE FUNCTION dup(int) RETURNS dup_result
720     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
721     LANGUAGE SQL;
722
723 SELECT * FROM dup(42);
724 </programlisting>
725    Another way to return multiple columns is to use a <literal>TABLE</>
726    function:
727 <programlisting>
728 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
729     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
730     LANGUAGE SQL;
731
732 SELECT * FROM dup(42);
733 </programlisting>
734    However, a <literal>TABLE</> function is different from the
735    preceding examples, because it actually returns a <emphasis>set</>
736    of records, not just one record.
737   </para>
738  </refsect1>
739
740  <refsect1 id="sql-createfunction-security">
741   <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>
742
743   <indexterm>
744    <primary><varname>search_path</varname> configuration parameter</>
745    <secondary>use in securing functions</>
746   </indexterm>
747
748    <para>
749     Because a <literal>SECURITY DEFINER</literal> function is executed
750     with the privileges of the user that owns it, care is needed to
751     ensure that the function cannot be misused.  For security,
752     <xref linkend="guc-search-path"> should be set to exclude any schemas
753     writable by untrusted users.  This prevents
754     malicious users from creating objects (e.g., tables, functions, and
755     operators) that mask objects intended to be used by the function.
756     Particularly important in this regard is the
757     temporary-table schema, which is searched first by default, and
758     is normally writable by anyone.  A secure arrangement can be obtained
759     by forcing the temporary schema to be searched last.  To do this,
760     write <literal>pg_temp</><indexterm><primary>pg_temp</><secondary>securing functions</></> as the last entry in <varname>search_path</>.
761     This function illustrates safe usage:
762
763 <programlisting>
764 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
765 RETURNS BOOLEAN AS $$
766 DECLARE passed BOOLEAN;
767 BEGIN
768         SELECT  (pwd = $2) INTO passed
769         FROM    pwds
770         WHERE   username = $1;
771
772         RETURN passed;
773 END;
774 $$  LANGUAGE plpgsql
775     SECURITY DEFINER
776     -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
777     SET search_path = admin, pg_temp;
778 </programlisting>
779
780     This function's intention is to access a table <literal>admin.pwds</>.
781     But without the <literal>SET</> clause, or with a <literal>SET</> clause
782     mentioning only <literal>admin</>, the function could be subverted by
783     creating a temporary table named <literal>pwds</>.
784    </para>
785
786    <para>
787     Before <productname>PostgreSQL</productname> version 8.3, the
788     <literal>SET</> clause was not available, and so older functions may
789     contain rather complicated logic to save, set, and restore
790     <varname>search_path</>.  The <literal>SET</> clause is far easier
791     to use for this purpose.
792    </para>
793
794    <para>
795     Another point to keep in mind is that by default, execute privilege
796     is granted to <literal>PUBLIC</> for newly created functions
797     (see <xref linkend="sql-grant"> for more
798     information).  Frequently you will wish to restrict use of a security
799     definer function to only some users.  To do that, you must revoke
800     the default <literal>PUBLIC</> privileges and then grant execute
801     privilege selectively.  To avoid having a window where the new function
802     is accessible to all, create it and set the privileges within a single
803     transaction.  For example:
804    </para>
805
806 <programlisting>
807 BEGIN;
808 CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
809 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
810 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
811 COMMIT;
812 </programlisting>
813
814  </refsect1>
815
816  <refsect1 id="sql-createfunction-compat">
817   <title>Compatibility</title>
818
819   <para>
820    A <command>CREATE FUNCTION</command> command is defined in SQL:1999 and later.
821    The <productname>PostgreSQL</productname> version is similar but
822    not fully compatible.  The attributes are not portable, neither are the
823    different available languages.
824   </para>
825
826   <para>
827    For compatibility with some other database systems,
828    <replaceable class="parameter">argmode</replaceable> can be written
829    either before or after <replaceable class="parameter">argname</replaceable>.
830    But only the first way is standard-compliant.
831   </para>
832
833   <para>
834    For parameter defaults, the SQL standard specifies only the syntax with
835    the <literal>DEFAULT</literal> key word.  The syntax
836    with <literal>=</literal> is used in T-SQL and Firebird.
837   </para>
838  </refsect1>
839
840
841  <refsect1>
842   <title>See Also</title>
843
844   <simplelist type="inline">
845    <member><xref linkend="sql-alterfunction"></member>
846    <member><xref linkend="sql-dropfunction"></member>
847    <member><xref linkend="sql-grant"></member>
848    <member><xref linkend="sql-load"></member>
849    <member><xref linkend="sql-revoke"></member>
850   </simplelist>
851  </refsect1>
852
853 </refentry>