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

CREATE FUNCTION

CREATE FUNCTION <refpurpose>define a new function</refpurpose> — 新しい関数を定義する

概要

CREATE [ OR REPLACE ] FUNCTION
    name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [, ...] ] )
    [ RETURNS rettype
      | RETURNS TABLE ( column_name column_type [, ...] ) ]
  { LANGUAGE lang_name
    | TRANSFORM { FOR TYPE type_name } [, ... ]
    | WINDOW
    | { IMMUTABLE | STABLE | VOLATILE }
    | [ NOT ] LEAKPROOF
    | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT }
    | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER }
    | PARALLEL { UNSAFE | RESTRICTED | SAFE }
    | COST execution_cost
    | ROWS result_rows
    | SUPPORT support_function
    | SET configuration_parameter { TO value | = value | FROM CURRENT }
    | AS 'definition'
    | AS 'obj_file', 'link_symbol'
    | sql_body
  } ...

説明

<title>Description</title>

<command>CREATE FUNCTION</command> defines a new function. <command>CREATE OR REPLACE FUNCTION</command> will either create a new function, or replace an existing definition. To be able to define a function, the user must have the <literal>USAGE</literal> privilege on the language. CREATE FUNCTIONは新しい関数を定義します。 CREATE OR REPLACE FUNCTIONは、新しい関数の作成、または、既存定義の置換のどちらかを行います。 関数を定義するには、ユーザはその言語のUSAGE権限が必要です。

If a schema name is included, then the function is created in the specified schema. Otherwise it is created in the current schema. The name of the new function must not match any existing function or procedure with the same input argument types in the same schema. However, functions and procedures of different argument types can share a name (this is called <firstterm>overloading</firstterm>). スキーマ名が含まれている場合、関数は指定されたスキーマに作成されます。 スキーマ名がなければ、関数は現在のスキーマに作成されます。 同じスキーマ内の同じ入力引数データ型を持つ既存の関数またはプロシージャの名前は、新しい関数の名前として使用できません。 しかし、異なる引数データ型を持つ関数やプロシージャであれば、名前が重複しても構いません (これを、オーバーロードと言います)。

To replace the current definition of an existing function, use <command>CREATE OR REPLACE FUNCTION</command>. It is not possible to change the name or argument types of a function this way (if you tried, you would actually be creating a new, distinct function). Also, <command>CREATE OR REPLACE FUNCTION</command> will not let you change the return type of an existing function. To do that, you must drop and recreate the function. (When using <literal>OUT</literal> parameters, that means you cannot change the types of any <literal>OUT</literal> parameters except by dropping the function.) 既存の関数定義を入れ替えるには、CREATE OR REPLACE FUNCTIONを使用してください。 この方法では関数の名前や引数の型を変更することはできません (これを行った場合、新しく別の関数が作成されます)。 また、CREATE OR REPLACE FUNCTIONでは、既存の関数の戻り値の型を変更することはできません。 戻り値の型を変更したい場合は、その関数を削除し、再度作成してください。 (これは、OUTパラメータを使用している場合、関数を削除しない限りOUTパラメータの型を変更できないことを意味します。)

When <command>CREATE OR REPLACE FUNCTION</command> is used to replace an existing function, the ownership and permissions of the function do not change. All other function properties are assigned the values specified or implied in the command. You must own the function to replace it (this includes being a member of the owning role). CREATE OR REPLACE FUNCTIONを使用して既存の関数を置き換える場合、関数の所有者と権限は変わりません。 他の関数に関するすべての属性には、そのコマンドで指定された値、または暗黙的な値が設定されます。 関数を置き換えるためにはその関数を所有していなければなりません。 (これには所有するロールのメンバであることが含まれています。)

If you drop and then recreate a function, the new function is not the same entity as the old; you will have to drop existing rules, views, triggers, etc. that refer to the old function. Use <command>CREATE OR REPLACE FUNCTION</command> to change a function definition without breaking objects that refer to the function. Also, <command>ALTER FUNCTION</command> can be used to change most of the auxiliary properties of an existing function. 関数を削除し再作成した場合、新しい関数は古いものと同じ実体にはなりません。 古い関数を参照する、既存のルール、ビュー、トリガなどを削除しなければならないでしょう。 関数を参照するオブジェクトを破壊せずに関数定義を変更するには、CREATE OR REPLACE FUNCTIONを使用してください。 また、ALTER FUNCTIONを使用して、既存の関数の補助属性のほとんどを変更することができます。

The user that creates the function becomes the owner of the function. 関数を作成したユーザが、その関数の所有者となります。

To be able to create a function, you must have <literal>USAGE</literal> privilege on the argument types and the return type. 関数を作成するためには、引数の型および戻り値の型に対するUSAGE権限を持たなければなりません。

Refer to <xref linkend="xfunc"/> for further information on writing functions. さらに詳しい関数の作成方法については38.3を参照してください。

パラメータ

<title>Parameters</title>
name

The name (optionally schema-qualified) of the function to create. 作成する関数の名前です(スキーマ修飾名も可)。

argmode

