Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

1.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { readFileSync } from "node:fs";
import { join } from "node:path";

/**
 * Column names per table, read out of the GENERATED `@carbon/database` types
 * (`packages/database/src/types.ts` `Row:` blocks). That file is regenerated by
 * `pnpm run generate:types` after every migration, so it is the freshest
 * machine-readable schema in the repo — fresher than
 * `packages/jobs/manifests/schema.json`, which only regenerates when the backup
 * check runs.
 *
 * I/O lives here rather than in a check, so `scan` stays pure: the caller loads
 * the map once and closes a check over it (the same shape as
 * `noAuthzDdlInMigrations(loadManagedFunctions(root))`).
 */
export function loadDbTableColumns(root: string): Map<string, Set<string>> {
  const contents = readFileSync(
    join(root, "packages/database/src/types.ts"),
    "utf-8"
  );
  const out = new Map<string, Set<string>>();
  // Both `Tables` and `Views` are shaped the same; a view is a legitimate read
  // target and never a write one, so including it costs nothing and keeps the
  // map a plain "what does this relation have" lookup.
  for (const m of contents.matchAll(
    /\n {6}(\w+): \{\n {8}Row: \{\n([\s\S]*?)\n {8}\}\n/g
  )) {
    const [, table, block] = m;
    if (!table || !block) continue;
    const fields = new Set(
      [...block.matchAll(/^ {10}(\w+)\??:/gm)].map((f) => f[1] as string)
    );
    if (fields.size > 0 && !out.has(table)) out.set(table, fields);
  }
  return out;
}