import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { Pool } from "pg"; import { afterAll, beforeAll, beforeEach } from "vitest"; /** Dedicated schema per suite; never runs application migrations or modifies application rows. */ export function testDatabase(): Pool { const connectionString = process.env.EGRESS_TEST_DATABASE_URL ?? "postgres://superposter:superposter_dev@127.0.0.1:5433/superposter"; const schema = `egress_test_${randomUUID().replaceAll("-", "")}`; const owner = new Pool({ connectionString }); const pool = new Pool({ connectionString, options: `-c search_path=${schema}`, max: 24 }); beforeAll(async () => { await owner.query(`CREATE SCHEMA ${schema}`); const client = await pool.connect(); try { await client.query("BEGIN"); await client.query(await readFile(new URL("../migrations/001_host_budgets.sql", import.meta.url), "utf8")); await client.query("COMMIT"); } finally { client.release(); } }); beforeEach(async () => { await pool.query("TRUNCATE host_budgets"); }); afterAll(async () => { await pool.end(); await owner.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); await owner.end(); }); return pool; }