GRANT Role Least Privilege
Give a reporting role read-only access with GRANT SELECT and ALTER DEFAULT PRIVILEGES so future tables inherit the same narrow scope.
Code
-- 最小权限起步:NOLOGIN 角色不能直接登录,只能作为权限容器
CREATE ROLE report_reader NOLOGIN;
-- schema USAGE 是进门权限,SELECT 是数据权限:写路径完全不授
GRANT USAGE ON SCHEMA public TO report_reader;
GRANT SELECT ON sales, orders TO report_reader;
-- 以后新建的表自动带上同样的 SELECT 授权,避免每次 DDL 后补权限
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO report_reader;
-- 复核角色实际拿到的权限
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE grantee = 'report_reader';
-- 收回是逐项的:orders 的读权限撤销后,角色只剩 sales 可读
REVOKE SELECT ON orders FROM report_reader;What the code does
Several statements share this file — SELECT / CREATE / ALTER, with information_schema.role_table_grants and report_reader among the objects involved.
What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; DEFAULT values filling omitted columns.
Using it
Run the statement against the information_schema.role_table_grants table.
Key statements
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE grantee = 'report_reader';
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO report_reader;
GRANT SELECT ON sales, orders TO report_reader;
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?
- `information_schema.role_table_grants`, `report_reader` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.