バージョンごとのドキュメント一覧

38.5. 問い合わせ言語(SQL)関数 #

<title>Query Language (<acronym>SQL</acronym>) Functions</title>

SQL functions execute an arbitrary list of SQL statements, returning the result of the last query in the list. In the simple (non-set) case, the first row of the last query's result will be returned. (Bear in mind that <quote>the first row</quote> of a multirow result is not well-defined unless you use <literal>ORDER BY</literal>.) If the last query happens to return no rows at all, the null value will be returned. SQL関数は、任意のSQL文のリストを実行し、そのリストの最後の問い合わせの結果を返します。 単純な(集合ではない)場合、最後の問い合わせの結果の最初の行が返されます。 (複数行の結果のうちの最初の行は、ORDER BYを使用しない限り定義付けることができないことを覚えておいてください。) 最後の問い合わせが何も行を返さない時はNULL値が返されます。

Alternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function's return type as <literal>SETOF <replaceable>sometype</replaceable></literal>, or equivalently by declaring it as <literal>RETURNS TABLE(<replaceable>columns</replaceable>)</literal>. In this case all rows of the last query's result are returned. Further details appear below. 他にも、SQL関数は、SETOF sometype型を返すように指定すること、または同意のRETURNS TABLE(columns)と宣言することにより、集合(つまり複数の行)を返すように宣言もできます。 この場合、最後の問い合わせの結果のすべての行が返されます。 詳細は後で説明します。

The body of an SQL function must be a list of SQL statements separated by semicolons. A semicolon after the last statement is optional. Unless the function is declared to return <type>void</type>, the last statement must be a <command>SELECT</command>, or an <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> that has a <literal>RETURNING</literal> clause. SQL関数の本体は、セミコロンで区切ったSQL文のリストでなければなりません。 最後の文の後のセミコロンは省略可能です。 関数がvoidを返すものと宣言されていない限り、最後の文はSELECT、またはRETURNING句を持つINSERTUPDATE、またはDELETEでなければなりません。

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>, <command>DELETE</command>, and <command>MERGE</command>), as well as other SQL commands. (You cannot use transaction control commands, e.g., <command>COMMIT</command>, <command>SAVEPOINT</command>, and some utility commands, e.g., <literal>VACUUM</literal>, in <acronym>SQL</acronym> functions.) However, the final command must be a <command>SELECT</command> or have a <literal>RETURNING</literal> clause that returns whatever is specified as the function's return type. Alternatively, if you want to define an SQL function that performs actions but has no useful value to return, you can define it as returning <type>void</type>. For example, this function removes rows with negative salaries from the <literal>emp</literal> table: SQL言語で作成された、任意のコマンド群はまとめて、関数として定義できます。 SELECT問い合わせ以外に、データ変更用の問い合わせ(つまり、INSERTUPDATEDELETEおよびMERGE)やその他のSQLコマンドを含めることができます。 (SQL関数ではCOMMITSAVEPOINTなどのトランザクション制御コマンドおよびVACUUMなどのユーティリティコマンドは使用できません。) しかし、最後のコマンドは、関数の戻り値型として定義したものを返すSELECT、またはRETURNING句があるものでなければなりません。 その他にも、何か動作をさせるが、有用な値を返さないSQL関数を定義したいのであれば、voidを返すものと定義することで実現可能です。 たとえば、以下の関数はempテーブルから負の給料となっている行を削除します。

CREATE FUNCTION clean_emp() RETURNS void AS '
    DELETE FROM emp
        WHERE salary < 0;
' LANGUAGE SQL;

SELECT clean_emp();

 clean_emp
-----------

(1 row)

You can also write this as a procedure, thus avoiding the issue of the return type. For example: これをプロシージャとして書くこともできるので、返り値の型の問題を避けることができます。 例を示します。

CREATE PROCEDURE clean_emp() AS '
    DELETE FROM emp
        WHERE salary < 0;
' LANGUAGE SQL;

CALL clean_emp();

In simple cases like this, the difference between a function returning <type>void</type> and a procedure is mostly stylistic. However, procedures offer additional functionality such as transaction control that is not available in functions. Also, procedures are SQL standard whereas returning <type>void</type> is a PostgreSQL extension. このような単純な例では、voidを返す関数とプロシージャの違いはほとんど様式的なものです。 しかし、プロシージャは関数では不可能なトランザクションの制御のような追加機能を提供します。 また、voidを返す関数がPostgreSQLの拡張であるのに対し、プロシージャはSQL標準です。

注記

The entire body of an SQL function is parsed before any of it is executed. While an SQL function can contain commands that alter the system catalogs (e.g., <command>CREATE TABLE</command>), the effects of such commands will not be visible during parse analysis of later commands in the function. Thus, for example, <literal>CREATE TABLE foo (...); INSERT INTO foo VALUES(...);</literal> will not work as desired if packaged up into a single SQL function, since <structname>foo</structname> won't exist yet when the <command>INSERT</command> command is parsed. It's recommended to use <application>PL/pgSQL</application> instead of an SQL function in this type of situation. SQL関数の本体全体は、その一部が実行される前に解析されます。 SQL関数はシステムカタログを変更するコマンド(例えばCREATE TABLE)を含むことができますので、そのようなコマンドの効果は関数の以降のコマンドの解析中は可視ではありません。 それゆえ、例えば、CREATE TABLE foo (...); INSERT INTO foo VALUES(...);は単一のSQL関数にまとめられていると期待したようには動作しません。INSERTコマンドが解析されている時にはfooがまだ存在しないからです。 このような場合にはSQL関数の代わりにPL/pgSQLを使うことを薦めます。

The syntax of the <command>CREATE FUNCTION</command> command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see <xref linkend="sql-syntax-dollar-quoting"/>) for the string constant. If you choose to use regular single-quoted string constant syntax, you must double single quote marks (<literal>'</literal>) and backslashes (<literal>\</literal>) (assuming escape string syntax) in the body of the function (see <xref linkend="sql-syntax-strings"/>). CREATE FUNCTIONコマンドの構文では、関数本体は文字列定数として作成される必要があります。 この文字列定数の記述には、通常、ドル引用符付け(4.1.2.4)が最も便利です。 文字列定数を単一引用符で括る通常の構文では、関数本体中で使用される単一引用符(')とバックスラッシュ(\)(エスケープ文字列構文を仮定)を二重にしなければなりません(4.1.2.1を参照)。

38.5.1. SQL関数用の引数 #

<title>Arguments for <acronym>SQL</acronym> Functions</title>

Arguments of an SQL function can be referenced in the function body using either names or numbers. Examples of both methods appear below. SQL関数の引数は関数本体内で名前または番号を用いて参照できます。 両方の方法の例を後で示します。