The mode of an argument: <literal>IN</literal>, <literal>OUT</literal>, <literal>INOUT</literal>, or <literal>VARIADIC</literal>. If omitted, the default is <literal>IN</literal>. Only <literal>OUT</literal> arguments can follow a <literal>VARIADIC</literal> one. Also, <literal>OUT</literal> and <literal>INOUT</literal> arguments cannot be used together with the <literal>RETURNS TABLE</literal> notation. 引数のモードで、INOUTINOUTVARIADICのいずれかです。 省略時のデフォルトはINです。 OUT引数のみがVARIADICの後に続けることができます。 また、RETURNS TABLE記法では、OUTINOUT引数の両方を使用することはできません。

argname

The name of an argument. Some languages (including SQL and PL/pgSQL) let you use the name in the function body. For other languages the name of an input argument is just extra documentation, so far as the function itself is concerned; but you can use input argument names when calling a function to improve readability (see <xref linkend="sql-syntax-calling-funcs"/>). In any case, the name of an output argument is significant, because it defines the column name in the result row type. (If you omit the name for an output argument, the system will choose a default column name.) 引数の名前です。 (SQLおよびPL/pgSQLを含む)言語の中にはこの名前を関数本体で使用できるものもあります。 他の言語では、関数そのものに注目する限り、入力引数の名前は単なる追加ドキュメントとして扱われます。 しかし関数呼び出し時に入力引数の名前を使用することで可読性を高めることができます。 (4.3参照) どのような場合であっても、出力引数の名前は、結果の行型の列名となりますので重要です。 (出力引数の名前を省略した場合、システムはデフォルトの列名を付与します。)

argtype

The data type(s) of the function's arguments (optionally schema-qualified), if any. The argument types can be base, composite, or domain types, or can reference the type of a table column. 関数の引数のデータ型です(スキーマ修飾名も可)。 基本データ型、複合データ型、ドメイン型、または、テーブル列の型の参照を使用することができます。

Depending on the implementation language it might also be allowed to specify <quote>pseudo-types</quote> such as <type>cstring</type>. Pseudo-types indicate that the actual argument type is either incompletely specified, or outside the set of ordinary SQL data types. また、実装する言語に依存しますが、cstringといった疑似型を指定できる場合もあります。 疑似型は、実引数の型の指定が不完全である、もしくは、通常のSQLデータ型の集合を越えていることを示します。

The type of a column is referenced by writing <literal><replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable>%TYPE</literal>. Using this feature can sometimes help make a function independent of changes to the definition of a table. 列の型を参照するには、table_name.column_name%TYPEと記述します。 これを使用すると、テーブル定義が変更されても関数が影響を受けないようにするのに役に立つことがあります。

default_expr

An expression to be used as default value if the parameter is not specified. The expression has to be coercible to the argument type of the parameter. Only input (including <literal>INOUT</literal>) parameters can have a default value. All input parameters following a parameter with a default value must have default values as well. パラメータが指定されなかった場合のデフォルト値として使用される式です。 この式はパラメータの引数型と変換可能でなければなりません。 入力パラメータ(INOUTを含みます)のみがデフォルト値を持つことができます。 デフォルト値を持つパラメータの後ろにあるパラメータはすべて、同様にデフォルト値を持たなければなりません。

rettype

The return data type (optionally schema-qualified). The return type can be a base, composite, or domain type, or can reference the type of a table column. Depending on the implementation language it might also be allowed to specify <quote>pseudo-types</quote> such as <type>cstring</type>. If the function is not supposed to return a value, specify <type>void</type> as the return type. 関数が返すデータの型です(スキーマ修飾名も可)。 基本型、複合型、ドメイン型、または、テーブル列の型の参照を設定することができます。 また、実装している言語によりますが、cstringのような疑似型も指定することが可能です。 その関数が値を返すことを想定していない場合は、戻り値としてvoidを指定してください。

When there are <literal>OUT</literal> or <literal>INOUT</literal> parameters, the <literal>RETURNS</literal> clause can be omitted. If present, it must agree with the result type implied by the output parameters: <literal>RECORD</literal> if there are multiple output parameters, or the same type as the single output parameter. OUTもしくはINOUTパラメータが存在する場合、RETURNS句を省略することができます。 省略しない場合は、出力用パラメータが意味する結果型に従ったもの、つまり、複数の出力用パラメータがあればRECORD、単一の出力用パラメータであればそれと同じ型、でなければなりません。

The <literal>SETOF</literal> modifier indicates that the function will return a set of items, rather than a single item. SETOF修飾子は、その関数が、1つではなく複数のアイテムの集合を返すことを示します。

The type of a column is referenced by writing <literal><replaceable class="parameter">table_name</replaceable>.<replaceable class="parameter">column_name</replaceable>%TYPE</literal>. 列の型は、table_name.column_name%TYPEと記述することで参照されます。

column_name

The name of an output column in the <literal>RETURNS TABLE</literal> syntax. This is effectively another way of declaring a named <literal>OUT</literal> parameter, except that <literal>RETURNS TABLE</literal> also implies <literal>RETURNS SETOF</literal>. RETURNS TABLE構文における出力列の名前です。 これは実際名前付けされたOUTパラメータを宣言する別の方法ですが、RETURNS TABLERETURNS SETOFをも意味する点が異なります。

column_type

The data type of an output column in the <literal>RETURNS TABLE</literal> syntax. RETURNS TABLE構文における出力列のデータ型です。

lang_name

