mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 09:47:22 +01:00
Pre-this-commit, the Hetzner DB had ALL 26 historical migrations applied (via drizzle-kit push during the v0.6 cutover, task #15) but ZERO rows in drizzle.__drizzle_migrations because push doesn't write the ledger. As a result drizzle-kit migrate would have tried to re-apply every migration from scratch on its first run — failing on the first CREATE TABLE for an already-existing table, OR worse, silently producing drift if any IF NOT EXISTS / IF EXISTS guards saved the run. This commit closes that gap permanently. NEW scripts/db/bootstrap-migration-ledger.ts (175 lines): Reads all drizzle/NNNN_*.sql files. Computes sha256 of each (drizzle's canonical hash format). Modes: --dry-run (default) Print the SQL it would apply --emit-sql Print to stdout (pipe to psql) --write-journal Update drizzle/meta/_journal.json locally --apply Run against DATABASE_URL via psql -f Idempotent (uses ON CONFLICT DO NOTHING). Safe to re-run. APPLIED to prod (postgresqlbridge.orangecat.ch): CREATE SCHEMA IF NOT EXISTS drizzle; CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (id, hash, created_at); CREATE UNIQUE INDEX __drizzle_migrations_hash_idx ON (hash); INSERT one row per migration (26 total) with computed sha256. Verified: SELECT count(*) FROM drizzle.__drizzle_migrations → 26. WROTE drizzle/meta/_journal.json: 26 entries, monotonic 'when' timestamps starting 2026-01-01. Future 'drizzle-kit generate' calls will append entries on top; 'drizzle-kit migrate' will see existing entries' hashes match the ledger and skip them, applying only new migrations. GOING FORWARD: Schema changes: edit src/db/schema/*.ts → drizzle-kit generate → review the new drizzle/NNNN_*.sql → drizzle-kit migrate to apply. No more direct 'drizzle-kit push' to prod (kept available for dev DBs). No more manual 'psql -f drizzle/NNNN_*.sql' shenanigans. Tech debt this resolves: - Drift detection: works now. drizzle-kit migrate exits 0 if and only if the ledger matches the file hashes. - CI: future deploy pipelines can run drizzle-kit migrate as a step and have confidence in the result. - Team scaling: someone other than me can apply migrations without 'how does this DB actually get migrated' tribal knowledge. Verified: tsc clean, 19/19 control-presenter tests pass. Prod DB unaffected outside the new drizzle schema.
189 lines
6.7 KiB
TypeScript
189 lines
6.7 KiB
TypeScript
/**
|
|
* 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<void> {
|
|
// 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();
|