To use a name, declare the function argument as having a name, and then just write that name in the function body. If the argument name is the same as any column name in the current SQL command within the function, the column name will take precedence. To override this, qualify the argument name with the name of the function itself, that is <literal><replaceable>function_name</replaceable>.<replaceable>argument_name</replaceable></literal>. (If this would conflict with a qualified column name, again the column name wins. You can avoid the ambiguity by choosing a different alias for the table within the SQL command.) 名前を使用するためには、関数引数を名前を持つものとして宣言し、その名前を関数本体内で記述するだけです。 引数名が関数内の現在のSQLコマンドにおける任意の列名と同じ場合は、列名が優先されます。 これを上書きするためには、function_name.argument_nameのように、引数名を関数自身の名前を付けて修飾してください。 (もしこれも修飾された列名と競合する場合は、列名が優先されます。 SQLコマンド内でテーブルに他の別名を付けることで、この曖昧さを防止できます。)

In the older numeric approach, arguments are referenced using the syntax <literal>$<replaceable>n</replaceable></literal>: <literal>$1</literal> refers to the first input argument, <literal>$2</literal> to the second, and so on. This will work whether or not the particular argument was declared with a name. 古い番号による方法では、引数は関数本体内で$nという構文を用いて表すことができます。 つまり、$1は第1引数を示し、$2は第2引数のようになります。 これは特定の引数が名前付きで宣言されているかどうかに関係なく動作します。

If an argument is of a composite type, then the dot notation, e.g., <literal><replaceable>argname</replaceable>.<replaceable>fieldname</replaceable></literal> or <literal>$1.<replaceable>fieldname</replaceable></literal>, can be used to access attributes of the argument. Again, you might need to qualify the argument's name with the function name to make the form with an argument name unambiguous. 引数が複合型の場合、argname.fieldname$1.fieldnameのようなドット表記を用いて引数の属性にアクセスできます。 ここでも、引数名を持つ形式で曖昧さが発生する場合には関数名で引数名を修飾してください。

SQL function arguments can only be used as data values, not as identifiers. Thus for example this is reasonable: SQL関数の引数は、識別子としてではなく、データ値としてのみ使用できます。 したがって、例えば

INSERT INTO mytable VALUES ($1);

but this will not work: は正しいものですが、以下は動作しません。

INSERT INTO $1 VALUES (42);

注記

The ability to use names to reference SQL function arguments was added in <productname>PostgreSQL</productname> 9.2. Functions to be used in older servers must use the <literal>$<replaceable>n</replaceable></literal> notation. SQL関数の引数を参照するために名前を使用できる機能は、PostgreSQL 9.2で追加されました。 これより古いサーバ内で使われる関数は$n記法を使用しなければなりません。

38.5.2. 基本型を使用するSQL関数 #

<title><acronym>SQL</acronym> Functions on Base Types</title>

The simplest possible <acronym>SQL</acronym> function has no arguments and simply returns a base type, such as <type>integer</type>: 最も簡単なSQL関数は、引数を取らずに単にintegerのような基本型を返すものです。

CREATE FUNCTION one() RETURNS integer AS $$
    SELECT 1 AS result;
$$ LANGUAGE SQL;


&#45;- Alternative syntax for string literal:

-- 文字列リテラルの別の構文では
CREATE FUNCTION one() RETURNS integer AS '
    SELECT 1 AS result;
' LANGUAGE SQL;

SELECT one();

 one
-----
   1

Notice that we defined a column alias within the function body for the result of the function (with the name <literal>result</literal>), but this column alias is not visible outside the function. Hence, the result is labeled <literal>one</literal> instead of <literal>result</literal>. 関数本体内で関数の結果用に列の別名を(resultという名前で)定義したことに注目してください。 しかし、この列の別名はこの関数の外部からは可視ではありません。 したがって、その結果はresultではなく、oneというラベルで表示されています。

It is almost as easy to define <acronym>SQL</acronym> functions that take base types as arguments: 基本型を引数として取る、SQL関数を定義することはほとんどの場合簡単です。

CREATE FUNCTION add_em(x integer, y integer) RETURNS integer AS $$
    SELECT x + y;
$$ LANGUAGE SQL;

SELECT add_em(1, 2) AS answer;

 answer
--------
      3

Alternatively, we could dispense with names for the arguments and use numbers: この他に、引数の名前を省いて、番号を使用することもできます。

CREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$
    SELECT $1 + $2;
$$ LANGUAGE SQL;

SELECT add_em(1, 2) AS answer;

 answer
--------
      3

Here is a more useful function, which might be used to debit a bank account: 以下にもう少し役に立つ関数を示します。 これは銀行口座からの引き落としに使用できます。

CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno;
    SELECT 1;
$$ LANGUAGE SQL;

A user could execute this function to debit account 17 by $100.00 as follows: 以下のように、ユーザはこの関数を使用して、口座番号17から100ドルを引き出すことが可能です。

SELECT tf1(17, 100.0);

In this example, we chose the name <literal>accountno</literal> for the first argument, but this is the same as the name of a column in the <literal>bank</literal> table. Within the <command>UPDATE</command> command, <literal>accountno</literal> refers to the column <literal>bank.accountno</literal>, so <literal>tf1.accountno</literal> must be used to refer to the argument. We could of course avoid this by using a different name for the argument. この例では、第一引数の名前にaccountnoを選びましたが、これはbankテーブルの列の名前と同じです。 UPDATEコマンドの中では、accountnobank.accountno列を参照しますので、引数を参照するためにはtf1.accountnoを使用しなければなりません。 もちろんこれは、引数に別の名前を使用することで防ぐことができます。

In practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is: 実際には、関数の結果を定数1よりもわかりやすい形にするために、以下のように定義するとよいでしょう。

CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno;
    SELECT balance FROM bank WHERE accountno = tf1.accountno;
$$ LANGUAGE SQL;

which adjusts the balance and returns the new balance. The same thing could be done in one command using <literal>RETURNING</literal>: これは残高を調整し、更新後の残高を返します。 同じことはRETURNINGを使用して1つのコマンドで行えます。

CREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tf1.accountno
    RETURNING balance;
$$ LANGUAGE SQL;

