Postgresql 中文操作指南

CREATE FOREIGN TABLE

CREATE FOREIGN TABLE — 定义新外部表

CREATE FOREIGN TABLE — define a new foreign table

Synopsis

CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [
  { column_name data_type [ OPTIONS ( option 'value' [, ... ] ) ] [ COLLATE collation ] [ column_constraint [ ... ] ]
    | table_constraint }
    [, ... ]
] )
[ INHERITS ( parent_table [, ... ] ) ]
  SERVER server_name
[ OPTIONS ( option 'value' [, ... ] ) ]

CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name
  PARTITION OF parent_table [ (
  { column_name [ WITH OPTIONS ] [ column_constraint [ ... ] ]
    | table_constraint }
    [, ... ]
) ]
{ FOR VALUES partition_bound_spec | DEFAULT }
  SERVER server_name
[ OPTIONS ( option 'value' [, ... ] ) ]

where column_constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL |
  NULL |
  CHECK ( expression ) [ NO INHERIT ] |
  DEFAULT default_expr |
  GENERATED ALWAYS AS ( generation_expr ) STORED }

and table_constraint is:

[ CONSTRAINT constraint_name ]
CHECK ( expression ) [ NO INHERIT ]

and partition_bound_spec is:

IN ( partition_bound_expr [, ...] ) |
FROM ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] )
  TO ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] ) |
WITH ( MODULUS numeric_literal, REMAINDER numeric_literal )

Description

CREATE FOREIGN TABLE 在当前数据库中创建一个新外部表。该表归发出该命令的用户所有。

CREATE FOREIGN TABLE creates a new foreign table in the current database. The table will be owned by the user issuing the command.

如果给定了架构名称(例如, CREATE FOREIGN TABLE myschema.mytable …​ ),则在指定的架构中创建表。否则将在当前架构中创建它。外部表名称必须与同一架构中任何其他关系(表、序列、索引、视图、物化视图或外部表)的名称不同。

If a schema name is given (for example, CREATE FOREIGN TABLE myschema.mytable …​) then the table is created in the specified schema. Otherwise it is created in the current schema. The name of the foreign table must be distinct from the name of any other relation (table, sequence, index, view, materialized view, or foreign table) in the same schema.

CREATE FOREIGN TABLE 还自动创建一种数据类型,该类型表示与外部表一行相对应的复合类型。因此,外部表不能与同一架构中的任何现有数据类型同名。

CREATE FOREIGN TABLE also automatically creates a data type that represents the composite type corresponding to one row of the foreign table. Therefore, foreign tables cannot have the same name as any existing data type in the same schema.

如果指定了 PARTITION OF 子句,则该表将创建为 parent_table 的分区,并具有指定边界。

If PARTITION OF clause is specified then the table is created as a partition of parent_table with specified bounds.

要能够创建外部表,您必须在外部服务器上具有 USAGE 权限,以及在表中使用的所有列类型上具有 USAGE 权限。

To be able to create a foreign table, you must have USAGE privilege on the foreign server, as well as USAGE privilege on all column types used in the table.

