create_function.7

来自「PostgreSQL 8.2中增加了很多企业用户所需要的功能和性能上的提高,其开」· 7 代码 · 共 364 行

7
364
字号
.\\" auto-generated by docbook2man-spec $Revision: 1.1.1.1 $.TH "CREATE FUNCTION" "" "2008-01-03" "SQL - Language Statements" "SQL Commands".SH NAMECREATE FUNCTION \- define a new function.SH SYNOPSIS.sp.nfCREATE [ OR REPLACE ] FUNCTION    \fIname\fR ( [ [ \fIargmode\fR ] [ \fIargname\fR ] \fIargtype\fR [, ...] ] )    [ RETURNS \fIrettype\fR ]  { LANGUAGE \fIlangname\fR    | IMMUTABLE | STABLE | VOLATILE    | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT    | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER    | AS '\fIdefinition\fR'    | AS '\fIobj_file\fR', '\fIlink_symbol\fR'  } ...    [ WITH ( \fIattribute\fR [, ...] ) ].sp.fi.SH "DESCRIPTION".PP\fBCREATE FUNCTION\fR defines a new function.\fBCREATE OR REPLACE FUNCTION\fR will either create anew function, or replace an existing definition..PPIf a schema name is included, then the function is created in thespecified schema. Otherwise it is created in the current schema.The name of the new function must not match any existing functionwith the same argument types in the same schema. However,functions of different argument types may share a name (this iscalled \fIoverloading\fR)..PPTo update the definition of an existing function, use\fBCREATE OR REPLACE FUNCTION\fR. It is not possibleto change the name or argument types of a function this way (if youtried, you would actually be creating a new, distinct function).Also, \fBCREATE OR REPLACE FUNCTION\fR will not letyou change the return type of an existing function. To do that,you must drop and recreate the function. (When using OUTparameters, that means you can't change the names or types of anyOUT parameters except by dropping the function.).PPIf you drop and then recreate a function, the new function is notthe same entity as the old; you will have to drop existing rules, views,triggers, etc. that refer to the old function. Use\fBCREATE OR REPLACE FUNCTION\fR to change a functiondefinition without breaking objects that refer to the function..PPThe user that creates the function becomes the owner of the function..SH "PARAMETERS".TP\fB\fIname\fB\fRThe name (optionally schema-qualified) of the function to create..TP\fB\fIargmode\fB\fRThe mode of an argument: either IN, OUT,or INOUT. If omitted, the default is IN..TP\fB\fIargname\fB\fRThe name of an argument. Some languages (currently only PL/pgSQL) letyou use the name in the function body. For other languages thename of an input argument is just extra documentation. But the nameof an output argument is significant, since it defines the columnname in the result row type. (If you omit the name for an outputargument, the system will choose a default column name.).TP\fB\fIargtype\fB\fRThe data type(s) of the function's arguments (optionally schema-qualified), if any. The argument types may be base, composite,or domain types, or may reference the type of a table column.Depending on the implementation language it may also be allowedto specify ``pseudotypes'' such as \fBcstring\fR.Pseudotypes indicate that the actual argument type is eitherincompletely specified, or outside the set of ordinary SQL data types.The type of a column is referenced by writing\fItablename\fR.\fIcolumnname\fR%TYPE.Using this feature can sometimes help make a function independent ofchanges to the definition of a table..TP\fB\fIrettype\fB\fRThe return data type (optionally schema-qualified). The return type may be a base, composite, or domain type,or may reference the type of a table column.Depending on the implementation language it may also be allowedto specify ``pseudotypes'' such as \fBcstring\fR.If the function is not supposed to return a value, specify\fBvoid\fR as the return type.When there are OUT or INOUT parameters,the RETURNS clause may be omitted. If present, itmust agree with the result type implied by the output parameters:RECORD if there are multiple output parameters, orthe same type as the single output parameter.The SETOFmodifier indicates that the function will return a set ofitems, rather than a single item.The type of a column is referenced by writing\fItablename\fR.\fIcolumnname\fR%TYPE..TP\fB\fIlangname\fB\fRThe name of the language that the function is implemented in.May be SQL, C,internal, or the name of a user-definedprocedural language. For backward compatibility,the name may be enclosed by single quotes..TP\fBIMMUTABLE\fR.TP\fBSTABLE\fR.TP\fBVOLATILE\fRThese attributes inform the query optimizer about the behaviorof the function. At most one choicemay be specified. If none of these appear,VOLATILE is the default assumption.IMMUTABLE indicates that the functioncannot modify the database and alwaysreturns the same result when given the same argument values; thatis, it does not do database lookups or otherwise use information notdirectly present in its argument list. If this option is given,any call of the function with all-constant arguments can beimmediately replaced with the function value.STABLE indicates that the functioncannot modify the database,and that within a single table scan it will consistentlyreturn the same result for the same argument values, but that itsresult could change across SQL statements. This is the appropriateselection for functions whose results depend on database lookups,parameter variables (such as the current time zone), etc. Also notethat the \fBcurrent_timestamp\fR family of functions qualifyas stable, since their values do not change within a transaction.VOLATILE indicates that the function value canchange even within a single table scan, so no optimizations can bemade. Relatively few database functions are volatile in this sense;some examples are random(), currval(),timeofday(). But note that any function that hasside-effects must be classified volatile, even if its result is quitepredictable, to prevent calls from being optimized away; an example issetval().For additional details see in the documentation..TP\fBCALLED ON NULL INPUT\fR.TP\fBRETURNS NULL ON NULL INPUT\fR.TP\fBSTRICT\fRCALLED ON NULL INPUT (the default) indicatesthat the function will be called normally when some of itsarguments are null. It is then the function author'sresponsibility to check for null values if necessary and respondappropriately.RETURNS NULL ON NULL INPUT orSTRICT indicates that the function alwaysreturns null whenever any of its arguments are null. If thisparameter is specified, the function is not executed when thereare null arguments; instead a null result is assumedautomatically..TP\fB[EXTERNAL] SECURITY INVOKER\fR.TP\fB[EXTERNAL] SECURITY DEFINER\fRSECURITY INVOKER indicates that the functionis to be executed with the privileges of the user that calls it.That is the default. SECURITY DEFINERspecifies that the function is to be executed with theprivileges of the user that created it.The key word EXTERNAL is allowed for SQLconformance, but it is optional since, unlike in SQL, this featureapplies to all functions not only external ones..TP\fB\fIdefinition\fB\fRA string constant defining the function; the meaning depends on thelanguage. It may be an internal function name, the path to anobject file, an SQL command, or text in a procedural language..TP\fB\fIobj_file\fB, \fIlink_symbol\fB\fRThis form of the AS clause is used fordynamically loadable C language functions when the function namein the C language source code is not the same as the name ofthe SQL function. The string \fIobj_file\fR is the name of thefile containing the dynamically loadable object, and\fIlink_symbol\fR is thefunction's link symbol, that is, the name of the function in the Clanguage source code. If the link symbol is omitted, it is assumedto be the same as the name of the SQL function being defined..TP\fB\fIattribute\fB\fRThe historical way to specify optional pieces of informationabout the function. The following attributes may appear here:.RS.TP\fBisStrict\fREquivalent to STRICT or RETURNS NULL ON NULL INPUT..TP\fBisCachable\fRisCachable is an obsolete equivalent ofIMMUTABLE; it's still accepted forbackwards-compatibility reasons..RE.PPAttribute names are not case-sensitive..SH "NOTES".PPRefer to in the documentation for further information on writingfunctions..PPThe full SQL type syntax is allowed forinput arguments and return value. However, some details of thetype specification (e.g., the precision field fortype \fBnumeric\fR) are the responsibility of theunderlying function implementation and are silently swallowed(i.e., not recognized orenforced) by the \fBCREATE FUNCTION\fR command..PPPostgreSQL allows function\fIoverloading\fR; that is, the same name can beused for several different functions so long as they have distinctargument types. However, the C names of all functions must bedifferent, so you must give overloaded C functions different Cnames (for example, use the argument types as part of the Cnames)..PPTwo functions are considered the same if they have the same names and\fBinput\fR argument types, ignoring any OUTparameters. Thus for example these declarations conflict:.sp.nfCREATE FUNCTION foo(int) ...CREATE FUNCTION foo(int, out text) ....sp.fi.PPWhen repeated \fBCREATE FUNCTION\fR calls refer tothe same object file, the file is only loaded once. To unload andreload the file (perhaps during development), use the LOAD [\fBload\fR(7)] command..PPUse DROP FUNCTION [\fBdrop_function\fR(7)] to remove user-definedfunctions..PPIt is often helpful to use dollar quoting (see in the documentation) to write the function definitionstring, rather than the normal single quote syntax. Without dollarquoting, any single quotes or backslashes in the function definition mustbe escaped by doubling them..PPTo be able to define a function, the user must have theUSAGE privilege on the language..SH "EXAMPLES".PPHere are some trivial examples to help you get started. For moreinformation and examples, see in the documentation..sp.nfCREATE FUNCTION add(integer, integer) RETURNS integer    AS 'select $1 + $2;'    LANGUAGE SQL    IMMUTABLE    RETURNS NULL ON NULL INPUT;.sp.fi.PPIncrement an integer, making use of an argument name, in\fBPL/pgSQL\fR:.sp.nfCREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$        BEGIN                RETURN i + 1;        END;$$ LANGUAGE plpgsql;.sp.fi.PPReturn a record containing multiple output parameters:.sp.nfCREATE FUNCTION dup(in int, out f1 int, out f2 text)    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$    LANGUAGE SQL;SELECT * FROM dup(42);.sp.fiYou can do the same thing more verbosely with an explicitly namedcomposite type:.sp.nfCREATE TYPE dup_result AS (f1 int, f2 text);CREATE FUNCTION dup(int) RETURNS dup_result    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$    LANGUAGE SQL;SELECT * FROM dup(42);.sp.fi.SH "WRITING SECURITY DEFINER FUNCTIONS SAFELY".PPBecause a SECURITY DEFINER function is executedwith the privileges of the user that created it, care is needed toensure that the function cannot be misused. For security,search_path should be set to exclude any schemaswritable by untrusted users. This preventsmalicious users from creating objects that mask objects used by thefunction. Particularly important in this regard is thetemporary-table schema, which is searched first by default, andis normally writable by anyone. A secure arrangement can be hadby forcing the temporary schema to be searched last. To do this,write pg_temp as the last entry in search_path.This function illustrates safe usage:.sp.nfCREATE FUNCTION check_password(uname TEXT, pass TEXT)RETURNS BOOLEAN AS $$DECLARE passed BOOLEAN;        old_path TEXT;BEGIN        -- Save old search_path; notice we must qualify current_setting        -- to ensure we invoke the right function        old_path := pg_catalog.current_setting('search_path');        -- Set a secure search_path: trusted schemas, then 'pg_temp'.        -- We set is_local = true so that the old value will be restored        -- in event of an error before we reach the function end.        PERFORM pg_catalog.set_config('search_path', 'admin, pg_temp', true);        -- Do whatever secure work we came for.        SELECT  (pwd = $2) INTO passed        FROM    pwds        WHERE   username = $1;        -- Restore caller's search_path        PERFORM pg_catalog.set_config('search_path', old_path, true);        RETURN passed;END;$$ LANGUAGE plpgsql SECURITY DEFINER;.sp.fi.SH "COMPATIBILITY".PPA \fBCREATE FUNCTION\fR command is defined in SQL:1999 and later.The PostgreSQL version is similar butnot fully compatible. The attributes are not portable, neither are thedifferent available languages..PPFor compatibility with some other database systems,\fIargmode\fR can be writteneither before or after \fIargname\fR.But only the first way is standard-compliant..SH "SEE ALSO"ALTER FUNCTION [\fBalter_function\fR(7)], DROP FUNCTION [\fBdrop_function\fR(l)], GRANT [\fBgrant\fR(l)], LOAD [\fBload\fR(l)], REVOKE [\fBrevoke\fR(l)], createlang [\fBcreatelang\fR(1)]

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?