@softure-ai/db 0.1.5 → 0.1.6

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 (63) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +215 -21
  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/index.d.ts +3 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +3 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/migrations/adopt.d.ts +8 -1
  20. package/dist/migrations/adopt.d.ts.map +1 -1
  21. package/dist/migrations/adopt.js +53 -87
  22. package/dist/migrations/adopt.js.map +1 -1
  23. package/dist/migrations/apply.d.ts +35 -0
  24. package/dist/migrations/apply.d.ts.map +1 -0
  25. package/dist/migrations/apply.js +115 -0
  26. package/dist/migrations/apply.js.map +1 -0
  27. package/dist/migrations/migrator.d.ts +55 -27
  28. package/dist/migrations/migrator.d.ts.map +1 -1
  29. package/dist/migrations/migrator.js +187 -103
  30. package/dist/migrations/migrator.js.map +1 -1
  31. package/dist/migrations/problems.d.ts +9 -0
  32. package/dist/migrations/problems.d.ts.map +1 -1
  33. package/dist/migrations/problems.js +9 -3
  34. package/dist/migrations/problems.js.map +1 -1
  35. package/dist/migrations/reference.d.ts +23 -0
  36. package/dist/migrations/reference.d.ts.map +1 -0
  37. package/dist/migrations/reference.js +64 -0
  38. package/dist/migrations/reference.js.map +1 -0
  39. package/dist/migrations/session.d.ts +2 -1
  40. package/dist/migrations/session.d.ts.map +1 -1
  41. package/dist/migrations/session.js +19 -2
  42. package/dist/migrations/session.js.map +1 -1
  43. package/dist/migrations/stubs.d.ts +23 -0
  44. package/dist/migrations/stubs.d.ts.map +1 -0
  45. package/dist/migrations/stubs.js +99 -0
  46. package/dist/migrations/stubs.js.map +1 -0
  47. package/dist/testing.d.ts +11 -2
  48. package/dist/testing.d.ts.map +1 -1
  49. package/dist/testing.js +28 -9
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +22 -5
  52. package/src/cli/run.ts +84 -23
  53. package/src/client.ts +88 -16
  54. package/src/configured.ts +109 -0
  55. package/src/index.ts +9 -0
  56. package/src/migrations/adopt.ts +65 -100
  57. package/src/migrations/apply.ts +135 -0
  58. package/src/migrations/migrator.ts +246 -128
  59. package/src/migrations/problems.ts +13 -5
  60. package/src/migrations/reference.ts +78 -0
  61. package/src/migrations/session.ts +28 -2
  62. package/src/migrations/stubs.ts +139 -0
  63. package/src/testing.ts +38 -10