If the final <literal>SELECT</literal> or <literal>RETURNING</literal> clause in an <acronym>SQL</acronym> function does not return exactly the function's declared result type, <productname>PostgreSQL</productname> will automatically cast the value to the required type, if that is possible with an implicit or assignment cast. Otherwise, you must write an explicit cast. For example, suppose we wanted the previous <function>add_em</function> function to return type <type>float8</type> instead. It's sufficient to write SQL関数の最後のSELECT句やRETURNING句が関数で定義された結果型を正確に返さない場合、PostgreSQLは可能な場合に暗黙的キャストまたは代入キャストで必要な型に自動でキャストします。 そうでない場合は明示的にキャストをする必要があります。 例えば、前出のadd_em関数が代わりにfloat8型を返して欲しいとします。 次のように記述すれば十分です。

CREATE FUNCTION add_em(integer, integer) RETURNS float8 AS $$
    SELECT $1 + $2;
$$ LANGUAGE SQL;

since the <type>integer</type> sum can be implicitly cast to <type>float8</type>. (See <xref linkend="typeconv"/> or <xref linkend="sql-createcast"/> for more about casts.) integerの和はfloat8に暗黙キャストできるからです。 (キャストについての詳細は第10章またはCREATE CASTを参照して下さい)。

38.5.3. 複合型を使用するSQL関数 #

<title><acronym>SQL</acronym> Functions on Composite Types</title>

When writing functions with arguments of composite types, we must not only specify which argument we want but also the desired attribute (field) of that argument. For example, suppose that <type>emp</type> is a table containing employee data, and therefore also the name of the composite type of each row of the table. Here is a function <function>double_salary</function> that computes what someone's salary would be if it were doubled: 関数の引数に複合型を記述した場合、必要な引数を指定するだけではなく、必要とする引数の属性(フィールド)も指定する必要があります。 例えば、empが従業員データを持つテーブルとすると、この名前はそのテーブル内の各行を表す複合型の名前でもあります。 以下に示すdouble_salary関数は、該当する従業員の給料が倍増したらどうなるかを計算します。

CREATE TABLE emp (
    name        text,
    salary      numeric,
    age         integer,
    cubicle     point
);

INSERT INTO emp VALUES ('Bill', 4200, 45, '(2,1)');

CREATE FUNCTION double_salary(emp) RETURNS numeric AS $$
    SELECT $1.salary * 2 AS salary;
$$ LANGUAGE SQL;

SELECT name, double_salary(emp.*) AS dream
    FROM emp
    WHERE emp.cubicle ~= point '(2,1)';

 name | dream
------+-------
 Bill |  8400

Notice the use of the syntax <literal>$1.salary</literal> to select one field of the argument row value. Also notice how the calling <command>SELECT</command> command uses <replaceable>table_name</replaceable><literal>.*</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: $1.salaryという構文を使用して、引数の行値の1フィールドを選択していることに注目してください。 また、table_name.*を使用したSELECTコマンドの呼び出しでは、複合型の値として、現在のテーブル行全体を表すテーブル名を使用していることにも注目してください。 別の方法として、テーブル行は以下のようにテーブル名だけを使用して参照できます。

SELECT name, double_salary(emp) AS dream
    FROM emp
    WHERE emp.cubicle ~= point '(2,1)';

but this usage is deprecated since it's easy to get confused. (See <xref linkend="rowtypes-usage"/> for details about these two notations for the composite value of a table row.) しかし、この使用方法は混乱しやすいためお勧めしません。 (テーブル行の複合型の値に対するこの二つの表記の詳細は8.16.5を参照してください)

Sometimes it is handy to construct a composite argument value on-the-fly. This can be done with the <literal>ROW</literal> construct. For example, we could adjust the data being passed to the function: その場で複合型の引数値を作成することが便利な場合があります。 これはROW式で行うことができます。 例えば、以下のようにして関数に渡すデータを調整できます。

SELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream
    FROM emp;

It is also possible to build a function that returns a composite type. This is an example of a function that returns a single <type>emp</type> row: 複合型を返す関数を作成することもできます。 以下に単一のemp行を返す関数の例を示します。

CREATE FUNCTION new_emp() RETURNS emp AS $$
    SELECT text 'None' AS name,
        1000.0 AS salary,
        25 AS age,
        point '(2,2)' AS cubicle;
$$ LANGUAGE SQL;

In this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants. ここでは、各属性を定数で指定していますが、この定数を何らかの演算に置き換えることもできます。

Note two important things about defining the function: 関数を定義する上で、2つの重要な注意点を以下に示します。

  • The select list order in the query must be exactly the same as that in which the columns appear in the composite type. (Naming the columns, as we did above, is irrelevant to the system.) 問い合わせにおける選択リストの順番は、複合型に列が現れる順番と正確に一致する必要があります。 (上で行ったように列に名前を付けても、システムは認識しません。)

  • We must ensure each expression's type can be cast to that of the corresponding column of the composite type. Otherwise we'll get errors like this: 各式の型が対応する複合型の列にキャストができるようにする必要があります。 さもなくば、以下のようなエラーとなります。

    
    ERROR:  return type mismatch in function declared to return emp
    DETAIL:  Final statement returns text instead of point at column 4.
    
    

    As with the base-type case, the system will not insert explicit casts automatically, only implicit or assignment casts. 基本型の場合と同様に、システムは明示的キャストを自動では挿入せず、暗黙または代入キャストのみをします。

A different way to define the same function is: 同じ関数を以下のように定義することもできます。

CREATE FUNCTION new_emp() RETURNS emp AS $$
    SELECT ROW('None', 1000.0, 25, '(2,2)')::emp;
$$ LANGUAGE SQL;

Here we wrote a <command>SELECT</command> 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 &mdash; for example, if we need to compute the result by calling another function that returns the desired composite value. Another example is that if we are trying to write a function that returns a domain over composite, rather than a plain composite type, it is always necessary to write it as returning a single column, since there is no way to cause a coercion of the whole row result. ここで、正しい複合型の単一の列を単に返すSELECTを記述しました。 今回の例ではこれはより優れたものとはいえませんが、例えば、必要な複合値を返す他の関数を呼び出して結果を計算しなければならない場合など、便利な解法になることがあります。 他の例としては、単なる複合型ではなく複合型のドメインを返す関数を書こうとしてる場合に、単一列を返すように書くことが常に必要となります。 なぜなら、行全体の結果を強制する方法がないからです。

We could call this function directly either by using it in a value expression: この関数を、評価式で使って直接呼び出せますし、

SELECT new_emp();

         new_emp
--------------------------
 (None,1000.0,25,"(2,2)")

or by calling it as a table function: テーブル関数として呼び出しても直接呼び出せます。

SELECT * FROM new_emp();

 name | salary | age | cubicle
------+--------+-----+---------
 None | 1000.0 |  25 | (2,2)

