ALTER DEFAULT PRIVILEGES Grants Future Tables

Pre-grant rights on tables and sequences a role will create later, then read pg_default_acl to see which default grants are registered.

SqlSecurity Boundaries

Code

snippet
-- default privileges cover future tables only;已存在的对象要单独 GRANT
ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT SELECT, INSERT, UPDATE ON TABLES TO app_readwrite;

ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT SELECT ON TABLES TO app_readonly;

-- 序列与函数是独立的默认权限面
ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT USAGE, SELECT ON SEQUENCES TO app_readwrite;

-- pg_default_acl 记录「由谁创建的默认 grants」:没有行说明还没注册任何默认授权
SELECT
    grantor_role.rolname AS grantor,
    target_schema.nspname AS schema_name,
    CASE acl.defaclobjtype
        WHEN 'r' THEN 'table'
        WHEN 'S' THEN 'sequence'
        WHEN 'f' THEN 'function'
        WHEN 'T' THEN 'type'
        WHEN 'n' THEN 'schema'
    END AS object_kind,
    acl.defaclacl AS granted
FROM pg_default_acl acl
JOIN pg_roles grantor_role ON grantor_role.oid = acl.defaclrole
JOIN pg_namespace target_schema ON target_schema.oid = acl.defaclnamespace
ORDER BY 1, 2, 3;

How it works

What runs here is SELECT / INSERT / UPDATE / ALTER — on, pg_default_acl, pg_roles and pg_namespace are the objects involved.

Mechanically, the statements are built from: 2 JOINs combining rows across tables; an ORDER BY that fixes the output order; DEFAULT values filling omitted columns.

What to watch for

  • Row counts compound across 2 joins; make sure the join keys are indexed before adapting this to production data volumes.

Applying it

The on table is the working surface here.

Statements that matter

ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT SELECT, INSERT, UPDATE ON TABLES TO app_readwrite;
ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT USAGE, SELECT ON SEQUENCES TO app_readwrite;
ALTER DEFAULT PRIVILEGES IN SCHEMA app
    GRANT SELECT ON TABLES TO app_readonly;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `on`, `pg_default_acl`, `pg_roles`, `pg_namespace`, with 2 joins tying them together.