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

43.3. 宣言 #

<title>Declarations</title>

All variables used in a block must be declared in the declarations section of the block. (The only exceptions are that the loop variable of a <literal>FOR</literal> loop iterating over a range of integer values is automatically declared as an integer variable, and likewise the loop variable of a <literal>FOR</literal> loop iterating over a cursor's result is automatically declared as a record variable.) ブロック内で使用される全ての変数はそのブロックの宣言部で宣言されなければなりません。 (唯一の例外は、FORループである整数値の範囲に渡って繰り返されるループ変数で、これは、自動的に整数型変数として宣言されます。 同様に、カーソルの結果に対して繰り返し適用されるFORループのループ変数はレコード変数として自動的に宣言されます。)

<application>PL/pgSQL</application> variables can have any SQL data type, such as <type>integer</type>, <type>varchar</type>, and <type>char</type>. PL/pgSQL変数は、integervarcharcharといった、任意のSQLデータ型を持つことができます。

Here are some examples of variable declarations: 変数宣言の例を以下に示します。

user_id integer;
quantity numeric(5);
url varchar;
myrow tablename%ROWTYPE;
myfield tablename.columnname%TYPE;
arow RECORD;

The general syntax of a variable declaration is: 変数宣言の一般的な構文は以下の通りです。

name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | := | = } expression ];

The <literal>DEFAULT</literal> clause, if given, specifies the initial value assigned to the variable when the block is entered. If the <literal>DEFAULT</literal> clause is not given then the variable is initialized to the <acronym>SQL</acronym> null value. The <literal>CONSTANT</literal> option prevents the variable from being assigned to after initialization, so that its value will remain constant for the duration of the block. The <literal>COLLATE</literal> option specifies a collation to use for the variable (see <xref linkend="plpgsql-declaration-collation"/>). If <literal>NOT NULL</literal> is specified, an assignment of a null value results in a run-time error. All variables declared as <literal>NOT NULL</literal> must have a nonnull default value specified. Equal (<literal>=</literal>) can be used instead of PL/SQL-compliant <literal>:=</literal>. DEFAULT句が指定された場合、ブロックに入った時に変数に代入される初期値を指定します。 DEFAULT句が指定されない場合、変数はSQLのNULL値に初期化されます。 CONSTANTオプションにより、そのブロック内でその値が不変になるように、その変数への初期化後の代入は禁止されます。 COLLATEオプションは、変数として使用するための照合を指定します(43.3.6を参照してください)。 NOT NULLが指定された場合、NULL値の代入は実行時エラーになります。 NOT NULLとして宣言した変数は全て、非NULLのデフォルト値を指定しなければなりません。 等号(=)がPL/SQLにおける代入記号(:=)の代わりに使用できます。

A variable's default value is evaluated and assigned to the variable each time the block is entered (not just once per function call). So, for example, assigning <literal>now()</literal> to a variable of type <type>timestamp</type> causes the variable to have the time of the current function call, not the time when the function was precompiled. 変数のデフォルト値はブロックに入る度に評価され、変数に代入されます(関数を呼び出す時に一度だけではありません)。 ですから、例えばnow()timestamp型の変数に代入することで、その変数には関数をプリコンパイルした時刻ではなく、関数呼び出し時の現在時刻が格納されます。

Examples: 例:

quantity integer DEFAULT 32;
url varchar := 'http://mysite.com';
transaction_time CONSTANT timestamp with time zone := now();

Once declared, a variable's value can be used in later initialization expressions in the same block, for example: 宣言された変数の値は、同じブロック内の後の初期化式で使用できます。 次に例を示します。

DECLARE
  x integer := 1;
  y integer := x + 1;

43.3.1. 関数引数の宣言 #

<title>Declaring Function Parameters</title>

Parameters passed to functions are named with the identifiers <literal>$1</literal>, <literal>$2</literal>, etc. Optionally, aliases can be declared for <literal>$<replaceable>n</replaceable></literal> parameter names for increased readability. Either the alias or the numeric identifier can then be used to refer to the parameter value. 関数に渡されるパラメータの名前には$1$2という識別子が付けられます。 省略することもできますが、$nというパラメータ名に別名を宣言することができ、可読性が向上します。 別名、数字による識別子の両方とも引数の値を参照する時に使用することができます。

There are two ways to create an alias. The preferred way is to give a name to the parameter in the <command>CREATE FUNCTION</command> command, for example: 別名を作成する方法は2つあり、望ましい方法はCREATE FUNCTIONコマンドの中でパラメータを命名するものです。 以下に例を示します。

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

