@softure-ai/db 0.1.5 → 0.1.7

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +261 -22
  3. package/dist/cli/run.d.ts +8 -1
  4. package/dist/cli/run.d.ts.map +1 -1
  5. package/dist/cli/run.js +71 -21
  6. package/dist/cli/run.js.map +1 -1
  7. package/dist/client.d.ts +39 -8
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +64 -8
  10. package/dist/client.js.map +1 -1
  11. package/dist/configured.d.ts +31 -0
  12. package/dist/configured.d.ts.map +1 -0
  13. package/dist/configured.js +74 -0
  14. package/dist/configured.js.map +1 -0
  15. package/dist/driver-errors.d.ts +21 -0
  16. package/dist/driver-errors.d.ts.map +1 -0
  17. package/dist/driver-errors.js +25 -0
  18. package/dist/driver-errors.js.map +1 -0
  19. package/dist/index.d.ts +6 -3
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +6 -3
  22. package/dist/index.js.map +1 -1
  23. package/dist/migrations/adopt.d.ts +8 -1
  24. package/dist/migrations/adopt.d.ts.map +1 -1
  25. package/dist/migrations/adopt.js +53 -87
  26. package/dist/migrations/adopt.js.map +1 -1
  27. package/dist/migrations/apply.d.ts +35 -0
  28. package/dist/migrations/apply.d.ts.map +1 -0
  29. package/dist/migrations/apply.js +115 -0
  30. package/dist/migrations/apply.js.map +1 -0
  31. package/dist/migrations/migrator.d.ts +55 -27
  32. package/dist/migrations/migrator.d.ts.map +1 -1
  33. package/dist/migrations/migrator.js +187 -103
  34. package/dist/migrations/migrator.js.map +1 -1
  35. package/dist/migrations/problems.d.ts +9 -0
  36. package/dist/migrations/problems.d.ts.map +1 -1
  37. package/dist/migrations/problems.js +9 -3
  38. package/dist/migrations/problems.js.map +1 -1
  39. package/dist/migrations/reference.d.ts +23 -0
  40. package/dist/migrations/reference.d.ts.map +1 -0
  41. package/dist/migrations/reference.js +64 -0
  42. package/dist/migrations/reference.js.map +1 -0
  43. package/dist/migrations/session.d.ts +2 -1
  44. package/dist/migrations/session.d.ts.map +1 -1
  45. package/dist/migrations/session.js +19 -2
  46. package/dist/migrations/session.js.map +1 -1
  47. package/dist/migrations/stubs.d.ts +23 -0
  48. package/dist/migrations/stubs.d.ts.map +1 -0
  49. package/dist/migrations/stubs.js +99 -0
  50. package/dist/migrations/stubs.js.map +1 -0
  51. package/dist/process.d.ts +23 -0
  52. package/dist/process.d.ts.map +1 -0
  53. package/dist/process.js +82 -0
  54. package/dist/process.js.map +1 -0
  55. package/dist/shared.d.ts +2 -0
  56. package/dist/shared.d.ts.map +1 -1
  57. package/dist/shared.js +9 -0
  58. package/dist/shared.js.map +1 -1
  59. package/dist/testing.d.ts +11 -2
  60. package/dist/testing.d.ts.map +1 -1
  61. package/dist/testing.js +28 -9
  62. package/dist/testing.js.map +1 -1
  63. package/package.json +22 -5
  64. package/src/cli/run.ts +84 -23
  65. package/src/client.ts +88 -16
  66. package/src/configured.ts +109 -0
  67. package/src/driver-errors.ts +40 -0
  68. package/src/index.ts +12 -1
  69. package/src/migrations/adopt.ts +65 -100
  70. package/src/migrations/apply.ts +135 -0
  71. package/src/migrations/migrator.ts +246 -128
  72. package/src/migrations/problems.ts +13 -5
  73. package/src/migrations/reference.ts +78 -0
  74. package/src/migrations/session.ts +28 -2
  75. package/src/migrations/stubs.ts +139 -0
  76. package/src/process.ts +110 -0
  77. package/src/shared.ts +9 -0
  78. package/src/testing.ts +38 -10
@@ -2,21 +2,20 @@
2
2
  // module's own schema, dependencies first, one transaction per file together with its ledger row.
3
3
  // Everything that can be checked (names, numbering, checksums, order) is checked for all modules
4
4
  // before the first file runs, so a problem in one module never leaves another half-migrated.
5
+ // The app's own migrations (drizzle's, usually) plug in through `app.before` / `app.after`, and
6
+ // `app.baseline` names the module files the app's own history already creates (issue #152).
5
7
  import { ok, sortModulesByDependencies, type AnySoftureModule } from "@softure-ai/core";
6
8
  import type { DatabaseHandle } from "../client.js";