The name of the language that the function is implemented in. It can be <literal>sql</literal>, <literal>c</literal>, <literal>internal</literal>, or the name of a user-defined procedural language, e.g., <literal>plpgsql</literal>. The default is <literal>sql</literal> if <replaceable class="parameter">sql_body</replaceable> is specified. Enclosing the name in single quotes is deprecated and requires matching case. 関数を実装している言語の名前です。 このパラメータには、sqlcinternal、もしくはユーザ定義手続き言語(例:plpgsql)の名前を指定可能です。 sql_bodyが指定されていれば、デフォルトはsqlです。 名前を単一引用符で囲むのは廃止予定で、大文字小文字の一致が必要になります。

TRANSFORM { FOR TYPE type_name } [, ... ] }

Lists which transforms a call to the function should apply. Transforms convert between SQL types and language-specific data types; see <xref linkend="sql-createtransform"/>. Procedural language implementations usually have hardcoded knowledge of the built-in types, so those don't need to be listed here. If a procedural language implementation does not know how to handle a type and no transform is supplied, it will fall back to a default behavior for converting data types, but this depends on the implementation. 関数呼び出しにどの変換を適用すべきかのリストです。 変換はSQLの型と言語独自のデータ型の間の変換を行います(CREATE TRANSFORMを参照)。 手続言語の実装では、通常、ビルトインの型についてハードコードされた知識があるので、それらをこのリストに含める必要はありません。 手続言語の実装が型の処理について定めておらず、変換が提供されない場合は、データ型変換のデフォルトの動作によることになりますが、これは実装に依存します。

WINDOW
<para><literal>WINDOW</literal> indicates that the function is a <firstterm>window function</firstterm> rather than a plain function. This is currently only useful for functions written in C. The <literal>WINDOW</literal> attribute cannot be changed when replacing an existing function definition.

WINDOWは、この関数が普通の関数ではなくウィンドウ関数であることを示します。 現在これはC言語で作成した関数のみに使用することができます。 既存の関数定義を置き換える場合、WINDOW属性を変更することはできません。

IMMUTABLE
STABLE
VOLATILE

These attributes inform the query optimizer about the behavior of the function. At most one choice can be specified. If none of these appear, <literal>VOLATILE</literal> is the default assumption. これらの属性は、関数の動作に関する情報を問い合わせオプティマイザに提供します。 いずれか1つのキーワードのみ指定できます。 指定がない場合は、デフォルトでVOLATILEと解釈されます。

<para><literal>IMMUTABLE</literal> indicates that the function cannot modify the database and always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use information not directly present in its argument list. If this option is given, any call of the function with all-constant arguments can be immediately replaced with the function value.

IMMUTABLEは、関数がデータベースに対する変更を行わないこと、および、その関数に同じ引数値を与えた場合に常に同じ結果を返すことを示します。 つまり、データベースを検索したり、引数リスト中に直接存在しない情報を使用したりしないということです。 このオプションが指定された場合、引数が全て定数である関数呼び出しは、即座に関数値と置き換えることができます。

<para><literal>STABLE</literal> indicates that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same argument values, but that its result could change across SQL statements. This is the appropriate selection for functions whose results depend on database lookups, parameter variables (such as the current time zone), etc. (It is inappropriate for <literal>AFTER</literal> triggers that wish to query rows modified by the current command.) Also note that the <function>current_timestamp</function> family of functions qualify as stable, since their values do not change within a transaction.

STABLEは、関数がデータベースに対する変更を行わないこと、および、1つのテーブルスキャン内でその関数に同じ引数値を与えた場合、常に同じ結果を返すが、SQL文が異なると結果が変わってしまう可能性があることを示します。 これは、データベース検索や(現在の時間帯のような)パラメータ変数などに結果が依存する関数に適します。 (これは現在のコマンドで変更された行を問い合わせたいAFTERトリガには不適切です。) また、current_timestamp系の関数は、1つのトランザクション内では値が変化しないため、STABLEであることに注意してください。

<para><literal>VOLATILE</literal> indicates that the function value can change even within a single table scan, so no optimizations can be made. Relatively few database functions are volatile in this sense; some examples are <literal>random()</literal>, <literal>currval()</literal>, <literal>timeofday()</literal>. But note that any function that has side-effects must be classified volatile, even if its result is quite predictable, to prevent calls from being optimized away; an example is <literal>setval()</literal>.

VOLATILEは、1つのテーブルスキャン内でも関数の値が変化する可能性があるため、最適化できないことを示します。 このような意味で変動的(volatile)なデータベース関数は、比較的少数です。 例えば、random()currval()timeofday()などは変動的な関数です。 しかし、例えばsetval()などの副作用がある関数は、その結果を完全に予測できるとしても、呼び出しを最適化しないよう、VOLATILE(変動的)に分類する必要があることに注意してください。

For additional details see <xref linkend="xfunc-volatility"/>. 詳細は38.7を参照してください。

LEAKPROOF