The second way is described more fully in <xref linkend="xfunc-sql-table-functions"/>. 2番目の方法については、38.5.8でより詳しく説明します。

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: 複合型を返す関数を使用する時に、その結果から1つのフィールド(属性)のみを使用したいという場合があります。 これは、以下のような構文で行うことができます。

SELECT (new_emp()).name;

 name
------
 None

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: パーサが混乱しないように、括弧を追加する必要があります。 括弧なしで行おうとすると、以下のような結果になります。

SELECT new_emp().name;
ERROR:  syntax error at or near "."
LINE 1: SELECT new_emp().name;
                        ^

Another option is to use functional notation for extracting an attribute: また、関数表記を使用して属性を抽出することもできます。

SELECT name(new_emp());

 name
------
 None

As explained in <xref linkend="rowtypes-usage"/>, the field notation and functional notation are equivalent. 8.16.5で述べるように、フィールド表記と関数表記は等価です。

Another way to use a function returning a composite type is to pass the result to another function that accepts the correct row type as input: 複合型を結果として返す関数を使用する他の方法は、その結果を、その行型を入力として受け付ける関数に渡す、以下のような方法です。

CREATE FUNCTION getname(emp) RETURNS text AS $$
    SELECT $1.name;
$$ LANGUAGE SQL;

SELECT getname(new_emp());
 getname
---------
 None
(1 row)

38.5.4. 出力パラメータを持つSQL関数 #

<title><acronym>SQL</acronym> Functions with Output Parameters</title>

An alternative way of describing a function's results is to define it with <firstterm>output parameters</firstterm>, as in this example: 関数の結果の記述方法には、他にも出力パラメータを使用して定義する方法があります。 以下に例を示します。

CREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)
AS 'SELECT x + y'
LANGUAGE SQL;

SELECT add_em(3,7);
 add_em
--------
     10
(1 row)

This is not essentially different from the version of <literal>add_em</literal> 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, 38.5.2で示したadd_em版と基本的な違いはありません。 複数列を返す関数を定義する簡単な方法を提供することが出力パラメータの本来の価値です。 以下に例を示します。

CREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)
AS 'SELECT x + y, x * y'
LANGUAGE SQL;

 SELECT * FROM sum_n_product(11,42);
 sum | product
-----+---------
  53 |     462
(1 row)

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 これは基本的に、関数結果用の無名の複合型の作成を行います。 上の例では、以下と同じ最終結果になります。

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;

but not having to bother with the separate composite type definition 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.) しかし、独立した複合型定義に悩まされることがなくなり、便利であるともいえます。 出力パラメータに割り振られた名前が単なる飾りではなく、無名複合型の列名を決定するものであることに注意してください。 (出力パラメータの名前を省略した場合、システム自身が名前を選びます。)

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 SQLからこうした関数を呼び出す時、出力パラメータが呼び出し側の引数リストに含まれないことに注意してください。 PostgreSQLでは入力パラメータのみが関数の呼び出しシグネチャを定義するとみなしているためです。 これはまた、関数を削除することなどを目的に関数を参照する場合、入力パラメータのみが考慮されることを意味しています。 上の関数は、次のいずれかの方法で削除できます。

DROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);
DROP FUNCTION sum_n_product (int, int);

Parameters can be marked as <literal>IN</literal> (the default), <literal>OUT</literal>, <literal>INOUT</literal>, or <literal>VARIADIC</literal>. An <literal>INOUT</literal> parameter serves as both an input parameter (part of the calling argument list) and an output parameter (part of the result record type). <literal>VARIADIC</literal> parameters are input parameters, but are treated specially as described below. パラメータには、IN(デフォルト)、OUTINOUT、またはVARIADICという印を付与できます。 INOUTパラメータは、入力パラメータ(呼び出し引数リストの一部)と出力パラメータ(結果のレコード型の一部)の両方を提供します。 VARIADICパラメータは入力パラメータですが、下で説明するように特別に扱われます。

38.5.5. 出力パラメータを持つSQLプロシージャ #

<title><acronym>SQL</acronym> Procedures with Output Parameters</title>

Output parameters are also supported in procedures, but they work a bit differently from functions. In <command>CALL</command> commands, output parameters must be included in the argument list. For example, the bank account debiting routine from earlier could be written like this: プロシージャでも出力パラメータがサポートされていますが、関数とは少し違った動作になります。 CALLコマンドでは、出力パラメータは引数リストに含まれていなければなりません。 たとえば、先程の銀行口座からの引き落としのルーチンはこのように書くことができます。

CREATE PROCEDURE tp1 (accountno integer, debit numeric, OUT new_balance numeric) AS $$
    UPDATE bank
        SET balance = balance - debit
        WHERE accountno = tp1.accountno
    RETURNING balance;
$$ LANGUAGE SQL;

To call this procedure, an argument matching the <literal>OUT</literal> parameter must be included. It's customary to write <literal>NULL</literal>: このプロシージャを呼び出すには、OUTに対応する引数を含めなければなりません。 習慣としてNULLを書きます。

CALL tp1(17, 100.0, NULL);

If you write something else, it must be an expression that is implicitly coercible to the declared type of the parameter, just as for input parameters. Note however that such an expression will not be evaluated. これ以外を書くなら、入力パラメータ同様、そのパラメータの宣言型に暗黙的に矯正できる式でなければなりません。 しかし、そのような式は評価されないことに注意してください。

When calling a procedure from <application>PL/pgSQL</application>, instead of writing <literal>NULL</literal> you must write a variable that will receive the procedure's output. See <xref linkend="plpgsql-statements-calling-procedure"/> for details. PL/pgSQLからプロシージャを呼び出す際にはNULLと書く代わりにプロシージャの出力を受け取る変数を書かなければなりません。 詳細は43.6.3をご覧ください。

38.5.6. 可変長引数を取るSQL関数 #

<title><acronym>SQL</acronym> Functions with Variable Numbers of Arguments</title>

<acronym>SQL</acronym> functions can be declared to accept variable numbers of arguments, so long as all the <quote>optional</quote> 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</literal>; this parameter must be declared as being of an array type. For example: すべてのオプションの引数が同じデータ型の場合、SQL関数は可変長の引数を受け付けるように宣言できます。 オプションの引数は配列として関数に渡されます。 この関数は最後のパラメータをVARIADICと印を付けて宣言されます。 このパラメータは配列型であるとして宣言されなければなりません。 例をあげます。

CREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$
    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;

SELECT mleast(10, -1, 5, 4.4);
 mleast
--------
     -1
(1 row)

Effectively, all the actual arguments at or beyond the <literal>VARIADIC</literal> position are gathered up into a one-dimensional array, as if you had written 実際、VARIADICの位置以降の実引数はすべて、あたかも以下のように記述したかのように、1次元の配列としてまとめられます。


