import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres"; import { Pool } from "pg"; import * as core from "./schema"; import * as workspace from "./schema-workspace"; const schema = { ...core, ...workspace }; export type Db = NodePgDatabase; declare global { var __polyllmPool: Pool | undefined; var __polyllmDb: Db | undefined; } function createPool(): Pool { const connectionString = process.env.DATABASE_URL ?? "postgres://localhost:5432/polyllm"; return new Pool({ connectionString, max: Number(process.env.DB_POOL_MAX ?? 10), idleTimeoutMillis: 30_000, connectionTimeoutMillis: 10_000, application_name: "polyllm", }); } /** Process-wide singleton (survives Next.js HMR in dev). */ export function getDb(): Db { if (!globalThis.__polyllmDb) { globalThis.__polyllmPool = globalThis.__polyllmPool ?? createPool(); globalThis.__polyllmDb = drizzle(globalThis.__polyllmPool, { schema }); } return globalThis.__polyllmDb; } export async function closeDb() { await globalThis.__polyllmPool?.end(); globalThis.__polyllmPool = undefined; globalThis.__polyllmDb = undefined; } export async function pingDb(): Promise { try { const pool = globalThis.__polyllmPool ?? (getDb(), globalThis.__polyllmPool!); await pool.query("select 1"); return true; } catch { return false; } } export * from "./schema"; export * from "./schema-workspace";