Files
Codewalkers/docs/database-migrations.md
2026-02-07 00:33:12 +01:00

1.9 KiB

Database Migrations

This project uses drizzle-kit for database schema management and migrations.

Overview

  • Schema definition: src/db/schema.ts (drizzle-orm table definitions)
  • Migration output: drizzle/ directory (SQL files + meta journal)
  • Config: drizzle.config.ts
  • Runtime migrator: src/db/ensure-schema.ts (calls drizzle-orm/better-sqlite3/migrator)

How It Works

On every server startup, ensureSchema(db) runs all pending migrations from the drizzle/ folder. Drizzle tracks applied migrations in a __drizzle_migrations table so only new migrations are applied. This is safe to call repeatedly.

Workflow

Making schema changes

  1. Edit src/db/schema.ts with your table/column changes
  2. Generate a migration:
    npx drizzle-kit generate
    
  3. Review the generated SQL in drizzle/NNNN_*.sql
  4. Commit the migration file along with your schema change

Applying migrations

Migrations are applied automatically on server startup. No manual step needed.

For tests, the same ensureSchema() function is called on in-memory SQLite databases in src/db/repositories/drizzle/test-helpers.ts.

Checking migration status

# See what drizzle-kit would generate (dry run)
npx drizzle-kit generate --dry-run

# Open drizzle studio to inspect the database
npx drizzle-kit studio

Rules

  • Never hand-write migration SQL. Always use drizzle-kit generate from the schema.
  • Never use raw CREATE TABLE statements for schema initialization. The migration system handles this.
  • Always commit migration files. They are the source of truth for database evolution.
  • Migration files are immutable. Once committed, never edit them. Make a new migration instead.
  • Test with npx vitest run after generating migrations to verify they work with in-memory databases.