Files
lunch/lib/db.ts
T
kai a62e48116a
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 55s
release / tag and release (push) Successful in 3s
Scaffold app, chart, CI and release (26.11.1) (#2)
2026-11-06 19:14:55 +00:00

56 lines
1.9 KiB
TypeScript

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<T>(householdId: string, fn: (client: PoolClient) => Promise<T>): Promise<T> {
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();
}
}
export async function databaseReachable(): Promise<boolean> {
try {
await pool.query("select 1");
return true;
} catch {
return false;
}
}