<literal>LEAKPROOF</literal> indicates that the function has no side effects. It reveals no information about its arguments other than by its return value. For example, a function which throws an error message for some argument values but not others, or which includes the argument values in any error message, is not leakproof. This affects how the system executes queries against views created with the <literal>security_barrier</literal> option or tables with row level security enabled. The system will enforce conditions from security policies and security barrier views before any user-supplied conditions from the query itself that contain non-leakproof functions, in order to prevent the inadvertent exposure of data. Functions and operators marked as leakproof are assumed to be trustworthy, and may be executed before conditions from security policies and security barrier views. In addition, functions which do not take arguments or which are not passed any arguments from the security barrier view or table do not have to be marked as leakproof to be executed before security conditions. See <xref linkend="sql-createview"/> and <xref linkend="rules-privileges"/>. This option can only be set by the superuser. LEAKPROOFは、関数が副作用を持たないことを示します。 その引数に関する情報を戻り値以外で漏らしません。 例えば、一部の引数値に対してのみエラーメッセージを返す関数や何らかのエラーメッセージの中に引数の値を含める関数は漏洩防止(leakproof)とはいえません。 これはsecurity_barrierオプション付きで作成されたビュー、あるいは行単位セキュリティが有効にされたテーブルに対して、システムが問い合わせを実行する方法に影響します。 データが偶然に露見することを防ぐため、システムは、漏洩防止でない関数を含む問い合わせのユーザが提供した条件より前に、セキュリティポリシーおよびセキュリティバリアビューの条件を強制します。 漏洩防止であるとされた関数および演算子は信頼できると見なされ、セキュリティポリシーおよびセキュリティバリアビューによる条件より先に実行されることがあります。 なお、引数を取らない、あるいはセキュリティバリアビューやテーブルから引数を渡されない関数は、セキュリティ条件より前に実行するために漏洩防止とする必要はありません。 CREATE VIEWおよび41.5を参照してください。 このオプションはスーパーユーザによってのみ設定することができます。

CALLED ON NULL INPUT
RETURNS NULL ON NULL INPUT
STRICT
<para><literal>CALLED ON NULL INPUT</literal> (the default) indicates that the function will be called normally when some of its arguments are null. It is then the function author's responsibility to check for null values if necessary and respond appropriately.

CALLED ON NULL INPUT(デフォルト)を指定すると、引数にNULLが含まれていても、関数が通常通り呼び出されます。 その場合は、必要に応じてNULL値を確認し、適切な対応をすることは関数作成者の責任です。

<para><literal>RETURNS NULL ON NULL INPUT</literal> or <literal>STRICT</literal> indicates that the function always returns null whenever any of its arguments are null. If this parameter is specified, the function is not executed when there are null arguments; instead a null result is assumed automatically.

RETURNS NULL ON NULL INPUTもしくはSTRICTを指定すると、関数の引数に1つでもNULLがある場合、常にNULLを返します。 このパラメータが指定されると、NULL引数がある場合、関数は実行されません。 代わりに、NULLという結果が自動的に与えられます。

[EXTERNAL] SECURITY INVOKER
[EXTERNAL] SECURITY DEFINER
<para><literal>SECURITY INVOKER</literal> indicates that the function is to be executed with the privileges of the user that calls it. That is the default. <literal>SECURITY DEFINER</literal> specifies that the function is to be executed with the privileges of the user that owns it. For information on how to write <literal>SECURITY DEFINER</literal> functions safely, <link linkend="sql-createfunction-security">see below</link>.

SECURITY INVOKERを指定すると、関数を呼び出したユーザの権限で、その関数が実行されます。 これがデフォルトです。 SECURITY DEFINERを指定すると、関数を所有するユーザの権限で、その関数が実行されます。 SECURITY DEFINER関数を安全に書く方法については、以下を参照してください

The key word <literal>EXTERNAL</literal> is allowed for SQL conformance, but it is optional since, unlike in SQL, this feature applies to all functions not only external ones. EXTERNALキーワードは、SQLとの互換性を保つために許されています。 しかし、SQLとは異なり、この機能は外部関数だけではなくすべての関数に適用されるため、このキーワードは省略可能です。

PARALLEL
<para><literal>PARALLEL UNSAFE</literal> indicates that the function can't be executed in parallel mode and the presence of such a function in an SQL statement forces a serial execution plan. This is the default. <literal>PARALLEL RESTRICTED</literal> indicates that the function can be executed in parallel mode, but the execution is restricted to parallel group leader. <literal>PARALLEL SAFE</literal> indicates that the function is safe to run in parallel mode without restriction.

PARALLEL UNSAFEは、その関数が並列モードでは実行できないこと、そしてそのような関数がSQL文の中にある場合は順次の実行プランが強制されることを意味します。 これがデフォルトです。 PARALLEL RESTRICTEDはその関数が並列モードで実行できますが、その実行は並列グループのリーダーに制限されることを意味します。 PARALLEL SAFEはその関数が並列モードで制限なく実行することについて安全であることを意味します。

