SET ROLE Switches Session Identity
SET ROLE changes the effective user inside a session, RESET ROLE returns to the login role, and privileges flip with each switch.
Code
-- 超级用户建两个角色:app_writer 可写,app_reader 只读
CREATE ROLE app_writer NOLOGIN;
CREATE ROLE app_reader NOLOGIN;
CREATE TABLE audit_notes (id int, note text);
GRANT INSERT, UPDATE ON audit_notes TO app_writer;
GRANT SELECT ON audit_notes TO app_reader;
-- SET ROLE 切换"当前会话身份":current_user 变成目标角色
SELECT current_user, session_user; -- 登录角色 vs 会话初始角色
SET ROLE app_writer;
INSERT INTO audit_notes VALUES (1, 'written as app_writer');
SELECT current_user;
-- 回到登录身份:RESET ROLE 恢复 session_user 的完整权限
RESET ROLE;
SELECT current_user;
-- 只授权限组:SET ROLE app_reader 后写入被拒绝
SET ROLE app_reader;
SELECT current_user; -- app_reader
RESET ROLE;Observing the statements run
What runs here is SELECT / INSERT / UPDATE / CREATE — on and audit_notes are the objects involved.
Applying it
The on table is the working surface here.
Statements that matter
GRANT INSERT, UPDATE ON audit_notes TO app_writer;
INSERT INTO audit_notes VALUES (1, 'written as app_writer');
SELECT current_user, session_user; -- 登录角色 vs 会话初始角色
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.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 appear in this script?
- The references are `on`, `audit_notes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.