courtmitra / packages /db /src /index.ts
hetanshwaghela's picture
Day 1–2: monorepo scaffold + ingestion→intake→evidence loop
170b9b6
Raw
History Blame
790 Bytes
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema.js";
export { schema };
export * from "./schema.js";
export type Database = ReturnType<typeof drizzle<typeof schema>>;
let pool: Pool | undefined;
let dbInstance: Database | undefined;
/** Lazily-constructed singleton Drizzle client (Node postgres driver). */
export function getDb(connectionString = process.env.DATABASE_URL): Database {
if (!connectionString) {
throw new Error("DATABASE_URL is not set");
}
if (!dbInstance) {
pool = new Pool({ connectionString });
dbInstance = drizzle(pool, { schema });
}
return dbInstance;
}
export async function closeDb(): Promise<void> {
await pool?.end();
pool = undefined;
dbInstance = undefined;
}