← 中文资源

简体中文版本

CHECK NO INHERIT 限定父表约束范围

用 NO INHERIT 定义父表 CHECK,让子表接受父表拒绝的行,并对比继承规则与本地约束。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE / ALTER,vehicles、prototypes 都在涉及之列。 机制上由这些部分组成:ORDER BY 固定了输出顺序;CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

说出这个文件涉及的表。

引用的是 vehicles、prototypes。

核心语句

CREATE TABLE vehicles (
  id int PRIMARY KEY,
  kind text NOT NULL,
  wheels int NOT NULL,
  CONSTRAINT cars_have_four_wheels
    CHECK (kind <> 'car' OR wheels = 4) NO INHERIT
);
SELECT tableoid::regclass AS source, id, kind, wheels
FROM vehicles
ORDER BY id;
INSERT INTO prototypes (id, kind, wheels, max_speed)
VALUES (3, 'car', 6, 120);

代码示例

CREATE TABLE vehicles (
  id int PRIMARY KEY,
  kind text NOT NULL,
  wheels int NOT NULL,
  CONSTRAINT cars_have_four_wheels
    CHECK (kind <> 'car' OR wheels = 4) NO INHERIT
);

-- The parent table enforces the rule.
INSERT INTO vehicles (id, kind, wheels) VALUES (1, 'car', 4);

CREATE TABLE prototypes (
  max_speed int
) INHERITS (vehicles);

-- The child does not inherit the NO INHERIT check.
INSERT INTO prototypes (id, kind, wheels, max_speed)
VALUES (3, 'car', 6, 120);

SELECT tableoid::regclass AS source, id, kind, wheels
FROM vehicles
ORDER BY id;

-- A local check still applies to the child table.
ALTER TABLE prototypes
ADD CONSTRAINT prototypes_need_speed
  CHECK (max_speed IS NULL OR max_speed > 0);

-- The parent rejects this row; the savepoint keeps the session usable.
BEGIN;
SAVEPOINT bad_parent;
INSERT INTO vehicles (id, kind, wheels) VALUES (2, 'car', 6);
ROLLBACK TO SAVEPOINT bad_parent;
COMMIT;