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

46.2. データ値 #

<title>Data Values</title>

Generally speaking, the aim of PL/Python is to provide a <quote>natural</quote> mapping between the PostgreSQL and the Python worlds. This informs the data mapping rules described below. 一般的にいって、PL/Pythonの目標はPostgreSQLとPythonの世界の間で自然な対応付けを提供することです。 これは以下のようなデータの対応付けを形成します。

46.2.1. データ型の対応付け #

<title>Data Type Mapping</title>

When a PL/Python function is called, its arguments are converted from their PostgreSQL data type to a corresponding Python type: PL/Python関数が呼ばれると、その引数は、以下のようにPostgreSQLの型から対応するPython型に変換されます。

  • PostgreSQL <type>boolean</type> is converted to Python <type>bool</type>. PostgreSQLのbooleanはPythonのboolに変換されます。

  • PostgreSQL <type>smallint</type>, <type>int</type>, <type>bigint</type> and <type>oid</type> are converted to Python <type>int</type>. PostgreSQLのsmallintintbigintおよびoidはPythonのintに変換されます。

  • PostgreSQL <type>real</type> and <type>double</type> are converted to Python <type>float</type>. PostgreSQLのrealおよびdoubleはPythonのfloatに変換されます。

  • PostgreSQL <type>numeric</type> is converted to Python <type>Decimal</type>. This type is imported from the <literal>cdecimal</literal> package if that is available. Otherwise, <literal>decimal.Decimal</literal> from the standard library will be used. <literal>cdecimal</literal> is significantly faster than <literal>decimal</literal>. In Python 3.3 and up, however, <literal>cdecimal</literal> has been integrated into the standard library under the name <literal>decimal</literal>, so there is no longer any difference. PostgreSQLのnumericはPythonのDecimalに変換されます。 この型は可能ならばcdecimalパッケージからインポートできます。 可能でなければ、標準ライブラリのdecimal.Decimalが使用できます。 cdecimaldecimalより高速です。 しかしPython 3.3から、cdecimaldecimalという名前で標準ライブラリに統合されたので、もはや差異はありません。

  • PostgreSQL <type>bytea</type> is converted to Python <type>bytes</type>. PostgreSQLのbyteaは、Pythonのbytesに変換されます。

  • All other data types, including the PostgreSQL character string types, are converted to a Python <type>str</type> (in Unicode like all Python strings). PostgreSQLの文字列型を含む、上記以外のデータ型はすべてPythonのstrに(すべてのPython文字列と同様にUnicodeで)変換されます。

  • For nonscalar data types, see below. スカラデータ型以外については後述します。

When a PL/Python function returns, its return value is converted to the function's declared PostgreSQL return data type as follows: PL/Python関数が戻る時には、その戻り値は、以下のようにPostgreSQLの宣言された戻り値データ型に変換されます。

  • When the PostgreSQL return type is <type>boolean</type>, the return value will be evaluated for truth according to the <emphasis>Python</emphasis> rules. That is, 0 and empty string are false, but notably <literal>'f'</literal> is true. PostgreSQLの戻り値の型がbooleanの場合、戻り値はPythonの規約に従った真に対して評価されます。 つまり、0や空文字列は偽です。 'f'が真となることには注意してください。

  • When the PostgreSQL return type is <type>bytea</type>, the return value will be converted to Python <type>bytes</type> using the respective Python built-ins, with the result being converted to <type>bytea</type>. PostgreSQLの戻り値の型がbyteaの場合、対応するPythonのビルトインを使用してPythonのbytesに変換され、その結果がbyteaに変換されます。

  • For all other PostgreSQL return types, the return value is converted to a string using the Python built-in <literal>str</literal>, and the result is passed to the input function of the PostgreSQL data type. (If the Python value is a <type>float</type>, it is converted using the <literal>repr</literal> built-in instead of <literal>str</literal>, to avoid loss of precision.) この他のPostgreSQLの戻り値型では、返される値はPythonのビルトインstrを使用して文字列に変換され、その結果がPostgreSQLデータ型の入力関数に渡されます。 (Pythonの値がfloatであれば、精度が失われるのを避けるため、strの代わりにreprビルトインを使って変換されます。)

    Strings are automatically converted to the PostgreSQL server encoding when they are passed to PostgreSQL. 文字列はPostgreSQLに渡される時に、自動的にPostgreSQLサーバの符号化方式に変換されます。

  • For nonscalar data types, see below. スカラデータ型以外については後述します。

