File size: 3,465 Bytes
9d4a3b0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | import { DatabaseSync, type SQLInputValue, type StatementSync } from "node:sqlite";
type BoundValue = ArrayBuffer | ArrayBufferView | bigint | boolean | null | number | string;
const databases = new Map<string, D1Database>();
function sqliteValue(value: BoundValue): SQLInputValue {
if (typeof value === "boolean") return value ? 1 : 0;
if (value instanceof ArrayBuffer) return new Uint8Array(value);
if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
return value;
}
function meta(duration: number, changes: bigint | number = 0, lastRowId: bigint | number = 0) {
const numericChanges = Number(changes);
return {
changed_db: numericChanges > 0,
changes: numericChanges,
duration,
last_row_id: Number(lastRowId),
rows_read: 0,
rows_written: numericChanges,
size_after: 0,
};
}
class NodeD1Statement {
constructor(
private readonly statement: StatementSync,
private readonly values: BoundValue[] = [],
) {}
bind(...values: BoundValue[]) {
return new NodeD1Statement(this.statement, values);
}
private parameters() {
return this.values.map(sqliteValue);
}
private rows() {
return this.statement.all(...this.parameters()) as Record<string, unknown>[];
}
async first(column?: string) {
const row = this.rows()[0] || null;
if (!row || column === undefined) return row;
if (!(column in row)) throw new Error(`Column ${column} is unavailable.`);
return row[column];
}
async run() {
const started = performance.now();
const result = this.statement.run(...this.parameters());
return { success: true, results: [], meta: meta(performance.now() - started, result.changes, result.lastInsertRowid) };
}
async all() {
const started = performance.now();
const results = this.rows();
return { success: true, results, meta: meta(performance.now() - started) };
}
async raw(options?: { columnNames?: boolean }) {
const columns = this.statement.columns().map((column) => column.name);
this.statement.setReturnArrays(true);
let rows: unknown[][];
try {
rows = this.statement.all(...this.parameters()) as unknown as unknown[][];
} finally {
this.statement.setReturnArrays(false);
}
return options?.columnNames ? [columns, ...rows] : rows;
}
}
class NodeD1Database {
private readonly database: DatabaseSync;
constructor(path: string) {
this.database = new DatabaseSync(path);
this.database.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
}
prepare(query: string) {
return new NodeD1Statement(this.database.prepare(query));
}
async batch(statements: NodeD1Statement[]) {
this.database.exec("BEGIN IMMEDIATE");
try {
const results = [];
for (const statement of statements) results.push(await statement.all());
this.database.exec("COMMIT");
return results;
} catch (error) {
this.database.exec("ROLLBACK");
throw error;
}
}
async exec(query: string) {
const started = performance.now();
this.database.exec(query);
return { count: 1, duration: performance.now() - started };
}
}
export function getNodeD1Database(path: string) {
let database = databases.get(path);
if (!database) {
database = new NodeD1Database(path) as unknown as D1Database;
databases.set(path, database);
}
return database;
}
|