The other way is to explicitly declare an alias, using the declaration syntax 他の方法は、宣言構文を用いて別名を明確に宣言するものです。

name ALIAS FOR $n;

The same example in this style looks like: 以下にこの方法による例を示します。

CREATE FUNCTION sales_tax(real) RETURNS real AS $$
DECLARE
    subtotal ALIAS FOR $1;
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

注記

These two examples are not perfectly equivalent. In the first case, <literal>subtotal</literal> could be referenced as <literal>sales_tax.subtotal</literal>, but in the second case it could not. (Had we attached a label to the inner block, <literal>subtotal</literal> could be qualified with that label, instead.) この二例は完全に同等ではありません。 最初の例では、subtotalsales_tax.subtotalで参照できますが、次の例ではできません (その代わり、内部ブロックにラベルを付与すれば、subtotalをラベルで修飾することができます)。

Some more examples: さらに数例を示します。

CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
DECLARE
    v_string ALIAS FOR $1;
    index ALIAS FOR $2;
BEGIN

    &#45;- some computations using v_string and index here

    -- v_string とインデックスを使用した何らかの演算を行なう
END;
$$ LANGUAGE plpgsql;


CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
BEGIN
    RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
END;
$$ LANGUAGE plpgsql;

When a <application>PL/pgSQL</application> function is declared with output parameters, the output parameters are given <literal>$<replaceable>n</replaceable></literal> names and optional aliases in just the same way as the normal input parameters. An output parameter is effectively a variable that starts out NULL; it should be assigned to during the execution of the function. The final value of the parameter is what is returned. For instance, the sales-tax example could also be done this way: PL/pgSQL関数が出力パラメータと共に宣言されると、通常の入力パラメータと同様に、出力パラメータには$nというパラメータ名と任意の別名が与えられます。 出力パラメータは実質的には最初がNULL値の変数であり、関数の実行中に値が指定されるはずです。 出力パラメータの最後の値は戻り値です。 例えば、消費税の例題は、次のようにすることもできます。

CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
BEGIN
    tax := subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

Notice that we omitted <literal>RETURNS real</literal> &mdash; we could have included it, but it would be redundant. RETURNS realを省略したことに注意してください。 含めることもできますが、冗長になります。

To call a function with <literal>OUT</literal> parameters, omit the output parameter(s) in the function call: OUTパラメータの付いた関数を呼び出すには、関数呼び出しで出力パラメータを省略してください。

SELECT sales_tax(100.00);

Output parameters are most useful when returning multiple values. A trivial example is: 出力パラメータは複数の値を返す時に最も有用になります。 簡単な例題を示します。

CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
BEGIN
    sum := x + y;
    prod := x * y;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM sum_n_product(2, 4);
 sum | prod
-----+------
   6 |    8

As discussed in <xref linkend="xfunc-output-parameters"/>, this effectively creates an anonymous record type for the function's results. If a <literal>RETURNS</literal> clause is given, it must say <literal>RETURNS record</literal>. 38.5.4で述べたように、この方法は関数の結果に対する匿名のレコード型を実質的に作成します。 RETURNS句が与えられた時は、RETURNS recordと言わなければなりません。

This also works with procedures, for example: これは以下のようにプロシージャでも機能します。

CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
BEGIN
    sum := x + y;
    prod := x * y;
END;
$$ LANGUAGE plpgsql;

In a call to a procedure, all the parameters must be specified. For output parameters, <literal>NULL</literal> may be specified when calling the procedure from plain SQL: プロシージャの呼び出しでは、すべてのパラメータを指定しなければなりません。 普通のSQLからプロシージャを呼び出す場合には、出力パラメータに対してはNULLを指定します。

CALL sum_n_product(2, 4, NULL, NULL);
 sum | prod
-----+------
   6 |    8

However, when calling a procedure from <application>PL/pgSQL</application>, you should instead write a variable for any output parameter; the variable will receive the result of the call. See <xref linkend="plpgsql-statements-calling-procedure"/> for details. しかしながら、PL/pgSQLからプロシージャを呼び出すときには、出力パラメータに対して変数を書かないといけません。変数は呼び出しの結果を受け取ります。 詳細は43.6.3を参照してください。

Another way to declare a <application>PL/pgSQL</application> function is with <literal>RETURNS TABLE</literal>, for example: PL/pgSQL関数を宣言する他の方法として、RETURNS TABLEを伴うことが挙げられます。 以下に例を示します。

