import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; import postgres from "postgres"; import * as schema from "@/db/schema"; type Database = PostgresJsDatabase; let database: Database | undefined; let client: ReturnType | undefined; export function getDb(): Database { const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { throw new Error( "DATABASE_URL is required for database-backed routes. Copy .env.example to .env and configure it.", ); } if (!database) { client = postgres(databaseUrl, { max: Number(process.env.DATABASE_POOL_SIZE ?? 10), prepare: false, }); database = drizzle(client, { schema }); } return database; } export async function closeDb(): Promise { await client?.end(); client = undefined; database = undefined; } export type { Database };