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

F.38. postgres_fdw — 外部のPostgreSQLサーバに格納されたデータにアクセスする #

<title>postgres_fdw &mdash; access data stored in external <productname>PostgreSQL</productname> servers</title>

The <filename>postgres_fdw</filename> module provides the foreign-data wrapper <literal>postgres_fdw</literal>, which can be used to access data stored in external <productname>PostgreSQL</productname> servers. postgres_fdwモジュールは、外部のPostgreSQLサーバに格納されたデータをアクセスするために使用する、postgres_fdw外部データラッパーを提供します。

The functionality provided by this module overlaps substantially with the functionality of the older <xref linkend="dblink"/> module. But <filename>postgres_fdw</filename> provides more transparent and standards-compliant syntax for accessing remote tables, and can give better performance in many cases. 実質上、本モジュールの提供する機能は以前のdblinkモジュールが提供する機能と重複していますが、postgres_fdwはリモートのテーブルにアクセスするためにより透過的で標準に準拠した構文を利用できるほか、多くの場合においてより良い性能を得る事ができます。

To prepare for remote access using <filename>postgres_fdw</filename>: postgres_fdwを使用したリモートアクセスを準備するには:

  1. Install the <filename>postgres_fdw</filename> extension using <xref linkend="sql-createextension"/>. CREATE EXTENSIONを使用してpostgres_fdw拡張をインストールします。

  2. Create a foreign server object, using <xref linkend="sql-createserver"/>, to represent each remote database you want to connect to. Specify connection information, except <literal>user</literal> and <literal>password</literal>, as options of the server object. CREATE SERVERを使用して、接続しようとする各リモートデータベースを定義する外部サーバオブジェクトを作成します。 userおよびpasswordを除く接続パラメータを、外部サーバオブジェクトのオプションとして指定します。

  3. Create a user mapping, using <xref linkend="sql-createusermapping"/>, for each database user you want to allow to access each foreign server. Specify the remote user name and password to use as <literal>user</literal> and <literal>password</literal> options of the user mapping. CREATE USER MAPPINGを使用して、外部サーバへのアクセスを許可するデータベースユーザごとにユーザマッピングを作成します。 ユーザマッピングのuserおよびpasswordオプションを使用してリモートユーザのためのユーザ名とパスワードを指定します。

  4. Create a foreign table, using <xref linkend="sql-createforeigntable"/> or <xref linkend="sql-importforeignschema"/>, for each remote table you want to access. The columns of the foreign table must match the referenced remote table. You can, however, use table and/or column names different from the remote table's, if you specify the correct remote names as options of the foreign table object. CREATE FOREIGN TABLEもしくはIMPORT FOREIGN SCHEMAを使用して、アクセスしたいリモートテーブルごとに外部テーブルを作成します。 外部テーブルのカラム定義は被参照側のリモートテーブルに一致していなければなりません。 しかしながら、外部テーブルのオプションとして正しいリモートの名前を外部テーブルのオプションに指定すれば、テーブルおよびカラム名はリモートのものと異なった名前を付ける事ができます。

Now you need only <command>SELECT</command> from a foreign table to access the data stored in its underlying remote table. You can also modify the remote table using <command>INSERT</command>, <command>UPDATE</command>, <command>DELETE</command>, <command>COPY</command>, or <command>TRUNCATE</command>. (Of course, the remote user you have specified in your user mapping must have privileges to do these things.) 今のところ、リモートテーブルに格納されているデータにアクセスするには少なくとも外部テーブルに対するSELECT権限が必要です。 また、INSERTUPDATEDELETECOPYTRUNCATEを使用してリモートテーブルを操作する事もできます。 (もちろん、ユーザマッピングで指定されたリモートユーザは、これらの操作を実行する権限を有している必要があります)

Note that the <literal>ONLY</literal> option specified in <command>SELECT</command>, <command>UPDATE</command>, <command>DELETE</command> or <command>TRUNCATE</command> has no effect when accessing or modifying the remote table. リモートテーブルをアクセスあるいは変更する際、SELECTUPDATEDELETETRUNCATEに対してONLYオプションを指定しても効果はありません。

Note that <filename>postgres_fdw</filename> currently lacks support for <command>INSERT</command> statements with an <literal>ON CONFLICT DO UPDATE</literal> clause. However, the <literal>ON CONFLICT DO NOTHING</literal> clause is supported, provided a unique index inference specification is omitted. Note also that <filename>postgres_fdw</filename> supports row movement invoked by <command>UPDATE</command> statements executed on partitioned tables, but it currently does not handle the case where a remote partition chosen to insert a moved row into is also an <command>UPDATE</command> target partition that will be updated elsewhere in the same command. postgres_fdwは今のところ、ON CONFLICT DO UPDATE句のあるINSERT文をサポートしていないことに注意して下さい。 しかし、一意インデックスの推定の指定を省略しているならば、ON CONFLICT DO NOTHING句はサポートされます。 postgres_fdwは、パーティションテーブルで実行されたUPDATE文により引き起こされる行の移動をサポートしますが、移動した行を挿入するよう選択されたリモートパーティションが同じコマンド内で別の場所で更新されるUPDATE対象のパーティションでもある場合は、今のところ扱わないことにも注意してください。

It is generally recommended that the columns of a foreign table be declared with exactly the same data types, and collations if applicable, as the referenced columns of the remote table. Although <filename>postgres_fdw</filename> is currently rather forgiving about performing data type conversions at need, surprising semantic anomalies may arise when types or collations do not match, due to the remote server interpreting query conditions differently from the local server. 一般的な推奨事項として、可能であれば外部テーブルのカラムを、被参照側のリモートテーブル側のカラムと全く同一のデータ型および照合順序によって定義してください。 postgres_fdwは必要に応じてデータ型の変換を行いますが、リモートサーバがローカルサーバとは異なる問い合わせ条件の解釈を行うため、データ型や照合順序が一致していないと、時には予期しない意味論的に異常な結果を得る事があるかもしれません。

Note that a foreign table can be declared with fewer columns, or with a different column order, than its underlying remote table has. Matching of columns to the remote table is by name, not position. リモートテーブルより少ないカラム数で、あるいは異なった順序であっても外部テーブルを定義できる事に留意してください。 リモートテーブル側のカラムとの対応付けは、その位置ではなく、名前によって行われます。

F.38.1. postgres_fdwの外部データラッパーオプション #

<title>FDW Options of postgres_fdw</title>

F.38.1.1. 接続オプション #

<title>Connection Options</title>

A foreign server using the <filename>postgres_fdw</filename> foreign data wrapper can have the same options that <application>libpq</application> accepts in connection strings, as described in <xref linkend="libpq-paramkeywords"/>, except that these options are not allowed or have special handling: postgres_fdw外部データラッパーを使用する外部サーバは、以下に記す許されていないものや特別な取り扱いのものを除き、34.1.2に記載されているlibpqが接続文字列としてサポートするものと同一のオプションを使用する事ができます。

  • <literal>user</literal>, <literal>password</literal> and <literal>sslpassword</literal> (specify these in a user mapping, instead, or use a service file) userpasswordおよびsslpassword(これらは代わりにユーザマッピングのオプションの中で指定するか、サービスファイルを使用します)

  • <literal>client_encoding</literal> (this is automatically set from the local server encoding) client_encoding(これはローカルサーバのエンコーディングが自動的にセットされます)

  • <literal>application_name</literal> - this may appear in <emphasis>either or both</emphasis> a connection and <xref linkend="guc-pgfdw-application-name"/>. If both are present, <varname>postgres_fdw.application_name</varname> overrides the connection setting. Unlike <application>libpq</application>, <filename>postgres_fdw</filename> allows <varname>application_name</varname> to include <quote>escape sequences</quote>. See <xref linkend="guc-pgfdw-application-name"/> for details. application_name-これは接続とpostgres_fdw.application_nameのいずれかまたは両方に現れる可能性があります。 両方が存在する場合、postgres_fdw.application_nameは接続設定を上書きします。 libpqとは異なり、postgres_fdwapplication_nameエスケープシーケンスを含めることを許可します。 詳細はpostgres_fdw.application_nameを参照してください。

  • <literal>fallback_application_name</literal> (always set to <literal>postgres_fdw</literal>) fallback_application_name(自動的にpostgres_fdwとセットされます)

  • <literal>sslkey</literal> and <literal>sslcert</literal> - these may appear in <emphasis>either or both</emphasis> a connection and a user mapping. If both are present, the user mapping setting overrides the connection setting. sslkeysslcert - これは、接続とユーザマッピングのどちらか一方、または両方に現れます。 両方に存在する場合、ユーザマッピングの設定が接続設定に優先します。

