← 中文资源

简体中文版本

视图 WITH CHECK OPTION 写入护栏

经视图写入时 WITH CHECK OPTION 强制满足视图的 WHERE 谓词:想让停用行穿过视图插入会被当场拒绝,避免出现插入成功却从视图里消失的不可见数据。

阅读英文原文

实现说明

实际执行的是 SELECT / INSERT / CREATE——tenants、active_tenants 是涉及的对象。 真正干活的子句:WHERE 把语句的作用范围收窄到满足条件的行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这个文件引用了哪些表?

引用的是 tenants、active_tenants。

核心语句

CREATE VIEW active_tenants AS
SELECT id, name, suspended_at
FROM tenants
WHERE suspended_at IS NULL
WITH CHECK OPTION;
CREATE TABLE tenants (
    id           bigint PRIMARY KEY,
    name         text NOT NULL,
    suspended_at timestamptz
);
INSERT INTO active_tenants (id, name, suspended_at) VALUES (2, 'ghost', now());

代码示例

-- 基础表与受限视图:视图只暴露未停用的租户
CREATE TABLE tenants (
    id           bigint PRIMARY KEY,
    name         text NOT NULL,
    suspended_at timestamptz
);

CREATE VIEW active_tenants AS
SELECT id, name, suspended_at
FROM tenants
WHERE suspended_at IS NULL
WITH CHECK OPTION;

-- 满足视图谓词:插入成功
INSERT INTO active_tenants (id, name) VALUES (1, 'acme');

-- 想借视图写入一条已停用租户:违反 check option,被拒绝
INSERT INTO active_tenants (id, name, suspended_at) VALUES (2, 'ghost', now());

-- 没有 CHECK OPTION 时这条会成功,但插入的行立刻从视图里"消失"