import "./_env"; import { adminSql } from "./_admin-sql"; import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { createHash } from "node:crypto"; const sql = adminSql(); const dir = join(import.meta.dirname, "..", "drizzle"); const files = readdirSync(dir).filter((f) => /^\d{4}_.*\.sql$/.test(f)).sort(); await sql`CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())`; const applied = new Map((await sql`SELECT name, checksum FROM schema_migrations`).map((r) => [r.name as string, r.checksum as string])); let n = 0; for (const f of files) { const body = readFileSync(join(dir, f), "utf8"); const sum = createHash("sha256").update(body).digest("hex"); if (applied.has(f)) { if (applied.get(f) !== sum) console.warn(`! ${f} changed after being applied (checksum mismatch)`); continue; } console.log(`→ applying ${f}`); await sql.begin(async (tx) => { await tx.unsafe(body); await tx`INSERT INTO schema_migrations (name, checksum) VALUES (${f}, ${sum})`; }); n++; } console.log(n ? `${n} migration(s) applied` : "schema up to date"); await sql.end();