mirror your GitHub repos to tangled.org automatically
1import { readFileSync } from 'node:fs'
2import { fileURLToPath } from 'node:url'
3import { PGlite } from '@electric-sql/pglite'
4import { drizzle } from 'drizzle-orm/pglite'
5import * as schema from '../../server/db/schema'
6import type { Db } from '../../server/utils/db'
7
8const migrationPath = fileURLToPath(
9 new URL('../../server/db/migrations/0000_initial.sql', import.meta.url),
10)
11
12/**
13 * Create a fresh in-memory Postgres (PGlite) for a single test, apply our
14 * schema, and return a Drizzle instance. Each call returns an isolated DB.
15 */
16export async function createTestDb(): Promise<Db> {
17 const pg = new PGlite()
18 const sql = readFileSync(migrationPath, 'utf8')
19
20 // The drizzle-generated migration file uses `--> statement-breakpoint` between
21 // statements; PGlite's exec accepts the whole thing if we strip those markers.
22 // Sequential by design — DDL ordering matters.
23 for (const statement of sql.split('--> statement-breakpoint')) {
24 const trimmed = statement.trim()
25 // eslint-disable-next-line no-await-in-loop
26 if (trimmed) await pg.exec(trimmed)
27 }
28
29 return drizzle(pg, { schema }) as unknown as Db
30}