Only superusers may create or modify user mappings with the <literal>sslcert</literal> or <literal>sslkey</literal> settings. スーパーユーザのみがsslcertsslkeyの設定のあるユーザマッピングを作成したり修正したりできます。

Non-superusers may connect to foreign servers using password authentication or with GSSAPI delegated credentials, so specify the <literal>password</literal> option for user mappings belonging to non-superusers where password authentication is required. 非スーパーユーザはパスワード認証またはGSSAPI委任認証情報を使用して外部サーバに接続するため、パスワード認証が必要な非スーパーユーザに属するユーザマッピングにはpasswordオプションを指定します。

A superuser may override this check on a per-user-mapping basis by setting the user mapping option <literal>password_required 'false'</literal>, e.g., ユーザマッピングオプションpassword_required 'false'を設定することで、スーパーユーザはこのユーザマッピング単位の検査を無効にできます。例えば以下の通りです。

ALTER USER MAPPING FOR some_non_superuser SERVER loopback_nopw
OPTIONS (ADD password_required 'false');

To prevent unprivileged users from exploiting the authentication rights of the unix user the postgres server is running as to escalate to superuser rights, only the superuser may set this option on a user mapping. 非特権ユーザが、postgresサーバが動作しているunixユーザの認証権限を悪用して、スーパーユーザ権限へ昇格するのを防ぐため、スーパーユーザのみがユーザーマッピングでこのオプションを設定できます。

Care is required to ensure that this does not allow the mapped user the ability to connect as superuser to the mapped database per CVE-2007-3278 and CVE-2007-6601. Don't set <literal>password_required=false</literal> on the <literal>public</literal> role. Keep in mind that the mapped user can potentially use any client certificates, <filename>.pgpass</filename>, <filename>.pg_service.conf</filename> etc. in the unix home directory of the system user the postgres server runs as. They can also use any trust relationship granted by authentication modes like <literal>peer</literal> or <literal>ident</literal> authentication. CVE-2007-3278やCVE-2007-6601により、マップされたユーザがマップされたデータベースにスーパーユーザとして接続するのを許可しないことを確実にするよう注意が必要です。 publicロールではpassword_required=falseを設定しないでください。 postgresサーバが動作しているシステムユーザのunixのホームディレクトリにある、任意のクライアント証明書や.pgpass.pg_service.confなどをマップされたユーザは潜在的には利用可能なことを心に留めておいてください。 peerident認証のような認証モードで付与された信頼関係を使うこともできます。

F.38.1.2. オブジェクト名オプション #

<title>Object Name Options</title>

These options can be used to control the names used in SQL statements sent to the remote <productname>PostgreSQL</productname> server. These options are needed when a foreign table is created with names different from the underlying remote table's names. これらのオプションによりリモートのPostgreSQLサーバに送出されるSQL文で使用される名前を制御する事ができます。 外部テーブルがリモートテーブルとは異なった名前で定義されている場合、これらのオプションは必須です。

schema_name (string)

This option, which can be specified for a foreign table, gives the schema name to use for the foreign table on the remote server. If this option is omitted, the name of the foreign table's schema is used. 外部テーブルに対して指定できるこのオプションは、リモートサーバ上のリモートテーブルのスキーマ名を与えます。 省略された場合、外部テーブルのスキーマ名が使用されます。 (訳注: to use for the foreign table on... は remote table の間違い。)

table_name (string)

This option, which can be specified for a foreign table, gives the table name to use for the foreign table on the remote server. If this option is omitted, the foreign table's name is used. 外部テーブルに対して指定できるこのオプションは、リモートサーバ上のリモートテーブル名を与えます。 省略された場合、外部テーブルのテーブル名が使用されます。

column_name (string)

This option, which can be specified for a column of a foreign table, gives the column name to use for the column on the remote server. If this option is omitted, the column's name is used. 外部テーブルのカラムに対して指定できるこのオプションは、リモートサーバ上のカラム名を与えます。 省略された場合、外部テーブルのカラム名が使用されます。

F.38.1.3. コスト推定オプション #

<title>Cost Estimation Options</title>

<filename>postgres_fdw</filename> retrieves remote data by executing queries against remote servers, so ideally the estimated cost of scanning a foreign table should be whatever it costs to be done on the remote server, plus some overhead for communication. The most reliable way to get such an estimate is to ask the remote server and then add something for overhead &mdash; but for simple queries, it may not be worth the cost of an additional remote query to get a cost estimate. So <filename>postgres_fdw</filename> provides the following options to control how cost estimation is done: postgres_fdwはリモートサーバに対するクエリを実行しリモートのデータを受信します。したがって、理想的には外部テーブルをスキャンする推定コストは、それをリモートサーバで実行するコストと通信オーバーヘッドの和となります。 この推定を行うための最も信頼できる方法は、リモートサーバに問い合わせを行い、その結果にオーバーヘッド分を加算する事ですが、小さいクエリではコスト推定を得るための追加的な問い合わせに要するコストに見合わないかもしれません。 そこで、どのようにコスト推定を行うかを制御するため、postgres_fdwは以下のようなオプションを提供します。

use_remote_estimate (boolean)

This option, which can be specified for a foreign table or a foreign server, controls whether <filename>postgres_fdw</filename> issues remote <command>EXPLAIN</command> commands to obtain cost estimates. A setting for a foreign table overrides any setting for its server, but only for that table. The default is <literal>false</literal>. 外部テーブルまたは外部サーバに指定できるこのオプションは、コスト推定を得るためにpostgres_fdwがリモートのEXPLAINコマンドを発行するかどうかを制御します。 外部テーブルに対する設定は、関連付けられた外部サーバに対する設定を上書きしますが、その効果は当該外部テーブルに限定されます。 デフォルト値はfalseです。

fdw_startup_cost (floating point)

This option, which can be specified for a foreign server, is a floating point value that is added to the estimated startup cost of any foreign-table scan on that server. This represents the additional overhead of establishing a connection, parsing and planning the query on the remote side, etc. The default value is <literal>100</literal>. 外部テーブルまたは外部サーバに指定できるこのオプションは、当該外部サーバに関連付けられた全ての外部テーブルスキャンの推定開始コストに加算される浮動小数点値です。 これは、接続の確立、リモート側でのクエリのパース・最適化など、追加的なオーバーヘッドを表現します。 デフォルト値は100です。

fdw_tuple_cost (floating point)

This option, which can be specified for a foreign server, is a floating point value that is used as extra cost per-tuple for foreign-table scans on that server. This represents the additional overhead of data transfer between servers. You might increase or decrease this number to reflect higher or lower network delay to the remote server. The default value is <literal>0.01</literal>. 外部サーバに指定できるこのオプションは、このサーバでの外部テーブルのスキャンにおいて、各タプル毎に発生する追加的なコストとして使用される浮動小数点値です。 これは、サーバ間のデータ転送における追加的なオーバーヘッドを表現し、リモートサーバへのネットワーク遅延の高低を反映するためにこの数値を増減することができます。 デフォルト値は0.01です。

