Make LC_COLLATE and LC_CTYPE database-level settings. Collation and
[PostgreSQL.git] / doc / src / sgml / ref / create_function.sgml
blobe05eae8bcfea275161a7ea0cabc222d3ed358b2e
1 <!--
2 $PostgreSQL$
3 -->
5 <refentry id="SQL-CREATEFUNCTION">
6 <refmeta>
7 <refentrytitle id="SQL-CREATEFUNCTION-TITLE">CREATE FUNCTION</refentrytitle>
8 <refmiscinfo>SQL - Language Statements</refmiscinfo>
9 </refmeta>
11 <refnamediv>
12 <refname>CREATE FUNCTION</refname>
13 <refpurpose>define a new function</refpurpose>
14 </refnamediv>
16 <indexterm zone="sql-createfunction">
17 <primary>CREATE FUNCTION</primary>
18 </indexterm>
20 <refsynopsisdiv>
21 <synopsis>
22 CREATE [ OR REPLACE ] FUNCTION
23 <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">argtype</replaceable> [, ...] ] )
24 [ RETURNS <replaceable class="parameter">rettype</replaceable>
25 | RETURNS TABLE ( <replaceable class="parameter">colname</replaceable> <replaceable class="parameter">coltype</replaceable> [, ...] ) ]
26 { LANGUAGE <replaceable class="parameter">langname</replaceable>
27 | IMMUTABLE | STABLE | VOLATILE
28 | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
29 | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
30 | COST <replaceable class="parameter">execution_cost</replaceable>
31 | ROWS <replaceable class="parameter">result_rows</replaceable>
32 | SET <replaceable class="parameter">configuration_parameter</replaceable> { TO <replaceable class="parameter">value</replaceable> | = <replaceable class="parameter">value</replaceable> | FROM CURRENT }
33 | AS '<replaceable class="parameter">definition</replaceable>'
34 | AS '<replaceable class="parameter">obj_file</replaceable>', '<replaceable class="parameter">link_symbol</replaceable>'
35 } ...
36 [ WITH ( <replaceable class="parameter">attribute</replaceable> [, ...] ) ]
37 </synopsis>
38 </refsynopsisdiv>
40 <refsect1 id="sql-createfunction-description">
41 <title>Description</title>
43 <para>
44 <command>CREATE FUNCTION</command> defines a new function.
45 <command>CREATE OR REPLACE FUNCTION</command> will either create a
46 new function, or replace an existing definition.
47 </para>
49 <para>
50 If a schema name is included, then the function is created in the
51 specified schema. Otherwise it is created in the current schema.
52 The name of the new function must not match any existing function
53 with the same input argument types in the same schema. However,
54 functions of different argument types can share a name (this is
55 called <firstterm>overloading</>).
56 </para>
58 <para>
59 To replace the current definition of an existing function, use
60 <command>CREATE OR REPLACE FUNCTION</command>. It is not possible
61 to change the name or argument types of a function this way (if you
62 tried, you would actually be creating a new, distinct function).
63 Also, <command>CREATE OR REPLACE FUNCTION</command> will not let
64 you change the return type of an existing function. To do that,
65 you must drop and recreate the function. (When using <literal>OUT</>
66 parameters, that means you cannot change the names or types of any
67 <literal>OUT</> parameters except by dropping the function.)
68 </para>
70 <para>
71 If you drop and then recreate a function, the new function is not
72 the same entity as the old; you will have to drop existing rules, views,
73 triggers, etc. that refer to the old function. Use
74 <command>CREATE OR REPLACE FUNCTION</command> to change a function
75 definition without breaking objects that refer to the function.
76 Also, <command>ALTER FUNCTION</> can be used to change most of the
77 auxiliary properties of an existing function.
78 </para>
80 <para>
81 The user that creates the function becomes the owner of the function.
82 </para>
83 </refsect1>
85 <refsect1>
86 <title>Parameters</title>
88 <variablelist>
90 <varlistentry>
91 <term><replaceable class="parameter">name</replaceable></term>
93 <listitem>
94 <para>
95 The name (optionally schema-qualified) of the function to create.
96 </para>
97 </listitem>
98 </varlistentry>
100 <varlistentry>
101 <term><replaceable class="parameter">argmode</replaceable></term>
103 <listitem>
104 <para>
105 The mode of an argument: <literal>IN</>, <literal>OUT</>,
106 <literal>INOUT</>, or <literal>VARIADIC</>.
107 If omitted, the default is <literal>IN</>.
108 Only <literal>OUT</> arguments can follow a <literal>VARIADIC</> one.
109 Also, <literal>OUT</> and <literal>INOUT</> arguments cannot be used
110 together with the <literal>RETURNS TABLE</> notation.
111 </para>
112 </listitem>
113 </varlistentry>
115 <varlistentry>
116 <term><replaceable class="parameter">argname</replaceable></term>
118 <listitem>
119 <para>
120 The name of an argument. Some languages (currently only PL/pgSQL) let
121 you use the name in the function body. For other languages the
122 name of an input argument is just extra documentation. But the name
123 of an output argument is significant, since it defines the column
124 name in the result row type. (If you omit the name for an output
125 argument, the system will choose a default column name.)
126 </para>
127 </listitem>
128 </varlistentry>
130 <varlistentry>
131 <term><replaceable class="parameter">argtype</replaceable></term>
133 <listitem>
134 <para>
135 The data type(s) of the function's arguments (optionally
136 schema-qualified), if any. The argument types can be base, composite,
137 or domain types, or can reference the type of a table column.
138 </para>
139 <para>
140 Depending on the implementation language it might also be allowed
141 to specify <quote>pseudotypes</> such as <type>cstring</>.
142 Pseudotypes indicate that the actual argument type is either
143 incompletely specified, or outside the set of ordinary SQL data types.
144 </para>
145 <para>
146 The type of a column is referenced by writing
147 <literal><replaceable
148 class="parameter">tablename</replaceable>.<replaceable
149 class="parameter">columnname</replaceable>%TYPE</literal>.
150 Using this feature can sometimes help make a function independent of
151 changes to the definition of a table.
152 </para>
153 </listitem>
154 </varlistentry>
156 <varlistentry>
157 <term><replaceable class="parameter">rettype</replaceable></term>
159 <listitem>
160 <para>
161 The return data type (optionally schema-qualified). The return type
162 can be a base, composite, or domain type,
163 or can reference the type of a table column.
164 Depending on the implementation language it might also be allowed
165 to specify <quote>pseudotypes</> such as <type>cstring</>.
166 If the function is not supposed to return a value, specify
167 <type>void</> as the return type.
168 </para>
169 <para>
170 When there are <literal>OUT</> or <literal>INOUT</> parameters,
171 the <literal>RETURNS</> clause can be omitted. If present, it
172 must agree with the result type implied by the output parameters:
173 <literal>RECORD</> if there are multiple output parameters, or
174 the same type as the single output parameter.
175 </para>
176 <para>
177 The <literal>SETOF</literal>
178 modifier indicates that the function will return a set of
179 items, rather than a single item.
180 </para>
181 <para>
182 The type of a column is referenced by writing
183 <literal><replaceable
184 class="parameter">tablename</replaceable>.<replaceable
185 class="parameter">columnname</replaceable>%TYPE</literal>.
186 </para>
187 </listitem>
188 </varlistentry>
190 <varlistentry>
191 <term><replaceable class="parameter">colname</replaceable></term>
193 <listitem>
194 <para>
195 The name of an output column in the <literal>RETURNS TABLE</>
196 syntax. This is effectively another way of declaring a named
197 <literal>OUT</> parameter, except that <literal>RETURNS TABLE</>
198 also implies <literal>RETURNS SETOF</>.
199 </para>
200 </listitem>
201 </varlistentry>
203 <varlistentry>
204 <term><replaceable class="parameter">coltype</replaceable></term>
206 <listitem>
207 <para>
208 The data type of an output column in the <literal>RETURNS TABLE</>
209 syntax.
210 </para>
211 </listitem>
212 </varlistentry>
214 <varlistentry>
215 <term><replaceable class="parameter">langname</replaceable></term>
217 <listitem>
218 <para>
219 The name of the language that the function is implemented in.
220 Can be <literal>SQL</literal>, <literal>C</literal>,
221 <literal>internal</literal>, or the name of a user-defined
222 procedural language. For backward compatibility,
223 the name can be enclosed by single quotes.
224 </para>
225 </listitem>
226 </varlistentry>
228 <varlistentry>
229 <term><literal>IMMUTABLE</literal></term>
230 <term><literal>STABLE</literal></term>
231 <term><literal>VOLATILE</literal></term>
233 <listitem>
234 <para>
235 These attributes inform the query optimizer about the behavior
236 of the function. At most one choice
237 can be specified. If none of these appear,
238 <literal>VOLATILE</literal> is the default assumption.
239 </para>
241 <para>
242 <literal>IMMUTABLE</literal> indicates that the function
243 cannot modify the database and always
244 returns the same result when given the same argument values; that
245 is, it does not do database lookups or otherwise use information not
246 directly present in its argument list. If this option is given,
247 any call of the function with all-constant arguments can be
248 immediately replaced with the function value.
249 </para>
251 <para>
252 <literal>STABLE</literal> indicates that the function
253 cannot modify the database,
254 and that within a single table scan it will consistently
255 return the same result for the same argument values, but that its
256 result could change across SQL statements. This is the appropriate
257 selection for functions whose results depend on database lookups,
258 parameter variables (such as the current time zone), etc. Also note
259 that the <function>current_timestamp</> family of functions qualify
260 as stable, since their values do not change within a transaction.
261 </para>
263 <para>
264 <literal>VOLATILE</literal> indicates that the function value can
265 change even within a single table scan, so no optimizations can be
266 made. Relatively few database functions are volatile in this sense;
267 some examples are <literal>random()</>, <literal>currval()</>,
268 <literal>timeofday()</>. But note that any function that has
269 side-effects must be classified volatile, even if its result is quite
270 predictable, to prevent calls from being optimized away; an example is
271 <literal>setval()</>.
272 </para>
274 <para>
275 For additional details see <xref linkend="xfunc-volatility">.
276 </para>
277 </listitem>
278 </varlistentry>
280 <varlistentry>
281 <term><literal>CALLED ON NULL INPUT</literal></term>
282 <term><literal>RETURNS NULL ON NULL INPUT</literal></term>
283 <term><literal>STRICT</literal></term>
285 <listitem>
286 <para>
287 <literal>CALLED ON NULL INPUT</literal> (the default) indicates
288 that the function will be called normally when some of its
289 arguments are null. It is then the function author's
290 responsibility to check for null values if necessary and respond
291 appropriately.
292 </para>
294 <para>
295 <literal>RETURNS NULL ON NULL INPUT</literal> or
296 <literal>STRICT</literal> indicates that the function always
297 returns null whenever any of its arguments are null. If this
298 parameter is specified, the function is not executed when there
299 are null arguments; instead a null result is assumed
300 automatically.
301 </para>
302 </listitem>
303 </varlistentry>
305 <varlistentry>
306 <term><literal><optional>EXTERNAL</optional> SECURITY INVOKER</literal></term>
307 <term><literal><optional>EXTERNAL</optional> SECURITY DEFINER</literal></term>
309 <listitem>
310 <para>
311 <literal>SECURITY INVOKER</literal> indicates that the function
312 is to be executed with the privileges of the user that calls it.
313 That is the default. <literal>SECURITY DEFINER</literal>
314 specifies that the function is to be executed with the
315 privileges of the user that created it.
316 </para>
318 <para>
319 The key word <literal>EXTERNAL</literal> is allowed for SQL
320 conformance, but it is optional since, unlike in SQL, this feature
321 applies to all functions not only external ones.
322 </para>
323 </listitem>
324 </varlistentry>
326 <varlistentry>
327 <term><replaceable class="parameter">execution_cost</replaceable></term>
329 <listitem>
330 <para>
331 A positive number giving the estimated execution cost for the function,
332 in units of <xref linkend="guc-cpu-operator-cost">. If the function
333 returns a set, this is the cost per returned row. If the cost is
334 not specified, 1 unit is assumed for C-language and internal functions,
335 and 100 units for functions in all other languages. Larger values
336 cause the planner to try to avoid evaluating the function more often
337 than necessary.
338 </para>
339 </listitem>
340 </varlistentry>
342 <varlistentry>
343 <term><replaceable class="parameter">result_rows</replaceable></term>
345 <listitem>
346 <para>
347 A positive number giving the estimated number of rows that the planner
348 should expect the function to return. This is only allowed when the
349 function is declared to return a set. The default assumption is
350 1000 rows.
351 </para>
352 </listitem>
353 </varlistentry>
355 <varlistentry>
356 <term><replaceable>configuration_parameter</replaceable></term>
357 <term><replaceable>value</replaceable></term>
358 <listitem>
359 <para>
360 The <literal>SET</> clause causes the specified configuration
361 parameter to be set to the specified value when the function is
362 entered, and then restored to its prior value when the function exits.
363 <literal>SET FROM CURRENT</> saves the session's current value of
364 the parameter as the value to be applied when the function is entered.
365 </para>
367 <para>
368 See <xref linkend="sql-set" endterm="sql-set-title"> and
369 <xref linkend="runtime-config">
370 for more information about allowed parameter names and values.
371 </para>
372 </listitem>
373 </varlistentry>
375 <varlistentry>
376 <term><replaceable class="parameter">definition</replaceable></term>
378 <listitem>
379 <para>
380 A string constant defining the function; the meaning depends on the
381 language. It can be an internal function name, the path to an
382 object file, an SQL command, or text in a procedural language.
383 </para>
384 </listitem>
385 </varlistentry>
387 <varlistentry>
388 <term><literal><replaceable class="parameter">obj_file</replaceable>, <replaceable class="parameter">link_symbol</replaceable></literal></term>
390 <listitem>
391 <para>
392 This form of the <literal>AS</literal> clause is used for
393 dynamically loadable C language functions when the function name
394 in the C language source code is not the same as the name of
395 the SQL function. The string <replaceable
396 class="parameter">obj_file</replaceable> is the name of the
397 file containing the dynamically loadable object, and
398 <replaceable class="parameter">link_symbol</replaceable> is the
399 function's link symbol, that is, the name of the function in the C
400 language source code. If the link symbol is omitted, it is assumed
401 to be the same as the name of the SQL function being defined.
402 </para>
403 </listitem>
404 </varlistentry>
406 <varlistentry>
407 <term><replaceable class="parameter">attribute</replaceable></term>
409 <listitem>
410 <para>
411 The historical way to specify optional pieces of information
412 about the function. The following attributes can appear here:
414 <variablelist>
415 <varlistentry>
416 <term><literal>isStrict</></term>
417 <listitem>
418 <para>
419 Equivalent to <literal>STRICT</literal> or <literal>RETURNS NULL ON NULL INPUT</literal>.
420 </para>
421 </listitem>
422 </varlistentry>
424 <varlistentry>
425 <term><literal>isCachable</></term>
426 <listitem>
427 <para>
428 <literal>isCachable</literal> is an obsolete equivalent of
429 <literal>IMMUTABLE</literal>; it's still accepted for
430 backwards-compatibility reasons.
431 </para>
432 </listitem>
433 </varlistentry>
435 </variablelist>
437 Attribute names are not case-sensitive.
438 </para>
439 </listitem>
440 </varlistentry>
442 </variablelist>
444 </refsect1>
446 <refsect1 id="sql-createfunction-notes">
447 <title>Notes</title>
449 <para>
450 Refer to <xref linkend="xfunc"> for further information on writing
451 functions.
452 </para>
454 <para>
455 The full <acronym>SQL</acronym> type syntax is allowed for
456 input arguments and return value. However, some details of the
457 type specification (e.g., the precision field for
458 type <type>numeric</type>) are the responsibility of the
459 underlying function implementation and are silently swallowed
460 (i.e., not recognized or
461 enforced) by the <command>CREATE FUNCTION</command> command.
462 </para>
464 <para>
465 <productname>PostgreSQL</productname> allows function
466 <firstterm>overloading</firstterm>; that is, the same name can be
467 used for several different functions so long as they have distinct
468 input argument types. However, the C names of all functions must be
469 different, so you must give overloaded C functions different C
470 names (for example, use the argument types as part of the C
471 names).
472 </para>
474 <para>
475 Two functions are considered the same if they have the same names and
476 <emphasis>input</> argument types, ignoring any <literal>OUT</>
477 parameters. Thus for example these declarations conflict:
478 <programlisting>
479 CREATE FUNCTION foo(int) ...
480 CREATE FUNCTION foo(int, out text) ...
481 </programlisting>
482 </para>
484 <para>
485 When repeated <command>CREATE FUNCTION</command> calls refer to
486 the same object file, the file is only loaded once per session.
487 To unload and
488 reload the file (perhaps during development), use the <xref
489 linkend="sql-load" endterm="sql-load-title"> command.
490 </para>
492 <para>
493 Use <xref linkend="sql-dropfunction"
494 endterm="sql-dropfunction-title"> to remove user-defined
495 functions.
496 </para>
498 <para>
499 It is often helpful to use dollar quoting (see <xref
500 linkend="sql-syntax-dollar-quoting">) to write the function definition
501 string, rather than the normal single quote syntax. Without dollar
502 quoting, any single quotes or backslashes in the function definition must
503 be escaped by doubling them.
504 </para>
506 <para>
507 If a <literal>SET</> clause is attached to a function, then
508 the effects of a <command>SET LOCAL</> command executed inside the
509 function for the same variable are restricted to the function: the
510 configuration parameter's prior value is still restored at function exit.
511 However, an ordinary
512 <command>SET</> command (without <literal>LOCAL</>) overrides the
513 <literal>SET</> clause, much as it would do for a previous <command>SET
514 LOCAL</> command: the effects of such a command will persist after
515 function exit, unless the current transaction is rolled back.
516 </para>
518 <para>
519 To be able to define a function, the user must have the
520 <literal>USAGE</literal> privilege on the language.
521 </para>
523 </refsect1>
525 <refsect1 id="sql-createfunction-examples">
526 <title>Examples</title>
528 <para>
529 Here are some trivial examples to help you get started. For more
530 information and examples, see <xref linkend="xfunc">.
531 <programlisting>
532 CREATE FUNCTION add(integer, integer) RETURNS integer
533 AS 'select $1 + $2;'
534 LANGUAGE SQL
535 IMMUTABLE
536 RETURNS NULL ON NULL INPUT;
537 </programlisting>
538 </para>
540 <para>
541 Increment an integer, making use of an argument name, in
542 <application>PL/pgSQL</application>:
543 <programlisting>
544 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
545 BEGIN
546 RETURN i + 1;
547 END;
548 $$ LANGUAGE plpgsql;
549 </programlisting>
550 </para>
552 <para>
553 Return a record containing multiple output parameters:
554 <programlisting>
555 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
556 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
557 LANGUAGE SQL;
559 SELECT * FROM dup(42);
560 </programlisting>
561 You can do the same thing more verbosely with an explicitly named
562 composite type:
563 <programlisting>
564 CREATE TYPE dup_result AS (f1 int, f2 text);
566 CREATE FUNCTION dup(int) RETURNS dup_result
567 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
568 LANGUAGE SQL;
570 SELECT * FROM dup(42);
571 </programlisting>
572 Another way to return multiple columns is to use a <literal>TABLE</>
573 function:
574 <programlisting>
575 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
576 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
577 LANGUAGE SQL;
579 SELECT * FROM dup(42);
580 </programlisting>
581 However, a <literal>TABLE</> function is different from the
582 preceding examples, because it actually returns a <emphasis>set</>
583 of records, not just one record.
584 </para>
585 </refsect1>
587 <refsect1 id="sql-createfunction-security">
588 <title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>
590 <para>
591 Because a <literal>SECURITY DEFINER</literal> function is executed
592 with the privileges of the user that created it, care is needed to
593 ensure that the function cannot be misused. For security,
594 <xref linkend="guc-search-path"> should be set to exclude any schemas
595 writable by untrusted users. This prevents
596 malicious users from creating objects that mask objects used by the
597 function. Particularly important in this regard is the
598 temporary-table schema, which is searched first by default, and
599 is normally writable by anyone. A secure arrangement can be had
600 by forcing the temporary schema to be searched last. To do this,
601 write <literal>pg_temp</> as the last entry in <varname>search_path</>.
602 This function illustrates safe usage:
603 </para>
605 <programlisting>
606 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
607 RETURNS BOOLEAN AS $$
608 DECLARE passed BOOLEAN;
609 BEGIN
610 SELECT (pwd = $2) INTO passed
611 FROM pwds
612 WHERE username = $1;
614 RETURN passed;
615 END;
616 $$ LANGUAGE plpgsql
617 SECURITY DEFINER
618 -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
619 SET search_path = admin, pg_temp;
620 </programlisting>
622 <para>
623 Before <productname>PostgreSQL</productname> version 8.3, the
624 <literal>SET</> option was not available, and so older functions may
625 contain rather complicated logic to save, set, and restore
626 <varname>search_path</>. The <literal>SET</> option is far easier
627 to use for this purpose.
628 </para>
630 <para>
631 Another point to keep in mind is that by default, execute privilege
632 is granted to <literal>PUBLIC</> for newly created functions
633 (see <xref linkend="sql-grant" endterm="sql-grant-title"> for more
634 information). Frequently you will wish to restrict use of a security
635 definer function to only some users. To do that, you must revoke
636 the default <literal>PUBLIC</> privileges and then grant execute
637 privilege selectively. To avoid having a window where the new function
638 is accessible to all, create it and set the privileges within a single
639 transaction. For example:
640 </para>
642 <programlisting>
643 BEGIN;
644 CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
645 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
646 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
647 COMMIT;
648 </programlisting>
650 </refsect1>
653 <refsect1 id="sql-createfunction-compat">
654 <title>Compatibility</title>
656 <para>
657 A <command>CREATE FUNCTION</command> command is defined in SQL:1999 and later.
658 The <productname>PostgreSQL</productname> version is similar but
659 not fully compatible. The attributes are not portable, neither are the
660 different available languages.
661 </para>
663 <para>
664 For compatibility with some other database systems,
665 <replaceable class="parameter">argmode</replaceable> can be written
666 either before or after <replaceable class="parameter">argname</replaceable>.
667 But only the first way is standard-compliant.
668 </para>
669 </refsect1>
672 <refsect1>
673 <title>See Also</title>
675 <simplelist type="inline">
676 <member><xref linkend="sql-alterfunction" endterm="sql-alterfunction-title"></member>
677 <member><xref linkend="sql-dropfunction" endterm="sql-dropfunction-title"></member>
678 <member><xref linkend="sql-grant" endterm="sql-grant-title"></member>
679 <member><xref linkend="sql-load" endterm="sql-load-title"></member>
680 <member><xref linkend="sql-revoke" endterm="sql-revoke-title"></member>
681 <member><xref linkend="app-createlang" endterm="app-createlang-title"></member>
682 </simplelist>
683 </refsect1>
685 </refentry>