withWritableStore

tcmts.cli.data_pages.withWritableStore · #sbx4ohma · term · runs on the server

uses node:path

Open the app data store to write (made, as the server makes it, if there's none yet), for fn, closed after.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";

export function withWritableStore<T>(cb: Codebase, fn: (db: DatabaseSync) => T): T {
  const dir = path.join(cb.lay.tcmDir, "data");
  fs.mkdirSync(dir, { recursive: true });
  const db = new DatabaseSync(path.join(dir, "store.sqlite"));
  try {
    db.exec(`PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;
      CREATE TABLE IF NOT EXISTS rows (tbl TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, schema_hash TEXT NOT NULL, updated INTEGER NOT NULL, PRIMARY KEY (tbl, id));
      CREATE TABLE IF NOT EXISTS schemas (tbl TEXT NOT NULL, hash TEXT NOT NULL, schema TEXT NOT NULL, first_seen INTEGER NOT NULL, PRIMARY KEY (tbl, hash));
      CREATE INDEX IF NOT EXISTS rows_by_schema ON rows (tbl, schema_hash);`);
    return fn(db);
  } finally {
    db.close();
  }
}

uses

used by