When <literal>use_remote_estimate</literal> is true, <filename>postgres_fdw</filename> obtains row count and cost estimates from the remote server and then adds <literal>fdw_startup_cost</literal> and <literal>fdw_tuple_cost</literal> to the cost estimates. When <literal>use_remote_estimate</literal> is false, <filename>postgres_fdw</filename> performs local row count and cost estimation and then adds <literal>fdw_startup_cost</literal> and <literal>fdw_tuple_cost</literal> to the cost estimates. This local estimation is unlikely to be very accurate unless local copies of the remote table's statistics are available. Running <xref linkend="sql-analyze"/> on the foreign table is the way to update the local statistics; this will perform a scan of the remote table and then calculate and store statistics just as though the table were local. Keeping local statistics can be a useful way to reduce per-query planning overhead for a remote table &mdash; but if the remote table is frequently updated, the local statistics will soon be obsolete. use_remote_estimatetrueの時、postgres_fdwはリモートサーバから行数とコスト推定値を取得し、それをfdw_startup_costfdw_tuple_costに加算します。 一方、use_remote_estimatefalseの時、postgres_fdwはローカルの行数とコスト推定値を取得しfdw_startup_costfdw_tuple_costをコスト推定値に加算します。 このローカルな推定は、リモートテーブルの統計情報のローカルコピーが利用可能でないと、正確である見込みはほとんどありません。 ローカルな統計情報を更新するには外部テーブルに対するANALYZEを実行します。これはリモートテーブルに対するスキャンを実行し、あたかもローカルなテーブルであるかのように統計情報の計算と保存を行います。 ローカルな統計情報を保存する事で、問い合わせの度にリモートテーブルの実行計画を作成するオーバーヘッドを削減する事ができます。 しかしながら、リモートテーブルの更新頻度が高ければローカルの統計情報はすぐに実態を反映しなくなるでしょう。

The following option controls how such an <command>ANALYZE</command> operation behaves: 以下のオプションは、このようなANALYZE操作の動作を制御します。

analyze_sampling (text)

This option, which can be specified for a foreign table or a foreign server, determines if <command>ANALYZE</command> on a foreign table samples the data on the remote side, or reads and transfers all data and performs the sampling locally. The supported values are <literal>off</literal>, <literal>random</literal>, <literal>system</literal>, <literal>bernoulli</literal> and <literal>auto</literal>. <literal>off</literal> disables remote sampling, so all data are transferred and sampled locally. <literal>random</literal> performs remote sampling using the <literal>random()</literal> function to choose returned rows, while <literal>system</literal> and <literal>bernoulli</literal> rely on the built-in <literal>TABLESAMPLE</literal> methods of those names. <literal>random</literal> works on all remote server versions, while <literal>TABLESAMPLE</literal> is supported only since 9.5. <literal>auto</literal> (the default) picks the recommended sampling method automatically; currently it means either <literal>bernoulli</literal> or <literal>random</literal> depending on the remote server version. このオプションは、外部テーブルまたはリモートサーバに対して指定できます。外部テーブルでのANALYZEによるサンプリングがリモート側で行われるか、すべてのデータを読み取ってローカルでサンプリングするかを決定します。 サポートされている値は、offrandomsystembernoulliautoです。 offはリモートサンプリングを無効にし、すべてのデータが転送されてローカルでサンプリングされます。 randomrandom()関数を使用してリモートサンプリングを実行し、返された行を選択します。一方、systembernoulliはそれらの名前の組込みTABLESAMPLEメソッドに依存します。 randomはすべてのリモートサーババージョンで動作し、TABLESAMPLEは9.5以降でのみサポートされます。 auto(デフォルト)は推奨されるサンプリング方法を自動的に選択します。現在はリモートサーバのバージョンに応じてbernoulliまたはrandomのいずれかを意味します。

F.38.1.4. リモート実行オプション #

<title>Remote Execution Options</title>

By default, only <literal>WHERE</literal> clauses using built-in operators and functions will be considered for execution on the remote server. Clauses involving non-built-in functions are checked locally after rows are fetched. If such functions are available on the remote server and can be relied on to produce the same results as they do locally, performance can be improved by sending such <literal>WHERE</literal> clauses for remote execution. This behavior can be controlled using the following option: デフォルトでは、組み込みの演算子および関数を使ったWHERE句のみがリモートサーバでの実行を考慮されます。 組み込みでない関数を含む句は、行が取得された後、ローカルで検査されます。 そのような関数がリモートサーバで利用でき、かつローカルで実行するのと同じ結果を生成すると信頼できるときは、そのようなWHERE句をリモートでの実行のために送出することでパフォーマンスを向上することができます。 この動作は以下のオプションを使うことで制御できます。

extensions (string)

This option is a comma-separated list of names of <productname>PostgreSQL</productname> extensions that are installed, in compatible versions, on both the local and remote servers. Functions and operators that are immutable and belong to a listed extension will be considered shippable to the remote server. This option can only be specified for foreign servers, not per-table. このオプションは、PostgreSQLの拡張で、ローカルとリモートの両方に、互換のバージョンがインストールされているものの名前のリストです。 IMMUTABLEで、列挙された拡張に属する関数と演算子は、リモートサーバに送出可能とみなされます。 このオプションは外部サーバについてのみ指定可能で、テーブル毎の指定ではありません。

When using the <literal>extensions</literal> option, <emphasis>it is the user's responsibility</emphasis> that the listed extensions exist and behave identically on both the local and remote servers. Otherwise, remote queries may fail or behave unexpectedly. extensionsオプションを使用する場合、列挙する拡張が存在し、かつローカルとリモートのサーバで同一の動作をするようにすることはユーザの責任です。 そうでない場合、リモートの問い合わせは失敗したり、期待と異なる動作をするかもしれません。

fetch_size (integer)

This option specifies the number of rows <filename>postgres_fdw</filename> should get in each fetch operation. It can be specified for a foreign table or a foreign server. The option specified on a table overrides an option specified for the server. The default is <literal>100</literal>. このオプションは、postgres_fdwが1回のフェッチの動作で何行のデータを取得するかを指定します。 これは外部テーブルあるいは外部サーバに対して指定できます。 テーブルに対して指定されたオプションは、サーバに対して指定されたオプションよりも優先します。 デフォルトは100です。

batch_size (integer)

This option specifies the number of rows <filename>postgres_fdw</filename> should insert in each insert operation. It can be specified for a foreign table or a foreign server. The option specified on a table overrides an option specified for the server. The default is <literal>1</literal>. このオプションは、postgres_fdwが個々のINSERT操作で挿入する行数を指定します。 外部テーブルあるいは外部サーバに対して指定することができます。 テーブルに対してこのオプションを指定すると、サーバに対して指定されたオプションを上書きします。 デフォルトは1です。

Note the actual number of rows <filename>postgres_fdw</filename> inserts at once depends on the number of columns and the provided <literal>batch_size</literal> value. The batch is executed as a single query, and the libpq protocol (which <filename>postgres_fdw</filename> uses to connect to a remote server) limits the number of parameters in a single query to 65535. When the number of columns * <literal>batch_size</literal> exceeds the limit, the <literal>batch_size</literal> will be adjusted to avoid an error. postgres_fdwが実際に一度に挿入する行数は、列の数と指定されたbatch_size値に依存することに注意してください。 一つのバッチは単一の問い合わせとして実行され、libpqプロトコル(postgres_fdwがリモートサーバに接続するために使用します)は単一の問い合わせにおけるパラメータ数を65535に制限していることに注意してください。 列数 * batch_sizeがその上限を超えると、エラーを回避するためにbatch_sizeが調整されます。

