@ingram-tech/nk-db 1.6.0 → 2.0.1

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/src/migrate.ts ADDED
@@ -0,0 +1,454 @@
1
+ // Migration runner with drift detection — the framework answer to three
2
+ // recurring pains with `drizzle-kit migrate`:
3
+ //
4
+ // 1. It swallows the real database error and exits 1 opaquely ("applying
5
+ // migrations..." then nothing). {@link runMigrations} uses drizzle-orm's
6
+ // own migrator, so a failing statement throws the actual Postgres error.
7
+ // 2. When a DB's migration journal drifts from the `drizzle/` files — the
8
+ // classic "built via db:push, or the 0000 baseline was regenerated" case —
9
+ // the migrator blindly replays 0000 and dies with a confusing
10
+ // `relation "..." already exists`. {@link runMigrations} runs a pre-flight
11
+ // {@link inspectMigrations} check and throws a {@link MigrationDriftError}
12
+ // that explains exactly what happened and how to fix it, and
13
+ // {@link baselineMigrations} reconciles a journal whose schema is already
14
+ // correct without re-running any DDL.
15
+ // 3. It decides what to apply by `when > max(created_at)`, so a migration
16
+ // whose journal timestamp lands below an already-applied one is skipped
17
+ // **silently, permanently, and reported as success**. {@link runMigrations}
18
+ // computes pending as a set difference on hash instead, and throws a
19
+ // {@link MigrationOrderError} rather than under-applying.
20
+ //
21
+ // This module is node-only (pg + fs + the drizzle migrator); it is NOT exported
22
+ // from the main entry, so a production bundle that only does runtime queries
23
+ // never pulls it. Reached via the "@ingram-tech/nk-db/migrate" subpath and the
24
+ // `nk-pg-migrate` bin.
25
+
26
+ import { createHash } from "node:crypto";
27
+ import { existsSync, readFileSync } from "node:fs";
28
+ import { join } from "node:path";
29
+ import type { Pool } from "pg";
30
+ import { z } from "zod";
31
+ import { isPgError } from "./errors.js";
32
+ import { type CreatePoolConfig, createPool } from "./pool.js";
33
+
34
+ /** One migration as recorded in `drizzle/meta/_journal.json` + its file hash. */
35
+ export interface MigrationFileMeta {
36
+ /** Journal position. */
37
+ idx: number;
38
+ /** Journal tag, e.g. `0003_illegal_jack_flag`. */
39
+ tag: string;
40
+ /** `sha256(fileContents)` — the exact value drizzle records, so our journal
41
+ * rows are byte-compatible with `drizzle-kit migrate`. */
42
+ hash: string;
43
+ /** The journal entry's `when` (ms epoch) — drizzle's `created_at`. */
44
+ folderMillis: number;
45
+ }
46
+
47
+ export interface MigrationsLocation {
48
+ /** Drizzle migrations folder. Default `drizzle`. */
49
+ migrationsFolder?: string;
50
+ /** Journal table name. Default `__drizzle_migrations`. */
51
+ migrationsTable?: string;
52
+ /** Journal table schema. Default `drizzle`. */
53
+ migrationsSchema?: string;
54
+ }
55
+
56
+ export type MigrateConfig = CreatePoolConfig &
57
+ MigrationsLocation & {
58
+ /** Reuse an existing pool instead of creating one from the connection
59
+ * string. The caller owns its lifecycle — it is not ended here. Pass your
60
+ * app's shared pool to avoid opening a second connection. */
61
+ pool?: Pool;
62
+ };
63
+
64
+ /** Resolve the pool to use: a caller-supplied one (left open) or a fresh one we
65
+ * own (ended on release). */
66
+ const acquire = (
67
+ config: MigrateConfig,
68
+ ): { pool: Pool; release: () => Promise<void> } => {
69
+ if (config.pool) return { pool: config.pool, release: async () => {} };
70
+ const pool = createPool(config);
71
+ return { pool, release: () => pool.end() };
72
+ };
73
+
74
+ const DEFAULTS = {
75
+ migrationsFolder: "drizzle",
76
+ migrationsTable: "__drizzle_migrations",
77
+ migrationsSchema: "drizzle",
78
+ } as const;
79
+
80
+ const journalSchema = z.object({
81
+ entries: z.array(z.object({ idx: z.number(), when: z.number(), tag: z.string() })),
82
+ });
83
+
84
+ /**
85
+ * Read `meta/_journal.json` + each `.sql` and compute the per-file hash the same
86
+ * way drizzle does (`sha256` of the raw file). Decoupled from drizzle's internal
87
+ * `readMigrationFiles` so we also keep the human-readable tag.
88
+ */
89
+ export const readJournal = (
90
+ migrationsFolder: string = DEFAULTS.migrationsFolder,
91
+ ): MigrationFileMeta[] => {
92
+ const journalPath = join(migrationsFolder, "meta", "_journal.json");
93
+ if (!existsSync(journalPath)) {
94
+ throw new Error(`@ingram-tech/nk-db: no migration journal at ${journalPath}`);
95
+ }
96
+ const journal = journalSchema.parse(JSON.parse(readFileSync(journalPath, "utf8")));
97
+ return journal.entries.map((entry) => {
98
+ const sql = readFileSync(join(migrationsFolder, `${entry.tag}.sql`), "utf8");
99
+ return {
100
+ idx: entry.idx,
101
+ tag: entry.tag,
102
+ hash: createHash("sha256").update(sql).digest("hex"),
103
+ folderMillis: entry.when,
104
+ };
105
+ });
106
+ };
107
+
108
+ /**
109
+ * Journal integrity, checked on the files alone.
110
+ *
111
+ * Both properties the migrator silently depends on: drizzle decides what to
112
+ * apply by comparing `when` against the newest recorded `created_at` with a
113
+ * strict `>`, so a `when` that doesn't strictly increase down the journal marks
114
+ * a migration the migrator can never reach (see {@link MigrationOrderError}),
115
+ * and a gap or repeat in `idx` means the journal was hand-edited or merged
116
+ * badly and no longer describes one ordered chain.
117
+ */
118
+ const journalIssues = (files: MigrationFileMeta[]): string[] => {
119
+ const issues: string[] = [];
120
+ for (let i = 1; i < files.length; i++) {
121
+ const prev = files[i - 1];
122
+ const cur = files[i];
123
+ if (!prev || !cur) continue;
124
+ if (cur.folderMillis <= prev.folderMillis) {
125
+ issues.push(
126
+ `${cur.tag} has when=${cur.folderMillis}, not after ${prev.tag}'s ${prev.folderMillis}`,
127
+ );
128
+ }
129
+ }
130
+ files.forEach((f, i) => {
131
+ if (f.idx !== i)
132
+ issues.push(`${f.tag} has idx=${f.idx} at journal position ${i}`);
133
+ });
134
+ return issues;
135
+ };
136
+
137
+ /** A row of the drizzle journal table. */
138
+ export interface RecordedMigration {
139
+ hash: string;
140
+ createdAt: number;
141
+ }
142
+
143
+ export interface MigrationStatus {
144
+ /** All journal files, in order. */
145
+ files: MigrationFileMeta[];
146
+ /** Rows already in the journal table, oldest first. */
147
+ recorded: RecordedMigration[];
148
+ /** Files whose hash is not yet in the journal table — everything still to
149
+ * apply, by set difference rather than by timestamp (see {@link unreachable}). */
150
+ pending: MigrationFileMeta[];
151
+ /** Pending files drizzle's migrator will never apply because their `when`
152
+ * doesn't beat the newest recorded `created_at`. Empty on a healthy chain. */
153
+ unreachable: MigrationFileMeta[];
154
+ /** Ordering defects in `meta/_journal.json` itself (non-increasing `when`,
155
+ * gaps or repeats in `idx`). */
156
+ journalIssues: string[];
157
+ /** True when the journal table doesn't line up with the files (see {@link drift}). */
158
+ drifted: boolean;
159
+ drift?: MigrationDrift;
160
+ }
161
+
162
+ export interface MigrationDrift {
163
+ reason: string;
164
+ /** Recorded hashes that match no current file (the regenerated-baseline tell). */
165
+ recordedNotInFiles: string[];
166
+ }
167
+
168
+ const qualified = (schema: string, table: string): string =>
169
+ `"${schema.replace(/"/g, '""')}"."${table.replace(/"/g, '""')}"`;
170
+
171
+ /** The `.query` surface shared by `Pool` and a checked-out `PoolClient`, so the
172
+ * inspect path can run over the advisory-lock client in {@link runMigrations}. */
173
+ type Queryable = Pick<Pool, "query">;
174
+
175
+ /** Read the journal table; returns [] if it doesn't exist yet (fresh DB). */
176
+ const readRecorded = async (
177
+ pool: Queryable,
178
+ schema: string,
179
+ table: string,
180
+ ): Promise<RecordedMigration[]> => {
181
+ try {
182
+ const { rows } = await pool.query<{ hash: string; created_at: string }>(
183
+ `select hash, created_at from ${qualified(schema, table)} order by created_at asc`,
184
+ );
185
+ // created_at is bigint → pg returns it as a string; coerce to number (ms
186
+ // epochs fit safely in a JS number).
187
+ return rows.map((r) => ({ hash: r.hash, createdAt: Number(r.created_at) }));
188
+ } catch (err) {
189
+ // 42P01 = undefined_table → never migrated; not an error.
190
+ if (isPgError(err, "42P01")) return [];
191
+ throw err;
192
+ }
193
+ };
194
+
195
+ const detectDrift = (
196
+ files: MigrationFileMeta[],
197
+ recorded: RecordedMigration[],
198
+ ): MigrationDrift | undefined => {
199
+ const fileHashes = new Set(files.map((f) => f.hash));
200
+ const recordedNotInFiles = recorded
201
+ .map((r) => r.hash)
202
+ .filter((h) => !fileHashes.has(h));
203
+
204
+ if (recorded.length > files.length) {
205
+ return {
206
+ reason: `the journal table has ${recorded.length} recorded migration(s) but only ${files.length} file(s) exist`,
207
+ recordedNotInFiles,
208
+ };
209
+ }
210
+ // A healthy journal is exactly the first N files, in order, by hash.
211
+ for (let i = 0; i < recorded.length; i++) {
212
+ if (recorded[i]?.hash !== files[i]?.hash) {
213
+ return {
214
+ reason:
215
+ recordedNotInFiles.length > 0
216
+ ? `recorded migration #${i + 1} matches no current file — the baseline was likely regenerated, or the schema was built with db:push`
217
+ : `recorded migration #${i + 1} doesn't match file ${files[i]?.tag} (a migration file changed after it was applied)`,
218
+ recordedNotInFiles,
219
+ };
220
+ }
221
+ }
222
+ return undefined;
223
+ };
224
+
225
+ /**
226
+ * Compare the DB's migration journal to the `drizzle/` files without changing
227
+ * anything. The basis for {@link runMigrations}'s pre-flight; also useful on its
228
+ * own (a `--status` check).
229
+ */
230
+ export const inspectMigrations = async (
231
+ config: MigrateConfig = {},
232
+ ): Promise<MigrationStatus> => {
233
+ const folder = config.migrationsFolder ?? DEFAULTS.migrationsFolder;
234
+ const schema = config.migrationsSchema ?? DEFAULTS.migrationsSchema;
235
+ const table = config.migrationsTable ?? DEFAULTS.migrationsTable;
236
+ const { pool, release } = acquire(config);
237
+ try {
238
+ return await inspectWith(pool, folder, schema, table);
239
+ } finally {
240
+ await release();
241
+ }
242
+ };
243
+
244
+ const inspectWith = async (
245
+ db: Queryable,
246
+ folder: string,
247
+ schema: string,
248
+ table: string,
249
+ ): Promise<MigrationStatus> => {
250
+ const files = readJournal(folder);
251
+ const recorded = await readRecorded(db, schema, table);
252
+ const drift = detectDrift(files, recorded);
253
+ // Pending is a set difference on hash, NOT `folderMillis > max(created_at)`.
254
+ // The high-water mark is how drizzle's own migrator decides, and it is why
255
+ // `unreachable` has to be computed separately: a file below the mark whose
256
+ // hash was never recorded is not pending-and-waiting, it is pending-forever.
257
+ const appliedHashes = new Set(recorded.map((r) => r.hash));
258
+ const pending = files.filter((f) => !appliedHashes.has(f.hash));
259
+ const maxRecorded = recorded.reduce((m, r) => Math.max(m, r.createdAt), 0);
260
+ const unreachable =
261
+ recorded.length > 0 ? pending.filter((f) => f.folderMillis <= maxRecorded) : [];
262
+ return {
263
+ files,
264
+ recorded,
265
+ pending,
266
+ unreachable,
267
+ journalIssues: journalIssues(files),
268
+ drifted: Boolean(drift),
269
+ drift,
270
+ };
271
+ };
272
+
273
+ /** Thrown by {@link runMigrations} when the journal is out of sync with the
274
+ * files — applying would replay already-present DDL and fail confusingly. */
275
+ export class MigrationDriftError extends Error {
276
+ readonly status: MigrationStatus;
277
+ constructor(status: MigrationStatus) {
278
+ const d = status.drift;
279
+ super(
280
+ [
281
+ `migration journal drift: ${d?.reason ?? "journal does not match files"}.`,
282
+ d?.recordedNotInFiles.length
283
+ ? ` Recorded hashes matching no file: ${d.recordedNotInFiles.map((h) => h.slice(0, 12)).join(", ")}.`
284
+ : "",
285
+ " Fix: if this DB's schema already matches the files (e.g. built via db:push, or after regenerating the baseline), reconcile the journal with `baselineMigrations()` / `nk-pg-migrate --baseline` — it records the current file chain WITHOUT re-running DDL. Otherwise rebuild the database.",
286
+ ]
287
+ .filter(Boolean)
288
+ .join("\n"),
289
+ );
290
+ this.name = "MigrationDriftError";
291
+ this.status = status;
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Thrown by {@link runMigrations} when the chain contains a migration the
297
+ * migrator would skip **silently and permanently**.
298
+ *
299
+ * drizzle's migrator applies exactly the files whose journal `when` is greater
300
+ * than the newest `created_at` in the journal table. A file below that mark
301
+ * that was never recorded — two branches generating migrations and merging in
302
+ * the other order, or a hand-edited `when` — is not applied, is not recorded,
303
+ * and is not drift: the recorded rows still match the files positionally, so
304
+ * the pre-flight passes and the run reports success having done nothing. The
305
+ * gap then persists for the life of the database.
306
+ *
307
+ * The fix is to renumber the stranded entry's `when` in `meta/_journal.json`
308
+ * past the newest applied migration. That edits the journal, not the `.sql`, so
309
+ * the file's hash — the thing every database recorded and `nk migrations`
310
+ * seals — is untouched.
311
+ */
312
+ export class MigrationOrderError extends Error {
313
+ readonly status: MigrationStatus;
314
+ constructor(status: MigrationStatus) {
315
+ const stranded = status.unreachable.map(
316
+ (m) => `${m.tag} (when=${m.folderMillis})`,
317
+ );
318
+ const newest = status.recorded.reduce((m, r) => Math.max(m, r.createdAt), 0);
319
+ super(
320
+ [
321
+ `migration ordering: ${status.unreachable.length} unapplied migration(s) sit at or below the newest applied timestamp (${newest}), so the migrator would skip them and report success:`,
322
+ ` ${stranded.join("\n ")}`,
323
+ status.journalIssues.length
324
+ ? ` Journal defects: ${status.journalIssues.join("; ")}.`
325
+ : "",
326
+ ` Fix: raise each stranded entry's "when" in meta/_journal.json above ${newest} (and keep the journal's "when" values strictly increasing). That changes the journal, not the .sql — the file hash every database recorded stays the same.`,
327
+ ]
328
+ .filter(Boolean)
329
+ .join("\n"),
330
+ );
331
+ this.name = "MigrationOrderError";
332
+ this.status = status;
333
+ }
334
+ }
335
+
336
+ export interface MigrateResult {
337
+ /** Tags of the migrations applied by this run (empty when up to date). */
338
+ applied: string[];
339
+ }
340
+
341
+ // Advisory-lock identity for the migration runner (two arbitrary-but-stable
342
+ // int32s, `classid`/`objid`). Session-scoped on the client that runs the whole
343
+ // migration, so a crashed runner releases it with its connection.
344
+ const MIGRATE_LOCK_CLASS = 0x6e6b_6462; // "nkdb"
345
+ const MIGRATE_LOCK_ID = 1;
346
+
347
+ /**
348
+ * Apply pending migrations with the real drizzle-orm migrator. Runs a drift
349
+ * pre-flight first and throws {@link MigrationDriftError} (not a confusing
350
+ * `already exists`) when the journal is out of sync, and a
351
+ * {@link MigrationOrderError} when the chain contains a migration the migrator
352
+ * would skip silently. Surfaces the actual Postgres error on a failing
353
+ * statement.
354
+ *
355
+ * Concurrency-safe: the whole run (pre-flight + migrate) happens on one client
356
+ * holding `pg_advisory_lock`, because drizzle's migrator takes no lock of its
357
+ * own — two concurrent deploys would otherwise both see the same pending set,
358
+ * double-apply it, and leave duplicate journal rows (i.e. permanent drift).
359
+ * The second runner blocks on the lock, then sees an up-to-date journal and
360
+ * no-ops. Everything runs on that single client (not the pool) so a `max: 1`
361
+ * pool — the local PGlite case — can't deadlock against the lock holder.
362
+ */
363
+ export const runMigrations = async (
364
+ config: MigrateConfig = {},
365
+ ): Promise<MigrateResult> => {
366
+ const folder = config.migrationsFolder ?? DEFAULTS.migrationsFolder;
367
+ const schema = config.migrationsSchema ?? DEFAULTS.migrationsSchema;
368
+ const table = config.migrationsTable ?? DEFAULTS.migrationsTable;
369
+
370
+ const { pool, release } = acquire(config);
371
+ try {
372
+ const client = await pool.connect();
373
+ try {
374
+ await client.query("select pg_advisory_lock($1, $2)", [
375
+ MIGRATE_LOCK_CLASS,
376
+ MIGRATE_LOCK_ID,
377
+ ]);
378
+ const status = await inspectWith(client, folder, schema, table);
379
+ if (status.drifted) throw new MigrationDriftError(status);
380
+ // Refuse rather than silently under-apply: drizzle's migrator would
381
+ // skip these and report success. See {@link MigrationOrderError}.
382
+ if (status.unreachable.length > 0) throw new MigrationOrderError(status);
383
+ if (status.pending.length === 0) return { applied: [] };
384
+
385
+ const { drizzle } = await import("drizzle-orm/node-postgres");
386
+ const { migrate } = await import("drizzle-orm/node-postgres/migrator");
387
+ await migrate(drizzle(client), {
388
+ migrationsFolder: folder,
389
+ migrationsTable: table,
390
+ migrationsSchema: schema,
391
+ });
392
+ return { applied: status.pending.map((m) => m.tag) };
393
+ } finally {
394
+ await client
395
+ .query("select pg_advisory_unlock($1, $2)", [
396
+ MIGRATE_LOCK_CLASS,
397
+ MIGRATE_LOCK_ID,
398
+ ])
399
+ .catch(() => {});
400
+ client.release();
401
+ }
402
+ } finally {
403
+ await release();
404
+ }
405
+ };
406
+
407
+ /**
408
+ * Reconcile a journal whose schema is ALREADY correct but whose
409
+ * `__drizzle_migrations` rows don't match the files (built via db:push, or after
410
+ * regenerating the baseline). Records the full current file chain as applied —
411
+ * hashes + `when` timestamps, byte-compatible with drizzle — WITHOUT running any
412
+ * migration DDL, so a subsequent `runMigrations` is a clean no-op.
413
+ *
414
+ * Only call this when you've confirmed the live schema matches the migration
415
+ * files; it does not verify that.
416
+ */
417
+ export const baselineMigrations = async (
418
+ config: MigrateConfig = {},
419
+ ): Promise<{ recorded: string[] }> => {
420
+ const folder = config.migrationsFolder ?? DEFAULTS.migrationsFolder;
421
+ const schema = config.migrationsSchema ?? DEFAULTS.migrationsSchema;
422
+ const table = config.migrationsTable ?? DEFAULTS.migrationsTable;
423
+ const files = readJournal(folder);
424
+ const { pool, release } = acquire(config);
425
+ const client = await pool.connect();
426
+ try {
427
+ await client.query("begin");
428
+ await client.query(
429
+ `create schema if not exists "${schema.replace(/"/g, '""')}"`,
430
+ );
431
+ await client.query(
432
+ `create table if not exists ${qualified(schema, table)} (
433
+ id SERIAL PRIMARY KEY,
434
+ hash text NOT NULL,
435
+ created_at bigint
436
+ )`,
437
+ );
438
+ await client.query(`delete from ${qualified(schema, table)}`);
439
+ for (const f of files) {
440
+ await client.query(
441
+ `insert into ${qualified(schema, table)} ("hash", "created_at") values ($1, $2)`,
442
+ [f.hash, f.folderMillis],
443
+ );
444
+ }
445
+ await client.query("commit");
446
+ return { recorded: files.map((f) => f.tag) };
447
+ } catch (err) {
448
+ await client.query("rollback").catch(() => {});
449
+ throw err;
450
+ } finally {
451
+ client.release();
452
+ await release();
453
+ }
454
+ };
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ // The `nk-pglite-dev` bin: what `nk dev` shells out to when this package is
3
+ // installed. Boots PGlite (persisted to .pglite/), applies the `drizzle/`
4
+ // migrations, then runs `next dev` against it. `--fresh` wipes and rebuilds.
5
+ //
6
+ // nk-pglite-dev apply drizzle/ + run next dev
7
+ // nk-pglite-dev --fresh wipe .pglite/ first
8
+ // nk-pglite-dev --dep-migrations <f>#<t> also apply chain <f> under journal
9
+ // table <t>, BEFORE drizzle/ (repeatable)
10
+ //
11
+ // `--dep-migrations` lets an orchestrator inject extra migration chains without
12
+ // this bin knowing whose they are — `nk dev` uses it to apply nk-auth's shipped
13
+ // auth tables. Everything else is forwarded to `next dev`.
14
+ //
15
+ // Run directly by Node, so the relative import carries a `.js` extension.
16
+ import type { PgliteServerOptions } from "./index.js";
17
+ import { startPgliteDev } from "./index.js";
18
+
19
+ const argv = process.argv.slice(2);
20
+
21
+ // Pull `--dep-migrations <folder>#<table>` pairs out of the args; everything
22
+ // left over (minus --fresh) is forwarded verbatim to `next dev`. `#` separates
23
+ // folder from table because it never appears in a node_modules path.
24
+ const dependencyMigrations: NonNullable<PgliteServerOptions["dependencyMigrations"]> =
25
+ [];
26
+ const nextArgs: string[] = [];
27
+ let fresh = false;
28
+
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const arg = argv[i];
31
+ if (arg === undefined) continue;
32
+ if (arg === "--fresh") {
33
+ fresh = true;
34
+ continue;
35
+ }
36
+ if (arg === "--dep-migrations") {
37
+ const spec = argv[++i];
38
+ if (spec === undefined) {
39
+ console.error(
40
+ "nk(pglite): --dep-migrations requires a <folder>#<table> value",
41
+ );
42
+ process.exit(1);
43
+ }
44
+ const hash = spec.lastIndexOf("#");
45
+ if (hash <= 0 || hash === spec.length - 1) {
46
+ console.error(
47
+ `nk(pglite): --dep-migrations expects <folder>#<table>, got "${spec}"`,
48
+ );
49
+ process.exit(1);
50
+ }
51
+ dependencyMigrations.push({
52
+ folder: spec.slice(0, hash),
53
+ table: spec.slice(hash + 1),
54
+ });
55
+ continue;
56
+ }
57
+ nextArgs.push(arg);
58
+ }
59
+
60
+ startPgliteDev({ fresh, nextArgs, dependencyMigrations }).catch((error: unknown) => {
61
+ console.error("nk(pglite): failed to start —", error);
62
+ process.exit(1);
63
+ });