CREATE FUNCTION
Description
Creates a function.
Precautions
- If the parameters or return values of a function have precision, the precision is not checked.
- When creating a function, you are advised to explicitly specify the schemas of tables in the function definition. Otherwise, the function may fail to be executed.
- current_schema and search_path specified by SET during function creation are invalid. search_path and current_schema before and after function execution should be the same.
- If a function has output parameters, the GUC parameter set behavior_compat_options must be set to 'proc_outparam_override' for the output parameters to take effect. When the function is called using SELECT or CALL, an actual parameter must be provided in the position of the output parameter. Otherwise, the function fails to be called.
- After REPLACE is specified, a new function is created instead of replacing a function if the number of parameters, parameter type, or return value is different.
- You cannot create overloaded functions with different formal parameter names (the function name and parameter list type are the same).
- You cannot create a function that has the same name and parameter list as a stored procedure.
- Formal parameters cannot be overloaded if only the custom ref cursor type is different from the sys_refcursor type.
- Function overloading is not supported if only the returned data types are different.
- Function overloading s not supported if only the default values are different.
- When an overloaded function is called, the variable type must be specified.
- If an undeclared variable is used in a function, an error is reported when the function is called.
- You can use the SELECT statement to specify different parameters using identical functions.
- When you create a function, you cannot insert other agg functions out of the avg function or other functions.
- In common cluster mode, return values, parameters, and variables cannot be set to the tables of the node groups that are not installed in the system by default. The internal statements of SQL functions cannot be executed on such tables.
- By default, the permissions to execute new functions are granted to PUBLIC users. For details, see GRANT. By default, a user inherits the permissions of the PUBLIC role. Therefore, the user has the permission to execute a function and view the definition of the function. In addition, to execute the function, the user must have the USAGE permission on the schema to which the function locates. You can revoke the default execution permissions from the PUBLIC role when creating a function and grant the function execution permission to users as needed. To avoid the time window during which new functions can be accessed by all users, create functions and set function execution permissions in a transaction. After the database object isolation attribute is enabled, common users can view only the definitions of functions that they have permission to execute.
- If a function is defined as IMMUTABLE or SHIPPABLE, avoid INSERT, UPDATE, DELETE, MERGE, and DDL operations in the function because the CN needs to determine the execution node for these operations. Otherwise, an error may occur. If DDL operations are performed on a function of the IMMUTABLE or SHIPPABLE type, database objects on each node may be inconsistent. To resolve this problem, create the VOLATILE PL/SQL function on the CN, run the EXECUTE statement in the function definition to dynamically execute the DDL operation for repairing system objects, and then use the EXECUTE DIRECT ON syntax to call the repair function on the specified DN.
- When functions without parameters are called inside another function, you can omit brackets and call functions using their names directly.
- If the parameter set behavior_compat_options is not set to proc_outparam_override, the OUT output parameter of the function is directly called by an anonymous block or stored procedure, and the return value is used as the first value of the OUT output parameter. As a result, the calling fails. To correctly use the OUT and IN OUT output parameters, set the parameter set behavior_compat_options to proc_outparam_override. For details, see the example.
- When other functions with output parameters are called in a function and an assignment expression, set the GUC parameter set behavior_compat_options to 'proc_outparam_override', define variables of the same type as the output parameters in advance, and use the variables as output parameters to call other functions with output parameters for the output parameters to take effect. Otherwise, the output parameters of the called functions will be ignored.
- After the GUC parameter behavior_compat_options is set to 'proc_outparam_override', if the return type of the function is setof, the output parameter will not take effect.
- Oracle-compatible functions support viewing, exporting, and importing parameter comments.
- Oracle-compatible functions support viewing, exporting, and importing comments between IS/AS and plsql_body.
- Users granted with the CREATE ANY FUNCTION permission can create or replace functions in the user schemas.
- The default permission on a function is SECURITY INVOKER. To change the permission to SECURITY DEFINER, set the GUC parameter behavior_compat_options to 'plsql_security_definer'.
- When a function is created, it depends on an undefined object. If behavior_compat_options is set to 'plpgsql_dependency', the creation can be executed and a warning message is displayed. If behavior_compat_options is not set to 'plpgsql_dependency', the creation cannot be executed.
- When behavior_compat_options is set to 'plpgsql_dependency', if function A is called in the function and function B is contained in the input and output parameters of function A, function B will not establish a dependency. For example, functionA(functionB()). gs_dependencies only creates dependency with function A.
- If a view directly depends on an O-style function and the behavior_compat_options parameter is set to 'plpgsql_dependency', the view can be accessed when the function is created again. However, if the behavior_compat_options parameter is not set to 'plpgsql_dependency', the view cannot be accessed.
- When creating a function, you cannot use the function itself as the default value of input parameter.
- The function with OUT parameter cannot be called by SQL statement.
- The function with OUT parameter cannot be called by SELECT INTO syntax.
- Functions with OUT parameters cannot be called in nested mode.
Example:
b := func(a,func(c,1));
Should be changed to:
tmp := func(c,1); b := func(a,tmp);
- When a function is created, the type of the return value of the function is not checked.
- If a function with the definer specified is created in a schema of another user, the function will be executed by another user, which may cause unauthorized operations. Therefore, exercise caution when performing this operation.
- In the schema of the O&M administrator, only the initial user and schema owner can create objects. The schema that does not allow other users to create and modify objects is the schema of the O&M administrator.
- If the out parameter is used as the output parameter in an expression, the expression does not take effect in the following scenarios: (a) The execute immediate sqlv using func syntax is used to execute a function. (b) The select func into syntax is used to execute a function. (c) DML statements such as INSERT and UPDATE are used to execute a function. (d) The select where a=func() statement is used. (e) When a function with the out output parameter is used as an input parameter, that is, fun (func (out b), a), the out b parameter does not take effect.
- When a stored procedure with the out parameter is called, you can set the GUC parameter set behavior_compat_options to 'proc_outparam_transfer_length' to transfer the parameter length. The specifications and constraints are as follows:
- The following types are supported: CHAR(n), CHARACTER(n), NCHAR(n), VARCHAR(n), VARYING(n), VARCHAR2(n), and NVARCHAR2(n).
- If the out parameter does not take effect (for example, perform), the length does not need to be transferred.
- The following types do not support precision transfer: NUMERIC, DECIMAL, NUMBER, FLOAT, DEC, INTEGER, TIME, TIMESTAMP, INTERVAL, TIME WITH TIME ZONE, TIMESTAMP WITH TIME ZONE, TIME WITHOUT TIME ZONE, and TIMESTAMP WITHOUT TIME ZONE.
- The parameter length can be transferred regardless of whether the GUC parameter set behavior_compat_options is set to proc_outparam_override.
Syntax
- Syntax (compatible with PostgreSQL) for creating a user-defined function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ]} [, ...] ] ) [ RETURNS rettype [ DETERMINISTIC ] | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | WINDOW | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | {fenced | not fenced} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT }} ][...] { AS 'definition' | AS 'obj_file', 'link_symbol' };
- ORA-compatible syntax for creating a user-defined function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ DETERMINISTIC ] [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {FENCED | NOT FENCED} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT | LANGUAGE lang_name ][...] { IS | AS } plsql_body /
Parameters
- function_name
Specifies the name of the function to be created (optionally schema-qualified).
Value range: a string. It must comply with the naming convention. The value contains a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function name.
- argname
Specifies the parameter name of the function.
Value range: a string. It must comply with the naming convention. The value contains a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function parameter name.
- argmode
Specifies the parameter mode of the function.
Value range: IN, OUT, INOUT, and VARIADIC. The default value is IN. Only the parameter of the OUT mode can be followed by VARIADIC. The parameters of OUT and INOUT cannot be used in the function definition of RETURNS TABLE.
VARIADIC specifies parameters of the array type.
- argtype
Specifies the data type of a function parameter. You can use %ROWTYPE to indirectly reference the type of a table. For details, see Variable Definition Statements.
- expression
Specifies the default expression of a parameter.
- If a_format_version is set to 10c and a_format_dev_version is set to s2, the default expression is not supported when the parameter is in INOUT mode.
- It is recommended that you define all default parameters after all non-default parameters.
- If a function with default parameters is called, input parameters are added to the function from left to right. If inputs of non-default parameters are missing, an error is reported.
- If proc_uncheck_default_param is enabled and a function with default parameters is called, input parameters are added to the function from left to right. The number of defaulted inputs depends on the number of default parameters. If an input of a non-default parameter is missing, the previous default value is used to fill this parameter.
- When a_format_version is set to 10c, a_format_dev_version is set to s1, proc_outparam_override is disabled, and the function parameters include the output parameter out and default, the default value cannot be used.
- rettype
Specifies the return data type. Same as argtype, %TYPE or %ROWTYPE can also be used to indirectly reference types.
When there is OUT or IN OUT parameter, the RETURNS clause can be omitted. If the clause is not omitted, the result type of the clause must be the same as that of the output parameter. The result type of the clause is the same as that of a single output parameter.
The SETOF modifier indicates that the function will return a set of items, rather than a single item.
- column_name
Specifies the column name.
- column_type
Specifies the column type.
- definition
Specifies a string constant defining a function. Its meaning depends on the language. It can be an internal function name, a path pointing to a target file, a SQL query, or text in a procedural language.
- DETERMINISTIC
Specifies an API compatible with the SQL syntax. You are advised not to use it.
- LANGUAGE lang_name
Specifies the name of the language that is used to implement the function. It can be SQL, C, internal, or the name of a customized process language. To ensure downward compatibility, the name can use single quotation marks. Contents in single quotation marks must be capitalized.
Due to compatibility issues, no matter which language is specified when an ORA-style database is created, the language used is plpgsql.
- When an internal function is defined, if AS specifies the function as an internal system function, the parameter type, number of parameters, and return value type of the new function must be the same as those of the internal system function, and the user who creates the internal function must have the permission to execute the internal system function.
- Only users with the sysadmin permission can create internal functions.
- WINDOW
Specifies that the function is a window function. This is currently only useful for functions written in C. The WINDOW attribute cannot be changed when replacing an existing function definition.
For a customized window function, the value of LANGUAGE can only be internal, and the referenced internal function must be a window function.
- IMMUTABLE
Specifies that the function always returns the same result if the parameter values are the same.
- STABLE
Specifies that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements.
- VOLATILE
Specifies that the function value can change in a single table scan and no optimization is performed.
- SHIPPABLE
NOT SHIPPABLE
Specifies whether the function can be pushed down to DNs for execution.
- Functions of the IMMUTABLE type can always be pushed down to DNs.
- Functions of the STABLE or VOLATILE type can be pushed down to DNs only if their attribute is SHIPPABLE.
The function or stored procedure of the SHIPPABLE/IMMUABLE type cannot contain EXCEPTION or call functions or stored procedures that contain EXCEPTION.
- LEAKPROOF
Specifies that the function has no side effects. LEAKPROOF can be set only by the system administrator.
- CALLED ON NULL INPUT
Declares that some parameters of the function can be called in normal mode if the parameter values are null. This parameter can be omitted.
- RETURNS NULL ON NULL INPUT
STRICT
Specifies that the function always returns null whenever any of its parameters is null. If this parameter is specified, the function is not executed when there are null parameters; instead a null result is returned automatically.
RETURNS NULL ON NULL INPUT and STRICT have the same functions.
- EXTERNAL
The purpose is to be compatible with SQL statements and it is optional. This feature applies to all functions, not only external functions.
- SECURITY INVOKER
AUTHID CURRENT_USER
Specifies that the function will be executed with the permissions of the user who calls it. This parameter can be omitted.
SECURITY INVOKER and AUTHID CURRENT_USER have the same functions.
- SECURITY DEFINER
AUTHID DEFINER
Specifies that the function will be executed with the permissions of the user who created it.
AUTHID DEFINER and SECURITY DEFINER have the same functions.
- FENCED
NOT FENCED
Specifies whether the function is executed in fenced mode or not fenced mode. In NOT FENCED mode, a function is executed in a CN or DN process. In FENCED mode, a function is executed in a new fork process, which does not affect CN or DN processes.
Application scenarios:
- Develop or debug a function in FENCED mode and execute it in NOT FENCED mode. This reduces the overhead of the fork process and communication.
- Perform complex OS operations, such as opening a file, and processing signals and threads in FENCED mode; otherwise, the GaussDB database execution may be affected.
- Customize PL/SQL functions. If this parameter is not specified, the default value NOT FENCED is used and the FENCED execution mode is not supported.
- COST execution_cost
Estimates the execution cost of a function.
The unit of execution_cost is cpu_operator_cost.
Value range: ≥ 0
- ROWS result_rows
Estimates the number of rows returned by the function. This is only allowed when the function is declared to return a set.
Value range: ≥ 0. The default value is 1000.
- configuration_parameter
- value
Sets a specified database session parameter to a specified value. If the value is DEFAULT or RESET, the default setting is used in the new session. OFF disables the setting.
Value range: a string
- DEFAULT
- OFF
- RESET
Specifies the default value.
- from current
Uses the value of configuration_parameter of the current session.
- value
- plsql_body
Specifies the PL/SQL stored procedure body.
When you perform password-related operations, such as user creation, password change, and encryption/decryption, in a function body, the password will be recorded in the system catalogs and logs in plaintext. To prevent sensitive information leakage, you are advised not to perform operations on the function body related to sensitive information, such as passwords or keys.
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
-- Create an ORA-compatible database. gaussdb=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY 'ORA'; CREATE DATABASE -- Switch to another database. gaussdb=# \c ora_compatible_db -- Define a function as SQL query. gaussdb=# CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; -- Add an integer by parameter name using PL/pgSQL. gaussdb=# CREATE OR REPLACE FUNCTION func_increment_plsql(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql; -- Return a record containing multiple output parameters. gaussdb=# CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; gaussdb=# SELECT * FROM func_dup_sql(42); -- Compute the sum of two integers and returning the result (if the input is null, the returned result is null): gaussdb=# CREATE FUNCTION func_add_sql2(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / -- Alter the execution rule of function add to IMMUTABLE (that is, the same result is returned if the parameter remains unchanged). gaussdb=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) IMMUTABLE; -- Alter the name of function add to add_two_number. gaussdb=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) RENAME TO add_two_number; -- Change the owner of function add to omm. gaussdb=# ALTER FUNCTION add_two_number(INTEGER, INTEGER) OWNER TO omm; -- Delete the function. gaussdb=# DROP FUNCTION add_two_number; gaussdb=# DROP FUNCTION func_increment_sql; gaussdb=# DROP FUNCTION func_dup_sql; gaussdb=# DROP FUNCTION func_increment_plsql; gaussdb=# DROP FUNCTION func_add_sql; -- If the parameter set behavior_compat_options is not set to proc_outparam_override, the OUT output parameter of the function is directly called by an anonymous block or stored procedure, and the return value is used as the first value of the OUT output parameter. As a result, the call fails. gaussdb=# create type rec as(c1 int, c2 int); gaussdb=# create or replace function func(a in out rec, b in out int) return int as begin a.c1:=100; a.c2:=200; b:=300; return 1; end; / declare r rec; b int; begin func(r,b); -- Not supported. end; / ERROR: cannot assign non-composite value to a row variable CONTEXT: PL/SQL function inline_code_block line 4 at SQL statement gaussdb=# create or replace function func_001(a in out date, b in out date) --#add in & inout #defult value return integer as begin raise info '%', a; raise info '%', b; return 1; end; / gaussdb=# declare date1 date := '2022-02-02'; date2 date := '2022-02-02'; begin func_001(date1, date2); end; / INFO: 2022-02-02 00:00:00 CONTEXT: PL/SQL function inline_code_block line 5 at SQL statement INFO: 2022-02-02 00:00:00 CONTEXT: PL/SQL function inline_code_block line 5 at SQL statement ERROR: invalid input syntax for type timestamp: "1" CONTEXT: PL/SQL function inline_code_block line 5 at SQL statement gaussdb=# create or replace function func_001(a in out INT, b in out date) --#add in & inout #defult value return INT as begin raise info '%', a; raise info '%', b; return a; end; / gaussdb=# declare date1 int := 1; date2 date := '2022-02-02'; begin func_001(date1, date2); end; / INFO: 1 CONTEXT: PL/SQL function inline_code_block line 5 at SQL statement INFO: 2022-02-02 00:00:00 CONTEXT: PL/SQL function inline_code_block line 5 at SQL statement ANONYMOUS BLOCK EXECUTE |
Helpful Links
Suggestions
- analyse | analyze
- Do not run ANALYZE in a transaction or anonymous block.
- Do not run ANALYZE in a function or stored procedure.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot