分区表上的 PostgreSQL 11 外键

PostgreSQL 11 foreign key on partitioning tables

在 PostgreSQL11 Release Notes 我发现分区功能有以下改进:

我需要这个功能并测试了它。

创建table:

CREATE TABLE public.tbl_test
(
    uuid character varying(32) NOT null,
    registration_date timestamp without time zone NOT NULL    
)
PARTITION BY RANGE (registration_date);

尝试创建主键:

ALTER TABLE public.tbl_test ADD CONSTRAINT pk_test PRIMARY KEY (uuid);

我收到错误 SQL 错误 [0A000]。如果使用复合 PK (uuid, registration_date) 那么它就可以了。因为PK包含分区列

结论:在分区 table 中创建 PK 有限制(PK 需要包含分区列)。

尝试创建外键

CREATE TABLE public.tbl_test2
(
    uuid character varying(32) NOT null,
    test_uuid character varying(32) NOT null
);

ALTER TABLE tbl_test2
   ADD CONSTRAINT fk_test FOREIGN KEY (test_uuid)
   REFERENCES tbl_test (uuid);

我收到错误 SQL 错误 [42809]。这意味着分区 table 上的 FOREIGN KEY 不起作用。

也许我做错了什么。也许有人尝试过这个功能并且知道它是如何工作的。 也许有人知道解决方法,除了在应用程序中实施约束。

Postgres 11 仅支持外键 分区table 到(非分区)table。

以前这甚至是不可能的,这就是发行说明的内容。

此限制记录在手册chapter about partitioning

While primary keys are supported on partitioned tables, foreign keys referencing partitioned tables are not supported. (Foreign key references from a partitioned table to some other table are supported.

(强调我的)

PostgreSQL v12.0 will probably support foreign keys that reference partitioned tables但这仍然不能保证,因为 v12.0 仍在开发中。

对于 v11 和更低版本,您可以使用 depesz 在这些帖子中描述的触发器:part1, part2, and part3

更新: PostgreSQL v12.0 已于 2019 年 10 月 3 日发布,with this feature included