/** * Bootstrap drizzle's __drizzle_migrations ledger from existing schema state. * * Background — task #57: When FleetCrown moved to Hetzner (task #15) the * schema was applied via `drizzle-kit push` (one-shot diff-and-apply). * That doesn't write to the `drizzle.__drizzle_migrations` ledger. As a * result the ledger table doesn't exist, and `drizzle-kit migrate` would * try to re-apply every historical migration from scratch on its first * run — which would fail loudly on CREATE TABLE for tables already * present, and silently produce drift if any IF NOT EXISTS / IF EXISTS * guards saved it. * * This script: * 1. Reads every drizzle/NNNN_*.sql migration file from disk * 2. Computes the drizzle-canonical SHA-256 of each (raw file bytes) * 3. Writes drizzle/meta/_journal.json so future `drizzle-kit generate` * knows the migration history * 4. Produces SQL to: * - CREATE SCHEMA drizzle (idempotent) * - CREATE TABLE drizzle.__drizzle_migrations (idempotent) * - INSERT one row per migration (hash + created_at) * * Modes: * --dry-run (default) print everything, write nothing * --write-journal only update drizzle/meta/_journal.json * --emit-sql emit the SQL to stdout (pipe to psql) * --apply $DATABASE_URL apply directly to the given DB * * Idempotency: --apply uses ON CONFLICT DO NOTHING. Re-running is safe. * * Usage examples: * npx tsx scripts/db/bootstrap-migration-ledger.ts --dry-run * npx tsx scripts/db/bootstrap-migration-ledger.ts --write-journal * npx tsx scripts/db/bootstrap-migration-ledger.ts --emit-sql > /tmp/bootstrap.sql * DATABASE_URL=... npx tsx scripts/db/bootstrap-migration-ledger.ts --apply */ import fs from "fs"; import path from "path"; import crypto from "crypto"; const MIGRATIONS_DIR = path.join(process.cwd(), "drizzle"); const JOURNAL_PATH = path.join(MIGRATIONS_DIR, "meta", "_journal.json"); interface JournalEntry { idx: number; version: string; when: number; tag: string; breakpoints: boolean; } interface MigrationRecord { tag: string; // "0000_initial_schema" file: string; // absolute path hash: string; // sha256 hex of raw file content (drizzle's canonical hash) } function listMigrations(): MigrationRecord[] { const files = fs .readdirSync(MIGRATIONS_DIR) .filter((f) => /^\d{4}_.+\.sql$/.test(f)) .sort(); return files.map((f) => { const filePath = path.join(MIGRATIONS_DIR, f); const content = fs.readFileSync(filePath); const hash = crypto.createHash("sha256").update(content).digest("hex"); const tag = f.replace(/\.sql$/, ""); return { tag, file: filePath, hash }; }); } function buildJournal(records: MigrationRecord[]): { version: string; dialect: string; entries: JournalEntry[] } { // Use monotonically increasing `when` values. The actual epoch milliseconds // don't matter — drizzle only uses these for ordering. Spacing them 1s // apart starting from 2026-01-01 keeps the values readable + ordered. const baseMs = new Date("2026-01-01T00:00:00Z").getTime(); return { version: "7", dialect: "postgresql", entries: records.map((rec, idx) => ({ idx, version: "7", when: baseMs + idx * 1000, tag: rec.tag, breakpoints: true, })), }; } function buildSql(records: MigrationRecord[]): string { const lines: string[] = []; lines.push(`-- Bootstrap drizzle.__drizzle_migrations ledger`); lines.push(`-- ${records.length} historical migrations marked as applied.`); lines.push(`-- Generated by scripts/db/bootstrap-migration-ledger.ts on ${new Date().toISOString()}`); lines.push(``); lines.push(`CREATE SCHEMA IF NOT EXISTS drizzle;`); lines.push(``); lines.push(`CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (`); lines.push(` id SERIAL PRIMARY KEY,`); lines.push(` hash text NOT NULL,`); lines.push(` created_at bigint`); lines.push(`);`); lines.push(``); lines.push(`CREATE UNIQUE INDEX IF NOT EXISTS __drizzle_migrations_hash_idx`); lines.push(` ON drizzle.__drizzle_migrations (hash);`); lines.push(``); // Use the same monotonic timestamps as the journal — that way the journal // and ledger agree on ordering. ON CONFLICT DO NOTHING makes this safe to // re-run; the hash column is unique. const baseMs = new Date("2026-01-01T00:00:00Z").getTime(); for (let i = 0; i < records.length; i++) { const r = records[i]; const when = baseMs + i * 1000; lines.push(`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES`); lines.push(` ('${r.hash}', ${when})`); lines.push(`ON CONFLICT (hash) DO NOTHING;`); lines.push(`-- ^ ${r.tag}`); lines.push(``); } return lines.join("\n"); } async function applyToDb(sql: string, databaseUrl: string): Promise { // Pipe to psql via a tmp file. postgres-js's statement splitter trips on // the comment lines + ON CONFLICT punctuation; psql parses the script // identically to how a human would `psql -f`. Tmp file is unlinked on // exit regardless of success. const { writeFileSync, unlinkSync } = await import("fs"); const { tmpdir } = await import("os"); const { spawnSync } = await import("child_process"); const sqlPath = path.join(tmpdir(), `fc-bootstrap-ledger-${process.pid}-${Date.now()}.sql`); writeFileSync(sqlPath, sql, "utf-8"); try { const result = spawnSync("psql", [databaseUrl, "-v", "ON_ERROR_STOP=1", "-f", sqlPath], { stdio: "inherit", }); if (result.status !== 0) { throw new Error(`psql exited with code ${result.status}`); } } finally { try { unlinkSync(sqlPath); } catch { /* best effort */ } } } function main() { const args = new Set(process.argv.slice(2)); const records = listMigrations(); console.log(`Found ${records.length} migration files in ${MIGRATIONS_DIR}`); for (const r of records) { console.log(` ${r.tag.padEnd(50, " ")} hash=${r.hash.slice(0, 12)}...`); } console.log(""); if (args.has("--write-journal")) { const journal = buildJournal(records); fs.writeFileSync(JOURNAL_PATH, JSON.stringify(journal, null, 2) + "\n"); console.log(`Wrote ${journal.entries.length} entries to ${JOURNAL_PATH}`); return; } const sql = buildSql(records); if (args.has("--emit-sql")) { process.stdout.write(sql); return; } if (args.has("--apply")) { const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { console.error("DATABASE_URL env var required for --apply"); process.exit(1); } void applyToDb(sql, databaseUrl).then(() => { console.log(`Applied to ${databaseUrl.replace(/:[^@]+@/, ":***@")}`); }); return; } console.log("--- SQL (dry run; pass --apply to write) ---\n"); console.log(sql); } main();