]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_function.sgml
Improve documentation about search_path for SECURITY DEFINER functions.
[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>pseudotypes</> such as <type>cstring</>.
164        Pseudotypes 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>pseudotypes</> 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 created 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 session's current value of
490        the parameter as the value to be applied when the function is entered.
491       </para>
492
493       <para>
494        If a <literal>SET</> clause is attached to a function, then
495        the effects of a <command>SET LOCAL</> command executed inside the
496        function for the same variable are restricted to the function: the
497        configuration parameter's prior value is still restored at function exit.
498        However, an ordinary
499        <command>SET</> command (without <literal>LOCAL</>) overrides the
500        <literal>SET</> clause, much as it would do for a previous <command>SET
501        LOCAL</> command: the effects of such a command will persist after
502        function exit, unless the current transaction is rolled back.
503       </para>
504
505       <para>
506        See <xref linkend="sql-set"> and
507        <xref linkend="runtime-config">
508        for more information about allowed parameter names and values.
509       </para>
510      </listitem>
511     </varlistentry>
512
513     <varlistentry>
514      <term><replaceable class="parameter">definition</replaceable></term>
515
516      <listitem>
517       <para>
518        A string constant defining the function; the meaning depends on the
519        language.  It can be an internal function name, the path to an
520        object file, an SQL command, or text in a procedural language.
521       </para>
522
523       <para>
524        It is often helpful to use dollar quoting (see <xref
525        linkend="sql-syntax-dollar-quoting">) to write the function definition
526        string, rather than the normal single quote syntax.  Without dollar
527        quoting, any single quotes or backslashes in the function definition must
528        be escaped by doubling them.
529       </para>
530
531      </listitem>
532     </varlistentry>
533
534     <varlistentry>
535      <term><literal><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></literal></term>
536
537      <listitem>
538       <para>
539        This form of the <literal>AS</literal> clause is used for
540        dynamically loadable C language functions when the function name
541        in the C language source code is not the same as the name of
542        the SQL function. The string <replaceable
543        class="parameter">obj_file</replaceable> is the name of the
544        file containing the dynamically loadable object, and
545        <replaceable class="parameter">link_symbol</replaceable> is the
546        function's link symbol, that is, the name of the function in the C
547        language source code.  If the link symbol is omitted, it is assumed
548        to be the same as the name of the SQL function being defined.
549       </para>
550
551       <para>
552        When repeated <command>CREATE FUNCTION</command> calls refer to
553        the same object file, the file is only loaded once per session.
554        To unload and
555        reload the file (perhaps during development), start a new session.
556       </para>
557
558      </listitem>
559     </varlistentry>
560
561     <varlistentry>
562      <term><replaceable class="parameter">attribute</replaceable></term>
563
564      <listitem>
565       <para>
566        The historical way to specify optional pieces of information
567        about the function.  The following attributes can appear here:
568
569       <variablelist>
570        <varlistentry>
571         <term><literal>isStrict</></term>
572         <listitem>
573          <para>
574           Equivalent to <literal>STRICT</literal> or <literal>RETURNS NULL ON NULL INPUT</literal>.
575          </para>
576         </listitem>
577        </varlistentry>
578
579        <varlistentry>
580         <term><literal>isCachable</></term>
581         <listitem>
582          <para><literal>isCachable</literal> is an obsolete equivalent of
583           <literal>IMMUTABLE</literal>; it's still accepted for
584           backwards-compatibility reasons.
585          </para>
586         </listitem>
587        </varlistentry>
588
589       </variablelist>
590
591       Attribute names are not case-sensitive.
592      </para>
593     </listitem>
594    </varlistentry>
595
596    </variablelist>
597
598    <para>
599     Refer to <xref linkend="xfunc"> for further information on writing
600     functions.
601    </para>
602
603  </refsect1>
604
605  <refsect1 id="sql-createfunction-overloading">
606   <title>Overloading</title>
607
608    <para>
609     <productname>PostgreSQL</productname> allows function
610     <firstterm>overloading</firstterm>; that is, the same name can be
611     used for several different functions so long as they have distinct
612     input argument types.  However, the C names of all functions must be
613     different, so you must give overloaded C functions different C
614     names (for example, use the argument types as part of the C
615     names).
616    </para>
617
618    <para>
619     Two functions are considered the same if they have the same names and
620     <emphasis>input</> argument types, ignoring any <literal>OUT</>
621     parameters.  Thus for example these declarations conflict:
622 <programlisting>
623 CREATE FUNCTION foo(int) ...
624 CREATE FUNCTION foo(int, out text) ...
625 </programlisting>
626    </para>
627
628    <para>
629     Functions that have different argument type lists will not be considered
630     to conflict at creation time, but if defaults are provided they might
631     conflict in use.  For example, consider
632 <programlisting>
633 CREATE FUNCTION foo(int) ...
634 CREATE FUNCTION foo(int, int default 42) ...
635 </programlisting>
636     A call <literal>foo(10)</> will fail due to the ambiguity about which
637     function should be called.
638    </para>
639
640  </refsect1>
641
642  <refsect1 id="sql-createfunction-notes">
643   <title>Notes</title>
644
645    <para>
646     The full <acronym>SQL</acronym> type syntax is allowed for
647     declaring a function's arguments and return value.  However,
648     parenthesized type modifiers (e.g., the precision field for
649     type <type>numeric</type>) are discarded by <command>CREATE FUNCTION</>.
650     Thus for example
651     <literal>CREATE FUNCTION foo (varchar(10)) ...</>
652     is exactly the same as
653     <literal>CREATE FUNCTION foo (varchar) ...</>.
654    </para>
655
656    <para>
657     When replacing an existing function with <command>CREATE OR REPLACE
658     FUNCTION</>, there are restrictions on changing parameter names.
659     You cannot change the name already assigned to any input parameter
660     (although you can add names to parameters that had none before).
661     If there is more than one output parameter, you cannot change the
662     names of the output parameters, because that would change the
663     column names of the anonymous composite type that describes the
664     function's result.  These restrictions are made to ensure that
665     existing calls of the function do not stop working when it is replaced.
666    </para>
667
668    <para>
669     If a function is declared <literal>STRICT</> with a <literal>VARIADIC</>
670     argument, the strictness check tests that the variadic array <emphasis>as
671     a whole</> is non-null.  The function will still be called if the
672     array has null elements.
673    </para>
674
675  </refsect1>
676
677  <refsect1 id="sql-createfunction-examples">
678   <title>Examples</title>
679
680   <para>
681    Here are some trivial examples to help you get started.  For more
682    information and examples, see <xref linkend="xfunc">.
683 <programlisting>
684 CREATE FUNCTION add(integer, integer) RETURNS integer
685     AS 'select $1 + $2;'
686     LANGUAGE SQL
687     IMMUTABLE
688     RETURNS NULL ON NULL INPUT;
689 </programlisting>
690   </para>
691
692   <para>
693    Increment an integer, making use of an argument name, in
694    <application>PL/pgSQL</application>:
695 <programlisting>
696 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
697         BEGIN
698                 RETURN i + 1;
699         END;
700 $$ LANGUAGE plpgsql;
701 </programlisting>
702   </para>
703
704   <para>
705    Return a record containing multiple output parameters:
706 <programlisting>
707 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
708     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
709     LANGUAGE SQL;
710
711 SELECT * FROM dup(42);
712 </programlisting>
713    You can do the same thing more verbosely with an explicitly named
714    composite type:
715 <programlisting>
716 CREATE TYPE dup_result AS (f1 int, f2 text);
717
718 CREATE FUNCTION dup(int) RETURNS dup_result
719     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
720     LANGUAGE SQL;
721
722 SELECT * FROM dup(42);
723 </programlisting>
724    Another way to return multiple columns is to use a <literal>TABLE</>
725    function:
726 <programlisting>
727 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
728     AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
729     LANGUAGE SQL;
730
731 SELECT * FROM dup(42);
732 </programlisting>
733    However, a <literal>TABLE</> function is different from the
734    preceding examples, because it actually returns a <emphasis>set</>
735    of records, not just one record.
736   </para>
737  </refsect1>
738
739  <refsect1 id="sql-createfunction-security">
740   <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>
741
742   <indexterm>
743    <primary><varname>search_path</varname> configuration parameter</>
744    <secondary>use in securing functions</>
745   </indexterm>
746
747    <para>
748     Because a <literal>SECURITY DEFINER</literal> function is executed
749     with the privileges of the user that created it, care is needed to
750     ensure that the function cannot be misused.  For security,
751     <xref linkend="guc-search-path"> should be set to exclude any schemas
752     writable by untrusted users.  This prevents
753     malicious users from creating objects (e.g., tables, functions, and
754     operators) that mask objects intended to be used by the function.
755     Particularly important in this regard is the
756     temporary-table schema, which is searched first by default, and
757     is normally writable by anyone.  A secure arrangement can be obtained
758     by forcing the temporary schema to be searched last.  To do this,
759     write <literal>pg_temp</><indexterm><primary>pg_temp</><secondary>securing functions</></> as the last entry in <varname>search_path</>.
760     This function illustrates safe usage:
761
762 <programlisting>
763 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
764 RETURNS BOOLEAN AS $$
765 DECLARE passed BOOLEAN;
766 BEGIN
767         SELECT  (pwd = $2) INTO passed
768         FROM    pwds
769         WHERE   username = $1;
770
771         RETURN passed;
772 END;
773 $$  LANGUAGE plpgsql
774     SECURITY DEFINER
775     -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
776     SET search_path = admin, pg_temp;
777 </programlisting>
778
779     This function's intention is to access a table <literal>admin.pwds</>.
780     But without the <literal>SET</> clause, or with a <literal>SET</> clause
781     mentioning only <literal>admin</>, the function could be subverted by
782     creating a temporary table named <literal>pwds</>.
783    </para>
784
785    <para>
786     Before <productname>PostgreSQL</productname> version 8.3, the
787     <literal>SET</> clause was not available, and so older functions may
788     contain rather complicated logic to save, set, and restore
789     <varname>search_path</>.  The <literal>SET</> clause is far easier
790     to use for this purpose.
791    </para>
792
793    <para>
794     Another point to keep in mind is that by default, execute privilege
795     is granted to <literal>PUBLIC</> for newly created functions
796     (see <xref linkend="sql-grant"> for more
797     information).  Frequently you will wish to restrict use of a security
798     definer function to only some users.  To do that, you must revoke
799     the default <literal>PUBLIC</> privileges and then grant execute
800     privilege selectively.  To avoid having a window where the new function
801     is accessible to all, create it and set the privileges within a single
802     transaction.  For example:
803    </para>
804
805 <programlisting>
806 BEGIN;
807 CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
808 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
809 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
810 COMMIT;
811 </programlisting>
812
813  </refsect1>
814
815  <refsect1 id="sql-createfunction-compat">
816   <title>Compatibility</title>
817
818   <para>
819    A <command>CREATE FUNCTION</command> command is defined in SQL:1999 and later.
820    The <productname>PostgreSQL</productname> version is similar but
821    not fully compatible.  The attributes are not portable, neither are the
822    different available languages.
823   </para>
824
825   <para>
826    For compatibility with some other database systems,
827    <replaceable class="parameter">argmode</replaceable> can be written
828    either before or after <replaceable class="parameter">argname</replaceable>.
829    But only the first way is standard-compliant.
830   </para>
831
832   <para>
833    For parameter defaults, the SQL standard specifies only the syntax with
834    the <literal>DEFAULT</literal> key word.  The syntax
835    with <literal>=</literal> is used in T-SQL and Firebird.
836   </para>
837  </refsect1>
838
839
840  <refsect1>
841   <title>See Also</title>
842
843   <simplelist type="inline">
844    <member><xref linkend="sql-alterfunction"></member>
845    <member><xref linkend="sql-dropfunction"></member>
846    <member><xref linkend="sql-grant"></member>
847    <member><xref linkend="sql-load"></member>
848    <member><xref linkend="sql-revoke"></member>
849    <member><xref linkend="app-createlang"></member>
850   </simplelist>
851  </refsect1>
852
853 </refentry>