Roles, databases, and schemas
Grant PostgreSQL permissions
Keep ownership with the migration role while granting the runtime role only the database, schema, table, and sequence access it needs.
8 minute lesson
~~~
Connect to notes_app, become the owner, and create a dedicated schema:
SET ROLE notes_owner;
CREATE SCHEMA app AUTHORIZATION notes_owner;
RESET ROLE;
Let the runtime role connect and resolve names inside that schema:
REVOKE CONNECT ON DATABASE notes_app FROM PUBLIC;
GRANT CONNECT ON DATABASE notes_app TO notes_app;
GRANT USAGE ON SCHEMA app TO notes_app;
USAGE does not grant access to tables. Grant row operations separately:
GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA app TO notes_app;
GRANT USAGE, SELECT
ON ALL SEQUENCES IN SCHEMA app TO notes_app;
Identity columns use sequences. Without sequence access, an insert can fail even when the role has INSERT on the table.
Existing grants do not cover tables created later. Run these statements as notes_owner:
SET ROLE notes_owner;
ALTER DEFAULT PRIVILEGES IN SCHEMA app
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO notes_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA app
GRANT USAGE, SELECT ON SEQUENCES TO notes_app;
RESET ROLE;
The runtime role can now change rows, but it does not own tables and cannot drop them.
Lesson completed