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