has_table_privilege Guards Migration Steps
Verify grants with has_table_privilege before risky DDL: test a named role, current_user, or PUBLIC, and list several privileges with OR semantics.
Code
-- 迁移脚本自检:动 DDL 之前先确认确实持有相应权限
CREATE ROLE audit_reader NOLOGIN;
CREATE TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
GRANT SELECT ON audit_log TO audit_reader;
-- 三种形态:显式角色 / 省略角色(默认 current_user)/ PUBLIC 伪角色
SELECT has_table_privilege('audit_reader', 'audit_log', 'SELECT') AS reader_can_select;
SELECT has_table_privilege('audit_reader', 'audit_log', 'INSERT') AS reader_can_insert;
SELECT has_table_privilege('audit_log', 'SELECT') AS i_am_allowed;
-- 权限串大小写不敏感;逗号分隔表示"任一持有即为真"(OR 语义)
SELECT has_table_privilege('audit_reader', 'audit_log', 'insert, update') AS reader_can_write;
-- PUBLIC 上的授权决定未显式授权的角色能不能读
SELECT has_table_privilege('public', 'audit_log', 'SELECT') AS public_can_select;
-- 迁移守门:缺权限就提前中断,而不是跑到一半报错
DO $$
BEGIN
IF NOT has_table_privilege('audit_reader', 'audit_log', 'TRUNCATE') THEN
RAISE EXCEPTION 'audit_reader lacks TRUNCATE; aborting refresh job';
END IF;
END $$;What the code does
The file runs SELECT / CREATE statements.
Mechanically, the statements are built from: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Key statements
SELECT has_table_privilege('audit_reader', 'audit_log', 'insert, update') AS reader_can_write;
SELECT has_table_privilege('audit_reader', 'audit_log', 'SELECT') AS reader_can_select;
SELECT has_table_privilege('audit_reader', 'audit_log', 'INSERT') AS reader_can_insert;
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.