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.3 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.

/**
 * Database client singleton for server-side usage.
 * Similar to Prisma client singleton. from https://www.prisma.io/docs/guides/react-router-7
 * Polluting the global namespace like this is usually discouraged, but it's okay as we're just caching connections during development.
 * In production, this code path is not hit multiple times as ESM modules are only singletons by default.
 */
import { getPostgresClient, getProcessPool } from "@carbon/database/client";
import { queryLog, traceConnectionWaits } from "@carbon/logger/tracing.server";
import { PostgresDriver } from "kysely";

const init = () => {
  const pool = traceConnectionWaits(getProcessPool());
  // We use the PostgresDriver from Kysely here as this code only runs in Node environment
  return getPostgresClient(pool, PostgresDriver, queryLog);
};

type ClientSingleton = ReturnType<typeof init>;

const globalForKysely = globalThis as unknown as {
  kysely: ClientSingleton | undefined;
};

const database = globalForKysely.kysely ?? init();

if (process.env.NODE_ENV !== "production") globalForKysely.kysely = database;

export const getDatabaseClient = () => database;