Functions should be labeled parallel unsafe if they modify any database state, or if they make changes to the transaction such as using sub-transactions, or if they access sequences or attempt to make persistent changes to settings (e.g., <literal>setval</literal>). They should be labeled as parallel restricted if they access temporary tables, client connection state, cursors, prepared statements, or miscellaneous backend-local state which the system cannot synchronize in parallel mode (e.g., <literal>setseed</literal> cannot be executed other than by the group leader because a change made by another process would not be reflected in the leader). In general, if a function is labeled as being safe when it is restricted or unsafe, or if it is labeled as being restricted when it is in fact unsafe, it may throw errors or produce wrong answers when used in a parallel query. C-language functions could in theory exhibit totally undefined behavior if mislabeled, since there is no way for the system to protect itself against arbitrary C code, but in most likely cases the result will be no worse than for any other function. If in doubt, functions should be labeled as <literal>UNSAFE</literal>, which is the default. 関数がデータベースの状態に何らかの変更を行う、サブトランザクションを使うなどトランザクションを変更する、シーケンスにアクセスするか設定に恒久的な変更をする(例えばsetval)という場合はparallel unsafe(並列は安全でない)という印をつけるべきです。 一時テーブル、クライアントの接続状態、カーソル、プリペアド文、その他並列モードでシステムが同期できない様々なバックエンド独自の状態に関数がアクセスする場合、parallel restricted(並列は制限される)という印をつけるべきです(例えば、setseedはグループのリーダー以外では実行できません。なぜなら他のプロセスでなされた変更がリーダーに反映されないからです)。 一般的に、restrictedあるいはunsafeな関数がsafeとラベル付けされた場合、あるいはunsafeな関数がrestrictedとラベル付けされた場合、それがパラレルクエリ内で使用されると、エラーが発生したり、誤った結果が生成されたりします。 C言語の関数は、ラベルが間違っていると、理論的には全く予想できない動作をすることがあります。 これは任意のCプログラムに対してシステムが自分を保護する手段がないからですが、多くの場合、その結果は他の関数と同程度の悪さでしょう。 よくわからない場合は、デフォルトのUNSAFEで関数にラベル付けしてください。

COST execution_cost

A positive number giving the estimated execution cost for the function, in units of <xref linkend="guc-cpu-operator-cost"/>. If the function returns a set, this is the cost per returned row. If the cost is not specified, 1 unit is assumed for C-language and internal functions, and 100 units for functions in all other languages. Larger values cause the planner to try to avoid evaluating the function more often than necessary. この関数の推定実行コストを表す正数で、単位はcpu_operator_costです。 関数が集合を返す場合、これは1行当たりのコストとなります。 このコストが指定されない場合、C言語および内部関数では1、他のすべての言語では100となります。 値をより大きくすると、プランナは必要以上に頻繁に関数を評価しないようになります。

ROWS result_rows

A positive number giving the estimated number of rows that the planner should expect the function to return. This is only allowed when the function is declared to return a set. The default assumption is 1000 rows. プランナが想定する、この関数が返す行数の推定値を表す正数です。 これは、関数が集合を返すものと宣言された場合のみ使用可能です。 デフォルト推定値は1000行です。

SUPPORT support_function

The name (optionally schema-qualified) of a <firstterm>planner support function</firstterm> to use for this function. See <xref linkend="xfunc-optimization"/> for details. You must be superuser to use this option. この関数のために使うプランナサポート関数の名前です(スキーマ修飾名も可)。 詳細は38.11を参照してください。 このオプションを使うにはスーパーユーザでなければなりません。

configuration_parameter
value

The <literal>SET</literal> clause causes the specified configuration parameter to be set to the specified value when the function is entered, and then restored to its prior value when the function exits. <literal>SET FROM CURRENT</literal> saves the value of the parameter that is current when <command>CREATE FUNCTION</command> is executed as the value to be applied when the function is entered. SET句により、関数が始まった時に指定した設定パラメータを指定した値に設定し、関数の終了時にそれを以前の値に戻すことができます。 SET FROM CURRENTは、CREATE FUNCTIONの実行時点でのパラメータ値を、関数に入る時に適用する値として保管します。

If a <literal>SET</literal> clause is attached to a function, then the effects of a <command>SET LOCAL</command> command executed inside the function for the same variable are restricted to the function: the configuration parameter's prior value is still restored at function exit. However, an ordinary <command>SET</command> command (without <literal>LOCAL</literal>) overrides the <literal>SET</literal> clause, much as it would do for a previous <command>SET LOCAL</command> command: the effects of such a command will persist after function exit, unless the current transaction is rolled back. 関数にSET句が付いている場合、関数内部で実行されるSET LOCALコマンドの同一変数に対する効果はその関数に制限されます。 つまり、設定パラメータの前の値は関数が終了する時に元に戻ります。 しかし、通常の(LOCALがない)SETコマンドはSET句を上書きします。 これは過去に行われたSET LOCALコマンドに対してもほぼ同じです。 つまり、このコマンドの効果は、現在のトランザクションがロールバックされない限り、関数が終了した後も永続化されます。

See <xref linkend="sql-set"/> and <xref linkend="runtime-config"/> for more information about allowed parameter names and values. 使用可能なパラメータと値については、SETおよび第20章を参照してください。

definition

A string constant defining the function; the meaning depends on the language. It can be an internal function name, the path to an object file, an SQL command, or text in a procedural language. 関数を定義する文字列定数です。 このパラメータの意味は言語に依存します。 内部的な関数名、オブジェクトファイルへのパス、SQLコマンド、手続き言語で記述されたテキストなどを指定できます。

It is often helpful to use dollar quoting (see <xref linkend="sql-syntax-dollar-quoting"/>) to write the function definition string, rather than the normal single quote syntax. Without dollar quoting, any single quotes or backslashes in the function definition must be escaped by doubling them. 関数を定義する文字列を記述する際に、通常の単一引用符ではなく、ドル引用符(4.1.2.4参照)を使用すると便利なことが多くあります。 ドル引用符を使用しなければ、関数定義内の単一引用符やバックスラッシュは必ず二重にしてエスケープしなければなりません。

