Skip to content

Commit e462ca8

Browse files
committed
test: Avoid repeated Postgres initialization
Bootstrapping embedded Postgres dominated the test suite. Reusing an empty database snapshot preserves per-test isolation while cutting median local `pnpm test` time from 24.24s to 7.74s across three runs.
1 parent 16b9edb commit e462ca8

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

‎packages/sync-postgres/test/helpers/pg.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,22 @@
66
import { PGlite } from '@electric-sql/pglite'
77
import type { SqlClient } from '../../src/db/client.js'
88

9-
export async function createTestDb(): Promise<SqlClient & { raw: PGlite }> {
9+
let emptyDataDir: Promise<Blob> | undefined
10+
11+
async function createEmptyDataDir(): Promise<Blob> {
1012
const pg = new PGlite()
13+
try {
14+
await pg.waitReady
15+
return await pg.dumpDataDir('none')
16+
} finally {
17+
await pg.close()
18+
}
19+
}
20+
21+
export async function createTestDb(): Promise<SqlClient & { raw: PGlite }> {
22+
// Reuse initdb's output, not the database; each test still owns its state.
23+
emptyDataDir ??= createEmptyDataDir()
24+
const pg = new PGlite({ loadDataDir: await emptyDataDir })
1125
await pg.waitReady
1226

1327
const client: SqlClient & { raw: PGlite } = {
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { it, expect } from 'vitest'
2+
import { createTestDb } from './helpers/pg.js'
3+
4+
it('creates isolated databases without carrying over schema or committed data', async () => {
5+
const first = await createTestDb()
6+
try {
7+
await first.exec(`create schema isolation; create table isolation.values (value text)`)
8+
await first.transaction(async (tx) => {
9+
await tx.query(`insert into isolation.values values ($1)`, ['first'])
10+
})
11+
12+
const second = await createTestDb()
13+
try {
14+
expect(second.raw).not.toBe(first.raw)
15+
const schema = await second.query(`select to_regnamespace('isolation') as name`)
16+
expect(schema.rows).toEqual([{ name: null }])
17+
18+
await second.exec(`create schema isolation; create table isolation.values (value text)`)
19+
await second.query(`insert into isolation.values values ($1)`, ['second'])
20+
expect((await first.query(`select value from isolation.values`)).rows).toEqual([{ value: 'first' }])
21+
expect((await second.query(`select value from isolation.values`)).rows).toEqual([{ value: 'second' }])
22+
} finally {
23+
await second.close()
24+
}
25+
} finally {
26+
await first.close()
27+
}
28+
})

0 commit comments

Comments
 (0)