SELECT mleast(ARRAY[10, -1, 5, 4.4]);    &#45;- doesn't work

SELECT mleast(ARRAY[10, -1, 5, 4.4]);    -- 動作しません

You can't actually write that, though &mdash; or at least, it will not match this function definition. A parameter marked <literal>VARIADIC</literal> matches one or more occurrences of its element type, not of its own type. しかし、実際にこのように記述することはできません。 少なくとも、この関数定義に一致しません。 VARIADIC印の付いたパラメータは、自身の型ではなく、その要素型が1つ以上存在することに一致します。

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. Also, this is the only secure way to call a variadic function found in a schema that permits untrusted users to create objects; see <xref linkend="typeconv-func"/>. You can do this by specifying <literal>VARIADIC</literal> in the call: 時として、variadic関数に既に構築された配列を渡せることは有用です。 1つのvariadic関数が、自身の配列パラメータを他のものに渡したいとき特に便利です。 また、これが、信用できないユーザがオブジェクトを作成できるスキーマにあるvariadic関数を呼び出す唯一の安全な方法です。10.3を参照してください。 これは、呼び出しにVARIADICを指定することで行えます。

SELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);

This prevents expansion of the function's variadic parameter into its element type, thereby allowing the array argument value to match normally. <literal>VARIADIC</literal> can only be attached to the last actual argument of a function call. これは関数のvariadicパラメータがその要素型に拡張するのを防ぎます。 その結果、配列引数値が標準的にマッチされるようになります。 VARIADICは関数呼び出しの最後の実引数としてのみ付加できます。

Specifying <literal>VARIADIC</literal> in the call is also the only way to pass an empty array to a variadic function, for example: 呼び出しでVARIADICを指定することは、variadic関数に空の配列を渡す唯一の方法でもあります。例えば、

SELECT mleast(VARIADIC ARRAY[]::numeric[]);

Simply writing <literal>SELECT mleast()</literal> does not work because a variadic parameter must match at least one actual argument. (You could define a second function also named <literal>mleast</literal>, with no parameters, if you wanted to allow such calls.) variadicパラメータが少なくとも1つの実引数と一致しなければなりませんので、単にSELECT mleast()と書くだけでは上手くいきません。 (もしそのような呼び出しを許可したいのなら、mleastという名前のパラメータのない第2の関数を定義できます。)

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</literal>. For example, this will work: variadicパラメータから生成される配列要素パラメータは、それ自身にはまったく名前を持たないものとして扱われます。 これは、名前付き引数(4.3)を使用して可変長の関数を呼び出すことができないことを意味します。 ただし、VARIADICを指定する場合は例外です。 たとえば、以下は動作しますが、

SELECT mleast(VARIADIC arr => ARRAY[10, -1, 5, 4.4]);

but not these: 以下は動作しません。

SELECT mleast(arr => 10);
SELECT mleast(arr => ARRAY[10, -1, 5, 4.4]);

38.5.7. 引数にデフォルト値を持つSQL関数 #

<title><acronym>SQL</acronym> Functions with Default Values for Arguments</title>

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 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.) Whether or not you use it, this capability creates a need for precautions when calling functions in databases where some users mistrust other users; see <xref linkend="typeconv-func"/>. 一部またはすべての入力引数にデフォルト値を持つ関数を宣言できます。 デフォルト値は、関数が実際の引数の数に足りない数の引数で呼び出された場合に挿入されます。 引数は実引数リストの終端から省略できますので、デフォルト値を持つパラメータの後にあるパラメータはすべて、同様にデフォルト値を持たなければなりません。 (名前付きの引数記法を使用してこの制限を緩和させることもできますが、まだ位置引数記法が実用的に動作できることが強制されています。) 使うかどうかに関わりなく、この能力は、あるユーザが他のユーザを信用しないデータベースで関数を呼び出す時に、セキュリティの事前の対策を必要とします。10.3を参照してください。

For example: 以下に例を示します。

CREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)
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)


SELECT foo();  &#45;- fails since there is no default for the first argument

SELECT foo();  -- 最初の引数にデフォルトがないため失敗
ERROR:  function foo() does not exist

The <literal>=</literal> sign can also be used in place of the key word <literal>DEFAULT</literal>. =記号をDEFAULTキーワードの代わりに使用することもできます。

38.5.8. テーブルソースとしてのSQL関数 #

<title><acronym>SQL</acronym> Functions as Table Sources</title>

All SQL functions can be used in the <literal>FROM</literal> clause of a query, but it is particularly useful for functions returning composite types. If the function is defined to return a base type, the table function produces a one-column table. If the function is defined to return a composite type, the table function produces a column for each attribute of the composite type. すべてのSQL関数は問い合わせのFROM句で使用できますが、複合型を返す関数に特に便利です。 関数が基本型を返すよう定義されている場合、テーブル関数は1列からなるテーブルを作成します。 関数が複合型を返すよう定義されている場合、テーブル関数は複合型の列のそれぞれに対して1つの列を作成します。

Here is an example: 以下に例を示します。

CREATE TABLE foo (fooid int, foosubid int, fooname text);
INSERT INTO foo VALUES (1, 1, 'Joe');
INSERT INTO foo VALUES (1, 2, 'Ed');
INSERT INTO foo VALUES (2, 1, 'Mary');

CREATE FUNCTION getfoo(int) RETURNS foo AS $$
    SELECT * FROM foo WHERE fooid = $1;
$$ LANGUAGE SQL;

SELECT *, upper(fooname) FROM getfoo(1) AS t1;

 fooid | foosubid | fooname | upper
-------+----------+---------+-------
     1 |        1 | Joe     | JOE
(1 row)

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. 例からわかる通り、関数の結果の列を通常のテーブルの列と同じように扱うことができます。

Note that we only got one row out of the function. This is because we did not use <literal>SETOF</literal>. That is described in the next section. この関数の結果得られたのは1行のみであることに注意してください。 これはSETOFを指定しなかったためです。 これについては次節で説明します。

38.5.9. 集合を返すSQL関数 #

<title><acronym>SQL</acronym> Functions Returning Sets</title>

When an SQL function is declared as returning <literal>SETOF <replaceable>sometype</replaceable></literal>, the function's final query is executed to completion, and each row it outputs is returned as an element of the result set. SQL関数がSETOF sometypeを返すよう宣言されている場合、関数の最後の問い合わせは最後まで実行され、各出力行は結果集合の要素として返されます。