This option also applies when copying into foreign tables. In that case the actual number of rows <filename>postgres_fdw</filename> copies at once is determined in a similar way to the insert case, but it is limited to at most 1000 due to implementation restrictions of the <command>COPY</command> command. このオプションは、外部テーブルにコピーする場合にも適用されます。 その場合、postgres_fdwが一度にコピーする実際の行数は、挿入する場合と類似した方法で決定されますが、COPYコマンドの実装上の制限により1000以下に制限されます。

F.38.1.5. 非同期実行オプション #

<title>Asynchronous Execution Options</title>

<filename>postgres_fdw</filename> supports asynchronous execution, which runs multiple parts of an <structname>Append</structname> node concurrently rather than serially to improve performance. This execution can be controlled using the following option: postgres_fdwは非同期実行をサポートします。 これは性能を向上するために、複数のAppendノードの部分を順番にではなく、並行して実行します。 この実行は以下のオプションで制御できます。

async_capable (boolean)

This option controls whether <filename>postgres_fdw</filename> allows foreign tables to be scanned concurrently for asynchronous execution. It can be specified for a foreign table or a foreign server. A table-level option overrides a server-level option. The default is <literal>false</literal>. このオプションは、postgres_fdwが非同期実行の際に外部テーブルの並列走査を許すかどうかを制御します。 外部テーブルあるいは外部サーバに対して指定できます。 テーブルレベルのオプションはサーバレベルのオプションを上書きします。 デフォルトはfalseです。

In order to ensure that the data being returned from a foreign server is consistent, <filename>postgres_fdw</filename> will only open one connection for a given foreign server and will run all queries against that server sequentially even if there are multiple foreign tables involved, unless those tables are subject to different user mappings. In such a case, it may be more performant to disable this option to eliminate the overhead associated with running queries asynchronously. 外部サーバから返却されるデータの一貫性を保証するために、postgres_fdwは一つの外部サーバに対して一つの接続だけを開きます。 そして、テーブルが異なるユーザマッピングの対象でない限り、複数の外部テーブルが存在してもすべての問い合わせをサーバに対して順番に実行します。 この場合、問い合わせを非同期に実行することによるオーバーヘッドをなくすためにこのオプションを使用しないほうが性能が良くなるかもしれません。

Asynchronous execution is applied even when an <structname>Append</structname> node contains subplan(s) executed synchronously as well as subplan(s) executed asynchronously. In such a case, if the asynchronous subplans are ones processed using <filename>postgres_fdw</filename>, tuples from the asynchronous subplans are not returned until after at least one synchronous subplan returns all tuples, as that subplan is executed while the asynchronous subplans are waiting for the results of asynchronous queries sent to foreign servers. This behavior might change in a future release. Appendノードに順次実行されるサブプランが含まれていても、あるいは非同期実行されるサブプランが含まれていても、非同期実行は適用されます。 このような場合では、非同期実行のサブプランがpostgres_fdwを用いて処理されると、外部サーバに送信される非同期問い合わせの結果を非同期サブプランが待っている間に順次実行サブプランが実行されるため、少なくとも1つの順次実行サブプランがすべてのタプルを返すまでは、非同期実行サブプランによるタプルは返りません。 このふるまいは将来のリリースでは変更されるかもしれません。

F.38.1.6. トランザクション制御オプション #

<title>Transaction Management Options</title>

As described in the Transaction Management section, in <filename>postgres_fdw</filename> transactions are managed by creating corresponding remote transactions, and subtransactions are managed by creating corresponding remote subtransactions. When multiple remote transactions are involved in the current local transaction, by default <filename>postgres_fdw</filename> commits or aborts those remote transactions serially when the local transaction is committed or aborted. When multiple remote subtransactions are involved in the current local subtransaction, by default <filename>postgres_fdw</filename> commits or aborts those remote subtransactions serially when the local subtransaction is committed or aborted. Performance can be improved with the following options: 「トランザクション制御」節で説明されているように、postgres_fdwでは、トランザクションは対応するリモートトランザクションを作成することで制御され、サブトランザクションは対応するリモートサブトランザクションを作成することで制御されます。 現在のローカルトランザクションに複数のリモートトランザクションが含まれている場合、デフォルトではpostgres_fdwはローカルトランザクションがコミットまたは中断されたときに、これらのリモートトランザクションを順番にコミットまたは中断します。 現在のローカルサブトランザクションに複数のリモートサブトランザクションが含まれている場合、デフォルトではpostgres_fdwはローカルサブトランザクションがコミットまたは中断されたときに、これらのリモートサブトランザクションを順番にコミットまたは中断します。 次のオプションでパフォーマンスを向上させることができます。

parallel_commit (boolean)

This option controls whether <filename>postgres_fdw</filename> commits, in parallel, remote transactions opened on a foreign server in a local transaction when the local transaction is committed. This setting also applies to remote and local subtransactions. This option can only be specified for foreign servers, not per-table. The default is <literal>false</literal>. このオプションは、ローカルトランザクションがコミットされたときに、ローカルトランザクション内の外部サーバで開かれたリモートトランザクションをpostgres_fdwが並行してコミットするかどうかを制御します。 この設定は、リモートサブトランザクションとローカルサブトランザクションにも適用されます。 このオプションは外部サーバに対してのみ指定でき、テーブル単位では指定できません。 デフォルトはfalseです。

parallel_abort (boolean)

This option controls whether <filename>postgres_fdw</filename> aborts, in parallel, remote transactions opened on a foreign server in a local transaction when the local transaction is aborted. This setting also applies to remote and local subtransactions. This option can only be specified for foreign servers, not per-table. The default is <literal>false</literal>. このオプションは、ローカルトランザクションが中断されたときに、ローカルトランザクション内の外部サーバで開かれたリモートトランザクションをpostgres_fdwが並行して中断するかどうかを制御します。 この設定は、リモートサブトランザクションとローカルサブトランザクションにも適用されます。 このオプションは外部サーバに対してのみ指定でき、テーブル単位では指定できません。 デフォルトはfalseです。

If multiple foreign servers with these options enabled are involved in a local transaction, multiple remote transactions on those foreign servers are committed or aborted in parallel across those foreign servers when the local transaction is committed or aborted. このオプションが有効になっている複数の外部サーバがローカルトランザクションに関与している場合、これらの外部サーバ上の複数のリモートトランザクションは、ローカルトランザクションがコミットまたは中断されるときに、これらの外部サーバ間で並列にコミットまたは中断されます。

When these options are enabled, a foreign server with many remote transactions may see a negative performance impact when the local transaction is committed or aborted. このオプションを有効にすると、多数のリモートトランザクションを持つ外部サーバは、ローカルトランザクションがコミットまたは中断されたときにパフォーマンスが悪影響を受ける可能性があります。

F.38.1.7. 更新機能オプション #

<title>Updatability Options</title>

By default all foreign tables using <filename>postgres_fdw</filename> are assumed to be updatable. This may be overridden using the following option: デフォルトではpostgres_fdwを使用する全ての外部テーブルは更新可能であると想定されます。以下のオプションにより、この挙動を上書きする事ができます。

updatable (boolean)

This option controls whether <filename>postgres_fdw</filename> allows foreign tables to be modified using <command>INSERT</command>, <command>UPDATE</command> and <command>DELETE</command> commands. It can be specified for a foreign table or a foreign server. A table-level option overrides a server-level option. The default is <literal>true</literal>. このオプションは、postgres_fdwINSERTUPDATEあるいはDELETEコマンドを使用して外部テーブルを操作する事を許可するかどうかを規定します。 外部テーブルで指定されたオプションは、外部サーバにおいて指定されたオプションを上書きします。 デフォルト値はtrueです。