CREATE FUNCTION extended_sales(p_itemno int)
RETURNS TABLE(quantity int, total numeric) AS $$
BEGIN
    RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
                 WHERE s.itemno = p_itemno;
END;
$$ LANGUAGE plpgsql;

This is exactly equivalent to declaring one or more <literal>OUT</literal> parameters and specifying <literal>RETURNS SETOF <replaceable>sometype</replaceable></literal>. これは、1つ、またはそれ以上のOUTパラメータを宣言すること、およびRETURNS SETOF 何らかのデータ型を指定することと全く等価です。

When the return type of a <application>PL/pgSQL</application> function is declared as a polymorphic type (see <xref linkend="extend-types-polymorphic"/>), a special parameter <literal>$0</literal> is created. Its data type is the actual return type of the function, as deduced from the actual input types. This allows the function to access its actual return type as shown in <xref linkend="plpgsql-declaration-type"/>. <literal>$0</literal> is initialized to null and can be modified by the function, so it can be used to hold the return value if desired, though that is not required. <literal>$0</literal> can also be given an alias. For example, this function works on any data type that has a <literal>+</literal> operator: PL/pgSQL関数の戻り値が多様型(38.2.5を参照)として宣言されると、特別な$0パラメータが作成されます。 このデータ型が、実際の入力型から推定された関数の実際の戻り値の型です。 これにより、関数は43.3.3に示すように、実際の戻り値の型にアクセスできます。 $0はNULLで初期化され、関数内で変更することができます。 ですので、必須ではありませんが、これを戻り値を保持するために使用しても構いません。 また$0に別名を付与することもできます。 例えば、以下の関数は+演算子を持つ任意のデータ型に対して稼働します。

CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
RETURNS anyelement AS $$
DECLARE
    result ALIAS FOR $0;
BEGIN
    result := v1 + v2 + v3;
    RETURN result;
END;
$$ LANGUAGE plpgsql;

The same effect can be obtained by declaring one or more output parameters as polymorphic types. In this case the special <literal>$0</literal> parameter is not used; the output parameters themselves serve the same purpose. For example: 1つ以上の出力パラメータを多様型として宣言することにより、同様の結果を得ることができます。 この場合、特殊な$0パラメータは使用されません。 出力パラメータ自身が同じ目的を果たします。 以下に例を示します。

CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
                                 OUT sum anyelement)
AS $$
BEGIN
    sum := v1 + v2 + v3;
END;
$$ LANGUAGE plpgsql;

In practice it might be more useful to declare a polymorphic function using the <type>anycompatible</type> family of types, so that automatic promotion of the input arguments to a common type will occur. For example: 実際には型にanycompatible族を使用して多様関数を宣言する方が有用である可能性があります。そうすれば、 入力引数が共通の型に自動的に昇格されます。 以下に例を示します。

CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompatible)
RETURNS anycompatible AS $$
BEGIN
    RETURN v1 + v2 + v3;
END;
$$ LANGUAGE plpgsql;

With this example, a call such as この例は

SELECT add_three_values(1, 2, 4.7);

will work, automatically promoting the integer inputs to numeric. The function using <type>anyelement</type> would require you to cast the three inputs to the same type manually. 自動的に整数の入力を数値データに昇格して呼び出しが動作します。 anyelementを使用する関数では、3つの入力を同じ型に手動でキャストする必要があります。

43.3.2. ALIAS #

newname ALIAS FOR oldname;

The <literal>ALIAS</literal> syntax is more general than is suggested in the previous section: you can declare an alias for any variable, not just function parameters. The main practical use for this is to assign a different name for variables with predetermined names, such as <varname>NEW</varname> or <varname>OLD</varname> within a trigger function. ALIAS構文は前節で示したものより一般的です。 関数の引数だけではなく、任意の変数に別名を宣言することができます。 この現実的な使用は主に、トリガ関数におけるNEWOLDなど、前もって決まった名前の変数に別の名前を割り当てることです。

Examples: 以下に例を示します。

DECLARE
  prior ALIAS FOR old;
  updated ALIAS FOR new;

Since <literal>ALIAS</literal> creates two different ways to name the same object, unrestricted use can be confusing. It's best to use it only for the purpose of overriding predetermined names. ALIASは同じオブジェクトを命名する2つの異なる手段を提供しますので、無制限に使用すると混乱を招くかもしれません。 前もって決まっている名前を上書きする目的に限定して使用することが最善です。

