Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,11 @@ await pg.describeQuery('SELECT * FROM test WHERE name = $1', ['test'])
}
```

### clone
`.clone(): Promise<PGlite>`

Clones the current instance. This is useful when a series of operations, like unit or integration test, need to be run on the same database without having to recreate the database each time, or for each test.

## Properties

### ready
Expand Down
5 changes: 5 additions & 0 deletions packages/pglite/src/pglite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -794,4 +794,9 @@ export class PGlite
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T> {
return this.#transactionMutex.runExclusive(fn)
}

async clone(): Promise<PGliteInterface> {
const dump = await this.dumpDataDir('none')
return new PGlite({ loadDataDir: dump })
}
}
42 changes: 42 additions & 0 deletions packages/pglite/tests/clone.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest'
import { PGlite } from '../dist/index.js'

describe('clone', () => {
it('clone pglite instance', async () => {
const pg1 = new PGlite()
await pg1.exec(`
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
name TEXT
);
`)
await pg1.exec("INSERT INTO test (name) VALUES ('test');")

const pg2 = await pg1.clone()

const ret1 = await pg1.query('SELECT * FROM test;')
const ret2 = await pg2.query('SELECT * FROM test;')

expect(ret1).toEqual(ret2)
})

it('clone pglite instance - insert into pg2', async () => {
const pg1 = new PGlite()
await pg1.exec(`
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
name TEXT
);
`)
await pg1.exec("INSERT INTO test (name) VALUES ('test');")

const pg2 = await pg1.clone()
await pg2.exec("INSERT INTO test (name) VALUES ('2-test');")

const ret1 = await pg1.query('SELECT * FROM test;')
const ret2 = await pg2.query('SELECT * FROM test;')

expect(ret1.rows.length).toBe(1)
expect(ret2.rows.length).toBe(2)
})
})
Loading