data

tcmts.cli.main.data · #xn7wp23w · term · runs on the server

uses node:fs

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { decode } from "#codebase/tcmts/cli/codec";
import { storeFile } from "#codebase/tcmts/cli/main";
import { bold, dim, yellow } from "#codebase/tcmts/cli/style";
import fs from "node:fs";
import { DatabaseSync } from "node:sqlite";
import { inspect } from "node:util";

export function data(cb: Codebase, table?: string, limit = 20) {
  if (!fs.existsSync(storeFile(cb)))
    return console.log(
      dim('no tables yet (table<Row>("name") from the server library: tcm lib add tcm server)'),
    );
  const db = new DatabaseSync(storeFile(cb), { readOnly: true });
  try {
    if (!table) {
      const rows = db
        .prepare(
          "SELECT tbl, count(*) AS n, count(DISTINCT schema_hash) AS versions FROM rows GROUP BY tbl ORDER BY tbl",
        )
        .all() as { tbl: string; n: number; versions: number }[];
      if (!rows.length) return console.log(dim("no rows stored yet"));
      for (const r of rows)
        console.log(
          `${bold(r.tbl.padEnd(20))} ${String(r.n).padStart(6)} row(s)${r.versions > 1 ? yellow(`  written under ${r.versions} row types (tcm data migrate ${r.tbl} upgrades them all)`) : ""}`,
        );
      return;
    }
    const rows = db
      .prepare("SELECT id, data, schema_hash FROM rows WHERE tbl = ? ORDER BY updated DESC LIMIT ?")
      .all(table, limit) as { id: string; data: string; schema_hash: string }[];
    if (!rows.length) return console.log(dim(`no rows in "${table}"`));
    for (const r of rows)
      console.log(
        `${dim(r.id)}  ${inspect(decode(r.data), { colors: true, breakLength: 120, depth: 4 })}  ${dim(`#${r.schema_hash.slice(0, 8)}`)}`,
      );
  } finally {
    db.close();
  }
}

uses

used by