Parameters

  • IF NOT EXISTS

    • Do not throw an error if a relation with the same name already exists. A notice is issued in this case. Note that there is no guarantee that the existing relation is anything like the one that would have been created.

  • table_name

    • The name (optionally schema-qualified) of the table to be created.

  • column_name

    • The name of a column to be created in the new table.

  • data_type

    • The data type of the column. This can include array specifiers. For more information on the data types supported by PostgreSQL, refer to Chapter 8.

  • COLLATE _collation_

    • The COLLATE clause assigns a collation to the column (which must be of a collatable data type). If not specified, the column data type’s default collation is used.

  • INHERITS ( _parent_table [, …​ ] )_

    • The optional INHERITS clause specifies a list of tables from which the new foreign table automatically inherits all columns. Parent tables can be plain tables or foreign tables. See the similar form of CREATE TABLE for more details.

  • PARTITION OF _parent_table { FOR VALUES partition_bound_spec | DEFAULT }_

    • This form can be used to create the foreign table as partition of the given parent table with specified partition bound values. See the similar form of CREATE TABLE for more details. Note that it is currently not allowed to create the foreign table as a partition of the parent table if there are UNIQUE indexes on the parent table. (See also ALTER TABLE ATTACH PARTITION.)

  • CONSTRAINT _constraint_name_

    • An optional name for a column or table constraint. If the constraint is violated, the constraint name is present in error messages, so constraint names like col must be positive can be used to communicate helpful constraint information to client applications. (Double-quotes are needed to specify constraint names that contain spaces.) If a constraint name is not specified, the system generates a name.

  • NOT NULL

    • The column is not allowed to contain null values.

  • NULL

    • The column is allowed to contain null values. This is the default.

    • This clause is only provided for compatibility with non-standard SQL databases. Its use is discouraged in new applications.

  • CHECK ( _expression ) [ NO INHERIT ]_

    • The CHECK clause specifies an expression producing a Boolean result which each row in the foreign table is expected to satisfy; that is, the expression should produce TRUE or UNKNOWN, never FALSE, for all rows in the foreign table. A check constraint specified as a column constraint should reference that column’s value only, while an expression appearing in a table constraint can reference multiple columns.

    • Currently, CHECK expressions cannot contain subqueries nor refer to variables other than columns of the current row. The system column tableoid may be referenced, but not any other system column.

    • A constraint marked with NO INHERIT will not propagate to child tables.

  • DEFAULT _default_expr_

    • The DEFAULT clause assigns a default data value for the column whose column definition it appears within. The value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed). The data type of the default expression must match the data type of the column.

    • The default expression will be used in any insert operation that does not specify a value for the column. If there is no default for a column, then the default is null.

  • GENERATED ALWAYS AS ( _generation_expr ) STORED_

    • This clause creates the column as a generated column. The column cannot be written to, and when read the result of the specified expression will be returned.

    • The keyword STORED is required to signify that the column will be computed on write. (The computed value will be presented to the foreign-data wrapper for storage and must be returned on reading.)

    • The generation expression can refer to other columns in the table, but not other generated columns. Any functions and operators used must be immutable. References to other tables are not allowed.

  • server_name

    • The name of an existing foreign server to use for the foreign table. For details on defining a server, see CREATE SERVER.

  • OPTIONS ( _option 'value' [, …​] )_

    • Options to be associated with the new foreign table or one of its columns. The allowed option names and values are specific to each foreign data wrapper and are validated using the foreign-data wrapper’s validator function. Duplicate option names are not allowed (although it’s OK for a table option and a column option to have the same name).

Notes

外部表格的约束(例如 CHECKNOT NULL 子句)不受核心 PostgreSQL 系统强制执行,大多数外部数据封装器也不会尝试强制执行它们;也就是说,简单地假定约束保持为真。这种强制几乎没有意义,因为它只适用于通过外部表插入或更新的行,而不适用于通过其他方式(例如直接在远程服务器上)修改的行。相反,附加到外部表的约束应表示由远程服务器强制执行的约束。

Constraints on foreign tables (such as CHECK or NOT NULL clauses) are not enforced by the core PostgreSQL system, and most foreign data wrappers do not attempt to enforce them either; that is, the constraint is simply assumed to hold true. There would be little point in such enforcement since it would only apply to rows inserted or updated via the foreign table, and not to rows modified by other means, such as directly on the remote server. Instead, a constraint attached to a foreign table should represent a constraint that is being enforced by the remote server.

一些特殊用途的外部数据封装器可能是其访问数据时唯一的访问机制,在这种情况下,由外部数据封装器本身执行约束强制可能是合适的。但是,您不应该假定封装器会这样做,除非其文档中这么说。

