📄 xfunc.sgml
字号:
<!--$PostgreSQL: pgsql/doc/src/sgml/xfunc.sgml,v 1.107.2.1 2006/01/19 22:52:20 momjian Exp $--> <sect1 id="xfunc"> <title>User-Defined Functions</title> <indexterm zone="xfunc"> <primary>function</primary> <secondary>user-defined</secondary> </indexterm> <para> <productname>PostgreSQL</productname> provides four kinds of functions: <itemizedlist> <listitem> <para> query language functions (functions written in <acronym>SQL</acronym>) (<xref linkend="xfunc-sql">) </para> </listitem> <listitem> <para> procedural language functions (functions written in, for example, <application>PL/pgSQL</> or <application>PL/Tcl</>) (<xref linkend="xfunc-pl">) </para> </listitem> <listitem> <para> internal functions (<xref linkend="xfunc-internal">) </para> </listitem> <listitem> <para> C-language functions (<xref linkend="xfunc-c">) </para> </listitem> </itemizedlist> </para> <para> Every kind of function can take base types, composite types, or combinations of these as arguments (parameters). In addition, every kind of function can return a base type or a composite type. Functions may also be defined to return sets of base or composite values. </para> <para> Many kinds of functions can take or return certain pseudo-types (such as polymorphic types), but the available facilities vary. Consult the description of each kind of function for more details. </para> <para> It's easiest to define <acronym>SQL</acronym> functions, so we'll start by discussing those. Most of the concepts presented for <acronym>SQL</acronym> functions will carry over to the other types of functions. </para> <para> Throughout this chapter, it can be useful to look at the reference page of the <xref linkend="sql-createfunction" endterm="sql-createfunction-title"> command to understand the examples better. Some examples from this chapter can be found in <filename>funcs.sql</filename> and <filename>funcs.c</filename> in the <filename>src/tutorial</> directory in the <productname>PostgreSQL</productname> source distribution. </para> </sect1> <sect1 id="xfunc-sql"> <title>Query Language (<acronym>SQL</acronym>) Functions</title> <indexterm zone="xfunc-sql"> <primary>function</primary> <secondary>user-defined</secondary> <tertiary>in SQL</tertiary> </indexterm> <para> SQL functions execute an arbitrary list of SQL statements, returning the result of the last query in the list. In the simple (non-set) case, the first row of the last query's result will be returned. (Bear in mind that <quote>the first row</quote> of a multirow result is not well-defined unless you use <literal>ORDER BY</>.) If the last query happens to return no rows at all, the null value will be returned. </para> <para> <indexterm><primary>SETOF</><seealso>function</></> Alternatively, an SQL function may be declared to return a set, by specifying the function's return type as <literal>SETOF <replaceable>sometype</></literal>. In this case all rows of the last query's result are returned. Further details appear below. </para> <para> The body of an SQL function must be a list of SQL statements separated by semicolons. A semicolon after the last statement is optional. Unless the function is declared to return <type>void</>, the last statement must be a <command>SELECT</>. </para> <para> Any collection of commands in the <acronym>SQL</acronym> language can be packaged together and defined as a function. Besides <command>SELECT</command> queries, the commands can include data modification queries (<command>INSERT</command>, <command>UPDATE</command>, and <command>DELETE</command>), as well as other SQL commands. (The only exception is that you can't put <command>BEGIN</>, <command>COMMIT</>, <command>ROLLBACK</>, or <command>SAVEPOINT</> commands into a <acronym>SQL</acronym> function.) However, the final command must be a <command>SELECT</command> that returns whatever is specified as the function's return type. Alternatively, if you want to define a SQL function that performs actions but has no useful value to return, you can define it as returning <type>void</>. In that case, the function body must not end with a <command>SELECT</command>. For example, this function removes rows with negative salaries from the <literal>emp</> table:<screen>CREATE FUNCTION clean_emp() RETURNS void AS ' DELETE FROM emp WHERE salary < 0;' LANGUAGE SQL;SELECT clean_emp(); clean_emp-----------(1 row)</screen> </para> <para> The syntax of the <command>CREATE FUNCTION</command> command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see <xref linkend="sql-syntax-dollar-quoting">) for the string constant. If you choose to use regular single-quoted string constant syntax, you must escape single quote marks (<literal>'</>) and backslashes (<literal>\</>) used in the body of the function, typically by doubling them (see <xref linkend="sql-syntax-strings">). </para> <para> Arguments to the SQL function are referenced in the function body using the syntax <literal>$<replaceable>n</></>: <literal>$1</> refers to the first argument, <literal>$2</> to the second, and so on. If an argument is of a composite type, then the dot notation, e.g., <literal>$1.name</literal>, may be used to access attributes of the argument. The arguments can only be used as data values, not as identifiers. Thus for example this is reasonable:<programlisting>INSERT INTO mytable VALUES ($1);</programlisting>but this will not work:<programlisting>INSERT INTO $1 VALUES (42);</programlisting> </para> <sect2 id="xfunc-sql-base-functions"> <title><acronym>SQL</acronym> Functions on Base Types</title> <para> The simplest possible <acronym>SQL</acronym> function has no arguments and simply returns a base type, such as <type>integer</type>: <screen>CREATE FUNCTION one() RETURNS integer AS $$ SELECT 1 AS result;$$ LANGUAGE SQL;-- Alternative syntax for string literal:CREATE FUNCTION one() RETURNS integer AS ' SELECT 1 AS result;' LANGUAGE SQL;SELECT one(); one----- 1</screen> </para> <para> Notice that we defined a column alias within the function body for the result of the function (with the name <literal>result</>), but this column alias is not visible outside the function. Hence, the result is labeled <literal>one</> instead of <literal>result</>. </para> <para> It is almost as easy to define <acronym>SQL</acronym> functions that take base types as arguments. In the example below, notice how we refer to the arguments within the function as <literal>$1</> and <literal>$2</>.<screen>CREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$ SELECT $1 + $2;$$ LANGUAGE SQL;SELECT add_em(1, 2) AS answer; answer-------- 3</screen> </para> <para> Here is a more useful function, which might be used to debit a bank account:<programlisting>CREATE FUNCTION tf1 (integer, numeric) RETURNS integer AS $$ UPDATE bank SET balance = balance - $2 WHERE accountno = $1; SELECT 1;$$ LANGUAGE SQL;</programlisting> A user could execute this function to debit account 17 by $100.00 as follows:<programlisting>SELECT tf1(17, 100.0);</programlisting> </para> <para> In practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is<programlisting>CREATE FUNCTION tf1 (integer, numeric) RETURNS numeric AS $$ UPDATE bank SET balance = balance - $2 WHERE accountno = $1; SELECT balance FROM bank WHERE accountno = $1;$$ LANGUAGE SQL;</programlisting> which adjusts the balance and returns the new balance. </para> </sect2> <sect2> <title><acronym>SQL</acronym> Functions on Composite Types</title> <para> When writing functions with arguments of composite types, we must not only specify which argument we want (as we did above with <literal>$1</> and <literal>$2</literal>) but also the desired attribute (field) of that argument. For example, suppose that <type>emp</type> is a table containing employee data, and therefore also the name of the composite type of each row of the table. Here is a function <function>double_salary</function> that computes what someone's salary would be if it were doubled:<screen>CREATE TABLE emp ( name text, salary numeric, age integer, cubicle point);CREATE FUNCTION double_salary(emp) RETURNS numeric AS $$ SELECT $1.salary * 2 AS salary;$$ LANGUAGE SQL;SELECT name, double_salary(emp.*) AS dream FROM emp WHERE emp.cubicle ~= point '(2,1)'; name | dream------+------- Bill | 8400</screen> </para> <para> Notice the use of the syntax <literal>$1.salary</literal> to select one field of the argument row value. Also notice how the calling <command>SELECT</> command uses <literal>*</> to select the entire current row of a table as a composite value. The table row can alternatively be referenced using just the table name, like this:<screen>SELECT name, double_salary(emp) AS dream FROM emp WHERE emp.cubicle ~= point '(2,1)';</screen> but this usage is deprecated since it's easy to get confused. </para> <para> Sometimes it is handy to construct a composite argument value on-the-fly. This can be done with the <literal>ROW</> construct. For example, we could adjust the data being passed to the function:<screen>SELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream FROM emp;</screen> </para> <para> It is also possible to build a function that returns a composite type. This is an example of a function that returns a single <type>emp</type> row:<programlisting>CREATE FUNCTION new_emp() RETURNS emp AS $$ SELECT text 'None' AS name, 1000.0 AS salary, 25 AS age, point '(2,2)' AS cubicle;$$ LANGUAGE SQL;</programlisting> In this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants. </para> <para> Note two important things about defining the function: <itemizedlist> <listitem> <para> The select list order in the query must be exactly the same as that in which the columns appear in the table associated with the composite type. (Naming the columns, as we did above, is irrelevant to the system.) </para> </listitem> <listitem> <para> You must typecast the expressions to match the definition of the composite type, or you will get errors like this:<screen><computeroutput>ERROR: function declared to return emp returns varchar instead of text at column 1</computeroutput></screen> </para> </listitem> </itemizedlist> </para> <para> A different way to define the same function is:<programlisting>CREATE FUNCTION new_emp() RETURNS emp AS $$ SELECT ROW('None', 1000.0, 25, '(2,2)')::emp;$$ LANGUAGE SQL;</programlisting> Here we wrote a <command>SELECT</> that returns just a single column of the correct composite type. This isn't really better in this situation, but it is a handy alternative in some cases — for example, if we need to compute the result by calling
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -