Row-Level Security (RLS)
Implement fine-grained access control at the row level for multi-tenant applications.
Enabling RLS
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
Creating Policies
Basic Tenant Isolation
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_tenant_id());
Read-Only Public Access
CREATE POLICY public_read ON products
USING (published = true);
Insert Validation
CREATE POLICY insert_own_data ON documents
WITH CHECK (owner_id = current_user_id());
Policy Types
| Type | Description |
|---|
PERMISSIVE | Multiple policies are OR’d together |
RESTRICTIVE | Multiple policies are AND’d together |
For All Operations
CREATE POLICY full_access ON accounts
USING (owner_id = current_user_id())
WITH CHECK (owner_id = current_user_id());
System Functions
| Function | Description |
|---|
current_tenant_id() | Current tenant ID |
current_tenant_name() | Current tenant name |
current_user_id() | Current user ID |
View Policies
SELECT * FROM pg_rls_policies();
REPL Commands
\tenant rls create orders policy_name "tenant_id = current_tenant_id()"
\tenant rls delete orders policy_name
Disabling RLS
ALTER TABLE orders DISABLE ROW LEVEL SECURITY;
DROP POLICY policy_name ON orders;