import { Pool, PoolClient } from "pg" const dbUrl = process.env.DATABASE_URL if (!dbUrl) { throw new Error("DATABASE_URL environment variable is required") } const pool = new Pool({ connectionString: dbUrl, max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000, statement_timeout: 30000, idle_in_transaction_session_timeout: 10000, ssl: dbUrl.includes("localhost") || dbUrl.includes("127.0.0.1") ? false : { rejectUnauthorized: false }, }) pool.on("error", (err) => { console.error("Unexpected database pool error:", err) }) export async function query(text: string, params?: unknown[], userId?: string) { const client = await pool.connect() try { if (userId) { await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId]) } const result = await client.query(text, params) return result } finally { client.release() } } export async function transaction( callback: (client: PoolClient) => Promise, userId?: string, ): Promise { const client = await pool.connect() try { await client.query("BEGIN") if (userId) { await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId]) } const result = await callback(client) await client.query("COMMIT") return result } catch (e) { await client.query("ROLLBACK").catch(() => {}) throw e } finally { client.release() } } export default pool