1.9 KiB
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(callsdrizzle-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
- Edit
src/db/schema.tswith your table/column changes - Generate a migration:
npx drizzle-kit generate - Review the generated SQL in
drizzle/NNNN_*.sql - 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 generatefrom 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 runafter generating migrations to verify they work with in-memory databases.