Sub topic 1
Roles: one concept for users and groups
Prerequisites
This chapter assumes you can connect to PostgreSQL with psql or another client. You should know basic SQL, including CREATE TABLE, SELECT, INSERT, UPDATE, and DELETE. You should also know that a server holds databases, and each database holds schemas and tables.
Roles: one concept for users and groups
PostgreSQL has no separate concept of users and groups. Both are roles. A role can log in, own objects, hold privileges, or contain other roles. Attributes and usage decide whether a role acts as a user or a group.
Role attributes: LOGIN, SUPERUSER, CREATEDB, CREATEROLE, and more
Attributes control what a role may do at the server level. The most common ones are:
- LOGIN: the role can connect to the server. A role without LOGIN works as a group.
- SUPERUSER: the role bypasses all privilege checks. Grant this sparingly.
- CREATEDB: the role can create databases.
- CREATEROLE: the role can create, alter, and drop other roles.
- INHERIT: the role automatically uses the privileges of roles it belongs to. This is the default.
CREATE ROLE app_readonly NOLOGIN;
CREATE ROLE alice LOGIN PASSWORD 'change-me' CREATEDB;Ownership versus privileges
Every object has exactly one owner. The owner can do anything to the object, including dropping it and granting access to others. Other roles get access only through privileges that the owner or a superuser grants. Ownership is recorded on the object at creation time. It is not a privilege you grant.
The privilege types and which objects they apply to
Each object type supports its own set of privileges:
| Object | Privileges |
|---|---|
| Database | CONNECT, CREATE, TEMPORARY |
| Schema | USAGE, CREATE |
| Table | SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER |
| Sequence | USAGE, SELECT, UPDATE |
| Function | EXECUTE |
GRANT and REVOKE in practice
Use GRANT to give a privilege and REVOKE to remove it. Reading a table also requires USAGE on its schema.
CREATE SCHEMA shop;
CREATE TABLE shop.orders (id bigint PRIMARY KEY, total numeric(10,2));
GRANT USAGE ON SCHEMA shop TO app_readonly;
GRANT SELECT ON shop.orders TO app_readonly;
GRANT app_readonly TO alice;
REVOKE SELECT ON shop.orders FROM app_readonly;Exercise
Alice is a member of app_readonly, which holds only SELECT on shop.orders. Can alice insert a row into shop.orders? Why or why not?
Show answer
No. Membership passes on only the privileges that appreadonly holds, and appreadonly has no INSERT privilege on the table. To allow inserts, grant INSERT on shop.orders to app_readonly or to a writer role that alice belongs to.