Some special-purpose foreign data wrappers might be the only access mechanism for the data they access, and in that case it might be appropriate for the foreign data wrapper itself to perform constraint enforcement. But you should not assume that a wrapper does that unless its documentation says so.

尽管 PostgreSQL 不会尝试强制执行外部表上的约束,但它确实假设它们对于查询优化而言是正确的。如果外部表中可见的行不满足已声明的约束,则对该表的查询可能会产生错误或不正确的答案。确保约束定义与现实相匹配是用户的责任。

Although PostgreSQL does not attempt to enforce constraints on foreign tables, it does assume that they are correct for purposes of query optimization. If there are rows visible in the foreign table that do not satisfy a declared constraint, queries on the table might produce errors or incorrect answers. It is the user’s responsibility to ensure that the constraint definition matches reality.

Caution

当外部表用作分区表的某一部分时,有一个隐含约束,其内容必须满足分区规则。同样,确保这是正确的也是用户的责任,最好的办法是在远程服务器上安装匹配的约束。

When a foreign table is used as a partition of a partitioned table, there is an implicit constraint that its contents must satisfy the partitioning rule. Again, it is the user’s responsibility to ensure that that is true, which is best done by installing a matching constraint on the remote server.

在包含外部表分区的已分区表中,更改分区键值 的 UPDATE 可能导致一行从本地分区移动到外部表分区,前提是外部数据封装器支持元组路由。但是,目前无法将行从外部表分区移动到另一个分区。假设远程服务器正确强制执行分区约束,则需要执行此操作的 UPDATE 将因分区约束而失败。

Within a partitioned table containing foreign-table partitions, an UPDATE that changes the partition key value can cause a row to be moved from a local partition to a foreign-table partition, provided the foreign data wrapper supports tuple routing. However, it is not currently possible to move a row from a foreign-table partition to another partition. An UPDATE that would require doing that will fail due to the partitioning constraint, assuming that that is properly enforced by the remote server.

类似的考虑因素也适用于已生成列。存储的已生成列是在本地 PostgreSQL 服务器上插入或更新时计算出的,并传递给外部数据封装器以写入外部数据存储,但并不要求外部表查询返回的值对于已存储的已生成列与生成表达式一致。同样,这可能会导致错误的查询结果。

Similar considerations apply to generated columns. Stored generated columns are computed on insert or update on the local PostgreSQL server and handed to the foreign-data wrapper for writing out to the foreign data store, but it is not enforced that a query of the foreign table returns values for stored generated columns that are consistent with the generation expression. Again, this might result in incorrect query results.

Examples

创建外部表 films ,它将通过服务器 film_server 访问:

Create foreign table films, which will be accessed through the server film_server:

CREATE FOREIGN TABLE films (
    code        char(5) NOT NULL,
    title       varchar(40) NOT NULL,
    did         integer NOT NULL,
    date_prod   date,
    kind        varchar(10),
    len         interval hour to minute
)
SERVER film_server;

创建外部表 measurement_y2016m07 ,它将通过服务器 server_07 访问,作为范围分区表 measurement 的一个分区:

Create foreign table measurement_y2016m07, which will be accessed through the server server_07, as a partition of the range partitioned table measurement:

CREATE FOREIGN TABLE measurement_y2016m07
    PARTITION OF measurement FOR VALUES FROM ('2016-07-01') TO ('2016-08-01')
    SERVER server_07;

Compatibility

CREATE FOREIGN TABLE 命令在很大程度上符合 SQL 标准;然而,与 CREATE TABLE 类似的是,允许 NULL 约束和零列外部表。指定列默认值的能力也是 PostgreSQL 扩展。PostgreSQL 定义的表格继承是非标准的。

The CREATE FOREIGN TABLE command largely conforms to the SQL standard; however, much as with CREATE TABLE, NULL constraints and zero-column foreign tables are permitted. The ability to specify column default values is also a PostgreSQL extension. Table inheritance, in the form defined by PostgreSQL, is nonstandard.