Spaces:
Paused
Paused
File size: 7,547 Bytes
f55c62a | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | import Database from 'better-sqlite3';
import type {
DbDriver,
ExecResult,
IntervalUnit,
Row,
SqlInput,
} from './types.js';
import { SqlFragment } from '../sql.js';
import { DbError, classifySqliteError } from '../errors.js';
/**
* SQLite `datetime('now', '-N units')` expression. Both `datetime` and
* the modifier string accept the plural unit names we use.
*/
function sqliteIntervalAgo(amount: number, unit: IntervalUnit): SqlFragment {
return new SqlFragment(`datetime('now', '-' || ? || ' ${unit}')`, [amount]);
}
function normalize(
s: SqlInput,
params?: readonly unknown[]
): { text: string; params: unknown[] } {
if (s instanceof SqlFragment) return { text: s.text, params: [...s.params] };
return { text: s, params: params ? [...params] : [] };
}
/**
* Coerce JS values into types better-sqlite3 accepts.
* - undefined → null
* - boolean → 0 / 1
*/
function coerce(params: unknown[]): unknown[] {
return params.map((p) => {
if (p === undefined) return null;
if (typeof p === 'boolean') return p ? 1 : 0;
return p;
});
}
/**
* Serializes async tasks. Used to guard transactions — better-sqlite3's
* single shared connection means a transaction must own the connection
* for its entire lifetime, which we enforce here.
*/
class Mutex {
private chain: Promise<unknown> = Promise.resolve();
run<T>(fn: () => Promise<T> | T): Promise<T> {
const prev = this.chain;
const next = prev.then(() => fn());
// swallow rejections from the chain so one failure doesn't poison subsequent tasks
this.chain = next.then(
() => undefined,
() => undefined
);
return next;
}
}
export class SqliteDriver implements DbDriver {
readonly dialect = 'sqlite' as const;
private readonly db: Database.Database;
private readonly mutex = new Mutex();
constructor(filename: string) {
this.db = new Database(filename);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db.pragma('busy_timeout = 5000');
this.db.pragma('foreign_keys = ON');
}
// --- sync core; all public async methods funnel through these via the mutex.
private execSync(text: string, params: unknown[]): ExecResult {
try {
const info = this.db.prepare(text).run(...coerce(params));
return { rowCount: Number(info.changes ?? 0) };
} catch (err) {
throw new DbError(classifySqliteError(err), (err as Error).message, err);
}
}
private querySync<T>(text: string, params: unknown[]): T[] {
try {
const stmt = this.db.prepare(text);
// statements that don't return rows (e.g. DDL) blow up on .all() —
// detect and switch to .run() in that case so a misclassified query
// still works.
if (!stmt.reader) {
stmt.run(...coerce(params));
return [];
}
return stmt.all(...coerce(params)) as T[];
} catch (err) {
throw new DbError(classifySqliteError(err), (err as Error).message, err);
}
}
// --- public
async exec(s: SqlInput, params?: readonly unknown[]): Promise<ExecResult> {
const { text, params: p } = normalize(s, params);
return this.mutex.run(() => this.execSync(text, p));
}
async query<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T[]> {
const { text, params: p } = normalize(s, params);
return this.mutex.run(() => this.querySync<T>(text, p));
}
async one<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T> {
const rows = await this.query<T>(s, params);
if (!rows.length) {
throw new DbError('not-found', 'Expected 1 row, got 0');
}
return rows[0];
}
async maybeOne<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T | null> {
const rows = await this.query<T>(s, params);
return rows[0] ?? null;
}
async count(s: SqlInput, params?: readonly unknown[]): Promise<number> {
const rows = await this.query<Row>(s, params);
if (!rows.length) return 0;
const first = rows[0];
const v =
(first.count as unknown) ??
(first.c as unknown) ??
Object.values(first)[0];
return Number(v ?? 0);
}
async tx<T>(fn: (tx: DbDriver) => Promise<T>): Promise<T> {
return this.mutex.run(async () => {
this.db.exec('BEGIN');
const txDriver = new SqliteTxDriver(this.db);
try {
const r = await fn(txDriver);
this.db.exec('COMMIT');
return r;
} catch (e) {
try {
this.db.exec('ROLLBACK');
} catch {
// rollback failure is informational; the original error is what matters
}
throw e;
}
});
}
intervalAgo(amount: number, unit: IntervalUnit): SqlFragment {
return sqliteIntervalAgo(amount, unit);
}
async close(): Promise<void> {
this.db.close();
}
async ping(): Promise<void> {
this.db.prepare('SELECT 1').get();
}
}
/**
* Transaction-scoped driver. Shares the same native handle as the parent;
* bypasses the parent's mutex because the parent already holds it for the
* duration of `tx()`.
*/
class SqliteTxDriver implements DbDriver {
readonly dialect = 'sqlite' as const;
constructor(private readonly db: Database.Database) {}
private execSync(text: string, params: unknown[]): ExecResult {
try {
const info = this.db.prepare(text).run(...coerce(params));
return { rowCount: Number(info.changes ?? 0) };
} catch (err) {
throw new DbError(classifySqliteError(err), (err as Error).message, err);
}
}
private querySync<T>(text: string, params: unknown[]): T[] {
try {
const stmt = this.db.prepare(text);
if (!stmt.reader) {
stmt.run(...coerce(params));
return [];
}
return stmt.all(...coerce(params)) as T[];
} catch (err) {
throw new DbError(classifySqliteError(err), (err as Error).message, err);
}
}
async exec(s: SqlInput, params?: readonly unknown[]): Promise<ExecResult> {
const { text, params: p } = normalize(s, params);
return this.execSync(text, p);
}
async query<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T[]> {
const { text, params: p } = normalize(s, params);
return this.querySync<T>(text, p);
}
async one<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T> {
const rows = await this.query<T>(s, params);
if (!rows.length) {
throw new DbError('not-found', 'Expected 1 row, got 0');
}
return rows[0];
}
async maybeOne<T extends Row = Row>(
s: SqlInput,
params?: readonly unknown[]
): Promise<T | null> {
const rows = await this.query<T>(s, params);
return rows[0] ?? null;
}
async count(s: SqlInput, params?: readonly unknown[]): Promise<number> {
const rows = await this.query<Row>(s, params);
if (!rows.length) return 0;
const first = rows[0];
const v =
(first.count as unknown) ??
(first.c as unknown) ??
Object.values(first)[0];
return Number(v ?? 0);
}
tx<T>(_fn: (tx: DbDriver) => Promise<T>): Promise<T> {
return Promise.reject(new Error('Nested transactions are not supported'));
}
intervalAgo(amount: number, unit: IntervalUnit): SqlFragment {
return sqliteIntervalAgo(amount, unit);
}
async close(): Promise<void> {
// owned by parent driver
}
async ping(): Promise<void> {
this.db.prepare('SELECT 1').get();
}
}
|