]> begriffs open source - ai-pg/blob - full-docs/txt/postgres-fdw.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / postgres-fdw.txt
1
2 F.38. postgres_fdw — access data stored in external PostgreSQL servers #
3
4    F.38.1. FDW Options of postgres_fdw
5    F.38.2. Functions
6    F.38.3. Connection Management
7    F.38.4. Transaction Management
8    F.38.5. Remote Query Optimization
9    F.38.6. Remote Query Execution Environment
10    F.38.7. Cross-Version Compatibility
11    F.38.8. Wait Events
12    F.38.9. Configuration Parameters
13    F.38.10. Examples
14    F.38.11. Author
15
16    The postgres_fdw module provides the foreign-data wrapper postgres_fdw,
17    which can be used to access data stored in external PostgreSQL servers.
18
19    The functionality provided by this module overlaps substantially with
20    the functionality of the older dblink module. But postgres_fdw provides
21    more transparent and standards-compliant syntax for accessing remote
22    tables, and can give better performance in many cases.
23
24    To prepare for remote access using postgres_fdw:
25     1. Install the postgres_fdw extension using CREATE EXTENSION.
26     2. Create a foreign server object, using CREATE SERVER, to represent
27        each remote database you want to connect to. Specify connection
28        information, except user and password, as options of the server
29        object.
30     3. Create a user mapping, using CREATE USER MAPPING, for each database
31        user you want to allow to access each foreign server. Specify the
32        remote user name and password to use as user and password options
33        of the user mapping.
34     4. Create a foreign table, using CREATE FOREIGN TABLE or IMPORT
35        FOREIGN SCHEMA, for each remote table you want to access. The
36        columns of the foreign table must match the referenced remote
37        table. You can, however, use table and/or column names different
38        from the remote table's, if you specify the correct remote names as
39        options of the foreign table object.
40
41    Now you need only SELECT from a foreign table to access the data stored
42    in its underlying remote table. You can also modify the remote table
43    using INSERT, UPDATE, DELETE, COPY, or TRUNCATE. (Of course, the remote
44    user you have specified in your user mapping must have privileges to do
45    these things.)
46
47    Note that the ONLY option specified in SELECT, UPDATE, DELETE or
48    TRUNCATE has no effect when accessing or modifying the remote table.
49
50    Note that postgres_fdw currently lacks support for INSERT statements
51    with an ON CONFLICT DO UPDATE clause. However, the ON CONFLICT DO
52    NOTHING clause is supported, provided a unique index inference
53    specification is omitted. Note also that postgres_fdw supports row
54    movement invoked by UPDATE statements executed on partitioned tables,
55    but it currently does not handle the case where a remote partition
56    chosen to insert a moved row into is also an UPDATE target partition
57    that will be updated elsewhere in the same command.
58
59    It is generally recommended that the columns of a foreign table be
60    declared with exactly the same data types, and collations if
61    applicable, as the referenced columns of the remote table. Although
62    postgres_fdw is currently rather forgiving about performing data type
63    conversions at need, surprising semantic anomalies may arise when types
64    or collations do not match, due to the remote server interpreting query
65    conditions differently from the local server.
66
67    Note that a foreign table can be declared with fewer columns, or with a
68    different column order, than its underlying remote table has. Matching
69    of columns to the remote table is by name, not position.
70
71 F.38.1. FDW Options of postgres_fdw #
72
73 F.38.1.1. Connection Options #
74
75    A foreign server using the postgres_fdw foreign data wrapper can have
76    the same options that libpq accepts in connection strings, as described
77    in Section 32.1.2, except that these options are not allowed or have
78    special handling:
79      * user, password and sslpassword (specify these in a user mapping
80        instead, or use a service file)
81      * client_encoding (this is automatically set from the local server
82        encoding)
83      * application_name - this may appear in either or both a connection
84        and postgres_fdw.application_name. If both are present,
85        postgres_fdw.application_name overrides the connection setting.
86        Unlike libpq, postgres_fdw allows application_name to include
87        “escape sequences”. See postgres_fdw.application_name for details.
88      * fallback_application_name (always set to postgres_fdw)
89      * sslkey and sslcert - these may appear in either or both a
90        connection and a user mapping. If both are present, the user
91        mapping setting overrides the connection setting.
92
93    Only superusers may create or modify user mappings with the sslcert or
94    sslkey settings.
95
96    Non-superusers may connect to foreign servers using password
97    authentication or with GSSAPI delegated credentials, so specify the
98    password option for user mappings belonging to non-superusers where
99    password authentication is required.
100
101    A superuser may override this check on a per-user-mapping basis by
102    setting the user mapping option password_required 'false', e.g.,
103 ALTER USER MAPPING FOR some_non_superuser SERVER loopback_nopw
104 OPTIONS (ADD password_required 'false');
105
106    To prevent unprivileged users from exploiting the authentication rights
107    of the unix user the postgres server is running as to escalate to
108    superuser rights, only the superuser may set this option on a user
109    mapping.
110
111    Care is required to ensure that this does not allow the mapped user the
112    ability to connect as superuser to the mapped database per
113    CVE-2007-3278 and CVE-2007-6601. Don't set password_required=false on
114    the public role. Keep in mind that the mapped user can potentially use
115    any client certificates, .pgpass, .pg_service.conf etc. in the unix
116    home directory of the system user the postgres server runs as. (For
117    details on how home directories are found, see Section 32.16.) They can
118    also use any trust relationship granted by authentication modes like
119    peer or ident authentication.
120
121 F.38.1.2. Object Name Options #
122
123    These options can be used to control the names used in SQL statements
124    sent to the remote PostgreSQL server. These options are needed when a
125    foreign table is created with names different from the underlying
126    remote table's names.
127
128    schema_name (string)
129           This option, which can be specified for a foreign table, gives
130           the schema name to use for the foreign table on the remote
131           server. If this option is omitted, the name of the foreign
132           table's schema is used.
133
134    table_name (string)
135           This option, which can be specified for a foreign table, gives
136           the table name to use for the foreign table on the remote
137           server. If this option is omitted, the foreign table's name is
138           used.
139
140    column_name (string)
141           This option, which can be specified for a column of a foreign
142           table, gives the column name to use for the column on the remote
143           server. If this option is omitted, the column's name is used.
144
145 F.38.1.3. Cost Estimation Options #
146
147    postgres_fdw retrieves remote data by executing queries against remote
148    servers, so ideally the estimated cost of scanning a foreign table
149    should be whatever it costs to be done on the remote server, plus some
150    overhead for communication. The most reliable way to get such an
151    estimate is to ask the remote server and then add something for
152    overhead — but for simple queries, it may not be worth the cost of an
153    additional remote query to get a cost estimate. So postgres_fdw
154    provides the following options to control how cost estimation is done:
155
156    use_remote_estimate (boolean)
157           This option, which can be specified for a foreign table or a
158           foreign server, controls whether postgres_fdw issues remote
159           EXPLAIN commands to obtain cost estimates. A setting for a
160           foreign table overrides any setting for its server, but only for
161           that table. The default is false.
162
163    fdw_startup_cost (floating point)
164           This option, which can be specified for a foreign server, is a
165           floating point value that is added to the estimated startup cost
166           of any foreign-table scan on that server. This represents the
167           additional overhead of establishing a connection, parsing and
168           planning the query on the remote side, etc. The default value is
169           100.
170
171    fdw_tuple_cost (floating point)
172           This option, which can be specified for a foreign server, is a
173           floating point value that is used as extra cost per-tuple for
174           foreign-table scans on that server. This represents the
175           additional overhead of data transfer between servers. You might
176           increase or decrease this number to reflect higher or lower
177           network delay to the remote server. The default value is 0.2.
178
179    When use_remote_estimate is true, postgres_fdw obtains row count and
180    cost estimates from the remote server and then adds fdw_startup_cost
181    and fdw_tuple_cost to the cost estimates. When use_remote_estimate is
182    false, postgres_fdw performs local row count and cost estimation and
183    then adds fdw_startup_cost and fdw_tuple_cost to the cost estimates.
184    This local estimation is unlikely to be very accurate unless local
185    copies of the remote table's statistics are available. Running ANALYZE
186    on the foreign table is the way to update the local statistics; this
187    will perform a scan of the remote table and then calculate and store
188    statistics just as though the table were local. Keeping local
189    statistics can be a useful way to reduce per-query planning overhead
190    for a remote table — but if the remote table is frequently updated, the
191    local statistics will soon be obsolete.
192
193    The following option controls how such an ANALYZE operation behaves:
194
195    analyze_sampling (string)
196           This option, which can be specified for a foreign table or a
197           foreign server, determines if ANALYZE on a foreign table samples
198           the data on the remote side, or reads and transfers all data and
199           performs the sampling locally. The supported values are off,
200           random, system, bernoulli and auto. off disables remote
201           sampling, so all data are transferred and sampled locally.
202           random performs remote sampling using the random() function to
203           choose returned rows, while system and bernoulli rely on the
204           built-in TABLESAMPLE methods of those names. random works on all
205           remote server versions, while TABLESAMPLE is supported only
206           since 9.5. auto (the default) picks the recommended sampling
207           method automatically; currently it means either bernoulli or
208           random depending on the remote server version.
209
210 F.38.1.4. Remote Execution Options #
211
212    By default, only WHERE clauses using built-in operators and functions
213    will be considered for execution on the remote server. Clauses
214    involving non-built-in functions are checked locally after rows are
215    fetched. If such functions are available on the remote server and can
216    be relied on to produce the same results as they do locally,
217    performance can be improved by sending such WHERE clauses for remote
218    execution. This behavior can be controlled using the following option:
219
220    extensions (string)
221           This option is a comma-separated list of names of PostgreSQL
222           extensions that are installed, in compatible versions, on both
223           the local and remote servers. Functions and operators that are
224           immutable and belong to a listed extension will be considered
225           shippable to the remote server. This option can only be
226           specified for foreign servers, not per-table.
227
228           When using the extensions option, it is the user's
229           responsibility that the listed extensions exist and behave
230           identically on both the local and remote servers. Otherwise,
231           remote queries may fail or behave unexpectedly.
232
233    fetch_size (integer)
234           This option specifies the number of rows postgres_fdw should get
235           in each fetch operation. It can be specified for a foreign table
236           or a foreign server. The option specified on a table overrides
237           an option specified for the server. The default is 100.
238
239    batch_size (integer)
240           This option specifies the number of rows postgres_fdw should
241           insert in each insert operation. It can be specified for a
242           foreign table or a foreign server. The option specified on a
243           table overrides an option specified for the server. The default
244           is 1.
245
246           Note the actual number of rows postgres_fdw inserts at once
247           depends on the number of columns and the provided batch_size
248           value. The batch is executed as a single query, and the libpq
249           protocol (which postgres_fdw uses to connect to a remote server)
250           limits the number of parameters in a single query to 65535. When
251           the number of columns * batch_size exceeds the limit, the
252           batch_size will be adjusted to avoid an error.
253
254           This option also applies when copying into foreign tables. In
255           that case the actual number of rows postgres_fdw copies at once
256           is determined in a similar way to the insert case, but it is
257           limited to at most 1000 due to implementation restrictions of
258           the COPY command.
259
260 F.38.1.5. Asynchronous Execution Options #
261
262    postgres_fdw supports asynchronous execution, which runs multiple parts
263    of an Append node concurrently rather than serially to improve
264    performance. This execution can be controlled using the following
265    option:
266
267    async_capable (boolean)
268           This option controls whether postgres_fdw allows foreign tables
269           to be scanned concurrently for asynchronous execution. It can be
270           specified for a foreign table or a foreign server. A table-level
271           option overrides a server-level option. The default is false.
272
273           In order to ensure that the data being returned from a foreign
274           server is consistent, postgres_fdw will only open one connection
275           for a given foreign server and will run all queries against that
276           server sequentially even if there are multiple foreign tables
277           involved, unless those tables are subject to different user
278           mappings. In such a case, it may be more performant to disable
279           this option to eliminate the overhead associated with running
280           queries asynchronously.
281
282           Asynchronous execution is applied even when an Append node
283           contains subplan(s) executed synchronously as well as subplan(s)
284           executed asynchronously. In such a case, if the asynchronous
285           subplans are ones processed using postgres_fdw, tuples from the
286           asynchronous subplans are not returned until after at least one
287           synchronous subplan returns all tuples, as that subplan is
288           executed while the asynchronous subplans are waiting for the
289           results of asynchronous queries sent to foreign servers. This
290           behavior might change in a future release.
291
292 F.38.1.6. Transaction Management Options #
293
294    As described in the Transaction Management section, in postgres_fdw
295    transactions are managed by creating corresponding remote transactions,
296    and subtransactions are managed by creating corresponding remote
297    subtransactions. When multiple remote transactions are involved in the
298    current local transaction, by default postgres_fdw commits or aborts
299    those remote transactions serially when the local transaction is
300    committed or aborted. When multiple remote subtransactions are involved
301    in the current local subtransaction, by default postgres_fdw commits or
302    aborts those remote subtransactions serially when the local
303    subtransaction is committed or aborted. Performance can be improved
304    with the following options:
305
306    parallel_commit (boolean)
307           This option controls whether postgres_fdw commits, in parallel,
308           remote transactions opened on a foreign server in a local
309           transaction when the local transaction is committed. This
310           setting also applies to remote and local subtransactions. This
311           option can only be specified for foreign servers, not per-table.
312           The default is false.
313
314    parallel_abort (boolean)
315           This option controls whether postgres_fdw aborts, in parallel,
316           remote transactions opened on a foreign server in a local
317           transaction when the local transaction is aborted. This setting
318           also applies to remote and local subtransactions. This option
319           can only be specified for foreign servers, not per-table. The
320           default is false.
321
322    If multiple foreign servers with these options enabled are involved in
323    a local transaction, multiple remote transactions on those foreign
324    servers are committed or aborted in parallel across those foreign
325    servers when the local transaction is committed or aborted.
326
327    When these options are enabled, a foreign server with many remote
328    transactions may see a negative performance impact when the local
329    transaction is committed or aborted.
330
331 F.38.1.7. Updatability Options #
332
333    By default all foreign tables using postgres_fdw are assumed to be
334    updatable. This may be overridden using the following option:
335
336    updatable (boolean)
337           This option controls whether postgres_fdw allows foreign tables
338           to be modified using INSERT, UPDATE and DELETE commands. It can
339           be specified for a foreign table or a foreign server. A
340           table-level option overrides a server-level option. The default
341           is true.
342
343           Of course, if the remote table is not in fact updatable, an
344           error would occur anyway. Use of this option primarily allows
345           the error to be thrown locally without querying the remote
346           server. Note however that the information_schema views will
347           report a postgres_fdw foreign table to be updatable (or not)
348           according to the setting of this option, without any check of
349           the remote server.
350
351 F.38.1.8. Truncatability Options #
352
353    By default all foreign tables using postgres_fdw are assumed to be
354    truncatable. This may be overridden using the following option:
355
356    truncatable (boolean)
357           This option controls whether postgres_fdw allows foreign tables
358           to be truncated using the TRUNCATE command. It can be specified
359           for a foreign table or a foreign server. A table-level option
360           overrides a server-level option. The default is true.
361
362           Of course, if the remote table is not in fact truncatable, an
363           error would occur anyway. Use of this option primarily allows
364           the error to be thrown locally without querying the remote
365           server.
366
367 F.38.1.9. Importing Options #
368
369    postgres_fdw is able to import foreign table definitions using IMPORT
370    FOREIGN SCHEMA. This command creates foreign table definitions on the
371    local server that match tables or views present on the remote server.
372    If the remote tables to be imported have columns of user-defined data
373    types, the local server must have compatible types of the same names.
374
375    Importing behavior can be customized with the following options (given
376    in the IMPORT FOREIGN SCHEMA command):
377
378    import_collate (boolean)
379           This option controls whether column COLLATE options are included
380           in the definitions of foreign tables imported from a foreign
381           server. The default is true. You might need to turn this off if
382           the remote server has a different set of collation names than
383           the local server does, which is likely to be the case if it's
384           running on a different operating system. If you do so, however,
385           there is a very severe risk that the imported table columns'
386           collations will not match the underlying data, resulting in
387           anomalous query behavior.
388
389           Even when this parameter is set to true, importing columns whose
390           collation is the remote server's default can be risky. They will
391           be imported with COLLATE "default", which will select the local
392           server's default collation, which could be different.
393
394    import_default (boolean)
395           This option controls whether column DEFAULT expressions are
396           included in the definitions of foreign tables imported from a
397           foreign server. The default is false. If you enable this option,
398           be wary of defaults that might get computed differently on the
399           local server than they would be on the remote server; nextval()
400           is a common source of problems. The IMPORT will fail altogether
401           if an imported default expression uses a function or operator
402           that does not exist locally.
403
404    import_generated (boolean)
405           This option controls whether column GENERATED expressions are
406           included in the definitions of foreign tables imported from a
407           foreign server. The default is true. The IMPORT will fail
408           altogether if an imported generated expression uses a function
409           or operator that does not exist locally.
410
411    import_not_null (boolean)
412           This option controls whether column NOT NULL constraints are
413           included in the definitions of foreign tables imported from a
414           foreign server. The default is true.
415
416    Note that constraints other than NOT NULL will never be imported from
417    the remote tables. Although PostgreSQL does support check constraints
418    on foreign tables, there is no provision for importing them
419    automatically, because of the risk that a constraint expression could
420    evaluate differently on the local and remote servers. Any such
421    inconsistency in the behavior of a check constraint could lead to
422    hard-to-detect errors in query optimization. So if you wish to import
423    check constraints, you must do so manually, and you should verify the
424    semantics of each one carefully. For more detail about the treatment of
425    check constraints on foreign tables, see CREATE FOREIGN TABLE.
426
427    Tables or foreign tables which are partitions of some other table are
428    imported only when they are explicitly specified in LIMIT TO clause.
429    Otherwise they are automatically excluded from IMPORT FOREIGN SCHEMA.
430    Since all data can be accessed through the partitioned table which is
431    the root of the partitioning hierarchy, importing only partitioned
432    tables should allow access to all the data without creating extra
433    objects.
434
435 F.38.1.10. Connection Management Options #
436
437    By default, all connections that postgres_fdw establishes to foreign
438    servers are kept open in the local session for re-use.
439
440    keep_connections (boolean) #
441           This option controls whether postgres_fdw keeps the connections
442           to the foreign server open so that subsequent queries can re-use
443           them. It can only be specified for a foreign server. The default
444           is on. If set to off, all connections to this foreign server
445           will be discarded at the end of each transaction.
446
447    use_scram_passthrough (boolean) #
448           This option controls whether postgres_fdw will use the SCRAM
449           pass-through authentication to connect to the foreign server.
450           With SCRAM pass-through authentication, postgres_fdw uses
451           SCRAM-hashed secrets instead of plain-text user passwords to
452           connect to the remote server. This avoids storing plain-text
453           user passwords in PostgreSQL system catalogs.
454
455           To use SCRAM pass-through authentication:
456
457           + The remote server must request the scram-sha-256
458             authentication method; otherwise, the connection will fail.
459           + The remote server can be of any PostgreSQL version that
460             supports SCRAM. Support for use_scram_passthrough is only
461             required on the client side (FDW side).
462           + The user mapping password is not used.
463           + The server running postgres_fdw and the remote server must
464             have identical SCRAM secrets (encrypted passwords) for the
465             user being used on postgres_fdw to authenticate on the foreign
466             server (same salt and iterations, not merely the same
467             password).
468             As a corollary, if FDW connections to multiple hosts are to be
469             made, for example for partitioned foreign tables/sharding,
470             then all hosts must have identical SCRAM secrets for the users
471             involved.
472           + The current session on the PostgreSQL instance that makes the
473             outgoing FDW connections also must also use SCRAM
474             authentication for its incoming client connection. (Hence
475             “pass-through”: SCRAM must be used going in and out.) This is
476             a technical requirement of the SCRAM protocol.
477
478 F.38.2. Functions #
479
480    postgres_fdw_get_connections( IN check_conn boolean DEFAULT false, OUT
481           server_name text, OUT user_name text, OUT valid boolean, OUT
482           used_in_xact boolean, OUT closed boolean, OUT remote_backend_pid
483           int4) returns setof record
484           This function returns information about all open connections
485           postgres_fdw has established from the local session to foreign
486           servers. If there are no open connections, no records are
487           returned.
488
489           If check_conn is set to true, the function checks the status of
490           each connection and shows the result in the closed column. This
491           feature is currently available only on systems that support the
492           non-standard POLLRDHUP extension to the poll system call,
493           including Linux. This is useful to check if all connections used
494           within a transaction are still open. If any connections are
495           closed, the transaction cannot be committed successfully, so it
496           is better to roll back as soon as a closed connection is
497           detected, rather than continuing to the end. Users can roll back
498           the transaction immediately if the function reports connections
499           where both used_in_xact and closed are true.
500
501           Example usage of the function:
502
503 postgres=# SELECT * FROM postgres_fdw_get_connections(true);
504  server_name | user_name | valid | used_in_xact | closed | remote_backend_pid
505 -------------+-----------+-------+--------------+-----------------------------
506  loopback1   | postgres  | t     | t            | f      |            1353340
507  loopback2   | public    | t     | t            | f      |            1353120
508  loopback3   |           | f     | t            | f      |            1353156
509
510           The output columns are described in Table F.28.
511
512           Table F.28. postgres_fdw_get_connections Output Columns
513
514    Column Type Description
515    server_name text The foreign server name of this connection. If the
516    server is dropped but the connection remains open (i.e., marked as
517    invalid), this will be NULL.
518    user_name text Name of the local user mapped to the foreign server of
519    this connection, or public if a public mapping is used. If the user
520    mapping is dropped but the connection remains open (i.e., marked as
521    invalid), this will be NULL.
522    valid boolean False if this connection is invalid, meaning it is used
523    in the current transaction, but its foreign server or user mapping has
524    been changed or dropped. The invalid connection will be closed at the
525    end of the transaction. True is returned otherwise.
526    used_in_xact boolean True if this connection is used in the current
527    transaction.
528    closed boolean True if this connection is closed, false otherwise. NULL
529    is returned if check_conn is set to false or if the connection status
530    check is not available on this platform.
531    remote_backend_pid int4 Process ID of the remote backend, on the
532    foreign server, handling the connection. If the remote backend is
533    terminated and the connection is closed (with closed set to true), this
534    still shows the process ID of the terminated backend.
535
536    postgres_fdw_disconnect(server_name text) returns boolean
537           This function discards the open connections that are established
538           by postgres_fdw from the local session to the foreign server
539           with the given name. Note that there can be multiple connections
540           to the given server using different user mappings. If the
541           connections are used in the current local transaction, they are
542           not disconnected and warning messages are reported. This
543           function returns true if it disconnects at least one connection,
544           otherwise false. If no foreign server with the given name is
545           found, an error is reported. Example usage of the function:
546
547 postgres=# SELECT postgres_fdw_disconnect('loopback1');
548  postgres_fdw_disconnect
549 -------------------------
550  t
551
552    postgres_fdw_disconnect_all() returns boolean
553           This function discards all the open connections that are
554           established by postgres_fdw from the local session to foreign
555           servers. If the connections are used in the current local
556           transaction, they are not disconnected and warning messages are
557           reported. This function returns true if it disconnects at least
558           one connection, otherwise false. Example usage of the function:
559
560 postgres=# SELECT postgres_fdw_disconnect_all();
561  postgres_fdw_disconnect_all
562 -----------------------------
563  t
564
565 F.38.3. Connection Management #
566
567    postgres_fdw establishes a connection to a foreign server during the
568    first query that uses a foreign table associated with the foreign
569    server. By default this connection is kept and re-used for subsequent
570    queries in the same session. This behavior can be controlled using
571    keep_connections option for a foreign server. If multiple user
572    identities (user mappings) are used to access the foreign server, a
573    connection is established for each user mapping.
574
575    When changing the definition of or removing a foreign server or a user
576    mapping, the associated connections are closed. But note that if any
577    connections are in use in the current local transaction, they are kept
578    until the end of the transaction. Closed connections will be
579    re-established when they are necessary by future queries using a
580    foreign table.
581
582    Once a connection to a foreign server has been established, it's by
583    default kept until the local or corresponding remote session exits. To
584    disconnect a connection explicitly, keep_connections option for a
585    foreign server may be disabled, or postgres_fdw_disconnect and
586    postgres_fdw_disconnect_all functions may be used. For example, these
587    are useful to close connections that are no longer necessary, thereby
588    releasing connections on the foreign server.
589
590 F.38.4. Transaction Management #
591
592    During a query that references any remote tables on a foreign server,
593    postgres_fdw opens a transaction on the remote server if one is not
594    already open corresponding to the current local transaction. The remote
595    transaction is committed or aborted when the local transaction commits
596    or aborts. Savepoints are similarly managed by creating corresponding
597    remote savepoints.
598
599    The remote transaction uses SERIALIZABLE isolation level when the local
600    transaction has SERIALIZABLE isolation level; otherwise it uses
601    REPEATABLE READ isolation level. This choice ensures that if a query
602    performs multiple table scans on the remote server, it will get
603    snapshot-consistent results for all the scans. A consequence is that
604    successive queries within a single transaction will see the same data
605    from the remote server, even if concurrent updates are occurring on the
606    remote server due to other activities. That behavior would be expected
607    anyway if the local transaction uses SERIALIZABLE or REPEATABLE READ
608    isolation level, but it might be surprising for a READ COMMITTED local
609    transaction. A future PostgreSQL release might modify these rules.
610
611    Note that it is currently not supported by postgres_fdw to prepare the
612    remote transaction for two-phase commit.
613
614 F.38.5. Remote Query Optimization #
615
616    postgres_fdw attempts to optimize remote queries to reduce the amount
617    of data transferred from foreign servers. This is done by sending query
618    WHERE clauses to the remote server for execution, and by not retrieving
619    table columns that are not needed for the current query. To reduce the
620    risk of misexecution of queries, WHERE clauses are not sent to the
621    remote server unless they use only data types, operators, and functions
622    that are built-in or belong to an extension that's listed in the
623    foreign server's extensions option. Operators and functions in such
624    clauses must be IMMUTABLE as well. For an UPDATE or DELETE query,
625    postgres_fdw attempts to optimize the query execution by sending the
626    whole query to the remote server if there are no query WHERE clauses
627    that cannot be sent to the remote server, no local joins for the query,
628    no row-level local BEFORE or AFTER triggers or stored generated columns
629    on the target table, and no CHECK OPTION constraints from parent views.
630    In UPDATE, expressions to assign to target columns must use only
631    built-in data types, IMMUTABLE operators, or IMMUTABLE functions, to
632    reduce the risk of misexecution of the query.
633
634    When postgres_fdw encounters a join between foreign tables on the same
635    foreign server, it sends the entire join to the foreign server, unless
636    for some reason it believes that it will be more efficient to fetch
637    rows from each table individually, or unless the table references
638    involved are subject to different user mappings. While sending the JOIN
639    clauses, it takes the same precautions as mentioned above for the WHERE
640    clauses.
641
642    The query that is actually sent to the remote server for execution can
643    be examined using EXPLAIN VERBOSE.
644
645 F.38.6. Remote Query Execution Environment #
646
647    In the remote sessions opened by postgres_fdw, the search_path
648    parameter is set to just pg_catalog, so that only built-in objects are
649    visible without schema qualification. This is not an issue for queries
650    generated by postgres_fdw itself, because it always supplies such
651    qualification. However, this can pose a hazard for functions that are
652    executed on the remote server via triggers or rules on remote tables.
653    For example, if a remote table is actually a view, any functions used
654    in that view will be executed with the restricted search path. It is
655    recommended to schema-qualify all names in such functions, or else
656    attach SET search_path options (see CREATE FUNCTION) to such functions
657    to establish their expected search path environment.
658
659    postgres_fdw likewise establishes remote session settings for various
660    parameters:
661      * TimeZone is set to UTC
662      * DateStyle is set to ISO
663      * IntervalStyle is set to postgres
664      * extra_float_digits is set to 3 for remote servers 9.0 and newer and
665        is set to 2 for older versions
666
667    These are less likely to be problematic than search_path, but can be
668    handled with function SET options if the need arises.
669
670    It is not recommended that you override this behavior by changing the
671    session-level settings of these parameters; that is likely to cause
672    postgres_fdw to malfunction.
673
674 F.38.7. Cross-Version Compatibility #
675
676    postgres_fdw can be used with remote servers dating back to PostgreSQL
677    8.3. Read-only capability is available back to 8.1.
678
679    A limitation however is that postgres_fdw generally assumes that
680    immutable built-in functions and operators are safe to send to the
681    remote server for execution, if they appear in a WHERE clause for a
682    foreign table. Thus, a built-in function that was added since the
683    remote server's release might be sent to it for execution, resulting in
684    “function does not exist” or a similar error. This type of failure can
685    be worked around by rewriting the query, for example by embedding the
686    foreign table reference in a sub-SELECT with OFFSET 0 as an
687    optimization fence, and placing the problematic function or operator
688    outside the sub-SELECT.
689
690    Another limitation is that when executing INSERT statements with an ON
691    CONFLICT DO NOTHING clause on a foreign table, the remote server must
692    be running PostgreSQL 9.5 or later, as earlier versions do not support
693    this feature.
694
695 F.38.8. Wait Events #
696
697    postgres_fdw can report the following wait events under the wait event
698    type Extension:
699
700    PostgresFdwCleanupResult
701           Waiting for transaction abort on remote server.
702
703    PostgresFdwConnect
704           Waiting to establish a connection to a remote server.
705
706    PostgresFdwGetResult
707           Waiting to receive the results of a query from a remote server.
708
709 F.38.9. Configuration Parameters #
710
711    postgres_fdw.application_name (string) #
712           Specifies a value for application_name configuration parameter
713           used when postgres_fdw establishes a connection to a foreign
714           server. This overrides application_name option of the server
715           object. Note that change of this parameter doesn't affect any
716           existing connections until they are re-established.
717
718           postgres_fdw.application_name can be any string of any length
719           and contain even non-ASCII characters. However when it's passed
720           to and used as application_name in a foreign server, note that
721           it will be truncated to less than NAMEDATALEN characters.
722           Anything other than printable ASCII characters are replaced with
723           C-style hexadecimal escapes. See application_name for details.
724
725           % characters begin “escape sequences” that are replaced with
726           status information as outlined below. Unrecognized escapes are
727           ignored. Other characters are copied straight to the application
728           name. Note that it's not allowed to specify a plus/minus sign or
729           a numeric literal after the % and before the option, for
730           alignment and padding.
731
732           Escape                            Effect
733           %a     Application name on local server
734           %c     Session ID on local server (see log_line_prefix for details)
735           %C     Cluster name on local server (see cluster_name for details)
736           %u     User name on local server
737           %d     Database name on local server
738           %p     Process ID of backend on local server
739           %%     Literal %
740
741           For example, suppose user local_user establishes a connection
742           from database local_db to foreign_db as user foreign_user, the
743           setting 'db=%d, user=%u' is replaced with 'db=local_db,
744           user=local_user'.
745
746 F.38.10. Examples #
747
748    Here is an example of creating a foreign table with postgres_fdw. First
749    install the extension:
750 CREATE EXTENSION postgres_fdw;
751
752    Then create a foreign server using CREATE SERVER. In this example we
753    wish to connect to a PostgreSQL server on host 192.83.123.89 listening
754    on port 5432. The database to which the connection is made is named
755    foreign_db on the remote server:
756 CREATE SERVER foreign_server
757         FOREIGN DATA WRAPPER postgres_fdw
758         OPTIONS (host '192.83.123.89', port '5432', dbname 'foreign_db');
759
760    A user mapping, defined with CREATE USER MAPPING, is needed as well to
761    identify the role that will be used on the remote server:
762 CREATE USER MAPPING FOR local_user
763         SERVER foreign_server
764         OPTIONS (user 'foreign_user', password 'password');
765
766    Now it is possible to create a foreign table with CREATE FOREIGN TABLE.
767    In this example we wish to access the table named
768    some_schema.some_table on the remote server. The local name for it will
769    be foreign_table:
770 CREATE FOREIGN TABLE foreign_table (
771         id integer NOT NULL,
772         data text
773 )
774         SERVER foreign_server
775         OPTIONS (schema_name 'some_schema', table_name 'some_table');
776
777    It's essential that the data types and other properties of the columns
778    declared in CREATE FOREIGN TABLE match the actual remote table. Column
779    names must match as well, unless you attach column_name options to the
780    individual columns to show how they are named in the remote table. In
781    many cases, use of IMPORT FOREIGN SCHEMA is preferable to constructing
782    foreign table definitions manually.
783
784 F.38.11. Author #
785
786    Shigeru Hanada <shigeru.hanada@gmail.com>