43.3.3. 型のコピー #

<title>Copying Types</title>
variable%TYPE

<literal>%TYPE</literal> provides the data type of a variable or table column. You can use this to declare variables that will hold database values. For example, let's say you have a column named <literal>user_id</literal> in your <literal>users</literal> table. To declare a variable with the same data type as <literal>users.user_id</literal> you write: %TYPEは変数やテーブル列のデータ型を提供します。 これを使用してデータベース値を保持する変数を宣言することができます。 例えば、usersテーブルにuser_idという列があるものとします。 users.user_idと同じデータ型の変数を宣言するには、以下のように記述します。

user_id users.user_id%TYPE;

By using <literal>%TYPE</literal> you don't need to know the data type of the structure you are referencing, and most importantly, if the data type of the referenced item changes in the future (for instance: you change the type of <literal>user_id</literal> from <type>integer</type> to <type>real</type>), you might not need to change your function definition. %TYPEを使用することで、参照する構造のデータ型を把握する必要がなくなります。 また、これが最も重要なことですが、参照される項目のデータ型が将来変更された(例えば、user_idのテーブル定義をintegerからrealに変更した)場合でも、関数定義を変更する必要をなくすことができます。

<literal>%TYPE</literal> is particularly valuable in polymorphic functions, since the data types needed for internal variables can change from one call to the next. Appropriate variables can be created by applying <literal>%TYPE</literal> to the function's arguments or result placeholders. 内部変数用のデータ型は呼び出す度に変わるかもしれませんので%TYPEは特に多様関数で有用です。 関数の引数や結果用のプレースホルダに%TYPEを適用することで、適切な変数を作成することができます。

43.3.4. 行型 #

<title>Row Types</title>
name table_name%ROWTYPE;
name composite_type_name;

A variable of a composite type is called a <firstterm>row</firstterm> variable (or <firstterm>row-type</firstterm> variable). Such a variable can hold a whole row of a <command>SELECT</command> or <command>FOR</command> query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example <literal>rowvar.field</literal>. 複合型の変数は、変数(または行型変数)と呼ばれます。 こういった変数には、問い合わせの列集合が変数の型宣言と一致する限り、SELECTFOR問い合わせの結果の行全体を保持することができます。 行変数の個々のフィールド値には、例えば、rowvar.fieldといったドット記法を使用してアクセスすることができます。

A row variable can be declared to have the same type as the rows of an existing table or view, by using the <replaceable>table_name</replaceable><literal>%ROWTYPE</literal> notation; or it can be declared by giving a composite type's name. (Since every table has an associated composite type of the same name, it actually does not matter in <productname>PostgreSQL</productname> whether you write <literal>%ROWTYPE</literal> or not. But the form with <literal>%ROWTYPE</literal> is more portable.) table_name%ROWTYPEという記法を使用して、既存のテーブルやビューの行と同じ型を持つ行変数を宣言することができます。 もしくは、複合型の名前を付与して宣言することができます。 (全てのテーブルは、同じ名前の関連する複合型を持ちますので、実際のところPostgreSQLでは、%ROWTYPEと書いても書かなくても問題にはなりません。 しかし、%ROWTYPEの方がより移植性が高まります。)

Parameters to a function can be composite types (complete table rows). In that case, the corresponding identifier <literal>$<replaceable>n</replaceable></literal> will be a row variable, and fields can be selected from it, for example <literal>$1.user_id</literal>. 関数へのパラメータとして複合型(テーブル行全体)を取ることができます。 その場合、対応する識別子$nは行変数であり、そのフィールドを、例えば、$1.user_idで選択することができます。

Here is an example of using composite types. <structname>table1</structname> and <structname>table2</structname> are existing tables having at least the mentioned fields: 以下に複合型を使用する例を示します。 table1及びtable2は、 少なくとも言及するフィールドを有する既存のテーブルです。

CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
DECLARE
    t2_row table2%ROWTYPE;
BEGIN
    SELECT * INTO t2_row FROM table2 WHERE ... ;
    RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
END;
$$ LANGUAGE plpgsql;

SELECT merge_fields(t.*) FROM table1 t WHERE ... ;

43.3.5. レコード型 #

