Sub topic 6
Roles and databases in a PostgreSQL cluster
This chapter assumes you can start psql and run a statement, as covered in the previous chapters. It explains how PostgreSQL organizes who can connect and where data lives. That model explains most of the "role does not exist" and "database does not exist" errors you will hit early on.
One server, one cluster
A PostgreSQL cluster is a single running server instance and the data directory it manages. It is not a group of machines. One cluster listens on one port (5432 by default) and holds two kinds of top-level objects:
- Roles: the identities that connect and own things.
- Databases: separate containers for tables, views, functions, and other objects.
Both are shared at the cluster level in different ways. Roles belong to the cluster, so a role created once can be used to connect to any database in it. Databases are isolated from each other. A session is connected to exactly one database and cannot query a table in another one with a plain SELECT.
Roles: users and groups are the same thing
PostgreSQL has one concept, the role. A role with the LOGIN attribute works as a user. A role without it works as a group that other roles can join. The older commands CREATE USER and CREATE GROUP still exist, but they are aliases. CREATE USER is CREATE ROLE ... LOGIN, so prefer CREATE ROLE and state the attributes explicitly.
The attributes you will meet most often:
| Attribute | Meaning | Default |
|---|---|---|
| `LOGIN` | The role can start a session | off with `CREATE ROLE` |
| `SUPERUSER` | Bypasses all permission checks | off |
| `CREATEDB` | Can create databases | off |
| `CREATEROLE` | Can create and manage other roles | off |
| `PASSWORD` | Sets a password for password authentication | none |
Most installations create one superuser at initialization. On Linux packages and the Windows installer it is named postgres. On Homebrew for macOS it is usually your operating-system username. This is why earlier chapters connected with -U postgres.
See who you are and where you are
Two functions report your current identity and database:
SELECT current_user, current_database();List all roles with the \du meta-command, or query the catalog directly:
SELECT rolname, rolcanlogin, rolsuper, rolcreatedb
FROM pg_roles
WHERE rolname !~ '^pg_'
ORDER BY rolname;The WHERE clause hides the built-in pg_ roles, such as pg_read_all_data, which exist for granting common privilege bundles. The query returns one row per role, including your postgres superuser. Its rolcanlogin and rolsuper columns are t (true).
Creating roles
Create a login role with a password, and a role that may also create databases:
CREATE ROLE reader LOGIN PASSWORD 'change-me-now';
CREATE ROLE app_admin LOGIN CREATEDB PASSWORD 'change-me-too';Use throwaway passwords for practice and real secrets in production. Statements containing passwords can appear in server logs and in your psql history. \password rolename in psql avoids that, because it prompts you and sends only a hash.
To make a group, create a role without LOGIN and grant it to members:
CREATE ROLE staff NOLOGIN;
GRANT staff TO reader;Privileges granted to staff are then available to reader. A role that is a member of another role normally inherits its privileges. Attributes such as SUPERUSER, CREATEDB, and LOGIN are never inherited this way. They belong only to the role they were set on.
Databases and their built-in members
A new cluster contains three databases:
| Database | Purpose |
|---|---|
| `postgres` | A default database for administrative connections. Safe to use as a landing spot. |
| `template1` | The template that `CREATE DATABASE` copies by default. |
| `template0` | A pristine, unmodified template. It normally refuses connections. |
List them with \l. Because CREATE DATABASE copies template1, anything you add to template1 (an extension, for example) appears in every database you create afterward. Keep template1 clean unless you want that effect.
Every database has an owner, which is the role that created it unless you say otherwise. The owner can drop the database and manage its objects. Set the owner at creation:
CREATE DATABASE teamdb OWNER app_admin;To create a database, your role needs CREATEDB or SUPERUSER. Setting OWNER to a different role also requires that you be a superuser or a member of that role.
Check owners from the catalog:
SELECT datname, pg_get_userbyid(datdba) AS owner
FROM pg_database
ORDER BY datname;How connection defaults pick a role and database
When you run psql with no options, it fills in the missing parameters itself:
- The role defaults to your operating-system username (or
PGUSERif set). - The database defaults to the role name, not to
postgres(orPGDATABASEif set).
This explains a very common first error. If you are logged in as alice and type psql, PostgreSQL tries to connect role alice to a database named alice. If that database does not exist, you get this:
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "alice" does not existThe fix is to name a database that exists:
psql -U postgres -d postgresThe reverse mistake produces FATAL: role "alice" does not exist. The role is missing from the cluster, so create it as a superuser or connect as an existing role.
Who may connect: two separate checks
Connecting passes through two independent gates. Confusing them is the main source of "it should work" frustration.
- Authentication is configured in
pg_hba.conf, a file on the server. Each line matches a connection type, database, role, and address to a method such asscram-sha-256,md5,peer, ortrust. Matching a line with a failing method givespassword authentication failedorPeer authentication failed. - Authorization is the privilege system inside the database. After authentication succeeds, the role needs
CONNECTon the database and the right privileges on its objects.
On many Linux installations, local socket connections use peer authentication. This lets the OS user postgres connect as role postgres without a password, but another OS user connecting as postgres over the socket is refused. Adding -h localhost makes psql use TCP, which usually falls under a password-based rule.
By default, the special pseudo-role PUBLIC (meaning every role) holds CONNECT on every new database. To restrict a database to specific roles, revoke from PUBLIC and grant explicitly:
REVOKE CONNECT ON DATABASE teamdb FROM PUBLIC;
GRANT CONNECT ON DATABASE teamdb TO reader;Superusers and the owner are not blocked by this, because they bypass or hold the privilege already.
Connecting as a new role
With the roles above in place, connect as reader to teamdb over TCP:
psql -h localhost -p 5432 -U reader -d teamdbEnter the password when prompted. Then run the identity query again:
SELECT current_user, current_database();It should return reader and teamdb. Inside psql, \c postgres reconnects the same session to another database, and \c teamdb reader switches both. Each \c opens a new connection. Session settings and temporary tables from the old one do not carry over.
Removing roles and databases
Cleanup order matters, because a role cannot be dropped while it still owns objects. Connect to a database other than the one you are dropping, such as postgres, then run:
DROP DATABASE teamdb;
DROP ROLE reader;
DROP ROLE staff;
DROP ROLE app_admin;DROP DATABASE fails if anyone is connected to the target, including your own session. If DROP ROLE reports role "app_admin" cannot be dropped because some objects depend on it, either drop those objects first or reassign them with REASSIGN OWNED BY app_admin TO postgres; and then DROP OWNED BY app_admin;. Run both in the database that contains the objects.
Common mistakes
- Expecting
psqlto default to thepostgresdatabase. It defaults to a database named after the role. - Creating a role with
CREATE ROLEand forgettingLOGIN, then seeingrole "x" is not permitted to log in. - Trying to query a table in another database with
otherdb.public.books. Cross-database references are not supported, so connect to the other database or use a foreign data wrapper. - Editing
pg_hba.confwithout reloading the server. The file is read again afterSELECT pg_reload_conf();or a service reload. - Running destructive statements as a superuser out of convenience.
Exercise
You are logged in to your OS as dana and run psql with no options. It fails with FATAL: database "dana" does not exist. Give two different ways to connect successfully, assuming the role dana exists and the database postgres exists.
Show answer
Name the database explicitly: psql -d postgres. Alternatively, create a database named dana from another session (CREATE DATABASE dana;, which needs a role with CREATEDB or superuser rights), after which a plain psql works. Setting the PGDATABASE=postgres environment variable also works. The failure happens because psql defaults the database name to the role name.
Exercise
A role report_user was created with CREATE ROLE report_user PASSWORD 'x';. Connecting as that role fails. What is the likely cause, and what single statement fixes it?
Show answer
The role lacks the LOGIN attribute, because CREATE ROLE does not grant it by default. Run ALTER ROLE report_user LOGIN; as a superuser. If the error then changes to a password or pg_hba.conf message, the remaining problem is authentication, not the role.