Dough Git

clove/pkviewer

api/src/db/index.ts

back to api/src/db

/* api/src/db/index.ts */
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { DatabaseSync, type SQLInputValue, type StatementSync } from "node:sqlite";

/** Values a query may bind. Booleans and undefined are normalised before binding. */
export type Binding = string | number | bigint | boolean | null | undefined | Uint8Array;

export type RunResult = {
  changes: number;
  lastInsertRowid: number | bigint;
};

/**
 * A prepared statement, shaped like bun:sqlite's so call sites are unchanged.
 *
 * `get` returns null on no row (node:sqlite returns undefined), and rows are
 * copied to plain objects (node:sqlite returns null-prototype objects).
 */
export class Statement<Row = unknown, Params extends Binding[] = Binding[]> {
  readonly #statement: StatementSync;

  constructor(statement: StatementSync) {
    this.#statement = statement;
  }

  get(...params: Params): Row | null {
    const row = this.#statement.get(...bind(params));
    return row === undefined ? null : ({ ...row } as Row);
  }

  all(...params: Params): Row[] {
    return this.#statement.all(...bind(params)).map((row) => ({ ...row }) as Row);
  }

  run(...params: Params): RunResult {
    const result = this.#statement.run(...bind(params));
    return {
      changes: Number(result.changes),
      lastInsertRowid: result.lastInsertRowid,
    };
  }
}

function bind(params: Binding[]): SQLInputValue[] {
  return params.map((value) => {
    if (value === undefined) return null;
    if (value === true) return 1;
    if (value === false) return 0;
    return value;
  });
}

/** A SQLite connection. Statements are cached per SQL string, as bun:sqlite's query() did. */
export class Db {
  readonly #database: DatabaseSync;
  readonly #statements = new Map<string, StatementSync>();

  constructor(path: string) {
    this.#database = new DatabaseSync(path);
  }

  query<Row = unknown, Params extends Binding[] = Binding[]>(sql: string): Statement<Row, Params> {
    let statement = this.#statements.get(sql);
    if (!statement) {
      statement = this.#database.prepare(sql);
      this.#statements.set(sql, statement);
    }
    return new Statement<Row, Params>(statement);
  }

  exec(sql: string): void {
    this.#database.exec(sql);
  }

  close(): void {
    this.#statements.clear();
    this.#database.close();
  }
}

/**
 * Opens a SQLite connection with the pragmas this application depends on.
 *
 * `foreign_keys` is off by default in SQLite and is per-connection, so it must
 * be set here or every ON DELETE CASCADE in the schema silently does nothing.
 */
export function openDb(path: string): Db {
  if (path !== ":memory:") {
    mkdirSync(dirname(path), { recursive: true });
  }
  const db = new Db(path);

  db.exec("PRAGMA journal_mode = WAL");
  db.exec("PRAGMA foreign_keys = ON");
  db.exec("PRAGMA busy_timeout = 5000");
  db.exec("PRAGMA synchronous = NORMAL");

  return db;
}

/**
 * Runs `fn` inside an IMMEDIATE transaction.
 *
 * Deferred transactions take a read lock first and try to upgrade on the first
 * write; if another writer holds the lock that upgrade fails with SQLITE_BUSY
 * *after* the work is done, and busy_timeout does not help because retrying
 * would deadlock. Taking the write lock upfront makes the transaction wait
 * instead. Every transaction that may write must use this.
 */
export function writeTx<T>(db: Db, fn: (db: Db) => T): T {
  db.exec("BEGIN IMMEDIATE");
  try {
    const result = fn(db);
    db.exec("COMMIT");
    return result;
  } catch (err) {
    try {
      db.exec("ROLLBACK");
    } catch {
      // A failed rollback must not mask the original error.
    }
    throw err;
  }
}

/** Read-only transaction, for multi-statement reads needing a consistent view. */
export function readTx<T>(db: Db, fn: (db: Db) => T): T {
  db.exec("BEGIN DEFERRED");
  try {
    const result = fn(db);
    db.exec("COMMIT");
    return result;
  } catch (err) {
    try {
      db.exec("ROLLBACK");
    } catch {
      /* see above */
    }
    throw err;
  }
}

/** Current time as integer Unix milliseconds. Injected so tests can control it. */
export type Clock = () => number;
export const systemClock: Clock = () => Date.now();