This feature is normally used when calling the function in the <literal>FROM</literal> clause. In this case each row returned by the function becomes a row of the table seen by the query. For example, assume that table <literal>foo</literal> has the same contents as above, and we say: この機能は通常、関数をFROM句内で呼び出す時に使用されます。 この場合、関数によって返される各行は、問い合わせによって見えるテーブルの行になります。 例えば、テーブルfooの内容が上記と同じであれば以下のようになります。

CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$
    SELECT * FROM foo WHERE fooid = $1;
$$ LANGUAGE SQL;

SELECT * FROM getfoo(1) AS t1;

Then we would get: この出力は以下の通りです。

 fooid | foosubid | fooname
-------+----------+---------
     1 |        1 | Joe
     1 |        2 | Ed
(2 rows)

It is also possible to return multiple rows with the columns defined by output parameters, like this: また、以下のように出力パラメータで定義された列を持つ複数の行を返すことも可能です。

CREATE TABLE tab (y int, z int);
INSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);

CREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)
RETURNS SETOF record
AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

SELECT * FROM sum_n_product_with_tab(10);
 sum | product
-----+---------
  11 |      10
  13 |      30
  15 |      50
  17 |      70
(4 rows)

The key point here is that you must write <literal>RETURNS SETOF record</literal> 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</type>. ここで重要な点は、関数が1行だけではなく複数行を返すことを示すためにRETURNS SETOF recordを記述しなければならない点です。 出力パラメータが1つしか存在しない場合は、recordではなく、そのパラメータの型を記述してください。

It is frequently useful to construct a query's result by invoking a set-returning function multiple times, with the parameters for each invocation coming from successive rows of a table or subquery. The preferred way to do this is to use the <literal>LATERAL</literal> key word, which is described in <xref linkend="queries-lateral"/>. Here is an example using a set-returning function to enumerate elements of a tree structure: 集合を返す関数を、それぞれの呼び出し時に連続するテーブル行または副問い合わせに由来するパラメータを付けて、複数回呼び出すことで問い合わせ結果を構築することはしばしば有用です。 お勧めする方法は、7.2.1.5で説明するLATERALキーワードを使用することです。 以下は集合を返す関数を使用して、ツリー構造の要素を模擬する例です。

SELECT * FROM nodes;
   name    | parent
-----------+--------
 Top       |
 Child1    | Top
 Child2    | Top
 Child3    | Top
 SubChild1 | Child1
 SubChild2 | Child1
(6 rows)

CREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$
    SELECT name FROM nodes WHERE parent = $1
$$ LANGUAGE SQL STABLE;

SELECT * FROM listchildren('Top');
 listchildren
--------------
 Child1
 Child2
 Child3
(3 rows)

SELECT name, child FROM nodes, LATERAL listchildren(name) AS child;
  name  |   child
--------+-----------
 Top    | Child1
 Top    | Child2
 Top    | Child3
 Child1 | SubChild1
 Child1 | SubChild2
(5 rows)

This example does not do anything that we couldn't have done with a simple join, but in more complex calculations the option to put some of the work into a function can be quite convenient. この例は単純な結合でできない何かを行うものではありません。 しかしより複雑な計算では、何らかの作業を関数内に押し込むオプションはかなり便利です。

Functions returning sets can also be called in the select list of a query. For each row that the query generates by itself, the set-returning function is invoked, and an output row is generated for each element of the function's result set. The previous example could also be done with queries like these: 集合を返す関数は問い合わせの選択リスト内でも呼び出すことができます。 問い合わせ自身によって生成する各行に対し、集合を返す関数が呼び出され、関数の結果集合の各要素に対して出力行が生成されます。 上の例は以下のような問い合わせでも実現できます。

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)

In the last <command>SELECT</command>, notice that no output row appears for <literal>Child2</literal>, <literal>Child3</literal>, etc. This happens because <function>listchildren</function> returns an empty set for those arguments, so no result rows are generated. This is the same behavior as we got from an inner join to the function result when using the <literal>LATERAL</literal> syntax. 最後のSELECTにおいて、Child2Child3などが出力行に表示されていないことに注意してください。 これは、listchildrenがこの入力に対して空の集合を返すため出力行が生成されないからです。 LATERAL構文を使用した時の関数の結果との内部結合から得る場合と同じ動作です。

<productname>PostgreSQL</productname>'s behavior for a set-returning function in a query's select list is almost exactly the same as if the set-returning function had been written in a <literal>LATERAL FROM</literal>-clause item instead. For example, 選択リストにある集合を返す関数に対するPostgreSQLの振舞いは、集合を返す関数がLATERAL FROM句に書かれている場合とほとんど同じです。 例えば

SELECT x, generate_series(1,5) AS g FROM tab;

is almost equivalent to は、以下とほぼ同じです。

SELECT x, g FROM tab, LATERAL generate_series(1,5) AS g;

It would be exactly the same, except that in this specific example, the planner could choose to put <structname>g</structname> on the outside of the nested-loop join, since <structname>g</structname> has no actual lateral dependency on <structname>tab</structname>. That would result in a different output row order. Set-returning functions in the select list are always evaluated as though they are on the inside of a nested-loop join with the rest of the <literal>FROM</literal> clause, so that the function(s) are run to completion before the next row from the <literal>FROM</literal> clause is considered. この特定の例では、gは実際にはtabにLATERALには依存しませんので、プランナがネステッドループ結合の外にgを置くことを選ぶかもしれないという点を除いて、全く同じです。 そのため、出力行の順番が異なる結果になるかもしれません。 選択リスト内の集合を返す関数は、FROM句からの次の行が考慮される前に関数の実行が完了するよう、FROM句の残りとのネステッドループ結合の中にあるかのように必ず評価されます。

If there is more than one set-returning function in the query's select list, the behavior is similar to what you get from putting the functions into a single <literal>LATERAL ROWS FROM( ... )</literal> <literal>FROM</literal>-clause item. For each row from the underlying query, there is an output row using the first result from each function, then an output row using the second result, and so on. If some of the set-returning functions produce fewer outputs than others, null values are substituted for the missing data, so that the total number of rows emitted for one underlying row is the same as for the set-returning function that produced the most outputs. Thus the set-returning functions run <quote>in lockstep</quote> until they are all exhausted, and then execution continues with the next underlying row. 問い合わせの選択リスト内に集合を返す関数が2つ以上ある場合には、振舞いは一つのLATERAL ROWS FROM( ... ) FROM句に関数を置いた場合に得られるものと似ています。 元となる問い合わせからの各行に対して、各関数からの最初の結果を使った出力行、2番目の結果を使った出力行、と続きます。 集合を返す関数の中に他のものより出力の数が少ないものがある場合には、欠けたデータの代わりにNULL値が使われますので、1つの元となる行から作られる行の合計の数は、一番多くの出力を出力する集合を返す関数に対するのと同じだけになります。 そのため、集合を返す関数はすべてが尽きるまで歩調を合わせて実行され、それから次の元となる行へと実行が続きます。

