import { randomBytes } from 'node:crypto'; import { startPrismaDevServer } from '@prisma/dev'; import pg from 'pg'; import { timeouts } from '../timeouts'; export interface PostgresServer { readonly url: string; /** Resolves when the server has closed or after `timeouts.devServerClose`, whichever is first. */ close(): Promise; } let externalDbCounter = 0; async function startExternalPostgresDatabase(adminUrl: string): Promise { externalDbCounter += 1; const dbName = `ba_${process.pid}_${externalDbCounter}_${randomBytes(4).toString('hex')}`; const admin = new pg.Client({ connectionString: adminUrl }); await admin.connect(); try { await admin.query(`CREATE DATABASE ${admin.escapeIdentifier(dbName)}`); } finally { await admin.end(); } const url = new URL(adminUrl); url.pathname = `/${dbName}`; if (url.hostname === 'localhost' || url.hostname === '::1') { url.hostname = '127.0.0.1'; } url.searchParams.delete('sslmode'); url.searchParams.delete('connection_limit'); let closed = false; return { url: url.toString(), async close() { if (closed) return; closed = true; const dropAdmin = new pg.Client({ connectionString: adminUrl }); await dropAdmin.connect(); try { await dropAdmin.query( `DROP DATABASE IF EXISTS ${dropAdmin.escapeIdentifier(dbName)} WITH (FORCE)`, ); } finally { await dropAdmin.end().catch(() => undefined); } }, }; } /** * Starts one Postgres test database: uses an isolated database on `TEST_POSTGRES_ADMIN_URL` when configured (CI), or an embedded `@prisma/dev` server locally. */ export async function startPostgresServer(): Promise { const adminUrl = process.env['TEST_POSTGRES_ADMIN_URL']; if (adminUrl !== undefined && adminUrl.length > 0) { return startExternalPostgresDatabase(adminUrl); } // Stops each dev server starting the Prisma Streams worker thread, which crashes Node 24. process.env['DS_TOUCH_WORKERS'] = '0'; const server = await startPrismaDevServer({ databaseConnectTimeoutMillis: 1000, databaseIdleTimeoutMillis: 30_000, extensions: 'none', }); const url = new URL(server.database.connectionString); url.searchParams.delete('sslmode'); url.searchParams.delete('connection_limit'); return { url: url.toString(), async close() { const closing = server.close().catch(() => undefined); let timer: ReturnType | undefined; const waited = new Promise((resolve) => { timer = setTimeout(resolve, timeouts.devServerClose); timer.unref(); }); await Promise.race([closing, waited]); clearTimeout(timer); }, }; }