Note that logical mismatches between the declared PostgreSQL return type and the Python data type of the actual return object are not flagged; the value will be converted in any case. 宣言されたPostgreSQLの戻り値型と実際に返されるオブジェクトのPythonデータ型との間の論理的な不整合が伝わらないことに注意してください。 値はいかなる場合でも変換されます。

46.2.2. NullとNone #

<title>Null, None</title>

If an SQL null value<indexterm><primary>null value</primary><secondary sortas="PL/Python">in PL/Python</secondary></indexterm> is passed to a function, the argument value will appear as <symbol>None</symbol> in Python. For example, the function definition of <function>pymax</function> shown in <xref linkend="plpython-funcs"/> will return the wrong answer for null inputs. We could add <literal>STRICT</literal> to the function definition to make <productname>PostgreSQL</productname> do something more reasonable: if a null value is passed, the function will not be called at all, but will just return a null result automatically. Alternatively, we could check for null inputs in the function body: SQLのNULL値が関数に渡されると、その引数値はPythonではNoneとなります。 例えば、46.1に示されたpymax関数の定義では、NULL入力に対して間違った結果が返されます。 関数定義にSTRICTを付与してPostgreSQLを、NULL値が渡された場合にその関数を呼び出さず、自動的に単にNULL結果を返すという、より理想的に動作させることができます。 他に、関数本体でNULL入力を検査することもできます。

CREATE FUNCTION pymax (a integer, b integer)
  RETURNS integer
AS $$
  if (a is None) or (b is None):
    return None
  if a > b:
    return a
  return b
$$ LANGUAGE plpython3u;

As shown above, to return an SQL null value from a PL/Python function, return the value <symbol>None</symbol>. This can be done whether the function is strict or not. 上で示したように、PL/Python関数からSQL NULL値を返すには、Noneという値を返してください。 関数を厳密とした場合でも厳密としない場合でも、これを行うことができます。

46.2.3. 配列、リスト #

<title>Arrays, Lists</title>

SQL array values are passed into PL/Python as a Python list. To return an SQL array value out of a PL/Python function, return a Python list: SQL配列値はPythonのリストとしてPL/Pythonに渡されます。 PL/Python関数の外部にSQL配列値を返すためには、Pythonのリストを返します。

CREATE FUNCTION return_arr()
  RETURNS int[]
AS $$
return [1, 2, 3, 4, 5]
$$ LANGUAGE plpython3u;

SELECT return_arr();
 return_arr
-------------
 {1,2,3,4,5}
(1 row)

Multidimensional arrays are passed into PL/Python as nested Python lists. A 2-dimensional array is a list of lists, for example. When returning a multi-dimensional SQL array out of a PL/Python function, the inner lists at each level must all be of the same size. For example: 多次元配列はPL/Pythonに入れ子のPythonのリストとして渡されます。 例えば、2次元配列はリストのリストです。 PL/Pythonから多次元のSQLの配列を返す場合には、各レベルの内側のリストはすべて同じ大きさでなければなりません。 例えば、

CREATE FUNCTION test_type_conversion_array_int4(x int4[]) RETURNS int4[] AS $$
plpy.info(x, type(x))
return x
$$ LANGUAGE plpython3u;

SELECT * FROM test_type_conversion_array_int4(ARRAY[[1,2,3],[4,5,6]]);
INFO:  ([[1, 2, 3], [4, 5, 6]], <type 'list'>)
 test_type_conversion_array_int4