7
- import { readMigrationFiles, type MigrationFile } from "./files.js";
8
- import {
9
- LEDGER_FILES,
10
- LEDGER_MODULE_ID,
11
- LEDGER_SCHEMA,
12
- LEDGER_VERSION,
13
- readJournal,
14
- recordMigration,
15
- type JournalRow,
16
- type MigrationMethod,
17
- } from "./ledger.js";
9
+ import { applyFile, describeError, recordAdoption, withMigrationLock, type MigrationUnit } from "./apply.js";
10
+ import { readMigrationFiles } from "./files.js";
11
+ import { describeSchema, diffSchemas } from "./introspect.js";
12
+ import { LEDGER_FILES, LEDGER_MODULE_ID, LEDGER_SCHEMA, LEDGER_VERSION, readJournal, type JournalRow } from "./ledger.js";
18
13
  import { failWith, type MigrationProblem, type MigrationResult } from "./problems.js";
14
+ import { buildReferenceSchema, listOwnedSchemas } from "./reference.js";
19
15
  import { withSession, type MigrationSession } from "./session.js";
16
+ import { readAppTables } from "./stubs.js";
17
+
18
+ export { applyFile, recordAdoption, rollBack, withMigrationLock, type MigrationUnit } from "./apply.js";
20
19
 
