Files
Reactive-Resume/packages/db/src/client.ts
T
Amruth Pillai 8de15822fb chore(db): delete tautological schema-mirror tests, collapse db singleton
- Delete 4 test files (auth/resume/agent schema mirrors + relations type check)
  that re-assert Drizzle table/column names copied verbatim from the schema files.
- Collapse makeDrizzleClient() + createDatabase() into a two-line module-level
  singleton; preserves globalThis.__drizzle caching behaviour.

Claude-Session: https://claude.ai/code/session_012Bnvt1MghwHj4qQRxuQUGa
2026-07-04 19:36:22 +02:00

36 lines
1.4 KiB
TypeScript

import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import { env } from "@reactive-resume/env/server";
import { relations } from "./relations";
declare global {
var __pool: Pool | undefined;
var __drizzle: NodePgDatabase<typeof relations> | undefined;
}
export function getPool() {
if (!globalThis.__pool) {
const pool = new Pool({ connectionString: env.DATABASE_URL });
const logPgError = (error: unknown) => {
console.error("[db] postgres connection error:", error);
};
// A Postgres connection can drop at any time — e.g. a serverless Postgres such as Neon
// terminating the connection (code 57P01). `pg` surfaces this as an 'error' event, and
// without a listener node re-throws it as an unhandled 'error' that crashes the process.
// Idle clients emit on the pool; a client that is connecting or checked out emits on the
// client itself, so we must listen on both. The pool then discards the dead client and
// opens a fresh one on the next query.
pool.on("error", logPgError);
pool.on("connect", (client) => {
client.on("error", logPgError);
});
globalThis.__pool = pool;
}
return globalThis.__pool;
}
// ponytail: two private fns collapsed; getPool() is already a singleton, global cache preserved
globalThis.__drizzle ??= drizzle({ client: getPool(), relations });
export const db = globalThis.__drizzle;