]> begriffs open source - ai-pg/blob - full-docs/man7/CREATE_FUNCTION.7
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / man7 / CREATE_FUNCTION.7
1 '\" t
2 .\"     Title: CREATE FUNCTION
3 .\"    Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
5 .\"      Date: 2025
6 .\"    Manual: PostgreSQL 18.0 Documentation
7 .\"    Source: PostgreSQL 18.0
8 .\"  Language: English
9 .\"
10 .TH "CREATE FUNCTION" "7" "2025" "PostgreSQL 18.0" "PostgreSQL 18.0 Documentation"
11 .\" -----------------------------------------------------------------
12 .\" * Define some portability stuff
13 .\" -----------------------------------------------------------------
14 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 .\" http://bugs.debian.org/507673
16 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 .ie \n(.g .ds Aq \(aq
19 .el       .ds Aq '
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
24 .nh
25 .\" disable justification (adjust text to left margin only)
26 .ad l
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
30 .SH "NAME"
31 CREATE_FUNCTION \- define a new function
32 .SH "SYNOPSIS"
33 .sp
34 .nf
35 CREATE [ OR REPLACE ] FUNCTION
36     \fIname\fR ( [ [ \fIargmode\fR ] [ \fIargname\fR ] \fIargtype\fR [ { DEFAULT | = } \fIdefault_expr\fR ] [, \&.\&.\&.] ] )
37     [ RETURNS \fIrettype\fR
38       | RETURNS TABLE ( \fIcolumn_name\fR \fIcolumn_type\fR [, \&.\&.\&.] ) ]
39   { LANGUAGE \fIlang_name\fR
40     | TRANSFORM { FOR TYPE \fItype_name\fR } [, \&.\&.\&. ]
41     | WINDOW
42     | { IMMUTABLE | STABLE | VOLATILE }
43     | [ NOT ] LEAKPROOF
44     | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT }
45     | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER }
46     | PARALLEL { UNSAFE | RESTRICTED | SAFE }
47     | COST \fIexecution_cost\fR
48     | ROWS \fIresult_rows\fR
49     | SUPPORT \fIsupport_function\fR
50     | SET \fIconfiguration_parameter\fR { TO \fIvalue\fR | = \fIvalue\fR | FROM CURRENT }
51     | AS \*(Aq\fIdefinition\fR\*(Aq
52     | AS \*(Aq\fIobj_file\fR\*(Aq, \*(Aq\fIlink_symbol\fR\*(Aq
53     | \fIsql_body\fR
54   } \&.\&.\&.
55 .fi
56 .SH "DESCRIPTION"
57 .PP
58 \fBCREATE FUNCTION\fR
59 defines a new function\&.
60 \fBCREATE OR REPLACE FUNCTION\fR
61 will either create a new function, or replace an existing definition\&. To be able to define a function, the user must have the
62 USAGE
63 privilege on the language\&.
64 .PP
65 If a schema name is included, then the function is created in the specified schema\&. Otherwise it is created in the current schema\&. The name of the new function must not match any existing function or procedure with the same input argument types in the same schema\&. However, functions and procedures of different argument types can share a name (this is called
66 overloading)\&.
67 .PP
68 To replace the current definition of an existing function, use
69 \fBCREATE OR REPLACE FUNCTION\fR\&. It is not possible to change the name or argument types of a function this way (if you tried, you would actually be creating a new, distinct function)\&. Also,
70 \fBCREATE OR REPLACE FUNCTION\fR
71 will not let you change the return type of an existing function\&. To do that, you must drop and recreate the function\&. (When using
72 OUT
73 parameters, that means you cannot change the types of any
74 OUT
75 parameters except by dropping the function\&.)
76 .PP
77 When
78 \fBCREATE OR REPLACE FUNCTION\fR
79 is used to replace an existing function, the ownership and permissions of the function do not change\&. All other function properties are assigned the values specified or implied in the command\&. You must own the function to replace it (this includes being a member of the owning role)\&.
80 .PP
81 If you drop and then recreate a function, the new function is not the same entity as the old; you will have to drop existing rules, views, triggers, etc\&. that refer to the old function\&. Use
82 \fBCREATE OR REPLACE FUNCTION\fR
83 to change a function definition without breaking objects that refer to the function\&. Also,
84 \fBALTER FUNCTION\fR
85 can be used to change most of the auxiliary properties of an existing function\&.
86 .PP
87 The user that creates the function becomes the owner of the function\&.
88 .PP
89 To be able to create a function, you must have
90 USAGE
91 privilege on the argument types and the return type\&.
92 .PP
93 Refer to
94 Section\ \&36.3
95 for further information on writing functions\&.
96 .SH "PARAMETERS"
97 .PP
98 \fIname\fR
99 .RS 4
100 The name (optionally schema\-qualified) of the function to create\&.
101 .RE
102 .PP
103 \fIargmode\fR
104 .RS 4
105 The mode of an argument:
106 IN,
107 OUT,
108 INOUT, or
109 VARIADIC\&. If omitted, the default is
110 IN\&. Only
111 OUT
112 arguments can follow a
113 VARIADIC
114 one\&. Also,
115 OUT
116 and
117 INOUT
118 arguments cannot be used together with the
119 RETURNS TABLE
120 notation\&.
121 .RE
122 .PP
123 \fIargname\fR
124 .RS 4
125 The name of an argument\&. Some languages (including SQL and PL/pgSQL) let you use the name in the function body\&. For other languages the name of an input argument is just extra documentation, so far as the function itself is concerned; but you can use input argument names when calling a function to improve readability (see
126 Section\ \&4.3)\&. In any case, the name of an output argument is significant, because it defines the column name in the result row type\&. (If you omit the name for an output argument, the system will choose a default column name\&.)
127 .RE
128 .PP
129 \fIargtype\fR
130 .RS 4
131 The data type(s) of the function\*(Aqs arguments (optionally schema\-qualified), if any\&. The argument types can be base, composite, or domain types, or can reference the type of a table column\&.
132 .sp
133 Depending on the implementation language it might also be allowed to specify
134 \(lqpseudo\-types\(rq
135 such as
136 cstring\&. Pseudo\-types indicate that the actual argument type is either incompletely specified, or outside the set of ordinary SQL data types\&.
137 .sp
138 The type of a column is referenced by writing
139 \fItable_name\fR\&.\fIcolumn_name\fR%TYPE\&. Using this feature can sometimes help make a function independent of changes to the definition of a table\&.
140 .RE
141 .PP
142 \fIdefault_expr\fR
143 .RS 4
144 An expression to be used as default value if the parameter is not specified\&. The expression has to be coercible to the argument type of the parameter\&. Only input (including
145 INOUT) parameters can have a default value\&. All input parameters following a parameter with a default value must have default values as well\&.
146 .RE
147 .PP
148 \fIrettype\fR
149 .RS 4
150 The return data type (optionally schema\-qualified)\&. The return type can be a base, composite, or domain type, or can reference the type of a table column\&. Depending on the implementation language it might also be allowed to specify
151 \(lqpseudo\-types\(rq
152 such as
153 cstring\&. If the function is not supposed to return a value, specify
154 void
155 as the return type\&.
156 .sp
157 When there are
158 OUT
159 or
160 INOUT
161 parameters, the
162 RETURNS
163 clause can be omitted\&. If present, it must agree with the result type implied by the output parameters:
164 RECORD
165 if there are multiple output parameters, or the same type as the single output parameter\&.
166 .sp
167 The
168 SETOF
169 modifier indicates that the function will return a set of items, rather than a single item\&.
170 .sp
171 The type of a column is referenced by writing
172 \fItable_name\fR\&.\fIcolumn_name\fR%TYPE\&.
173 .RE
174 .PP
175 \fIcolumn_name\fR
176 .RS 4
177 The name of an output column in the
178 RETURNS TABLE
179 syntax\&. This is effectively another way of declaring a named
180 OUT
181 parameter, except that
182 RETURNS TABLE
183 also implies
184 RETURNS SETOF\&.
185 .RE
186 .PP
187 \fIcolumn_type\fR
188 .RS 4
189 The data type of an output column in the
190 RETURNS TABLE
191 syntax\&.
192 .RE
193 .PP
194 \fIlang_name\fR
195 .RS 4
196 The name of the language that the function is implemented in\&. It can be
197 sql,
198 c,
199 internal, or the name of a user\-defined procedural language, e\&.g\&.,
200 plpgsql\&. The default is
201 sql
202 if
203 \fIsql_body\fR
204 is specified\&. Enclosing the name in single quotes is deprecated and requires matching case\&.
205 .RE
206 .PP
207 TRANSFORM { FOR TYPE \fItype_name\fR } [, \&.\&.\&. ] }
208 .RS 4
209 Lists which transforms a call to the function should apply\&. Transforms convert between SQL types and language\-specific data types; see
210 CREATE TRANSFORM (\fBCREATE_TRANSFORM\fR(7))\&. Procedural language implementations usually have hardcoded knowledge of the built\-in types, so those don\*(Aqt need to be listed here\&. If a procedural language implementation does not know how to handle a type and no transform is supplied, it will fall back to a default behavior for converting data types, but this depends on the implementation\&.
211 .RE
212 .PP
213 WINDOW
214 .RS 4
215 WINDOW
216 indicates that the function is a
217 window function
218 rather than a plain function\&. This is currently only useful for functions written in C\&. The
219 WINDOW
220 attribute cannot be changed when replacing an existing function definition\&.
221 .RE
222 .PP
223 IMMUTABLE
224 .br
225 STABLE
226 .br
227 VOLATILE
228 .RS 4
229 These attributes inform the query optimizer about the behavior of the function\&. At most one choice can be specified\&. If none of these appear,
230 VOLATILE
231 is the default assumption\&.
232 .sp
233 IMMUTABLE
234 indicates that the function cannot modify the database and always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use information not directly present in its argument list\&. If this option is given, any call of the function with all\-constant arguments can be immediately replaced with the function value\&.
235 .sp
236 STABLE
237 indicates that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same argument values, but that its result could change across SQL statements\&. This is the appropriate selection for functions whose results depend on database lookups, parameter variables (such as the current time zone), etc\&. (It is inappropriate for
238 AFTER
239 triggers that wish to query rows modified by the current command\&.) Also note that the
240 \fBcurrent_timestamp\fR
241 family of functions qualify as stable, since their values do not change within a transaction\&.
242 .sp
243 VOLATILE
244 indicates that the function value can change even within a single table scan, so no optimizations can be made\&. Relatively few database functions are volatile in this sense; some examples are
245 random(),
246 currval(),
247 timeofday()\&. But note that any function that has side\-effects must be classified volatile, even if its result is quite predictable, to prevent calls from being optimized away; an example is
248 setval()\&.
249 .sp
250 For additional details see
251 Section\ \&36.7\&.
252 .RE
253 .PP
254 LEAKPROOF
255 .RS 4
256 LEAKPROOF
257 indicates that the function has no side effects\&. It reveals no information about its arguments other than by its return value\&. For example, a function which throws an error message for some argument values but not others, or which includes the argument values in any error message, is not leakproof\&. This affects how the system executes queries against views created with the
258 security_barrier
259 option or tables with row level security enabled\&. The system will enforce conditions from security policies and security barrier views before any user\-supplied conditions from the query itself that contain non\-leakproof functions, in order to prevent the inadvertent exposure of data\&. Functions and operators marked as leakproof are assumed to be trustworthy, and may be executed before conditions from security policies and security barrier views\&. In addition, functions which do not take arguments or which are not passed any arguments from the security barrier view or table do not have to be marked as leakproof to be executed before security conditions\&. See
260 CREATE VIEW (\fBCREATE_VIEW\fR(7))
261 and
262 Section\ \&39.5\&. This option can only be set by the superuser\&.
263 .RE
264 .PP
265 CALLED ON NULL INPUT
266 .br
267 RETURNS NULL ON NULL INPUT
268 .br
269 STRICT
270 .RS 4
271 CALLED ON NULL INPUT
272 (the default) indicates that the function will be called normally when some of its arguments are null\&. It is then the function author\*(Aqs responsibility to check for null values if necessary and respond appropriately\&.
273 .sp
274 RETURNS NULL ON NULL INPUT
275 or
276 STRICT
277 indicates that the function always returns null whenever any of its arguments are null\&. If this parameter is specified, the function is not executed when there are null arguments; instead a null result is assumed automatically\&.
278 .RE
279 .PP
280 [EXTERNAL] SECURITY INVOKER
281 .br
282 [EXTERNAL] SECURITY DEFINER
283 .RS 4
284 SECURITY INVOKER
285 indicates that the function is to be executed with the privileges of the user that calls it\&. That is the default\&.
286 SECURITY DEFINER
287 specifies that the function is to be executed with the privileges of the user that owns it\&. For information on how to write
288 SECURITY DEFINER
289 functions safely,
290 see below\&.
291 .sp
292 The key word
293 EXTERNAL
294 is allowed for SQL conformance, but it is optional since, unlike in SQL, this feature applies to all functions not only external ones\&.
295 .RE
296 .PP
297 PARALLEL
298 .RS 4
299 PARALLEL UNSAFE
300 indicates that the function can\*(Aqt be executed in parallel mode; the presence of such a function in an SQL statement forces a serial execution plan\&. This is the default\&.
301 PARALLEL RESTRICTED
302 indicates that the function can be executed in parallel mode, but only in the parallel group leader process\&.
303 PARALLEL SAFE
304 indicates that the function is safe to run in parallel mode without restriction, including in parallel worker processes\&.
305 .sp
306 Functions should be labeled parallel unsafe if they modify any database state, change the transaction state (other than by using a subtransaction for error recovery), access sequences (e\&.g\&., by calling
307 currval) or make persistent changes to settings\&. They should be labeled parallel restricted if they access temporary tables, client connection state, cursors, prepared statements, or miscellaneous backend\-local state which the system cannot synchronize in parallel mode (e\&.g\&.,
308 setseed
309 cannot be executed other than by the group leader because a change made by another process would not be reflected in the leader)\&. In general, if a function is labeled as being safe when it is restricted or unsafe, or if it is labeled as being restricted when it is in fact unsafe, it may throw errors or produce wrong answers when used in a parallel query\&. C\-language functions could in theory exhibit totally undefined behavior if mislabeled, since there is no way for the system to protect itself against arbitrary C code, but in most likely cases the result will be no worse than for any other function\&. If in doubt, functions should be labeled as
310 UNSAFE, which is the default\&.
311 .RE
312 .PP
313 COST \fIexecution_cost\fR
314 .RS 4
315 A positive number giving the estimated execution cost for the function, in units of
316 cpu_operator_cost\&. If the function returns a set, this is the cost per returned row\&. If the cost is not specified, 1 unit is assumed for C\-language and internal functions, and 100 units for functions in all other languages\&. Larger values cause the planner to try to avoid evaluating the function more often than necessary\&.
317 .RE
318 .PP
319 ROWS \fIresult_rows\fR
320 .RS 4
321 A positive number giving the estimated number of rows that the planner should expect the function to return\&. This is only allowed when the function is declared to return a set\&. The default assumption is 1000 rows\&.
322 .RE
323 .PP
324 SUPPORT \fIsupport_function\fR
325 .RS 4
326 The name (optionally schema\-qualified) of a
327 planner support function
328 to use for this function\&. See
329 Section\ \&36.11
330 for details\&. You must be superuser to use this option\&.
331 .RE
332 .PP
333 \fIconfiguration_parameter\fR
334 .br
335 \fIvalue\fR
336 .RS 4
337 The
338 SET
339 clause causes the specified configuration parameter to be set to the specified value when the function is entered, and then restored to its prior value when the function exits\&.
340 SET FROM CURRENT
341 saves the value of the parameter that is current when
342 \fBCREATE FUNCTION\fR
343 is executed as the value to be applied when the function is entered\&.
344 .sp
345 If a
346 SET
347 clause is attached to a function, then the effects of a
348 \fBSET LOCAL\fR
349 command executed inside the function for the same variable are restricted to the function: the configuration parameter\*(Aqs prior value is still restored at function exit\&. However, an ordinary
350 \fBSET\fR
351 command (without
352 LOCAL) overrides the
353 SET
354 clause, much as it would do for a previous
355 \fBSET LOCAL\fR
356 command: the effects of such a command will persist after function exit, unless the current transaction is rolled back\&.
357 .sp
358 See
359 \fBSET\fR(7)
360 and
361 Chapter\ \&19
362 for more information about allowed parameter names and values\&.
363 .RE
364 .PP
365 \fIdefinition\fR
366 .RS 4
367 A string constant defining the function; the meaning depends on the language\&. It can be an internal function name, the path to an object file, an SQL command, or text in a procedural language\&.
368 .sp
369 It is often helpful to use dollar quoting (see
370 Section\ \&4.1.2.4) to write the function definition string, rather than the normal single quote syntax\&. Without dollar quoting, any single quotes or backslashes in the function definition must be escaped by doubling them\&.
371 .RE
372 .PP
373 \fIobj_file\fR, \fIlink_symbol\fR
374 .RS 4
375 This form of the
376 AS
377 clause is used for dynamically loadable C language functions when the function name in the C language source code is not the same as the name of the SQL function\&. The string
378 \fIobj_file\fR
379 is the name of the shared library file containing the compiled C function, and is interpreted as for the
380 \fBLOAD\fR
381 command\&. The string
382 \fIlink_symbol\fR
383 is the function\*(Aqs link symbol, that is, the name of the function in the C language source code\&. If the link symbol is omitted, it is assumed to be the same as the name of the SQL function being defined\&. The C names of all functions must be different, so you must give overloaded C functions different C names (for example, use the argument types as part of the C names)\&.
384 .sp
385 When repeated
386 \fBCREATE FUNCTION\fR
387 calls refer to the same object file, the file is only loaded once per session\&. To unload and reload the file (perhaps during development), start a new session\&.
388 .RE
389 .PP
390 \fIsql_body\fR
391 .RS 4
392 The body of a
393 LANGUAGE SQL
394 function\&. This can either be a single statement
395 .sp
396 .if n \{\
397 .RS 4
398 .\}
399 .nf
400 RETURN \fIexpression\fR
401 .fi
402 .if n \{\
403 .RE
404 .\}
405 .sp
406 or a block
407 .sp
408 .if n \{\
409 .RS 4
410 .\}
411 .nf
412 BEGIN ATOMIC
413   \fIstatement\fR;
414   \fIstatement\fR;
415   \&.\&.\&.
416   \fIstatement\fR;
417 END
418 .fi
419 .if n \{\
420 .RE
421 .\}
422 .sp
423 This is similar to writing the text of the function body as a string constant (see
424 \fIdefinition\fR
425 above), but there are some differences: This form only works for
426 LANGUAGE SQL, the string constant form works for all languages\&. This form is parsed at function definition time, the string constant form is parsed at execution time; therefore this form cannot support polymorphic argument types and other constructs that are not resolvable at function definition time\&. This form tracks dependencies between the function and objects used in the function body, so
427 DROP \&.\&.\&. CASCADE
428 will work correctly, whereas the form using string literals may leave dangling functions\&. Finally, this form is more compatible with the SQL standard and other SQL implementations\&.
429 .RE
430 .SH "OVERLOADING"
431 .PP
432 PostgreSQL
433 allows function
434 overloading; that is, the same name can be used for several different functions so long as they have distinct input argument types\&. Whether or not you use it, this capability entails security precautions when calling functions in databases where some users mistrust other users; see
435 Section\ \&10.3\&.
436 .PP
437 Two functions are considered the same if they have the same names and
438 \fIinput\fR
439 argument types, ignoring any
440 OUT
441 parameters\&. Thus for example these declarations conflict:
442 .sp
443 .if n \{\
444 .RS 4
445 .\}
446 .nf
447 CREATE FUNCTION foo(int) \&.\&.\&.
448 CREATE FUNCTION foo(int, out text) \&.\&.\&.
449 .fi
450 .if n \{\
451 .RE
452 .\}
453 .PP
454 Functions that have different argument type lists will not be considered to conflict at creation time, but if defaults are provided they might conflict in use\&. For example, consider
455 .sp
456 .if n \{\
457 .RS 4
458 .\}
459 .nf
460 CREATE FUNCTION foo(int) \&.\&.\&.
461 CREATE FUNCTION foo(int, int default 42) \&.\&.\&.
462 .fi
463 .if n \{\
464 .RE
465 .\}
466 .sp
467 A call
468 foo(10)
469 will fail due to the ambiguity about which function should be called\&.
470 .SH "NOTES"
471 .PP
472 The full
473 SQL
474 type syntax is allowed for declaring a function\*(Aqs arguments and return value\&. However, parenthesized type modifiers (e\&.g\&., the precision field for type
475 numeric) are discarded by
476 \fBCREATE FUNCTION\fR\&. Thus for example
477 CREATE FUNCTION foo (varchar(10)) \&.\&.\&.
478 is exactly the same as
479 CREATE FUNCTION foo (varchar) \&.\&.\&.\&.
480 .PP
481 When replacing an existing function with
482 \fBCREATE OR REPLACE FUNCTION\fR, there are restrictions on changing parameter names\&. You cannot change the name already assigned to any input parameter (although you can add names to parameters that had none before)\&. If there is more than one output parameter, you cannot change the names of the output parameters, because that would change the column names of the anonymous composite type that describes the function\*(Aqs result\&. These restrictions are made to ensure that existing calls of the function do not stop working when it is replaced\&.
483 .PP
484 If a function is declared
485 STRICT
486 with a
487 VARIADIC
488 argument, the strictness check tests that the variadic array
489 \fIas a whole\fR
490 is non\-null\&. The function will still be called if the array has null elements\&.
491 .SH "EXAMPLES"
492 .PP
493 Add two integers using an SQL function:
494 .sp
495 .if n \{\
496 .RS 4
497 .\}
498 .nf
499 CREATE FUNCTION add(integer, integer) RETURNS integer
500     AS \*(Aqselect $1 + $2;\*(Aq
501     LANGUAGE SQL
502     IMMUTABLE
503     RETURNS NULL ON NULL INPUT;
504 .fi
505 .if n \{\
506 .RE
507 .\}
508 .sp
509 The same function written in a more SQL\-conforming style, using argument names and an unquoted body:
510 .sp
511 .if n \{\
512 .RS 4
513 .\}
514 .nf
515 CREATE FUNCTION add(a integer, b integer) RETURNS integer
516     LANGUAGE SQL
517     IMMUTABLE
518     RETURNS NULL ON NULL INPUT
519     RETURN a + b;
520 .fi
521 .if n \{\
522 .RE
523 .\}
524 .PP
525 Increment an integer, making use of an argument name, in
526 PL/pgSQL:
527 .sp
528 .if n \{\
529 .RS 4
530 .\}
531 .nf
532 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
533         BEGIN
534                 RETURN i + 1;
535         END;
536 $$ LANGUAGE plpgsql;
537 .fi
538 .if n \{\
539 .RE
540 .\}
541 .PP
542 Return a record containing multiple output parameters:
543 .sp
544 .if n \{\
545 .RS 4
546 .\}
547 .nf
548 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
549     AS $$ SELECT $1, CAST($1 AS text) || \*(Aq is text\*(Aq $$
550     LANGUAGE SQL;
551
552 SELECT * FROM dup(42);
553 .fi
554 .if n \{\
555 .RE
556 .\}
557 .sp
558 You can do the same thing more verbosely with an explicitly named composite type:
559 .sp
560 .if n \{\
561 .RS 4
562 .\}
563 .nf
564 CREATE TYPE dup_result AS (f1 int, f2 text);
565
566 CREATE FUNCTION dup(int) RETURNS dup_result
567     AS $$ SELECT $1, CAST($1 AS text) || \*(Aq is text\*(Aq $$
568     LANGUAGE SQL;
569
570 SELECT * FROM dup(42);
571 .fi
572 .if n \{\
573 .RE
574 .\}
575 .sp
576 Another way to return multiple columns is to use a
577 TABLE
578 function:
579 .sp
580 .if n \{\
581 .RS 4
582 .\}
583 .nf
584 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
585     AS $$ SELECT $1, CAST($1 AS text) || \*(Aq is text\*(Aq $$
586     LANGUAGE SQL;
587
588 SELECT * FROM dup(42);
589 .fi
590 .if n \{\
591 .RE
592 .\}
593 .sp
594 However, a
595 TABLE
596 function is different from the preceding examples, because it actually returns a
597 \fIset\fR
598 of records, not just one record\&.
599 .SH "WRITING SECURITY DEFINER FUNCTIONS SAFELY"
600 .PP
601 Because a
602 SECURITY DEFINER
603 function is executed with the privileges of the user that owns it, care is needed to ensure that the function cannot be misused\&. For security,
604 search_path
605 should be set to exclude any schemas writable by untrusted users\&. This prevents malicious users from creating objects (e\&.g\&., tables, functions, and operators) that mask objects intended to be used by the function\&. Particularly important in this regard is the temporary\-table schema, which is searched first by default, and is normally writable by anyone\&. A secure arrangement can be obtained by forcing the temporary schema to be searched last\&. To do this, write
606 pg_temp
607 as the last entry in
608 \fIsearch_path\fR\&. This function illustrates safe usage:
609 .sp
610 .if n \{\
611 .RS 4
612 .\}
613 .nf
614 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
615 RETURNS BOOLEAN AS $$
616 DECLARE passed BOOLEAN;
617 BEGIN
618         SELECT  (pwd = $2) INTO passed
619         FROM    pwds
620         WHERE   username = $1;
621
622         RETURN passed;
623 END;
624 $$  LANGUAGE plpgsql
625     SECURITY DEFINER
626     \-\- Set a secure search_path: trusted schema(s), then \*(Aqpg_temp\*(Aq\&.
627     SET search_path = admin, pg_temp;
628 .fi
629 .if n \{\
630 .RE
631 .\}
632 .sp
633 This function\*(Aqs intention is to access a table
634 admin\&.pwds\&. But without the
635 SET
636 clause, or with a
637 SET
638 clause mentioning only
639 admin, the function could be subverted by creating a temporary table named
640 pwds\&.
641 .PP
642 If the security definer function intends to create roles, and if it is running as a non\-superuser,
643 \fIcreaterole_self_grant\fR
644 should also be set to a known value using the
645 SET
646 clause\&.
647 .PP
648 Another point to keep in mind is that by default, execute privilege is granted to
649 PUBLIC
650 for newly created functions (see
651 Section\ \&5.8
652 for more information)\&. Frequently you will wish to restrict use of a security definer function to only some users\&. To do that, you must revoke the default
653 PUBLIC
654 privileges and then grant execute privilege selectively\&. To avoid having a window where the new function is accessible to all, create it and set the privileges within a single transaction\&. For example:
655 .sp
656 .if n \{\
657 .RS 4
658 .\}
659 .nf
660 BEGIN;
661 CREATE FUNCTION check_password(uname TEXT, pass TEXT) \&.\&.\&. SECURITY DEFINER;
662 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
663 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
664 COMMIT;
665 .fi
666 .if n \{\
667 .RE
668 .\}
669 .SH "COMPATIBILITY"
670 .PP
671 A
672 \fBCREATE FUNCTION\fR
673 command is defined in the SQL standard\&. The
674 PostgreSQL
675 implementation can be used in a compatible way but has many extensions\&. Conversely, the SQL standard specifies a number of optional features that are not implemented in
676 PostgreSQL\&.
677 .PP
678 The following are important compatibility issues:
679 .sp
680 .RS 4
681 .ie n \{\
682 \h'-04'\(bu\h'+03'\c
683 .\}
684 .el \{\
685 .sp -1
686 .IP \(bu 2.3
687 .\}
688 OR REPLACE
689 is a PostgreSQL extension\&.
690 .RE
691 .sp
692 .RS 4
693 .ie n \{\
694 \h'-04'\(bu\h'+03'\c
695 .\}
696 .el \{\
697 .sp -1
698 .IP \(bu 2.3
699 .\}
700 For compatibility with some other database systems,
701 \fIargmode\fR
702 can be written either before or after
703 \fIargname\fR\&. But only the first way is standard\-compliant\&.
704 .RE
705 .sp
706 .RS 4
707 .ie n \{\
708 \h'-04'\(bu\h'+03'\c
709 .\}
710 .el \{\
711 .sp -1
712 .IP \(bu 2.3
713 .\}
714 For parameter defaults, the SQL standard specifies only the syntax with the
715 DEFAULT
716 key word\&. The syntax with
717 =
718 is used in T\-SQL and Firebird\&.
719 .RE
720 .sp
721 .RS 4
722 .ie n \{\
723 \h'-04'\(bu\h'+03'\c
724 .\}
725 .el \{\
726 .sp -1
727 .IP \(bu 2.3
728 .\}
729 The
730 SETOF
731 modifier is a PostgreSQL extension\&.
732 .RE
733 .sp
734 .RS 4
735 .ie n \{\
736 \h'-04'\(bu\h'+03'\c
737 .\}
738 .el \{\
739 .sp -1
740 .IP \(bu 2.3
741 .\}
742 Only
743 SQL
744 is standardized as a language\&.
745 .RE
746 .sp
747 .RS 4
748 .ie n \{\
749 \h'-04'\(bu\h'+03'\c
750 .\}
751 .el \{\
752 .sp -1
753 .IP \(bu 2.3
754 .\}
755 All other attributes except
756 CALLED ON NULL INPUT
757 and
758 RETURNS NULL ON NULL INPUT
759 are not standardized\&.
760 .RE
761 .sp
762 .RS 4
763 .ie n \{\
764 \h'-04'\(bu\h'+03'\c
765 .\}
766 .el \{\
767 .sp -1
768 .IP \(bu 2.3
769 .\}
770 For the body of
771 LANGUAGE SQL
772 functions, the SQL standard only specifies the
773 \fIsql_body\fR
774 form\&.
775 .RE
776 .PP
777 Simple
778 LANGUAGE SQL
779 functions can be written in a way that is both standard\-conforming and portable to other implementations\&. More complex functions using advanced features, optimization attributes, or other languages will necessarily be specific to PostgreSQL in a significant way\&.
780 .SH "SEE ALSO"
781 ALTER FUNCTION (\fBALTER_FUNCTION\fR(7)), DROP FUNCTION (\fBDROP_FUNCTION\fR(7)), \fBGRANT\fR(7), \fBLOAD\fR(7), \fBREVOKE\fR(7)