21
20
  export interface MigrateOptions {
22
21
  /** The enabled modules, in any order; dependencies are applied first. */
@@ -28,8 +27,40 @@ export interface MigrateOptions {
28
27
  readonly migrationsDir?: URL;
29
28
  /** Called after each file is committed, e.g. to print progress. */
30
29
  readonly onApplied?: (step: MigrationStep) => void;
30
+ /** Called after each file a baseline recorded as adopted, e.g. to print progress. */
31
+ readonly onAdopted?: (step: MigrationStep) => void;
32
+ /**
33
+ * The app's own migrations around the module files, and its baseline. `planMigrations` runs no
34
+ * hook; it reads only the baseline.
35
+ */
36
+ readonly app?: AppMigrations;
37
+ /** Called after an app hook succeeded, e.g. to print progress. */
38
+ readonly onAppMigrated?: (phase: AppMigrationPhase) => void;
31
39
  }
32
40
 
41
+ /**
42
+ * The app's own migration runner, called by `migrate` under the migration lock on every run (it
43
+ * must skip what it already applied, as drizzle's migrator does). A throw or rejection is reported
44
+ * as `db.app_migration_failed`.
45
+ */
46
+ export type AppMigrationHook = (handle: DatabaseHandle) => Promise<void>;
47
+
48
+ export interface AppMigrations {
49
+ /** Runs before the module files: app tables that module SQL references (normally the app's whole history). */
50
+ readonly before?: AppMigrationHook;
51
+ /** Runs after the module files: app migrations that reference tables a module creates. */
52
+ readonly after?: AppMigrationHook;
53
+ /**
54
+ * The module files the app's own history already creates: module id → the last such file (1..n).
55
+ * For a listed module the ledger has never seen, `migrate` compares the module's schema with
56
+ * files 1..n once `before` ran and records them as `adopted`, then applies the later files; an
57
+ * empty schema is migrated normally. Once the module is in the ledger the entry has no effect.
58
+ */
59
+ readonly baseline?: Readonly<Record<string, number>>;
60
+ }
61
+
62
+ export type AppMigrationPhase = "before" | "after";
63
+
33
64
  export interface MigrationStep {
34
65
  readonly module: string;
35
66
  readonly schema: string;
@@ -41,23 +72,23 @@ export interface MigrationStep {
41
72
  export interface MigrationPlan {
42
73
  /** What `migrate` would apply, in order. */
43
74
  readonly pending: readonly MigrationStep[];
75
+ /**
76
+ * The pending steps a baseline may adopt instead of applying: they are adopted when the module's
77
+ * schema already holds objects after `before` (which a plan does not run).
78
+ */
79
+ readonly baseline: readonly MigrationStep[];
44
80
  }
45
81
 
46
82
  export interface MigrationReport {
47
83
  readonly applied: readonly MigrationStep[];
84
+ /** The files a baseline recorded as adopted, in order. */
85
+ readonly adopted: readonly MigrationStep[];
86
+ /** The app hooks that ran, in order. */
87
+ readonly app: readonly AppMigrationPhase[];
48
88
  }
49
89
 
50
- /** One migration owner: the ledger itself or an enabled module with a schema. */
51
- export interface MigrationUnit {
52
- readonly module: string;
53
- readonly schema: string;
54
- readonly moduleVersion: string;
55
- readonly files: readonly MigrationFile[];
56
- }
57
-
58
- // Any constant works; it only has to be the same for every runner of every app.
59
- const MIGRATION_LOCK_KEY = "73012026";
60
- const RESERVED_SCHEMAS = new Set([LEDGER_SCHEMA, "public", "information_schema"]);
90
+ // `drizzle` holds drizzle's own ledger (`drizzle.__drizzle_migrations`) in every app on this stack.
91
+ const RESERVED_SCHEMAS = new Set([LEDGER_SCHEMA, "public", "information_schema", "drizzle"]);
61
92
  const MAX_IDENTIFIER_BYTES = 63;
62
93
 
63
94
  /** The dry run: what `migrate` would apply. Takes no lock and writes nothing. */
@@ -66,43 +97,222 @@ export async function planMigrations(handle: DatabaseHandle, options: MigrateOpt
66
97
  if (!units.ok) {
67
98
  return units;
68
99
  }
100
+ const baseline = options.app?.baseline ?? {};
101
+ const baselineProblems = checkBaseline(options.modules, units.value, baseline);
102
+ if (baselineProblems.length > 0) {
103
+ return failWith(baselineProblems);
104
+ }
69
105
  const journal = await withSession(handle, readJournal);
70
106
  const comparison = compareJournal(units.value, journal);
71
- return comparison.problems.length > 0 ? failWith(comparison.problems) : ok({ pending: comparison.pending });
107
+ if (comparison.problems.length > 0) {
108
+ return failWith(comparison.problems);
109
+ }
110
+ const adoptable = comparison.pending.filter((step) => isBaselineStep(step, baseline, journal));
111
+ return ok({ pending: comparison.pending, baseline: adoptable });
72
112
  }
73
113
 
74
- /** Applies every pending migration under the advisory lock. */
114
+ /**
115
+ * Applies every pending migration under the advisory lock: the ledger, `app.before`, the module
116
+ * files (adopting a baseline where it applies), then `app.after`. Nothing runs when a check fails.
117
+ */
75
118
  export async function migrate(handle: DatabaseHandle, options: MigrateOptions): Promise<MigrationResult<MigrationReport>> {
76
119
  const units = await prepareUnits(options.modules, options.migrationsDir);
77
120
  if (!units.ok) {
78
121
  return units;
79
122
  }
123
+ const app = options.app ?? {};
124
+ const baseline = app.baseline ?? {};
125
+ const baselineProblems = checkBaseline(options.modules, units.value, baseline);
126
+ if (baselineProblems.length > 0) {
127
+ return failWith(baselineProblems);
128
+ }
80
129
  return withSession(handle, (session) =>
81
130
  withMigrationLock(session, async () => {
82
131
  // Read after the lock: a runner that waited sees what the first one applied.
83
- const comparison = compareJournal(units.value, await readJournal(session));
132
+ const journal = await readJournal(session);
133
+ const comparison = compareJournal(units.value, journal);
84
134
  if (comparison.problems.length > 0) {
85
135
  return failWith(comparison.problems);
86
136
  }
87
137
  const applied: MigrationStep[] = [];
88
- for (const step of comparison.pending) {
89
- const unit = units.value.find((candidate) => candidate.module === step.module);
90
- const file = unit?.files.find((candidate) => candidate.version === step.version);
91
- if (unit === undefined || file === undefined) {
92
- throw new Error(`migrate: step ${step.module} ${step.version} has no file; compareJournal is broken`);
138
+ const adopted: MigrationStep[] = [];
139
+ const ranHooks: AppMigrationPhase[] = [];
140
+ const applySteps = async (steps: readonly MigrationStep[]): Promise<MigrationProblem | null> => {
141
+ for (const step of steps) {
142
+ const { unit, file } = findFile(units.value, step);
143
+ const failure = await applyFile(session, { unit, file, method: "applied" });
144
+ if (failure !== null) {
145
+ return failure;
146
+ }
147
+ applied.push(step);
148
+ options.onApplied?.(step);
93
149
  }
94
- const failure = await applyFile(session, { unit, file, method: "applied" });
95
- if (failure !== null) {
96
- return failWith([failure]);
150
+ return null;
151
+ };
152
+ const runHook = async (phase: AppMigrationPhase): Promise<MigrationProblem | null> => {
153
+ const failure = await runAppHook(handle, app, phase);
154
+ if (failure === null && app[phase] !== undefined) {
155
+ ranHooks.push(phase);
156
+ options.onAppMigrated?.(phase);
97
157
  }
98
- applied.push(step);
99
- options.onApplied?.(step);
158
+ return failure;
159
+ };
160
+ // Unit by unit in dependency order, so a module's dependencies are migrated before its
161
+ // baseline is compared.
162
+ const migrateModules = async (): Promise<MigrationProblem | null> => {
163
+ for (const unit of units.value) {
164
+ if (unit.module === LEDGER_MODULE_ID) continue;
165
+ const steps = comparison.pending.filter((step) => step.module === unit.module);
166
+ const through = baseline[unit.module];
167
+ if (through === undefined || journal.some((row) => row.module === unit.module)) {
168
+ const failure = await applySteps(steps);
169
+ if (failure !== null) return failure;
170
+ continue;
171
+ }
172
+ const adoption = await adoptBaseline(session, { modules: options.modules, units: units.value, unit, through });
173
+ if (adoption.problem !== null) return adoption.problem;
174
+ for (const step of adoption.adopted) {
175
+ adopted.push(step);
176
+ options.onAdopted?.(step);
177
+ }
178
+ const failure = await applySteps(steps.filter((step) => !adoption.adopted.some((done) => done.version === step.version)));
179
+ if (failure !== null) return failure;
180
+ }
181
+ return null;
182
+ };
183
+
184
+ // The ledger first, so it exists whatever a hook does; then before, the modules, after.
185
+ const ledgerSteps = comparison.pending.filter((step) => step.module === LEDGER_MODULE_ID);
186
+ const failure = (await applySteps(ledgerSteps)) ?? (await runHook("before")) ?? (await migrateModules()) ?? (await runHook("after"));
187
+ if (failure !== null) {
188
+ return failWith([failure]);
100
189
  }
101
- return ok({ applied });
190
+ return ok({ applied, adopted, app: ranHooks });
102
191
  }),
103
192
  );
104
193
  }
105
194
 
195
+ /**
196
+ * Adopt-or-migrate for a baseline module the ledger has never seen: an empty schema adopts
197
+ * nothing (its files are then applied normally); otherwise the schema must equal files 1..through,
198
+ * which are then recorded as adopted in one transaction.
199
+ */
200
+ async function adoptBaseline(
201
+ session: MigrationSession,
202
+ input: { modules: readonly AnySoftureModule[]; units: readonly MigrationUnit[]; unit: MigrationUnit; through: number },
203
+ ): Promise<{ adopted: MigrationStep[]; problem: MigrationProblem | null }> {
204
+ const { unit, through } = input;
205
+ const live = await describeSchema(session, unit.schema);
206
+ if (live.length === 0) {
207
+ return { adopted: [], problem: null };
208
+ }
209
+ // Built only here, so a database whose modules are all in the ledger never needs PGlite. The app's
210
+ // tables exist by now (`before` ran), so module SQL that references them finds their stubs.
211
+ const appTables = await readAppTables(session, listOwnedSchemas(input.units));
212
+ const reference = await buildReferenceSchema({ modules: input.modules, units: input.units, target: unit, through, appTables });
213
+ if (!reference.ok) {
214
+ return { adopted: [], problem: reference.problems[0] ?? null };
215
+ }
216
+ const differences = diffSchemas(reference.value, live);
217
+ if (differences.length > 0) {
218
+ return { adopted: [], problem: { code: "db.schema_mismatch", module: unit.module, schema: unit.schema, differences } };
219
+ }
220
+ const files = unit.files.filter((file) => file.version <= through);
221
+ const failure = await recordAdoption(session, unit, files);
222
+ if (failure !== null) {
223
+ return { adopted: [], problem: failure };
224
+ }
225
+ return { adopted: files.map((file) => toStep(unit, file)), problem: null };
226
+ }
227
+
228
+ /**
229
+ * A baseline may name only enabled modules with a schema and migrations, and a last file between
230
+ * 1 and the module's file count. Checked before anything runs.
231
+ */
232
+ function checkBaseline(
233
+ modules: readonly AnySoftureModule[],
234
+ units: readonly MigrationUnit[],
235
+ baseline: Readonly<Record<string, number>>,
236
+ ): MigrationProblem[] {
237
+ return Object.entries(baseline).flatMap(([module, through]): MigrationProblem[] => {
238
+ if (!modules.some((candidate) => candidate.id === module)) {
239
+ return [{ code: "db.adopt_unknown_module", module }];
240
+ }
241
+ const unit = units.find((candidate) => candidate.module === module);
242
+ if (unit === undefined) {
243
+ return [{ code: "db.adopt_no_schema", module }];
244
+ }
245
+ return checkThrough(unit, through);
246
+ });
247
+ }
248
+
249
+ /** `through` must be a whole number from 1 to the unit's file count. */
250
+ export function checkThrough(unit: MigrationUnit, through: number): MigrationProblem[] {
251
+ const files = unit.files.length;
252
+ return Number.isInteger(through) && through >= 1 && through <= files
253
+ ? []
254
+ : [{ code: "db.adopt_through_out_of_range", module: unit.module, through, files }];
255
+ }
256
+
257
+ function isBaselineStep(step: MigrationStep, baseline: Readonly<Record<string, number>>, journal: readonly JournalRow[]): boolean {
258
+ const through = baseline[step.module];
259
+ return through !== undefined && step.version <= through && !journal.some((row) => row.module === step.module);
260
+ }
261
+
262
+ function findFile(units: readonly MigrationUnit[], step: MigrationStep): { unit: MigrationUnit; file: MigrationUnit["files"][number] } {
263
+ const unit = units.find((candidate) => candidate.module === step.module);
264
+ const file = unit?.files.find((candidate) => candidate.version === step.version);
265
+ if (unit === undefined || file === undefined) {
266
+ throw new Error(`migrate: step ${step.module} ${step.version} has no file; compareJournal is broken`);
267
+ }
268
+ return { unit, file };
269
+ }
270
+
271
+ export function toStep(unit: MigrationUnit, file: MigrationUnit["files"][number]): MigrationStep {
272
+ return { module: unit.module, schema: unit.schema, version: file.version, name: file.name, checksum: file.checksum };
273
+ }
274
+
275
+ /**
276
+ * Runs one app hook alone under the migration lock (the CLI's `--adopt` runs `before` first, so the
277
+ * app migration that moves a table and the adoption are one command). Ok when there is no hook.
278
+ */
279
+ export async function runAppMigrations(
280
+ handle: DatabaseHandle,
281
+ app: AppMigrations,
282
+ phase: AppMigrationPhase,
283
+ ): Promise<MigrationResult<{ ran: boolean }>> {
284
+ if (app[phase] === undefined) {
285
+ return ok({ ran: false });
286
+ }
287
+ const failure = await withSession(handle, (session) => withMigrationLock(session, () => runAppHook(handle, app, phase)));
288
+ return failure === null ? ok({ ran: true }) : failWith([failure]);
289
+ }
290
+
291
+ async function runAppHook(handle: DatabaseHandle, app: AppMigrations, phase: AppMigrationPhase): Promise<MigrationProblem | null> {
292
+ const hook = app[phase];
293
+ if (hook === undefined) {
294
+ return null;
295
+ }
296
+ try {
297
+ await hook(handle);
298
+ return null;
299
+ } catch (error) {
300
+ return { code: "db.app_migration_failed", phase, reason: describeErrorChain(error) };
301
+ }
302
+ }
303
+
304
+ // drizzle wraps the database error (`Failed query: <sql>`, the Postgres message in `cause`), so the
305
+ // whole chain is the reason.
306
+ function describeErrorChain(error: unknown): string {
307
+ const messages: string[] = [];
308
+ let current: unknown = error;
309
+ while (current !== undefined && current !== null && messages.length < 5) {
310
+ messages.push(describeError(current));
311
+ current = current instanceof Error ? current.cause : undefined;
312
+ }
313
+ return messages.join(": ");
314
+ }
315
+
106
316
  /**
107
317
  * Validates the module list and reads every file: the ledger first, then the modules with a
108
318
  * schema in dependency order. Fails with every problem found.
@@ -173,90 +383,6 @@ export function compareJournal(
173
383
  return { problems, pending };
174
384
  }
175
385
 
176
- /**
177
- * Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
178
- * problem when the SQL fails; the transaction is rolled back first.
179
- */
180
- export async function applyFile(
181
- session: MigrationSession,
182
- input: { unit: MigrationUnit; file: MigrationFile; method: MigrationMethod },
183
- ): Promise<MigrationProblem | null> {
184
- const { unit, file, method } = input;
185
- // The schema passed the manifest's lower_snake_case rule and checkModule; quoting is a second line.
186
- const schema = quoteIdentifier(unit.schema);
187
- try {
188
- await session.exec(`BEGIN; CREATE SCHEMA IF NOT EXISTS ${schema}; SET LOCAL search_path TO ${schema}, public;`);
189
- const transactionId = await readTransactionId(session);
190
- if (method === "applied") {
191
- await session.exec(file.sql);
192
- }
193
- // Second line behind findTransactionControl: a file that still ended the transaction left
194
- // part of itself committed, so it must not be reported as cleanly rolled back.
195
- if ((await readTransactionId(session)) !== transactionId) {
196
- throw new TransactionEndedError();
197
- }
198
- await recordMigration(session, {
199
- module: unit.module,
200
- version: file.version,
201
- name: file.name,
202
- checksum: file.checksum,
203
- moduleVersion: unit.moduleVersion,
204
- method,
205
- });
206
- await session.exec("COMMIT");
207
- return null;
208
- } catch (error) {
209
- const reason = await rollBack(session, error);
210
- return { code: "db.migration_failed", module: unit.module, version: file.version, name: file.name, reason };
211
- }
212
- }
213
-
214
- class TransactionEndedError extends Error {
215
- constructor() {
216
- super("the file ended the migrator's transaction, so the statements before that point may be committed; check the schema by hand");
217
- }
218
- }
219
-
220
- // The transaction id, not now(): two transactions can share a start time (PGlite's clock ticks in
221
- // milliseconds), but never an id.
222
- async function readTransactionId(session: MigrationSession): Promise<string> {
223
- const [row] = await session.query<{ id: string }>("SELECT pg_current_xact_id()::text AS id");
224
- return row?.id ?? "";
225
- }
226
-
227
- /**
228
- * Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
229
- * connection) is added to the reason instead of hiding the original error.
230
- */
231
- export async function rollBack(session: MigrationSession, error: unknown): Promise<string> {
232
- const reason = describeError(error);
233
- try {
234
- await session.exec("ROLLBACK");
235
- return reason;
236
- } catch (rollbackError) {
237
- return `${reason} (and ROLLBACK failed: ${describeError(rollbackError)})`;
238
- }
239
- }
240
-
241
- /** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
242
- export async function withMigrationLock<T>(session: MigrationSession, run: () => Promise<T>): Promise<T> {
243
- await session.query("SELECT pg_advisory_lock($1)", [MIGRATION_LOCK_KEY]);
244
- let result: T;
245
- try {
246
- result = await run();
247
- } catch (error) {
248
- // The run's own error wins; an unlock failure here is secondary (the session is discarded).
249
- await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]).catch((unlockError: unknown) => {
250
- throw new Error(`migration run failed (${describeError(error)}) and releasing the lock failed: ${describeError(unlockError)}`, {
251
- cause: error,
252
- });
253
- });
254
- throw error;
255
- }
256
- await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]);
257
- return result;
258
- }
259
-
260
386
  function checkModule(module: AnySoftureModule): MigrationProblem[] {
261
387
  const schema = module.manifest.dbSchema;
262
388
  if (module.id === LEDGER_MODULE_ID || (schema !== null && isReservedSchema(schema))) {
@@ -272,14 +398,6 @@ function isReservedSchema(schema: string): boolean {
272
398
  return RESERVED_SCHEMAS.has(schema) || schema.startsWith("pg_") || Buffer.byteLength(schema, "utf8") > MAX_IDENTIFIER_BYTES;
273
399
  }
274
400
 
275
- function quoteIdentifier(name: string): string {
276
- return `"${name.replace(/"/g, '""')}"`;
277
- }
278
-
279
401
  function ensureFolderUrl(url: URL): URL {
280
402
  return url.href.endsWith("/") ? url : new URL(`${url.href}/`);
281
403
  }
282
-
283
- function describeError(error: unknown): string {
284
- return error instanceof Error ? error.message : String(error);
285
- }
@@ -1,6 +1,6 @@
1
1
  // Every expected migration failure, as a value (AGENTS.md: expected failures are results). Each
2
- // problem names the module and file it is about; `describeProblem` turns it into the English line
3
- // the CLI prints and `createTestDatabase` throws.
2
+ // problem names the module and file it is about (or the app's hook phase); `describeProblem` turns
3
+ // it into the English line the CLI prints and `createTestDatabase` throws.
4
4
  import type { Err, Ok } from "@softure-ai/core";
5
5
 
6
6
  export type MigrationProblem =
@@ -10,6 +10,7 @@ export type MigrationProblem =
10
10
  | { readonly code: "db.migration_missing"; readonly module: string; readonly version: number; readonly name: string }
11
11
  | { readonly code: "db.migration_out_of_order"; readonly module: string; readonly version: number; readonly appliedVersion: number }
12
12
  | { readonly code: "db.migration_failed"; readonly module: string; readonly version: number; readonly name: string; readonly reason: string }
13
+ | { readonly code: "db.app_migration_failed"; readonly phase: "before" | "after"; readonly reason: string }
13
14
  | { readonly code: "db.reserved_module"; readonly module: string }
14
15
  | { readonly code: "db.migrations_without_schema"; readonly module: string }
15
16
  | { readonly code: "db.dependency_cycle"; readonly modules: readonly string[] }
@@ -18,6 +19,7 @@ export type MigrationProblem =
18
19
  | { readonly code: "db.adopt_already_applied"; readonly module: string }
19
20
  | { readonly code: "db.adopt_dependency_pending"; readonly module: string; readonly dependency: string }
20
21
  | { readonly code: "db.adopt_no_schema"; readonly module: string }
22
+ | { readonly code: "db.adopt_through_out_of_range"; readonly module: string; readonly through: number; readonly files: number }
21
23
  | { readonly code: "db.adopt_reference_failed"; readonly module: string; readonly reason: string }
22
24
  | { readonly code: "db.export_target_not_empty"; readonly module: string; readonly dir: string; readonly entries: readonly string[] }
23
25
  | { readonly code: "db.schema_mismatch"; readonly module: string; readonly schema: string; readonly differences: readonly string[] };
@@ -54,8 +56,12 @@ export function describeProblem(problem: MigrationProblem): string {
54
56
  return `${problem.module}: migration ${formatVersion(problem.version)} is pending but ${formatVersion(problem.appliedVersion)} is already applied`;
55
57
  case "db.migration_failed":
56
58
  return `${problem.module}: migration ${formatFile(problem.version, problem.name)} failed and was rolled back: ${problem.reason}`;
59
+ case "db.app_migration_failed":
60
+ return problem.phase === "before"
61
+ ? `app: the before migrations failed: ${problem.reason}; no module migration ran`
62
+ : `app: the after migrations failed: ${problem.reason}; the module migrations before it stay applied`;
57
63
  case "db.reserved_module":
58
- return `${problem.module}: uses a reserved id or schema (the id "softure"; the schemas softure, public, information_schema, pg_* and names over 63 bytes)`;
64
+ return `${problem.module}: uses a reserved id or schema (the id "softure"; the schemas softure, public, information_schema, drizzle, pg_* and names over 63 bytes)`;
59
65
  case "db.migrations_without_schema":
60
66
  return `${problem.module}: has migrations but no dbSchema in its manifest`;
61
67
  case "db.dependency_cycle":
@@ -67,9 +73,11 @@ export function describeProblem(problem: MigrationProblem): string {
67
73
  case "db.adopt_already_applied":
68
74
  return `${problem.module}: already has migrations in the ledger; adopt only works on a module the ledger has never seen`;
69
75
  case "db.adopt_dependency_pending":
70
- return `${problem.module}: depends on ${problem.dependency}, which has migrations still pending; migrate or adopt ${problem.dependency} first`;
76
+ return `${problem.module}: depends on ${problem.dependency}, whose pending migrations could not be applied (see above); adopt ${problem.dependency} first`;
71
77
  case "db.adopt_no_schema":
72
- return `${problem.module}: has no dbSchema, so there is nothing to adopt`;
78
+ return `${problem.module}: has no dbSchema or no migrations, so there is nothing to adopt`;
79
+ case "db.adopt_through_out_of_range":
80
+ return `${problem.module}: cannot adopt through ${String(problem.through)}; it is the number of the last file to adopt, a whole number from 1 to ${problem.files}`;
73
81
  case "db.adopt_reference_failed":
74
82
  return `${problem.module}: could not build the reference schema: ${problem.reason}`;
75
83
  case "db.export_target_not_empty":
@@ -0,0 +1,78 @@
1
+ // The reference schema for adoption: what a module's files 1..N create, built on a scratch
2
+ // in-memory PGlite together with the modules it depends on (directly or not), because its SQL may
3
+ // reference them. `adoptModule` and a baseline in `migrate` compare a live schema with it. Module
4
+ // SQL may also reference the app's own tables; their stubs, copied from the live database
5
+ // (`stubs.ts`), are created first (issue #170).
6
+ import { ok, type AnySoftureModule } from "@softure-ai/core";
7
+ import { createDatabase } from "../client.js";
8
+ import { applyFile, type MigrationUnit } from "./apply.js";
9
+ import { describeSchema } from "./introspect.js";
10
+ import { LEDGER_MODULE_ID, LEDGER_SCHEMA } from "./ledger.js";
11
+ import { failWith, type MigrationProblem, type MigrationResult } from "./problems.js";
12
+ import { withSession } from "./session.js";
13
+ import { createAppStubs, type AppCatalog } from "./stubs.js";
14
+
15
+ // drizzle's ledger schema (`drizzle.__drizzle_migrations`): never an app table a module references.
16
+ const APP_MIGRATOR_SCHEMA = "drizzle";
17
+
18
+ export interface ReferenceInput {
19
+ /** The enabled modules, for the dependency graph. */
20
+ readonly modules: readonly AnySoftureModule[];
21
+ /** Their prepared units (`prepareUnits`), the ledger first, in dependency order. */
22
+ readonly units: readonly MigrationUnit[];
23
+ /** The module whose schema is described. */
24
+ readonly target: MigrationUnit;
25
+ /** The last file of the target to run; its dependencies run in full. */
26
+ readonly through: number;
27
+ /** Stubs of the app's tables (`readAppTables`), created before any file runs. */
28
+ readonly appTables?: AppCatalog;
29
+ }
30
+
31
+ /** Every line `describeSchema` prints for the target's schema after its files 1..through. */
32
+ export async function buildReferenceSchema(input: ReferenceInput): Promise<MigrationResult<string[]>> {
33
+ const included = collectWithDependencies(input.modules, input.target.module);
34
+ const units = input.units
35
+ .filter((unit) => unit.module === LEDGER_MODULE_ID || included.has(unit.module))
36
+ .map((unit) => (unit.module === input.target.module ? { ...unit, files: unit.files.filter((file) => file.version <= input.through) } : unit));
37
+ const scratch = await createDatabase("pglite://");
38
+ try {
39
+ return await withSession(scratch, async (session) => {
40
+ const skipped = input.appTables === undefined ? [] : await createAppStubs(session, input.appTables);
41
+ for (const unit of units) {
42
+ for (const file of unit.files) {
43
+ const failure = await applyFile(session, { unit, file, method: "applied" });
44
+ if (failure !== null) {
45
+ const reason = describeFailure(failure) + (skipped.length > 0 ? ` (app table stubs skipped: ${skipped.join("; ")})` : "");
46
+ return failWith([{ code: "db.adopt_reference_failed", module: input.target.module, reason }]);
47
+ }
48
+ }
49
+ }
50
+ return ok(await describeSchema(session, input.target.schema));
51
+ });
52
+ } finally {
53
+ await scratch.close();
54
+ }
55
+ }
56
+
57
+ /** The schemas the migrator owns, which hold no app table: the ledger's, every unit's and drizzle's. */
58
+ export function listOwnedSchemas(units: readonly MigrationUnit[]): string[] {
59
+ return [...new Set([LEDGER_SCHEMA, APP_MIGRATOR_SCHEMA, ...units.map((unit) => unit.schema)])];
60
+ }
61
+
62
+ /** The ids of the target and every enabled module it depends on, directly or not. */
63
+ export function collectWithDependencies(modules: readonly AnySoftureModule[], target: string): Set<string> {
64
+ const byId = new Map(modules.map((module) => [module.id, module]));
65
+ const collected = new Set<string>();
66
+ const visit = (id: string): void => {
67
+ const module = byId.get(id);
68
+ if (module === undefined || collected.has(id)) return;
69
+ collected.add(id);
70
+ for (const dependency of Object.keys(module.manifest.dependsOn)) visit(dependency);
71
+ };
72
+ visit(target);
73
+ return collected;
74
+ }
75
+
76
+ function describeFailure(problem: MigrationProblem): string {
77
+ return problem.code === "db.migration_failed" ? `${problem.module} ${problem.name}: ${problem.reason}` : problem.code;
78
+ }
@@ -2,6 +2,8 @@
2
2
  // transaction and every statement of a run must share this connection (never `pool.query`).
3
3
  import type { DatabaseHandle } from "../client.js";
4
4
 
5
+ type PgliteClient = Extract<DatabaseHandle, { kind: "pglite" }>["client"];
6
+
5
7
  export interface MigrationSession {
6
8
  /** A parameterised statement; returns its rows. */
7
9
  readonly query: <T>(text: string, params?: readonly unknown[]) => Promise<T[]>;
@@ -9,14 +11,23 @@ export interface MigrationSession {
9
11
  readonly exec: (sql: string) => Promise<void>;
10
12
  }
11
13
 
14
+ interface SessionSetting {
15
+ readonly name: string;
16
+ readonly value: string;
17
+ }
18
+
19
+ const SESSION_SETTINGS_SQL = "SELECT name, current_setting(name) AS value FROM pg_settings WHERE source = 'session'";
20
+
12
21
  /**
13
22
  * Runs `run` on one dedicated connection. A pg client is destroyed afterwards instead of going
14
23
  * back to the pool, so a `SET` inside a migration file or a lock that failed to release cannot
15
- * leak into the app's queries. PGlite has one connection, so its settings are reset instead.
24
+ * leak into the app's queries. PGlite has one connection, shared with the app, so the settings the
25
+ * run changed are put back afterwards; the app's own (`TimeZone`, `search_path`) stay as they were.
16
26
  */
17
27
  export async function withSession<T>(handle: DatabaseHandle, run: (session: MigrationSession) => Promise<T>): Promise<T> {
18
28
  if (handle.kind === "pglite") {
19
29
  const { client } = handle;
30
+ const before = (await client.query<SessionSetting>(SESSION_SETTINGS_SQL)).rows;
20
31
  try {
21
32
  return await run({
22
33
  query: async <R>(text: string, params?: readonly unknown[]) => (await client.query<R>(text, params ? [...params] : undefined)).rows,
@@ -25,7 +36,7 @@ export async function withSession<T>(handle: DatabaseHandle, run: (session: Migr
25
36
  },
26
37
  });
27
38
  } finally {
28
- await client.exec("RESET ALL");
39
+ await restoreSessionSettings(client, before);
29
40
  }
30
41
  }
31
42
 
@@ -46,3 +57,18 @@ export async function withSession<T>(handle: DatabaseHandle, run: (session: Migr
46
57
  client.off("error", ignoreClientError);
47
58
  }
48
59
  }
60
+
61
+ /** Puts back every value in `before` (also one the run reset) and resets every session setting the run added. */
62
+ async function restoreSessionSettings(client: PgliteClient, before: readonly SessionSetting[]): Promise<void> {
63
+ const after = new Map((await client.query<SessionSetting>(SESSION_SETTINGS_SQL)).rows.map((setting) => [setting.name, setting.value]));
64
+ for (const setting of before) {
65
+ if (after.get(setting.name) !== setting.value) {
66
+ await client.query("SELECT set_config($1, $2, false)", [setting.name, setting.value]);
67
+ }
68
+ after.delete(setting.name);
69
+ }
70
+ for (const name of after.keys()) {
71
+ // Names come from pg_settings, not from input; quoted as identifiers all the same.
72
+ await client.exec(`RESET "${name.replaceAll('"', '""')}"`);
73
+ }
74
+ }