// SQL snippet

Default privileges for future tables

GRANT ... ON ALL TABLES covers the tables that exist when it runs. Default privileges make tables created later accessible too; without them, every migration that adds a table locks the reporting role out of it.

Main statement
PostgreSQL
次もカバーします
SQL Server MySQL

The task

The reader role loses access to every new table the migration user creates, and re-granting by hand each time is the current workaround.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_reader;
-- tables app_owner creates in public from now on get these
-- grants for app_reader automatically

仕組み

Default privileges are keyed to the role that creates the objects. Without FOR ROLE they apply only to tables created by the role running the ALTER, so if a migration user creates the tables, name that role. Existing tables are untouched; run GRANT ... ON ALL TABLES IN SCHEMA alongside so current and future tables are both covered.

Variations

PostgreSQL: audit current defaults

PostgreSQL
-- defaclobjtype: r = tables, S = sequences, f = functions,
-- T = types, n = schemas; psql shows the same with \ddp
SELECT defaclrole::regrole AS creating_role,
       defaclnamespace::regnamespace AS schema_name,
       defaclobjtype, defaclacl
FROM pg_default_acl;

MySQL

MySQL
-- MySQL has no default-privilege mechanism; grant at the
-- database level instead, which covers future tables:
GRANT SELECT ON mydb.* TO 'analyst'@'%';

SQL Server

SQL Server
-- no default privileges either; a schema-level grant already
-- covers objects created in the schema later:
GRANT SELECT ON SCHEMA::dbo TO app_reader;

Questions that come up

Why do my default privileges do nothing?

Almost always the FOR ROLE clause: defaults apply to objects created by the named role, and your migrations may run as a different user. Query pg_default_acl to see which creating roles have defaults configured, and add one for whichever role actually runs your DDL.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.