Row Level Security Tenant Policy
Enforce tenant isolation in the database with row level security: ENABLE plus FORCE ROW LEVEL SECURITY and a policy that compares tenant to a session setting.
Code
-- RLS:把行级可见性交给数据库策略,应用层不再手工拼租户过滤
CREATE TABLE documents (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant text NOT NULL,
title text NOT NULL
);
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
-- 表所有者默认绕过 RLS;FORCE 让所有者也受策略约束
ALTER TABLE documents FORCE ROW LEVEL SECURITY;
-- 会话变量未设置时 current_setting 第二参 true 返回 NULL,
-- 比较 结果为 NULL,一行都看不到,而不是全部放行
CREATE POLICY tenant_isolation ON documents
USING (tenant = current_setting('app.tenant_id', true));
SET app.tenant_id = 'acme';
SELECT title FROM documents; -- 只能看到 acme 的行
RESET app.tenant_id;What the code does
Several statements share this file — SELECT / CREATE / ALTER, with documents among the objects involved.
What the statements actually assemble: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
The documents table is the working surface here.
Key statements
CREATE TABLE documents (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant text NOT NULL,
title text NOT NULL
);
CREATE POLICY tenant_isolation ON documents
USING (tenant = current_setting('app.tenant_id', true));
SELECT title FROM documents; -- 只能看到 acme 的行
RESET app.tenant_id;
Interactive Tools for This Topic
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.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.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Which relations are involved here?
- `documents` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.