import { Pool, type PoolClient } from "pg"; const globalDb = globalThis as unknown as { promptPool?: Pool }; export function db() { if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required"); return globalDb.promptPool ??= new Pool({ connectionString: process.env.DATABASE_URL, max: 10 }); } export async function transaction(run: (client: PoolClient) => Promise): Promise { const client = await db().connect(); try { await client.query("BEGIN"); const result = await run(client); await client.query("COMMIT"); return result; } catch (error) { await client.query("ROLLBACK"); throw error; } finally { client.release(); } }