current_user Session Role Identity
current_user tracks the role in effect while session_user keeps the login identity; SET ROLE swaps one, RESET ROLE restores, and both reads stay honest.
Code
CREATE ROLE app_reader;
-- current_user is the role in effect; session_user is the login identity
SELECT current_user AS effective, session_user AS login;
-- SET ROLE switches the effective role; a superuser may switch to any role
SET ROLE app_reader;
SELECT current_user AS effective, session_user AS login;
-- current_role and current_user agree in ordinary sessions
SELECT current_role AS active_role;
-- RESET ROLE returns to the login identity, which never changed
RESET ROLE;
SELECT current_user AS effective, session_user AS login;
SELECT current_role AS role_restored;What the demo swaps
Three SELECT pairs print both identifiers around a role switch. Before it, current_user and session_user match the login. SET ROLE app_reader changes only the effective role: the second pair shows current_user as app_reader while session_user still names the login.
current_role agrees with current_user in this ordinary session, and RESET ROLE restores the original pairing. The login identity was never touched; only the acting role moved and moved back.
Points to remember
- Permission checks consult current_user, not session_user.
- SET ROLE requires membership in the target role unless superuser.
Interactive Tools for This Topic
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.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.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
- What does RESET ROLE restore?
- The session's original current_user, the login identity that session_user kept reporting all along, as the third printed pair shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.