Of course, if the remote table is not in fact updatable, an error would occur anyway. Use of this option primarily allows the error to be thrown locally without querying the remote server. Note however that the <literal>information_schema</literal> views will report a <filename>postgres_fdw</filename> foreign table to be updatable (or not) according to the setting of this option, without any check of the remote server. もちろん、リモートテーブルが実際には更新可能ではなかった場合、いずれにしてもエラーが発生するでしょう。このオプションを使用することで、リモートサーバへの問い合わせを行う事なくローカルでエラーを発生させることができます。 また、information_schemaビューは、このオプションの値に従ってpostgres_fdw管理下の外部テーブルを更新可能(あるいは不可能)であるとレポートする事に留意してください。 リモートサーバ側のチェックは一切行われません。

F.38.1.8. 切り詰めオプション #

<title>Truncatability Options</title>

By default all foreign tables using <filename>postgres_fdw</filename> are assumed to be truncatable. This may be overridden using the following option: デフォルトではpostgres_fdwを使用する外部テーブルは切り詰め可能であると見なされます。 これは以下のオプションで変更が可能です。

truncatable (boolean)

This option controls whether <filename>postgres_fdw</filename> allows foreign tables to be truncated using the <command>TRUNCATE</command> command. It can be specified for a foreign table or a foreign server. A table-level option overrides a server-level option. The default is <literal>true</literal>. このオプションはpostgres_fdwが外部テーブルをTRUNCATEを使って切り詰めることができるかどうかを制御します。 外部テーブルあるいは外部サーバに対して指定できます。 外部テーブルで指定されたオプションは、外部サーバにおいて指定されたオプションを上書きします。 デフォルトはtrueです。

Of course, if the remote table is not in fact truncatable, an error would occur anyway. Use of this option primarily allows the error to be thrown locally without querying the remote server. もちろん外部テーブルが切り詰め不可能なら、結局エラーが生じます。 このオプションを使用することにより、リモートサーバに問い合わせることなくエラーをローカルで起こすことができるのが主な用途です。

F.38.1.9. インポートのオプション #

<title>Importing Options</title>

<filename>postgres_fdw</filename> is able to import foreign table definitions using <xref linkend="sql-importforeignschema"/>. This command creates foreign table definitions on the local server that match tables or views present on the remote server. If the remote tables to be imported have columns of user-defined data types, the local server must have compatible types of the same names. postgres_fdwIMPORT FOREIGN SCHEMAを使って、外部テーブルの定義をインポートすることができます。 このコマンドは、リモートのサーバ上に存在するテーブルあるいはビューとマッチする外部テーブルの定義をローカルサーバ上に作成します。 インポートするリモートのテーブルにユーザ定義のデータ型の列がある場合、ローカルサーバにも同じ名前の互換性のある型がなければなりません。

Importing behavior can be customized with the following options (given in the <command>IMPORT FOREIGN SCHEMA</command> command): インポートの動作は以下のオプションでカスタマイズできます(IMPORT FOREIGN SCHEMAコマンドで指定します)。

import_collate (boolean)

This option controls whether column <literal>COLLATE</literal> options are included in the definitions of foreign tables imported from a foreign server. The default is <literal>true</literal>. You might need to turn this off if the remote server has a different set of collation names than the local server does, which is likely to be the case if it's running on a different operating system. If you do so, however, there is a very severe risk that the imported table columns' collations will not match the underlying data, resulting in anomalous query behavior. このオプションは、列のCOLLATEオプションが、外部サーバからインポートする外部テーブルの定義に含まれているかどうかを制御します。 デフォルトはtrueです。 リモートサーバとローカルサーバで照合順序の名前の集合が異なる場合は、この設定を無効にする必要があるでしょう。 リモートサーバが異なるOSで動作しているなら、そういうことがありそうです。 しかし、そうした時には、インポートしたテーブルの列の照合順序が実際のデータと一致せず、問い合わせの振る舞いが結果として異常になる大きなリスクがあります。

Even when this parameter is set to <literal>true</literal>, importing columns whose collation is the remote server's default can be risky. They will be imported with <literal>COLLATE "default"</literal>, which will select the local server's default collation, which could be different. このパラメータがtrueのときでさえ、照合順序がリモートサーバのデフォルトである列をインポートするのは危険性があります。 これらの列はCOLLATE "default"としてインポートされますが、ローカルサーバのデフォルトの照合順序は異なるかもしれません。

import_default (boolean)

This option controls whether column <literal>DEFAULT</literal> expressions are included in the definitions of foreign tables imported from a foreign server. The default is <literal>false</literal>. If you enable this option, be wary of defaults that might get computed differently on the local server than they would be on the remote server; <function>nextval()</function> is a common source of problems. The <command>IMPORT</command> will fail altogether if an imported default expression uses a function or operator that does not exist locally. このオプションは、列のDEFAULT式が外部サーバからインポートされる外部テーブルの定義に含まれているかどうかを制御します。 デフォルトはfalseです。 このオプションを有効にする場合は、ローカルサーバとリモートサーバで異なる計算をされるデフォルトに注意して下さい。 nextval()はよくある問題の一つです。 インポートされるデフォルト式がローカルには存在しない関数または演算子を使っていた場合、IMPORTは失敗します。

import_generated (boolean)

This option controls whether column <literal>GENERATED</literal> expressions are included in the definitions of foreign tables imported from a foreign server. The default is <literal>true</literal>. The <command>IMPORT</command> will fail altogether if an imported generated expression uses a function or operator that does not exist locally. このオプションは、外部サーバからインポートされた外部テーブルの定義にGENERATED列式が含まれるかどうかを制御します。 デフォルトはtrueです。 インポートされる生成式がローカルには存在しない関数あるいは演算子を使っていた場合、IMPORTは失敗します。

import_not_null (boolean)

This option controls whether column <literal>NOT NULL</literal> constraints are included in the definitions of foreign tables imported from a foreign server. The default is <literal>true</literal>. このオプションは、列のNOT NULL制約が、外部サーバからインポートされる外部テーブルの定義に含まれているかどうかを制御します。 デフォルトはtrueです。

Note that constraints other than <literal>NOT NULL</literal> will never be imported from the remote tables. Although <productname>PostgreSQL</productname> does support check constraints on foreign tables, there is no provision for importing them automatically, because of the risk that a constraint expression could evaluate differently on the local and remote servers. Any such inconsistency in the behavior of a check constraint could lead to hard-to-detect errors in query optimization. So if you wish to import check constraints, you must do so manually, and you should verify the semantics of each one carefully. For more detail about the treatment of check constraints on foreign tables, see <xref linkend="sql-createforeigntable"/>. NOT NULL以外の制約は決してリモートのテーブルからインポートされないことに注意して下さい。 PostgreSQLは外部テーブルのcheck制約をサポートしていますが、それを自動的にインポートする予定はありません。 なぜなら、制約の式はローカルとリモートのサーバで異なる評価をされる危険があるからです。 check制約でそのような一貫しない動作があると、問い合わせの最適化で検知するのが難しい誤りが発生するかもしれません。 そのため、check制約をインポートしたい場合は、それを手作業で実行する必要があり、またその一つ一つの意味を注意深く確認するべきです。 外部テーブルのcheck制約の取扱いについて、詳しくはCREATE FOREIGN TABLEを参照して下さい。

Tables or foreign tables which are partitions of some other table are imported only when they are explicitly specified in <literal>LIMIT TO</literal> clause. Otherwise they are automatically excluded from <xref linkend="sql-importforeignschema"/>. Since all data can be accessed through the partitioned table which is the root of the partitioning hierarchy, importing only partitioned tables should allow access to all the data without creating extra objects. 他のテーブルのパーティションであるテーブルや外部テーブルは、明示的なLIMIT TO句が指定されている場合にのみインポートされます。 そうでなければそれらは、IMPORT FOREIGN SCHEMAから自動的に除外されます。 パーティショニング化階層のルートであるパーティションテーブルを介してすべてのデータにアクセスできるため、パーティション化テーブルのみをインポートすることで余分なオブジェクトを作成せずにすべてのデータにアクセスできます。

