spb/autoscholar
Public
1import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";2import { Pool } from "pg";3import * as schema from "./schema/index.js";45export type Db = NodePgDatabase<typeof schema>;6export type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];78let pool: Pool | undefined;9let db: Db | undefined;1011export function getPool(connectionString = process.env.DATABASE_URL): Pool {12 if (!connectionString) throw new Error("DATABASE_URL is not set");13 if (!pool) {14 pool = new Pool({15 connectionString,16 max: Number(process.env.PG_POOL_MAX ?? 10),17 idleTimeoutMillis: 30_000,18 });19 pool.on("error", (err) => console.error("[db] pool error", err.message));20 }21 return pool;22}2324export function getDb(connectionString?: string): Db {25 if (!db) db = drizzle(getPool(connectionString), { schema });26 return db;27}2829export async function closeDb(): Promise<void> {30 await pool?.end();31 pool = undefined;32 db = undefined;33}3435export { schema };36