import { migrate } from "drizzle-orm/node-postgres/migrator"; import { readFileSync } from "node:fs"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { createClient } from "./index.js"; import { assertJournalMonotonic, formatJournalViolations, type JournalEntry, } from "./journal-check.js"; const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { console.error("DATABASE_URL not set"); process.exit(1); } // --- Pre-flight: refuse to run if the journal is non-monotonic. ----------- // Drizzle silently skips entries whose `when` is older than the previous // entry's `when`. We've hit this twice now (0010/0011, then 0012/0013), // each time the symptom was "Migrations applied." with no schema change // and a 500 in production for the missing column. Catch it before we // hand the journal to drizzle. const __dirname = dirname(fileURLToPath(import.meta.url)); const journalPath = join(__dirname, "..", "migrations", "meta", "_journal.json"); const journal = JSON.parse(readFileSync(journalPath, "utf8")) as { entries: JournalEntry[]; }; const check = assertJournalMonotonic(journal.entries); if (!check.ok) { console.error(formatJournalViolations(check)); console.error( "\nRefusing to run drizzle migrate. Bump the offending `when` values in\n" + "_journal.json so they're strictly increasing in the same order as `idx`.", ); process.exit(2); } const { db, pool } = createClient(databaseUrl); console.log("Applying migrations..."); await migrate(db, { migrationsFolder: "./migrations" }); console.log("Migrations applied."); await pool.end();