obj_file, link_symbol

This form of the <literal>AS</literal> clause is used for dynamically loadable C language functions when the function name in the C language source code is not the same as the name of the SQL function. The string <replaceable class="parameter">obj_file</replaceable> is the name of the shared library file containing the compiled C function, and is interpreted as for the <link linkend="sql-load"><command>LOAD</command></link> command. The string <replaceable class="parameter">link_symbol</replaceable> is the function's link symbol, that is, the name of the function in the C language source code. If the link symbol is omitted, it is assumed to be the same as the name of the SQL function being defined. The C names of all functions must be different, so you must give overloaded C functions different C names (for example, use the argument types as part of the C names). この構文のAS句は、動的にロードされるC言語関数において、C言語のソースコード中の関数名がSQL関数の名前と同じでない場合に使われます。 obj_fileという文字列はコンパイルされたC関数を含む共有ライブラリファイルの名前で、LOADコマンドの場合と同じように解釈されます。 文字列link_symbolはその関数のリンクシンボル、つまり、C言語ソースコード中の関数の名前です。 リンクシンボルが省略された場合、定義されるSQL関数の名前と同じものであるとみなされます。 全ての関数について、C言語における名前は、重複してはいけません。したがって、オーバーロードするC言語関数には、異なるC言語の名前を与える必要があります(例えば、C言語における名前の一部に引数の型を使用してください)。

When repeated <command>CREATE FUNCTION</command> calls refer to the same object file, the file is only loaded once per session. To unload and reload the file (perhaps during development), start a new session. 同一オブジェクトファイルを参照する、CREATE FUNCTION呼び出しが繰り返された場合、そのファイルはセッション毎に一度だけロードされます。 (おそらく開発段階で)ファイルをアンロードし再ロードするには、新しいセッションを開始してください。

sql_body

The body of a <literal>LANGUAGE SQL</literal> function. This can either be a single statement LANGUAGE SQL関数の本体です。 これは以下のような単一の文

RETURN expression

or a block またはブロックです。

BEGIN ATOMIC
  statement;
  statement;
  ...
  statement;
END

This is similar to writing the text of the function body as a string constant (see <replaceable>definition</replaceable> above), but there are some differences: This form only works for <literal>LANGUAGE SQL</literal>, the string constant form works for all languages. This form is parsed at function definition time, the string constant form is parsed at execution time; therefore this form cannot support polymorphic argument types and other constructs that are not resolvable at function definition time. This form tracks dependencies between the function and objects used in the function body, so <literal>DROP ... CASCADE</literal> will work correctly, whereas the form using string literals may leave dangling functions. Finally, this form is more compatible with the SQL standard and other SQL implementations. これは文字列定数として関数本体を書くのと似ていますが(上記のdefinitionを参照してください)、いくつか違いがあります。 この形式はLANGUAGE SQLに対してのみ機能し、文字列定数の形式はすべての言語に対して機能します。 この形式はプロシージャ定義時に解析され、文字列定数の形式は実行時に解析されます。 そのため、この形式は多様引数型や関数定義時に解決できないその他の構文をサポートできません。 この形式は関数と関数本体の中で使われているオブジェクトの間の依存関係を追跡しますので、DROP ... CASCADEは正しく動作しますが、一方、文字列定数を使う形式は宙に浮いた関数を放置するかもしれません。 最後に、この形式は標準SQLや他のSQL実装とより互換性があります。

オーバーロード

<title>Overloading</title>

<productname>PostgreSQL</productname> allows function <firstterm>overloading</firstterm>; that is, the same name can be used for several different functions so long as they have distinct input argument types. Whether or not you use it, this capability entails security precautions when calling functions in databases where some users mistrust other users; see <xref linkend="typeconv-func"/>. PostgreSQLでは関数のオーバーロードが可能です。 つまり、入力引数の型が異なっていれば、複数の関数に同じ名前を使用することができます。 使うかどうかに関わりなく、この能力は、あるユーザが他のユーザを信用しないデータベースで関数を呼び出す時に、セキュリティの事前の対策を必要とします。10.3を参照してください。

Two functions are considered the same if they have the same names and <emphasis>input</emphasis> argument types, ignoring any <literal>OUT</literal> parameters. Thus for example these declarations conflict: 同じ名前、同じ入力用パラメータ型を持つ場合、2つの関数は同一であるとみなされます。 OUTパラメータは無視されます。 したがって、例えば以下の宣言は競合しています。

CREATE FUNCTION foo(int) ...
CREATE FUNCTION foo(int, out text) ...

Functions that have different argument type lists will not be considered to conflict at creation time, but if defaults are provided they might conflict in use. For example, consider 異なる引数型のリストを持つ関数は、作成時に競合するとはみなされませんが、デフォルト値が指定された場合使用時に競合する可能性があります。 例えば以下を考えてみましょう。

CREATE FUNCTION foo(int) ...
CREATE FUNCTION foo(int, int default 42) ...

A call <literal>foo(10)</literal> will fail due to the ambiguity about which function should be called. foo(10)という呼び出しは、どちらの関数を呼び出すべきかに関して曖昧さがあるために失敗します。

注釈

<title>Notes</title>

