How to Dump and Restore a Database in GitHub Actions
Run pg_dump to capture the database to a file and pg_restore to reload it; in CI this drives fixture builds and migration smoke tests.
Use the custom format (-Fc) for a compressed, restorable archive. Dump from a source database, then restore into a fresh target with pg_restore --clean --no-owner to verify the dump is consistent.
Steps
- Set
PGPASSWORDsopg_dump/pg_restoreauthenticate non-interactively. - Dump with
pg_dump -Fcto a file. - Restore into a fresh database with
pg_restore --no-owner.
Workflow
.github/workflows/ci.yml
steps:
- name: Dump
run: pg_dump -Fc -h localhost -U postgres app > app.dump
env: { PGPASSWORD: postgres }
- name: Create restore target
run: createdb -h localhost -U postgres app_restored
env: { PGPASSWORD: postgres }
- name: Restore
run: pg_restore -h localhost -U postgres -d app_restored --no-owner app.dump
env: { PGPASSWORD: postgres }Gotchas
- A plain SQL dump (default format) is restored with
psql -f, notpg_restore;pg_restoreneeds the custom or directory format. - Use
--no-ownerand--no-aclwhen restoring under a different role than the dump was taken as.
Related guides
How to Cache a Database Fixture Snapshot in GitHub ActionsSpeed up CI by caching a pre-migrated, pre-seeded database dump with actions/cache, restoring it with pg_rest…
How to Validate Migrations Are Reversible in GitHub ActionsVerify a new migration can roll back cleanly in GitHub Actions by applying it, rolling it back one step, and…
How to Run Integration Tests Against a Real Database in GitHub ActionsWire a GitHub Actions service container, migrations, and seed data together so your integration suite runs ag…