Skip to content
Latchkey

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/cache on a hash of the migrations and seed files.
  • On a miss, migrate + seed, then pg_dump to the cached path.
  • On a hit, restore the dump with pg_restore and 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: postgres

Gotchas

  • 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

Run this faster and cheaper on Latchkey managed runners. Start free →