@@ -0,0 +1,35 @@
1
+ import type { MigrationFile } from "./files.js";
2
+ import { type MigrationMethod } from "./ledger.js";
3
+ import type { MigrationProblem } from "./problems.js";
4
+ import type { MigrationSession } from "./session.js";
5
+ /** One migration owner: the ledger itself or an enabled module with a schema. */
6
+ export interface MigrationUnit {
7
+ readonly module: string;
8
+ readonly schema: string;
9
+ readonly moduleVersion: string;
10
+ readonly files: readonly MigrationFile[];
11
+ }
12
+ /**
13
+ * Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
14
+ * problem when the SQL fails; the transaction is rolled back first.
15
+ */
16
+ export declare function applyFile(session: MigrationSession, input: {
17
+ unit: MigrationUnit;
18
+ file: MigrationFile;
19
+ method: MigrationMethod;
20
+ }): Promise<MigrationProblem | null>;
21
+ /**
22
+ * Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
23
+ * connection) is added to the reason instead of hiding the original error.
24
+ */
25
+ export declare function rollBack(session: MigrationSession, error: unknown): Promise<string>;
26
+ /** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
27
+ export declare function withMigrationLock<T>(session: MigrationSession, run: () => Promise<T>): Promise<T>;
28
+ /**
29
+ * Records `files` of the unit as adopted, all in one transaction: either every row is written or
30
+ * none. Returns the problem when a write fails.
31
+ */
32
+ export declare function recordAdoption(session: MigrationSession, unit: MigrationUnit, files: readonly MigrationFile[]): Promise<MigrationProblem | null>;
33
+ export declare function quoteIdentifier(name: string): string;
34
+ export declare function describeError(error: unknown): string;
35
+ //# sourceMappingURL=apply.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../src/migrations/apply.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAmB,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,CAAC;CAC1C;AAKD;;;GAGG;AACH,wBAAsB,SAAS,CAC7B,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,IAAI,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,eAAe,CAAA;CAAE,GAC3E,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CA6BlC;AAeD;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAQzF;AAED,4FAA4F;AAC5F,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,EAAE,gBAAgB,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAgBvG;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,aAAa,EAAE,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAoBtJ;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEpD"}
@@ -0,0 +1,115 @@
1
+ import { recordMigration } from "./ledger.js";
2
+ // Any constant works; it only has to be the same for every runner of every app.
3
+ const MIGRATION_LOCK_KEY = "73012026";
4
+ /**
5
+ * Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
6
+ * problem when the SQL fails; the transaction is rolled back first.
7
+ */
8
+ export async function applyFile(session, input) {
9
+ const { unit, file, method } = input;
10
+ // The schema passed the manifest's lower_snake_case rule and checkModule; quoting is a second line.
11
+ const schema = quoteIdentifier(unit.schema);
12
+ try {
13
+ await session.exec(`BEGIN; CREATE SCHEMA IF NOT EXISTS ${schema}; SET LOCAL search_path TO ${schema}, public;`);
14
+ const transactionId = await readTransactionId(session);
15
+ if (method === "applied") {
16
+ await session.exec(file.sql);
17
+ }
18
+ // Second line behind findTransactionControl: a file that still ended the transaction left
19
+ // part of itself committed, so it must not be reported as cleanly rolled back.
20
+ if ((await readTransactionId(session)) !== transactionId) {
21
+ throw new TransactionEndedError();
22
+ }
23
+ await recordMigration(session, {
24
+ module: unit.module,
25
+ version: file.version,
26
+ name: file.name,
27
+ checksum: file.checksum,
28
+ moduleVersion: unit.moduleVersion,
29
+ method,
30
+ });
31
+ await session.exec("COMMIT");
32
+ return null;
33
+ }
34
+ catch (error) {
35
+ const reason = await rollBack(session, error);
36
+ return { code: "db.migration_failed", module: unit.module, version: file.version, name: file.name, reason };
37
+ }
38
+ }
39
+ class TransactionEndedError extends Error {
40
+ constructor() {
41
+ super("the file ended the migrator's transaction, so the statements before that point may be committed; check the schema by hand");
42
+ }
43
+ }
44
+ // The transaction id, not now(): two transactions can share a start time (PGlite's clock ticks in
45
+ // milliseconds), but never an id.
46
+ async function readTransactionId(session) {
47
+ const [row] = await session.query("SELECT pg_current_xact_id()::text AS id");
48
+ return row?.id ?? "";
49
+ }
50
+ /**
51
+ * Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
52
+ * connection) is added to the reason instead of hiding the original error.
53
+ */
54
+ export async function rollBack(session, error) {
55
+ const reason = describeError(error);
56
+ try {
57
+ await session.exec("ROLLBACK");
58
+ return reason;
59
+ }
60
+ catch (rollbackError) {
61
+ return `${reason} (and ROLLBACK failed: ${describeError(rollbackError)})`;
62
+ }
63
+ }
64
+ /** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
65
+ export async function withMigrationLock(session, run) {
66
+ await session.query("SELECT pg_advisory_lock($1)", [MIGRATION_LOCK_KEY]);
67
+ let result;
68
+ try {
69
+ result = await run();
70
+ }
71
+ catch (error) {
72
+ // The run's own error wins; an unlock failure here is secondary (the session is discarded).
73
+ await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]).catch((unlockError) => {
74
+ throw new Error(`migration run failed (${describeError(error)}) and releasing the lock failed: ${describeError(unlockError)}`, {
75
+ cause: error,
76
+ });
77
+ });
78
+ throw error;
79
+ }
80
+ await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]);
81
+ return result;
82
+ }
83
+ /**
84
+ * Records `files` of the unit as adopted, all in one transaction: either every row is written or
85
+ * none. Returns the problem when a write fails.
86
+ */
87
+ export async function recordAdoption(session, unit, files) {
88
+ try {
89
+ await session.exec("BEGIN");
90
+ for (const file of files) {
91
+ await recordMigration(session, {
92
+ module: unit.module,
93
+ version: file.version,
94
+ name: file.name,
95
+ checksum: file.checksum,
96
+ moduleVersion: unit.moduleVersion,
97
+ method: "adopted",
98
+ });
99
+ }
100
+ await session.exec("COMMIT");
101
+ return null;
102
+ }
103
+ catch (error) {
104
+ const reason = await rollBack(session, error);
105
+ const first = files[0];
106
+ return { code: "db.migration_failed", module: unit.module, version: first?.version ?? 0, name: first?.name ?? "", reason };
107
+ }
108
+ }
109
+ export function quoteIdentifier(name) {
110
+ return `"${name.replace(/"/g, '""')}"`;
111
+ }
112
+ export function describeError(error) {
113
+ return error instanceof Error ? error.message : String(error);
114
+ }
115
+ //# sourceMappingURL=apply.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply.js","sourceRoot":"","sources":["../../src/migrations/apply.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAwB,MAAM,aAAa,CAAC;AAYpE,gFAAgF;AAChF,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAEtC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAyB,EACzB,KAA4E;IAE5E,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IACrC,oGAAoG;IACpG,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,CAAC;QACH,MAAM,OAAO,CAAC,IAAI,CAAC,sCAAsC,MAAM,8BAA8B,MAAM,WAAW,CAAC,CAAC;QAChH,MAAM,aAAa,GAAG,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACvD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,MAAM,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,CAAC;QACD,0FAA0F;QAC1F,+EAA+E;QAC/E,IAAI,CAAC,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC,KAAK,aAAa,EAAE,CAAC;YACzD,MAAM,IAAI,qBAAqB,EAAE,C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gBACvB,aAAa,EAAE,IAAI,CAAC,aAAa;gBACjC,MAAM,EAAE,SAAS;aAClB,CAAC,CAAC;QACL,CAAC;QACD,MAAM,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC9C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACvB,OAAO,EAAE,IAAI,EAAE,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC;IAC7H,CAAC;AACH,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
@@ -1,9 +1,9 @@
1
1
  import { type AnySoftureModule } from "@softure-ai/core";
