DEV Community

websilvercraft
websilvercraft

Posted on

How does Drizzle handle migrations - Part 1

Drizzle keeps a local snapshot of the previous schema and diffs the current TS schema against that snapshot when generating migrations.

Here’s how it works:

  • The source of truth: the TypeScript schema files (e.g. src/db/schema.ts, schema.billing.ts).

  • Drizzle’s stored “old state”: a small meta snapshot that lives next to the migrations, typically under something like:

  migrations/
    0001_init.sql
    0002_billing.sql
    ...
    meta/
      _journal.json
      _meta.json
Enter fullscreen mode Exit fullscreen mode

(Exact file names can vary by Drizzle version, but there’s always a meta folder with the snapshot/journal.)

  • When you run drizzle-kit generate: Drizzle reads:
  1. your current TS schema
  2. the previous meta snapshot …and produces a new 00xx_*.sql migration that transforms the old snapshot into the new schema. It also updates the meta files.
  • What the DB stores: In the database, Drizzle keeps a tiny migrations journal table (e.g. __drizzle_migrations / similar) that tracks which migration files were applied. It’s not used for schema diffing-only for apply-order / applied-state when you execute migrations.

If things get out of sync

  • Lost meta folder? You can introspect the DB to recreate a baseline schema (Drizzle has an introspect command) or generate a new “initial” migration matching the current DB, then continue forward.
  • Edited an old migration? Don’t. Migrations should be immutable once applied. If you must, expect to reconcile by fixing your meta and/or DB to match.
  • DB drifted from code? Either:

    • Update your TS schema to match and generate the next migration, or
    • Use introspection to realign the local snapshot with the live DB, then proceed.

TL;DR

  • Drizzle diffs TS schema vs. its local meta snapshot, not the live DB.
  • The DB only tracks which migrations ran, not the structure for diffing.
  • If the snapshot is missing/outdated, use introspection to rebuild a baseline or create a new initial migration that matches the current DB, then keep going.

Top comments (0)