mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-25 00:41:04 +01:00
108 lines
5.5 KiB
TypeScript
108 lines
5.5 KiB
TypeScript
// Writes src/db/types.ts, the table types Kysely queries are checked against, from a freshly migrated SQLite database
|
|
// (src/schema.sql plus the migrations in src/db.ts, read back with PRAGMA table_info). `--check` exits 1 when the
|
|
// committed file is stale.
|
|
//
|
|
// Type mapping: what both engines return for the column (src/db/postgres.ts parses int8, numeric and bool into
|
|
// node:sqlite's shapes): INTEGER and REAL → number, TEXT → string (JSON stays text), BLOB → Uint8Array. A column with no
|
|
// NOT NULL is `| null`; an INTEGER PRIMARY KEY of a rowid table or a column with a default is `Generated<>`, so inserts may
|
|
// leave it out. Virtual tables (full-text search) are left out: queries reach them only through src/db/kx.ts.
|
|
//
|
|
// `COLUMNS` lists each table's and view's columns in table order, without rowid or dropped columns, for `kx.cols`.
|
|
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { connect, DROPPED_COLUMNS } from "../src/db.ts";
|
|
import { TYPE_OVERRIDES } from "../src/db/pg-schema.ts";
|
|
|
|
type Col = { name: string; type: string; notnull: number; dflt_value: string | null; pk: number };
|
|
type Rel = { name: string; type: "table" | "view"; sql: string };
|
|
|
|
// Values written as bytes into TEXT columns by newer code; older rows hold text (src/agents/runs.ts unpackText reads both).
|
|
const OVERRIDE_TS: Record<string, string> = { bytea: "string | Uint8Array" };
|
|
|
|
/** The TypeScript type of a declared SQLite column type, by SQLite's affinity rules. */
|
|
function tsType(decl: string, where: string): string {
|
|
const t = decl.toUpperCase();
|
|
if (t.includes("INT")) return "number";
|
|
if (/CHAR|CLOB|TEXT/.test(t)) return "string";
|
|
if (t.includes("BLOB")) return "Uint8Array";
|
|
if (/REAL|FLOA|DOUB/.test(t)) return "number";
|
|
// An expression column of a view has no declared type.
|
|
if (t === "") return "unknown";
|
|
if (t.includes("NUMERIC")) return "number";
|
|
throw new Error(`gen-db-types: no type mapping for ${decl} (${where})`);
|
|
}
|
|
|
|
const pascal = (s: string): string => s.split("_").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
|
|
const key = (s: string): string => (/^[A-Za-z_$][\w$]*$/.test(s) ? s : JSON.stringify(s));
|
|
|
|
export function renderDbTypes(): string {
|
|
const dir = mkdtempSync(join(tmpdir(), "gen-db-types-"));
|
|
try {
|
|
const db = connect(join(dir, "schema.db"));
|
|
try {
|
|
const rels = db.prepare("SELECT name, type, sql FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name").all() as Rel[];
|
|
const virtual = rels.filter((r) => /^CREATE VIRTUAL TABLE/i.test(r.sql)).map((r) => r.name);
|
|
const shadow = (n: string) => virtual.some((v) => ["data", "idx", "docsize", "config", "content"].some((s) => n === `${v}_${s}`));
|
|
const dropped = new Set(DROPPED_COLUMNS.map(([t, c]) => `${t}.${c}`));
|
|
const out: string[] = [
|
|
"// Generated by scripts/gen-db-types.ts from a freshly migrated SQLite database: `pnpm db-types` rewrites it, `pnpm check` fails when it is stale.",
|
|
"// Every table is also keyed as `main.<table>`, for code that reads past the scoped views or writes a shadowed table (src/db/scoped.ts).",
|
|
'import type { Generated } from "kysely";',
|
|
"",
|
|
];
|
|
const names: Rel[] = [];
|
|
const columns: string[] = [];
|
|
for (const r of rels) {
|
|
if (virtual.includes(r.name) || shadow(r.name)) continue;
|
|
const cols = db.prepare(`PRAGMA table_info(${JSON.stringify(r.name)})`).all() as Col[];
|
|
const pks = cols.filter((c) => c.pk > 0);
|
|
const rowidTable = r.type === "table" && !/WITHOUT\s+ROWID\s*;?\s*$/i.test(r.sql);
|
|
out.push(`export interface ${pascal(r.name)} {`);
|
|
const kept: string[] = [];
|
|
for (const c of cols) {
|
|
const where = `${r.name}.${c.name}`;
|
|
if (dropped.has(where)) continue;
|
|
kept.push(JSON.stringify(c.name));
|
|
const override = TYPE_OVERRIDES[where];
|
|
let t = override ? OVERRIDE_TS[override] ?? tsType(override, where) : tsType(c.type, where);
|
|
// Postgres makes every primary key column NOT NULL; SQLite allows NULL only in a non-INTEGER key of a rowid table.
|
|
if (!c.notnull && !c.pk && t !== "unknown") t += " | null";
|
|
const intKey = rowidTable && pks.length === 1 && c.pk === 1 && c.type.toUpperCase() === "INTEGER";
|
|
if (intKey || c.dflt_value !== null) t = `Generated<${t}>`;
|
|
out.push(` ${key(c.name)}: ${t};`);
|
|
}
|
|
out.push("}", "");
|
|
names.push(r);
|
|
columns.push(` ${key(r.name)}: [${kept.join(", ")}],`);
|
|
}
|
|
out.push("export interface DB {");
|
|
for (const r of names) out.push(` ${key(r.name)}: ${pascal(r.name)};`);
|
|
for (const r of names) out.push(` ${key(`main.${r.name}`)}: ${pascal(r.name)};`);
|
|
out.push("}", "");
|
|
out.push("/** Each table's and view's columns in table order (no rowid), for selecting a whole row: `kx.cols`. */");
|
|
out.push("export const COLUMNS = {", ...columns, "} as const;", "");
|
|
return out.join("\n");
|
|
} finally {
|
|
db.close();
|
|
}
|
|
} finally {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
const file = new URL("../src/db/types.ts", import.meta.url);
|
|
const want = renderDbTypes();
|
|
if (process.argv.includes("--check")) {
|
|
let have = "";
|
|
try {
|
|
have = readFileSync(file, "utf8");
|
|
} catch {
|
|
// missing counts as stale
|
|
}
|
|
if (have !== want) {
|
|
console.error("src/db/types.ts is stale: run `pnpm db-types`");
|
|
process.exit(1);
|
|
}
|
|
} else writeFileSync(file, want);
|