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.

926 B
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 { maybeOne, quote } from "../sql.ts";
import type { Ctx } from "../types.ts";

/**
 * Cached in ctx.refs.misc — never module scope, which would leak across the
 * drift check's four companies.
 */
export async function bootstrapIdByName(
  ctx: Ctx,
  table: string,
  name: string
): Promise<string> {
  const key = `${table}:${name}`;
  const cached = ctx.refs.misc[key];
  if (cached) return cached;
  const row = await maybeOne<{ id: string }>(
    ctx.client,
    `SELECT id FROM ${quote(table)} WHERE "companyId" = $1 AND name = $2`,
    [ctx.companyId, name]
  );
  if (!row) {
    throw new Error(`Seed: no ${table} named "${name}"`);
  }
  ctx.refs.misc[key] = row.id;
  return row.id;
}