The full <acronym>SQL</acronym> type syntax is allowed for declaring a function's arguments and return value. However, parenthesized type modifiers (e.g., the precision field for type <type>numeric</type>) are discarded by <command>CREATE FUNCTION</command>. Thus for example <literal>CREATE FUNCTION foo (varchar(10)) ...</literal> is exactly the same as <literal>CREATE FUNCTION foo (varchar) ...</literal>. 関数の引数と戻り値の宣言において、完全なSQL型の構文が使用できます。 しかし、括弧付けされた型修飾子(例えばnumeric型の精度フィールド)は、CREATE FUNCTIONにより破棄されます。 従って、CREATE FUNCTION foo (varchar(10)) ...CREATE FUNCTION foo (varchar) ...とまったく同じになります。

When replacing an existing function with <command>CREATE OR REPLACE FUNCTION</command>, there are restrictions on changing parameter names. You cannot change the name already assigned to any input parameter (although you can add names to parameters that had none before). If there is more than one output parameter, you cannot change the names of the output parameters, because that would change the column names of the anonymous composite type that describes the function's result. These restrictions are made to ensure that existing calls of the function do not stop working when it is replaced. 既存の関数をCREATE OR REPLACE FUNCTIONを使って置き換える場合、パラメータ名の変更に関して制限があります。 すでに何らかの入力パラメータに割り当てられた名前を変更することはできません。 (しかし、これまで名前を持たなかったパラメータに名前を追加することは可能です。) 複数の出力パラメータが存在する場合、関数の結果を表わす無名複合型の列名を変更することになるため、出力パラメータの名前を変更することはできません。 既存の関数呼び出しが置き換わった時に動作しなくなることを確実に防ぐために、これらの制限がなされています。

If a function is declared <literal>STRICT</literal> with a <literal>VARIADIC</literal> argument, the strictness check tests that the variadic array <emphasis>as a whole</emphasis> is non-null. The function will still be called if the array has null elements. 関数がVARIADIC引数を持つSTRICTと宣言された場合、その厳密性検査では、variadic配列全体が非NULLかどうかを検査します。 配列がNULL要素を持っていたとしても関数は呼び出されます。

<title>Examples</title>

Add two integers using an SQL function: SQL関数を使って2つの整数を足す。

CREATE FUNCTION add(integer, integer) RETURNS integer
    AS 'select $1 + $2;'
    LANGUAGE SQL
    IMMUTABLE
    RETURNS NULL ON NULL INPUT;

The same function written in a more SQL-conforming style, using argument names and an unquoted body: 引数名と引用されていない本体を使って、よりSQLに準拠した形で書かれた同じ関数。

CREATE FUNCTION add(a integer, b integer) RETURNS integer
    LANGUAGE SQL
    IMMUTABLE
    RETURNS NULL ON NULL INPUT
    RETURN a + b;

Increment an integer, making use of an argument name, in <application>PL/pgSQL</application>: PL/pgSQLで、引数名を使用して、整数を1増やします。

CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
        BEGIN
                RETURN i + 1;
        END;
$$ LANGUAGE plpgsql;

Return a record containing multiple output parameters: 複数の出力用パラメータを持つレコードを返します。

CREATE FUNCTION dup(in int, out f1 int, out f2 text)
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

You can do the same thing more verbosely with an explicitly named composite type: 上と同じことを、明示的な名前が付いた複合型を使用して、より冗長に行うことができます。

CREATE TYPE dup_result AS (f1 int, f2 text);

CREATE FUNCTION dup(int) RETURNS dup_result
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

Another way to return multiple columns is to use a <literal>TABLE</literal> function: 複数列を返す別の方法は、TABLE関数を使用することです。

CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

However, a <literal>TABLE</literal> function is different from the preceding examples, because it actually returns a <emphasis>set</emphasis> of records, not just one record. しかし、これは実際には、1つのレコードではなく、レコードの集合を返しますので、TABLE関数は上の例とは異なります。

SECURITY DEFINER関数の安全な作成

<title>Writing <literal>SECURITY DEFINER</literal> Functions Safely</title>

Because a <literal>SECURITY DEFINER</literal> function is executed with the privileges of the user that owns it, care is needed to ensure that the function cannot be misused. For security, <xref linkend="guc-search-path"/> should be set to exclude any schemas writable by untrusted users. This prevents malicious users from creating objects (e.g., tables, functions, and operators) that mask objects intended to be used by the function. Particularly important in this regard is the temporary-table schema, which is searched first by default, and is normally writable by anyone. A secure arrangement can be obtained by forcing the temporary schema to be searched last. To do this, write <literal>pg_temp</literal><indexterm><primary>pg_temp</primary><secondary>securing functions</secondary></indexterm> as the last entry in <varname>search_path</varname>. This function illustrates safe usage: SECURITY DEFINER関数は関数を所有するユーザの権限で実行されますので、その関数を間違って使用できないことを確実にしなければなりません。 安全上、search_pathは、信頼できないユーザが書き込み可能なスキーマを除去した形で設定すべきです。 これは、悪意のあるユーザがその関数で使用されるオブジェクトを隠すようなオブジェクト(例えば、テーブル、関数、演算子など)を作成することを防ぎます。 ここで特に重要なことは、一時テーブルスキーマです。 このスキーマはデフォルトで最初に検索され、そして、通常誰でも書き込み可能です。 一時スキーマの検索を強制的に最後にすることで、セキュリティを調整できます。 このためには、pg_tempsearch_pathの最後の項目として記載してください。 安全な使用方法を以下の関数で示します。

