Skip to content
refs
52 lines · 2.3 KBRaw
1import { readdirSync, readFileSync } from "node:fs";
2import { DatabaseSync } from "node:sqlite";
3
4const migrations = new URL("../../../migrations/", import.meta.url);
5
6interface Shimmed {
7 sql: string;
8 params: unknown[];
9}
10
11function execute(sqlite: DatabaseSync, { sql, params }: Shimmed) {
12 const statement = sqlite.prepare(sql);
13 if (!statement.columns().length) {
14 const result = statement.run(...(params as never[]));
15 return { results: [], meta: { last_row_id: Number(result.lastInsertRowid), changes: Number(result.changes) } };
16 }
17 const results = statement.all(...(params as never[]));
18 const changes = Number(sqlite.prepare("SELECT changes() AS n").get()!.n);
19 return { results, meta: { last_row_id: Number(sqlite.prepare("SELECT last_insert_rowid() AS id").get()!.id), changes } };
20}
21
22/** A D1 binding over `node:sqlite`, enough for the statements the backend builds. `seen` collects every statement prepared through it. */
23export function d1(sqlite: DatabaseSync, seen: string[] = []): D1Database {
24 const prepare = (sql: string, params: unknown[] = []): D1PreparedStatement => {
25 seen.push(sql);
26 return {
27 sql,
28 params,
29 bind: (...values: unknown[]) => prepare(sql, values),
30 all: async () => ({ results: sqlite.prepare(sql).all(...(params as never[])) }),
31 first: async (column?: string) => {
32 const row = (sqlite.prepare(sql).get(...(params as never[])) ?? null) as Record<string, unknown> | null;
33 return column && row ? row[column] : row;
34 },
35 run: async () => execute(sqlite, { sql, params }),
36 } as unknown as D1PreparedStatement;
37 };
38 const batch = async (statements: D1PreparedStatement[]) => statements.map((statement) => execute(sqlite, statement as unknown as Shimmed));
39 return { prepare, batch } as unknown as D1Database;
40}
41
42/** An in-memory database with every migration applied, or only those before `before`. */
43export function migrated(before = "~"): DatabaseSync {
44 const sqlite = new DatabaseSync(":memory:");
45 for (const file of readdirSync(migrations).sort()) if (file < before) sqlite.exec(readFileSync(new URL(file, migrations), "utf8"));
46 sqlite.exec("PRAGMA foreign_keys = OFF");
47 return sqlite;
48}
49
50export function migration(file: string): string {
51 return readFileSync(new URL(file, migrations), "utf8");
52}