Sub topic 2
Group roles, membership, and inheritance
This chapter assumes you can write basic SQL, connect to PostgreSQL with psql, and know that a database holds schemas, and schemas hold tables. You should also know that PostgreSQL uses one concept, the role, for both users and groups.
Group roles and membership
A group role is a role created with NOLOGIN. You grant privileges to the group, then make login roles members of it. Members inherit the group's privileges when their INHERIT setting is on, which is the default.
CREATE ROLE app_readonly NOLOGIN;
CREATE ROLE alice LOGIN PASSWORD 'change-me';
GRANT app_readonly TO alice;Alice now holds every privilege granted to app_readonly. In PostgreSQL 16 and later, each membership carries its own options: GRANT app_readonly TO alice WITH INHERIT TRUE, SET FALSE;. In older versions, set NOINHERIT on the member role and use SET ROLE to switch into the group.
PUBLIC and the defaults you did not set
PUBLIC is a pseudo-role. Every role is implicitly a member of it, so a grant to PUBLIC applies to everyone. A new database gives PUBLIC CONNECT and TEMPORARY. Before PostgreSQL 15, PUBLIC also had CREATE on the public schema. Remove what you do not want:
REVOKE ALL ON DATABASE appdb FROM PUBLIC;
GRANT CONNECT ON DATABASE appdb TO app_readonly, app_writer;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;Database and schema privileges
A role needs CONNECT on the database and USAGE on a schema before it can reach any table inside. Schema CREATE lets a role add objects to that schema.
CREATE SCHEMA shop AUTHORIZATION app_owner;
GRANT USAGE ON SCHEMA shop TO app_readonly, app_writer;Table and column privileges
Table privileges include SELECT, INSERT, UPDATE, DELETE, and TRUNCATE. Column-level grants limit a role to named columns.
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO app_readonly;
GRANT SELECT (id, customer) ON shop.orders TO alice;ALL TABLES affects only tables that exist when you run the command. Tables created later need ALTER DEFAULT PRIVILEGES.
Exercise:
Exercise
alice is a member of appreadonly, which has SELECT on shop.orders. appreadonly does not have USAGE on schema shop. Can alice select from shop.orders?
Show answer
No. PostgreSQL checks schema USAGE before it resolves the table name, so the query fails even though the table grant exists. Grant USAGE on the schema to app_readonly.