2
2
  import type { DatabaseHandle } from "../client.js";
3
- import { type MigrationFile } from "./files.js";
4
- import { type JournalRow, type MigrationMethod } from "./ledger.js";
3
+ import { type MigrationUnit } from "./apply.js";
4
+ import { type JournalRow } from "./ledger.js";
5
5
  import { type MigrationProblem, type MigrationResult } from "./problems.js";
6
- import { type MigrationSession } from "./session.js";
6
+ export { applyFile, recordAdoption, rollBack, withMigrationLock, type MigrationUnit } from "./apply.js";
7
7
  export interface MigrateOptions {
8
8
  /** The enabled modules, in any order; dependencies are applied first. */
9
9
  readonly modules: readonly AnySoftureModule[];
@@ -14,7 +14,36 @@ export interface MigrateOptions {
14
14
  readonly migrationsDir?: URL;
15
15
  /** Called after each file is committed, e.g. to print progress. */
16
16
  readonly onApplied?: (step: MigrationStep) => void;
17
+ /** Called after each file a baseline recorded as adopted, e.g. to print progress. */
18
+ readonly onAdopted?: (step: MigrationStep) => void;
19
+ /**
20
+ * The app's own migrations around the module files, and its baseline. `planMigrations` runs no
21
+ * hook; it reads only the baseline.
22
+ */
23
+ readonly app?: AppMigrations;
24
+ /** Called after an app hook succeeded, e.g. to print progress. */
25
+ readonly onAppMigrated?: (phase: AppMigrationPhase) => void;
26
+ }
27
+ /**
28
+ * The app's own migration runner, called by `migrate` under the migration lock on every run (it
29
+ * must skip what it already applied, as drizzle's migrator does). A throw or rejection is reported
30
+ * as `db.app_migration_failed`.
31
+ */
32
+ export type AppMigrationHook = (handle: DatabaseHandle) => Promise<void>;
33
+ export interface AppMigrations {
34
+ /** Runs before the module files: app tables that module SQL references (normally the app's whole history). */
35
+ readonly before?: AppMigrationHook;
36
+ /** Runs after the module files: app migrations that reference tables a module creates. */
37
+ readonly after?: AppMigrationHook;
38
+ /**
39
+ * The module files the app's own history already creates: module id → the last such file (1..n).
40
+ * For a listed module the ledger has never seen, `migrate` compares the module's schema with
41
+ * files 1..n once `before` ran and records them as `adopted`, then applies the later files; an
42
+ * empty schema is migrated normally. Once the module is in the ledger the entry has no effect.
43
+ */
44
+ readonly baseline?: Readonly<Record<string, number>>;
17
45
  }
46
+ export type AppMigrationPhase = "before" | "after";
18
47
  export interface MigrationStep {
19
48
  readonly module: string;
20
49
  readonly schema: string;
@@ -25,21 +54,36 @@ export interface MigrationStep {
25
54
  export interface MigrationPlan {
26
55
  /** What `migrate` would apply, in order. */
27
56
  readonly pending: readonly MigrationStep[];
57
+ /**
58
+ * The pending steps a baseline may adopt instead of applying: they are adopted when the module's
59
+ * schema already holds objects after `before` (which a plan does not run).
60
+ */
61
+ readonly baseline: readonly MigrationStep[];
28
62
  }
29
63
  export interface MigrationReport {
30
64
  readonly applied: readonly MigrationStep[];
31
- }
32
- /** One migration owner: the ledger itself or an enabled module with a schema. */
33
- export interface MigrationUnit {
34
- readonly module: string;
35
- readonly schema: string;
36
- readonly moduleVersion: string;
37
- readonly files: readonly MigrationFile[];
65
+ /** The files a baseline recorded as adopted, in order. */
66
+ readonly adopted: readonly MigrationStep[];
67
+ /** The app hooks that ran, in order. */
68
+ readonly app: readonly AppMigrationPhase[];
38
69
  }
39
70
  /** The dry run: what `migrate` would apply. Takes no lock and writes nothing. */
40
71
  export declare function planMigrations(handle: DatabaseHandle, options: MigrateOptions): Promise<MigrationResult<MigrationPlan>>;
41
- /** Applies every pending migration under the advisory lock. */
72
+ /**
73
+ * Applies every pending migration under the advisory lock: the ledger, `app.before`, the module
74
+ * files (adopting a baseline where it applies), then `app.after`. Nothing runs when a check fails.
75
+ */
42
76
  export declare function migrate(handle: DatabaseHandle, options: MigrateOptions): Promise<MigrationResult<MigrationReport>>;
77
+ /** `through` must be a whole number from 1 to the unit's file count. */
78
+ export declare function checkThrough(unit: MigrationUnit, through: number): MigrationProblem[];
79
+ export declare function toStep(unit: MigrationUnit, file: MigrationUnit["files"][number]): MigrationStep;
80
+ /**
81
+ * Runs one app hook alone under the migration lock (the CLI's `--adopt` runs `before` first, so the
82
+ * app migration that moves a table and the adoption are one command). Ok when there is no hook.
83
+ */
84
+ export declare function runAppMigrations(handle: DatabaseHandle, app: AppMigrations, phase: AppMigrationPhase): Promise<MigrationResult<{
85
+ ran: boolean;
86
+ }>>;
43
87
  /**
44
88
  * Validates the module list and reads every file: the ledger first, then the modules with a
45
89
  * schema in dependency order. Fails with every problem found.
@@ -50,20 +94,4 @@ export declare function compareJournal(units: readonly MigrationUnit[], journal:
50
94
  problems: MigrationProblem[];
51
95
  pending: MigrationStep[];
52
96
  };
53
- /**
54
- * Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
55
- * problem when the SQL fails; the transaction is rolled back first.
56
- */
57
- export declare function applyFile(session: MigrationSession, input: {
58
- unit: MigrationUnit;
59
- file: MigrationFile;
60
- method: MigrationMethod;
61
- }): Promise<MigrationProblem | null>;
62
- /**
63
- * Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
64
- * connection) is added to the reason instead of hiding the original error.
65
- */
66
- export declare function rollBack(session: MigrationSession, error: unknown): Promise<string>;
67
- /** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
68
- export declare function withMigrationLock<T>(session: MigrationSession, run: () => Promise<T>): Promise<T>;
69
97
  //# sourceMappingURL=migrator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrator.d.ts","sourceRoot":"","sources":["../../src/migrations/migrator.ts"],"names":[],"mappings":"AAIA,OAAO,EAAiC,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACxF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAsB,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EAOL,KAAK,UAAU,EACf,KAAK,eAAe,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAY,KAAK,gBAAgB,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AACtF,OAAO,EAAe,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAElE,MAAM,WAAW,cAAc;IAC7B,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAC9C;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,GAAG,CAAC;IAC7B,mEAAmE;IACnE,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;CACpD;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAA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// 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 } from "@softure-ai/core";
8
+ import { applyFile, describeError, recordAdoption, withMigrationLock } from "./apply.js";
6
9
  import { readMigrationFiles } from "./files.js";
7
- import { LEDGER_FILES, LEDGER_MODULE_ID, LEDGER_SCHEMA, LEDGER_VERSION, readJournal, recordMigration, } from "./ledger.js";
10
+ import { describeSchema, diffSchemas } from "./introspect.js";
11
+ import { LEDGER_FILES, LEDGER_MODULE_ID, LEDGER_SCHEMA, LEDGER_VERSION, readJournal } from "./ledger.js";
8
12
  import { failWith } from "./problems.js";
13
+ import { buildReferenceSchema, listOwnedSchemas } from "./reference.js";
9
14
  import { withSession } from "./session.js";
10
- // Any constant works; it only has to be the same for every runner of every app.
11
- const MIGRATION_LOCK_KEY = "73012026";
12
- const RESERVED_SCHEMAS = new Set([LEDGER_SCHEMA, "public", "information_schema"]);
15
+ import { readAppTables } from "./stubs.js";
16
+ export { applyFile, recordAdoption, rollBack, withMigrationLock } from "./apply.js";
17
+ // `drizzle` holds drizzle's own ledger (`drizzle.__drizzle_migrations`) in every app on this stack.
18
+ const RESERVED_SCHEMAS = new Set([LEDGER_SCHEMA, "public", "information_schema", "drizzle"]);
13
19
  const MAX_IDENTIFIER_BYTES = 63;
14
20
  /** The dry run: what `migrate` would apply. Takes no lock and writes nothing. */
15
21
  export async function planMigrations(handle, options) {
@@ -17,39 +23,202 @@ export async function planMigrations(handle, options) {
17
23
  if (!units.ok) {
18
24
  return units;
19
25
  }
26
+ const baseline = options.app?.baseline ?? {};
27
+ const baselineProblems = checkBaseline(options.modules, units.value, baseline);
28
+ if (baselineProblems.length > 0) {
29
+ return failWith(baselineProblems);
30
+ }
20
31
  const journal = await withSession(handle, readJournal);
21
32
  const comparison = compareJournal(units.value, journal);
22
- return comparison.problems.length > 0 ? failWith(comparison.problems) : ok({ pending: comparison.pending });
33
+ if (comparison.problems.length > 0) {
34
+ return failWith(comparison.problems);
35
+ }
36
+ const adoptable = comparison.pending.filter((step) => isBaselineStep(step, baseline, journal));
37
+ return ok({ pending: comparison.pending, baseline: adoptable });
23
38
  }
24
- /** Applies every pending migration under the advisory lock. */
39
+ /**
40
+ * Applies every pending migration under the advisory lock: the ledger, `app.before`, the module
41
+ * files (adopting a baseline where it applies), then `app.after`. Nothing runs when a check fails.
42
+ */
25
43
  export async function migrate(handle, options) {
26
44
  const units = await prepareUnits(options.modules, options.migrationsDir);
27
45
  if (!units.ok) {
28
46
  return units;
29
47
  }
48
+ const app = options.app ?? {};
49
+ const baseline = app.baseline ?? {};
50
+ const baselineProblems = checkBaseline(options.modules, units.value, baseline);
51
+ if (baselineProblems.length > 0) {
52
+ return failWith(baselineProblems);
53
+ }
30
54
  return withSession(handle, (session) => withMigrationLock(session, async () => {
31
55
  // Read after the lock: a runner that waited sees what the first one applied.
32
- const comparison = compareJournal(units.value, await readJournal(session));
56
+ const journal = await readJournal(session);
57
+ const comparison = compareJournal(units.value, journal);
33
58
  if (comparison.problems.length > 0) {
34
59
  return failWith(comparison.problems);
35
60
  }
36
61
  const applied = [];
37
- for (const step of comparison.pending) {
38
- const unit = units.value.find((candidate) => candidate.module === step.module);
39
- const file = unit?.files.find((candidate) => candidate.version === step.version);
40
- if (unit === undefined || file === undefined) {
41
- throw new Error(`migrate: step ${step.module} ${step.version} has no file; compareJournal is broken`);
62
+ const adopted = [];
63
+ const ranHooks = [];
64
+ const applySteps = async (steps) => {
65
+ for (const step of steps) {
66
+ const { unit, file } = findFile(units.value, step);
67
+ const failure = await applyFile(session, { unit, file, method: "applied" });
68
+ if (failure !== null) {
69
+ return failure;
70
+ }
71
+ applied.push(step);
72
+ options.onApplied?.(step);
73
+ }
74
+ return null;
75
+ };
76
+ const runHook = async (phase) => {
77
+ const failure = await runAppHook(handle, app, phase);
78
+ if (failure === null && app[phase] !== undefined) {
79
+ ranHooks.push(phase);
80
+ options.onAppMigrated?.(phase);
42
81
  }
43
- const failure = await applyFile(session, { unit, file, method: "applied" });
44
- if (failure !== null) {
45
- return failWith([failure]);
82
+ return failure;
83
+ };
84
+ // Unit by unit in dependency order, so a module's dependencies are migrated before its
85
+ // baseline is compared.
86
+ const migrateModules = async () => {
87
+ for (const unit of units.value) {
88
+ if (unit.module === LEDGER_MODULE_ID)
89
+ continue;
90
+ const steps = comparison.pending.filter((step) => step.module === unit.module);
91
+ const through = baseline[unit.module];
92
+ if (through === undefined || journal.some((row) => row.module === unit.module)) {
93
+ const failure = await applySteps(steps);
94
+ if (failure !== null)
95
+ return failure;
96
+ continue;
97
+ }
98
+ const adoption = await adoptBaseline(session, { modules: options.modules, units: units.value, unit, through });
99
+ if (adoption.problem !== null)
100
+ return adoption.problem;
101
+ for (const step of adoption.adopted) {
102
+ adopted.push(step);
103
+ options.onAdopted?.(step);
104
+ }
105
+ const failure = await applySteps(steps.filter((step) => !adoption.adopted.some((done) => done.version === step.version)));
106
+ if (failure !== null)
107
+ return failure;
46
108
  }
47
- applied.push(step);
48
- options.onApplied?.(step);
109
+ return null;
110
+ };
111
+ // The ledger first, so it exists whatever a hook does; then before, the modules, after.
112
+ const ledgerSteps = comparison.pending.filter((step) => step.module === LEDGER_MODULE_ID);
113
+ const failure = (await applySteps(ledgerSteps)) ?? (await runHook("before")) ?? (await migrateModules()) ?? (await runHook("after"));
114
+ if (failure !== null) {
115
+ return failWith([failure]);
49
116
  }
50
- return ok({ applied });
117
+ return ok({ applied, adopted, app: ranHooks });
51
118
  }));
52
119
  }
120
+ /**
121
+ * Adopt-or-migrate for a baseline module the ledger has never seen: an empty schema adopts
122
+ * nothing (its files are then applied normally); otherwise the schema must equal files 1..through,
123
+ * which are then recorded as adopted in one transaction.
124
+ */
125
+ async function adoptBaseline(session, input) {
126
+ const { unit, through } = input;
127
+ const live = await describeSchema(session, unit.schema);
128
+ if (live.length === 0) {
129
+ return { adopted: [], problem: null };
130
+ }
131
+ // Built only here, so a database whose modules are all in the ledger never needs PGlite. The app's
132
+ // tables exist by now (`before` ran), so module SQL that references them finds their stubs.
133
+ const appTables = await readAppTables(session, listOwnedSchemas(input.units));
134
+ const reference = await buildReferenceSchema({ modules: input.modules, units: input.units, target: unit, through, appTables });
135
+ if (!reference.ok) {
136
+ return { adopted: [], problem: reference.problems[0] ?? null };
137
+ }
138
+ const differences = diffSchemas(reference.value, live);
139
+ if (differences.length > 0) {
140
+ return { adopted: [], problem: { code: "db.schema_mismatch", module: unit.module, schema: unit.schema, differences } };
141
+ }
142
+ const files = unit.files.filter((file) => file.version <= through);
143
+ const failure = await recordAdoption(session, unit, files);
144
+ if (failure !== null) {
145
+ return { adopted: [], problem: failure };
146
+ }
147
+ return { adopted: files.map((file) => toStep(unit, file)), problem: null };
148
+ }
149
+ /**
150
+ * A baseline may name only enabled modules with a schema and migrations, and a last file between
151
+ * 1 and the module's file count. Checked before anything runs.
152
+ */
153
+ function checkBaseline(modules, units, baseline) {
154
+ return Object.entries(baseline).flatMap(([module, through]) => {
155
+ if (!modules.some((candidate) => candidate.id === module)) {
156
+ return [{ code: "db.adopt_unknown_module", module }];
157
+ }
158
+ const unit = units.find((candidate) => candidate.module === module);
159
+ if (unit === undefined) {
160
+ return [{ code: "db.adopt_no_schema", module }];
161
+ }
162
+ return checkThrough(unit, through);
163
+ });
164
+ }
165
+ /** `through` must be a whole number from 1 to the unit's file count. */
166
+ export function checkThrough(unit, through) {
167
+ const files = unit.files.length;
168
+ return Number.isInteger(through) && through >= 1 && through <= files
169
+ ? []
170
+ : [{ code: "db.adopt_through_out_of_range", module: unit.module, through, files }];
171
+ }
172
+ function isBaselineStep(step, baseline, journal) {
173
+ const through = baseline[step.module];
174
+ return through !== undefined && step.version <= through && !journal.some((row) => row.module === step.module);
175
+ }
176
+ function findFile(units, step) {
177
+ const unit = units.find((candidate) => candidate.module === step.module);
178
+ const file = unit?.files.find((candidate) => candidate.version === step.version);
179
+ if (unit === undefined || file === undefined) {
180
+ throw new Error(`migrate: step ${step.module} ${step.version} has no file; compareJournal is broken`);
181
+ }
182
+ return { unit, file };
183
+ }
184
+ export function toStep(unit, file) {
185
+ return { module: unit.module, schema: unit.schema, version: file.version, name: file.name, checksum: file.checksum };
186
+ }
187
+ /**
188
+ * Runs one app hook alone under the migration lock (the CLI's `--adopt` runs `before` first, so the
189
+ * app migration that moves a table and the adoption are one command). Ok when there is no hook.
190
+ */
191
+ export async function runAppMigrations(handle, app, phase) {
192
+ if (app[phase] === undefined) {
193
+ return ok({ ran: false });
194
+ }
195
+ const failure = await withSession(handle, (session) => withMigrationLock(session, () => runAppHook(handle, app, phase)));
196
+ return failure === null ? ok({ ran: true }) : failWith([failure]);
197
+ }
198
+ async function runAppHook(handle, app, phase) {
199
+ const hook = app[phase];
200
+ if (hook === undefined) {
201
+ return null;
202
+ }
203
+ try {
204
+ await hook(handle);
205
+ return null;
206
+ }
207
+ catch (error) {
208
+ return { code: "db.app_migration_failed", phase, reason: describeErrorChain(error) };
209
+ }
210
+ }
211
+ // drizzle wraps the database error (`Failed query: <sql>`, the Postgres message in `cause`), so the
212
+ // whole chain is the reason.
213
+ function describeErrorChain(error) {
214
+ const messages = [];
215
+ let current = error;
216
+ while (current !== undefined && current !== null && messages.length < 5) {
217
+ messages.push(describeError(current));
218
+ current = current instanceof Error ? current.cause : undefined;
219
+ }
220
+ return messages.join(": ");
221
+ }
53
222
  /**
54
223
  * Validates the module list and reads every file: the ledger first, then the modules with a
55
224
  * schema in dependency order. Fails with every problem found.
@@ -113,85 +282,6 @@ export function compareJournal(units, journal) {
113
282
  }
114
283
  return { problems, pending };
115
284
  }
116
- /**
117
- * Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
118
- * problem when the SQL fails; the transaction is rolled back first.
119
- */
120
- export async function applyFile(session, input) {
121
- const { unit, file, method } = input;
122
- // The schema passed the manifest's lower_snake_case rule and checkModule; quoting is a second line.
123
- const schema = quoteIdentifier(unit.schema);
124
- try {
125
- await session.exec(`BEGIN; CREATE SCHEMA IF NOT EXISTS ${schema}; SET LOCAL search_path TO ${schema}, public;`);
126
- const transactionId = await readTransactionId(session);
127
- if (method === "applied") {
128
- await session.exec(file.sql);
129
- }
130
- // Second line behind findTransactionControl: a file that still ended the transaction left
131
- // part of itself committed, so it must not be reported as cleanly rolled back.
132
- if ((await readTransactionId(session)) !== transactionId) {
133
- throw new TransactionEndedError();
134
- }
135
- await recordMigration(session, {
136
- module: unit.module,
137
- version: file.version,
138
- name: file.name,
139
- checksum: file.checksum,
140
- moduleVersion: unit.moduleVersion,
141
- method,
142
- });
143
- await session.exec("COMMIT");
144
- return null;
145
- }
146
- catch (error) {
147
- const reason = await rollBack(session, error);
148
- return { code: "db.migration_failed", module: unit.module, version: file.version, name: file.name, reason };
149
- }
150
- }
151
- class TransactionEndedError extends Error {
152
- constructor() {
153
- super("the file ended the migrator's transaction, so the statements before that point may be committed; check the schema by hand");
154
- }
155
- }
156
- // The transaction id, not now(): two transactions can share a start time (PGlite's clock ticks in
157
- // milliseconds), but never an id.
158
- async function readTransactionId(session) {
159
- const [row] = await session.query("SELECT pg_current_xact_id()::text AS id");
160
- return row?.id ?? "";
161
- }
162
- /**
163
- * Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
164
- * connection) is added to the reason instead of hiding the original error.
165
- */
166
- export async function rollBack(session, error) {
167
- const reason = describeError(error);
168
- try {
169
- await session.exec("ROLLBACK");
170
- return reason;
171
- }
172
- catch (rollbackError) {
173
- return `${reason} (and ROLLBACK failed: ${describeError(rollbackError)})`;
174
- }
175
- }
176
- /** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
177
- export async function withMigrationLock(session, run) {
178
- await session.query("SELECT pg_advisory_lock($1)", [MIGRATION_LOCK_KEY]);
179
- let result;
180
- try {
181
- result = await run();
182
- }
183
- catch (error) {
184
- // The run's own error wins; an unlock failure here is secondary (the session is discarded).
185
- await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]).catch((unlockError) => {
186
- throw new Error(`migration run failed (${describeError(error)}) and releasing the lock failed: ${describeError(unlockError)}`, {
187
- cause: error,
188
- });
189
- });
190
- throw error;
191
- }
192
- await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]);
193
- return result;
194
- }
195
285
  function checkModule(module) {
196
286
  const schema = module.manifest.dbSchema;
197
287
  if (module.id === LEDGER_MODULE_ID || (schema !== null && isReservedSchema(schema))) {
@@ -205,13 +295,7 @@ function checkModule(module) {
205
295
  function isReservedSchema(schema) {
206
296
  return RESERVED_SCHEMAS.has(schema) || schema.startsWith("pg_") || Buffer.byteLength(schema, "utf8") > MAX_IDENTIFIER_BYTES;
207
297
  }
208
- function quoteIdentifier(name) {
209
- return `"${name.replace(/"/g, '""')}"`;
210
- }
211
298
  function ensureFolderUrl(url) {
212
299
  return url.href.endsWith("/") ? url : new URL(`${url.href}/`);
213
300
  }
214
- function describeError(error) {
215
- return error instanceof Error ? error.message : String(error);
216
- }
217
301
  //# sourceMappingURL=migrator.js.map