CREATE FUNCTION check_password(uname TEXT, pass TEXT)
RETURNS BOOLEAN AS $$
DECLARE passed BOOLEAN;
BEGIN
        SELECT  (pwd = $2) INTO passed
        FROM    pwds
        WHERE   username = $1;

        RETURN passed;
END;
$$  LANGUAGE plpgsql
    SECURITY DEFINER

    &#45;- Set a secure search_path: trusted schema(s), then 'pg_temp'.

    -- 信頼できるスキーマ、その後にpg_tempという順でsearch_pathを安全に設定します。
    SET search_path = admin, pg_temp;

This function's intention is to access a table <literal>admin.pwds</literal>. But without the <literal>SET</literal> clause, or with a <literal>SET</literal> clause mentioning only <literal>admin</literal>, the function could be subverted by creating a temporary table named <literal>pwds</literal>. この関数の意図は、テーブルadmin.pwdsにアクセスすることです。 しかしSET句がなければ、あるいはSET句がadminだけしか記述していなければ、pwdsという名前の一時テーブルを作成することで、この関数は無意味になってしまいます。

If the security definer function intends to create roles, and if it is running as a non-superuser, <varname>createrole_self_grant</varname> should also be set to a known value using the <literal>SET</literal> clause. SECURITY DEFINER関数がロールを作成しようとしていて、それが非スーパーユーザとして実行されている場合、createrole_self_grantSET句を使用して既知の値に設定することが必要です。

Another point to keep in mind is that by default, execute privilege is granted to <literal>PUBLIC</literal> for newly created functions (see <xref linkend="ddl-priv"/> for more information). Frequently you will wish to restrict use of a security definer function to only some users. To do that, you must revoke the default <literal>PUBLIC</literal> privileges and then grant execute privilege selectively. To avoid having a window where the new function is accessible to all, create it and set the privileges within a single transaction. For example: この他に注意すべき点として、新しく作成された関数ではデフォルトで実行権限がPUBLICに付与されていることがあります。 (詳細は5.7を参照してください。) SECURITY DEFINER関数の使用を一部のユーザのみに制限したいことはよくあります。 このためには、デフォルトのPUBLIC権限を取り消し、そして、実行権限の付与を選択して行ってください。 新しい関数がすべてのユーザに実行可能となる隙間が存在することを防ぐためには、単一トランザクション内で作成と権限設定を行ってください。 以下に例を示します。

BEGIN;
CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
COMMIT;

互換性

<title>Compatibility</title>

A <command>CREATE FUNCTION</command> command is defined in the SQL standard. The <productname>PostgreSQL</productname> implementation can be used in a compatible way but has many extensions. Conversely, the SQL standard specifies a number of optional features that are not implemented in <productname>PostgreSQL</productname>. CREATE FUNCTIONコマンドは標準SQLで定義されています。 PostgreSQLの実装は互換性のある方法で使うことはできますが、多くの拡張があります。 逆に、標準SQLにはPostgreSQLでは実装されていない多くの省略可能な機能が定義されています。

The following are important compatibility issues: 以下が重要な互換性の問題です。

  • <literal>OR REPLACE</literal> is a PostgreSQL extension. OR REPLACEはPostgreSQLの拡張です。

  • For compatibility with some other database systems, <replaceable class="parameter">argmode</replaceable> can be written either before or after <replaceable class="parameter">argname</replaceable>. But only the first way is standard-compliant. 他のデータベースシステムとの互換性のために、argmodeargnameの前に書くことも後に書くこともできます。 しかし、1つ目の方法が標準に従っています。

  • For parameter defaults, the SQL standard specifies only the syntax with the <literal>DEFAULT</literal> key word. The syntax with <literal>=</literal> is used in T-SQL and Firebird. パラメータのデフォルトに関しては、標準SQLではDEFAULTキーワードの構文のみを規定します。 =を持つ構文はT-SQLおよびFirebirdで使用されています。

  • The <literal>SETOF</literal> modifier is a PostgreSQL extension. SETOF修飾子はPostgreSQLの拡張です。

  • Only <literal>SQL</literal> is standardized as a language. SQLのみが言語として標準化されています。

  • All other attributes except <literal>CALLED ON NULL INPUT</literal> and <literal>RETURNS NULL ON NULL INPUT</literal> are not standardized. CALLED ON NULL INPUTRETURNS NULL ON NULL INPUT以外の属性はすべて標準化されていません。

  • For the body of <literal>LANGUAGE SQL</literal> functions, the SQL standard only specifies the <replaceable>sql_body</replaceable> form. LANGUAGE SQL関数の本体に対して、標準SQLはsql_body形式のみを定義しています。

Simple <literal>LANGUAGE SQL</literal> functions can be written in a way that is both standard-conforming and portable to other implementations. More complex functions using advanced features, optimization attributes, or other languages will necessarily be specific to PostgreSQL in a significant way. 単純なLANGUAGE SQL関数は、標準に準拠して、なおかつ他の実装に移植性のある方法で書くことができます。 高度な機能、最適化属性、他の言語を使ったより複雑な関数は、必ず重要なところでPostgreSQLに固有のものになるでしょう。

関連項目

<title>See Also</title> ALTER FUNCTION, DROP FUNCTION, GRANT, LOAD, REVOKE