Move drizzle/, dist/, and coverage/ into apps/server/ so all server-specific artifacts live alongside the source they belong to. - git mv drizzle/ → apps/server/drizzle/ - drizzle.config.ts: out → ./apps/server/drizzle - tsconfig.json: outDir → ./apps/server/dist, exclude drizzle dir - package.json: main/bin/clean point to apps/server/dist/ - vitest.config.ts: reportsDirectory → ./apps/server/coverage - .gitignore: add coverage/ entry - ensure-schema.ts: update getMigrationsPath() for new layout - docs/database-migrations.md: update drizzle/ references
1.9 KiB
1.9 KiB
Database Migrations
This project uses drizzle-kit for database schema management and migrations.
Overview
- Schema definition:
apps/server/db/schema.ts(drizzle-orm table definitions) - Migration output:
apps/server/drizzle/directory (SQL files + meta journal) - Config:
drizzle.config.ts - Runtime migrator:
apps/server/db/ensure-schema.ts(callsdrizzle-orm/better-sqlite3/migrator)
How It Works
On every server startup, ensureSchema(db) runs all pending migrations from the apps/server/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
apps/server/db/schema.tswith your table/column changes - Generate a migration:
npx drizzle-kit generate - Review the generated SQL in
apps/server/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 apps/server/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.