F.38.1.10. 接続管理オプション #

<title>Connection Management Options</title>

By default, all connections that <filename>postgres_fdw</filename> establishes to foreign servers are kept open in the local session for re-use. デフォルトではpostgres_fdwが外部サーバに確立した接続は、再利用のためにローカルセッションにおいて開いたまま維持されます。

keep_connections (boolean)

This option controls whether <filename>postgres_fdw</filename> keeps the connections to the foreign server open so that subsequent queries can re-use them. It can only be specified for a foreign server. The default is <literal>on</literal>. If set to <literal>off</literal>, all connections to this foreign server will be discarded at the end of each transaction. このオプションは、後の再利用のためにpostgres_fdwが外部サーバに対する接続を保持したままにしておくかどうかを制御します。 外部サーバに対してのみ指定ができます。 デフォルトはonです。 offに設定すると、この外部サーバに対するすべての接続は個々のトランザクションの終了時に破棄されます。

F.38.2. 関数 #

<title>Functions</title>
postgres_fdw_get_connections(OUT server_name text, OUT valid boolean) returns setof record

This function returns the foreign server names of all the open connections that <filename>postgres_fdw</filename> established from the local session to the foreign servers. It also returns whether each connection is valid or not. <literal>false</literal> is returned if the foreign server connection is used in the current local transaction but its foreign server or user mapping is changed or dropped (Note that server name of an invalid connection will be <literal>NULL</literal> if the server is dropped), and then such invalid connection will be closed at the end of that transaction. <literal>true</literal> is returned otherwise. If there are no open connections, no record is returned. Example usage of the function: この関数は、postgres_fdwによってローカルセッションから外部サーバに確立されたすべての開いている接続の外部サーバ名を返します。 個々の接続が有効かどうかも返します。 外部サーバの接続が現在のローカルトランザクションで使用されていても、外部サーバあるいはユーザマッピングが変更あるいは削除されるとfalseが返り(無効な接続のサーバ名は、サーバが削除されるとNULLになることに注意してください)、そうした無効な接続はトランザクションの終了時に閉じられます。 そうでなければtrueが返ります。 開いた接続がなければレコードは返りません。 関数の使用例を示します。

postgres=# SELECT * FROM postgres_fdw_get_connections() ORDER BY 1;
 server_name | valid
-------------+-------
 loopback1   | t
 loopback2   | f

postgres_fdw_disconnect(server_name text) returns boolean

This function discards the open connections that are established by <filename>postgres_fdw</filename> from the local session to the foreign server with the given name. Note that there can be multiple connections to the given server using different user mappings. If the connections are used in the current local transaction, they are not disconnected and warning messages are reported. This function returns <literal>true</literal> if it disconnects at least one connection, otherwise <literal>false</literal>. If no foreign server with the given name is found, an error is reported. Example usage of the function: この関数は、postgres_fdwによってローカルセッションから指定された名前の外部サーバに確立された開いている接続を破棄します。 異なるユーザマッピングを使用することにより、指定されたサーバに複数の接続が存在する可能性があることに注意してください。 現在のローカルトランザクションで接続が使われている場合は、接続は切断されず、警告メッセージが報告されます。 少なくとも1つの接続が切断されると、この関数はtrueを返し、そうでない場合はfalseを返します。 指定した名前の外部サーバが存在しなければ、エラーが報告されます。 この関数の使用例を示します。

postgres=# SELECT postgres_fdw_disconnect('loopback1');
 postgres_fdw_disconnect
-------------------------
 t

postgres_fdw_disconnect_all() returns boolean

This function discards all the open connections that are established by <filename>postgres_fdw</filename> from the local session to foreign servers. If the connections are used in the current local transaction, they are not disconnected and warning messages are reported. This function returns <literal>true</literal> if it disconnects at least one connection, otherwise <literal>false</literal>. Example usage of the function: この関数は、postgres_fdwによってローカルセッションから外部サーバに確立されたすべての開いている接続を破棄します。 現在のローカルトランザクションで接続が使われている場合は、接続は切断されず、警告メッセージが報告されます。 少なくとも1つの接続が切断されると、この関数はtrueを返します。 さもなければfalseが返ります。 この関数の使用例を示します。

postgres=# SELECT postgres_fdw_disconnect_all();
 postgres_fdw_disconnect_all
-----------------------------
 t

F.38.3. 接続管理 #

<title>Connection Management</title>

<filename>postgres_fdw</filename> establishes a connection to a foreign server during the first query that uses a foreign table associated with the foreign server. By default this connection is kept and re-used for subsequent queries in the same session. This behavior can be controlled using <literal>keep_connections</literal> option for a foreign server. If multiple user identities (user mappings) are used to access the foreign server, a connection is established for each user mapping. postgres_fdwは、外部サーバに関連付けられた外部テーブルを参照するクエリを最初に実行する際に、外部サーバへの接続を確立します。 デフォルトではこの接続は保持され、同じセッションで以降の問い合わせのために再利用されます。 この振る舞いは外部サーバのkeep_connectionsオプションを使って制御できます。 しかし、外部サーバへのアクセスに対して複数のユーザ識別子(ユーザマッピング)が使用される場合には、接続はユーザマッピング毎に確立される事になります。

When changing the definition of or removing a foreign server or a user mapping, the associated connections are closed. But note that if any connections are in use in the current local transaction, they are kept until the end of the transaction. Closed connections will be re-established when they are necessary by future queries using a foreign table. 外部サーバあるいはユーザマッピングの定義を変更ないし削除している場合は、関連する接続は閉じられます。 しかし、現在のローカルトランザクションが接続を使っていると、接続はトランザクションが終了するまでは維持されることに注意してください。 このあと外部テーブルを使用する問い合わせで必要になれば、閉じた接続は再び確立されます。

Once a connection to a foreign server has been established, it's by default kept until the local or corresponding remote session exits. To disconnect a connection explicitly, <literal>keep_connections</literal> option for a foreign server may be disabled, or <function>postgres_fdw_disconnect</function> and <function>postgres_fdw_disconnect_all</function> functions may be used. For example, these are useful to close connections that are no longer necessary, thereby releasing connections on the foreign server. ひとたび外部サーバに接続が確立されると、デフォルトではローカルあるいは関連するリモートセッションが終了するまで接続は維持されます。 明示的に接続を切断するには外部サーバのkeep_connectionsオプションを無効にするか、postgres_fdw_disconnect関数あるいはpostgres_fdw_disconnect_all関数を使用します。 たとえば、必要がなくなった接続を切断し、それによって外部サーバの接続を開放するのにこれらの関数が役に立ちます。

F.38.4. トランザクション制御 #

<title>Transaction Management</title>

During a query that references any remote tables on a foreign server, <filename>postgres_fdw</filename> opens a transaction on the remote server if one is not already open corresponding to the current local transaction. The remote transaction is committed or aborted when the local transaction commits or aborts. Savepoints are similarly managed by creating corresponding remote savepoints. 外部サーバ上のリモートテーブルを参照する際に、まだトランザクションが開始されていなければpostgres_fdwはリモートサーバ上でトランザクションを開始します。 ローカルのトランザクションがコミット、あるいはアボートした時、リモートのトランザクションも同様にコミット、あるいはアボートします。 セーブポイントも同様に管理され、リモート側に関連付けられたセーブポイントが作成されます。

