📄 xfunc.sgml
字号:
another function that returns the desired composite value. </para> <para> We could call this function directly in either of two ways:<screen>SELECT new_emp(); new_emp-------------------------- (None,1000.0,25,"(2,2)")SELECT * FROM new_emp(); name | salary | age | cubicle------+--------+-----+--------- None | 1000.0 | 25 | (2,2)</screen> The second way is described more fully in <xref linkend="xfunc-sql-table-functions">. </para> <para> When you use a function that returns a composite type, you might want only one field (attribute) from its result. You can do that with syntax like this:<screen>SELECT (new_emp()).name; name------ None</screen> The extra parentheses are needed to keep the parser from getting confused. If you try to do it without them, you get something like this:<screen>SELECT new_emp().name;ERROR: syntax error at or near "." at character 17LINE 1: SELECT new_emp().name; ^</screen> </para> <para> Another option is to use functional notation for extracting an attribute. The simple way to explain this is that we can use the notations <literal>attribute(table)</> and <literal>table.attribute</> interchangeably.<screen>SELECT name(new_emp()); name------ None</screen><screen>-- This is the same as:-- SELECT emp.name AS youngster FROM emp WHERE emp.age < 30;SELECT name(emp) AS youngster FROM emp WHERE age(emp) < 30; youngster----------- Sam Andy</screen> </para> <tip> <para> The equivalence between functional notation and attribute notation makes it possible to use functions on composite types to emulate <quote>computed fields</>. <indexterm> <primary>computed field</primary> </indexterm> <indexterm> <primary>field</primary> <secondary>computed</secondary> </indexterm> For example, using the previous definition for <literal>double_salary(emp)</>, we can write<screen>SELECT emp.name, emp.double_salary FROM emp;</screen> An application using this wouldn't need to be directly aware that <literal>double_salary</> isn't a real column of the table. (You can also emulate computed fields with views.) </para> </tip> <para> Another way to use a function returning a composite type is to pass the result to another function that accepts the correct row type as input:<screen>CREATE FUNCTION getname(emp) RETURNS text AS $$ SELECT $1.name;$$ LANGUAGE SQL;SELECT getname(new_emp()); getname--------- None(1 row)</screen> </para> <para> Still another way to use a function that returns a composite type is to call it as a table function, as described in <xref linkend="xfunc-sql-table-functions">. </para> </sect2> <sect2 id="xfunc-output-parameters"> <title>Functions with Output Parameters</title> <indexterm> <primary>function</primary> <secondary>output parameter</secondary> </indexterm> <para> An alternative way of describing a function's results is to define it with <firstterm>output parameters</>, as in this example:<screen>CREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)AS 'SELECT $1 + $2'LANGUAGE SQL;SELECT add_em(3,7); add_em-------- 10(1 row)</screen> This is not essentially different from the version of <literal>add_em</> shown in <xref linkend="xfunc-sql-base-functions">. The real value of output parameters is that they provide a convenient way of defining functions that return several columns. For example,<screen>CREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)AS 'SELECT $1 + $2, $1 * $2'LANGUAGE SQL; SELECT * FROM sum_n_product(11,42); sum | product-----+--------- 53 | 462(1 row)</screen> What has essentially happened here is that we have created an anonymous composite type for the result of the function. The above example has the same end result as<screen>CREATE TYPE sum_prod AS (sum int, product int);CREATE FUNCTION sum_n_product (int, int) RETURNS sum_prodAS 'SELECT $1 + $2, $1 * $2'LANGUAGE SQL;</screen> but not having to bother with the separate composite type definition is often handy. </para> <para> Notice that output parameters are not included in the calling argument list when invoking such a function from SQL. This is because <productname>PostgreSQL</productname> considers only the input parameters to define the function's calling signature. That means also that only the input parameters matter when referencing the function for purposes such as dropping it. We could drop the above function with either of<screen>DROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);DROP FUNCTION sum_n_product (int, int);</screen> </para> <para> Parameters can be marked as <literal>IN</> (the default), <literal>OUT</>, or <literal>INOUT</>. An <literal>INOUT</> parameter serves as both an input parameter (part of the calling argument list) and an output parameter (part of the result record type). </para> </sect2> <sect2 id="xfunc-sql-table-functions"> <title><acronym>SQL</acronym> Functions as Table Sources</title> <para> All SQL functions may be used in the <literal>FROM</> clause of a query, but it is particularly useful for functions returning composite types. If the function is defined to return a base type, the table function produces a one-column table. If the function is defined to return a composite type, the table function produces a column for each attribute of the composite type. </para> <para> Here is an example:<screen>CREATE TABLE foo (fooid int, foosubid int, fooname text);INSERT INTO foo VALUES (1, 1, 'Joe');INSERT INTO foo VALUES (1, 2, 'Ed');INSERT INTO foo VALUES (2, 1, 'Mary');CREATE FUNCTION getfoo(int) RETURNS foo AS $$ SELECT * FROM foo WHERE fooid = $1;$$ LANGUAGE SQL;SELECT *, upper(fooname) FROM getfoo(1) AS t1; fooid | foosubid | fooname | upper-------+----------+---------+------- 1 | 1 | Joe | JOE(1 row)</screen> As the example shows, we can work with the columns of the function's result just the same as if they were columns of a regular table. </para> <para> Note that we only got one row out of the function. This is because we did not use <literal>SETOF</>. That is described in the next section. </para> </sect2> <sect2> <title><acronym>SQL</acronym> Functions Returning Sets</title> <para> When an SQL function is declared as returning <literal>SETOF <replaceable>sometype</></literal>, the function's final <command>SELECT</> query is executed to completion, and each row it outputs is returned as an element of the result set. </para> <para> This feature is normally used when calling the function in the <literal>FROM</> clause. In this case each row returned by the function becomes a row of the table seen by the query. For example, assume that table <literal>foo</> has the same contents as above, and we say:<programlisting>CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$ SELECT * FROM foo WHERE fooid = $1;$$ LANGUAGE SQL;SELECT * FROM getfoo(1) AS t1;</programlisting> Then we would get:<screen> fooid | foosubid | fooname-------+----------+--------- 1 | 1 | Joe 1 | 2 | Ed(2 rows)</screen> </para> <para> Currently, functions returning sets may also be called in the select list of a query. For each row that the query generates by itself, the function returning set is invoked, and an output row is generated for each element of the function's result set. Note, however, that this capability is deprecated and may be removed in future releases. The following is an example function returning a set from the select list:<screen>CREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$ SELECT name FROM nodes WHERE parent = $1$$ LANGUAGE SQL;SELECT * FROM nodes; name | parent-----------+-------- Top | Child1 | Top Child2 | Top Child3 | Top SubChild1 | Child1 SubChild2 | Child1(6 rows)SELECT listchildren('Top'); listchildren-------------- Child1 Child2 Child3(3 rows)SELECT name, listchildren(name) FROM nodes; name | listchildren--------+-------------- Top | Child1 Top | Child2 Top | Child3 Child1 | SubChild1 Child1 | SubChild2(5 rows)</screen> In the last <command>SELECT</command>, notice that no output row appears for <literal>Child2</>, <literal>Child3</>, etc. This happens because <function>listchildren</function> returns an empty set for those arguments, so no result rows are generated. </para> </sect2> <sect2> <title>Polymorphic <acronym>SQL</acronym> Functions</title> <para> <acronym>SQL</acronym> functions may be declared to accept and return the polymorphic types <type>anyelement</type> and <type>anyarray</type>. See <xref linkend="extend-types-polymorphic"> for a more detailed explanation of polymorphic functions. Here is a polymorphic function <function>make_array</function> that builds up an array from two arbitrary data type elements:<screen>CREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$ SELECT ARRAY[$1, $2];$$ LANGUAGE SQL;SELECT make_array(1, 2) AS intarray, make_array('a'::text, 'b') AS textarray; intarray | textarray----------+----------- {1,2} | {a,b}(1 row)</screen> </para> <para> Notice the use of the typecast <literal>'a'::text</literal> to specify that the argument is of type <type>text</type>. This is required if the argument is just a string literal, since otherwise it would be treated as type <type>unknown</type>, and array of <type>unknown</type> is not a valid type. Without the typecast, you will get errors like this:<screen><computeroutput>ERROR: could not determine "anyarray"/"anyelement" type because input has type "unknown"</computeroutput></screen> </para> <para> It is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example:<screen>CREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$ SELECT $1 > $2;$$ LANGUAGE SQL;SELECT is_greater(1, 2); is_greater------------
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -