import "server-only"; import { Pool, type PoolClient } from "pg"; // Zugang zur Postgres von Olares. Die Werte injiziert das Chart aus // .Values.postgres.* (CLAUDE.md, Olares-Regel 5) — nie hartkodieren. // Lokal reicht DATABASE_URL. function createPool(): Pool { if (process.env.DATABASE_URL) return new Pool({ connectionString: process.env.DATABASE_URL, max: 10 }); return new Pool({ host: process.env.DB_HOST, port: Number(process.env.DB_PORT ?? 5432), user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, max: 10, }); } const globalForPool = globalThis as unknown as { lunchPool?: Pool }; export const pool: Pool = globalForPool.lunchPool ?? createPool(); if (process.env.NODE_ENV !== "production") globalForPool.lunchPool = pool; /** * Führt `fn` in einer Transaktion im Namen eines Haushalts aus. * * Jede Fachtabelle hat RLS mit FORCE und die Policy „Mitglied des Haushalts“ * über `app.household_id`. Ohne diesen Aufruf sieht eine Abfrage nichts — * die App verbindet als Tabelleneigentümerin, FORCE ist die einzige Wand. * `set_config(…, true)` gilt nur bis zum Ende der Transaktion; ein Client, * der in den Pool zurückgeht, trägt keinen Haushalt weiter. */ export async function withHousehold(householdId: string, fn: (client: PoolClient) => Promise): Promise { const client = await pool.connect(); try { await client.query("begin"); await client.query("select set_config('app.household_id', $1, true)", [householdId]); const result = await fn(client); await client.query("commit"); return result; } catch (error) { await client.query("rollback").catch(() => undefined); throw error; } finally { client.release(); } } /** * Für die Anmeldung, bevor der Haushalt bekannt ist: setzt `app.auth = on`. * Die Policies lassen das nur auf den Tabellen der Anmeldung zu (Migration * 0002). Außerhalb von lib/auth/ nie benutzen. */ export async function withAuth(fn: (client: PoolClient) => Promise): Promise { const client = await pool.connect(); try { await client.query("begin"); await client.query("select set_config('app.auth', 'on', true)"); const result = await fn(client); await client.query("commit"); return result; } catch (error) { await client.query("rollback").catch(() => undefined); throw error; } finally { client.release(); } } export async function databaseReachable(): Promise { try { await pool.query("select 1"); return true; } catch { return false; } }