Set-returning functions can be nested in a select list, although that is not allowed in <literal>FROM</literal>-clause items. In such cases, each level of nesting is treated separately, as though it were a separate <literal>LATERAL ROWS FROM( ... )</literal> item. For example, in 集合を返す関数は、FROM句内では許されていませんが、選択リスト内では入れ子にできます。 その場合、入れ子の各階層は、別々のLATERAL ROWS FROM( ... )であるかのように別々に扱われます。 例えば、

SELECT srf1(srf2(x), srf3(y)), srf4(srf5(z)) FROM tab;

the set-returning functions <function>srf2</function>, <function>srf3</function>, and <function>srf5</function> would be run in lockstep for each row of <structname>tab</structname>, and then <function>srf1</function> and <function>srf4</function> would be applied in lockstep to each row produced by the lower functions. では、集合を返す関数srf2srf3srf5tabの各行に対して歩調を合わせて実行され、次に階層の低い関数が生成した各行に対してsrf1srf4が歩調を合わせて適用されます。

Set-returning functions cannot be used within conditional-evaluation constructs, such as <literal>CASE</literal> or <literal>COALESCE</literal>. For example, consider 集合を返す関数はCASECOALESCEのような条件を評価する構成の中では使えません。 例えば、次のように考えてみてください。

SELECT x, CASE WHEN x > 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;

It might seem that this should produce five repetitions of input rows that have <literal>x &gt; 0</literal>, and a single repetition of those that do not; but actually, because <function>generate_series(1, 5)</function> would be run in an implicit <literal>LATERAL FROM</literal> item before the <literal>CASE</literal> expression is ever evaluated, it would produce five repetitions of every input row. To reduce confusion, such cases produce a parse-time error instead. これは、x > 0である入力行の5回の繰り返しとそうでないものの1回の繰り返しを生成するように思えるかもしれません。しかし、実際には、generate_series(1, 5)CASEが評価される前に暗黙のLATERAL FROMの中で実行されますので、各入力行に対して5回の繰り返しを生成します。 混乱を減らすため、そのような場合にはその代わりに解析時エラーになります。

注記

If a function's last command is <command>INSERT</command>, <command>UPDATE</command>, or <command>DELETE</command> with <literal>RETURNING</literal>, that command will always be executed to completion, even if the function is not declared with <literal>SETOF</literal> or the calling query does not fetch all the result rows. Any extra rows produced by the <literal>RETURNING</literal> clause are silently dropped, but the commanded table modifications still happen (and are all completed before returning from the function). もし関数の最後のコマンドがRETURNINGを持つINSERTUPDATE、またはDELETEである場合、関数がSETOF付きで宣言されていない、または呼び出す問い合わせがすべての結果行を取り出さなくても、そのコマンドは完了まで実行されます。 RETURNING句で生成される余計な行はすべて警告無しに削除されますが、コマンド対象のテーブルの変更はそれでも起こります(そして、関数から戻る前にすべて完了します)。

注記

Before <productname>PostgreSQL</productname> 10, putting more than one set-returning function in the same select list did not behave very sensibly unless they always produced equal numbers of rows. Otherwise, what you got was a number of output rows equal to the least common multiple of the numbers of rows produced by the set-returning functions. Also, nested set-returning functions did not work as described above; instead, a set-returning function could have at most one set-returning argument, and each nest of set-returning functions was run independently. Also, conditional execution (set-returning functions inside <literal>CASE</literal> etc.) was previously allowed, complicating things even more. Use of the <literal>LATERAL</literal> syntax is recommended when writing queries that need to work in older <productname>PostgreSQL</productname> versions, because that will give consistent results across different versions. If you have a query that is relying on conditional execution of a set-returning function, you may be able to fix it by moving the conditional test into a custom set-returning function. For example, PostgreSQL 10より前では、集合を返す関数を2つ以上同じ選択リストに置くと常に等しい数の行を生成しない限りあまり賢くは振舞いませんでした。 そうでなければ、得られるのは、集合を返す関数が生成する行の数の最小公倍数に等しい数の出力行でした。 また、入れ子の集合を返す関数は上に書いたようには動作しませんでした。代わりに、集合を返す関数は多くても1つの集合を返す引数を持ち、集合を返す関数の各入れ子は独立に実行されました。 また、条件実行(CASE等の内側にある集合を返す関数)は以前は認められており、事態をより複雑にしていました。 PostgreSQLの古いバージョンで動作が必要な問い合わせを書く場合には、バージョンが異なっても一貫した結果を返しますので、LATERAL構文を使うことを勧めます。 集合を返す関数の条件実行に頼った問い合わせがあるのなら、条件確認を独自の集合を返す関数の中に移動することで修正できます。 例えば

SELECT x, CASE WHEN y > 0 THEN generate_series(1, z) ELSE 5 END FROM tab;

could become は、以下のようになります。

CREATE FUNCTION case_generate_series(cond bool, start int, fin int, els int)
  RETURNS SETOF int AS $$
BEGIN
  IF cond THEN
    RETURN QUERY SELECT generate_series(start, fin);
  ELSE
    RETURN QUERY SELECT els;
  END IF;
END$$ LANGUAGE plpgsql;

SELECT x, case_generate_series(y > 0, 1, z, 5) FROM tab;

This formulation will work the same in all versions of <productname>PostgreSQL</productname>. この定式化はPostgreSQLのバージョンすべてで同じように動作します。

38.5.10. TABLEを返すSQL関数 #

<title><acronym>SQL</acronym> Functions Returning <literal>TABLE</literal></title>

