import { mkdir, readFile, readdir } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { DatabaseSync } from "node:sqlite"; const root = process.cwd(); const configuredPath = process.env.LINKEDIN_SQLITE_PATH?.trim(); if (!configuredPath) { throw new Error("LINKEDIN_SQLITE_PATH is required for local SQLite migrations."); } const deterministicEpoch = process.env.WEBSITEBENCH_DETERMINISTIC_EPOCH_SECONDS?.trim(); if (deterministicEpoch && !/^\d+$/.test(deterministicEpoch)) { throw new Error("WEBSITEBENCH_DETERMINISTIC_EPOCH_SECONDS must be unsigned epoch seconds."); } const databaseNow = deterministicEpoch ?? "unixepoch()"; const databasePath = resolve(root, configuredPath); await mkdir(dirname(databasePath), { recursive: true }); const database = new DatabaseSync(databasePath); try { database.exec(` PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; CREATE TABLE IF NOT EXISTS __drizzle_migrations ( name TEXT PRIMARY KEY NOT NULL, applied_at INTEGER NOT NULL DEFAULT (${databaseNow}) ); `); const applied = database.prepare("SELECT 1 FROM __drizzle_migrations WHERE name = ?"); const record = database.prepare("INSERT INTO __drizzle_migrations (name) VALUES (?)"); const migrations = (await readdir(join(root, "drizzle"))).filter((file) => file.endsWith(".sql")).sort(); let appliedCount = 0; for (const migration of migrations) { if (applied.get(migration)) continue; const source = await readFile(join(root, "drizzle", migration), "utf8"); const executableSource = deterministicEpoch ? source.replaceAll("unixepoch()", deterministicEpoch) : source; database.exec("BEGIN IMMEDIATE"); try { for (const statement of executableSource.split("--> statement-breakpoint")) { if (statement.trim()) database.exec(statement); } record.run(migration); database.exec("COMMIT"); appliedCount += 1; } catch (error) { database.exec("ROLLBACK"); throw error; } } console.log(`Applied ${appliedCount} of ${migrations.length} LinkedIn SQLite migrations.`); } finally { database.close(); }