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.

SqlSecurity Boundaries

Code

snippet
-- 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

FAQ

Which relations are involved here?
`documents` — referenced directly, no join needed.