pglite-test 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +158 -0
- package/esm/index.js +85 -0
- package/esm/txn.js +61 -0
- package/index.d.ts +68 -0
- package/index.js +93 -0
- package/package.json +60 -0
- package/txn.d.ts +41 -0
- package/txn.js +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# pglite-test
|
|
2
|
+
|
|
3
|
+
A drop-in [`pgsql-test`](../pgsql-test) `getConnections()` backed by an in-process
|
|
4
|
+
[**PGlite**](https://github.com/electric-sql/pglite) instance (WASM Postgres) โ
|
|
5
|
+
**no Postgres server, no `createdb`, no `psql`, no TCP.**
|
|
6
|
+
|
|
7
|
+
It follows the same pattern as `drizzle-orm-test` / `supabase-test`: a thin
|
|
8
|
+
`getConnections()` wrapper that composes the existing `pg-cache` / `pgsql-client`
|
|
9
|
+
seams.
|
|
10
|
+
|
|
11
|
+
- [`@pgpmjs/pglite-adapter`](../pglite-adapter)'s `registerPglite()` routes
|
|
12
|
+
`pg-cache`'s `getPgPool()` at PGlite, so `seed.pgpm()` deploys your module into
|
|
13
|
+
it with the unmodified pgpm engine.
|
|
14
|
+
- `pgsql-client`'s client-factory seam routes `PgTestClient`'s underlying
|
|
15
|
+
`pg.Client` at the same PGlite session.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { getConnections, PgTestClient } from 'pglite-test';
|
|
21
|
+
|
|
22
|
+
let pg: PgTestClient;
|
|
23
|
+
let db: PgTestClient;
|
|
24
|
+
let teardown: () => Promise<void>;
|
|
25
|
+
|
|
26
|
+
beforeAll(async () => {
|
|
27
|
+
({ pg, db, teardown } = await getConnections());
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
afterAll(async () => {
|
|
31
|
+
await teardown();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
beforeEach(async () => {
|
|
35
|
+
await pg.beforeEach();
|
|
36
|
+
await db.beforeEach();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
afterEach(async () => {
|
|
40
|
+
await db.afterEach();
|
|
41
|
+
await pg.afterEach();
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('queries the pgpm-deployed schema', async () => {
|
|
45
|
+
const { rows } = await db.query('SELECT count(*)::int AS n FROM app.users');
|
|
46
|
+
expect(rows[0].n).toBe(0);
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Jest must run with `NODE_OPTIONS=--experimental-vm-modules` (PGlite loads a WASM
|
|
51
|
+
module); the package's `test` script sets this.
|
|
52
|
+
|
|
53
|
+
## Single-session model
|
|
54
|
+
|
|
55
|
+
PGlite is one in-process session, so `pg` and `db` share it. That differs from
|
|
56
|
+
`pgsql-test` (two authenticated connections on a real server):
|
|
57
|
+
|
|
58
|
+
- Transaction control is **ref-counted** (`SharedTxn`) so the standard
|
|
59
|
+
two-client `beforeEach`/`afterEach` harness emits exactly one
|
|
60
|
+
`BEGIN`/`SAVEPOINT`/`ROLLBACK`/`COMMIT` per test. The single-client (`db` only)
|
|
61
|
+
pattern also works.
|
|
62
|
+
- Role-based RLS uses `setContext({ role })` (i.e. `SET LOCAL role`) on the shared
|
|
63
|
+
session rather than separate authenticated connections. Any role you switch to
|
|
64
|
+
must exist โ create it via `pglite.extensionSql` (e.g.
|
|
65
|
+
`['CREATE ROLE authenticated;']`).
|
|
66
|
+
- `publish()` (commit-and-continue) is not supported under the shared-session
|
|
67
|
+
coordinator.
|
|
68
|
+
|
|
69
|
+
## Options
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
await getConnections(
|
|
73
|
+
{
|
|
74
|
+
pglite: {
|
|
75
|
+
dataDir: undefined, // in-memory by default
|
|
76
|
+
extensions: { vector }, // WASM extensions (e.g. pglite-pgvector)
|
|
77
|
+
extensionSql: [ // run once after ready
|
|
78
|
+
'CREATE EXTENSION IF NOT EXISTS vector;',
|
|
79
|
+
'CREATE ROLE authenticated;'
|
|
80
|
+
]
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
[seed.pgpm()] // default seed adapter
|
|
84
|
+
);
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Education and Tutorials
|
|
90
|
+
|
|
91
|
+
1. ๐ [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
92
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
93
|
+
|
|
94
|
+
2. ๐ฆ [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
95
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
96
|
+
|
|
97
|
+
3. โ๏ธ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
98
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
99
|
+
|
|
100
|
+
4. ๐งช [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
101
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
102
|
+
|
|
103
|
+
5. โก [Supabase Testing](https://constructive.io/learn/supabase)
|
|
104
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
105
|
+
|
|
106
|
+
6. ๐ง [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
107
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
108
|
+
|
|
109
|
+
7. ๐ง [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
110
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
111
|
+
|
|
112
|
+
## Related Constructive Tooling
|
|
113
|
+
|
|
114
|
+
### ๐ฆ Package Management
|
|
115
|
+
|
|
116
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **๐ฅ๏ธ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
117
|
+
|
|
118
|
+
### ๐งช Testing
|
|
119
|
+
|
|
120
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **๐ Isolated testing environments** with per-test transaction rollbacksโideal for integration tests, complex migrations, and RLS simulation.
|
|
121
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **๐ฑ PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
122
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **๐งช Supabase-native test harness** preconfigured for the local Supabase stackโper-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
123
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **๐ Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
124
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **๐ Session context injection** to add session-local context (e.g., `SET LOCAL`) into queriesโideal for setting `role`, `jwt.claims`, and other session settings.
|
|
125
|
+
|
|
126
|
+
### ๐ง Parsing & AST
|
|
127
|
+
|
|
128
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **๐ SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
129
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **๐ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
130
|
+
* [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **๐ฆ Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
131
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **๐ท๏ธ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
132
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **๐ Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
133
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **๐ ๏ธ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
134
|
+
|
|
135
|
+
### ๐ Documentation & Skills
|
|
136
|
+
|
|
137
|
+
* [constructive-skills](https://github.com/constructive-io/constructive-skills): **๐ Platform documentation and AI agent skills** โ feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
|
|
138
|
+
|
|
139
|
+
Install skills for AI coding agents:
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
143
|
+
npx skills add constructive-io/constructive-skills
|
|
144
|
+
|
|
145
|
+
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
146
|
+
npx skills add https://github.com/constructive-io/constructive --skill pgpm
|
|
147
|
+
npx skills add https://github.com/constructive-io/constructive --skill constructive-testing
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Credits
|
|
151
|
+
|
|
152
|
+
**๐ Built by the [Constructive](https://constructive.io) team โ creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
153
|
+
|
|
154
|
+
## Disclaimer
|
|
155
|
+
|
|
156
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
157
|
+
|
|
158
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pglite-test
|
|
3
|
+
*
|
|
4
|
+
* A drop-in `getConnections()` โ like `drizzle-orm-test` / `supabase-test` โ that
|
|
5
|
+
* backs the pgsql-test client model with an in-process **PGlite** instance
|
|
6
|
+
* instead of a Postgres server. No `createdb`, no `psql`, no TCP: one WASM
|
|
7
|
+
* Postgres session per suite.
|
|
8
|
+
*
|
|
9
|
+
* It composes the existing seams rather than forking anything:
|
|
10
|
+
* - `@pgpmjs/pglite-adapter`'s `registerPglite()` routes `pg-cache`'s
|
|
11
|
+
* `getPgPool()` at PGlite (so `seed.pgpm()` deploys into it), and
|
|
12
|
+
* - `pgsql-client`'s client-factory seam routes `PgTestClient`'s underlying
|
|
13
|
+
* `pg.Client` at the same PGlite session.
|
|
14
|
+
*
|
|
15
|
+
* Because PGlite is a single session, `pg` and `db` share it; transaction
|
|
16
|
+
* control is ref-counted (see `SharedTxn`) so the standard
|
|
17
|
+
* `pg.beforeEach()/db.beforeEach()` + `db.afterEach()/pg.afterEach()` harness
|
|
18
|
+
* works unchanged.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* import { getConnections, PgTestClient } from 'pglite-test';
|
|
23
|
+
*
|
|
24
|
+
* let pg: PgTestClient, db: PgTestClient, teardown: () => Promise<void>;
|
|
25
|
+
* beforeAll(async () => { ({ pg, db, teardown } = await getConnections()); });
|
|
26
|
+
* afterAll(async () => { await teardown(); });
|
|
27
|
+
* beforeEach(async () => { await pg.beforeEach(); await db.beforeEach(); });
|
|
28
|
+
* afterEach(async () => { await db.afterEach(); await pg.afterEach(); });
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
import { createPgliteClient, registerPglite } from '@pgpmjs/pglite-adapter';
|
|
32
|
+
import { getPgEnvOptions } from 'pg-env';
|
|
33
|
+
import { getActivePgClientFactory, registerPgClientFactory } from 'pgsql-client';
|
|
34
|
+
import { seed } from 'pgsql-test';
|
|
35
|
+
import { PgliteTestClient, SharedTxn } from './txn';
|
|
36
|
+
/**
|
|
37
|
+
* Create an isolated PGlite-backed test environment and return `pg`/`db` clients
|
|
38
|
+
* plus a `teardown()`. Defaults to seeding via `seed.pgpm()` (deploys the pgpm
|
|
39
|
+
* module in `cwd`), matching pgsql-test.
|
|
40
|
+
*/
|
|
41
|
+
export const getConnections = async (cn = {}, seedAdapters = [seed.pgpm()]) => {
|
|
42
|
+
// Capture the previously-active client factory so teardown restores it
|
|
43
|
+
// (rather than clobbering to the default), mirroring how registerPglite
|
|
44
|
+
// restores the previous pool factory. Keeps nested/sequential suites clean.
|
|
45
|
+
const previousClientFactory = getActivePgClientFactory();
|
|
46
|
+
const handle = await registerPglite({
|
|
47
|
+
dataDir: cn.pglite?.dataDir,
|
|
48
|
+
extensions: cn.pglite?.extensions,
|
|
49
|
+
extensionSql: cn.pglite?.extensionSql,
|
|
50
|
+
instance: cn.pglite?.instance
|
|
51
|
+
});
|
|
52
|
+
// Route pgsql-client's PgClient at the same in-process PGlite session.
|
|
53
|
+
registerPgClientFactory(() => createPgliteClient(handle.db));
|
|
54
|
+
try {
|
|
55
|
+
const config = getPgEnvOptions({ database: 'postgres', ...cn.pg });
|
|
56
|
+
const txn = new SharedTxn();
|
|
57
|
+
const pg = new PgliteTestClient(config, {}, txn);
|
|
58
|
+
const db = new PgliteTestClient(config, { auth: cn.db?.auth, roles: cn.db?.roles }, txn);
|
|
59
|
+
// seed.pgpm deploys via getPgPool -> PGlite; sqlfile/json/csv/fn use ctx.pg.
|
|
60
|
+
if (seedAdapters.length) {
|
|
61
|
+
await seed.compose(seedAdapters).seed({
|
|
62
|
+
connect: cn.db ?? {},
|
|
63
|
+
admin: undefined, // unused by the PGlite-safe adapters
|
|
64
|
+
config,
|
|
65
|
+
pg
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const teardown = async () => {
|
|
69
|
+
registerPgClientFactory(previousClientFactory);
|
|
70
|
+
await pg.close();
|
|
71
|
+
await db.close();
|
|
72
|
+
await handle.close();
|
|
73
|
+
};
|
|
74
|
+
return { pg, db, instance: handle.db, teardown };
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
// Setup failed after registering the seams โ unwind so a broken suite
|
|
78
|
+
// doesn't leak factories/instance into the next one.
|
|
79
|
+
registerPgClientFactory(previousClientFactory);
|
|
80
|
+
await handle.close();
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
export { PgliteTestClient, SharedTxn } from './txn';
|
|
85
|
+
export { PgTestClient, seed } from 'pgsql-test';
|
package/esm/txn.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { PgTestClient } from 'pgsql-test';
|
|
2
|
+
/**
|
|
3
|
+
* Coordinates transaction control across the `pg` and `db` clients when they
|
|
4
|
+
* share ONE PGlite session.
|
|
5
|
+
*
|
|
6
|
+
* On a real Postgres server `pg` and `db` are independent connections, each with
|
|
7
|
+
* its own transaction, so the standard harness opens a `BEGIN`+`SAVEPOINT` on
|
|
8
|
+
* both. PGlite is a single in-process session, so a second `BEGIN` is a no-op
|
|
9
|
+
* and a `ROLLBACK TO SAVEPOINT` after the other client's `COMMIT` errors.
|
|
10
|
+
*
|
|
11
|
+
* This coordinator ref-counts the shared depth so exactly one `BEGIN`, one
|
|
12
|
+
* outer `SAVEPOINT`, one `ROLLBACK TO SAVEPOINT` and one `COMMIT` run per test โ
|
|
13
|
+
* regardless of whether the caller drives one client or both. It works for the
|
|
14
|
+
* common orderings:
|
|
15
|
+
* beforeEach: pg.beforeEach(); db.beforeEach();
|
|
16
|
+
* afterEach: db.afterEach(); pg.afterEach();
|
|
17
|
+
* and for the single-client pattern (`db` only).
|
|
18
|
+
*/
|
|
19
|
+
export class SharedTxn {
|
|
20
|
+
depth = 0;
|
|
21
|
+
/** True only for the outermost `begin()` (the one that should emit BEGIN). */
|
|
22
|
+
beginNeeded() {
|
|
23
|
+
return this.depth++ === 0;
|
|
24
|
+
}
|
|
25
|
+
/** True only for the outermost `commit()` (the one that should emit COMMIT). */
|
|
26
|
+
commitNeeded() {
|
|
27
|
+
return --this.depth === 0;
|
|
28
|
+
}
|
|
29
|
+
/** True while exactly one transaction level is open (the outer savepoint scope). */
|
|
30
|
+
atOuter() {
|
|
31
|
+
return this.depth === 1;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* `PgTestClient` whose transaction control is routed through a `SharedTxn`, so
|
|
36
|
+
* two clients over one PGlite session don't double-`BEGIN` or over-`COMMIT`.
|
|
37
|
+
* Everything else (query, setContext, auth, loadSql, ...) is inherited verbatim.
|
|
38
|
+
*/
|
|
39
|
+
export class PgliteTestClient extends PgTestClient {
|
|
40
|
+
txn;
|
|
41
|
+
constructor(config, opts, txn) {
|
|
42
|
+
super(config, opts);
|
|
43
|
+
this.txn = txn;
|
|
44
|
+
}
|
|
45
|
+
async begin() {
|
|
46
|
+
if (this.txn.beginNeeded())
|
|
47
|
+
await super.begin();
|
|
48
|
+
}
|
|
49
|
+
async savepoint(name) {
|
|
50
|
+
if (this.txn.atOuter())
|
|
51
|
+
await super.savepoint(name);
|
|
52
|
+
}
|
|
53
|
+
async rollback(name) {
|
|
54
|
+
if (this.txn.atOuter())
|
|
55
|
+
await super.rollback(name);
|
|
56
|
+
}
|
|
57
|
+
async commit() {
|
|
58
|
+
if (this.txn.commitNeeded())
|
|
59
|
+
await super.commit();
|
|
60
|
+
}
|
|
61
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pglite-test
|
|
3
|
+
*
|
|
4
|
+
* A drop-in `getConnections()` โ like `drizzle-orm-test` / `supabase-test` โ that
|
|
5
|
+
* backs the pgsql-test client model with an in-process **PGlite** instance
|
|
6
|
+
* instead of a Postgres server. No `createdb`, no `psql`, no TCP: one WASM
|
|
7
|
+
* Postgres session per suite.
|
|
8
|
+
*
|
|
9
|
+
* It composes the existing seams rather than forking anything:
|
|
10
|
+
* - `@pgpmjs/pglite-adapter`'s `registerPglite()` routes `pg-cache`'s
|
|
11
|
+
* `getPgPool()` at PGlite (so `seed.pgpm()` deploys into it), and
|
|
12
|
+
* - `pgsql-client`'s client-factory seam routes `PgTestClient`'s underlying
|
|
13
|
+
* `pg.Client` at the same PGlite session.
|
|
14
|
+
*
|
|
15
|
+
* Because PGlite is a single session, `pg` and `db` share it; transaction
|
|
16
|
+
* control is ref-counted (see `SharedTxn`) so the standard
|
|
17
|
+
* `pg.beforeEach()/db.beforeEach()` + `db.afterEach()/pg.afterEach()` harness
|
|
18
|
+
* works unchanged.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* import { getConnections, PgTestClient } from 'pglite-test';
|
|
23
|
+
*
|
|
24
|
+
* let pg: PgTestClient, db: PgTestClient, teardown: () => Promise<void>;
|
|
25
|
+
* beforeAll(async () => { ({ pg, db, teardown } = await getConnections()); });
|
|
26
|
+
* afterAll(async () => { await teardown(); });
|
|
27
|
+
* beforeEach(async () => { await pg.beforeEach(); await db.beforeEach(); });
|
|
28
|
+
* afterEach(async () => { await db.afterEach(); await pg.afterEach(); });
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
import type { PGlite } from '@electric-sql/pglite';
|
|
32
|
+
import { GetConnectionOpts, PgTestClient, SeedAdapter } from 'pgsql-test';
|
|
33
|
+
export interface PgliteConnectionOpts extends GetConnectionOpts {
|
|
34
|
+
/** PGlite-specific knobs (in-memory by default). */
|
|
35
|
+
pglite?: {
|
|
36
|
+
/** Persist to a directory (default: in-memory). */
|
|
37
|
+
dataDir?: string;
|
|
38
|
+
/** WASM extensions registered at construction, e.g. `{ vector }`. */
|
|
39
|
+
extensions?: Record<string, any>;
|
|
40
|
+
/**
|
|
41
|
+
* SQL run once after the instance is ready โ `CREATE EXTENSION ...`, and any
|
|
42
|
+
* `CREATE ROLE ...` needed for RLS role switching (PGlite starts as a single
|
|
43
|
+
* superuser, so roles used via `setContext({ role })` must be created here).
|
|
44
|
+
*/
|
|
45
|
+
extensionSql?: string[];
|
|
46
|
+
/** Reuse an already-created PGlite instance instead of creating one. */
|
|
47
|
+
instance?: PGlite;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export interface PgliteConnectionResult {
|
|
51
|
+
/** Superuser-style client (bypasses RLS by not switching role). */
|
|
52
|
+
pg: PgTestClient;
|
|
53
|
+
/** Application client (role/context switched via `setContext`). */
|
|
54
|
+
db: PgTestClient;
|
|
55
|
+
/** The underlying PGlite instance, for direct access. */
|
|
56
|
+
instance: PGlite;
|
|
57
|
+
/** Unregister the seams and close the PGlite instance. */
|
|
58
|
+
teardown: () => Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Create an isolated PGlite-backed test environment and return `pg`/`db` clients
|
|
62
|
+
* plus a `teardown()`. Defaults to seeding via `seed.pgpm()` (deploys the pgpm
|
|
63
|
+
* module in `cwd`), matching pgsql-test.
|
|
64
|
+
*/
|
|
65
|
+
export declare const getConnections: (cn?: PgliteConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<PgliteConnectionResult>;
|
|
66
|
+
export { PgliteTestClient, SharedTxn } from './txn';
|
|
67
|
+
export type { GetConnectionOpts, SeedAdapter } from 'pgsql-test';
|
|
68
|
+
export { PgTestClient, seed } from 'pgsql-test';
|
package/index.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* pglite-test
|
|
4
|
+
*
|
|
5
|
+
* A drop-in `getConnections()` โ like `drizzle-orm-test` / `supabase-test` โ that
|
|
6
|
+
* backs the pgsql-test client model with an in-process **PGlite** instance
|
|
7
|
+
* instead of a Postgres server. No `createdb`, no `psql`, no TCP: one WASM
|
|
8
|
+
* Postgres session per suite.
|
|
9
|
+
*
|
|
10
|
+
* It composes the existing seams rather than forking anything:
|
|
11
|
+
* - `@pgpmjs/pglite-adapter`'s `registerPglite()` routes `pg-cache`'s
|
|
12
|
+
* `getPgPool()` at PGlite (so `seed.pgpm()` deploys into it), and
|
|
13
|
+
* - `pgsql-client`'s client-factory seam routes `PgTestClient`'s underlying
|
|
14
|
+
* `pg.Client` at the same PGlite session.
|
|
15
|
+
*
|
|
16
|
+
* Because PGlite is a single session, `pg` and `db` share it; transaction
|
|
17
|
+
* control is ref-counted (see `SharedTxn`) so the standard
|
|
18
|
+
* `pg.beforeEach()/db.beforeEach()` + `db.afterEach()/pg.afterEach()` harness
|
|
19
|
+
* works unchanged.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```typescript
|
|
23
|
+
* import { getConnections, PgTestClient } from 'pglite-test';
|
|
24
|
+
*
|
|
25
|
+
* let pg: PgTestClient, db: PgTestClient, teardown: () => Promise<void>;
|
|
26
|
+
* beforeAll(async () => { ({ pg, db, teardown } = await getConnections()); });
|
|
27
|
+
* afterAll(async () => { await teardown(); });
|
|
28
|
+
* beforeEach(async () => { await pg.beforeEach(); await db.beforeEach(); });
|
|
29
|
+
* afterEach(async () => { await db.afterEach(); await pg.afterEach(); });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
33
|
+
exports.seed = exports.PgTestClient = exports.SharedTxn = exports.PgliteTestClient = exports.getConnections = void 0;
|
|
34
|
+
const pglite_adapter_1 = require("@pgpmjs/pglite-adapter");
|
|
35
|
+
const pg_env_1 = require("pg-env");
|
|
36
|
+
const pgsql_client_1 = require("pgsql-client");
|
|
37
|
+
const pgsql_test_1 = require("pgsql-test");
|
|
38
|
+
const txn_1 = require("./txn");
|
|
39
|
+
/**
|
|
40
|
+
* Create an isolated PGlite-backed test environment and return `pg`/`db` clients
|
|
41
|
+
* plus a `teardown()`. Defaults to seeding via `seed.pgpm()` (deploys the pgpm
|
|
42
|
+
* module in `cwd`), matching pgsql-test.
|
|
43
|
+
*/
|
|
44
|
+
const getConnections = async (cn = {}, seedAdapters = [pgsql_test_1.seed.pgpm()]) => {
|
|
45
|
+
// Capture the previously-active client factory so teardown restores it
|
|
46
|
+
// (rather than clobbering to the default), mirroring how registerPglite
|
|
47
|
+
// restores the previous pool factory. Keeps nested/sequential suites clean.
|
|
48
|
+
const previousClientFactory = (0, pgsql_client_1.getActivePgClientFactory)();
|
|
49
|
+
const handle = await (0, pglite_adapter_1.registerPglite)({
|
|
50
|
+
dataDir: cn.pglite?.dataDir,
|
|
51
|
+
extensions: cn.pglite?.extensions,
|
|
52
|
+
extensionSql: cn.pglite?.extensionSql,
|
|
53
|
+
instance: cn.pglite?.instance
|
|
54
|
+
});
|
|
55
|
+
// Route pgsql-client's PgClient at the same in-process PGlite session.
|
|
56
|
+
(0, pgsql_client_1.registerPgClientFactory)(() => (0, pglite_adapter_1.createPgliteClient)(handle.db));
|
|
57
|
+
try {
|
|
58
|
+
const config = (0, pg_env_1.getPgEnvOptions)({ database: 'postgres', ...cn.pg });
|
|
59
|
+
const txn = new txn_1.SharedTxn();
|
|
60
|
+
const pg = new txn_1.PgliteTestClient(config, {}, txn);
|
|
61
|
+
const db = new txn_1.PgliteTestClient(config, { auth: cn.db?.auth, roles: cn.db?.roles }, txn);
|
|
62
|
+
// seed.pgpm deploys via getPgPool -> PGlite; sqlfile/json/csv/fn use ctx.pg.
|
|
63
|
+
if (seedAdapters.length) {
|
|
64
|
+
await pgsql_test_1.seed.compose(seedAdapters).seed({
|
|
65
|
+
connect: cn.db ?? {},
|
|
66
|
+
admin: undefined, // unused by the PGlite-safe adapters
|
|
67
|
+
config,
|
|
68
|
+
pg
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const teardown = async () => {
|
|
72
|
+
(0, pgsql_client_1.registerPgClientFactory)(previousClientFactory);
|
|
73
|
+
await pg.close();
|
|
74
|
+
await db.close();
|
|
75
|
+
await handle.close();
|
|
76
|
+
};
|
|
77
|
+
return { pg, db, instance: handle.db, teardown };
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
// Setup failed after registering the seams โ unwind so a broken suite
|
|
81
|
+
// doesn't leak factories/instance into the next one.
|
|
82
|
+
(0, pgsql_client_1.registerPgClientFactory)(previousClientFactory);
|
|
83
|
+
await handle.close();
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
exports.getConnections = getConnections;
|
|
88
|
+
var txn_2 = require("./txn");
|
|
89
|
+
Object.defineProperty(exports, "PgliteTestClient", { enumerable: true, get: function () { return txn_2.PgliteTestClient; } });
|
|
90
|
+
Object.defineProperty(exports, "SharedTxn", { enumerable: true, get: function () { return txn_2.SharedTxn; } });
|
|
91
|
+
var pgsql_test_2 = require("pgsql-test");
|
|
92
|
+
Object.defineProperty(exports, "PgTestClient", { enumerable: true, get: function () { return pgsql_test_2.PgTestClient; } });
|
|
93
|
+
Object.defineProperty(exports, "seed", { enumerable: true, get: function () { return pgsql_test_2.seed; } });
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pglite-test",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"author": "Constructive <developers@constructive.io>",
|
|
5
|
+
"description": "Drop-in pgsql-test getConnections backed by an in-process PGlite instance โ no Postgres server, instance-per-suite isolation",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/constructive",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/constructive"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/constructive/issues"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"postgres",
|
|
24
|
+
"postgresql",
|
|
25
|
+
"pglite",
|
|
26
|
+
"wasm",
|
|
27
|
+
"testing",
|
|
28
|
+
"integration-tests",
|
|
29
|
+
"database-testing",
|
|
30
|
+
"rls",
|
|
31
|
+
"pgsql-test",
|
|
32
|
+
"jest"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"clean": "makage clean",
|
|
36
|
+
"prepack": "npm run build",
|
|
37
|
+
"build": "makage build",
|
|
38
|
+
"build:dev": "makage build --dev",
|
|
39
|
+
"lint": "eslint . --fix",
|
|
40
|
+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests",
|
|
41
|
+
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@electric-sql/pglite": "0.5.4",
|
|
45
|
+
"@types/pg": "^8.20.0",
|
|
46
|
+
"makage": "^0.3.0"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@pgpmjs/env": "^2.26.1",
|
|
50
|
+
"@pgpmjs/pglite-adapter": "^0.1.0",
|
|
51
|
+
"pg-cache": "^3.14.0",
|
|
52
|
+
"pg-env": "^1.17.0",
|
|
53
|
+
"pgsql-client": "^3.20.0",
|
|
54
|
+
"pgsql-test": "^4.18.3"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@electric-sql/pglite": ">=0.5.0"
|
|
58
|
+
},
|
|
59
|
+
"gitHead": "7cbe15fac21a9345b169203ba9542ba9a50c866c"
|
|
60
|
+
}
|
package/txn.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { PgConfig } from 'pg-env';
|
|
2
|
+
import { PgTestClient, PgTestClientOpts } from 'pgsql-test';
|
|
3
|
+
/**
|
|
4
|
+
* Coordinates transaction control across the `pg` and `db` clients when they
|
|
5
|
+
* share ONE PGlite session.
|
|
6
|
+
*
|
|
7
|
+
* On a real Postgres server `pg` and `db` are independent connections, each with
|
|
8
|
+
* its own transaction, so the standard harness opens a `BEGIN`+`SAVEPOINT` on
|
|
9
|
+
* both. PGlite is a single in-process session, so a second `BEGIN` is a no-op
|
|
10
|
+
* and a `ROLLBACK TO SAVEPOINT` after the other client's `COMMIT` errors.
|
|
11
|
+
*
|
|
12
|
+
* This coordinator ref-counts the shared depth so exactly one `BEGIN`, one
|
|
13
|
+
* outer `SAVEPOINT`, one `ROLLBACK TO SAVEPOINT` and one `COMMIT` run per test โ
|
|
14
|
+
* regardless of whether the caller drives one client or both. It works for the
|
|
15
|
+
* common orderings:
|
|
16
|
+
* beforeEach: pg.beforeEach(); db.beforeEach();
|
|
17
|
+
* afterEach: db.afterEach(); pg.afterEach();
|
|
18
|
+
* and for the single-client pattern (`db` only).
|
|
19
|
+
*/
|
|
20
|
+
export declare class SharedTxn {
|
|
21
|
+
private depth;
|
|
22
|
+
/** True only for the outermost `begin()` (the one that should emit BEGIN). */
|
|
23
|
+
beginNeeded(): boolean;
|
|
24
|
+
/** True only for the outermost `commit()` (the one that should emit COMMIT). */
|
|
25
|
+
commitNeeded(): boolean;
|
|
26
|
+
/** True while exactly one transaction level is open (the outer savepoint scope). */
|
|
27
|
+
atOuter(): boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `PgTestClient` whose transaction control is routed through a `SharedTxn`, so
|
|
31
|
+
* two clients over one PGlite session don't double-`BEGIN` or over-`COMMIT`.
|
|
32
|
+
* Everything else (query, setContext, auth, loadSql, ...) is inherited verbatim.
|
|
33
|
+
*/
|
|
34
|
+
export declare class PgliteTestClient extends PgTestClient {
|
|
35
|
+
private txn;
|
|
36
|
+
constructor(config: PgConfig, opts: PgTestClientOpts, txn: SharedTxn);
|
|
37
|
+
begin(): Promise<void>;
|
|
38
|
+
savepoint(name?: string): Promise<void>;
|
|
39
|
+
rollback(name?: string): Promise<void>;
|
|
40
|
+
commit(): Promise<void>;
|
|
41
|
+
}
|
package/txn.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PgliteTestClient = exports.SharedTxn = void 0;
|
|
4
|
+
const pgsql_test_1 = require("pgsql-test");
|
|
5
|
+
/**
|
|
6
|
+
* Coordinates transaction control across the `pg` and `db` clients when they
|
|
7
|
+
* share ONE PGlite session.
|
|
8
|
+
*
|
|
9
|
+
* On a real Postgres server `pg` and `db` are independent connections, each with
|
|
10
|
+
* its own transaction, so the standard harness opens a `BEGIN`+`SAVEPOINT` on
|
|
11
|
+
* both. PGlite is a single in-process session, so a second `BEGIN` is a no-op
|
|
12
|
+
* and a `ROLLBACK TO SAVEPOINT` after the other client's `COMMIT` errors.
|
|
13
|
+
*
|
|
14
|
+
* This coordinator ref-counts the shared depth so exactly one `BEGIN`, one
|
|
15
|
+
* outer `SAVEPOINT`, one `ROLLBACK TO SAVEPOINT` and one `COMMIT` run per test โ
|
|
16
|
+
* regardless of whether the caller drives one client or both. It works for the
|
|
17
|
+
* common orderings:
|
|
18
|
+
* beforeEach: pg.beforeEach(); db.beforeEach();
|
|
19
|
+
* afterEach: db.afterEach(); pg.afterEach();
|
|
20
|
+
* and for the single-client pattern (`db` only).
|
|
21
|
+
*/
|
|
22
|
+
class SharedTxn {
|
|
23
|
+
depth = 0;
|
|
24
|
+
/** True only for the outermost `begin()` (the one that should emit BEGIN). */
|
|
25
|
+
beginNeeded() {
|
|
26
|
+
return this.depth++ === 0;
|
|
27
|
+
}
|
|
28
|
+
/** True only for the outermost `commit()` (the one that should emit COMMIT). */
|
|
29
|
+
commitNeeded() {
|
|
30
|
+
return --this.depth === 0;
|
|
31
|
+
}
|
|
32
|
+
/** True while exactly one transaction level is open (the outer savepoint scope). */
|
|
33
|
+
atOuter() {
|
|
34
|
+
return this.depth === 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.SharedTxn = SharedTxn;
|
|
38
|
+
/**
|
|
39
|
+
* `PgTestClient` whose transaction control is routed through a `SharedTxn`, so
|
|
40
|
+
* two clients over one PGlite session don't double-`BEGIN` or over-`COMMIT`.
|
|
41
|
+
* Everything else (query, setContext, auth, loadSql, ...) is inherited verbatim.
|
|
42
|
+
*/
|
|
43
|
+
class PgliteTestClient extends pgsql_test_1.PgTestClient {
|
|
44
|
+
txn;
|
|
45
|
+
constructor(config, opts, txn) {
|
|
46
|
+
super(config, opts);
|
|
47
|
+
this.txn = txn;
|
|
48
|
+
}
|
|
49
|
+
async begin() {
|
|
50
|
+
if (this.txn.beginNeeded())
|
|
51
|
+
await super.begin();
|
|
52
|
+
}
|
|
53
|
+
async savepoint(name) {
|
|
54
|
+
if (this.txn.atOuter())
|
|
55
|
+
await super.savepoint(name);
|
|
56
|
+
}
|
|
57
|
+
async rollback(name) {
|
|
58
|
+
if (this.txn.atOuter())
|
|
59
|
+
await super.rollback(name);
|
|
60
|
+
}
|
|
61
|
+
async commit() {
|
|
62
|
+
if (this.txn.commitNeeded())
|
|
63
|
+
await super.commit();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
exports.PgliteTestClient = PgliteTestClient;
|