SPB Git

spb/polyllm

Public
1.3 KB · 49 lines typescript
1import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";2import { Pool } from "pg";3import * as schema from "./schema";45export type Db = NodePgDatabase<typeof schema>;67declare global {8  var __polyllmPool: Pool | undefined;9  var __polyllmDb: Db | undefined;10}1112function createPool(): Pool {13  const connectionString = process.env.DATABASE_URL ?? "postgres://localhost:5432/polyllm";14  return new Pool({15    connectionString,16    max: Number(process.env.DB_POOL_MAX ?? 10),17    idleTimeoutMillis: 30_000,18    connectionTimeoutMillis: 10_000,19    application_name: "polyllm",20  });21}2223/** Process-wide singleton (survives Next.js HMR in dev). */24export function getDb(): Db {25  if (!globalThis.__polyllmDb) {26    globalThis.__polyllmPool = globalThis.__polyllmPool ?? createPool();27    globalThis.__polyllmDb = drizzle(globalThis.__polyllmPool, { schema });28  }29  return globalThis.__polyllmDb;30}3132export async function closeDb() {33  await globalThis.__polyllmPool?.end();34  globalThis.__polyllmPool = undefined;35  globalThis.__polyllmDb = undefined;36}3738export async function pingDb(): Promise<boolean> {39  try {40    const pool = globalThis.__polyllmPool ?? (getDb(), globalThis.__polyllmPool!);41    await pool.query("select 1");42    return true;43  } catch {44    return false;45  }46}4748export * from "./schema";49
Files · d6f683a5f3ce2650916bcde9467e60c640c62fa9
Menu

Theme