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

38.14. ユーザ定義の演算子 #

<title>User-Defined Operators</title>

Every operator is <quote>syntactic sugar</quote> for a call to an underlying function that does the real work; so you must first create the underlying function before you can create the operator. However, an operator is <emphasis>not merely</emphasis> syntactic sugar, because it carries additional information that helps the query planner optimize queries that use the operator. The next section will be devoted to explaining that additional information. 演算子は裏側で実際の作業を行う関数を呼び出す構文上の飾りです。 ですから、演算子を作成する前にまずこの基礎となる関数を作成する必要があります。 しかし、演算子は単なる構文上の飾りではありません。 問い合わせプランナによる演算子を使用する問い合わせの最適化を補助する追加情報をやり取りするからです。 次節では、この追加情報について重点的に説明します。

<productname>PostgreSQL</productname> supports prefix and infix operators. Operators can be overloaded;<indexterm><primary>overloading</primary><secondary>operators</secondary></indexterm> that is, the same operator name can be used for different operators that have different numbers and types of operands. When a query is executed, the system determines the operator to call from the number and types of the provided operands. PostgreSQLでは前置演算子、中置演算子をサポートしています。 演算子はオーバーロード可能です。 つまり、同じ演算子名をオペランドの数と型が異なる演算子に対して使用することができるということです。 問い合わせが実行されると、システムは与えられたオペランドの数と型より呼び出すべき演算子を決定します。

Here is an example of creating an operator for adding two complex numbers. We assume we've already created the definition of type <type>complex</type> (see <xref linkend="xtypes"/>). First we need a function that does the work, then we can define the operator: 以下に2つの複素数の加算を行う演算子を作成する例を示します。 既にcomplex型の定義(38.13を参照)を作成していることを前提としています。 まず、実作業を行う関数が必要です。 その後、演算子を定義できます。

CREATE FUNCTION complex_add(complex, complex)
    RETURNS complex
    AS 'filename', 'complex_add'
    LANGUAGE C IMMUTABLE STRICT;

CREATE OPERATOR + (
    leftarg = complex,
    rightarg = complex,
    function = complex_add,
    commutator = +
);

Now we could execute a query like this: これで以下のような問い合わせを実行できるようになります。

SELECT (a + b) AS c FROM test_complex;

        c
-----------------
 (5.2,6.05)
 (133.42,144.95)

We've shown how to create a binary operator here. To create a prefix operator, just omit the <literal>leftarg</literal>. The <literal>function</literal> clause and the argument clauses are the only required items in <command>CREATE OPERATOR</command>. The <literal>commutator</literal> clause shown in the example is an optional hint to the query optimizer. Further details about <literal>commutator</literal> and other optimizer hints appear in the next section. ここでは二項演算子をどのように作成するのかを示しました。 前置演算子を作成するには、単にleftargを省略するだけです。 function句と引数用の句のみがCREATE OPERATORでの必須項目です。 例で示したcommutator句は省略可能で、問い合わせオプティマイザへのヒントとなります。 commutatorやその他のオプティマイザへのヒントについての詳細は次節で説明します。