实现说明
实际执行的是 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 时这条会成功,但插入的行立刻从视图里"消失"