---------------------------------
 {{1,2,3},{4,5,6}}
(1 row)

Other Python sequences, like tuples, are also accepted for backwards-compatibility with PostgreSQL versions 9.6 and below, when multi-dimensional arrays were not supported. However, they are always treated as one-dimensional arrays, because they are ambiguous with composite types. For the same reason, when a composite type is used in a multi-dimensional array, it must be represented by a tuple, rather than a list. タプル等のその他のPythonのシーケンスも、PostgreSQLバージョン9.6以下との後方互換性のために受け入れられます。当時は、多次元配列はサポートされていませんでした。 しかしながら、複合型と区別できないため、常に1次元配列として扱われます。 同じ理由で、複合型を多次元配列内で使う場合、リストではなくタプルとして表現しなければなりません。

Note that in Python, strings are sequences, which can have undesirable effects that might be familiar to Python programmers: Pythonでは、文字列はシーケンスであることに注意してください。 これは予想できない影響を与えることがありますが、Pythonプログラマには慣れたものでしょう。

CREATE FUNCTION return_str_arr()
  RETURNS varchar[]
AS $$
return "hello"
$$ LANGUAGE plpython3u;

SELECT return_str_arr();
 return_str_arr
----------------
 {h,e,l,l,o}
(1 row)

46.2.4. 複合型 #

<title>Composite Types</title>

Composite-type arguments are passed to the function as Python mappings. The element names of the mapping are the attribute names of the composite type. If an attribute in the passed row has the null value, it has the value <symbol>None</symbol> in the mapping. Here is an example: 複合型の引数はPythonのマップとして渡されます。 マップの要素名は複合型の属性名です。 渡された行の属性値がNULLの場合、マップ上ではNoneという値となります。 以下に例を示します。

CREATE TABLE employee (
  name text,
  salary integer,
  age integer
);

CREATE FUNCTION overpaid (e employee)
  RETURNS boolean
AS $$
  if e["salary"] > 200000:
    return True
  if (e["age"] < 30) and (e["salary"] > 100000):
    return True
  return False
$$ LANGUAGE plpython3u;

There are multiple ways to return row or composite types from a Python function. The following examples assume we have: Python関数から行または複合型を返す方法は複数存在します。 以下の例はそれを前提とします。

CREATE TYPE named_value AS (
  name   text,
  value  integer
);

A composite result can be returned as a: 複合型の結果は以下のように返されます。

シーケンス型(タプルまたはリスト。ただしインデックス付けができないためsetは不可)

Returned sequence objects must have the same number of items as the composite result type has fields. The item with index 0 is assigned to the first field of the composite type, 1 to the second and so on. For example: 返されるシーケンスオブジェクトは、結果の複合型が持つフィールドと同じ項目数をもたなければなりません。 0というインデックスの項目が複合型の最初のフィールド、1が次のフィールド、などとなります。 以下に例を示します。

CREATE FUNCTION make_pair (name text, value integer)
  RETURNS named_value
AS $$
  return ( name, value )

  # or alternatively, as list: return [ name, value ]

  # もしくは、リストとして返すなら: return [ name, value ]
$$ LANGUAGE plpython3u;

To return an SQL null for any column, insert <symbol>None</symbol> at the corresponding position. 任意の列でSQL NULL値を返すには、対応する位置にNoneを挿入します。

When an array of composite types is returned, it cannot be returned as a list, because it is ambiguous whether the Python list represents a composite type, or another array dimension. 複合型の配列を返す場合、Pythonのリストが複合型を表しているのか、また別の配列の次元を表しているのかあいまいですので、リストとして返すことはできません。

マップ(辞書)

The value for each result type column is retrieved from the mapping with the column name as key. Example: 結果型の列の値は、列名をキーとして持つマップから取り出されます。 以下に例を示します。

CREATE FUNCTION make_pair (name text, value integer)
  RETURNS named_value