There is another way to declare a function as returning a set, which is to use the syntax <literal>RETURNS TABLE(<replaceable>columns</replaceable>)</literal>. This is equivalent to using one or more <literal>OUT</literal> parameters plus marking the function as returning <literal>SETOF record</literal> (or <literal>SETOF</literal> 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</literal>. 集合を返すものとして関数を宣言するには、他にも方法があります。 RETURNS TABLE(columns)構文を使用することです。 これは1つ以上のOUTパラメータを使い、さらに、関数をSETOF record(または、適切ならば単一の出力パラメータの型のSETOF)を返すものと印を付けることと等価です。 この記法は標準SQLの最近の版で規定されたものですので、SETOFを使用するより移植性がより高いかもしれません。

For example, the preceding sum-and-product example could also be done this way: 例えば前述の合計と積の例はこのように書けます。

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

It is not allowed to use explicit <literal>OUT</literal> or <literal>INOUT</literal> parameters with the <literal>RETURNS TABLE</literal> notation &mdash; you must put all the output columns in the <literal>TABLE</literal> list. RETURNS TABLE記法と一緒に、明示的OUTまたはINOUTパラメータは使用できません。 すべての出力列をTABLEリストに含めなければなりません。

38.5.11. 多様SQL関数 #

<title>Polymorphic <acronym>SQL</acronym> Functions</title>

<acronym>SQL</acronym> functions can be declared to accept and return the polymorphic types described in <xref linkend="extend-types-polymorphic"/>. Here is a polymorphic function <function>make_array</function> that builds up an array from two arbitrary data type elements: SQL関数は、38.2.5の多様型を受け付け、返すように宣言できます。 以下のmake_array多様関数は、任意の2つのデータ型要素から配列を作成します。

CREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$
    SELECT ARRAY[$1, $2];
$$ LANGUAGE SQL;

SELECT make_array(1, 2) AS intarray, make_array('a'::text, 'b') AS textarray;
 intarray | textarray
----------+-----------
 {1,2}    | {a,b}
(1 row)

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: 'a'::textという型キャストを使用して、引数がtext型であることを指定していることに注目してください。 これは引数が単なる文字列リテラルである場合に必要です。 さもないと、unknown型として扱われてしまうため、無効なunknownの配列を返そうとしてしまいます。 型キャストがないと、以下のようなエラーが発生します。

ERROR:  could not determine polymorphic type because input has type unknown

With <function>make_array</function> declared as above, you must provide two arguments that are of exactly the same data type; the system will not attempt to resolve any type differences. Thus for example this does not work: 上記のようにmake_arrayを宣言した場合、まったく同じデータ型の2つの引数を指定する必要があります。 システムは型の違いを解決しようとしません。 したがって、例えばこれはうまくいきません。

SELECT make_array(1, 2.5) AS numericarray;
ERROR:  function make_array(integer, numeric) does not exist

An alternative approach is to use the <quote>common</quote> family of polymorphic types, which allows the system to try to identify a suitable common type: 別の方法として、共通族の多様型を使用する方法があります。 これにより、システムは適切な共通の型を特定できます。

CREATE FUNCTION make_array2(anycompatible, anycompatible)
RETURNS anycompatiblearray AS $$
    SELECT ARRAY[$1, $2];
$$ LANGUAGE SQL;

SELECT make_array2(1, 2.5) AS numericarray;
 numericarray
--------------
 {1,2.5}
(1 row)

Because the rules for common type resolution default to choosing type <type>text</type> when all inputs are of unknown types, this also works: すべての入力が未知の型である場合、共通の型を解決するルールはデフォルトでtext型を選択するので、これも動作します。

SELECT make_array2('a', 'b') AS textarray;
 textarray
-----------
 {a,b}
(1 row)

It is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example: 固定の戻り値型を持ちながら多様引数を持つことは許されますが、逆は許されません。 以下に例を示します。

CREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$
    SELECT $1 > $2;
$$ LANGUAGE SQL;

SELECT is_greater(1, 2);
 is_greater
------------
 f
(1 row)

CREATE FUNCTION invalid_func() RETURNS anyelement AS $$
    SELECT 1;
$$ LANGUAGE SQL;
ERROR:  cannot determine result data type
DETAIL:  A result of type anyelement requires at least one input of type anyelement, anyarray, anynonarray, anyenum, or anyrange.

Polymorphism can be used with functions that have output arguments. For example: 出力引数を持つ関数でも多様性を使用できます。 以下に例を示します。

CREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)
AS 'select $1, array[$1,$1]' LANGUAGE SQL;

SELECT * FROM dup(22);
 f2 |   f3
----+---------
 22 | {22,22}
(1 row)

Polymorphism can also be used with variadic functions. For example: 多様性はvariadic関数とともに使用できます。例をあげます。

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)

CREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$
    SELECT array_to_string($2, $1);
$$ LANGUAGE SQL;

SELECT concat_values('|', 1, 4, 2);
 concat_values
---------------
 1|4|2
(1 row)

38.5.12. 照合順序を持つSQL関数 #

<title><acronym>SQL</acronym> Functions with Collations</title>

When an 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> function described above, the result of SQL関数が照合順序の変更が可能なデータ型のパラメータを1つ以上持つ場合、24.2で説明されているように、それぞれの関数呼び出しに対して、実引数に割り当てられた照合順序に応じて、照合順序が識別されます。 照合順序の識別に成功した(つまり、暗黙的な照合順序がすべての引数で競合しない)場合、すべての照合順序の変更が可能なパラメータは暗黙的に照合順序を持つものとして扱われます。 これは関数内の照合順序に依存する操作の振舞いに影響します。 例えば、上記のanyleastを使って考えます。

SELECT anyleast('abc'::text, 'ABC');

will depend on the database's default collation. In <literal>C</literal> locale the result will be <literal>ABC</literal>, but in many other locales it will be <literal>abc</literal>. The collation to use can be forced by adding a <literal>COLLATE</literal> clause to any of the arguments, for example この結果はデータベースのデフォルト照合順序に依存します。 CロケールではABCという結果になりますが、他の多くのロケールではabcになります。 使用される照合順序をCOLLATE句を付与することで強制できます。 例を以下に示します。

SELECT anyleast('abc'::text, 'ABC' COLLATE "C");

Alternatively, if you wish a function to operate with a particular collation regardless of what it is called with, insert <literal>COLLATE</literal> clauses as needed in the function definition. This version of <function>anyleast</function> would always use <literal>en_US</literal> locale to compare strings: この他、呼び出し元の照合順序とは関係なく特定の照合順序で動作する関数にしたければ、関数定義において必要な所にCOLLATE句を付けてください。 以下のanyleastでは、文字列を比較する際に常にen_USを使用します。

CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
    SELECT min($1[i] COLLATE "en_US") FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;

But note that this will throw an error if applied to a non-collatable data type. しかし、もし照合順序の変更ができないデータ型が与えられた場合にエラーになってしまうことに注意してください。

If no common collation can be identified among the actual arguments, then an 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). 実引数全体で共通の照合順序を識別できない場合、SQL関数はパラメータがそのデータ型のデフォルト照合順序(通常はデータベースのデフォルトの照合順序ですが、ドメイン型のパラメータでは異なる可能性があります)を持つものとみなします。

The behavior of collatable parameters can be thought of as a limited form of polymorphism, applicable only to textual data types. 照合順序の変更ができるパラメータの動作は、テキストのデータ型にのみ適用できる、限定された多様性と考えることができます。