import { readdirSync, readFileSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; const migrations = new URL("../../../migrations/", import.meta.url); interface Shimmed { sql: string; params: unknown[]; } function execute(sqlite: DatabaseSync, { sql, params }: Shimmed) { const statement = sqlite.prepare(sql); if (!statement.columns().length) { const result = statement.run(...(params as never[])); return { results: [], meta: { last_row_id: Number(result.lastInsertRowid), changes: Number(result.changes) } }; } const results = statement.all(...(params as never[])); const changes = Number(sqlite.prepare("SELECT changes() AS n").get()!.n); return { results, meta: { last_row_id: Number(sqlite.prepare("SELECT last_insert_rowid() AS id").get()!.id), changes } }; } /** A D1 binding over `node:sqlite`, enough for the statements the backend builds. `seen` collects every statement prepared through it. */ export function d1(sqlite: DatabaseSync, seen: string[] = []): D1Database { const prepare = (sql: string, params: unknown[] = []): D1PreparedStatement => { seen.push(sql); return { sql, params, bind: (...values: unknown[]) => prepare(sql, values), all: async () => ({ results: sqlite.prepare(sql).all(...(params as never[])) }), first: async (column?: string) => { const row = (sqlite.prepare(sql).get(...(params as never[])) ?? null) as Record | null; return column && row ? row[column] : row; }, run: async () => execute(sqlite, { sql, params }), } as unknown as D1PreparedStatement; }; const batch = async (statements: D1PreparedStatement[]) => statements.map((statement) => execute(sqlite, statement as unknown as Shimmed)); return { prepare, batch } as unknown as D1Database; } /** An in-memory database with every migration applied, or only those before `before`. */ export function migrated(before = "~"): DatabaseSync { const sqlite = new DatabaseSync(":memory:"); for (const file of readdirSync(migrations).sort()) if (file < before) sqlite.exec(readFileSync(new URL(file, migrations), "utf8")); sqlite.exec("PRAGMA foreign_keys = OFF"); return sqlite; } export function migration(file: string): string { return readFileSync(new URL(file, migrations), "utf8"); }