AS $$
  return { "name": name, "value": value }
$$ LANGUAGE plpython3u;

Any extra dictionary key/value pairs are ignored. Missing keys are treated as errors. To return an SQL null value for any column, insert <symbol>None</symbol> with the corresponding column name as the key. 余計な辞書のキーと値の組み合わせは無視されます。 存在しないキーはエラーとして扱われます。 任意の列でSQL NULLを返すためには、対応する列名をキーとしてNoneを挿入してください。

オブジェクト(__getattr__メソッドを提供する任意のオブジェクト)

This works the same as a mapping. Example: これはマップと同じように動作します。 以下に例を示します。

CREATE FUNCTION make_pair (name text, value integer)
  RETURNS named_value
AS $$
  class named_value:
    def __init__ (self, n, v):
      self.name = n
      self.value = v
  return named_value(name, value)

  # or simply
  class nv: pass
  nv.name = name
  nv.value = value
  return nv
$$ LANGUAGE plpython3u;

Functions with <literal>OUT</literal> parameters are also supported. For example: OUTパラメータを用いる関数もサポートされています。 以下に例を示します。

CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$
return (1, 2)
$$ LANGUAGE plpython3u;

SELECT * FROM multiout_simple();

Output parameters of procedures are passed back the same way. For example: プロシージャの出力パラメータは同様に戻されます。 以下に例を示します。

CREATE PROCEDURE python_triple(INOUT a integer, INOUT b integer) AS $$
return (a * 3, b * 3)
$$ LANGUAGE plpython3u;

CALL python_triple(5, 10);

46.2.5. 集合を返す関数 #

<title>Set-Returning Functions</title>

A <application>PL/Python</application> function can also return sets of scalar or composite types. There are several ways to achieve this because the returned object is internally turned into an iterator. The following examples assume we have composite type: また、PL/Python関数はスカラまたは複合型の集合を返すこともできます。 返されるオブジェクトは内部的にイテレータに変換されるため、複数の実現方法があります。 以下の例では、以下の複合型が存在することを仮定します。

CREATE TYPE greeting AS (
  how text,
  who text
);

A set result can be returned from a: 集合という結果は以下から返されます。

シーケンス型(タプル、リスト、セット)

CREATE FUNCTION greet (how text)
  RETURNS SETOF greeting
AS $$
  # return tuple containing lists as composite types
  # all other combinations work also
  return ( [ how, "World" ], [ how, "PostgreSQL" ], [ how, "PL/Python" ] )
$$ LANGUAGE plpython3u;

イテレータ(__iter__メソッドとnextメソッドを提供する任意のオブジェクト)

CREATE FUNCTION greet (how text)
  RETURNS SETOF greeting
AS $$
  class producer:
    def __init__ (self, how, who):
      self.how = how
      self.who = who
      self.ndx = -1

    def __iter__ (self):
      return self

    def next (self):
      self.ndx += 1
      if self.ndx == len(self.who):
        raise StopIteration
      return ( self.how, self.who[self.ndx] )

  return producer(how, [ "World", "PostgreSQL", "PL/Python" ])
$$ LANGUAGE plpython3u;

ジェネレータ(yield)

CREATE FUNCTION greet (how text)
  RETURNS SETOF greeting
AS $$
  for who in [ "World", "PostgreSQL", "PL/Python" ]:
    yield ( how, who )
$$ LANGUAGE plpython3u;

Set-returning functions with <literal>OUT</literal> parameters (using <literal>RETURNS SETOF record</literal>) are also supported. For example: RETURNS SETOF recordを使用して)OUTパラメータを持つ集合を返す関数もサポートされます。 以下に例を示します。

CREATE FUNCTION multiout_simple_setof(n integer, OUT integer, OUT integer) RETURNS SETOF record AS $$
return [(1, 2)] * n
$$ LANGUAGE plpython3u;

SELECT * FROM multiout_simple_setof(3);