brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pg_dumpall --globals-only saves the PostgreSQL roles that pg_dump leaves out

Postgresql
~/tips/tip-database-pg-dumpall-globals-only

pg_dumpall --globals-only -f globals.sql

Dumps only the roles and tablespaces of a PostgreSQL server, which per-database dumps do not contain.

A pg_dump of one database holds its tables, but not the users that own them. Roles and tablespaces live outside any single database. If you restore onto a fresh server, the restore then complains about roles that do not exist. This is an easy gap in a backup routine.

pg_dumpall --globals-only -f globals.sql

The docs describe -g / --globals-only as dumping only global objects, which means roles and tablespaces, and no databases. The result is a plain SQL file you can keep next to your normal dumps. If you only want the roles, --roles-only (-r) narrows it further.

A restore on a new server then goes in two steps: first the globals, then each database:

psql -f globals.sql postgres
pg_restore -d appdb appdb.dump

The docs say you need superuser privileges to run a saved script that adds roles, so run the first command as a superuser. Connecting to the postgres database for it is a common choice.

The caveat is what a globals dump contains. It includes role definitions and, by default, their passwords, so treat the file like a secret and keep it out of shared folders and git. If you do not want the passwords in there, the docs list --no-role-passwords, but then restored roles have no password until you set one. Also, the output has no databases in it. It does not replace the per-database dumps, it complements them.

With a plain text dump you can open the file and see what is there, which is handy before you run it on a new machine. If you get “role already exists” errors on a server that already has some roles, that is expected, and you can read the file and decide what to skip.

Further reading: PostgreSQL documentation: pg_dumpall

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link