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.
Code
-- 基础表与受限视图:视图只暴露未停用的租户
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Which tables does this file reference?
- The references are `tenants`, `active_tenants`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.