import { createHash, randomBytes } from 'node:crypto'; import { readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { suppressIdleConnectionErrors } from '@internal/utils/suppress-idle-connection-errors'; import { type ServerOptions, startPrismaDevServer } from '@prisma/dev'; import { Client } from 'pg'; export * from '../application-domain-of'; export * from '../column-descriptors'; export * from '../contract-factories'; export * from '../contract-types-modules'; export * from '../lowered-params'; export * from '../migration-modules'; export * from '../operation-descriptors'; export * from '../startup-parameters'; export * from '../timeouts'; function normalizeConnectionString(raw: string): string { const url = new URL(raw); if (url.hostname === 'localhost' || url.hostname === '::1') { url.hostname = '127.0.0.1'; } return url.toString(); } export interface DevDatabase { readonly connectionString: string; /** How long the server keeps an idle connection open before closing it. */ readonly databaseIdleTimeoutMillis: number; dumpDataDir(compression?: 'gzip' | 'none'): Promise; close(): Promise; } export type DevDatabaseOptions = ServerOptions & { /** Force an embedded `@prisma/dev` PGlite server even when `TEST_POSTGRES_ADMIN_URL` is set. */ readonly forcePglite?: boolean; }; let externalPgCounter = 0; /** Returns true when `TEST_POSTGRES_ADMIN_URL` opts test runs into a shared external Postgres server. */ export function isExternalPostgresEnabled(): boolean { const url = process.env['TEST_POSTGRES_ADMIN_URL']; return url !== undefined && url.length > 0; } /** Returns true when `TEST_MONGO_URI` opts test runs into a shared external MongoDB replica set. */ export function isExternalMongoEnabled(): boolean { const uri = process.env['TEST_MONGO_URI']; return uri !== undefined && uri.length > 0; } /** Rewrites a Postgres admin URL to target a specific isolated database name. */ export function buildExternalPostgresDatabaseUrl(adminUrl: string, dbName: string): string { const url = new URL(adminUrl); url.pathname = `/${dbName}`; return normalizeConnectionString(url.toString()); } /** Rewrites a MongoDB base URI to target a specific isolated database name. */ export function buildExternalMongoUri(baseUri: string, dbName: string): string { const url = new URL(baseUri); url.pathname = `/${dbName}`; return url.toString(); } function uniquePgDatabaseName(): string { externalPgCounter += 1; return `pt_${process.pid}_${externalPgCounter}_${randomBytes(4).toString('hex')}`; } async function createExternalPostgresDatabase( adminUrl: string, idleTimeoutMillis: number, ): Promise { const dbName = uniquePgDatabaseName(); const admin = new Client({ connectionString: adminUrl }); await admin.connect(); try { await admin.query(`CREATE DATABASE ${admin.escapeIdentifier(dbName)}`); } finally { await admin.end(); } const connectionString = buildExternalPostgresDatabaseUrl(adminUrl, dbName); let closed = false; return { connectionString, databaseIdleTimeoutMillis: idleTimeoutMillis, dumpDataDir() { return Promise.reject( new TypeError( 'dumpDataDir() is only supported on embedded @prisma/dev PGlite databases (pass { forcePglite: true })', ), ); }, async close() { if (closed) return; closed = true; const dropAdmin = new Client({ connectionString: adminUrl }); await dropAdmin.connect(); try { await dropAdmin.query( `DROP DATABASE IF EXISTS ${dropAdmin.escapeIdentifier(dbName)} WITH (FORCE)`, ); } finally { await dropAdmin.end().catch(() => {}); } }, }; } /** * The Postgres driver's pool keeps an idle client for 30 s. The dev server must * not close a connection sooner, or the pool hands a test a dead client the * first time it pauses between queries — which a slow or coverage-instrumented * run does routinely. */ const DEFAULT_IDLE_TIMEOUT_MS = 30_000; /** * Narrow set of PGlite extensions actually used across repo tests * (`pg_stat_statements` is always retained by `@prisma/dev`). Loading 4 * extensions instead of all ~46 trims ~50ms off every PGlite boot; extension- * free suites can pass `{ extensions: 'none' }` to shave another ~40ms. */ const DEFAULT_DEV_EXTENSIONS: NonNullable = [ 'vector', 'citext', 'pg_trgm', 'uuid_ossp', ]; const requireFromHere = createRequire(import.meta.url); function getPrismaDevVersion(): string { try { const pkg: unknown = requireFromHere('@prisma/dev/package.json'); if ( typeof pkg === 'object' && pkg !== null && 'version' in pkg && typeof pkg.version === 'string' ) { return pkg.version; } } catch { // Fallback if package.json is not exported } return 'unknown'; } const snapshotMemoryCache = new Map>(); /** * Loads or generates a reusable PGlite PGDATA tar snapshot cached both in memory * and in `os.tmpdir()` (keyed by `cacheKey` + `@prisma/dev` version) so parallel * Vitest workers share one pre-seeded template via `loadDataDir`. */ export function loadOrCreatePgDataSnapshot( cacheKey: string, options: Omit, populate: (connectionString: string) => Promise, ): Promise { const digest = createHash('sha256') .update(getPrismaDevVersion()) .update('\0') .update(cacheKey) .digest('hex') .slice(0, 24); const existing = snapshotMemoryCache.get(digest); if (existing !== undefined) { return existing; } const snapPath = join(tmpdir(), `prisma-pgdata-snap-${digest}.tar`); const promise = (async () => { try { return new Uint8Array(readFileSync(snapPath)); } catch { // Cache miss on disk — build the template once and atomically publish it. } const database = await createDevDatabase({ ...options, forcePglite: true }); let bytes: Uint8Array; try { await populate(database.connectionString); const blob = await database.dumpDataDir('none'); bytes = new Uint8Array(await blob.arrayBuffer()); } finally { await database.close(); } const tmpPath = `${snapPath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`; try { writeFileSync(tmpPath, bytes); renameSync(tmpPath, snapPath); } catch { try { rmSync(tmpPath, { force: true }); } catch { // Ignore cleanup failure } } return bytes; })(); snapshotMemoryCache.set(digest, promise); promise.catch(() => { if (snapshotMemoryCache.get(digest) === promise) { snapshotMemoryCache.delete(digest); } }); return promise; } /** * Creates a dev database instance for testing. * Automatically handles connection string normalization and cleanup. * @prisma/dev automatically assigns ports to avoid conflicts and enforces a single * active connection (second connections are rejected until the first is closed). */ export async function createDevDatabase(options?: DevDatabaseOptions): Promise { const idleTimeoutMillis = options?.databaseIdleTimeoutMillis ?? DEFAULT_IDLE_TIMEOUT_MS; const adminUrl = process.env['TEST_POSTGRES_ADMIN_URL']; if ( adminUrl !== undefined && adminUrl.length > 0 && options?.forcePglite !== true && options?.loadDataDir === undefined && options?.databasePort === undefined ) { return createExternalPostgresDatabase(adminUrl, idleTimeoutMillis); } // Stops each dev server starting the Prisma Streams touch-processor worker // thread, which crashes Node 24 (nodejs/node#66366, nodejs/node#63323). process.env['DS_TOUCH_WORKERS'] = '0'; const { forcePglite: _forcePglite, ...serverOptions } = options ?? {}; const settings: ServerOptions & { readonly databaseIdleTimeoutMillis: number } = { databaseConnectTimeoutMillis: 1000, databaseIdleTimeoutMillis: idleTimeoutMillis, extensions: DEFAULT_DEV_EXTENSIONS, ...serverOptions, }; const server = await startPrismaDevServer(settings); return { ...server, databaseIdleTimeoutMillis: settings.databaseIdleTimeoutMillis, connectionString: normalizeConnectionString(server.database.connectionString), }; } /** * Executes a function with a dev database, automatically cleaning up afterward. * @prisma/dev automatically assigns ports and will reject any attempt to open a * second connection while the first is active, so ensure each helper call closes * before starting another. */ export async function withDevDatabase( fn: (ctx: DevDatabase) => Promise, options?: DevDatabaseOptions, ): Promise { const database = await createDevDatabase(options); try { return await fn(database); } finally { await database.close(); } } /** * Executes a function with a database client, automatically cleaning up afterward. */ export async function withClient( connectionString: string, fn: (client: Client) => Promise, ): Promise { // A PGlite (WASM) dev server can abort mid-operation on the slower CI // runners; the suppressed connection-level 'error' event would otherwise // fail the whole run even though the awaited query already rejected and the // test is retried on a fresh database. const client = suppressIdleConnectionErrors(new Client({ connectionString })); await client.connect(); try { return await fn(client); } finally { // On a dropped connection `end()` itself can reject; the caller already has // the real failure from `fn`, so don't let cleanup mask or replace it. await client.end().catch(() => {}); } } /** * Drains an async iterable, consuming all values without collecting them. * Useful for testing side effects without memory overhead. */ export async function drainAsyncIterable(iterable: AsyncIterable): Promise { for await (const _ of iterable) { // exhaust iterator } } /** * Collects all values from an async iterable into an array. * Useful for testing query results. */ export async function collectAsync(iterable: AsyncIterable): Promise { const out: T[] = []; for await (const item of iterable) { out.push(item); } return out; } /** * Tears down test database by dropping schema and tables. * This helper DRYs up the common pattern of database teardown in tests. */ export async function teardownTestDatabase(client: Client, tables?: string[]): Promise { if (tables && tables.length > 0) { for (const table of tables) { await client.query(`drop table if exists "${table}"`); } } await client.query('drop schema if exists prisma cascade'); await client.query('drop schema if exists prisma_contract cascade'); }