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.

SqlSecurity Boundaries

Code

snippet
-- 超级用户建两个角色: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

FAQ

Which tables appear in this script?
The references are `on`, `audit_notes`.