View WITH CHECK OPTION Enforces WHERE

Attach WITH CHECK OPTION to a view so inserts and updates through it must satisfy the view WHERE predicate instead of writing invisible rows.

SqlSecurity Boundaries

Code

snippet
-- 基础表与受限视图:视图只暴露未停用的租户
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 时这条会成功,但插入的行立刻从视图里"消失"

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with tenants and active_tenants among the objects involved.

What the statements actually assemble: a WHERE clause that scopes which rows one statement can hit; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the tenants table.

Statements that matter

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());

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `tenants`, `active_tenants`.