<title>Record Types</title>
name RECORD;

Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a <command>SELECT</command> or <command>FOR</command> command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error. レコード変数は行型変数と似ていますが、事前に定義された構造を持っていません。 これはSELECTFORコマンドの間で代入された行の実際の行構造を取ります。 レコード変数の副構造は、代入を行う度に変更できます。 つまり、レコード変数は、最初に代入されるまで副構造を持たず、したがって、フィールドへのアクセスを試みると実行時エラーが発生します。

Note that <literal>RECORD</literal> is not a true data type, only a placeholder. One should also realize that when a <application>PL/pgSQL</application> function is declared to return type <type>record</type>, this is not quite the same concept as a record variable, even though such a function might use a record variable to hold its result. In both cases the actual row structure is unknown when the function is written, but for a function returning <type>record</type> the actual structure is determined when the calling query is parsed, whereas a record variable can change its row structure on-the-fly. RECORDは本当のデータ型ではなく、単なるプレースホルダであることに注意してください。 PL/pgSQL関数がrecord型を返す時、この関数ではレコード変数を使用してその結果を保持することができますが、これはレコード変数としての概念とはまったく異なることを認識すべきです。 両方とも、関数の作成段階では実際の行構造は不明です。 しかし、レコード変数はその場その場でその行構造を変更できるにもかかわらず、recordを返す関数では呼び出し元の問い合わせが解析された時点で実際の構造は決定されます。

43.3.6. PL/pgSQL変数の照合 #

<title>Collation of <application>PL/pgSQL</application> Variables</title>

When a <application>PL/pgSQL</application> 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, consider PL/pgSQL関数が照合可能なデータ型のパラメータを 1つ以上保有する場合、24.2に記述したように、実際の引数に割り当てられた照合に従って、関数呼び出し毎に照合が識別されます。 照合の識別に成功した場合(すなわち、引数の間に事実上の照合における衝突がない場合)、照合可能な全てのパラメータは暗黙の照合を有するとして扱われます。 これは関数内部において、照合に依存する操作の作用に影響します。 以下の例を考えてください。

CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
BEGIN
    RETURN a < b;
END;
$$ LANGUAGE plpgsql;

SELECT less_than(text_field_1, text_field_2) FROM table1;
SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;

The first use of <function>less_than</function> will use the common collation of <structfield>text_field_1</structfield> and <structfield>text_field_2</structfield> for the comparison, while the second use will use <literal>C</literal> collation. 第一の使用方法においてless_thanは、text_field_1text_field_2の比較のための通常の照合として用いられます。 第二の使用方法においては、C照合として用いられます。

Furthermore, the identified collation is also assumed as the collation of any local variables that are of collatable types. Thus this function would not work any differently if it were written as さらに、識別された照合は、照合可能なデータ型の全ての局所変数の照合としても仮定されます。 したがって、この関数は下に記述する関数と差異なく作動します。

CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
DECLARE
    local_a text := a;
    local_b text := b;
BEGIN
    RETURN local_a < local_b;
END;
$$ LANGUAGE plpgsql;

If there are no parameters of collatable data types, or no common collation can be identified for them, then parameters and local variables use the default collation of their data type (which is usually the database's default collation, but could be different for variables of domain types). 照合可能なデータ型のパラメータが存在しない場合、または、それらで共通する照合順序を識別できない場合、パラメータと局所変数は自身のデータ型のデフォルトの照合順序(通常これはデータベースのデフォルトの照合順序ですが、ドメイン型の変数の場合は異なるかもしれません)を使用します。

A local variable of a collatable data type can have a different collation associated with it by including the <literal>COLLATE</literal> option in its declaration, for example 照合可能なデータ型の局所変数は、宣言内でCOLLATEオプションを含めることにより、別の照合と関連づけることができます。 例を示します。

DECLARE
    local_a text COLLATE "en_US";

This option overrides the collation that would otherwise be given to the variable according to the rules above. このオプションは上記ルールにより、変数に他の方法で付与されるはずであった照合を上書きします。

Also, of course explicit <literal>COLLATE</literal> clauses can be written inside a function if it is desired to force a particular collation to be used in a particular operation. For example, また当然ながら、強制的に特定の操作において特定の照合順序を使用したい場合、明示的なCOLLATE句を関数内部に記述することができます。 例を示します。

CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
BEGIN
    RETURN a < b COLLATE "C";
END;
$$ LANGUAGE plpgsql;

This overrides the collations associated with the table columns, parameters, or local variables used in the expression, just as would happen in a plain SQL command. 単純なSQLコマンドで起こるように、これはテーブルの列、パラメータ、または式の中の局所変数に関連づけられた照合を上書きします