import { execFileSync } from 'node:child_process'; import { createRequire } from 'node:module'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from 'pg'; import { collabTestDatabaseUrl } from './src/testing/test-db.js'; const require = createRequire(import.meta.url); const here = dirname(fileURLToPath(import.meta.url)); /** * Prepare the isolated collab test database (see `test-db.ts`): create it if * missing, then push the current Prisma schema (owned by the api package) into * it. Runs once per test run; a no-op when `TEST_DATABASE_URL` is unset, in * which case the DB-backed suite skips itself. */ export default async function globalSetup(): Promise { const base = process.env.TEST_DATABASE_URL; if (!base) return; const target = collabTestDatabaseUrl(base); const dbName = decodeURIComponent(new URL(target).pathname.slice(1)); const admin = new Client({ connectionString: base }); await admin.connect(); try { const exists = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [dbName]); if (exists.rowCount === 0) { // Identifier can't be parameterised; dbName is derived from our own env. await admin.query(`CREATE DATABASE "${dbName}"`); } } finally { await admin.end(); } execFileSync( process.execPath, [ require.resolve('prisma/build/index.js'), 'db', 'push', '--skip-generate', '--schema', resolve(here, '../api/prisma/schema.prisma'), ], { env: { ...process.env, DATABASE_URL: target }, stdio: 'inherit', cwd: here }, ); }