The remote transaction uses <literal>SERIALIZABLE</literal> isolation level when the local transaction has <literal>SERIALIZABLE</literal> isolation level; otherwise it uses <literal>REPEATABLE READ</literal> isolation level. This choice ensures that if a query performs multiple table scans on the remote server, it will get snapshot-consistent results for all the scans. A consequence is that successive queries within a single transaction will see the same data from the remote server, even if concurrent updates are occurring on the remote server due to other activities. That behavior would be expected anyway if the local transaction uses <literal>SERIALIZABLE</literal> or <literal>REPEATABLE READ</literal> isolation level, but it might be surprising for a <literal>READ COMMITTED</literal> local transaction. A future <productname>PostgreSQL</productname> release might modify these rules. ローカルトランザクションがSERIALIZABLE分離レベルを用いている時、リモートトランザクションもSERIALIZABLE分離レベルを使用します。 それ以外の場合にはREPEATABLE READ分離レベルを使用します。 これは、あるクエリが複数のテーブルスキャンをリモート側で行う際に、確実に全てのスキャンにおいて一貫したスナップショットで結果を取り出すためです。 その結果、別の要求によってリモートサーバ側で競合する更新が発生したとしても、あるトランザクション内の問い合わせはリモートサーバからの一貫したデータを参照する事となります。 ローカルのトランザクションがSERIALIZABLEあるいはREPEATABLE READ分離レベルを用いている場合、この動作は期待通りのものでしょう。 一方、ローカルのトランザクションがREAD COMMITTED分離レベルを使用している場合には、予想外の動作かもしれません。 将来のPostgreSQLリリースではこれらのルールに変更が加えられるかもしれません。

Note that it is currently not supported by <filename>postgres_fdw</filename> to prepare the remote transaction for two-phase commit. postgres_fdwは今のところ、二相コミットのためのリモートトランザクションの準備をサポートしていないことに注意して下さい。

F.38.5. リモート問い合わせの最適化 #

<title>Remote Query Optimization</title>

<filename>postgres_fdw</filename> attempts to optimize remote queries to reduce the amount of data transferred from foreign servers. This is done by sending query <literal>WHERE</literal> clauses to the remote server for execution, and by not retrieving table columns that are not needed for the current query. To reduce the risk of misexecution of queries, <literal>WHERE</literal> clauses are not sent to the remote server unless they use only data types, operators, and functions that are built-in or belong to an extension that's listed in the foreign server's <literal>extensions</literal> option. Operators and functions in such clauses must be <literal>IMMUTABLE</literal> as well. For an <command>UPDATE</command> or <command>DELETE</command> query, <filename>postgres_fdw</filename> attempts to optimize the query execution by sending the whole query to the remote server if there are no query <literal>WHERE</literal> clauses that cannot be sent to the remote server, no local joins for the query, no row-level local <literal>BEFORE</literal> or <literal>AFTER</literal> triggers or stored generated columns on the target table, and no <literal>CHECK OPTION</literal> constraints from parent views. In <command>UPDATE</command>, expressions to assign to target columns must use only built-in data types, <literal>IMMUTABLE</literal> operators, or <literal>IMMUTABLE</literal> functions, to reduce the risk of misexecution of the query. 外部サーバからのデータ転送量を削減するため、postgres_fdwはリモート問い合わせを最適化しようと試みます。 これは問い合わせのWHERE句をリモートサーバに送出する事、およびクエリで必要とされていないカラムを取得しない事により行われます。 問い合わせの誤作動のリスクを下げるため、組み込みあるいは外部サーバのextensionsオプションに列挙されている拡張に属するデータ型、演算子、関数だけを用いたものでない限り、リモートサーバにWHERE句は送出されません。 また、そのようなWHERE句で使われる演算子と関数はIMMUTABLEでなければなりません。 UPDATEあるいはDELETEの問い合わせについては、リモートサーバに送出できないWHERE句がなく、問い合わせにローカルな結合がなく、対象のテーブルにローカルな行レベルのBEFOREあるいはAFTERトリガーや格納された生成列がなく、親ビューからのCHECK OPTION制約がないのであれば、postgres_fdwは問い合わせ全体をリモートサーバに送出することで、問い合わせの実行の最適化を図ります。 UPDATEでは、問い合わせの誤った実行のリスクを低減するため、対象列への代入式では組み込みのデータ型、IMMUTABLE演算子、IMMUTABLE関数のみを使わなければなりません。

When <filename>postgres_fdw</filename> encounters a join between foreign tables on the same foreign server, it sends the entire join to the foreign server, unless for some reason it believes that it will be more efficient to fetch rows from each table individually, or unless the table references involved are subject to different user mappings. While sending the <literal>JOIN</literal> clauses, it takes the same precautions as mentioned above for the <literal>WHERE</literal> clauses. 同一の外部サーバ上の外部テーブルの間の結合がある場合、postgres_fdwはその結合全体を外部サーバに送出します。 ただし、何らかの理由で各テーブルから個別に行を取得する方が効率的だと思われる場合、あるいは結合に含まれるテーブルの参照が異なるユーザマッピングに従う場合を除きます。 JOIN句を送出するにあたり、WHERE句に関して上で説明したことと同じ注意が払われます。

The query that is actually sent to the remote server for execution can be examined using <command>EXPLAIN VERBOSE</command>. リモートサーバでの実行のために実際に送出される問い合わせはEXPLAIN VERBOSEを用いて調べる事ができます。

F.38.6. リモート問い合わせ実行環境 #

<title>Remote Query Execution Environment</title>

In the remote sessions opened by <filename>postgres_fdw</filename>, the <xref linkend="guc-search-path"/> parameter is set to just <literal>pg_catalog</literal>, so that only built-in objects are visible without schema qualification. This is not an issue for queries generated by <filename>postgres_fdw</filename> itself, because it always supplies such qualification. However, this can pose a hazard for functions that are executed on the remote server via triggers or rules on remote tables. For example, if a remote table is actually a view, any functions used in that view will be executed with the restricted search path. It is recommended to schema-qualify all names in such functions, or else attach <literal>SET search_path</literal> options (see <xref linkend="sql-createfunction"/>) to such functions to establish their expected search path environment. postgres_fdwが開いたリモートセッションでは、search_pathパラメータはpg_catalogにだけ設定されますので、スキーマで修飾しなければ組み込みオブジェクトだけが可視です。 postgres_fdw自身が生成した問い合わせでは、常にそのような修飾を行ないますので、これは問題になりません。 しかし、リモートテーブルのトリガやルールによってリモートサーバ上で実行された関数にとっては問題の原因となり得ます。 例えば、リモートテーブルが実際にはビューであれば、そのビューで使われている関数はすべて制限された検索パスで実行されるでしょう。 期待される検索パス環境を確立できるよう、そのような関数では名前はすべてスキーマ修飾するか、そのような関数にSET search_pathオプション(CREATE FUNCTION参照)を付けることをお薦めします。

<filename>postgres_fdw</filename> likewise establishes remote session settings for various parameters: postgres_fdwは、同様に様々なパラメータでリモートセッション設定を確立します。

  • <xref linkend="guc-timezone"/> is set to <literal>UTC</literal> TimeZoneUTCに設定されます。

  • <xref linkend="guc-datestyle"/> is set to <literal>ISO</literal> DateStyleISOに設定されます。

  • <xref linkend="guc-intervalstyle"/> is set to <literal>postgres</literal> IntervalStylepostgresに設定されます。

  • <xref linkend="guc-extra-float-digits"/> is set to <literal>3</literal> for remote servers 9.0 and newer and is set to <literal>2</literal> for older versions extra_float_digitsはリモートサーバが9.0以上では3に設定され、それより古いバージョンでは2に設定されます。

These are less likely to be problematic than <varname>search_path</varname>, but can be handled with function <literal>SET</literal> options if the need arises. これはsearch_pathほど問題にはならないでしょうが、もし必要になったら関数のSETオプションで処理してください。

It is <emphasis>not</emphasis> recommended that you override this behavior by changing the session-level settings of these parameters; that is likely to cause <filename>postgres_fdw</filename> to malfunction. 上のパラメータのセッションレベルの設定を変更することで、この振舞いを覆すことはお薦めしませんpostgres_fdwが正常に動作しない原因となるでしょう。

