How to Cache a Database Fixture Snapshot in GitHub Actions
Cache a SQL dump of a migrated, seeded database keyed on the migration and seed files, then restore it instead of rebuilding the schema each run.
Build the fixture once (migrate + seed), pg_dump it to a file, and cache that file keyed on a hash of your migrations and seeds. On a cache hit, pg_restore the dump; on a miss, rebuild and repopulate the cache.
Steps
- Key
actions/cacheon a hash of the migrations and seed files. - On a miss, migrate + seed, then
pg_dumpto the cached path. - On a hit, restore the dump with
pg_restoreand skip migrate/seed.
Workflow
.github/workflows/ci.yml
steps:
- uses: actions/checkout@v4
- id: fixture
uses: actions/cache@v4
with:
path: fixture.dump
key: dbfixture-${{ hashFiles('migrations/**', 'seeds/**') }}
- if: steps.fixture.outputs.cache-hit != 'true'
run: |
npx prisma migrate deploy && npx prisma db seed
pg_dump -Fc -h localhost -U postgres app_test > fixture.dump
- if: steps.fixture.outputs.cache-hit == 'true'
run: pg_restore -h localhost -U postgres -d app_test --no-owner fixture.dump
- run: npm test
env:
PGPASSWORD: postgresGotchas
- Include every input that changes the data in the cache key, or stale fixtures will mask schema changes.
- Restore into a freshly created database; restoring over existing tables can fail on conflicts.
Related guides
How to Dump and Restore a Database in GitHub ActionsCapture a Postgres database with pg_dump and reload it with pg_restore inside a GitHub Actions job, useful fo…
How to Seed a Test Database in GitHub ActionsLoad fixture data into the CI database after migrations and before tests in GitHub Actions, so integration te…
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…