import { Pool, types } from 'pg'; // COUNT()/SUM() come back as bigint (type 20) and numeric (1700): hand them to JS as numbers. types.setTypeParser(20, (v) => parseInt(v, 10)); types.setTypeParser(1700, (v) => parseFloat(v)); const g = globalThis as unknown as { __pgPool?: Pool }; function pool(): Pool { if (!g.__pgPool) { if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not set'); // scripts/load-pg.js publishes each build as schema "live" g.__pgPool = new Pool({ connectionString: process.env.DATABASE_URL, max: 8, options: '-c search_path=live' }); } return g.__pgPool; } /** Run SQL written with `?` placeholders (rewritten to $1, $2, ...). */ export async function query(sql: string, params: unknown[] = []): Promise { let i = 0; const text = sql.replace(/\?/g, () => `$${++i}`); return (await pool().query(text, params as any[])).rows as T[]; } export async function one(sql: string, params: unknown[] = []): Promise { return (await query(sql, params))[0]; }