0033. SQL migrations own the schema, Drizzle is generated
Source:
docs/decisions/0033-sql-migrations-own-the-schema.md. Generated at build time; edit the source file.
Date: 2026-11-21 Status: Accepted. Implements 0030.
Context
Section titled “Context”Until R1 the schema lived in packages/db/src/schema.ts and Drizzle generated the migrations from it. The Rust backend reads and writes the same Postgres database, so two tools cannot both own the schema. Existing databases (local, and any deployed one) were migrated by Drizzle and carry drizzle.__drizzle_migrations.
Decision
Section titled “Decision”db/migrations/is the source of truth. Plain SQL files, applied by sqlx (db::MIGRATOR,db::pool::migrate) when the worker and the CLI start. Tests get a fresh database from#[sqlx::test(migrator = "db::MIGRATOR")].- The baseline is the three Drizzle migrations concatenated (
20261121000000_m1_baseline.sql, statement breakpoints removed). Its identity is proved, not assumed:backend/scripts/check-baseline-schema.shmigrates one database with drizzle-kit and another with only the baseline file, then diffspg_dump --schema-only --no-owner --no-privileges --exclude-schema=drizzleand a catalogue introspection (columns, constraints, indexes, enum labels, sequences). The expected output is empty with exit code 0. - Existing databases are adopted.
db::baseline::adopt_drizzle_baselineruns beforemigrate. When_sqlx_migrationshas no rows anddrizzle.__drizzle_migrationshas exactly three rows, it creates_sqlx_migrationswith sqlx’s own DDL and records the baseline with the checksum embedded inMIGRATOR;migratethen applies only later migrations. If_sqlx_migrationsalready has rows it does nothing, and a database with no history at all is left tomigrate. Adoption also checks thatcreated_atof the three Drizzle rows equals the known journal timestamps and that every baseline table (games,linked_accounts,moves,import_runs,user_events,position_evals) and theanalysis_statusenum exist. Any other state (for example two Drizzle rows, three rows with a missing table, or tables without any history) is an error that names the state, so a half-migrated database is never guessed at. - Migrations run on their own connection.
db::pool::connect_for_migrationsdisablesstatement_timeout(a long index build must not be cut at 30 s) and is the pool to pass tomigrate. It sets the timeout as a startup parameter, which pgbouncer in transaction mode rejects, so migrations must connect to Postgres directly, not through a pooler. - The web app’s Drizzle schema is generated from the SQL migrations (Task 15), so the web app keeps typed queries without owning DDL.
drizzle-kit generateis no longer run by hand. - Version ranges.
20261121000000to20261121009999are reserved for R1 (baseline, jobs, events, analysis generations). Later milestones, such as M4’s Better Auth tables, use later versions.
Consequences
Section titled “Consequences”- One migration history, in one directory, applied by one tool; migrations are never edited after release (sqlx verifies checksums).
- The schema check needs Docker and the TypeScript worker image, so it runs as a script (CI job
baseline-schema) rather than incargo test. - Until the Drizzle migration files are deleted (R1 Task 27), changing the schema means writing a new SQL migration and regenerating the Drizzle schema.
Generated schema and M4 hand-off
Section titled “Generated schema and M4 hand-off”scripts/db/generate-drizzle-schema.shcreates a scratch databaseschema_pull, applies everydb/migrations/*.sqlin version order (psql -1,ON_ERROR_STOP), runsdrizzle-kit pull(pnpm --filter @ci/db db:pull, configpackages/db/drizzle.pull.config.ts,_sqlx_migrationsexcluded), formats with Biome and drops the database. The output,packages/db/src/generated/schema.tsandrelations.ts, is committed.- CI job
schema-driftruns the script and thengit diff --exit-code packages/db/src/generated. A migration change without regeneration fails it with the command to run. Every lane that adds a migration (T16user_events_watermark, T19, M4) reruns the script as its last step and commits the regenerated files. - M4 (
apps/web) imports the generated schema and adds its own tables (Better Auth) only as SQL migrations indb/migrations/with versions after20261121009999, then reruns the script. Until R1 Task 27 removespackages/db/src/schema.ts, the hand-written schema remains the@ci/dbexport; generated enum names differ (see the rename list below); the$type<>narrowing is re-applied by the normalisation step.
Generator safety and normalisation (fix round 1)
Section titled “Generator safety and normalisation (fix round 1)”Safety. The scratch database is schema_pull_<pid>_<epoch> (unique per run); the exit trap drops only that database and removes only the scratch directory packages/db/.pull-tmp-<pid>. drizzle-kit pull writes into that directory (PULL_OUT); schema.ts and relations.ts are copied over the committed files only after pull, normalisation and Biome all succeeded. A failed run leaves the committed output untouched. drizzle-kit and drizzle-orm are pinned exactly (0.31.11, 0.45.4) so the output cannot change under a range bump.
Normalisation (packages/db/scripts/normalise-generated.mjs, run by the generator before Biome; each rule fails loudly if its input pattern is absent):
- All timestamp columns use
mode: "date"(drizzle-kit emits"string"), matching the hand-written schema. user_events.idisbigserial({ mode: "number" })(drizzle-kit emits"bigint").jobs.idstaysbigint.position_evals.pvandinteractive_evals.moves(R3) defaults aresql`'{}'::text[]`(drizzle-kit emits[""]); thesqlimport is added.- Every
.op("..._ops")opclass is removed: drizzle-kit attaches opclass names from the wrong column (for exampletimestamptz_opson a uuid column). Postgres uses the default opclass anyway. $type<ImportCursor>()onlinked_accounts.import_cursorand$type<ImportErrorCode>()onimport_runs.error_codeare re-applied, and both types are exported from the generatedschema.ts.- Output order is stable: enums first (tables evaluate them eagerly), then tables, each sorted by export name; in
relations.tsblocks and the entries inside each block are sorted by name. - The
relations.tsimport./schemabecomes./schema.js(nodenext).
Enum rename list (hand-written export to generated export): platformEnum to platform, timeClassEnum to timeClass, colorEnum to color, resultEnum to result, analysisStatusEnum to analysisStatus, evalSourceEnum to evalSource, judgementEnum to judgement, phaseEnum to phase, importRunStatusEnum to importRunStatus. New: jobState. Table exports keep their names. Note platform, color, result and phase are generic words and can shadow local variables.
Import path. @ci/db/generated (and @ci/db/generated/relations) export the generated files: development condition to src/generated/*.ts (ADR 0026), types/default to dist/generated/*; the build emits them. @ci/db itself still exports the hand-written schema.ts. Task 27 owns the switch of the main @ci/db export to the generated schema: it removes the hand-written schema.ts, repoints export * from "./schema.js" at the generated schema and migrates the enum consumers to the new names above. M4 may import @ci/db/generated before that.
What drift detection does NOT cover. drizzle-kit pull does not emit comments, so comment-only migrations (COMMENT ON ...) produce no diff; triggers and functions are not represented; some CHECK constraints and partial-index details may not round-trip. Only column, enum, index, key and relation changes reliably show up as drift. The Rust sqlx code and the SQL migrations remain the authority for everything else.