F.38.7. バージョン間互換性 #

<title>Cross-Version Compatibility</title>

<filename>postgres_fdw</filename> can be used with remote servers dating back to <productname>PostgreSQL</productname> 8.3. Read-only capability is available back to 8.1. A limitation however is that <filename>postgres_fdw</filename> generally assumes that immutable built-in functions and operators are safe to send to the remote server for execution, if they appear in a <literal>WHERE</literal> clause for a foreign table. Thus, a built-in function that was added since the remote server's release might be sent to it for execution, resulting in <quote>function does not exist</quote> or a similar error. This type of failure can be worked around by rewriting the query, for example by embedding the foreign table reference in a sub-<literal>SELECT</literal> with <literal>OFFSET 0</literal> as an optimization fence, and placing the problematic function or operator outside the sub-<literal>SELECT</literal>. postgres_fdwのリモートサーバにはPostgreSQL 8.3以降のバージョンを使用する事ができます。 読み取り専用であれば、8.1以降のバージョンまで可能です。 一方、postgres_fdwIMMUTABLE属性を持った組み込みの演算子と関数が外部テーブルのWHERE句に含まれる場合、リモート側で実行しても安全であると仮定します。そのため、リモートサーバのリリース後に追加された関数が実行のために送出されるかもしれず、結果として関数が見つかりませんあるいは類するエラーを発生させる事になります。 この種の問題は問い合わせの書き換えによって対処する事ができます。 例えば、最適化を妨げるため、外部テーブルへの参照をOFFSET 0を付けてsub-SELECTに埋め込み、問題のある関数や演算子をsub-SELECTの外に配置するなどの方法があります。

F.38.8. 設定パラメータ #

<title>Configuration Parameters</title>
postgres_fdw.application_name (string) #

Specifies a value for <xref linkend="guc-application-name"/> configuration parameter used when <filename>postgres_fdw</filename> establishes a connection to a foreign server. This overrides <varname>application_name</varname> option of the server object. Note that change of this parameter doesn't affect any existing connections until they are re-established. postgres_fdwが外部サーバへの接続を確立する際に使用されるapplication_name設定パラメータの値を指定します。 これにより、サーバオブジェクトのapplication_nameオプションが上書きされます。 このパラメータを変更しても、再確立されるまで既存の接続には影響しません。

<varname>postgres_fdw.application_name</varname> can be any string of any length and contain even non-ASCII characters. However when it's passed to and used as <varname>application_name</varname> in a foreign server, note that it will be truncated to less than <symbol>NAMEDATALEN</symbol> characters and anything other than printable ASCII characters will be replaced with question marks (<literal>?</literal>). See <xref linkend="guc-application-name"/> for details. postgres_fdw.application_nameは任意の長さの文字列で、非ASCII文字も含むことさえできます。 しかし、外部サーバでapplication_nameとして渡されて使用される場合、NAMEDATALEN文字未満に切り捨てられ、印字可能なASCII文字以外の文字は疑問符(?)に置き換えられることに注意してください。 詳細はapplication_nameを参照してください。

<literal>%</literal> characters begin <quote>escape sequences</quote> that are replaced with status information as outlined below. Unrecognized escapes are ignored. Other characters are copied straight to the application name. Note that it's not allowed to specify a plus/minus sign or a numeric literal after the <literal>%</literal> and before the option, for alignment and padding. %文字はエスケープシーケンスを開始し、以下で説明するようにステータス情報に置き換えられます。 認識されないエスケープは無視されます。 他の文字はアプリケーション名に直接コピーされます。 位置合わせとパディングのために、%の後とオプションの前にプラス/マイナス記号または数値リテラルを指定することはできないことに注意してください。

エスケープ効果
%aローカルサーバ上のアプリケーション名
%c Session ID on local server (see <xref linkend="guc-log-line-prefix"/> for details) ローカルサーバ上のセッションID(詳細はlog_line_prefixを参照)
%C Cluster name on local server (see <xref linkend="guc-cluster-name"/> for details) ローカルサーバ上のクラスタ名(詳細はcluster_nameを参照)
%uローカルサーバ上のユーザ名
%dローカルサーバ上のデータベース名
%pローカルサーバ上のバックエンドのプロセスID
%%文字 %

For example, suppose user <literal>local_user</literal> establishes a connection from database <literal>local_db</literal> to <literal>foreign_db</literal> as user <literal>foreign_user</literal>, the setting <literal>'db=%d, user=%u'</literal> is replaced with <literal>'db=local_db, user=local_user'</literal>. たとえば、ユーザーlocal_userがデータベースlocal_dbからforeign_dbへの接続をユーザーforeign_userとして確立するとします。 設定'db=%d,user=%u''db=local_db,user=local_user'に置き換えられます。

F.38.9. 例 #

<title>Examples</title>

Here is an example of creating a foreign table with <literal>postgres_fdw</literal>. First install the extension: これはpostgres_fdwで外部テーブルを作成する例です。 まず、拡張をインストールします。

CREATE EXTENSION postgres_fdw;

Then create a foreign server using <xref linkend="sql-createserver"/>. In this example we wish to connect to a <productname>PostgreSQL</productname> server on host <literal>192.83.123.89</literal> listening on port <literal>5432</literal>. The database to which the connection is made is named <literal>foreign_db</literal> on the remote server: 次に、CREATE SERVERを使って外部サーバを作成します。 この例では、ホスト192.83.123.89でポート5432を監視しているPostgreSQLサーバに接続します。 接続されるデータベースはリモートサーバ上でforeign_dbという名前です。

CREATE SERVER foreign_server
        FOREIGN DATA WRAPPER postgres_fdw
        OPTIONS (host '192.83.123.89', port '5432', dbname 'foreign_db');

A user mapping, defined with <xref linkend="sql-createusermapping"/>, is needed as well to identify the role that will be used on the remote server: リモートサーバで使われるロールを特定するためにユーザマッピングも必要です。ユーザマッピングはCREATE USER MAPPINGで定義されます。

CREATE USER MAPPING FOR local_user
        SERVER foreign_server
        OPTIONS (user 'foreign_user', password 'password');

Now it is possible to create a foreign table with <xref linkend="sql-createforeigntable"/>. In this example we wish to access the table named <structname>some_schema.some_table</structname> on the remote server. The local name for it will be <structname>foreign_table</structname>: これでCREATE FOREIGN TABLEにより外部テーブルが作成できるようになりました。 この例では、リモートサーバのsome_schema.some_tableという名前のテーブルにアクセスします。 対応するローカルの名前はforeign_tableです。

CREATE FOREIGN TABLE foreign_table (
        id integer NOT NULL,
        data text
)
        SERVER foreign_server
        OPTIONS (schema_name 'some_schema', table_name 'some_table');

It's essential that the data types and other properties of the columns declared in <command>CREATE FOREIGN TABLE</command> match the actual remote table. Column names must match as well, unless you attach <literal>column_name</literal> options to the individual columns to show how they are named in the remote table. In many cases, use of <link linkend="sql-importforeignschema"><command>IMPORT FOREIGN SCHEMA</command></link> is preferable to constructing foreign table definitions manually. CREATE FOREIGN TABLEで宣言した列のデータ型やその他の属性は、実際のリモートテーブルと一致していることが必須です。 リモートテーブルでどのような名前なのかを個々の列に対してcolumn_nameオプションで指定しない限り、列名も一致していなければなりません。 多くの場合、外部テーブルの定義を手作業で作成するよりも、IMPORT FOREIGN SCHEMAを使用する方が望ましいです。

F.38.10. 作者 #

<title>Author</title>

Shigeru Hanada <email>shigeru.hanada@gmail.com</email> 花田 茂