2010-09-20 22:08:53 +02:00
|
|
|
<!-- doc/src/sgml/xfunc.sgml -->
|
2000-03-31 05:27:42 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<sect1 id="xfunc">
|
2011-02-01 23:00:26 +01:00
|
|
|
<title>User-defined Functions</title>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="xfunc">
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>user-defined</secondary>
|
|
|
|
</indexterm>
|
2001-11-12 20:19:39 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2001-09-15 21:56:59 +02:00
|
|
|
<productname>PostgreSQL</productname> provides four kinds of
|
|
|
|
functions:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
query language functions (functions written in
|
|
|
|
<acronym>SQL</acronym>) (<xref linkend="xfunc-sql">)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
procedural language functions (functions written in, for
|
2004-12-30 04:13:56 +01:00
|
|
|
example, <application>PL/pgSQL</> or <application>PL/Tcl</>)
|
2003-04-10 03:22:45 +02:00
|
|
|
(<xref linkend="xfunc-pl">)
|
2001-09-15 21:56:59 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
internal functions (<xref linkend="xfunc-internal">)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
C-language functions (<xref linkend="xfunc-c">)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
2001-09-15 21:56:59 +02:00
|
|
|
</para>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
<para>
|
1999-07-22 17:11:05 +02:00
|
|
|
Every kind
|
2003-04-10 03:22:45 +02:00
|
|
|
of function can take base types, composite types, or
|
2004-12-30 04:13:56 +01:00
|
|
|
combinations of these as arguments (parameters). In addition,
|
1999-07-22 17:11:05 +02:00
|
|
|
every kind of function can return a base type or
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
a composite type. Functions can also be defined to return
|
2004-12-30 04:13:56 +01:00
|
|
|
sets of base or composite values.
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
2003-08-10 00:50:22 +02:00
|
|
|
<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>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<para>
|
2004-05-14 23:42:30 +02:00
|
|
|
It's easiest to define <acronym>SQL</acronym>
|
2003-08-10 00:50:22 +02:00
|
|
|
functions, so we'll start by discussing those.
|
2003-10-23 00:28:10 +02:00
|
|
|
Most of the concepts presented for <acronym>SQL</acronym> functions
|
|
|
|
will carry over to the other types of functions.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
2002-01-07 03:29:15 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Throughout this chapter, it can be useful to look at the reference
|
2010-04-03 09:23:02 +02:00
|
|
|
page of the <xref linkend="sql-createfunction"> command to
|
2004-05-14 23:42:30 +02:00
|
|
|
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.
|
2002-01-07 03:29:15 +01:00
|
|
|
</para>
|
2001-09-15 21:56:59 +02:00
|
|
|
</sect1>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2000-09-29 22:21:34 +02:00
|
|
|
<sect1 id="xfunc-sql">
|
1999-07-22 17:11:05 +02:00
|
|
|
<title>Query Language (<acronym>SQL</acronym>) Functions</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="xfunc-sql">
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>user-defined</secondary>
|
|
|
|
<tertiary>in SQL</tertiary>
|
|
|
|
</indexterm>
|
2001-11-12 20:19:39 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2001-09-15 21:56:59 +02:00
|
|
|
SQL functions execute an arbitrary list of SQL statements, returning
|
2003-08-10 00:50:22 +02:00
|
|
|
the result of the last query in the list.
|
2001-11-01 05:07:29 +01:00
|
|
|
In the simple (non-set)
|
2001-10-26 21:58:12 +02:00
|
|
|
case, the first row of the last query's result will be returned.
|
2002-03-22 20:20:45 +01:00
|
|
|
(Bear in mind that <quote>the first row</quote> of a multirow
|
2001-11-01 05:07:29 +01:00
|
|
|
result is not well-defined unless you use <literal>ORDER BY</>.)
|
|
|
|
If the last query happens
|
2003-04-10 03:22:45 +02:00
|
|
|
to return no rows at all, the null value will be returned.
|
2001-10-26 21:58:12 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2008-07-18 05:32:53 +02:00
|
|
|
Alternatively, an SQL function can be declared to return a set,
|
|
|
|
by specifying the function's return type as <literal>SETOF
|
|
|
|
<replaceable>sometype</></literal>, or equivalently by declaring it as
|
|
|
|
<literal>RETURNS TABLE(<replaceable>columns</>)</literal>. In this case
|
|
|
|
all rows of the last query's result are returned. Further details appear
|
|
|
|
below.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2004-09-21 00:48:29 +02:00
|
|
|
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
|
2008-10-31 20:37:56 +01:00
|
|
|
<type>void</>, the last statement must be a <command>SELECT</>,
|
|
|
|
or an <command>INSERT</>, <command>UPDATE</>, or <command>DELETE</>
|
|
|
|
that has a <literal>RETURNING</> clause.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
2005-01-07 23:40:46 +01:00
|
|
|
<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
|
2011-03-11 00:47:44 +01:00
|
|
|
other SQL commands. (You cannot use transaction control commands, e.g.
|
2011-03-11 00:46:21 +01:00
|
|
|
<command>COMMIT</>, <command>SAVEPOINT</>, and some utility
|
2011-03-11 00:50:44 +01:00
|
|
|
commands, e.g. <literal>VACUUM</>, in <acronym>SQL</acronym> functions.)
|
2008-07-18 05:32:53 +02:00
|
|
|
However, the final command
|
2008-10-31 20:37:56 +01:00
|
|
|
must be a <command>SELECT</command> or have a <literal>RETURNING</>
|
|
|
|
clause that returns whatever is
|
2005-01-07 23:40:46 +01:00
|
|
|
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</>.
|
|
|
|
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>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2004-09-21 00:48:29 +02:00
|
|
|
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,
|
2007-01-30 23:29:23 +01:00
|
|
|
you must double single quote marks (<literal>'</>) and backslashes
|
|
|
|
(<literal>\</>) (assuming escape string syntax) in the body of
|
|
|
|
the function (see <xref linkend="sql-syntax-strings">).
|
2004-09-21 00:48:29 +02:00
|
|
|
</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,
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
e.g., <literal>$1.name</literal>, can be used to access attributes
|
2005-01-08 23:13:38 +01:00
|
|
|
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>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
2005-04-01 00:46:33 +02:00
|
|
|
<sect2 id="xfunc-sql-base-functions">
|
2003-04-10 03:22:45 +02:00
|
|
|
<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>:
|
2008-07-18 05:32:53 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION one() RETURNS integer AS $$
|
|
|
|
SELECT 1 AS result;
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
-- Alternative syntax for string literal:
|
2003-04-10 03:22:45 +02:00
|
|
|
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>
|
2008-07-18 05:32:53 +02:00
|
|
|
It is almost as easy to define <acronym>SQL</acronym> functions
|
2003-04-10 03:22:45 +02:00
|
|
|
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>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$
|
2003-04-10 03:22:45 +02:00
|
|
|
SELECT $1 + $2;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2003-04-10 03:22:45 +02:00
|
|
|
|
|
|
|
SELECT add_em(1, 2) AS answer;
|
|
|
|
|
|
|
|
answer
|
|
|
|
--------
|
|
|
|
3
|
|
|
|
</screen>
|
|
|
|
</para>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
Here is a more useful function, which might be used to debit a
|
|
|
|
bank account:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
<programlisting>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION tf1 (integer, numeric) RETURNS integer AS $$
|
2008-07-18 05:32:53 +02:00
|
|
|
UPDATE bank
|
2001-10-26 21:58:12 +02:00
|
|
|
SET balance = balance - $2
|
|
|
|
WHERE accountno = $1;
|
|
|
|
SELECT 1;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2001-09-15 21:56:59 +02:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
|
|
|
A user could execute this function to debit account 17 by $100.00 as
|
|
|
|
follows:
|
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
<programlisting>
|
2003-04-10 03:22:45 +02:00
|
|
|
SELECT tf1(17, 100.0);
|
2001-09-15 21:56:59 +02:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
In practice one would probably like a more useful result from the
|
2003-04-10 03:22:45 +02:00
|
|
|
function than a constant 1, so a more likely definition
|
2007-02-01 01:28:19 +01:00
|
|
|
is:
|
2001-09-15 21:56:59 +02:00
|
|
|
|
|
|
|
<programlisting>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION tf1 (integer, numeric) RETURNS numeric AS $$
|
2008-07-18 05:32:53 +02:00
|
|
|
UPDATE bank
|
2001-10-26 21:58:12 +02:00
|
|
|
SET balance = balance - $2
|
|
|
|
WHERE accountno = $1;
|
|
|
|
SELECT balance FROM bank WHERE accountno = $1;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2001-09-15 21:56:59 +02:00
|
|
|
</programlisting>
|
2001-10-26 21:58:12 +02:00
|
|
|
|
|
|
|
which adjusts the balance and returns the new balance.
|
2008-10-31 20:37:56 +01:00
|
|
|
The same thing could be done in one command using <literal>RETURNING</>:
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION tf1 (integer, numeric) RETURNS numeric AS $$
|
|
|
|
UPDATE bank
|
|
|
|
SET balance = balance - $2
|
|
|
|
WHERE accountno = $1
|
|
|
|
RETURNING balance;
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
</programlisting>
|
2001-10-26 21:58:12 +02:00
|
|
|
</para>
|
1999-07-22 17:11:05 +02:00
|
|
|
</sect2>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2010-11-07 19:03:19 +01:00
|
|
|
<sect2 id="xfunc-sql-composite-functions">
|
1999-07-22 17:11:05 +02:00
|
|
|
<title><acronym>SQL</acronym> Functions on Composite Types</title>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2004-05-11 00:44:49 +02:00
|
|
|
When writing functions with arguments of composite
|
2001-10-26 21:58:12 +02:00
|
|
|
types, we must not only specify which
|
2001-09-15 21:56:59 +02:00
|
|
|
argument we want (as we did above with <literal>$1</> and <literal>$2</literal>) but
|
2004-05-11 00:44:49 +02:00
|
|
|
also the desired attribute (field) of that argument. For example,
|
2008-07-18 05:32:53 +02:00
|
|
|
suppose that
|
2003-04-10 03:22:45 +02:00
|
|
|
<type>emp</type> is a table containing employee data, and therefore
|
2001-10-26 21:58:12 +02:00
|
|
|
also the name of the composite type of each row of the table. Here
|
2003-04-10 03:22:45 +02:00
|
|
|
is a function <function>double_salary</function> that computes what someone's
|
1999-07-22 17:11:05 +02:00
|
|
|
salary would be if it were doubled:
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
|
|
|
CREATE TABLE emp (
|
|
|
|
name text,
|
2004-05-11 00:44:49 +02:00
|
|
|
salary numeric,
|
2003-04-10 03:22:45 +02:00
|
|
|
age integer,
|
|
|
|
cubicle point
|
|
|
|
);
|
|
|
|
|
2010-07-25 10:30:42 +02:00
|
|
|
INSERT INTO emp VALUES ('Bill', 4200, 45, '(2,1)');
|
|
|
|
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION double_salary(emp) RETURNS numeric AS $$
|
2001-09-15 21:56:59 +02:00
|
|
|
SELECT $1.salary * 2 AS salary;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2004-05-11 00:44:49 +02:00
|
|
|
SELECT name, double_salary(emp.*) AS dream
|
2003-04-10 03:22:45 +02:00
|
|
|
FROM emp
|
|
|
|
WHERE emp.cubicle ~= point '(2,1)';
|
2000-08-25 17:17:50 +02:00
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
name | dream
|
|
|
|
------+-------
|
2005-01-07 23:40:46 +01:00
|
|
|
Bill | 8400
|
2001-09-15 21:56:59 +02:00
|
|
|
</screen>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
2001-09-15 21:56:59 +02:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
Notice the use of the syntax <literal>$1.salary</literal>
|
|
|
|
to select one field of the argument row value. Also notice
|
2004-05-11 00:44:49 +02:00
|
|
|
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:
|
2003-09-13 00:17:24 +02:00
|
|
|
<screen>
|
2004-05-11 00:44:49 +02:00
|
|
|
SELECT name, double_salary(emp) AS dream
|
2003-09-13 00:17:24 +02:00
|
|
|
FROM emp
|
|
|
|
WHERE emp.cubicle ~= point '(2,1)';
|
|
|
|
</screen>
|
2004-05-11 00:44:49 +02:00
|
|
|
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>
|
2005-01-07 23:40:46 +01:00
|
|
|
SELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream
|
2004-05-11 00:44:49 +02:00
|
|
|
FROM emp;
|
|
|
|
</screen>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
2001-09-15 21:56:59 +02:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
It is also possible to build a function that returns a composite type.
|
2008-07-18 05:32:53 +02:00
|
|
|
This is an example of a function
|
2003-04-10 03:22:45 +02:00
|
|
|
that returns a single <type>emp</type> row:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
<programlisting>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION new_emp() RETURNS emp AS $$
|
|
|
|
SELECT text 'None' AS name,
|
2005-01-07 23:40:46 +01:00
|
|
|
1000.0 AS salary,
|
2000-08-25 17:17:50 +02:00
|
|
|
25 AS age,
|
2004-05-17 01:22:08 +02:00
|
|
|
point '(2,2)' AS cubicle;
|
|
|
|
$$ LANGUAGE SQL;
|
2001-09-15 21:56:59 +02:00
|
|
|
</programlisting>
|
|
|
|
|
2003-08-10 00:50:22 +02:00
|
|
|
In this example we have specified each of the attributes
|
2003-04-10 03:22:45 +02:00
|
|
|
with a constant value, but any computation
|
1998-03-01 09:16:16 +01:00
|
|
|
could have been substituted for these constants.
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
Note two important things about defining the function:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
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.)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
You must typecast the expressions to match the
|
|
|
|
definition of the composite type, or you will get errors like this:
|
2001-09-15 21:56:59 +02:00
|
|
|
<screen>
|
|
|
|
<computeroutput>
|
2000-08-25 01:36:29 +02:00
|
|
|
ERROR: function declared to return emp returns varchar instead of text at column 1
|
2001-09-15 21:56:59 +02:00
|
|
|
</computeroutput>
|
|
|
|
</screen>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
2001-10-26 21:58:12 +02:00
|
|
|
</itemizedlist>
|
2008-07-18 05:32:53 +02:00
|
|
|
</para>
|
2001-10-26 21:58:12 +02:00
|
|
|
|
|
|
|
<para>
|
2005-01-07 23:40:46 +01:00
|
|
|
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
|
|
|
|
another function that returns the desired composite value.
|
2008-07-18 05:32:53 +02:00
|
|
|
</para>
|
2005-01-07 23:40:46 +01:00
|
|
|
|
|
|
|
<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">.
|
2008-07-18 05:32:53 +02:00
|
|
|
</para>
|
2005-01-07 23:40:46 +01:00
|
|
|
|
|
|
|
<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:
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2001-09-15 21:56:59 +02:00
|
|
|
<screen>
|
2003-04-10 03:22:45 +02:00
|
|
|
SELECT (new_emp()).name;
|
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
name
|
|
|
|
------
|
2001-09-15 21:56:59 +02:00
|
|
|
None
|
2002-03-21 17:02:16 +01:00
|
|
|
</screen>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
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:
|
2002-03-21 17:02:16 +01:00
|
|
|
|
|
|
|
<screen>
|
|
|
|
SELECT new_emp().name;
|
2008-10-31 20:37:56 +01:00
|
|
|
ERROR: syntax error at or near "."
|
2004-12-30 04:13:56 +01:00
|
|
|
LINE 1: SELECT new_emp().name;
|
|
|
|
^
|
2001-09-15 21:56:59 +02:00
|
|
|
</screen>
|
2001-10-26 21:58:12 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2002-08-29 02:17:06 +02:00
|
|
|
Another option is to use
|
2008-07-18 05:32:53 +02:00
|
|
|
functional notation for extracting an attribute. The simple way
|
2002-03-21 17:02:16 +01:00
|
|
|
to explain this is that we can use the
|
2001-10-26 21:58:12 +02:00
|
|
|
notations <literal>attribute(table)</> and <literal>table.attribute</>
|
2003-04-10 03:22:45 +02:00
|
|
|
interchangeably.
|
2001-10-26 21:58:12 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
2002-03-21 17:02:16 +01:00
|
|
|
SELECT name(new_emp());
|
|
|
|
|
|
|
|
name
|
|
|
|
------
|
|
|
|
None
|
|
|
|
</screen>
|
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
<screen>
|
2003-04-10 03:22:45 +02:00
|
|
|
-- This is the same as:
|
2005-01-07 23:40:46 +01:00
|
|
|
-- SELECT emp.name AS youngster FROM emp WHERE emp.age < 30;
|
2003-04-10 03:22:45 +02:00
|
|
|
|
2005-01-07 23:40:46 +01:00
|
|
|
SELECT name(emp) AS youngster FROM emp WHERE age(emp) < 30;
|
2003-04-10 03:22:45 +02:00
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
youngster
|
|
|
|
-----------
|
|
|
|
Sam
|
2005-01-07 23:40:46 +01:00
|
|
|
Andy
|
2001-10-26 21:58:12 +02:00
|
|
|
</screen>
|
|
|
|
</para>
|
|
|
|
|
2005-01-08 00:08:44 +01:00
|
|
|
<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>
|
2010-11-07 19:03:19 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Because of this behavior, it's unwise to give a function that takes
|
|
|
|
a single composite-type argument the same name as any of the fields of
|
|
|
|
that composite type.
|
|
|
|
</para>
|
2005-01-08 00:08:44 +01:00
|
|
|
</tip>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2005-04-01 00:46:33 +02:00
|
|
|
Another way to use a function returning a composite type is to pass the
|
2004-12-30 04:13:56 +01:00
|
|
|
result to another function that accepts the correct row type as input:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION getname(emp) RETURNS text AS $$
|
2003-11-12 23:47:47 +01:00
|
|
|
SELECT $1.name;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
SELECT getname(new_emp());
|
|
|
|
getname
|
|
|
|
---------
|
|
|
|
None
|
|
|
|
(1 row)
|
|
|
|
</screen>
|
2008-07-16 03:30:23 +02:00
|
|
|
</para>
|
2004-12-30 04:13:56 +01:00
|
|
|
|
|
|
|
<para>
|
2005-04-01 00:46:33 +02:00
|
|
|
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>
|
|
|
|
|
2009-10-08 04:39:25 +02:00
|
|
|
<sect2 id="xfunc-named-parameters">
|
|
|
|
<title><acronym>SQL</> Functions with Parameter Names</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>named parameter</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
It is possible to attach names to a function's parameters, for example
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION tf1 (acct_no integer, debit numeric) RETURNS numeric AS $$
|
|
|
|
UPDATE bank
|
|
|
|
SET balance = balance - $2
|
|
|
|
WHERE accountno = $1
|
|
|
|
RETURNING balance;
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
Here the first parameter has been given the name <literal>acct_no</>,
|
|
|
|
and the second parameter the name <literal>debit</>.
|
|
|
|
So far as the SQL function itself is concerned, these names are just
|
|
|
|
decoration; you must still refer to the parameters as <literal>$1</>,
|
|
|
|
<literal>$2</>, etc within the function body. (Some procedural
|
|
|
|
languages let you use the parameter names instead.) However,
|
|
|
|
attaching names to the parameters is useful for documentation purposes.
|
|
|
|
When a function has many parameters, it is also useful to use the names
|
|
|
|
while calling the function, as described in
|
|
|
|
<xref linkend="sql-syntax-calling-funcs">.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2005-04-01 00:46:33 +02:00
|
|
|
<sect2 id="xfunc-output-parameters">
|
2008-07-16 03:30:23 +02:00
|
|
|
<title><acronym>SQL</> Functions with Output Parameters</title>
|
2005-04-01 00:46:33 +02:00
|
|
|
|
|
|
|
<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_prod
|
|
|
|
AS 'SELECT $1 + $2, $1 * $2'
|
|
|
|
LANGUAGE SQL;
|
|
|
|
</screen>
|
|
|
|
|
|
|
|
but not having to bother with the separate composite type definition
|
2009-10-08 04:39:25 +02:00
|
|
|
is often handy. Notice that the names attached to the output parameters
|
|
|
|
are not just decoration, but determine the column names of the anonymous
|
|
|
|
composite type. (If you omit a name for an output parameter, the
|
|
|
|
system will choose a name on its own.)
|
2005-04-01 00:46:33 +02:00
|
|
|
</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),
|
2008-07-16 03:30:23 +02:00
|
|
|
<literal>OUT</>, <literal>INOUT</>, or <literal>VARIADIC</>.
|
|
|
|
An <literal>INOUT</>
|
2005-04-01 00:46:33 +02:00
|
|
|
parameter serves as both an input parameter (part of the calling
|
|
|
|
argument list) and an output parameter (part of the result record type).
|
2008-07-16 03:30:23 +02:00
|
|
|
<literal>VARIADIC</> parameters are input parameters, but are treated
|
|
|
|
specially as described next.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="xfunc-sql-variadic-functions">
|
|
|
|
<title><acronym>SQL</> Functions with Variable Numbers of Arguments</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>variadic</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>variadic function</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
<acronym>SQL</acronym> functions can be declared to accept
|
|
|
|
variable numbers of arguments, so long as all the <quote>optional</>
|
|
|
|
arguments are of the same data type. The optional arguments will be
|
|
|
|
passed to the function as an array. The function is declared by
|
|
|
|
marking the last parameter as <literal>VARIADIC</>; this parameter
|
|
|
|
must be declared as being of an array type. For example:
|
|
|
|
|
|
|
|
<screen>
|
2009-10-08 04:39:25 +02:00
|
|
|
CREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$
|
2008-07-16 03:30:23 +02:00
|
|
|
SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
|
|
|
|
SELECT mleast(10, -1, 5, 4.4);
|
|
|
|
mleast
|
|
|
|
--------
|
|
|
|
-1
|
|
|
|
(1 row)
|
|
|
|
</screen>
|
|
|
|
|
|
|
|
Effectively, all the actual arguments at or beyond the
|
|
|
|
<literal>VARIADIC</> position are gathered up into a one-dimensional
|
|
|
|
array, as if you had written
|
|
|
|
|
|
|
|
<screen>
|
|
|
|
SELECT mleast(ARRAY[10, -1, 5, 4.4]); -- doesn't work
|
|
|
|
</screen>
|
|
|
|
|
|
|
|
You can't actually write that, though — or at least, it will
|
|
|
|
not match this function definition. A parameter marked
|
|
|
|
<literal>VARIADIC</> matches one or more occurrences of its element
|
|
|
|
type, not of its own type.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Sometimes it is useful to be able to pass an already-constructed array
|
|
|
|
to a variadic function; this is particularly handy when one variadic
|
|
|
|
function wants to pass on its array parameter to another one. You can
|
|
|
|
do that by specifying <literal>VARIADIC</> in the call:
|
|
|
|
|
|
|
|
<screen>
|
|
|
|
SELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);
|
|
|
|
</screen>
|
|
|
|
|
|
|
|
This prevents expansion of the function's variadic parameter into its
|
|
|
|
element type, thereby allowing the array argument value to match
|
|
|
|
normally. <literal>VARIADIC</> can only be attached to the last
|
|
|
|
actual argument of a function call.
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
2009-10-08 04:39:25 +02:00
|
|
|
|
|
|
|
<para>
|
|
|
|
The array element parameters generated from a variadic parameter are
|
|
|
|
treated as not having any names of their own. This means it is not
|
|
|
|
possible to call a variadic function using named arguments (<xref
|
|
|
|
linkend="sql-syntax-calling-funcs">), except when you specify
|
|
|
|
<literal>VARIADIC</>. For example, this will work:
|
|
|
|
|
|
|
|
<screen>
|
2010-05-30 20:10:41 +02:00
|
|
|
SELECT mleast(VARIADIC arr := ARRAY[10, -1, 5, 4.4]);
|
2009-10-08 04:39:25 +02:00
|
|
|
</screen>
|
|
|
|
|
|
|
|
but not these:
|
|
|
|
|
|
|
|
<screen>
|
2010-05-30 20:10:41 +02:00
|
|
|
SELECT mleast(arr := 10);
|
|
|
|
SELECT mleast(arr := ARRAY[10, -1, 5, 4.4]);
|
2009-10-08 04:39:25 +02:00
|
|
|
</screen>
|
|
|
|
</para>
|
2001-10-26 21:58:12 +02:00
|
|
|
</sect2>
|
|
|
|
|
2008-12-18 19:20:35 +01:00
|
|
|
<sect2 id="xfunc-sql-parameter-defaults">
|
|
|
|
<title><acronym>SQL</> Functions with Default Values for Arguments</title>
|
2008-12-04 18:51:28 +01:00
|
|
|
|
|
|
|
<indexterm>
|
2008-12-18 19:20:35 +01:00
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>default values for arguments</secondary>
|
2008-12-04 18:51:28 +01:00
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
2008-12-18 19:20:35 +01:00
|
|
|
Functions can be declared with default values for some or all input
|
|
|
|
arguments. The default values are inserted whenever the function is
|
|
|
|
called with insufficiently many actual arguments. Since arguments
|
|
|
|
can only be omitted from the end of the actual argument list, all
|
|
|
|
parameters after a parameter with a default value have to have
|
2009-10-08 04:39:25 +02:00
|
|
|
default values as well. (Although the use of named argument notation
|
|
|
|
could allow this restriction to be relaxed, it's still enforced so that
|
|
|
|
positional argument notation works sensibly.)
|
2008-12-04 18:51:28 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
For example:
|
|
|
|
<screen>
|
2008-12-18 19:20:35 +01:00
|
|
|
CREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)
|
2008-12-04 18:51:28 +01:00
|
|
|
RETURNS int
|
|
|
|
LANGUAGE SQL
|
|
|
|
AS $$
|
|
|
|
SELECT $1 + $2 + $3;
|
|
|
|
$$;
|
|
|
|
|
|
|
|
SELECT foo(10, 20, 30);
|
|
|
|
foo
|
|
|
|
-----
|
|
|
|
60
|
|
|
|
(1 row)
|
|
|
|
|
|
|
|
SELECT foo(10, 20);
|
|
|
|
foo
|
|
|
|
-----
|
|
|
|
33
|
|
|
|
(1 row)
|
|
|
|
|
|
|
|
SELECT foo(10);
|
|
|
|
foo
|
|
|
|
-----
|
|
|
|
15
|
|
|
|
(1 row)
|
|
|
|
|
2008-12-18 19:20:35 +01:00
|
|
|
SELECT foo(); -- fails since there is no default for the first argument
|
|
|
|
ERROR: function foo() does not exist
|
2008-12-04 18:51:28 +01:00
|
|
|
</screen>
|
2008-12-18 19:20:35 +01:00
|
|
|
The <literal>=</literal> sign can also be used in place of the
|
2009-10-08 04:39:25 +02:00
|
|
|
key word <literal>DEFAULT</literal>.
|
2008-12-04 18:51:28 +01:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2005-01-07 23:40:46 +01:00
|
|
|
<sect2 id="xfunc-sql-table-functions">
|
2003-04-10 03:22:45 +02:00
|
|
|
<title><acronym>SQL</acronym> Functions as Table Sources</title>
|
2002-06-20 18:57:00 +02:00
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
All SQL functions can be used in the <literal>FROM</> clause of a query,
|
2002-08-29 02:17:06 +02:00
|
|
|
but it is particularly useful for functions returning composite types.
|
2002-06-20 18:57:00 +02:00
|
|
|
If the function is defined to return a base type, the table function
|
2002-08-29 02:17:06 +02:00
|
|
|
produces a one-column table. If the function is defined to return
|
2003-04-10 03:22:45 +02:00
|
|
|
a composite type, the table function produces a column for each attribute
|
2002-08-29 02:17:06 +02:00
|
|
|
of the composite type.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Here is an example:
|
2002-06-20 18:57:00 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
2002-08-29 02:17:06 +02:00
|
|
|
CREATE TABLE foo (fooid int, foosubid int, fooname text);
|
2003-04-10 03:22:45 +02:00
|
|
|
INSERT INTO foo VALUES (1, 1, 'Joe');
|
|
|
|
INSERT INTO foo VALUES (1, 2, 'Ed');
|
|
|
|
INSERT INTO foo VALUES (2, 1, 'Mary');
|
2002-08-29 02:17:06 +02:00
|
|
|
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION getfoo(int) RETURNS foo AS $$
|
2002-08-29 02:17:06 +02:00
|
|
|
SELECT * FROM foo WHERE fooid = $1;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
SELECT *, upper(fooname) FROM getfoo(1) AS t1;
|
|
|
|
|
|
|
|
fooid | foosubid | fooname | upper
|
|
|
|
-------+----------+---------+-------
|
|
|
|
1 | 1 | Joe | JOE
|
2005-10-14 22:48:18 +02:00
|
|
|
(1 row)
|
2002-08-29 02:17:06 +02:00
|
|
|
</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
|
2004-12-30 04:13:56 +01:00
|
|
|
we did not use <literal>SETOF</>. That is described in the next section.
|
2002-08-29 02:17:06 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2008-07-18 05:32:53 +02:00
|
|
|
<sect2 id="xfunc-sql-functions-returning-set">
|
2002-08-29 02:17:06 +02:00
|
|
|
<title><acronym>SQL</acronym> Functions Returning Sets</title>
|
|
|
|
|
2008-07-18 05:32:53 +02:00
|
|
|
<indexterm>
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>with SETOF</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
2002-08-29 02:17:06 +02:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
When an SQL function is declared as returning <literal>SETOF
|
|
|
|
<replaceable>sometype</></literal>, the function's final
|
2008-10-31 20:37:56 +01:00
|
|
|
query is executed to completion, and each row it
|
2003-04-10 03:22:45 +02:00
|
|
|
outputs is returned as an element of the result set.
|
2002-08-29 02:17:06 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
This feature is normally used when calling the function in the <literal>FROM</>
|
|
|
|
clause. In this case each row returned by the function becomes
|
2002-08-29 02:17:06 +02:00
|
|
|
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>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$
|
2002-06-20 18:57:00 +02:00
|
|
|
SELECT * FROM foo WHERE fooid = $1;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2002-08-29 02:17:06 +02:00
|
|
|
|
2002-06-20 18:57:00 +02:00
|
|
|
SELECT * FROM getfoo(1) AS t1;
|
|
|
|
</programlisting>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
Then we would get:
|
2002-06-20 18:57:00 +02:00
|
|
|
<screen>
|
|
|
|
fooid | foosubid | fooname
|
|
|
|
-------+----------+---------
|
|
|
|
1 | 1 | Joe
|
|
|
|
1 | 2 | Ed
|
|
|
|
(2 rows)
|
|
|
|
</screen>
|
|
|
|
</para>
|
2001-10-26 21:58:12 +02:00
|
|
|
|
2007-11-10 21:14:36 +01:00
|
|
|
<para>
|
|
|
|
It is also possible to return multiple rows with the columns defined by
|
|
|
|
output parameters, like this:
|
|
|
|
|
|
|
|
<programlisting>
|
2010-07-26 22:14:05 +02:00
|
|
|
CREATE TABLE tab (y int, z int);
|
|
|
|
INSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);
|
|
|
|
|
2010-05-16 06:35:04 +02:00
|
|
|
CREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)
|
2010-07-26 22:14:05 +02:00
|
|
|
RETURNS SETOF record
|
|
|
|
AS $$
|
2008-07-18 05:32:53 +02:00
|
|
|
SELECT $1 + tab.y, $1 * tab.y FROM tab;
|
2007-11-10 21:14:36 +01:00
|
|
|
$$ LANGUAGE SQL;
|
2010-07-26 22:14:05 +02:00
|
|
|
|
|
|
|
SELECT * FROM sum_n_product_with_tab(10);
|
|
|
|
sum | product
|
|
|
|
-----+---------
|
|
|
|
11 | 10
|
|
|
|
13 | 30
|
|
|
|
15 | 50
|
|
|
|
17 | 70
|
|
|
|
(4 rows)
|
2007-11-10 21:14:36 +01:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
The key point here is that you must write <literal>RETURNS SETOF record</>
|
|
|
|
to indicate that the function returns multiple rows instead of just one.
|
|
|
|
If there is only one output parameter, write that parameter's type
|
|
|
|
instead of <type>record</>.
|
|
|
|
</para>
|
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
Currently, functions returning sets can also be called in the select list
|
2003-04-10 03:22:45 +02:00
|
|
|
of a query. For each row that the query
|
2002-06-20 18:57:00 +02:00
|
|
|
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,
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
however, that this capability is deprecated and might be removed in future
|
2002-06-20 18:57:00 +02:00
|
|
|
releases. The following is an example function returning a set from the
|
2003-04-10 03:22:45 +02:00
|
|
|
select list:
|
2001-10-26 21:58:12 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<screen>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$
|
|
|
|
SELECT name FROM nodes WHERE parent = $1
|
|
|
|
$$ LANGUAGE SQL;
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
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)
|
2001-09-15 21:56:59 +02:00
|
|
|
</screen>
|
2001-10-26 21:58:12 +02:00
|
|
|
|
2002-01-07 03:29:15 +01:00
|
|
|
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
|
2003-04-10 03:22:45 +02:00
|
|
|
for those arguments, so no result rows are generated.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
2008-10-31 20:37:56 +01:00
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
If a function's last command is <command>INSERT</>, <command>UPDATE</>,
|
|
|
|
or <command>DELETE</> with <literal>RETURNING</>, that command will
|
|
|
|
always be executed to completion, even if the function is not declared
|
|
|
|
with <literal>SETOF</> or the calling query does not fetch all the
|
|
|
|
result rows. Any extra rows produced by the <literal>RETURNING</>
|
|
|
|
clause are silently dropped, but the commanded table modifications
|
|
|
|
still happen (and are all completed before returning from the function).
|
|
|
|
</para>
|
|
|
|
</note>
|
1999-07-22 17:11:05 +02:00
|
|
|
</sect2>
|
2003-08-10 00:50:22 +02:00
|
|
|
|
2008-07-18 05:32:53 +02:00
|
|
|
<sect2 id="xfunc-sql-functions-returning-table">
|
|
|
|
<title><acronym>SQL</acronym> Functions Returning <literal>TABLE</></title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>RETURNS TABLE</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
There is another way to declare a function as returning a set,
|
|
|
|
which is to use the syntax
|
|
|
|
<literal>RETURNS TABLE(<replaceable>columns</>)</literal>.
|
|
|
|
This is equivalent to using one or more <literal>OUT</> parameters plus
|
|
|
|
marking the function as returning <literal>SETOF record</> (or
|
|
|
|
<literal>SETOF</> a single output parameter's type, as appropriate).
|
|
|
|
This notation is specified in recent versions of the SQL standard, and
|
|
|
|
thus may be more portable than using <literal>SETOF</>.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
For example, the preceding sum-and-product example could also be
|
|
|
|
done this way:
|
|
|
|
|
|
|
|
<programlisting>
|
2010-05-16 06:35:04 +02:00
|
|
|
CREATE FUNCTION sum_n_product_with_tab (x int)
|
|
|
|
RETURNS TABLE(sum int, product int) AS $$
|
2008-07-18 05:32:53 +02:00
|
|
|
SELECT $1 + tab.y, $1 * tab.y FROM tab;
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
It is not allowed to use explicit <literal>OUT</> or <literal>INOUT</>
|
|
|
|
parameters with the <literal>RETURNS TABLE</> notation — you must
|
|
|
|
put all the output columns in the <literal>TABLE</> list.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2003-08-10 00:50:22 +02:00
|
|
|
<sect2>
|
|
|
|
<title>Polymorphic <acronym>SQL</acronym> Functions</title>
|
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
<acronym>SQL</acronym> functions can be declared to accept and
|
2007-04-02 05:49:42 +02:00
|
|
|
return the polymorphic types <type>anyelement</type>,
|
2007-06-07 01:00:50 +02:00
|
|
|
<type>anyarray</type>, <type>anynonarray</type>, and
|
|
|
|
<type>anyenum</type>. See <xref
|
2003-11-12 23:47:47 +01:00
|
|
|
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:
|
2003-08-10 00:50:22 +02:00
|
|
|
<screen>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$
|
2003-08-10 00:50:22 +02:00
|
|
|
SELECT ARRAY[$1, $2];
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2003-08-10 00:50:22 +02:00
|
|
|
|
|
|
|
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>
|
2007-04-02 05:49:42 +02:00
|
|
|
ERROR: could not determine polymorphic type because input has type "unknown"
|
2003-08-10 00:50:22 +02:00
|
|
|
</computeroutput>
|
|
|
|
</screen>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
It is permitted to have polymorphic arguments with a fixed
|
2003-08-10 00:50:22 +02:00
|
|
|
return type, but the converse is not. For example:
|
|
|
|
<screen>
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$
|
2005-01-22 23:56:36 +01:00
|
|
|
SELECT $1 > $2;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2003-08-10 00:50:22 +02:00
|
|
|
|
|
|
|
SELECT is_greater(1, 2);
|
|
|
|
is_greater
|
|
|
|
------------
|
|
|
|
f
|
|
|
|
(1 row)
|
|
|
|
|
2004-05-17 01:22:08 +02:00
|
|
|
CREATE FUNCTION invalid_func() RETURNS anyelement AS $$
|
2003-08-10 00:50:22 +02:00
|
|
|
SELECT 1;
|
2004-05-17 01:22:08 +02:00
|
|
|
$$ LANGUAGE SQL;
|
2003-11-12 23:47:47 +01:00
|
|
|
ERROR: cannot determine result data type
|
2007-04-02 05:49:42 +02:00
|
|
|
DETAIL: A function returning a polymorphic type must have at least one polymorphic argument.
|
2005-04-01 00:46:33 +02:00
|
|
|
</screen>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Polymorphism can be used with functions that have output arguments.
|
|
|
|
For example:
|
|
|
|
<screen>
|
|
|
|
CREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)
|
2008-07-16 03:30:23 +02:00
|
|
|
AS 'select $1, array[$1,$1]' LANGUAGE SQL;
|
2005-04-01 00:46:33 +02:00
|
|
|
|
|
|
|
SELECT * FROM dup(22);
|
|
|
|
f2 | f3
|
|
|
|
----+---------
|
|
|
|
22 | {22,22}
|
|
|
|
(1 row)
|
2008-07-16 03:30:23 +02:00
|
|
|
</screen>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Polymorphism can also be used with variadic functions.
|
|
|
|
For example:
|
|
|
|
<screen>
|
|
|
|
CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
|
|
|
|
SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
|
|
|
|
SELECT anyleast(10, -1, 5, 4);
|
|
|
|
anyleast
|
|
|
|
----------
|
|
|
|
-1
|
|
|
|
(1 row)
|
|
|
|
|
|
|
|
SELECT anyleast('abc'::text, 'def');
|
|
|
|
anyleast
|
|
|
|
----------
|
|
|
|
abc
|
|
|
|
(1 row)
|
|
|
|
|
2011-02-17 18:37:13 +01:00
|
|
|
CREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$
|
2008-07-16 03:30:23 +02:00
|
|
|
SELECT array_to_string($2, $1);
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
|
2011-02-17 18:37:13 +01:00
|
|
|
SELECT concat_values('|', 1, 4, 2);
|
|
|
|
concat_values
|
|
|
|
---------------
|
2008-07-16 03:30:23 +02:00
|
|
|
1|4|2
|
|
|
|
(1 row)
|
2003-08-10 00:50:22 +02:00
|
|
|
</screen>
|
|
|
|
</para>
|
|
|
|
</sect2>
|
2011-03-25 23:21:25 +01:00
|
|
|
|
|
|
|
<sect2>
|
|
|
|
<title><acronym>SQL</acronym> Functions with Collations</title>
|
|
|
|
|
|
|
|
<indexterm>
|
|
|
|
<primary>collation</>
|
|
|
|
<secondary>in SQL functions</>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
When a SQL function has one or more parameters of collatable data types,
|
|
|
|
a collation is identified for each function call depending on the
|
|
|
|
collations assigned to the actual arguments, as described in <xref
|
|
|
|
linkend="collation">. If a collation is successfully identified
|
|
|
|
(i.e., there are no conflicts of implicit collations among the arguments)
|
|
|
|
then all the collatable parameters are treated as having that collation
|
|
|
|
implicitly. This will affect the behavior of collation-sensitive
|
|
|
|
operations within the function. For example, using the
|
|
|
|
<function>anyleast</> function described above, the result of
|
|
|
|
<programlisting>
|
|
|
|
SELECT anyleast('abc'::text, 'ABC');
|
|
|
|
</programlisting>
|
|
|
|
will depend on the database's default collation. In <literal>C</> locale
|
|
|
|
the result will be <literal>ABC</>, but in many other locales it will
|
|
|
|
be <literal>abc</>. The collation to use can be forced by adding
|
|
|
|
a <literal>COLLATE</> clause to any of the arguments, for example
|
|
|
|
<programlisting>
|
|
|
|
SELECT anyleast('abc'::text, 'ABC' COLLATE "C");
|
|
|
|
</programlisting>
|
|
|
|
Alternatively, if you wish a function to operate with a particular
|
|
|
|
collation regardless of what it is called with, insert
|
|
|
|
<literal>COLLATE</> clauses as needed in the function definition.
|
|
|
|
This version of <function>anyleast</> would always use <literal>en_US</>
|
|
|
|
locale to compare strings:
|
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
|
|
|
|
SELECT min($1[i] COLLATE "en_US") FROM generate_subscripts($1, 1) g(i);
|
|
|
|
$$ LANGUAGE SQL;
|
|
|
|
</programlisting>
|
|
|
|
But note that this will throw an error if applied to a non-collatable
|
|
|
|
data type.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
If no common collation can be identified among the actual arguments,
|
|
|
|
then a SQL function treats its parameters as having their data types'
|
|
|
|
default collation (which is usually the database's default collation,
|
|
|
|
but could be different for parameters of domain types).
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The behavior of collatable parameters can be thought of as a limited
|
|
|
|
form of polymorphism, applicable only to textual data types.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
1999-07-22 17:11:05 +02:00
|
|
|
</sect1>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<sect1 id="xfunc-overload">
|
|
|
|
<title>Function Overloading</title>
|
|
|
|
|
|
|
|
<indexterm zone="xfunc-overload">
|
|
|
|
<primary>overloading</primary>
|
|
|
|
<secondary>functions</secondary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
More than one function can be defined with the same SQL name, so long
|
2004-12-30 04:13:56 +01:00
|
|
|
as the arguments they take are different. In other words,
|
|
|
|
function names can be <firstterm>overloaded</firstterm>. When a
|
|
|
|
query is executed, the server will determine which function to
|
|
|
|
call from the data types and the number of the provided arguments.
|
|
|
|
Overloading can also be used to simulate functions with a variable
|
|
|
|
number of arguments, up to a finite maximum number.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
When creating a family of overloaded functions, one should be
|
|
|
|
careful not to create ambiguities. For instance, given the
|
2007-02-01 01:28:19 +01:00
|
|
|
functions:
|
2004-12-30 04:13:56 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION test(int, real) RETURNS ...
|
|
|
|
CREATE FUNCTION test(smallint, double precision) RETURNS ...
|
|
|
|
</programlisting>
|
|
|
|
it is not immediately clear which function would be called with
|
|
|
|
some trivial input like <literal>test(1, 1.5)</literal>. The
|
|
|
|
currently implemented resolution rules are described in
|
|
|
|
<xref linkend="typeconv">, but it is unwise to design a system that subtly
|
|
|
|
relies on this behavior.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A function that takes a single argument of a composite type should
|
|
|
|
generally not have the same name as any attribute (field) of that type.
|
|
|
|
Recall that <literal>attribute(table)</literal> is considered equivalent
|
|
|
|
to <literal>table.attribute</literal>. In the case that there is an
|
|
|
|
ambiguity between a function on a composite type and an attribute of
|
|
|
|
the composite type, the attribute will always be used. It is possible
|
|
|
|
to override that choice by schema-qualifying the function name
|
|
|
|
(that is, <literal>schema.func(table)</literal>) but it's better to
|
|
|
|
avoid the problem by not choosing conflicting names.
|
|
|
|
</para>
|
|
|
|
|
2008-07-16 03:30:23 +02:00
|
|
|
<para>
|
|
|
|
Another possible conflict is between variadic and non-variadic functions.
|
|
|
|
For instance, it is possible to create both <literal>foo(numeric)</> and
|
|
|
|
<literal>foo(VARIADIC numeric[])</>. In this case it is unclear which one
|
|
|
|
should be matched to a call providing a single numeric argument, such as
|
|
|
|
<literal>foo(10.1)</>. The rule is that the function appearing
|
|
|
|
earlier in the search path is used, or if the two functions are in the
|
|
|
|
same schema, the non-variadic one is preferred.
|
|
|
|
</para>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<para>
|
|
|
|
When overloading C-language functions, there is an additional
|
|
|
|
constraint: The C name of each function in the family of
|
|
|
|
overloaded functions must be different from the C names of all
|
|
|
|
other functions, either internal or dynamically loaded. If this
|
|
|
|
rule is violated, the behavior is not portable. You might get a
|
|
|
|
run-time linker error, or one of the functions will get called
|
|
|
|
(usually the internal one). The alternative form of the
|
|
|
|
<literal>AS</> clause for the SQL <command>CREATE
|
|
|
|
FUNCTION</command> command decouples the SQL function name from
|
2007-02-01 01:28:19 +01:00
|
|
|
the function name in the C source code. For instance:
|
2004-12-30 04:13:56 +01:00
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION test(int) RETURNS int
|
|
|
|
AS '<replaceable>filename</>', 'test_1arg'
|
|
|
|
LANGUAGE C;
|
|
|
|
CREATE FUNCTION test(int, int) RETURNS int
|
|
|
|
AS '<replaceable>filename</>', 'test_2arg'
|
|
|
|
LANGUAGE C;
|
|
|
|
</programlisting>
|
|
|
|
The names of the C functions here reflect one of many possible conventions.
|
|
|
|
</para>
|
|
|
|
</sect1>
|
|
|
|
|
|
|
|
<sect1 id="xfunc-volatility">
|
|
|
|
<title>Function Volatility Categories</title>
|
|
|
|
|
|
|
|
<indexterm zone="xfunc-volatility">
|
|
|
|
<primary>volatility</primary>
|
|
|
|
<secondary>functions</secondary>
|
|
|
|
</indexterm>
|
2005-01-14 22:46:09 +01:00
|
|
|
<indexterm zone="xfunc-volatility">
|
|
|
|
<primary>VOLATILE</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm zone="xfunc-volatility">
|
|
|
|
<primary>STABLE</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm zone="xfunc-volatility">
|
|
|
|
<primary>IMMUTABLE</primary>
|
|
|
|
</indexterm>
|
2004-12-30 04:13:56 +01:00
|
|
|
|
|
|
|
<para>
|
|
|
|
Every function has a <firstterm>volatility</> classification, with
|
|
|
|
the possibilities being <literal>VOLATILE</>, <literal>STABLE</>, or
|
|
|
|
<literal>IMMUTABLE</>. <literal>VOLATILE</> is the default if the
|
2010-04-03 09:23:02 +02:00
|
|
|
<xref linkend="sql-createfunction">
|
2005-10-15 03:47:12 +02:00
|
|
|
command does not specify a category. The volatility category is a
|
|
|
|
promise to the optimizer about the behavior of the function:
|
2004-12-30 04:13:56 +01:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A <literal>VOLATILE</> function can do anything, including modifying
|
|
|
|
the database. It can return different results on successive calls with
|
|
|
|
the same arguments. The optimizer makes no assumptions about the
|
|
|
|
behavior of such functions. A query using a volatile function will
|
|
|
|
re-evaluate the function at every row where its value is needed.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
A <literal>STABLE</> function cannot modify the database and is
|
|
|
|
guaranteed to return the same results given the same arguments
|
2006-01-19 23:52:08 +01:00
|
|
|
for all rows within a single statement. This category allows the
|
|
|
|
optimizer to optimize multiple calls of the function to a single
|
|
|
|
call. In particular, it is safe to use an expression containing
|
|
|
|
such a function in an index scan condition. (Since an index scan
|
|
|
|
will evaluate the comparison value only once, not once at each
|
|
|
|
row, it is not valid to use a <literal>VOLATILE</> function in an
|
|
|
|
index scan condition.)
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
An <literal>IMMUTABLE</> function cannot modify the database and is
|
|
|
|
guaranteed to return the same results given the same arguments forever.
|
|
|
|
This category allows the optimizer to pre-evaluate the function when
|
|
|
|
a query calls it with constant arguments. For example, a query like
|
|
|
|
<literal>SELECT ... WHERE x = 2 + 2</> can be simplified on sight to
|
|
|
|
<literal>SELECT ... WHERE x = 4</>, because the function underlying
|
|
|
|
the integer addition operator is marked <literal>IMMUTABLE</>.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
For best optimization results, you should label your functions with the
|
|
|
|
strictest volatility category that is valid for them.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Any function with side-effects <emphasis>must</> be labeled
|
|
|
|
<literal>VOLATILE</>, so that calls to it cannot be optimized away.
|
|
|
|
Even a function with no side-effects needs to be labeled
|
|
|
|
<literal>VOLATILE</> if its value can change within a single query;
|
|
|
|
some examples are <literal>random()</>, <literal>currval()</>,
|
|
|
|
<literal>timeofday()</>.
|
|
|
|
</para>
|
|
|
|
|
2009-05-27 03:18:06 +02:00
|
|
|
<para>
|
|
|
|
Another important example is that the <function>current_timestamp</>
|
|
|
|
family of functions qualify as <literal>STABLE</>, since their values do
|
|
|
|
not change within a transaction.
|
|
|
|
</para>
|
|
|
|
|
2004-12-30 04:13:56 +01:00
|
|
|
<para>
|
|
|
|
There is relatively little difference between <literal>STABLE</> and
|
|
|
|
<literal>IMMUTABLE</> categories when considering simple interactive
|
|
|
|
queries that are planned and immediately executed: it doesn't matter
|
|
|
|
a lot whether a function is executed once during planning or once during
|
|
|
|
query execution startup. But there is a big difference if the plan is
|
|
|
|
saved and reused later. Labeling a function <literal>IMMUTABLE</> when
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
it really isn't might allow it to be prematurely folded to a constant during
|
2004-12-30 04:13:56 +01:00
|
|
|
planning, resulting in a stale value being re-used during subsequent uses
|
|
|
|
of the plan. This is a hazard when using prepared statements or when
|
|
|
|
using function languages that cache plans (such as
|
|
|
|
<application>PL/pgSQL</>).
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2009-05-27 03:18:06 +02:00
|
|
|
For functions written in SQL or in any of the standard procedural
|
|
|
|
languages, there is a second important property determined by the
|
|
|
|
volatility category, namely the visibility of any data changes that have
|
|
|
|
been made by the SQL command that is calling the function. A
|
|
|
|
<literal>VOLATILE</> function will see such changes, a <literal>STABLE</>
|
|
|
|
or <literal>IMMUTABLE</> function will not. This behavior is implemented
|
|
|
|
using the snapshotting behavior of MVCC (see <xref linkend="mvcc">):
|
|
|
|
<literal>STABLE</> and <literal>IMMUTABLE</> functions use a snapshot
|
|
|
|
established as of the start of the calling query, whereas
|
|
|
|
<literal>VOLATILE</> functions obtain a fresh snapshot at the start of
|
|
|
|
each query they execute.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
Functions written in C can manage snapshots however they want, but it's
|
|
|
|
usually a good idea to make C functions work this way too.
|
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Because of this snapshotting behavior,
|
2004-12-30 04:13:56 +01:00
|
|
|
a function containing only <command>SELECT</> commands can safely be
|
|
|
|
marked <literal>STABLE</>, even if it selects from tables that might be
|
|
|
|
undergoing modifications by concurrent queries.
|
2009-05-27 03:18:06 +02:00
|
|
|
<productname>PostgreSQL</productname> will execute all commands of a
|
|
|
|
<literal>STABLE</> function using the snapshot established for the
|
|
|
|
calling query, and so it will see a fixed view of the database throughout
|
|
|
|
that query.
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The same snapshotting behavior is used for <command>SELECT</> commands
|
|
|
|
within <literal>IMMUTABLE</> functions. It is generally unwise to select
|
|
|
|
from database tables within an <literal>IMMUTABLE</> function at all,
|
|
|
|
since the immutability will be broken if the table contents ever change.
|
|
|
|
However, <productname>PostgreSQL</productname> does not enforce that you
|
|
|
|
do not do that.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
A common error is to label a function <literal>IMMUTABLE</> when its
|
|
|
|
results depend on a configuration parameter. For example, a function
|
|
|
|
that manipulates timestamps might well have results that depend on the
|
|
|
|
<xref linkend="guc-timezone"> setting. For safety, such functions should
|
|
|
|
be labeled <literal>STABLE</> instead.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
Before <productname>PostgreSQL</productname> release 8.0, the requirement
|
|
|
|
that <literal>STABLE</> and <literal>IMMUTABLE</> functions cannot modify
|
2009-05-27 03:18:06 +02:00
|
|
|
the database was not enforced by the system. Releases 8.0 and later enforce it
|
2004-12-30 04:13:56 +01:00
|
|
|
by requiring SQL functions and procedural language functions of these
|
|
|
|
categories to contain no SQL commands other than <command>SELECT</>.
|
|
|
|
(This is not a completely bulletproof test, since such functions could
|
|
|
|
still call <literal>VOLATILE</> functions that modify the database.
|
|
|
|
If you do that, you will find that the <literal>STABLE</> or
|
|
|
|
<literal>IMMUTABLE</> function does not notice the database changes
|
2009-05-27 03:18:06 +02:00
|
|
|
applied by the called function, since they are hidden from its snapshot.)
|
2004-12-30 04:13:56 +01:00
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
</sect1>
|
|
|
|
|
2000-09-29 22:21:34 +02:00
|
|
|
<sect1 id="xfunc-pl">
|
1999-07-22 17:11:05 +02:00
|
|
|
<title>Procedural Language Functions</title>
|
|
|
|
|
|
|
|
<para>
|
2004-12-30 22:45:37 +01:00
|
|
|
<productname>PostgreSQL</productname> allows user-defined functions
|
|
|
|
to be written in other languages besides SQL and C. These other
|
|
|
|
languages are generically called <firstterm>procedural
|
|
|
|
languages</firstterm> (<acronym>PL</>s).
|
2003-10-23 00:28:10 +02:00
|
|
|
Procedural languages aren't built into the
|
|
|
|
<productname>PostgreSQL</productname> server; they are offered
|
2004-12-30 22:45:37 +01:00
|
|
|
by loadable modules.
|
|
|
|
See <xref linkend="xplang"> and following chapters for more
|
|
|
|
information.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</sect1>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2000-09-29 22:21:34 +02:00
|
|
|
<sect1 id="xfunc-internal">
|
1999-07-22 17:11:05 +02:00
|
|
|
<title>Internal Functions</title>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2001-11-12 20:19:39 +01:00
|
|
|
<indexterm zone="xfunc-internal"><primary>function</><secondary>internal</></>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2000-12-22 19:57:50 +01:00
|
|
|
Internal functions are functions written in C that have been statically
|
2001-09-15 21:56:59 +02:00
|
|
|
linked into the <productname>PostgreSQL</productname> server.
|
|
|
|
The <quote>body</quote> of the function definition
|
|
|
|
specifies the C-language name of the function, which need not be the
|
1999-07-22 17:11:05 +02:00
|
|
|
same as the name being declared for SQL use.
|
2011-03-11 20:33:10 +01:00
|
|
|
(For reasons of backward compatibility, an empty body
|
2001-09-15 21:56:59 +02:00
|
|
|
is accepted as meaning that the C-language function name is the
|
|
|
|
same as the SQL name.)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
2000-08-25 01:36:29 +02:00
|
|
|
|
|
|
|
<para>
|
2001-09-15 21:56:59 +02:00
|
|
|
Normally, all internal functions present in the
|
2009-12-10 07:32:28 +01:00
|
|
|
server are declared during the initialization of the database cluster
|
|
|
|
(see <xref linkend="creating-cluster">),
|
2001-09-15 21:56:59 +02:00
|
|
|
but a user could use <command>CREATE FUNCTION</command>
|
|
|
|
to create additional alias names for an internal function.
|
2000-08-25 01:36:29 +02:00
|
|
|
Internal functions are declared in <command>CREATE FUNCTION</command>
|
2001-09-15 21:56:59 +02:00
|
|
|
with language name <literal>internal</literal>. For instance, to
|
|
|
|
create an alias for the <function>sqrt</function> function:
|
|
|
|
<programlisting>
|
|
|
|
CREATE FUNCTION square_root(double precision) RETURNS double precision
|
2004-09-21 00:48:29 +02:00
|
|
|
AS 'dsqrt'
|
2003-04-10 03:22:45 +02:00
|
|
|
LANGUAGE internal
|
|
|
|
STRICT;
|
2001-09-15 21:56:59 +02:00
|
|
|
</programlisting>
|
|
|
|
(Most internal functions expect to be declared <quote>strict</quote>.)
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
2001-09-15 21:56:59 +02:00
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
Not all <quote>predefined</quote> functions are
|
|
|
|
<quote>internal</quote> in the above sense. Some predefined
|
|
|
|
functions are written in SQL.
|
|
|
|
</para>
|
|
|
|
</note>
|
1999-07-22 17:11:05 +02:00
|
|
|
</sect1>
|
|
|
|
|
2000-09-29 22:21:34 +02:00
|
|
|
<sect1 id="xfunc-c">
|
2003-04-10 03:22:45 +02:00
|
|
|
<title>C-Language Functions</title>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2005-04-01 00:46:33 +02:00
|
|
|
<indexterm zone="xfunc-c">
|
2003-08-31 19:32:24 +02:00
|
|
|
<primary>function</primary>
|
|
|
|
<secondary>user-defined</secondary>
|
|
|
|
<tertiary>in C</tertiary>
|
|
|
|
</indexterm>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2001-05-19 11:01:10 +02:00
|
|
|
User-defined functions can be written in C (or a language that can
|
|
|
|
be made compatible with C, such as C++). Such functions are
|
|
|
|
compiled into dynamically loadable objects (also called shared
|
2001-10-26 21:58:12 +02:00
|
|
|
libraries) and are loaded by the server on demand. The dynamic
|
|
|
|
loading feature is what distinguishes <quote>C language</> functions
|
2004-11-15 07:32:15 +01:00
|
|
|
from <quote>internal</> functions — the actual coding conventions
|
2001-10-26 21:58:12 +02:00
|
|
|
are essentially the same for both. (Hence, the standard internal
|
|
|
|
function library is a rich source of coding examples for user-defined
|
|
|
|
C functions.)
|
2001-05-19 11:01:10 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Two different calling conventions are currently used for C functions.
|
2001-09-13 17:55:24 +02:00
|
|
|
The newer <quote>version 1</quote> calling convention is indicated by writing
|
2001-05-19 11:01:10 +02:00
|
|
|
a <literal>PG_FUNCTION_INFO_V1()</literal> macro call for the function,
|
|
|
|
as illustrated below. Lack of such a macro indicates an old-style
|
2003-02-19 05:06:28 +01:00
|
|
|
(<quote>version 0</quote>) function. The language name specified in <command>CREATE FUNCTION</command>
|
2001-09-13 17:55:24 +02:00
|
|
|
is <literal>C</literal> in either case. Old-style functions are now deprecated
|
2001-05-19 11:01:10 +02:00
|
|
|
because of portability problems and lack of functionality, but they
|
|
|
|
are still supported for compatibility reasons.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<sect2 id="xfunc-c-dynload">
|
|
|
|
<title>Dynamic Loading</title>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>dynamic loading</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2001-05-19 11:01:10 +02:00
|
|
|
<para>
|
|
|
|
The first time a user-defined function in a particular
|
2003-04-10 03:22:45 +02:00
|
|
|
loadable object file is called in a session,
|
2000-08-25 01:36:29 +02:00
|
|
|
the dynamic loader loads that object file into memory so that the
|
|
|
|
function can be called. The <command>CREATE FUNCTION</command>
|
2001-05-19 11:01:10 +02:00
|
|
|
for a user-defined C function must therefore specify two pieces of
|
2000-08-25 01:36:29 +02:00
|
|
|
information for the function: the name of the loadable
|
|
|
|
object file, and the C name (link symbol) of the specific function to call
|
|
|
|
within that object file. If the C name is not explicitly specified then
|
|
|
|
it is assumed to be the same as the SQL function name.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-05-19 11:01:10 +02:00
|
|
|
The following algorithm is used to locate the shared object file
|
|
|
|
based on the name given in the <command>CREATE FUNCTION</command>
|
|
|
|
command:
|
|
|
|
|
|
|
|
<orderedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
If the name is an absolute path, the given file is loaded.
|
2001-05-19 11:01:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
If the name starts with the string <literal>$libdir</literal>,
|
2001-11-21 07:09:45 +01:00
|
|
|
that part is replaced by the <productname>PostgreSQL</> package
|
2004-12-30 04:13:56 +01:00
|
|
|
library directory
|
2001-11-12 20:19:39 +01:00
|
|
|
name, which is determined at build time.<indexterm><primary>$libdir</></>
|
2001-05-19 11:01:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
If the name does not contain a directory part, the file is
|
2001-10-26 21:58:12 +02:00
|
|
|
searched for in the path specified by the configuration variable
|
2004-03-09 17:57:47 +01:00
|
|
|
<xref linkend="guc-dynamic-library-path">.<indexterm><primary>dynamic_library_path</></>
|
2001-05-19 11:01:10 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Otherwise (the file was not found in the path, or it contains a
|
|
|
|
non-absolute directory part), the dynamic loader will try to
|
|
|
|
take the name as given, which will most likely fail. (It is
|
|
|
|
unreliable to depend on the current working directory.)
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</orderedlist>
|
|
|
|
|
|
|
|
If this sequence does not work, the platform-specific shared
|
|
|
|
library file name extension (often <filename>.so</filename>) is
|
|
|
|
appended to the given name and this sequence is tried again. If
|
|
|
|
that fails as well, the load will fail.
|
|
|
|
</para>
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2006-08-08 21:15:09 +02:00
|
|
|
<para>
|
|
|
|
It is recommended to locate shared libraries either relative to
|
|
|
|
<literal>$libdir</literal> or through the dynamic library path.
|
|
|
|
This simplifies version upgrades if the new installation is at a
|
|
|
|
different location. The actual directory that
|
|
|
|
<literal>$libdir</literal> stands for can be found out with the
|
|
|
|
command <literal>pg_config --pkglibdir</literal>.
|
|
|
|
</para>
|
|
|
|
|
2003-11-12 23:47:47 +01:00
|
|
|
<para>
|
|
|
|
The user ID the <productname>PostgreSQL</productname> server runs
|
|
|
|
as must be able to traverse the path to the file you intend to
|
|
|
|
load. Making the file or a higher-level directory not readable
|
|
|
|
and/or not executable by the <systemitem>postgres</systemitem>
|
|
|
|
user is a common mistake.
|
|
|
|
</para>
|
2001-05-19 11:01:10 +02:00
|
|
|
|
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
In any case, the file name that is given in the
|
2001-05-19 11:01:10 +02:00
|
|
|
<command>CREATE FUNCTION</command> command is recorded literally
|
|
|
|
in the system catalogs, so if the file needs to be loaded again
|
|
|
|
the same procedure is applied.
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
2001-10-26 21:58:12 +02:00
|
|
|
<note>
|
|
|
|
<para>
|
2002-11-15 04:11:18 +01:00
|
|
|
<productname>PostgreSQL</productname> will not compile a C function
|
2001-10-26 21:58:12 +02:00
|
|
|
automatically. The object file must be compiled before it is referenced
|
|
|
|
in a <command>CREATE
|
|
|
|
FUNCTION</> command. See <xref linkend="dfunc"> for additional
|
|
|
|
information.
|
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
|
2006-08-08 21:15:09 +02:00
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>magic block</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
To ensure that a dynamically loaded object file is not loaded into an
|
|
|
|
incompatible server, <productname>PostgreSQL</productname> checks that the
|
|
|
|
file contains a <quote>magic block</> with the appropriate contents.
|
|
|
|
This allows the server to detect obvious incompatibilities, such as code
|
|
|
|
compiled for a different major version of
|
|
|
|
<productname>PostgreSQL</productname>. A magic block is required as of
|
|
|
|
<productname>PostgreSQL</productname> 8.2. To include a magic block,
|
|
|
|
write this in one (and only one) of the module source files, after having
|
|
|
|
included the header <filename>fmgr.h</>:
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
#ifdef PG_MODULE_MAGIC
|
|
|
|
PG_MODULE_MAGIC;
|
|
|
|
#endif
|
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
The <literal>#ifdef</> test can be omitted if the code doesn't
|
|
|
|
need to compile against pre-8.2 <productname>PostgreSQL</productname>
|
|
|
|
releases.
|
|
|
|
</para>
|
|
|
|
|
2003-11-12 23:47:47 +01:00
|
|
|
<para>
|
|
|
|
After it is used for the first time, a dynamically loaded object
|
|
|
|
file is retained in memory. Future calls in the same session to
|
|
|
|
the function(s) in that file will only incur the small overhead of
|
|
|
|
a symbol table lookup. If you need to force a reload of an object
|
2009-09-04 00:11:07 +02:00
|
|
|
file, for example after recompiling it, begin a fresh session.
|
2003-11-12 23:47:47 +01:00
|
|
|
</para>
|
2001-10-26 21:58:12 +02:00
|
|
|
|
2006-08-08 21:15:09 +02:00
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>_PG_init</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>_PG_fini</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>library initialization function</primary>
|
|
|
|
</indexterm>
|
|
|
|
<indexterm zone="xfunc-c-dynload">
|
|
|
|
<primary>library finalization function</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
<para>
|
2006-08-08 21:15:09 +02:00
|
|
|
Optionally, a dynamically loaded file can contain initialization and
|
|
|
|
finalization functions. If the file includes a function named
|
2006-11-23 06:28:18 +01:00
|
|
|
<function>_PG_init</>, that function will be called immediately after
|
2006-08-08 21:15:09 +02:00
|
|
|
loading the file. The function receives no parameters and should
|
|
|
|
return void. If the file includes a function named
|
2006-11-23 06:28:18 +01:00
|
|
|
<function>_PG_fini</>, that function will be called immediately before
|
2006-08-08 21:15:09 +02:00
|
|
|
unloading the file. Likewise, the function receives no parameters and
|
2006-11-23 06:28:18 +01:00
|
|
|
should return void. Note that <function>_PG_fini</> will only be called
|
2006-08-08 21:15:09 +02:00
|
|
|
during an unload of the file, not during process termination.
|
2009-09-04 00:11:07 +02:00
|
|
|
(Presently, unloads are disabled and will never occur, but this may
|
|
|
|
change in the future.)
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
2001-05-19 11:01:10 +02:00
|
|
|
</sect2>
|
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<sect2 id="xfunc-c-basetype">
|
2000-08-25 01:36:29 +02:00
|
|
|
<title>Base Types in C-Language Functions</title>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2003-08-31 19:32:24 +02:00
|
|
|
<indexterm zone="xfunc-c-basetype">
|
|
|
|
<primary>data type</primary>
|
2005-10-15 22:12:33 +02:00
|
|
|
<secondary>internal organization</secondary>
|
2003-08-31 19:32:24 +02:00
|
|
|
</indexterm>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
To know how to write C-language functions, you need to know how
|
2003-09-11 23:42:20 +02:00
|
|
|
<productname>PostgreSQL</productname> internally represents base
|
|
|
|
data types and how they can be passed to and from functions.
|
|
|
|
Internally, <productname>PostgreSQL</productname> regards a base
|
|
|
|
type as a <quote>blob of memory</quote>. The user-defined
|
|
|
|
functions that you define over a type in turn define the way that
|
|
|
|
<productname>PostgreSQL</productname> can operate on it. That
|
|
|
|
is, <productname>PostgreSQL</productname> will only store and
|
|
|
|
retrieve the data from disk and use your user-defined functions
|
|
|
|
to input, process, and output the data.
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
1998-03-01 09:16:16 +01:00
|
|
|
Base types can have one of three internal formats:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
pass by value, fixed-length
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
pass by reference, fixed-length
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
2004-12-30 04:13:56 +01:00
|
|
|
pass by reference, variable-length
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
By-value types can only be 1, 2, or 4 bytes in length
|
2001-09-15 21:56:59 +02:00
|
|
|
(also 8 bytes, if <literal>sizeof(Datum)</literal> is 8 on your machine).
|
2008-10-31 20:37:56 +01:00
|
|
|
You should be careful to define your types such that they will be the
|
|
|
|
same size (in bytes) on all architectures. For example, the
|
|
|
|
<literal>long</literal> type is dangerous because it is 4 bytes on some
|
|
|
|
machines and 8 bytes on others, whereas <type>int</type> type is 4 bytes
|
|
|
|
on most Unix machines. A reasonable implementation of the
|
|
|
|
<type>int4</type> type on Unix machines might be:
|
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
/* 4-byte integer, passed by value */
|
|
|
|
typedef int int4;
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
On the other hand, fixed-length types of any size can
|
1998-03-01 09:16:16 +01:00
|
|
|
be passed by-reference. For example, here is a sample
|
2001-09-15 21:56:59 +02:00
|
|
|
implementation of a <productname>PostgreSQL</productname> type:
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
/* 16-byte structure, passed by reference */
|
|
|
|
typedef struct
|
|
|
|
{
|
|
|
|
double x, y;
|
|
|
|
} Point;
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
1998-03-01 09:16:16 +01:00
|
|
|
Only pointers to such types can be used when passing
|
2001-11-21 07:09:45 +01:00
|
|
|
them in and out of <productname>PostgreSQL</productname> functions.
|
2000-08-25 01:36:29 +02:00
|
|
|
To return a value of such a type, allocate the right amount of
|
2003-04-10 03:22:45 +02:00
|
|
|
memory with <literal>palloc</literal>, fill in the allocated memory,
|
2005-03-12 21:25:06 +01:00
|
|
|
and return a pointer to it. (Also, if you just want to return the
|
|
|
|
same value as one of your input arguments that's of the same data type,
|
|
|
|
you can skip the extra <literal>palloc</literal> and just return the
|
|
|
|
pointer to the input value.)
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
1998-03-01 09:16:16 +01:00
|
|
|
Finally, all variable-length types must also be passed
|
|
|
|
by reference. All variable-length types must begin
|
|
|
|
with a length field of exactly 4 bytes, and all data to
|
2008-10-31 20:37:56 +01:00
|
|
|
be stored within that type must be located in the memory
|
1998-03-01 09:16:16 +01:00
|
|
|
immediately following that length field. The
|
2003-04-10 03:22:45 +02:00
|
|
|
length field contains the total length of the structure,
|
|
|
|
that is, it includes the size of the length field
|
|
|
|
itself.
|
|
|
|
</para>
|
|
|
|
|
2005-03-12 21:25:06 +01:00
|
|
|
<warning>
|
|
|
|
<para>
|
|
|
|
<emphasis>Never</> modify the contents of a pass-by-reference input
|
|
|
|
value. If you do so you are likely to corrupt on-disk data, since
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
the pointer you are given might point directly into a disk buffer.
|
2005-03-12 21:25:06 +01:00
|
|
|
The sole exception to this rule is explained in
|
|
|
|
<xref linkend="xaggr">.
|
|
|
|
</para>
|
|
|
|
</warning>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<para>
|
|
|
|
As an example, we can define the type <type>text</type> as
|
|
|
|
follows:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
typedef struct {
|
|
|
|
int4 length;
|
|
|
|
char data[1];
|
|
|
|
} text;
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-11-14 23:14:22 +01:00
|
|
|
Obviously, the data field declared here is not long enough to hold
|
|
|
|
all possible strings. Since it's impossible to declare a variable-size
|
|
|
|
structure in <acronym>C</acronym>, we rely on the knowledge that the
|
|
|
|
<acronym>C</acronym> compiler won't range-check array subscripts. We
|
|
|
|
just allocate the necessary amount of space and then access the array as
|
2003-04-10 03:22:45 +02:00
|
|
|
if it were declared the right length. (This is a common trick, which
|
|
|
|
you can read about in many textbooks about C.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2008-10-31 20:37:56 +01:00
|
|
|
When manipulating
|
|
|
|
variable-length types, we must be careful to allocate
|
2001-11-14 23:14:22 +01:00
|
|
|
the correct amount of memory and set the length field correctly.
|
2003-04-10 03:22:45 +02:00
|
|
|
For example, if we wanted to store 40 bytes in a <structname>text</>
|
1998-03-01 09:16:16 +01:00
|
|
|
structure, we might use a code fragment like this:
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
1999-07-22 17:11:05 +02:00
|
|
|
#include "postgres.h"
|
|
|
|
...
|
|
|
|
char buffer[40]; /* our source data */
|
|
|
|
...
|
|
|
|
text *destination = (text *) palloc(VARHDRSZ + 40);
|
2008-12-08 00:46:39 +01:00
|
|
|
destination->length = VARHDRSZ + 40;
|
|
|
|
memcpy(destination->data, buffer, 40);
|
1999-07-22 17:11:05 +02:00
|
|
|
...
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
2001-11-14 23:14:22 +01:00
|
|
|
|
|
|
|
<literal>VARHDRSZ</> is the same as <literal>sizeof(int4)</>, but
|
|
|
|
it's considered good style to use the macro <literal>VARHDRSZ</>
|
|
|
|
to refer to the size of the overhead for a variable-length type.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<para>
|
|
|
|
<xref linkend="xfunc-c-type-table"> specifies which C type
|
|
|
|
corresponds to which SQL type when writing a C-language function
|
|
|
|
that uses a built-in type of <productname>PostgreSQL</>.
|
|
|
|
The <quote>Defined In</quote> column gives the header file that
|
|
|
|
needs to be included to get the type definition. (The actual
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
definition might be in a different file that is included by the
|
2003-04-10 03:22:45 +02:00
|
|
|
listed file. It is recommended that users stick to the defined
|
|
|
|
interface.) Note that you should always include
|
|
|
|
<filename>postgres.h</filename> first in any source file, because
|
|
|
|
it declares a number of things that you will need anyway.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<table tocentry="1" id="xfunc-c-type-table">
|
2011-02-01 23:00:26 +01:00
|
|
|
<title>Equivalent C Types for Built-in SQL Types</title>
|
2003-04-10 03:22:45 +02:00
|
|
|
<tgroup cols="3">
|
|
|
|
<thead>
|
2004-12-30 04:13:56 +01:00
|
|
|
<row>
|
|
|
|
<entry>
|
|
|
|
SQL Type
|
|
|
|
</entry>
|
|
|
|
<entry>
|
|
|
|
C Type
|
|
|
|
</entry>
|
|
|
|
<entry>
|
|
|
|
Defined In
|
|
|
|
</entry>
|
|
|
|
</row>
|
2003-04-10 03:22:45 +02:00
|
|
|
</thead>
|
|
|
|
<tbody>
|
2004-12-30 04:13:56 +01:00
|
|
|
<row>
|
|
|
|
<entry><type>abstime</type></entry>
|
|
|
|
<entry><type>AbsoluteTime</type></entry>
|
|
|
|
<entry><filename>utils/nabstime.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>boolean</type></entry>
|
|
|
|
<entry><type>bool</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename> (maybe compiler built-in)</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>box</type></entry>
|
|
|
|
<entry><type>BOX*</type></entry>
|
|
|
|
<entry><filename>utils/geo_decls.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>bytea</type></entry>
|
|
|
|
<entry><type>bytea*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>"char"</type></entry>
|
|
|
|
<entry><type>char</type></entry>
|
|
|
|
<entry>(compiler built-in)</entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>character</type></entry>
|
|
|
|
<entry><type>BpChar*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>cid</type></entry>
|
|
|
|
<entry><type>CommandId</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>date</type></entry>
|
|
|
|
<entry><type>DateADT</type></entry>
|
|
|
|
<entry><filename>utils/date.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>smallint</type> (<type>int2</type>)</entry>
|
|
|
|
<entry><type>int2</type> or <type>int16</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>int2vector</type></entry>
|
|
|
|
<entry><type>int2vector*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>integer</type> (<type>int4</type>)</entry>
|
|
|
|
<entry><type>int4</type> or <type>int32</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>real</type> (<type>float4</type>)</entry>
|
|
|
|
<entry><type>float4*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>double precision</type> (<type>float8</type>)</entry>
|
|
|
|
<entry><type>float8*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>interval</type></entry>
|
|
|
|
<entry><type>Interval*</type></entry>
|
|
|
|
<entry><filename>utils/timestamp.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>lseg</type></entry>
|
|
|
|
<entry><type>LSEG*</type></entry>
|
|
|
|
<entry><filename>utils/geo_decls.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>name</type></entry>
|
|
|
|
<entry><type>Name</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>oid</type></entry>
|
|
|
|
<entry><type>Oid</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>oidvector</type></entry>
|
|
|
|
<entry><type>oidvector*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>path</type></entry>
|
|
|
|
<entry><type>PATH*</type></entry>
|
|
|
|
<entry><filename>utils/geo_decls.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>point</type></entry>
|
|
|
|
<entry><type>POINT*</type></entry>
|
|
|
|
<entry><filename>utils/geo_decls.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>regproc</type></entry>
|
|
|
|
<entry><type>regproc</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>reltime</type></entry>
|
|
|
|
<entry><type>RelativeTime</type></entry>
|
|
|
|
<entry><filename>utils/nabstime.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>text</type></entry>
|
|
|
|
<entry><type>text*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>tid</type></entry>
|
|
|
|
<entry><type>ItemPointer</type></entry>
|
|
|
|
<entry><filename>storage/itemptr.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>time</type></entry>
|
|
|
|
<entry><type>TimeADT</type></entry>
|
|
|
|
<entry><filename>utils/date.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>time with time zone</type></entry>
|
|
|
|
<entry><type>TimeTzADT</type></entry>
|
|
|
|
<entry><filename>utils/date.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>timestamp</type></entry>
|
|
|
|
<entry><type>Timestamp*</type></entry>
|
|
|
|
<entry><filename>utils/timestamp.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>tinterval</type></entry>
|
|
|
|
<entry><type>TimeInterval</type></entry>
|
|
|
|
<entry><filename>utils/nabstime.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>varchar</type></entry>
|
|
|
|
<entry><type>VarChar*</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
|
|
|
<row>
|
|
|
|
<entry><type>xid</type></entry>
|
|
|
|
<entry><type>TransactionId</type></entry>
|
|
|
|
<entry><filename>postgres.h</filename></entry>
|
|
|
|
</row>
|
2003-04-10 03:22:45 +02:00
|
|
|
</tbody>
|
|
|
|
</tgroup>
|
|
|
|
</table>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
1998-03-01 09:16:16 +01:00
|
|
|
Now that we've gone over all of the possible structures
|
2000-08-25 01:36:29 +02:00
|
|
|
for base types, we can show some examples of real functions.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2>
|
2006-11-23 06:43:32 +01:00
|
|
|
<title>Version 0 Calling Conventions</title>
|
2000-08-25 01:36:29 +02:00
|
|
|
|
|
|
|
<para>
|
2004-11-15 07:32:15 +01:00
|
|
|
We present the <quote>old style</quote> calling convention first — although
|
2000-08-25 01:36:29 +02:00
|
|
|
this approach is now deprecated, it's easier to get a handle on
|
2000-11-20 21:36:57 +01:00
|
|
|
initially. In the version-0 method, the arguments and result
|
2000-08-25 01:36:29 +02:00
|
|
|
of the C function are just declared in normal C style, but being
|
|
|
|
careful to use the C representation of each SQL data type as shown
|
|
|
|
above.
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Here are some examples:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2000-05-02 22:02:03 +02:00
|
|
|
#include "postgres.h"
|
2008-12-08 00:46:39 +01:00
|
|
|
#include <string.h>
|
2009-11-23 22:41:20 +01:00
|
|
|
#include "utils/geo_decls.h"
|
|
|
|
|
|
|
|
#ifdef PG_MODULE_MAGIC
|
|
|
|
PG_MODULE_MAGIC;
|
|
|
|
#endif
|
1999-03-14 16:24:15 +01:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* by value */
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
int
|
|
|
|
add_one(int arg)
|
|
|
|
{
|
2000-08-25 01:36:29 +02:00
|
|
|
return arg + 1;
|
2000-05-02 22:02:03 +02:00
|
|
|
}
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* by reference, fixed length */
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
float8 *
|
|
|
|
add_one_float8(float8 *arg)
|
|
|
|
{
|
|
|
|
float8 *result = (float8 *) palloc(sizeof(float8));
|
|
|
|
|
|
|
|
*result = *arg + 1.0;
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
Point *
|
2000-08-25 01:36:29 +02:00
|
|
|
makepoint(Point *pointx, Point *pointy)
|
2000-05-02 22:02:03 +02:00
|
|
|
{
|
|
|
|
Point *new_point = (Point *) palloc(sizeof(Point));
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
new_point->x = pointx->x;
|
|
|
|
new_point->y = pointy->y;
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
return new_point;
|
|
|
|
}
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* by reference, variable length */
|
2000-05-02 22:02:03 +02:00
|
|
|
|
|
|
|
text *
|
|
|
|
copytext(text *t)
|
|
|
|
{
|
|
|
|
/*
|
|
|
|
* VARSIZE is the total size of the struct in bytes.
|
|
|
|
*/
|
|
|
|
text *new_t = (text *) palloc(VARSIZE(t));
|
2007-02-28 00:48:10 +01:00
|
|
|
SET_VARSIZE(new_t, VARSIZE(t));
|
2000-05-02 22:02:03 +02:00
|
|
|
/*
|
|
|
|
* VARDATA is a pointer to the data region of the struct.
|
|
|
|
*/
|
|
|
|
memcpy((void *) VARDATA(new_t), /* destination */
|
|
|
|
(void *) VARDATA(t), /* source */
|
2006-11-23 06:43:32 +01:00
|
|
|
VARSIZE(t) - VARHDRSZ); /* how many bytes */
|
2000-08-25 01:36:29 +02:00
|
|
|
return new_t;
|
2000-05-02 22:02:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
text *
|
|
|
|
concat_text(text *arg1, text *arg2)
|
|
|
|
{
|
|
|
|
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
|
|
|
|
text *new_text = (text *) palloc(new_text_size);
|
|
|
|
|
2007-02-28 00:48:10 +01:00
|
|
|
SET_VARSIZE(new_text, new_text_size);
|
2006-11-23 06:43:32 +01:00
|
|
|
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1) - VARHDRSZ);
|
|
|
|
memcpy(VARDATA(new_text) + (VARSIZE(arg1) - VARHDRSZ),
|
|
|
|
VARDATA(arg2), VARSIZE(arg2) - VARHDRSZ);
|
2000-08-25 01:36:29 +02:00
|
|
|
return new_text;
|
2000-05-02 22:02:03 +02:00
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2000-08-25 01:36:29 +02:00
|
|
|
Supposing that the above code has been prepared in file
|
|
|
|
<filename>funcs.c</filename> and compiled into a shared object,
|
2001-11-21 07:09:45 +01:00
|
|
|
we could define the functions to <productname>PostgreSQL</productname>
|
2000-08-25 01:36:29 +02:00
|
|
|
with commands like this:
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
2003-04-10 03:22:45 +02:00
|
|
|
CREATE FUNCTION add_one(integer) RETURNS integer
|
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'add_one'
|
|
|
|
LANGUAGE C STRICT;
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
-- note overloading of SQL function name "add_one"
|
|
|
|
CREATE FUNCTION add_one(double precision) RETURNS double precision
|
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'add_one_float8'
|
|
|
|
LANGUAGE C STRICT;
|
2000-05-02 22:02:03 +02:00
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
CREATE FUNCTION makepoint(point, point) RETURNS point
|
2003-04-10 03:22:45 +02:00
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'makepoint'
|
|
|
|
LANGUAGE C STRICT;
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
CREATE FUNCTION copytext(text) RETURNS text
|
2003-04-10 03:22:45 +02:00
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'copytext'
|
|
|
|
LANGUAGE C STRICT;
|
2000-08-25 01:36:29 +02:00
|
|
|
|
|
|
|
CREATE FUNCTION concat_text(text, text) RETURNS text
|
2005-10-15 03:47:12 +02:00
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'concat_text'
|
2003-04-10 03:22:45 +02:00
|
|
|
LANGUAGE C STRICT;
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
Here, <replaceable>DIRECTORY</replaceable> stands for the
|
2003-09-11 23:42:20 +02:00
|
|
|
directory of the shared library file (for instance the
|
|
|
|
<productname>PostgreSQL</productname> tutorial directory, which
|
|
|
|
contains the code for the examples used in this section).
|
|
|
|
(Better style would be to use just <literal>'funcs'</> in the
|
|
|
|
<literal>AS</> clause, after having added
|
|
|
|
<replaceable>DIRECTORY</replaceable> to the search path. In any
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
case, we can omit the system-specific extension for a shared
|
2003-09-11 23:42:20 +02:00
|
|
|
library, commonly <literal>.so</literal> or
|
2001-10-26 21:58:12 +02:00
|
|
|
<literal>.sl</literal>.)
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-10-26 21:58:12 +02:00
|
|
|
Notice that we have specified the functions as <quote>strict</quote>,
|
|
|
|
meaning that
|
2003-04-10 03:22:45 +02:00
|
|
|
the system should automatically assume a null result if any input
|
|
|
|
value is null. By doing this, we avoid having to check for null inputs
|
2002-09-21 20:32:54 +02:00
|
|
|
in the function code. Without this, we'd have to check for null values
|
2003-04-10 03:22:45 +02:00
|
|
|
explicitly, by checking for a null pointer for each
|
2000-08-25 01:36:29 +02:00
|
|
|
pass-by-reference argument. (For pass-by-value arguments, we don't
|
|
|
|
even have a way to check!)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2000-11-20 21:36:57 +01:00
|
|
|
Although this calling convention is simple to use,
|
2000-08-25 01:36:29 +02:00
|
|
|
it is not very portable; on some architectures there are problems
|
2003-04-10 03:22:45 +02:00
|
|
|
with passing data types that are smaller than <type>int</type> this way. Also, there is
|
|
|
|
no simple way to return a null result, nor to cope with null arguments
|
2000-11-20 21:36:57 +01:00
|
|
|
in any way other than making the function strict. The version-1
|
2000-08-25 01:36:29 +02:00
|
|
|
convention, presented next, overcomes these objections.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<sect2>
|
2006-11-23 06:43:32 +01:00
|
|
|
<title>Version 1 Calling Conventions</title>
|
2000-08-25 01:36:29 +02:00
|
|
|
|
|
|
|
<para>
|
2000-11-20 21:36:57 +01:00
|
|
|
The version-1 calling convention relies on macros to suppress most
|
2000-08-25 01:36:29 +02:00
|
|
|
of the complexity of passing arguments and results. The C declaration
|
2007-02-01 01:28:19 +01:00
|
|
|
of a version-1 function is always:
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
|
|
|
Datum funcname(PG_FUNCTION_ARGS)
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
In addition, the macro call:
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
|
|
|
PG_FUNCTION_INFO_V1(funcname);
|
|
|
|
</programlisting>
|
2010-05-16 05:55:41 +02:00
|
|
|
must appear in the same source file. (Conventionally, it's
|
2003-04-10 03:22:45 +02:00
|
|
|
written just before the function itself.) This macro call is not
|
|
|
|
needed for <literal>internal</>-language functions, since
|
|
|
|
<productname>PostgreSQL</> assumes that all internal functions
|
|
|
|
use the version-1 convention. It is, however, required for
|
|
|
|
dynamically-loaded functions.
|
2000-11-20 21:36:57 +01:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-01-12 23:15:32 +01:00
|
|
|
In a version-1 function, each actual argument is fetched using a
|
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>()</function>
|
2003-04-10 03:22:45 +02:00
|
|
|
macro that corresponds to the argument's data type, and the
|
|
|
|
result is returned using a
|
2001-01-22 17:11:17 +01:00
|
|
|
<function>PG_RETURN_<replaceable>xxx</replaceable>()</function>
|
2001-01-12 23:15:32 +01:00
|
|
|
macro for the return type.
|
2003-04-10 03:22:45 +02:00
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>()</function>
|
|
|
|
takes as its argument the number of the function argument to
|
|
|
|
fetch, where the count starts at 0.
|
|
|
|
<function>PG_RETURN_<replaceable>xxx</replaceable>()</function>
|
|
|
|
takes as its argument the actual value to return.
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2001-01-22 17:11:17 +01:00
|
|
|
Here we show the same functions as above, coded in version-1 style:
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2000-08-25 01:36:29 +02:00
|
|
|
#include "postgres.h"
|
2008-12-08 00:46:39 +01:00
|
|
|
#include <string.h>
|
2000-08-25 01:36:29 +02:00
|
|
|
#include "fmgr.h"
|
2009-11-23 22:41:20 +01:00
|
|
|
#include "utils/geo_decls.h"
|
|
|
|
|
|
|
|
#ifdef PG_MODULE_MAGIC
|
|
|
|
PG_MODULE_MAGIC;
|
|
|
|
#endif
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* by value */
|
2000-11-20 21:36:57 +01:00
|
|
|
|
|
|
|
PG_FUNCTION_INFO_V1(add_one);
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
Datum
|
|
|
|
add_one(PG_FUNCTION_ARGS)
|
|
|
|
{
|
|
|
|
int32 arg = PG_GETARG_INT32(0);
|
|
|
|
|
|
|
|
PG_RETURN_INT32(arg + 1);
|
|
|
|
}
|
|
|
|
|
2005-02-21 07:12:14 +01:00
|
|
|
/* by reference, fixed length */
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(add_one_float8);
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
Datum
|
|
|
|
add_one_float8(PG_FUNCTION_ARGS)
|
|
|
|
{
|
2003-04-10 03:22:45 +02:00
|
|
|
/* The macros for FLOAT8 hide its pass-by-reference nature. */
|
2000-08-25 01:36:29 +02:00
|
|
|
float8 arg = PG_GETARG_FLOAT8(0);
|
|
|
|
|
|
|
|
PG_RETURN_FLOAT8(arg + 1.0);
|
|
|
|
}
|
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(makepoint);
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
Datum
|
|
|
|
makepoint(PG_FUNCTION_ARGS)
|
|
|
|
{
|
2003-04-10 03:22:45 +02:00
|
|
|
/* Here, the pass-by-reference nature of Point is not hidden. */
|
2000-08-25 01:36:29 +02:00
|
|
|
Point *pointx = PG_GETARG_POINT_P(0);
|
|
|
|
Point *pointy = PG_GETARG_POINT_P(1);
|
|
|
|
Point *new_point = (Point *) palloc(sizeof(Point));
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
new_point->x = pointx->x;
|
|
|
|
new_point->y = pointy->y;
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
PG_RETURN_POINT_P(new_point);
|
|
|
|
}
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* by reference, variable length */
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(copytext);
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
Datum
|
|
|
|
copytext(PG_FUNCTION_ARGS)
|
|
|
|
{
|
|
|
|
text *t = PG_GETARG_TEXT_P(0);
|
|
|
|
/*
|
|
|
|
* VARSIZE is the total size of the struct in bytes.
|
|
|
|
*/
|
|
|
|
text *new_t = (text *) palloc(VARSIZE(t));
|
2007-02-28 00:48:10 +01:00
|
|
|
SET_VARSIZE(new_t, VARSIZE(t));
|
2000-08-25 01:36:29 +02:00
|
|
|
/*
|
|
|
|
* VARDATA is a pointer to the data region of the struct.
|
|
|
|
*/
|
|
|
|
memcpy((void *) VARDATA(new_t), /* destination */
|
|
|
|
(void *) VARDATA(t), /* source */
|
2006-11-23 06:43:32 +01:00
|
|
|
VARSIZE(t) - VARHDRSZ); /* how many bytes */
|
2000-08-25 01:36:29 +02:00
|
|
|
PG_RETURN_TEXT_P(new_t);
|
|
|
|
}
|
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(concat_text);
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
Datum
|
|
|
|
concat_text(PG_FUNCTION_ARGS)
|
|
|
|
{
|
|
|
|
text *arg1 = PG_GETARG_TEXT_P(0);
|
|
|
|
text *arg2 = PG_GETARG_TEXT_P(1);
|
|
|
|
int32 new_text_size = VARSIZE(arg1) + VARSIZE(arg2) - VARHDRSZ;
|
|
|
|
text *new_text = (text *) palloc(new_text_size);
|
|
|
|
|
2007-02-28 00:48:10 +01:00
|
|
|
SET_VARSIZE(new_text, new_text_size);
|
2006-11-23 06:43:32 +01:00
|
|
|
memcpy(VARDATA(new_text), VARDATA(arg1), VARSIZE(arg1) - VARHDRSZ);
|
|
|
|
memcpy(VARDATA(new_text) + (VARSIZE(arg1) - VARHDRSZ),
|
|
|
|
VARDATA(arg2), VARSIZE(arg2) - VARHDRSZ);
|
2000-08-25 01:36:29 +02:00
|
|
|
PG_RETURN_TEXT_P(new_text);
|
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The <command>CREATE FUNCTION</command> commands are the same as
|
2001-01-22 17:11:17 +01:00
|
|
|
for the version-0 equivalents.
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
At first glance, the version-1 coding conventions might appear to
|
2003-04-10 03:22:45 +02:00
|
|
|
be just pointless obscurantism. They do, however, offer a number
|
2001-01-12 23:15:32 +01:00
|
|
|
of improvements, because the macros can hide unnecessary detail.
|
2002-01-07 03:29:15 +01:00
|
|
|
An example is that in coding <function>add_one_float8</>, we no longer need to
|
|
|
|
be aware that <type>float8</type> is a pass-by-reference type. Another
|
2003-04-10 03:22:45 +02:00
|
|
|
example is that the <literal>GETARG</> macros for variable-length types allow
|
|
|
|
for more efficient fetching of <quote>toasted</quote> (compressed or
|
|
|
|
out-of-line) values.
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
One big improvement in version-1 functions is better handling of null
|
2002-01-07 03:29:15 +01:00
|
|
|
inputs and results. The macro <function>PG_ARGISNULL(<replaceable>n</>)</function>
|
2003-04-10 03:22:45 +02:00
|
|
|
allows a function to test whether each input is null. (Of course, doing
|
|
|
|
this is only necessary in functions not declared <quote>strict</>.)
|
2001-02-15 20:03:35 +01:00
|
|
|
As with the
|
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>()</function> macros,
|
2001-10-26 21:58:12 +02:00
|
|
|
the input arguments are counted beginning at zero. Note that one
|
|
|
|
should refrain from executing
|
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>()</function> until
|
2003-04-10 03:22:45 +02:00
|
|
|
one has verified that the argument isn't null.
|
|
|
|
To return a null result, execute <function>PG_RETURN_NULL()</function>;
|
2002-01-07 03:29:15 +01:00
|
|
|
this works in both strict and nonstrict functions.
|
2001-02-15 20:03:35 +01:00
|
|
|
</para>
|
|
|
|
|
2002-03-05 06:33:31 +01:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
Other options provided in the new-style interface are two
|
2002-03-05 06:33:31 +01:00
|
|
|
variants of the
|
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>()</function>
|
|
|
|
macros. The first of these,
|
2003-04-10 03:22:45 +02:00
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>_COPY()</function>,
|
|
|
|
guarantees to return a copy of the specified argument that is
|
2002-03-05 06:33:31 +01:00
|
|
|
safe for writing into. (The normal macros will sometimes return a
|
2003-04-10 03:22:45 +02:00
|
|
|
pointer to a value that is physically stored in a table, which
|
2002-08-29 02:17:06 +02:00
|
|
|
must not be written to. Using the
|
2002-03-05 06:33:31 +01:00
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>_COPY()</function>
|
|
|
|
macros guarantees a writable result.)
|
|
|
|
The second variant consists of the
|
|
|
|
<function>PG_GETARG_<replaceable>xxx</replaceable>_SLICE()</function>
|
2003-04-10 03:22:45 +02:00
|
|
|
macros which take three arguments. The first is the number of the
|
|
|
|
function argument (as above). The second and third are the offset and
|
2002-03-05 06:33:31 +01:00
|
|
|
length of the segment to be returned. Offsets are counted from
|
|
|
|
zero, and a negative length requests that the remainder of the
|
2003-04-10 03:22:45 +02:00
|
|
|
value be returned. These macros provide more efficient access to
|
2002-03-05 06:33:31 +01:00
|
|
|
parts of large values in the case where they have storage type
|
2003-02-19 05:06:28 +01:00
|
|
|
<quote>external</quote>. (The storage type of a column can be specified using
|
2002-03-11 06:03:52 +01:00
|
|
|
<literal>ALTER TABLE <replaceable>tablename</replaceable> ALTER
|
2002-03-05 06:33:31 +01:00
|
|
|
COLUMN <replaceable>colname</replaceable> SET STORAGE
|
2003-04-10 03:22:45 +02:00
|
|
|
<replaceable>storagetype</replaceable></literal>. <replaceable>storagetype</replaceable> is one of
|
2002-03-11 06:03:52 +01:00
|
|
|
<literal>plain</>, <literal>external</>, <literal>extended</literal>,
|
|
|
|
or <literal>main</>.)
|
2002-03-05 06:33:31 +01:00
|
|
|
</para>
|
|
|
|
|
2001-02-15 20:03:35 +01:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
Finally, the version-1 function call conventions make it possible
|
|
|
|
to return set results (<xref linkend="xfunc-c-return-set">) and
|
|
|
|
implement trigger functions (<xref linkend="triggers">) and
|
|
|
|
procedural-language call handlers (<xref
|
2003-10-23 00:28:10 +02:00
|
|
|
linkend="plhandler">). Version-1 code is also more
|
2003-04-10 03:22:45 +02:00
|
|
|
portable than version-0, because it does not break restrictions
|
|
|
|
on function call protocol in the C standard. For more details
|
|
|
|
see <filename>src/backend/utils/fmgr/README</filename> in the
|
|
|
|
source distribution.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2>
|
|
|
|
<title>Writing Code</title>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Before we turn to the more advanced topics, we should discuss
|
2003-09-11 23:42:20 +02:00
|
|
|
some coding rules for <productname>PostgreSQL</productname>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
C-language functions. While it might be possible to load functions
|
2003-09-11 23:42:20 +02:00
|
|
|
written in languages other than C into
|
|
|
|
<productname>PostgreSQL</productname>, this is usually difficult
|
|
|
|
(when it is possible at all) because other languages, such as
|
|
|
|
C++, FORTRAN, or Pascal often do not follow the same calling
|
|
|
|
convention as C. That is, other languages do not pass argument
|
|
|
|
and return values between functions in the same way. For this
|
|
|
|
reason, we will assume that your C-language functions are
|
|
|
|
actually written in C.
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The basic rules for writing and building C functions are as follows:
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Use <literal>pg_config
|
2003-08-31 19:32:24 +02:00
|
|
|
--includedir-server</literal><indexterm><primary>pg_config</><secondary>with user-defined C functions</></>
|
2003-04-10 03:22:45 +02:00
|
|
|
to find out where the <productname>PostgreSQL</> server header
|
|
|
|
files are installed on your system (or the system that your
|
2006-04-23 05:39:52 +02:00
|
|
|
users will be running on).
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2006-05-31 22:58:09 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Compiling and linking your code so that it can be dynamically
|
|
|
|
loaded into <productname>PostgreSQL</productname> always
|
|
|
|
requires special flags. See <xref linkend="dfunc"> for a
|
|
|
|
detailed explanation of how to do it for your particular
|
|
|
|
operating system.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2006-08-08 21:15:09 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Remember to define a <quote>magic block</> for your shared library,
|
|
|
|
as described in <xref linkend="xfunc-c-dynload">.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
When allocating memory, use the
|
|
|
|
<productname>PostgreSQL</productname> functions
|
2003-08-31 19:32:24 +02:00
|
|
|
<function>palloc</function><indexterm><primary>palloc</></> and <function>pfree</function><indexterm><primary>pfree</></>
|
2003-04-10 03:22:45 +02:00
|
|
|
instead of the corresponding C library functions
|
|
|
|
<function>malloc</function> and <function>free</function>.
|
|
|
|
The memory allocated by <function>palloc</function> will be
|
|
|
|
freed automatically at the end of each transaction, preventing
|
|
|
|
memory leaks.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Always zero the bytes of your structures using
|
2004-12-30 04:13:56 +01:00
|
|
|
<function>memset</function>. Without this, it's difficult to
|
|
|
|
support hash indexes or hash joins, as you must pick out only
|
|
|
|
the significant bits of your data structure to compute a hash.
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
Even if you initialize all fields of your structure, there might be
|
|
|
|
alignment padding (holes in the structure) that contain
|
2003-04-10 03:22:45 +02:00
|
|
|
garbage values.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Most of the internal <productname>PostgreSQL</productname>
|
|
|
|
types are declared in <filename>postgres.h</filename>, while
|
|
|
|
the function manager interfaces
|
|
|
|
(<symbol>PG_FUNCTION_ARGS</symbol>, etc.) are in
|
|
|
|
<filename>fmgr.h</filename>, so you will need to include at
|
|
|
|
least these two files. For portability reasons it's best to
|
|
|
|
include <filename>postgres.h</filename> <emphasis>first</>,
|
|
|
|
before any other system or user header files. Including
|
|
|
|
<filename>postgres.h</filename> will also include
|
|
|
|
<filename>elog.h</filename> and <filename>palloc.h</filename>
|
|
|
|
for you.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
|
2006-05-30 16:09:32 +02:00
|
|
|
<listitem>
|
|
|
|
<para>
|
2006-05-30 23:21:30 +02:00
|
|
|
Symbol names defined within object files must not conflict
|
|
|
|
with each other or with symbols defined in the
|
|
|
|
<productname>PostgreSQL</productname> server executable. You
|
|
|
|
will have to rename your functions or variables if you get
|
|
|
|
error messages to this effect.
|
2006-05-30 16:09:32 +02:00
|
|
|
</para>
|
2006-05-30 23:21:30 +02:00
|
|
|
</listitem>
|
2003-04-10 03:22:45 +02:00
|
|
|
</itemizedlist>
|
2000-08-25 01:36:29 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
&dfunc;
|
|
|
|
|
2000-08-25 01:36:29 +02:00
|
|
|
<sect2>
|
2011-02-01 23:00:26 +01:00
|
|
|
<title>Composite-type Arguments</title>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2004-08-24 02:06:51 +02:00
|
|
|
Composite types do not have a fixed layout like C structures.
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
Instances of a composite type can contain null fields. In
|
2004-08-24 02:06:51 +02:00
|
|
|
addition, composite types that are part of an inheritance
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
hierarchy can have different fields than other members of the
|
2004-08-24 02:06:51 +02:00
|
|
|
same inheritance hierarchy. Therefore,
|
|
|
|
<productname>PostgreSQL</productname> provides a function
|
|
|
|
interface for accessing fields of composite types from C.
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
Suppose we want to write a function to answer the query:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
|
|
|
SELECT name, c_overpaid(emp, 1500) AS overpaid
|
2003-04-10 03:22:45 +02:00
|
|
|
FROM emp
|
|
|
|
WHERE name = 'Bill' OR name = 'Sam';
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
Using call conventions version 0, we can define
|
|
|
|
<function>c_overpaid</> as:
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2000-05-02 22:02:03 +02:00
|
|
|
#include "postgres.h"
|
|
|
|
#include "executor/executor.h" /* for GetAttributeByName() */
|
|
|
|
|
2009-11-23 22:41:20 +01:00
|
|
|
#ifdef PG_MODULE_MAGIC
|
|
|
|
PG_MODULE_MAGIC;
|
|
|
|
#endif
|
|
|
|
|
2000-05-02 22:02:03 +02:00
|
|
|
bool
|
2004-04-01 23:28:47 +02:00
|
|
|
c_overpaid(HeapTupleHeader t, /* the current row of emp */
|
2000-08-25 01:36:29 +02:00
|
|
|
int32 limit)
|
2000-05-02 22:02:03 +02:00
|
|
|
{
|
2000-08-25 01:36:29 +02:00
|
|
|
bool isnull;
|
|
|
|
int32 salary;
|
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
|
2000-05-02 22:02:03 +02:00
|
|
|
if (isnull)
|
2003-04-10 03:22:45 +02:00
|
|
|
return false;
|
2008-12-08 00:46:39 +01:00
|
|
|
return salary > limit;
|
2000-08-25 01:36:29 +02:00
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2003-04-10 03:22:45 +02:00
|
|
|
</programlisting>
|
|
|
|
|
|
|
|
In version-1 coding, the above would look like this:
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2003-04-10 03:22:45 +02:00
|
|
|
#include "postgres.h"
|
|
|
|
#include "executor/executor.h" /* for GetAttributeByName() */
|
2000-11-20 21:36:57 +01:00
|
|
|
|
2009-11-23 22:41:20 +01:00
|
|
|
#ifdef PG_MODULE_MAGIC
|
|
|
|
PG_MODULE_MAGIC;
|
|
|
|
#endif
|
|
|
|
|
2000-11-20 21:36:57 +01:00
|
|
|
PG_FUNCTION_INFO_V1(c_overpaid);
|
2000-08-25 01:36:29 +02:00
|
|
|
|
|
|
|
Datum
|
|
|
|
c_overpaid(PG_FUNCTION_ARGS)
|
|
|
|
{
|
2004-04-01 23:28:47 +02:00
|
|
|
HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
|
2000-08-25 01:36:29 +02:00
|
|
|
int32 limit = PG_GETARG_INT32(1);
|
|
|
|
bool isnull;
|
2004-12-30 04:13:56 +01:00
|
|
|
Datum salary;
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
salary = GetAttributeByName(t, "salary", &isnull);
|
2000-08-25 01:36:29 +02:00
|
|
|
if (isnull)
|
|
|
|
PG_RETURN_BOOL(false);
|
2003-04-10 03:22:45 +02:00
|
|
|
/* Alternatively, we might prefer to do PG_RETURN_NULL() for null salary. */
|
2000-08-25 01:36:29 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
PG_RETURN_BOOL(DatumGetInt32(salary) > limit);
|
2000-05-02 22:02:03 +02:00
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2008-10-31 20:37:56 +01:00
|
|
|
<function>GetAttributeByName</function> is the
|
2001-11-21 07:09:45 +01:00
|
|
|
<productname>PostgreSQL</productname> system function that
|
2003-04-10 03:22:45 +02:00
|
|
|
returns attributes out of the specified row. It has
|
2004-04-01 23:28:47 +02:00
|
|
|
three arguments: the argument of type <type>HeapTupleHeader</type> passed
|
2008-10-31 20:37:56 +01:00
|
|
|
into
|
1998-03-01 09:16:16 +01:00
|
|
|
the function, the name of the desired attribute, and a
|
2000-08-25 01:36:29 +02:00
|
|
|
return parameter that tells whether the attribute
|
2002-01-07 03:29:15 +01:00
|
|
|
is null. <function>GetAttributeByName</function> returns a <type>Datum</type>
|
|
|
|
value that you can convert to the proper data type by using the
|
2004-12-30 04:13:56 +01:00
|
|
|
appropriate <function>DatumGet<replaceable>XXX</replaceable>()</function>
|
|
|
|
macro. Note that the return value is meaningless if the null flag is
|
|
|
|
set; always check the null flag before trying to do anything with the
|
|
|
|
result.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
2004-04-01 23:28:47 +02:00
|
|
|
<para>
|
|
|
|
There is also <function>GetAttributeByNum</function>, which selects
|
|
|
|
the target attribute by column number instead of name.
|
|
|
|
</para>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
The following command declares the function
|
|
|
|
<function>c_overpaid</function> in SQL:
|
1999-07-22 17:11:05 +02:00
|
|
|
|
2001-01-12 23:15:32 +01:00
|
|
|
<programlisting>
|
2003-11-12 23:47:47 +01:00
|
|
|
CREATE FUNCTION c_overpaid(emp, integer) RETURNS boolean
|
2003-04-10 03:22:45 +02:00
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'c_overpaid'
|
2004-04-01 23:28:47 +02:00
|
|
|
LANGUAGE C STRICT;
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
|
|
|
|
Notice we have used <literal>STRICT</> so that we did not have to
|
|
|
|
check whether the input arguments were NULL.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2>
|
2006-11-23 06:43:32 +01:00
|
|
|
<title>Returning Rows (Composite Types)</title>
|
2002-07-18 06:47:17 +02:00
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
To return a row or composite-type value from a C-language
|
|
|
|
function, you can use a special API that provides macros and
|
|
|
|
functions to hide most of the complexity of building composite
|
|
|
|
data types. To use this API, the source file must include:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
#include "funcapi.h"
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2004-04-01 23:28:47 +02:00
|
|
|
There are two ways you can build a composite data value (henceforth
|
|
|
|
a <quote>tuple</>): you can build it from an array of Datum values,
|
|
|
|
or from an array of C strings that can be passed to the input
|
2004-12-13 19:05:10 +01:00
|
|
|
conversion functions of the tuple's column data types. In either
|
2004-04-01 23:28:47 +02:00
|
|
|
case, you first need to obtain or construct a <structname>TupleDesc</>
|
|
|
|
descriptor for the tuple structure. When working with Datums, you
|
|
|
|
pass the <structname>TupleDesc</> to <function>BlessTupleDesc</>,
|
2005-03-16 22:38:10 +01:00
|
|
|
and then call <function>heap_form_tuple</> for each row. When working
|
2004-04-01 23:28:47 +02:00
|
|
|
with C strings, you pass the <structname>TupleDesc</> to
|
|
|
|
<function>TupleDescGetAttInMetadata</>, and then call
|
|
|
|
<function>BuildTupleFromCStrings</> for each row. In the case of a
|
|
|
|
function returning a set of tuples, the setup steps can all be done
|
|
|
|
once during the first call of the function.
|
2002-09-21 20:32:54 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2005-05-31 01:09:07 +02:00
|
|
|
Several helper functions are available for setting up the needed
|
|
|
|
<structname>TupleDesc</>. The recommended way to do this in most
|
2007-02-01 01:28:19 +01:00
|
|
|
functions returning composite values is to call:
|
2005-05-31 01:09:07 +02:00
|
|
|
<programlisting>
|
|
|
|
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo,
|
|
|
|
Oid *resultTypeId,
|
|
|
|
TupleDesc *resultTupleDesc)
|
|
|
|
</programlisting>
|
|
|
|
passing the same <literal>fcinfo</> struct passed to the calling function
|
|
|
|
itself. (This of course requires that you use the version-1
|
|
|
|
calling conventions.) <varname>resultTypeId</> can be specified
|
|
|
|
as <literal>NULL</> or as the address of a local variable to receive the
|
|
|
|
function's result type OID. <varname>resultTupleDesc</> should be the
|
|
|
|
address of a local <structname>TupleDesc</> variable. Check that the
|
|
|
|
result is <literal>TYPEFUNC_COMPOSITE</>; if so,
|
|
|
|
<varname>resultTupleDesc</> has been filled with the needed
|
|
|
|
<structname>TupleDesc</>. (If it is not, you can report an error along
|
|
|
|
the lines of <quote>function returning record called in context that
|
|
|
|
cannot accept type record</quote>.)
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<tip>
|
|
|
|
<para>
|
|
|
|
<function>get_call_result_type</> can resolve the actual type of a
|
|
|
|
polymorphic function result; so it is useful in functions that return
|
|
|
|
scalar polymorphic results, not only functions that return composites.
|
|
|
|
The <varname>resultTypeId</> output is primarily useful for functions
|
|
|
|
returning polymorphic scalars.
|
|
|
|
</para>
|
|
|
|
</tip>
|
|
|
|
|
|
|
|
<note>
|
|
|
|
<para>
|
|
|
|
<function>get_call_result_type</> has a sibling
|
|
|
|
<function>get_expr_result_type</>, which can be used to resolve the
|
|
|
|
expected output type for a function call represented by an expression
|
|
|
|
tree. This can be used when trying to determine the result type from
|
|
|
|
outside the function itself. There is also
|
|
|
|
<function>get_func_result_type</>, which can be used when only the
|
|
|
|
function's OID is available. However these functions are not able
|
|
|
|
to deal with functions declared to return <structname>record</>, and
|
|
|
|
<function>get_func_result_type</> cannot resolve polymorphic types,
|
|
|
|
so you should preferentially use <function>get_call_result_type</>.
|
|
|
|
</para>
|
|
|
|
</note>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Older, now-deprecated functions for obtaining
|
2007-02-01 01:28:19 +01:00
|
|
|
<structname>TupleDesc</>s are:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
2002-08-29 02:17:06 +02:00
|
|
|
TupleDesc RelationNameGetTupleDesc(const char *relname)
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2005-05-31 01:09:07 +02:00
|
|
|
to get a <structname>TupleDesc</> for the row type of a named relation,
|
2007-02-01 01:28:19 +01:00
|
|
|
and:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
TupleDesc TypeGetTupleDesc(Oid typeoid, List *colaliases)
|
|
|
|
</programlisting>
|
2002-09-21 20:32:54 +02:00
|
|
|
to get a <structname>TupleDesc</> based on a type OID. This can
|
2003-04-10 03:22:45 +02:00
|
|
|
be used to get a <structname>TupleDesc</> for a base or
|
2005-05-31 01:09:07 +02:00
|
|
|
composite type. It will not work for a function that returns
|
|
|
|
<structname>record</>, however, and it cannot resolve polymorphic
|
|
|
|
types.
|
2004-04-01 23:28:47 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
Once you have a <structname>TupleDesc</>, call:
|
2004-04-01 23:28:47 +02:00
|
|
|
<programlisting>
|
|
|
|
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
|
|
|
|
</programlisting>
|
2007-02-01 01:28:19 +01:00
|
|
|
if you plan to work with Datums, or:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
AttInMetadata *TupleDescGetAttInMetadata(TupleDesc tupdesc)
|
|
|
|
</programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
if you plan to work with C strings. If you are writing a function
|
|
|
|
returning set, you can save the results of these functions in the
|
2004-11-15 07:32:15 +01:00
|
|
|
<structname>FuncCallContext</> structure — use the
|
2004-04-01 23:28:47 +02:00
|
|
|
<structfield>tuple_desc</> or <structfield>attinmeta</> field
|
|
|
|
respectively.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
When working with Datums, use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
2005-03-16 22:38:10 +01:00
|
|
|
HeapTuple heap_form_tuple(TupleDesc tupdesc, Datum *values, bool *isnull)
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
to build a <structname>HeapTuple</> given user data in Datum form.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
When working with C strings, use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
|
|
|
|
</programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
to build a <structname>HeapTuple</> given user data
|
|
|
|
in C string form. <literal>values</literal> is an array of C strings,
|
|
|
|
one for each attribute of the return row. Each C string should be in
|
2002-09-21 20:32:54 +02:00
|
|
|
the form expected by the input function of the attribute data
|
|
|
|
type. In order to return a null value for one of the attributes,
|
|
|
|
the corresponding pointer in the <parameter>values</> array
|
|
|
|
should be set to <symbol>NULL</>. This function will need to
|
2003-04-10 03:22:45 +02:00
|
|
|
be called again for each row you return.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
2002-07-30 18:20:03 +02:00
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
Once you have built a tuple to return from your function, it
|
2007-02-01 01:28:19 +01:00
|
|
|
must be converted into a <type>Datum</>. Use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
HeapTupleGetDatum(HeapTuple tuple)
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2004-04-01 23:28:47 +02:00
|
|
|
to convert a <structname>HeapTuple</> into a valid Datum. This
|
2002-09-21 20:32:54 +02:00
|
|
|
<type>Datum</> can be returned directly if you intend to return
|
|
|
|
just a single row, or it can be used as the current return value
|
|
|
|
in a set-returning function.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
An example appears in the next section.
|
2002-08-29 02:17:06 +02:00
|
|
|
</para>
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
</sect2>
|
|
|
|
|
|
|
|
<sect2 id="xfunc-c-return-set">
|
2006-11-23 06:43:32 +01:00
|
|
|
<title>Returning Sets</title>
|
2002-08-29 02:17:06 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
<para>
|
|
|
|
There is also a special API that provides support for returning
|
|
|
|
sets (multiple rows) from a C-language function. A set-returning
|
|
|
|
function must follow the version-1 calling conventions. Also,
|
|
|
|
source files must include <filename>funcapi.h</filename>, as
|
|
|
|
above.
|
|
|
|
</para>
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
<para>
|
2003-04-10 03:22:45 +02:00
|
|
|
A set-returning function (<acronym>SRF</>) is called
|
2002-09-21 20:32:54 +02:00
|
|
|
once for each item it returns. The <acronym>SRF</> must
|
|
|
|
therefore save enough state to remember what it was doing and
|
2003-04-10 03:22:45 +02:00
|
|
|
return the next item on each call.
|
|
|
|
The structure <structname>FuncCallContext</> is provided to help
|
|
|
|
control this process. Within a function, <literal>fcinfo->flinfo->fn_extra</>
|
2002-09-21 20:32:54 +02:00
|
|
|
is used to hold a pointer to <structname>FuncCallContext</>
|
|
|
|
across calls.
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
typedef struct
|
|
|
|
{
|
2002-09-21 20:32:54 +02:00
|
|
|
/*
|
2003-04-10 03:22:45 +02:00
|
|
|
* Number of times we've been called before
|
2008-10-31 20:37:56 +01:00
|
|
|
*
|
2002-09-21 20:32:54 +02:00
|
|
|
* call_cntr is initialized to 0 for you by SRF_FIRSTCALL_INIT(), and
|
|
|
|
* incremented for you every time SRF_RETURN_NEXT() is called.
|
|
|
|
*/
|
|
|
|
uint32 call_cntr;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* OPTIONAL maximum number of calls
|
|
|
|
*
|
2003-04-10 03:22:45 +02:00
|
|
|
* max_calls is here for convenience only and setting it is optional.
|
2002-09-21 20:32:54 +02:00
|
|
|
* If not set, you must provide alternative means to know when the
|
|
|
|
* function is done.
|
|
|
|
*/
|
|
|
|
uint32 max_calls;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* OPTIONAL pointer to result slot
|
2008-10-31 20:37:56 +01:00
|
|
|
*
|
2011-03-11 20:33:10 +01:00
|
|
|
* This is obsolete and only present for backward compatibility, viz,
|
2004-04-01 23:28:47 +02:00
|
|
|
* user-defined SRFs that use the deprecated TupleDescGetSlot().
|
2002-09-21 20:32:54 +02:00
|
|
|
*/
|
|
|
|
TupleTableSlot *slot;
|
|
|
|
|
|
|
|
/*
|
2003-04-10 03:22:45 +02:00
|
|
|
* OPTIONAL pointer to miscellaneous user-provided context information
|
2008-10-31 20:37:56 +01:00
|
|
|
*
|
2003-04-10 03:22:45 +02:00
|
|
|
* user_fctx is for use as a pointer to your own data to retain
|
|
|
|
* arbitrary context information between calls of your function.
|
2002-09-21 20:32:54 +02:00
|
|
|
*/
|
|
|
|
void *user_fctx;
|
|
|
|
|
|
|
|
/*
|
2003-04-10 03:22:45 +02:00
|
|
|
* OPTIONAL pointer to struct containing attribute type input metadata
|
2008-10-31 20:37:56 +01:00
|
|
|
*
|
2003-04-10 03:22:45 +02:00
|
|
|
* attinmeta is for use when returning tuples (i.e., composite data types)
|
2004-04-01 23:28:47 +02:00
|
|
|
* and is not used when returning base data types. It is only needed
|
|
|
|
* if you intend to use BuildTupleFromCStrings() to create the return
|
|
|
|
* tuple.
|
2002-09-21 20:32:54 +02:00
|
|
|
*/
|
|
|
|
AttInMetadata *attinmeta;
|
|
|
|
|
|
|
|
/*
|
2003-04-10 03:22:45 +02:00
|
|
|
* memory context used for structures that must live for multiple calls
|
2002-09-21 20:32:54 +02:00
|
|
|
*
|
|
|
|
* multi_call_memory_ctx is set by SRF_FIRSTCALL_INIT() for you, and used
|
|
|
|
* by SRF_RETURN_DONE() for cleanup. It is the most appropriate memory
|
2003-04-10 03:22:45 +02:00
|
|
|
* context for any memory that is to be reused across multiple calls
|
2002-09-21 20:32:54 +02:00
|
|
|
* of the SRF.
|
|
|
|
*/
|
|
|
|
MemoryContext multi_call_memory_ctx;
|
2004-04-01 23:28:47 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* OPTIONAL pointer to struct containing tuple description
|
|
|
|
*
|
2009-04-27 18:27:36 +02:00
|
|
|
* tuple_desc is for use when returning tuples (i.e., composite data types)
|
2004-04-01 23:28:47 +02:00
|
|
|
* and is only needed if you are going to build the tuples with
|
2005-03-16 22:38:10 +01:00
|
|
|
* heap_form_tuple() rather than with BuildTupleFromCStrings(). Note that
|
2004-04-01 23:28:47 +02:00
|
|
|
* the TupleDesc pointer stored here should usually have been run through
|
|
|
|
* BlessTupleDesc() first.
|
|
|
|
*/
|
|
|
|
TupleDesc tuple_desc;
|
|
|
|
|
2002-09-21 20:32:54 +02:00
|
|
|
} FuncCallContext;
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2003-04-10 03:22:45 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2002-09-21 20:32:54 +02:00
|
|
|
An <acronym>SRF</> uses several functions and macros that
|
|
|
|
automatically manipulate the <structname>FuncCallContext</>
|
2007-02-01 01:28:19 +01:00
|
|
|
structure (and expect to find it via <literal>fn_extra</>). Use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
SRF_IS_FIRSTCALL()
|
|
|
|
</programlisting>
|
2002-08-29 02:17:06 +02:00
|
|
|
to determine if your function is being called for the first or a
|
2007-02-01 01:28:19 +01:00
|
|
|
subsequent time. On the first call (only) use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
SRF_FIRSTCALL_INIT()
|
|
|
|
</programlisting>
|
2002-09-21 20:32:54 +02:00
|
|
|
to initialize the <structname>FuncCallContext</>. On every function call,
|
2007-02-01 01:28:19 +01:00
|
|
|
including the first, use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
SRF_PERCALL_SETUP()
|
|
|
|
</programlisting>
|
2002-09-21 20:32:54 +02:00
|
|
|
to properly set up for using the <structname>FuncCallContext</>
|
|
|
|
and clearing any previously returned data left over from the
|
|
|
|
previous pass.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2007-02-01 01:28:19 +01:00
|
|
|
If your function has data to return, use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
SRF_RETURN_NEXT(funcctx, result)
|
|
|
|
</programlisting>
|
2003-04-10 03:22:45 +02:00
|
|
|
to return it to the caller. (<literal>result</> must be of type
|
2002-09-21 20:32:54 +02:00
|
|
|
<type>Datum</>, either a single value or a tuple prepared as
|
2003-04-10 03:22:45 +02:00
|
|
|
described above.) Finally, when your function is finished
|
2007-02-01 01:28:19 +01:00
|
|
|
returning data, use:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
|
|
|
SRF_RETURN_DONE(funcctx)
|
|
|
|
</programlisting>
|
2002-09-21 20:32:54 +02:00
|
|
|
to clean up and end the <acronym>SRF</>.
|
2002-07-18 06:47:17 +02:00
|
|
|
</para>
|
|
|
|
|
2002-08-29 19:14:33 +02:00
|
|
|
<para>
|
2002-09-21 20:32:54 +02:00
|
|
|
The memory context that is current when the <acronym>SRF</> is called is
|
2002-08-29 19:14:33 +02:00
|
|
|
a transient context that will be cleared between calls. This means
|
2003-04-10 03:22:45 +02:00
|
|
|
that you do not need to call <function>pfree</> on everything
|
|
|
|
you allocated using <function>palloc</>; it will go away anyway. However, if you want to allocate
|
2002-08-29 19:14:33 +02:00
|
|
|
any data structures to live across calls, you need to put them somewhere
|
|
|
|
else. The memory context referenced by
|
|
|
|
<structfield>multi_call_memory_ctx</> is a suitable location for any
|
2002-09-21 20:32:54 +02:00
|
|
|
data that needs to survive until the <acronym>SRF</> is finished running. In most
|
2002-08-29 19:14:33 +02:00
|
|
|
cases, this means that you should switch into
|
|
|
|
<structfield>multi_call_memory_ctx</> while doing the first-call setup.
|
|
|
|
</para>
|
|
|
|
|
2002-07-18 06:47:17 +02:00
|
|
|
<para>
|
|
|
|
A complete pseudo-code example looks like the following:
|
|
|
|
<programlisting>
|
|
|
|
Datum
|
2003-04-10 03:22:45 +02:00
|
|
|
my_set_returning_function(PG_FUNCTION_ARGS)
|
2002-07-18 06:47:17 +02:00
|
|
|
{
|
2002-08-29 19:14:33 +02:00
|
|
|
FuncCallContext *funcctx;
|
|
|
|
Datum result;
|
2003-04-10 03:22:45 +02:00
|
|
|
<replaceable>further declarations as needed</replaceable>
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
if (SRF_IS_FIRSTCALL())
|
|
|
|
{
|
2009-11-30 16:49:35 +01:00
|
|
|
MemoryContext oldcontext;
|
|
|
|
|
2002-08-29 19:14:33 +02:00
|
|
|
funcctx = SRF_FIRSTCALL_INIT();
|
2005-01-22 23:06:27 +01:00
|
|
|
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
|
2003-04-10 03:22:45 +02:00
|
|
|
/* One-time setup code appears here: */
|
|
|
|
<replaceable>user code</replaceable>
|
|
|
|
<replaceable>if returning composite</replaceable>
|
|
|
|
<replaceable>build TupleDesc, and perhaps AttInMetadata</replaceable>
|
|
|
|
<replaceable>endif returning composite</replaceable>
|
|
|
|
<replaceable>user code</replaceable>
|
2002-08-29 19:14:33 +02:00
|
|
|
MemoryContextSwitchTo(oldcontext);
|
2002-08-29 02:17:06 +02:00
|
|
|
}
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* Each-time setup code appears here: */
|
|
|
|
<replaceable>user code</replaceable>
|
2002-08-29 02:17:06 +02:00
|
|
|
funcctx = SRF_PERCALL_SETUP();
|
2003-04-10 03:22:45 +02:00
|
|
|
<replaceable>user code</replaceable>
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
/* this is just one way we might test whether we are done: */
|
|
|
|
if (funcctx->call_cntr < funcctx->max_calls)
|
|
|
|
{
|
2003-04-10 03:22:45 +02:00
|
|
|
/* Here we want to return another item: */
|
|
|
|
<replaceable>user code</replaceable>
|
|
|
|
<replaceable>obtain result Datum</replaceable>
|
2002-08-29 02:17:06 +02:00
|
|
|
SRF_RETURN_NEXT(funcctx, result);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2003-04-10 03:22:45 +02:00
|
|
|
/* Here we are done returning items and just need to clean up: */
|
|
|
|
<replaceable>user code</replaceable>
|
2002-08-29 02:17:06 +02:00
|
|
|
SRF_RETURN_DONE(funcctx);
|
|
|
|
}
|
2002-07-18 06:47:17 +02:00
|
|
|
}
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
2005-05-31 01:09:07 +02:00
|
|
|
A complete example of a simple <acronym>SRF</> returning a composite type
|
|
|
|
looks like:
|
2008-12-08 00:46:39 +01:00
|
|
|
<programlisting><![CDATA[
|
2005-05-31 01:09:07 +02:00
|
|
|
PG_FUNCTION_INFO_V1(retcomposite);
|
2003-04-10 03:22:45 +02:00
|
|
|
|
2002-07-18 06:47:17 +02:00
|
|
|
Datum
|
2005-05-31 01:09:07 +02:00
|
|
|
retcomposite(PG_FUNCTION_ARGS)
|
2002-07-18 06:47:17 +02:00
|
|
|
{
|
2002-08-29 02:17:06 +02:00
|
|
|
FuncCallContext *funcctx;
|
|
|
|
int call_cntr;
|
|
|
|
int max_calls;
|
|
|
|
TupleDesc tupdesc;
|
|
|
|
AttInMetadata *attinmeta;
|
|
|
|
|
2009-11-30 16:49:35 +01:00
|
|
|
/* stuff done only on the first call of the function */
|
|
|
|
if (SRF_IS_FIRSTCALL())
|
|
|
|
{
|
2004-12-30 04:13:56 +01:00
|
|
|
MemoryContext oldcontext;
|
2002-08-29 19:14:33 +02:00
|
|
|
|
2002-08-29 02:17:06 +02:00
|
|
|
/* create a function context for cross-call persistence */
|
2002-08-29 19:14:33 +02:00
|
|
|
funcctx = SRF_FIRSTCALL_INIT();
|
|
|
|
|
|
|
|
/* switch to memory context appropriate for multiple function calls */
|
2008-12-08 00:46:39 +01:00
|
|
|
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
/* total number of tuples to be returned */
|
2008-12-08 00:46:39 +01:00
|
|
|
funcctx->max_calls = PG_GETARG_UINT32(0);
|
2002-08-29 02:17:06 +02:00
|
|
|
|
2005-05-31 01:09:07 +02:00
|
|
|
/* Build a tuple descriptor for our result type */
|
2008-12-08 00:46:39 +01:00
|
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
2005-05-31 01:09:07 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("function returning record called in context "
|
|
|
|
"that cannot accept type record")));
|
2002-08-29 02:17:06 +02:00
|
|
|
|
|
|
|
/*
|
2003-04-10 03:22:45 +02:00
|
|
|
* generate attribute metadata needed later to produce tuples from raw
|
2002-08-29 02:17:06 +02:00
|
|
|
* C strings
|
|
|
|
*/
|
|
|
|
attinmeta = TupleDescGetAttInMetadata(tupdesc);
|
2008-12-08 00:46:39 +01:00
|
|
|
funcctx->attinmeta = attinmeta;
|
2002-08-29 19:14:33 +02:00
|
|
|
|
|
|
|
MemoryContextSwitchTo(oldcontext);
|
2002-07-18 06:47:17 +02:00
|
|
|
}
|
|
|
|
|
2002-08-29 02:17:06 +02:00
|
|
|
/* stuff done on every call of the function */
|
|
|
|
funcctx = SRF_PERCALL_SETUP();
|
2002-07-18 06:47:17 +02:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
call_cntr = funcctx->call_cntr;
|
|
|
|
max_calls = funcctx->max_calls;
|
|
|
|
attinmeta = funcctx->attinmeta;
|
2008-10-31 20:37:56 +01:00
|
|
|
|
2008-12-08 00:46:39 +01:00
|
|
|
if (call_cntr < max_calls) /* do when there is more left to send */
|
2002-08-29 02:17:06 +02:00
|
|
|
{
|
|
|
|
char **values;
|
|
|
|
HeapTuple tuple;
|
|
|
|
Datum result;
|
|
|
|
|
|
|
|
/*
|
2004-04-01 23:28:47 +02:00
|
|
|
* Prepare a values array for building the returned tuple.
|
2002-08-29 02:17:06 +02:00
|
|
|
* This should be an array of C strings which will
|
2003-04-10 03:22:45 +02:00
|
|
|
* be processed later by the type input functions.
|
2002-08-29 02:17:06 +02:00
|
|
|
*/
|
|
|
|
values = (char **) palloc(3 * sizeof(char *));
|
|
|
|
values[0] = (char *) palloc(16 * sizeof(char));
|
|
|
|
values[1] = (char *) palloc(16 * sizeof(char));
|
|
|
|
values[2] = (char *) palloc(16 * sizeof(char));
|
|
|
|
|
|
|
|
snprintf(values[0], 16, "%d", 1 * PG_GETARG_INT32(1));
|
|
|
|
snprintf(values[1], 16, "%d", 2 * PG_GETARG_INT32(1));
|
|
|
|
snprintf(values[2], 16, "%d", 3 * PG_GETARG_INT32(1));
|
|
|
|
|
|
|
|
/* build a tuple */
|
|
|
|
tuple = BuildTupleFromCStrings(attinmeta, values);
|
|
|
|
|
|
|
|
/* make the tuple into a datum */
|
2004-04-01 23:28:47 +02:00
|
|
|
result = HeapTupleGetDatum(tuple);
|
2002-08-29 02:17:06 +02:00
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
/* clean up (this is not really necessary) */
|
2002-08-29 02:17:06 +02:00
|
|
|
pfree(values[0]);
|
|
|
|
pfree(values[1]);
|
|
|
|
pfree(values[2]);
|
|
|
|
pfree(values);
|
|
|
|
|
2003-04-10 03:22:45 +02:00
|
|
|
SRF_RETURN_NEXT(funcctx, result);
|
2002-08-29 02:17:06 +02:00
|
|
|
}
|
|
|
|
else /* do when there is no more left */
|
|
|
|
{
|
2003-04-10 03:22:45 +02:00
|
|
|
SRF_RETURN_DONE(funcctx);
|
2002-08-29 02:17:06 +02:00
|
|
|
}
|
2002-07-18 06:47:17 +02:00
|
|
|
}
|
2008-12-08 00:46:39 +01:00
|
|
|
]]>
|
2002-07-18 06:47:17 +02:00
|
|
|
</programlisting>
|
2003-04-10 03:22:45 +02:00
|
|
|
|
2005-05-31 01:09:07 +02:00
|
|
|
One way to declare this function in SQL is:
|
2002-07-18 06:47:17 +02:00
|
|
|
<programlisting>
|
2005-05-31 01:09:07 +02:00
|
|
|
CREATE TYPE __retcomposite AS (f1 integer, f2 integer, f3 integer);
|
2002-07-18 06:47:17 +02:00
|
|
|
|
2005-05-31 01:09:07 +02:00
|
|
|
CREATE OR REPLACE FUNCTION retcomposite(integer, integer)
|
|
|
|
RETURNS SETOF __retcomposite
|
|
|
|
AS '<replaceable>filename</>', 'retcomposite'
|
|
|
|
LANGUAGE C IMMUTABLE STRICT;
|
|
|
|
</programlisting>
|
|
|
|
A different way is to use OUT parameters:
|
|
|
|
<programlisting>
|
|
|
|
CREATE OR REPLACE FUNCTION retcomposite(IN integer, IN integer,
|
|
|
|
OUT f1 integer, OUT f2 integer, OUT f3 integer)
|
|
|
|
RETURNS SETOF record
|
|
|
|
AS '<replaceable>filename</>', 'retcomposite'
|
2003-04-10 03:22:45 +02:00
|
|
|
LANGUAGE C IMMUTABLE STRICT;
|
2001-01-12 23:15:32 +01:00
|
|
|
</programlisting>
|
2005-05-31 01:09:07 +02:00
|
|
|
Notice that in this method the output type of the function is formally
|
|
|
|
an anonymous <structname>record</> type.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
1998-03-01 09:16:16 +01:00
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
<para>
|
2011-01-26 15:22:21 +01:00
|
|
|
The directory <link linkend="tablefunc">contrib/tablefunc</>
|
|
|
|
module in the source distribution contains more examples of
|
|
|
|
set-returning functions.
|
1999-07-22 17:11:05 +02:00
|
|
|
</para>
|
|
|
|
</sect2>
|
2003-08-10 00:50:22 +02:00
|
|
|
|
|
|
|
<sect2>
|
|
|
|
<title>Polymorphic Arguments and Return Types</title>
|
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
C-language functions can be declared to accept and
|
2003-11-12 23:47:47 +01:00
|
|
|
return the polymorphic types
|
2007-06-07 01:00:50 +02:00
|
|
|
<type>anyelement</type>, <type>anyarray</type>, <type>anynonarray</type>,
|
|
|
|
and <type>anyenum</type>.
|
2003-08-31 19:32:24 +02:00
|
|
|
See <xref linkend="extend-types-polymorphic"> for a more detailed explanation
|
2003-08-10 00:50:22 +02:00
|
|
|
of polymorphic functions. When function arguments or return types
|
|
|
|
are defined as polymorphic types, the function author cannot know
|
|
|
|
in advance what data type it will be called with, or
|
|
|
|
need to return. There are two routines provided in <filename>fmgr.h</>
|
|
|
|
to allow a version-1 C function to discover the actual data types
|
|
|
|
of its arguments and the type it is expected to return. The routines are
|
|
|
|
called <literal>get_fn_expr_rettype(FmgrInfo *flinfo)</> and
|
|
|
|
<literal>get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)</>.
|
2003-11-01 02:56:29 +01:00
|
|
|
They return the result or argument type OID, or <symbol>InvalidOid</symbol> if the
|
2003-08-10 00:50:22 +02:00
|
|
|
information is not available.
|
|
|
|
The structure <literal>flinfo</> is normally accessed as
|
|
|
|
<literal>fcinfo->flinfo</>. The parameter <literal>argnum</>
|
2005-05-31 01:09:07 +02:00
|
|
|
is zero based. <function>get_call_result_type</> can also be used
|
|
|
|
as an alternative to <function>get_fn_expr_rettype</>.
|
2003-08-10 00:50:22 +02:00
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
For example, suppose we want to write a function to accept a single
|
|
|
|
element of any type, and return a one-dimensional array of that type:
|
|
|
|
|
|
|
|
<programlisting>
|
|
|
|
PG_FUNCTION_INFO_V1(make_array);
|
|
|
|
Datum
|
|
|
|
make_array(PG_FUNCTION_ARGS)
|
|
|
|
{
|
|
|
|
ArrayType *result;
|
|
|
|
Oid element_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
|
|
|
|
Datum element;
|
2005-11-17 23:14:56 +01:00
|
|
|
bool isnull;
|
2003-08-10 00:50:22 +02:00
|
|
|
int16 typlen;
|
|
|
|
bool typbyval;
|
|
|
|
char typalign;
|
|
|
|
int ndims;
|
|
|
|
int dims[MAXDIM];
|
|
|
|
int lbs[MAXDIM];
|
|
|
|
|
|
|
|
if (!OidIsValid(element_type))
|
|
|
|
elog(ERROR, "could not determine data type of input");
|
|
|
|
|
2005-11-17 23:14:56 +01:00
|
|
|
/* get the provided element, being careful in case it's NULL */
|
|
|
|
isnull = PG_ARGISNULL(0);
|
|
|
|
if (isnull)
|
|
|
|
element = (Datum) 0;
|
|
|
|
else
|
|
|
|
element = PG_GETARG_DATUM(0);
|
2003-08-10 00:50:22 +02:00
|
|
|
|
|
|
|
/* we have one dimension */
|
|
|
|
ndims = 1;
|
|
|
|
/* and one element */
|
|
|
|
dims[0] = 1;
|
|
|
|
/* and lower bound is 1 */
|
|
|
|
lbs[0] = 1;
|
|
|
|
|
|
|
|
/* get required info about the element type */
|
|
|
|
get_typlenbyvalalign(element_type, &typlen, &typbyval, &typalign);
|
|
|
|
|
|
|
|
/* now build the array */
|
2005-11-17 23:14:56 +01:00
|
|
|
result = construct_md_array(&element, &isnull, ndims, dims, lbs,
|
2003-08-10 00:50:22 +02:00
|
|
|
element_type, typlen, typbyval, typalign);
|
|
|
|
|
|
|
|
PG_RETURN_ARRAYTYPE_P(result);
|
|
|
|
}
|
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
The following command declares the function
|
|
|
|
<function>make_array</function> in SQL:
|
|
|
|
|
|
|
|
<programlisting>
|
2003-11-12 23:47:47 +01:00
|
|
|
CREATE FUNCTION make_array(anyelement) RETURNS anyarray
|
2003-08-10 00:50:22 +02:00
|
|
|
AS '<replaceable>DIRECTORY</replaceable>/funcs', 'make_array'
|
2005-11-17 23:14:56 +01:00
|
|
|
LANGUAGE C IMMUTABLE;
|
2006-11-23 04:52:05 +01:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
2008-07-16 03:30:23 +02:00
|
|
|
|
|
|
|
<para>
|
|
|
|
There is a variant of polymorphism that is only available to C-language
|
|
|
|
functions: they can be declared to take parameters of type
|
|
|
|
<literal>"any"</>. (Note that this type name must be double-quoted,
|
|
|
|
since it's also a SQL reserved word.) This works like
|
|
|
|
<type>anyelement</> except that it does not constrain different
|
|
|
|
<literal>"any"</> arguments to be the same type, nor do they help
|
|
|
|
determine the function's result type. A C-language function can also
|
|
|
|
declare its final parameter to be <literal>VARIADIC "any"</>. This will
|
|
|
|
match one or more actual arguments of any type (not necessarily the same
|
|
|
|
type). These arguments will <emphasis>not</> be gathered into an array
|
|
|
|
as happens with normal variadic functions; they will just be passed to
|
|
|
|
the function separately. The <function>PG_NARGS()</> macro and the
|
|
|
|
methods described above must be used to determine the number of actual
|
|
|
|
arguments and their types when using this feature.
|
|
|
|
</para>
|
2006-11-23 04:52:05 +01:00
|
|
|
</sect2>
|
2008-07-16 03:30:23 +02:00
|
|
|
|
2006-11-23 04:52:05 +01:00
|
|
|
<sect2>
|
2006-11-23 06:43:32 +01:00
|
|
|
<title>Shared Memory and LWLocks</title>
|
2006-11-23 04:52:05 +01:00
|
|
|
|
|
|
|
<para>
|
Update documentation on may/can/might:
Standard English uses "may", "can", and "might" in different ways:
may - permission, "You may borrow my rake."
can - ability, "I can lift that log."
might - possibility, "It might rain today."
Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice. Similarly, "It may crash" is better stated, "It might crash".
Also update two error messages mentioned in the documenation to match.
2007-01-31 21:56:20 +01:00
|
|
|
Add-ins can reserve LWLocks and an allocation of shared memory on server
|
2006-11-23 06:43:32 +01:00
|
|
|
startup. The add-in's shared library must be preloaded by specifying
|
2008-10-31 20:37:56 +01:00
|
|
|
it in
|
2010-08-06 22:09:03 +02:00
|
|
|
<xref linkend="guc-shared-preload-libraries"><indexterm><primary>shared_preload_libraries</></>.
|
2006-11-23 06:43:32 +01:00
|
|
|
Shared memory is reserved by calling:
|
2006-11-23 04:52:05 +01:00
|
|
|
<programlisting>
|
|
|
|
void RequestAddinShmemSpace(int size)
|
|
|
|
</programlisting>
|
2006-11-23 06:28:18 +01:00
|
|
|
from your <function>_PG_init</> function.
|
2006-11-23 04:52:05 +01:00
|
|
|
</para>
|
|
|
|
<para>
|
2006-11-23 06:43:32 +01:00
|
|
|
LWLocks are reserved by calling:
|
2006-11-23 04:52:05 +01:00
|
|
|
<programlisting>
|
|
|
|
void RequestAddinLWLocks(int n)
|
|
|
|
</programlisting>
|
2008-10-31 20:37:56 +01:00
|
|
|
from <function>_PG_init</>.
|
2006-12-15 03:19:21 +01:00
|
|
|
</para>
|
2006-11-23 04:52:05 +01:00
|
|
|
<para>
|
2006-11-23 06:43:32 +01:00
|
|
|
To avoid possible race-conditions, each backend should use the LWLock
|
2008-10-31 20:37:56 +01:00
|
|
|
<function>AddinShmemInitLock</> when connecting to and initializing
|
2006-11-23 06:43:32 +01:00
|
|
|
its allocation of shared memory, as shown here:
|
2006-11-23 04:52:05 +01:00
|
|
|
<programlisting>
|
2010-07-29 21:34:41 +02:00
|
|
|
static mystruct *ptr = NULL;
|
2006-11-23 04:52:05 +01:00
|
|
|
|
2010-07-29 21:34:41 +02:00
|
|
|
if (!ptr)
|
|
|
|
{
|
|
|
|
bool found;
|
|
|
|
|
|
|
|
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
|
|
|
|
ptr = ShmemInitStruct("my struct name", size, &found);
|
|
|
|
if (!found)
|
2006-11-23 04:52:05 +01:00
|
|
|
{
|
2010-07-29 21:34:41 +02:00
|
|
|
initialize contents of shmem area;
|
|
|
|
acquire any requested LWLocks using:
|
|
|
|
ptr->mylockid = LWLockAssign();
|
2006-11-23 04:52:05 +01:00
|
|
|
}
|
2010-07-29 21:34:41 +02:00
|
|
|
LWLockRelease(AddinShmemInitLock);
|
|
|
|
}
|
2003-08-10 00:50:22 +02:00
|
|
|
</programlisting>
|
|
|
|
</para>
|
|
|
|
</sect2>
|
2011-02-08 22:08:41 +01:00
|
|
|
|
|
|
|
<sect2 id="extend-Cpp">
|
|
|
|
<title>Using C++ for Extensibility</title>
|
|
|
|
|
|
|
|
<indexterm zone="extend-Cpp">
|
|
|
|
<primary>C++</primary>
|
|
|
|
</indexterm>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
Although the <productname>PostgreSQL</productname> backend is written in
|
|
|
|
C, it is possible to write extensions in C++ if these guidelines are
|
|
|
|
followed:
|
|
|
|
|
|
|
|
<itemizedlist>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
All functions accessed by the backend must present a C interface
|
|
|
|
to the backend; these C functions can then call C++ functions.
|
|
|
|
For example, <literal>extern C</> linkage is required for
|
|
|
|
backend-accessed functions. This is also necessary for any
|
|
|
|
functions that are passed as pointers between the backend and
|
|
|
|
C++ code.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Free memory using the appropriate deallocation method. For example,
|
|
|
|
most backend memory is allocated using <function>palloc()</>, so use
|
|
|
|
<function>pfree()</> to free it. Using C++
|
|
|
|
<function>delete</> in such cases will fail.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
Prevent exceptions from propagating into the C code (use a catch-all
|
|
|
|
block at the top level of all <literal>extern C</> functions). This
|
|
|
|
is necessary even if the C++ code does not explicitly throw any
|
|
|
|
exceptions, because events like out-of-memory can still throw
|
|
|
|
exceptions. Any exceptions must be caught and appropriate errors
|
|
|
|
passed back to the C interface. If possible, compile C++ with
|
|
|
|
<option>-fno-exceptions</> to eliminate exceptions entirely; in such
|
|
|
|
cases, you must check for failures in your C++ code, e.g. check for
|
|
|
|
NULL returned by <function>new()</>.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
<listitem>
|
|
|
|
<para>
|
|
|
|
If calling backend functions from C++ code, be sure that the
|
|
|
|
C++ call stack contains only plain old data structures
|
|
|
|
(<acronym>POD</>). This is necessary because backend errors
|
|
|
|
generate a distant <function>longjmp()</> that does not properly
|
|
|
|
unroll a C++ call stack with non-POD objects.
|
|
|
|
</para>
|
|
|
|
</listitem>
|
|
|
|
</itemizedlist>
|
|
|
|
</para>
|
|
|
|
|
|
|
|
<para>
|
|
|
|
In summary, it is best to place C++ code behind a wall of
|
|
|
|
<literal>extern C</> functions that interface to the backend,
|
|
|
|
and avoid exception, memory, and call stack leakage.
|
|
|
|
</para>
|
|
|
|
</sect2>
|
|
|
|
|
1999-07-22 17:11:05 +02:00
|
|
|
</sect1>
|