@ingram-tech/nk-db 1.6.0 → 2.0.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/README.md +76 -22
- package/dist/id-drizzle.d.ts +47 -31
- package/dist/id-drizzle.d.ts.map +1 -1
- package/dist/id-drizzle.js +5 -2
- package/dist/id-drizzle.js.map +1 -1
- package/dist/id-sql.d.ts +8 -0
- package/dist/id-sql.d.ts.map +1 -0
- package/dist/id-sql.js +31 -0
- package/dist/id-sql.js.map +1 -0
- package/dist/pglite/index.d.ts +8 -0
- package/dist/pglite/index.d.ts.map +1 -1
- package/dist/pglite/index.js +3 -0
- package/dist/pglite/index.js.map +1 -1
- package/package.json +11 -4
- package/src/coerce.ts +50 -0
- package/src/drizzle.ts +51 -0
- package/src/errors.ts +35 -0
- package/src/id-drizzle.ts +130 -0
- package/src/id-sql.ts +32 -0
- package/src/id.ts +21 -0
- package/src/index.ts +27 -0
- package/src/keys.ts +78 -0
- package/src/migrate-bin.ts +87 -0
- package/src/migrate.ts +454 -0
- package/src/pglite/dev.ts +63 -0
- package/src/pglite/index.ts +255 -0
- package/src/pglite/reset.ts +31 -0
- package/src/pool.ts +148 -0
- package/src/queries.ts +244 -0
- package/src/rls.ts +90 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// PGlite dev/test harness — Postgres-in-WASM, no Docker. Ported from a proven
|
|
2
|
+
// app-level `scripts/pglite-dev.ts` (whose own comment said it should "move into
|
|
3
|
+
// the shared package so the whole fleet inherits it"). PGlite 0.5.x is
|
|
4
|
+
// PostgreSQL 18.3, so plpgsql / gen_random_uuid() / RLS all work and dev matches
|
|
5
|
+
// a pg18 prod target.
|
|
6
|
+
//
|
|
7
|
+
// This module is the only place the PGlite deps are imported; it loads solely
|
|
8
|
+
// via the "@ingram-tech/nk-db/pglite" subpath (dev/test), never from the main
|
|
9
|
+
// entry, so production bundles stay clean.
|
|
10
|
+
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { rm } from "node:fs/promises";
|
|
13
|
+
import { createServer } from "node:net";
|
|
14
|
+
import { PGlite, type Extensions } from "@electric-sql/pglite";
|
|
15
|
+
import { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
16
|
+
import { ID758_SQL } from "id758/sql";
|
|
17
|
+
import type { Pool } from "pg";
|
|
18
|
+
import { resetPublicTables } from "./reset.js";
|
|
19
|
+
|
|
20
|
+
export interface PgliteServerOptions {
|
|
21
|
+
/** Persisted data dir; omit for an in-memory database (tests). */
|
|
22
|
+
dataDir?: string;
|
|
23
|
+
/** Host to bind the TCP socket on. Default `127.0.0.1`. */
|
|
24
|
+
host?: string;
|
|
25
|
+
/** Port for the TCP socket. Default `PGLITE_PORT` env or `5432`. */
|
|
26
|
+
port?: number;
|
|
27
|
+
/** Wipe `dataDir` before booting (rebuild after adding a migration). */
|
|
28
|
+
fresh?: boolean;
|
|
29
|
+
/** Drizzle migrations folder for the default applier. Default `drizzle`. */
|
|
30
|
+
migrationsFolder?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Extra journaled migration chains to apply **before** `migrationsFolder`,
|
|
33
|
+
* in the order given — each with its own journal table so it versions
|
|
34
|
+
* independently of the app's `drizzle/` chain. Use for schema owned by a
|
|
35
|
+
* dependency that the app's own migrations then reference (e.g. `nk-auth`
|
|
36
|
+
* ships its auth tables this way, and app tables FK to `user`). Applying
|
|
37
|
+
* these first is what makes those FKs resolve. Generic on purpose: this
|
|
38
|
+
* harness knows nothing about which package a chain belongs to — the caller
|
|
39
|
+
* (`nk dev`, a test harness) resolves the folder and names the table.
|
|
40
|
+
*/
|
|
41
|
+
dependencyMigrations?: Array<{
|
|
42
|
+
/** The chain's migrations folder (must contain `meta/_journal.json`). */
|
|
43
|
+
folder: string;
|
|
44
|
+
/** Journal table — MUST differ from other chains sharing `schema`
|
|
45
|
+
* (default `drizzle`), or the chains collide. E.g. `__nkauth_migrations`. */
|
|
46
|
+
table: string;
|
|
47
|
+
/** Journal table schema. Default `drizzle`. */
|
|
48
|
+
schema?: string;
|
|
49
|
+
}>;
|
|
50
|
+
/**
|
|
51
|
+
* Install the id codec's Postgres functions (`id758_encode` / `id758_decode`,
|
|
52
|
+
* see `@ingram-tech/nk-db/id/sql`) before any migration runs. Default `true`:
|
|
53
|
+
* the script is idempotent and costs nothing, and having it in dev/test means
|
|
54
|
+
* a query can use the functions before — or without — the site journaling
|
|
55
|
+
* them. Set `false` to boot exactly what the migrations declare.
|
|
56
|
+
*/
|
|
57
|
+
id758?: boolean;
|
|
58
|
+
/** Override how the primary `migrationsFolder` is applied (e.g. raw-SQL apps).
|
|
59
|
+
* `dependencyMigrations` still run first, before this. */
|
|
60
|
+
migrate?: (db: PGlite) => Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* PGlite contrib/extension modules to register at create time — e.g.
|
|
63
|
+
* `{ pg_trgm }` from `@electric-sql/pglite/contrib/pg_trgm` or `{ vector }`
|
|
64
|
+
* from `@electric-sql/pglite/vector`. Required when your migrations
|
|
65
|
+
* `CREATE EXTENSION` them: PGlite only knows the extensions passed here.
|
|
66
|
+
*/
|
|
67
|
+
extensions?: Extensions;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface PgliteServer {
|
|
71
|
+
db: PGlite;
|
|
72
|
+
server: PGLiteSocketServer;
|
|
73
|
+
/** Connection string the app's `pg.Pool` should use. */
|
|
74
|
+
databaseUrl: string;
|
|
75
|
+
stop: () => Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Ask the OS for a currently-free TCP port (bind :0, read it back, release).
|
|
79
|
+
* Used so the test harness never collides with a dev Postgres on 5432. */
|
|
80
|
+
const freePort = (host: string): Promise<number> =>
|
|
81
|
+
new Promise((resolve, reject) => {
|
|
82
|
+
const srv = createServer();
|
|
83
|
+
srv.once("error", reject);
|
|
84
|
+
srv.listen(0, host, () => {
|
|
85
|
+
const addr = srv.address();
|
|
86
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
87
|
+
srv.close((err) => (err ? reject(err) : resolve(port)));
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const defaultMigrate =
|
|
92
|
+
(migrationsFolder: string) =>
|
|
93
|
+
async (db: PGlite): Promise<void> => {
|
|
94
|
+
const { drizzle } = await import("drizzle-orm/pglite");
|
|
95
|
+
const { migrate } = await import("drizzle-orm/pglite/migrator");
|
|
96
|
+
await migrate(drizzle(db), { migrationsFolder });
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** Apply each dependency chain in order, before the app's own migrations. Each
|
|
100
|
+
* gets its own journal table so it tracks independently (see
|
|
101
|
+
* {@link PgliteServerOptions.dependencyMigrations}). */
|
|
102
|
+
const applyDependencyMigrations = async (
|
|
103
|
+
db: PGlite,
|
|
104
|
+
chains: NonNullable<PgliteServerOptions["dependencyMigrations"]>,
|
|
105
|
+
): Promise<void> => {
|
|
106
|
+
if (chains.length === 0) return;
|
|
107
|
+
const { drizzle } = await import("drizzle-orm/pglite");
|
|
108
|
+
const { migrate } = await import("drizzle-orm/pglite/migrator");
|
|
109
|
+
const orm = drizzle(db);
|
|
110
|
+
for (const chain of chains) {
|
|
111
|
+
await migrate(orm, {
|
|
112
|
+
migrationsFolder: chain.folder,
|
|
113
|
+
migrationsTable: chain.table,
|
|
114
|
+
migrationsSchema: chain.schema ?? "drizzle",
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Boot PGlite, apply migrations (on a fresh/in-memory db), and expose it over a
|
|
121
|
+
* TCP socket so a normal `pg.Pool` connects via `DATABASE_URL` with no app code
|
|
122
|
+
* changes. Reused by both `startPgliteDev` (persisted) and `createTestDb`
|
|
123
|
+
* (in-memory). The socket server is single-connection — keep the consuming pool
|
|
124
|
+
* at `max: 1` (createPool does this for local hosts).
|
|
125
|
+
*/
|
|
126
|
+
export const createPgliteServer = async (
|
|
127
|
+
options: PgliteServerOptions = {},
|
|
128
|
+
): Promise<PgliteServer> => {
|
|
129
|
+
const host = options.host ?? "127.0.0.1";
|
|
130
|
+
const envPort = Number(process.env.PGLITE_PORT ?? 5432);
|
|
131
|
+
if (!Number.isInteger(envPort) || envPort < 0 || envPort > 65535) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`@ingram-tech/nk-db: invalid PGLITE_PORT "${process.env.PGLITE_PORT}"`,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
const port = options.port ?? envPort;
|
|
137
|
+
const migrationsFolder = options.migrationsFolder ?? "drizzle";
|
|
138
|
+
const { dataDir } = options;
|
|
139
|
+
|
|
140
|
+
if (options.fresh && dataDir && existsSync(dataDir)) {
|
|
141
|
+
await rm(dataDir, { recursive: true, force: true });
|
|
142
|
+
}
|
|
143
|
+
const db = dataDir
|
|
144
|
+
? await PGlite.create({ dataDir, extensions: options.extensions })
|
|
145
|
+
: await PGlite.create({ extensions: options.extensions });
|
|
146
|
+
// Always run migrations: the drizzle migrator is journal-tracked, so on an
|
|
147
|
+
// existing dataDir this applies only what's new (previously it was skipped
|
|
148
|
+
// entirely whenever the dir existed, silently ignoring added migrations
|
|
149
|
+
// until a --fresh wipe). A custom `migrate` must be idempotent the same way.
|
|
150
|
+
// Dependency chains (e.g. nk-auth's tables) go first so the app's own
|
|
151
|
+
// migrations can reference them by FK.
|
|
152
|
+
if (options.id758 !== false) await db.exec(ID758_SQL);
|
|
153
|
+
await applyDependencyMigrations(db, options.dependencyMigrations ?? []);
|
|
154
|
+
await (options.migrate ?? defaultMigrate(migrationsFolder))(db);
|
|
155
|
+
|
|
156
|
+
const server = new PGLiteSocketServer({ db, host, port });
|
|
157
|
+
await server.start();
|
|
158
|
+
const databaseUrl = `postgresql://postgres:postgres@${host}:${port}/postgres`;
|
|
159
|
+
const stop = async (): Promise<void> => {
|
|
160
|
+
await server.stop().catch(() => {});
|
|
161
|
+
await db.close().catch(() => {});
|
|
162
|
+
};
|
|
163
|
+
return { db, server, databaseUrl, stop };
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* `nk dev`'s PGlite mode: boot a persisted local Postgres, then `next dev` with
|
|
168
|
+
* `DATABASE_URL` pointed at it. Invoked by the `nk-pglite-dev` bin.
|
|
169
|
+
*/
|
|
170
|
+
export const startPgliteDev = async (
|
|
171
|
+
options: PgliteServerOptions & { nextArgs?: string[] } = {},
|
|
172
|
+
): Promise<void> => {
|
|
173
|
+
const { spawn } = await import("node:child_process");
|
|
174
|
+
const { databaseUrl, stop } = await createPgliteServer({
|
|
175
|
+
dataDir: options.dataDir ?? ".pglite",
|
|
176
|
+
...options,
|
|
177
|
+
});
|
|
178
|
+
console.log(
|
|
179
|
+
`nk(pglite): Postgres 18 (WASM) ready on ${databaseUrl} — no Docker, no external service`,
|
|
180
|
+
);
|
|
181
|
+
|
|
182
|
+
const child = spawn(
|
|
183
|
+
"bun",
|
|
184
|
+
["x", "next", "dev", "--turbopack", ...(options.nextArgs ?? [])],
|
|
185
|
+
{ stdio: "inherit", env: { ...process.env, DATABASE_URL: databaseUrl } },
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
let closing = false;
|
|
189
|
+
const close = async (code: number): Promise<void> => {
|
|
190
|
+
if (closing) return;
|
|
191
|
+
closing = true;
|
|
192
|
+
await stop();
|
|
193
|
+
process.exit(code);
|
|
194
|
+
};
|
|
195
|
+
process.on("SIGINT", () => child.kill("SIGINT"));
|
|
196
|
+
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
|
197
|
+
child.on("exit", (code) => void close(code ?? 0));
|
|
198
|
+
// Without this, a failed spawn (e.g. bun missing) is an uncaught exception
|
|
199
|
+
// and the socket server never shuts down.
|
|
200
|
+
child.on("error", (err) => {
|
|
201
|
+
console.error(`nk(pglite): failed to start next dev: ${err.message}`);
|
|
202
|
+
void close(1);
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
export interface TestDb {
|
|
207
|
+
/** A `pg.Pool` (max:1) bound to the in-memory database over the socket. */
|
|
208
|
+
pool: Pool;
|
|
209
|
+
databaseUrl: string;
|
|
210
|
+
/** TRUNCATE every public table — call in Vitest `beforeEach`. */
|
|
211
|
+
reset: () => Promise<void>;
|
|
212
|
+
/** Close the pool and the database — call in `afterAll`. */
|
|
213
|
+
close: () => Promise<void>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* An in-memory PGlite for integration tests. Real Postgres semantics, instant,
|
|
218
|
+
* no cleanup. Run with Vitest `fileParallelism: false` (the socket is
|
|
219
|
+
* single-connection) and close in `afterAll` (modules are isolated per file).
|
|
220
|
+
*
|
|
221
|
+
* Transport note: this harness is socket + `pg.Pool`, which is what a Next site
|
|
222
|
+
* dialing `DATABASE_URL` wants — but that single-connection socket is also why it
|
|
223
|
+
* needs serial files. A pure in-process Drizzle/PGlite harness (no socket) runs
|
|
224
|
+
* files in parallel and is faster, which is what an actual service reached for.
|
|
225
|
+
* Both share `resetPublicTables`. If a second in-process consumer appears, the
|
|
226
|
+
* move is to promote an in-process harness to first-class here, not to bolt one
|
|
227
|
+
* beside this socket default.
|
|
228
|
+
*
|
|
229
|
+
* Port: unlike `startPgliteDev` (which wants the stable 5432 the app dials),
|
|
230
|
+
* tests reach the db through the returned `pool`/`databaseUrl`, so the socket
|
|
231
|
+
* port is irrelevant — it defaults to an **ephemeral free port** so the harness
|
|
232
|
+
* never collides with a developer's real Postgres on 5432 (the EADDRINUSE that
|
|
233
|
+
* otherwise kills the suite). An explicit `port` option or `PGLITE_PORT` still
|
|
234
|
+
* wins.
|
|
235
|
+
*/
|
|
236
|
+
export const createTestDb = async (
|
|
237
|
+
options: PgliteServerOptions = {},
|
|
238
|
+
): Promise<TestDb> => {
|
|
239
|
+
const { Pool } = await import("pg");
|
|
240
|
+
const host = options.host ?? "127.0.0.1";
|
|
241
|
+
const port =
|
|
242
|
+
options.port ??
|
|
243
|
+
(process.env.PGLITE_PORT
|
|
244
|
+
? Number(process.env.PGLITE_PORT)
|
|
245
|
+
: await freePort(host));
|
|
246
|
+
const { databaseUrl, stop } = await createPgliteServer({ ...options, host, port });
|
|
247
|
+
const pool = new Pool({ connectionString: databaseUrl, max: 1 });
|
|
248
|
+
const reset = (): Promise<void> =>
|
|
249
|
+
resetPublicTables((sql) => pool.query<{ tablename: string }>(sql));
|
|
250
|
+
const close = async (): Promise<void> => {
|
|
251
|
+
await pool.end();
|
|
252
|
+
await stop();
|
|
253
|
+
};
|
|
254
|
+
return { pool, databaseUrl, reset, close };
|
|
255
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Reset a PGlite/Postgres test database to empty between tests — the canonical
|
|
2
|
+
// "introspect public tables, then TRUNCATE … RESTART IDENTITY CASCADE" unit,
|
|
3
|
+
// kept transport-agnostic so the socket-backed `createTestDb` and any in-process
|
|
4
|
+
// Drizzle/PGlite harness share one implementation instead of each re-deriving the
|
|
5
|
+
// SQL (and the easy-to-forget empty-list guard) and drifting apart.
|
|
6
|
+
//
|
|
7
|
+
// Deliberately zero imports: this loads via the dedicated
|
|
8
|
+
// "@ingram-tech/nk-db/pglite/reset" subpath, so an in-process consumer gets the
|
|
9
|
+
// reset logic WITHOUT dragging in PGlite or the PGLiteSocketServer that
|
|
10
|
+
// `./index.ts` imports at the top level.
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A row-returning query — `pg.Pool.query`, raw PGlite `.query`, etc. The
|
|
14
|
+
* `pg_tables` introspection reads rows back, so this can't be a fire-and-forget
|
|
15
|
+
* `exec(sql)`: the contract has to surface `{ rows }`.
|
|
16
|
+
*/
|
|
17
|
+
export type Queryable = (sql: string) => Promise<{ rows: { tablename: string }[] }>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* TRUNCATE every table in the `public` schema, resetting identity sequences.
|
|
21
|
+
* Call in a Vitest `beforeEach`. No-op when the schema is empty (e.g. before
|
|
22
|
+
* migrations have run), so it's safe to call unconditionally.
|
|
23
|
+
*/
|
|
24
|
+
export async function resetPublicTables(query: Queryable): Promise<void> {
|
|
25
|
+
const { rows } = await query(
|
|
26
|
+
"select tablename from pg_tables where schemaname = 'public'",
|
|
27
|
+
);
|
|
28
|
+
if (rows.length === 0) return;
|
|
29
|
+
const list = rows.map((row) => `"${row.tablename.replace(/"/g, '""')}"`).join(", ");
|
|
30
|
+
await query(`truncate table ${list} restart identity cascade`);
|
|
31
|
+
}
|
package/src/pool.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { Pool, type PoolConfig } from "pg";
|
|
2
|
+
import { dbEnv, getDatabaseUrl } from "./keys.js";
|
|
3
|
+
|
|
4
|
+
export interface CreatePoolConfig {
|
|
5
|
+
/** Override the resolved connection string (defaults to the env contract). */
|
|
6
|
+
connectionString?: string;
|
|
7
|
+
/** PEM CA cert; when set, the server cert + hostname are verified. */
|
|
8
|
+
caCert?: string;
|
|
9
|
+
/** Pool size cap. Defaults to env DATABASE_POOL_MAX, or 1 for a local socket. */
|
|
10
|
+
max?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
14
|
+
|
|
15
|
+
const isLocal = (connectionString: string): boolean => {
|
|
16
|
+
// Parse the URL: a substring check would misclassify a remote URL whose
|
|
17
|
+
// password or database name happens to contain "localhost".
|
|
18
|
+
try {
|
|
19
|
+
return LOCAL_HOSTS.has(new URL(connectionString).hostname);
|
|
20
|
+
} catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Un-escape a PEM CA cert that arrived with literal `\n` instead of real
|
|
27
|
+
* newlines. A multiline secret survives intact in the app's runtime env (e.g.
|
|
28
|
+
* Vercel hands `process.env.DATABASE_CA_CERT` back with real newlines), but
|
|
29
|
+
* `vercel env pull` — and most `.env` serializers — collapse it to a single
|
|
30
|
+
* quoted line with `\n` escapes. A caller that then sources that file (the
|
|
31
|
+
* `nk-pg-migrate` runner, a CI job) gets the literal-`\n` form, which OpenSSL
|
|
32
|
+
* rejects with "self-signed certificate in certificate chain" even though the
|
|
33
|
+
* deployed app verifies the very same cert fine. Normalise here, the one place
|
|
34
|
+
* the cert reaches `pg`, so every caller gets verify-full regardless of how the
|
|
35
|
+
* env was loaded. A correctly-newlined PEM contains no literal `\n`, so this is
|
|
36
|
+
* a no-op there — idempotent and safe (base64 + the BEGIN/END lines never
|
|
37
|
+
* contain a backslash).
|
|
38
|
+
*/
|
|
39
|
+
export const normalizeCaCert = (caCert: string | undefined): string | undefined =>
|
|
40
|
+
caCert?.includes("\\n") ? caCert.replace(/\\n/g, "\n") : caCert;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The one shared `pg.Pool`. Reuse this for everything — app queries (via
|
|
44
|
+
* `createQueries` / Drizzle) AND Better Auth's adapter — so there's exactly one
|
|
45
|
+
* pool per process (the playbook's rule).
|
|
46
|
+
*
|
|
47
|
+
* TLS handling matches the fleet standard (lifted from nk-auth's
|
|
48
|
+
* `createAuthPool`):
|
|
49
|
+
*
|
|
50
|
+
* - `caCert` set -> verify the server cert + hostname (`sslmode=verify-full`).
|
|
51
|
+
* - local host -> no TLS, and cap at `max: 1` (the PGlite socket server is
|
|
52
|
+
* single-connection/multiplexed; a larger pool breaks dev).
|
|
53
|
+
* - otherwise -> TLS **without** chain verification. Managed certs (e.g.
|
|
54
|
+
* DigitalOcean) aren't in Node's trust store, so full
|
|
55
|
+
* verification fails with "self-signed certificate in
|
|
56
|
+
* certificate chain"; the link is still encrypted. `sslmode`
|
|
57
|
+
* is stripped from the URL because `pg` ignores the `ssl`
|
|
58
|
+
* object when the URL carries SSL settings.
|
|
59
|
+
*
|
|
60
|
+
* On Vercel Fluid / serverless, hold the pool on `globalThis` so warm
|
|
61
|
+
* invocations reuse it instead of opening a connection per request (see the
|
|
62
|
+
* app-side `src/lib/db.ts` pattern in docs/db-package.md).
|
|
63
|
+
*/
|
|
64
|
+
export const createPool = (config: CreatePoolConfig = {}): Pool => {
|
|
65
|
+
// Resolve the connection string WITHOUT throwing when it is simply absent.
|
|
66
|
+
// createPool runs at module load in every app's `lib/db`, so importing that
|
|
67
|
+
// module — and therefore `next build` collecting page data, a unit test, or
|
|
68
|
+
// a CLI tool that never queries — must stay side-effect-free. Validate the
|
|
69
|
+
// full env (which *does* throw fast on a present-but-invalid value) only once
|
|
70
|
+
// a URL is known to exist; when nothing is configured, defer the error to
|
|
71
|
+
// first use via `unconfiguredPool`.
|
|
72
|
+
const env =
|
|
73
|
+
config.connectionString !== undefined
|
|
74
|
+
? undefined
|
|
75
|
+
: getDatabaseUrl() !== undefined
|
|
76
|
+
? dbEnv()
|
|
77
|
+
: undefined;
|
|
78
|
+
const connectionString = config.connectionString ?? env?.connectionString;
|
|
79
|
+
if (!connectionString) {
|
|
80
|
+
return unconfiguredPool();
|
|
81
|
+
}
|
|
82
|
+
const caCert = normalizeCaCert(config.caCert ?? env?.caCert);
|
|
83
|
+
const local = isLocal(connectionString);
|
|
84
|
+
// Local wins over the env: a pulled .env (e.g. `vercel env pull`) carries the
|
|
85
|
+
// production DATABASE_POOL_MAX/DATABASE_CA_CERT, but the PGlite socket is
|
|
86
|
+
// single-connection and speaks no TLS — honoring them breaks dev. An explicit
|
|
87
|
+
// `config.max` in code still applies.
|
|
88
|
+
const max = config.max ?? (local ? 1 : env?.poolMax);
|
|
89
|
+
|
|
90
|
+
const base: PoolConfig = max === undefined ? {} : { max };
|
|
91
|
+
|
|
92
|
+
if (local) {
|
|
93
|
+
return new Pool({ ...base, connectionString });
|
|
94
|
+
}
|
|
95
|
+
if (caCert) {
|
|
96
|
+
return new Pool({
|
|
97
|
+
...base,
|
|
98
|
+
connectionString,
|
|
99
|
+
ssl: { ca: caCert, rejectUnauthorized: true },
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
const url = new URL(connectionString);
|
|
103
|
+
url.searchParams.delete("sslmode");
|
|
104
|
+
return new Pool({
|
|
105
|
+
...base,
|
|
106
|
+
connectionString: url.toString(),
|
|
107
|
+
ssl: { rejectUnauthorized: false },
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A pool that constructs cleanly but rejects any real operation with the clear
|
|
113
|
+
* "set DATABASE_URL" error. Returned by {@link createPool} when no connection
|
|
114
|
+
* string is configured.
|
|
115
|
+
*
|
|
116
|
+
* Constructing the pool — which happens at module load in every app's `lib/db`,
|
|
117
|
+
* and therefore during `next build`'s page-data collection and in unit tests —
|
|
118
|
+
* must not throw just because a database isn't wired up. A process that then
|
|
119
|
+
* runs a real query without a URL is genuinely misconfigured and fails fast and
|
|
120
|
+
* legibly here; the env is fixed at process start, so this is never a transient
|
|
121
|
+
* miss. `query` and `connect` are the only entry points that reach the wire
|
|
122
|
+
* (Drizzle and `createQueries` go through them), so guarding both is sufficient.
|
|
123
|
+
*
|
|
124
|
+
* The rejection is deferred to a macrotask, not returned already-rejected, so it
|
|
125
|
+
* mimics real connection I/O: an async framework that inspects the in-flight
|
|
126
|
+
* promise before it settles — e.g. Next.js partial prerendering deciding a
|
|
127
|
+
* segment is dynamic — sees a pending promise and postpones it, exactly as it
|
|
128
|
+
* would for a real (reachable or not) pool. An already-rejected promise would
|
|
129
|
+
* instead surface as a synchronous render error at build.
|
|
130
|
+
*/
|
|
131
|
+
const unconfiguredPool = (): Pool => {
|
|
132
|
+
const pool = new Pool();
|
|
133
|
+
const reject = (): Promise<never> =>
|
|
134
|
+
new Promise((_resolve, rej) => {
|
|
135
|
+
setTimeout(
|
|
136
|
+
() =>
|
|
137
|
+
rej(
|
|
138
|
+
new Error(
|
|
139
|
+
"@ingram-tech/nk-db: no database connection string — set DATABASE_URL.",
|
|
140
|
+
),
|
|
141
|
+
),
|
|
142
|
+
0,
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
pool.query = reject as typeof pool.query;
|
|
146
|
+
pool.connect = reject as typeof pool.connect;
|
|
147
|
+
return pool;
|
|
148
|
+
};
|
package/src/queries.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { Pool, PoolClient, QueryResultRow } from "pg";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import {
|
|
4
|
+
type RlsClaims,
|
|
5
|
+
type RlsOptions,
|
|
6
|
+
resolveRlsConfig,
|
|
7
|
+
rlsPreamble,
|
|
8
|
+
} from "./rls.js";
|
|
9
|
+
|
|
10
|
+
/** Anything that can run a query: a Pool, a PoolClient, or a tx scope. */
|
|
11
|
+
type Executor = Pick<Pool, "query">;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A raw result shaped like pg's `QueryResult` or Drizzle's `tx.execute()` output
|
|
15
|
+
* — just the `rows`. Consumed by {@link parseRows} / {@link parseMaybeRow} /
|
|
16
|
+
* {@link parseOneRow}, which validate that array against a Zod schema.
|
|
17
|
+
*/
|
|
18
|
+
export interface RowsResult {
|
|
19
|
+
rows: readonly unknown[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Queries {
|
|
23
|
+
/**
|
|
24
|
+
* Run a query and return all rows. Pass a Zod row `schema` as the third
|
|
25
|
+
* argument to validate (and coerce) every row instead of trusting a `<T>`
|
|
26
|
+
* cast — the schema is also where `numeric`/timestamp coercion belongs
|
|
27
|
+
* (`z.coerce.number()`, an ISO transform), per the no-`as`-on-external-input
|
|
28
|
+
* rule.
|
|
29
|
+
*/
|
|
30
|
+
query: {
|
|
31
|
+
<T extends QueryResultRow = QueryResultRow>(
|
|
32
|
+
text: string,
|
|
33
|
+
params?: unknown[],
|
|
34
|
+
): Promise<T[]>;
|
|
35
|
+
<S extends z.ZodType>(
|
|
36
|
+
text: string,
|
|
37
|
+
params: unknown[] | undefined,
|
|
38
|
+
schema: S,
|
|
39
|
+
): Promise<z.output<S>[]>;
|
|
40
|
+
};
|
|
41
|
+
/** Run a query expected to return at most one row; `null` when none. */
|
|
42
|
+
maybeOne: {
|
|
43
|
+
<T extends QueryResultRow = QueryResultRow>(
|
|
44
|
+
text: string,
|
|
45
|
+
params?: unknown[],
|
|
46
|
+
): Promise<T | null>;
|
|
47
|
+
<S extends z.ZodType>(
|
|
48
|
+
text: string,
|
|
49
|
+
params: unknown[] | undefined,
|
|
50
|
+
schema: S,
|
|
51
|
+
): Promise<z.output<S> | null>;
|
|
52
|
+
};
|
|
53
|
+
/** Run a query that must return exactly one row; throws otherwise. */
|
|
54
|
+
one: {
|
|
55
|
+
<T extends QueryResultRow = QueryResultRow>(
|
|
56
|
+
text: string,
|
|
57
|
+
params?: unknown[],
|
|
58
|
+
): Promise<T>;
|
|
59
|
+
<S extends z.ZodType>(
|
|
60
|
+
text: string,
|
|
61
|
+
params: unknown[] | undefined,
|
|
62
|
+
schema: S,
|
|
63
|
+
): Promise<z.output<S>>;
|
|
64
|
+
};
|
|
65
|
+
/** Run a write and return the affected row count. */
|
|
66
|
+
execute: (text: string, params?: unknown[]) => Promise<number>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const bind = (executor: Executor): Queries => {
|
|
70
|
+
function query<T extends QueryResultRow = QueryResultRow>(
|
|
71
|
+
text: string,
|
|
72
|
+
params?: unknown[],
|
|
73
|
+
): Promise<T[]>;
|
|
74
|
+
function query<S extends z.ZodType>(
|
|
75
|
+
text: string,
|
|
76
|
+
params: unknown[] | undefined,
|
|
77
|
+
schema: S,
|
|
78
|
+
): Promise<z.output<S>[]>;
|
|
79
|
+
async function query(
|
|
80
|
+
text: string,
|
|
81
|
+
params: unknown[] = [],
|
|
82
|
+
schema?: z.ZodType,
|
|
83
|
+
): Promise<unknown[]> {
|
|
84
|
+
const result = await executor.query(text, params);
|
|
85
|
+
return schema ? result.rows.map((row) => schema.parse(row)) : result.rows;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function maybeOne<T extends QueryResultRow = QueryResultRow>(
|
|
89
|
+
text: string,
|
|
90
|
+
params?: unknown[],
|
|
91
|
+
): Promise<T | null>;
|
|
92
|
+
function maybeOne<S extends z.ZodType>(
|
|
93
|
+
text: string,
|
|
94
|
+
params: unknown[] | undefined,
|
|
95
|
+
schema: S,
|
|
96
|
+
): Promise<z.output<S> | null>;
|
|
97
|
+
async function maybeOne(
|
|
98
|
+
text: string,
|
|
99
|
+
params: unknown[] = [],
|
|
100
|
+
schema?: z.ZodType,
|
|
101
|
+
): Promise<unknown> {
|
|
102
|
+
const result = await executor.query(text, params);
|
|
103
|
+
const first = result.rows[0];
|
|
104
|
+
if (first === undefined) return null;
|
|
105
|
+
return schema ? schema.parse(first) : first;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function one<T extends QueryResultRow = QueryResultRow>(
|
|
109
|
+
text: string,
|
|
110
|
+
params?: unknown[],
|
|
111
|
+
): Promise<T>;
|
|
112
|
+
function one<S extends z.ZodType>(
|
|
113
|
+
text: string,
|
|
114
|
+
params: unknown[] | undefined,
|
|
115
|
+
schema: S,
|
|
116
|
+
): Promise<z.output<S>>;
|
|
117
|
+
async function one(
|
|
118
|
+
text: string,
|
|
119
|
+
params: unknown[] = [],
|
|
120
|
+
schema?: z.ZodType,
|
|
121
|
+
): Promise<unknown> {
|
|
122
|
+
const result = await executor.query(text, params);
|
|
123
|
+
if (result.rows.length === 0) {
|
|
124
|
+
throw new Error("Expected exactly one row, got none");
|
|
125
|
+
}
|
|
126
|
+
if (result.rows.length > 1) {
|
|
127
|
+
throw new Error(`Expected exactly one row, got ${result.rows.length}`);
|
|
128
|
+
}
|
|
129
|
+
const row = result.rows[0];
|
|
130
|
+
return schema ? schema.parse(row) : row;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const execute = async (text: string, params: unknown[] = []): Promise<number> => {
|
|
134
|
+
const result = await executor.query(text, params);
|
|
135
|
+
return result.rowCount ?? 0;
|
|
136
|
+
};
|
|
137
|
+
return { query, maybeOne, one, execute };
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Validate the `rows` of a raw result (a pg `QueryResult` or the output of
|
|
142
|
+
* Drizzle's `tx.execute()`) against a Zod row schema, returning the parsed rows.
|
|
143
|
+
*
|
|
144
|
+
* This is the result-side counterpart to {@link Queries.query}'s `schema` arg,
|
|
145
|
+
* for the Drizzle RLS path: inside `withRlsTransaction`, `tx.execute()` hands
|
|
146
|
+
* back an untyped `{ rows }`, and this gives it the same validated/coerced
|
|
147
|
+
* result the pool helpers have. The schema doubles as the coercion layer.
|
|
148
|
+
*/
|
|
149
|
+
export const parseRows = <S extends z.ZodType>(
|
|
150
|
+
result: RowsResult,
|
|
151
|
+
schema: S,
|
|
152
|
+
): z.output<S>[] => result.rows.map((row) => schema.parse(row));
|
|
153
|
+
|
|
154
|
+
/** Like {@link parseRows} but for at most one row; `null` when none. */
|
|
155
|
+
export const parseMaybeRow = <S extends z.ZodType>(
|
|
156
|
+
result: RowsResult,
|
|
157
|
+
schema: S,
|
|
158
|
+
): z.output<S> | null => {
|
|
159
|
+
const first = result.rows[0];
|
|
160
|
+
return first === undefined ? null : schema.parse(first);
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/** Like {@link parseRows} but requires exactly one row; throws otherwise. */
|
|
164
|
+
export const parseOneRow = <S extends z.ZodType>(
|
|
165
|
+
result: RowsResult,
|
|
166
|
+
schema: S,
|
|
167
|
+
): z.output<S> => {
|
|
168
|
+
if (result.rows.length === 0) {
|
|
169
|
+
throw new Error("Expected exactly one row, got none");
|
|
170
|
+
}
|
|
171
|
+
if (result.rows.length > 1) {
|
|
172
|
+
throw new Error(`Expected exactly one row, got ${result.rows.length}`);
|
|
173
|
+
}
|
|
174
|
+
return schema.parse(result.rows[0]);
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export interface PoolQueries extends Queries {
|
|
178
|
+
/**
|
|
179
|
+
* Run `fn` inside a single transaction on a dedicated client (`begin` /
|
|
180
|
+
* `commit`, `rollback` on throw). The `tx` passed to `fn` is a `Queries`
|
|
181
|
+
* bound to that client — use it, not the pool-level helpers, for the
|
|
182
|
+
* statements that must be atomic.
|
|
183
|
+
*/
|
|
184
|
+
withTx: <T>(fn: (tx: Queries) => Promise<T>) => Promise<T>;
|
|
185
|
+
/**
|
|
186
|
+
* Like `withTx`, but first **scopes the transaction to a user** so RLS
|
|
187
|
+
* policies apply: it sets `request.jwt.claims` + `SET LOCAL ROLE` (default
|
|
188
|
+
* `authenticated`) before `fn`, so `auth.uid()`-style policies fire. Use this
|
|
189
|
+
* for user-facing reads/writes on a direct connection; keep `withTx` / `query`
|
|
190
|
+
* for service-role paths that should bypass RLS. The connection role must not
|
|
191
|
+
* bypass RLS for the rows touched — see `rls.ts`.
|
|
192
|
+
*/
|
|
193
|
+
withRls: <T>(
|
|
194
|
+
claims: RlsClaims,
|
|
195
|
+
fn: (tx: Queries) => Promise<T>,
|
|
196
|
+
options?: RlsOptions,
|
|
197
|
+
) => Promise<T>;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Bind the raw-SQL helpers (`query` / `one` / `maybeOne` / `execute` / `withTx`)
|
|
202
|
+
* to a pool. Signatures match what apps hand-rolled, so adopting
|
|
203
|
+
* this is a find-and-replace of the import. Drizzle (via `createDb`) is the
|
|
204
|
+
* default query path; these are the escape hatch for SQL the ORM is awkward at
|
|
205
|
+
* (Postgres-function `select fn($1,…)` calls, `pgmq` draining, `pg_trgm`).
|
|
206
|
+
*/
|
|
207
|
+
export const createQueries = (pool: Pool): PoolQueries => {
|
|
208
|
+
const base = bind(pool);
|
|
209
|
+
// One transaction runner; `setup` (if any) runs after `begin`, before `fn` —
|
|
210
|
+
// that's where withRls injects the claims/role GUCs.
|
|
211
|
+
const runTx = async <T>(
|
|
212
|
+
setup: ((client: PoolClient) => Promise<void>) | undefined,
|
|
213
|
+
fn: (tx: Queries) => Promise<T>,
|
|
214
|
+
): Promise<T> => {
|
|
215
|
+
const client: PoolClient = await pool.connect();
|
|
216
|
+
try {
|
|
217
|
+
await client.query("begin");
|
|
218
|
+
if (setup) await setup(client);
|
|
219
|
+
const result = await fn(bind(client));
|
|
220
|
+
await client.query("commit");
|
|
221
|
+
return result;
|
|
222
|
+
} catch (error) {
|
|
223
|
+
// Swallow rollback failures: if the failing query destroyed the
|
|
224
|
+
// connection, the rollback's own "Connection terminated" would mask the
|
|
225
|
+
// real error.
|
|
226
|
+
await client.query("rollback").catch(() => {});
|
|
227
|
+
throw error;
|
|
228
|
+
} finally {
|
|
229
|
+
client.release();
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const withTx = <T>(fn: (tx: Queries) => Promise<T>): Promise<T> =>
|
|
233
|
+
runTx(undefined, fn);
|
|
234
|
+
const withRls = <T>(
|
|
235
|
+
claims: RlsClaims,
|
|
236
|
+
fn: (tx: Queries) => Promise<T>,
|
|
237
|
+
options?: RlsOptions,
|
|
238
|
+
): Promise<T> =>
|
|
239
|
+
runTx(async (client) => {
|
|
240
|
+
const { text, values } = rlsPreamble(resolveRlsConfig(claims, options));
|
|
241
|
+
await client.query(text, values);
|
|
242
|
+
}, fn);
|
|
243
|
+
return { ...base, withTx, withRls };
|
|
244
|
+
};
|