okmodel 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +182 -22
  2. package/dist/contracts/catalog/document.d.ts +6 -2
  3. package/dist/dialects/pg/ext/citext.js +1 -1
  4. package/dist/dialects/pg/ext/index.js +1 -1
  5. package/dist/dialects/pg/ext/pg-trgm.js +1 -1
  6. package/dist/dialects/pg/index.js +3 -3
  7. package/dist/dialects/pg/role/sql.d.ts +11 -4
  8. package/dist/dialects/pg/table.d.ts +17 -1
  9. package/dist/dialects/pg/view/index.js +1 -1
  10. package/dist/dialects/pg/view/scratch.d.ts +3 -2
  11. package/dist/runtime/catalog-cache.d.ts +17 -0
  12. package/dist/runtime/compat-words.d.ts +23 -0
  13. package/dist/runtime/drift-detail.d.ts +20 -4
  14. package/dist/runtime/drift.d.ts +4 -2
  15. package/dist/runtime/pg/bun.js +2 -2
  16. package/dist/runtime/pg/pg.js +2 -2
  17. package/dist/runtime/pg/pglite.js +2 -2
  18. package/dist/runtime/pg/postgresjs.js +2 -2
  19. package/dist/runtime/traits/index.js +5 -4
  20. package/dist/runtime/types.d.ts +2 -0
  21. package/dist/runtime/validate/index.js +2 -2
  22. package/dist/shared/2321avmn.js +418 -0
  23. package/dist/shared/{x6wysh83.js → 3p4b1fg0.js} +3 -5
  24. package/dist/shared/{wekze34d.js → 41kv2xdm.js} +74 -2
  25. package/dist/shared/{fs0ex00p.js → 4ef7mmqf.js} +2 -2
  26. package/dist/shared/5mtf6cj3.js +94 -0
  27. package/dist/shared/{999ade2q.js → 5vdm4sgp.js} +1 -1
  28. package/dist/shared/{qybh48nd.js → 6693j9rs.js} +1 -1
  29. package/dist/shared/{bqha5cg6.js → 6p5k20sm.js} +2 -2
  30. package/dist/shared/7nk68fj8.js +751 -0
  31. package/dist/shared/{ne02ng5c.js → 84ptn35q.js} +7 -4
  32. package/dist/shared/{t616ynfn.js → 8jb4ymh2.js} +59 -12
  33. package/dist/shared/{th14ygv2.js → 8ktwd3rh.js} +29 -1
  34. package/dist/shared/9yn6a2vd.js +11 -0
  35. package/dist/shared/ady1ms74.js +72 -0
  36. package/dist/shared/{scwxrpx2.js → c5g81ngb.js} +82 -15
  37. package/dist/shared/{6bazvqwm.js → fb00y8fp.js} +2 -2
  38. package/dist/shared/{jkc6ws1p.js → g7ez901n.js} +83 -2
  39. package/dist/shared/{kgnc8grt.js → gdh9mrtp.js} +1 -1
  40. package/dist/shared/hqjsxnz7.js +13 -0
  41. package/dist/shared/htnaj77v.js +17 -0
  42. package/dist/shared/{mt5wswjz.js → jgxzjzcz.js} +1 -1
  43. package/dist/shared/{6w5j844a.js → jsd07prz.js} +2 -2
  44. package/dist/shared/{m78s7898.js → kafaa5zv.js} +1 -1
  45. package/dist/shared/kj680nxv.js +19 -0
  46. package/dist/shared/{k34e0xf2.js → kkzwp3d2.js} +8 -8
  47. package/dist/shared/{2ssqrv66.js → n5y9zyj1.js} +1029 -174
  48. package/dist/shared/{ty3v3hfk.js → nxb42q7h.js} +2 -2
  49. package/dist/shared/{5nmdenb6.js → q6zsyh31.js} +1003 -40
  50. package/dist/shared/{fptpmvxp.js → q795afwa.js} +26 -21
  51. package/dist/shared/{3ekj9x92.js → qn0srwwq.js} +1 -1
  52. package/dist/shared/s4mb6a4b.js +545 -0
  53. package/dist/shared/{01yr20s5.js → sf8m6tfy.js} +2 -2
  54. package/dist/shared/{bryqk9k9.js → sr5ms7b3.js} +1 -1
  55. package/dist/shared/{meck53jv.js → tny2t3sm.js} +6 -5
  56. package/dist/shared/{p24x2334.js → v7tpnhnz.js} +1 -1
  57. package/dist/shared/{xw1d69vd.js → wqem4jed.js} +6 -6
  58. package/dist/shared/{49ypnfwt.js → xghkt7a9.js} +50 -28
  59. package/dist/shared/{7fvtrkwr.js → ycatkxmq.js} +1 -1
  60. package/dist/shared/ygem90rn.js +900 -0
  61. package/dist/shared/{1tfdfvhh.js → yjw02enp.js} +6 -4
  62. package/dist/shared/{ydaz1sv3.js → zg24x0hm.js} +1 -1
  63. package/dist/tooling/cli.js +46 -17
  64. package/dist/tooling/migrate/apply.d.ts +59 -5
  65. package/dist/tooling/migrate/backfill.d.ts +136 -0
  66. package/dist/tooling/migrate/check.d.ts +65 -0
  67. package/dist/tooling/migrate/classify.d.ts +108 -0
  68. package/dist/tooling/migrate/commands.d.ts +2 -2
  69. package/dist/tooling/migrate/config.d.ts +22 -0
  70. package/dist/tooling/migrate/doctor.d.ts +3 -0
  71. package/dist/tooling/migrate/drift.d.ts +18 -2
  72. package/dist/tooling/migrate/estimate.d.ts +50 -0
  73. package/dist/tooling/migrate/extensions.d.ts +2 -0
  74. package/dist/tooling/migrate/files.d.ts +12 -0
  75. package/dist/tooling/migrate/index.d.ts +3 -2
  76. package/dist/tooling/migrate/index.js +67 -1
  77. package/dist/tooling/migrate/lint-rules.d.ts +51 -0
  78. package/dist/tooling/migrate/lint.d.ts +71 -0
  79. package/dist/tooling/migrate/managed.d.ts +1 -1
  80. package/dist/tooling/migrate/plan.d.ts +64 -9
  81. package/dist/tooling/migrate/project.d.ts +42 -7
  82. package/dist/tooling/migrate/provision.d.ts +18 -0
  83. package/dist/tooling/migrate/reference.d.ts +40 -0
  84. package/dist/tooling/migrate/runner.d.ts +108 -0
  85. package/dist/tooling/migrate/safe.d.ts +77 -0
  86. package/dist/tooling/migrate/seed.d.ts +20 -0
  87. package/dist/tooling/migrate/snapshot.d.ts +78 -0
  88. package/dist/tooling/migrate/status.d.ts +25 -6
  89. package/dist/tooling/testing/factories.d.ts +117 -0
  90. package/dist/tooling/testing/facts.d.ts +72 -0
  91. package/dist/tooling/testing/index.d.ts +89 -0
  92. package/dist/tooling/testing/index.js +8 -0
  93. package/dist/tooling/testing/isolation.d.ts +30 -0
  94. package/dist/tooling/testing/random.d.ts +40 -0
  95. package/dist/tooling/testing/record.d.ts +38 -0
  96. package/package.json +6 -2
  97. package/dist/shared/dbjej1tw.js +0 -456
  98. package/dist/shared/g4f5kcx9.js +0 -37
  99. package/dist/shared/qbxzvwwc.js +0 -88
  100. package/dist/shared/zwmqxb0g.js +0 -79
  101. package/dist/shared/{xva8v7qk.js → awrsqrn7.js} +3 -3
  102. package/dist/shared/{75xkjv0t.js → fa9vt245.js} +0 -0
  103. package/dist/shared/{m9tv7xn7.js → radd3z4g.js} +3 -3
  104. /package/dist/shared/{0jc3ffzf.js → zvbjc949.js} +0 -0
@@ -672,6 +672,8 @@ export type ConnectOptions<S extends QuerySchema> = {
672
672
  * Directory of `catalog.hash` and `catalog.json`.
673
673
  *
674
674
  * When omitted, `connect` reads `.okm` under the process cwd if that hash file exists.
675
+ * The hash file is the fast path. A mismatch then reads `catalog.json` once
676
+ * per process and does not rebuild the catalog from the schema.
675
677
  */
676
678
  readonly catalogDir?: string;
677
679
  readonly logger?: {
@@ -3,10 +3,10 @@ import {
3
3
  } from "../../shared/9m80mkac.js";
4
4
  import {
5
5
  addSchemaHook
6
- } from "../../shared/x6wysh83.js";
6
+ } from "../../shared/3p4b1fg0.js";
7
7
  import {
8
8
  queryHandle
9
- } from "../../shared/k34e0xf2.js";
9
+ } from "../../shared/kkzwp3d2.js";
10
10
  import {
11
11
  OkmError2
12
12
  } from "../../shared/52szzakm.js";
@@ -0,0 +1,418 @@
1
+ import {
2
+ parseCatalog2
3
+ } from "./8jb4ymh2.js";
4
+ import"./wqem4jed.js";
5
+ import"./n442h54c.js";
6
+ import {
7
+ applyTarget2,
8
+ backfillTiming2
9
+ } from "./s4mb6a4b.js";
10
+ import {
11
+ introspectSchema,
12
+ sealViews,
13
+ catalogQuery2,
14
+ managedRoleOptions2
15
+ } from "./xghkt7a9.js";
16
+ import {
17
+ loadMigrations,
18
+ catalogsEqual,
19
+ snapshotDifference
20
+ } from "./7nk68fj8.js";
21
+ import {
22
+ lintMigrationDirectory,
23
+ hasError,
24
+ lintRefusal,
25
+ selectTarget,
26
+ openProject
27
+ } from "./q6zsyh31.js";
28
+ import {
29
+ canonicalTypeName,
30
+ classOf,
31
+ strictestClass,
32
+ planMigration,
33
+ parsePlan
34
+ } from "./n5y9zyj1.js";
35
+ import {
36
+ quoteIdent
37
+ } from "./41kv2xdm.js";
38
+ import {
39
+ catalog,
40
+ isDomain
41
+ } from "./g7ez901n.js";
42
+ import {
43
+ identityKey2
44
+ } from "./t4tbsy9h.js";
45
+ import {
46
+ OkmError2
47
+ } from "./52szzakm.js";
48
+
49
+ // src/tooling/migrate/check.ts
50
+ import { readFileSync } from "node:fs";
51
+ import { join } from "node:path";
52
+ import postgres from "postgres";
53
+ var CHECK_SCHEMA_PREFIX = "okm_check_";
54
+ var HISTORY_CODE = "OKM1547";
55
+ var PREVIOUS_CODE = "OKM1548";
56
+ var STALE_CODE = "OKM1549";
57
+ var HISTORY_FIX = "Regenerate the migration so the stored catalog matches the schema the SQL applies.";
58
+ var FORK_FIX = "Generate the later migration from the previous migration's catalog, not from an older parent.";
59
+ var PREVIOUS_FIX = "Keep every table, column, constraint, and type the previous catalog relies on, or classify the migration as contract.";
60
+ var STALE_FIX = "Run okm generate.";
61
+ async function checkMigrations(cwd, flags, options) {
62
+ const opened = await openProject(cwd);
63
+ const target = selectTarget(opened.config, flags.target);
64
+ if (target.protected) {
65
+ throw new OkmError2("OKM1850", `okm migrate check writes a scratch schema and refuses protected target ${target.name}. Point it at a throwaway Postgres.`, {
66
+ kind: "forbidden",
67
+ fix: {
68
+ summary: "Point okm migrate check at a throwaway Postgres. --allow-protected does not apply."
69
+ }
70
+ });
71
+ }
72
+ const directory = join(cwd, opened.config.migrations ?? "migrations");
73
+ const history = readHistory(directory);
74
+ if (options?.provision === true) {
75
+ const equivalence = await proveSnapshot(opened.config, target.url, target.name, flags, history);
76
+ if (equivalence !== undefined)
77
+ throwFailure([equivalence]);
78
+ }
79
+ const previous = previousFailures(history);
80
+ const stale = staleFailure(history, opened.built.catalog);
81
+ const lint = lintFailure(directory, history, opened.config.lintFrom);
82
+ const replayed = await replayHistory(opened.config, target.url, target.name, flags, history);
83
+ const failures = [...replayed, ...previous, ...stale, ...lint];
84
+ if (failures.length > 0)
85
+ throwFailure(failures);
86
+ return `ok ${String(history.length)} migrations
87
+ `;
88
+ }
89
+ function previousCatalogGaps(before, after) {
90
+ const afterBy = new Map(after.objects.map((object) => [identityKey2(object.identity), object]));
91
+ const gaps = [];
92
+ for (const object of before.objects) {
93
+ if (!checkedKind(object.kind))
94
+ continue;
95
+ const next = afterBy.get(identityKey2(object.identity));
96
+ if (next === undefined || next.kind !== object.kind) {
97
+ gaps.push(`${objectLabel(object)} is missing`);
98
+ continue;
99
+ }
100
+ if (object.kind === "column" && next.kind === "column") {
101
+ gaps.push(...columnGaps(object, next));
102
+ }
103
+ if (object.kind === "type" && next.kind === "type" && !sameType(object.definition, next.definition)) {
104
+ gaps.push(`${objectLabel(object)} changed`);
105
+ }
106
+ }
107
+ return gaps;
108
+ }
109
+ function recomputedMigrationClass(plan, before, after) {
110
+ if (plan.steps.length === 0)
111
+ return "expand";
112
+ if (plan.steps.some((step) => step.kind === undefined)) {
113
+ return planMigration({ before, after, name: plan.name }).class;
114
+ }
115
+ return strictestClass(plan.steps.map((step) => classOf(step.kind ?? "raw-sql")));
116
+ }
117
+ function migrationAllowsPreviousGaps(plan, before, after) {
118
+ return recomputedMigrationClass(plan, before, after) === "contract" && plan.class !== "expand";
119
+ }
120
+ function previousFailures(history) {
121
+ const failures = [];
122
+ let before = catalog([]);
123
+ for (const migration of history) {
124
+ const gaps = previousCatalogGaps(before, migration.catalog);
125
+ if (gaps.length > 0 && !migrationAllowsPreviousGaps(migration.plan, before, migration.catalog)) {
126
+ const stated = migration.plan.class === "expand" ? "expand" : recomputedMigrationClass(migration.plan, before, migration.catalog);
127
+ failures.push({
128
+ code: PREVIOUS_CODE,
129
+ message: `${migration.id}: previous catalog is not satisfied (${gaps.join("; ")}). The migration is classified ${stated}.`,
130
+ fix: PREVIOUS_FIX
131
+ });
132
+ }
133
+ before = migration.catalog;
134
+ }
135
+ return failures;
136
+ }
137
+ function staleFailure(history, head) {
138
+ const last = history.at(-1)?.catalog ?? catalog([]);
139
+ if (catalogsEqual(last, head))
140
+ return [];
141
+ return [
142
+ {
143
+ code: STALE_CODE,
144
+ message: "The last migration's catalog does not match the schema.",
145
+ fix: STALE_FIX
146
+ }
147
+ ];
148
+ }
149
+ function lintFailure(directory, history, lintFrom) {
150
+ const findings = lintMigrationDirectory(directory, lintIds(history, lintFrom));
151
+ if (!hasError(findings))
152
+ return [];
153
+ const refusal = lintRefusal(findings);
154
+ return [{ code: refusal.code, message: refusal.message, fix: refusal.fix.summary }];
155
+ }
156
+ function lintIds(history, lintFrom) {
157
+ if (lintFrom === undefined)
158
+ return;
159
+ const ids = history.map((migration) => migration.id);
160
+ const start = ids.indexOf(lintFrom);
161
+ if (start < 0) {
162
+ throw new OkmError2("invalid", `lintFrom ${lintFrom} is not a migration id.`, {
163
+ fix: {
164
+ summary: "Set lintFrom to a migration id. Files before that id are the adoption baseline and are not linted."
165
+ }
166
+ });
167
+ }
168
+ return new Set(ids.slice(start));
169
+ }
170
+ async function proveSnapshot(config, url, target, flags, history) {
171
+ const head = history.at(-1);
172
+ if (head === undefined)
173
+ return;
174
+ const sql = postgres(url, {
175
+ max: 1,
176
+ connect_timeout: 5,
177
+ idle_timeout: 1,
178
+ onnotice: () => {}
179
+ });
180
+ const provided = `${CHECK_SCHEMA_PREFIX}p${crypto.randomUUID().replaceAll("-", "")}`;
181
+ const replayed = `${CHECK_SCHEMA_PREFIX}r${crypto.randomUUID().replaceAll("-", "")}`;
182
+ const timing = {
183
+ ...flags.lockTimeoutMs !== undefined ? { lockTimeoutMs: flags.lockTimeoutMs } : config.timeouts?.lock !== undefined ? { lockTimeoutMs: config.timeouts.lock } : {},
184
+ ...flags.statementTimeoutMs !== undefined ? { statementTimeoutMs: flags.statementTimeoutMs } : config.timeouts?.statement !== undefined ? { statementTimeoutMs: config.timeouts.statement } : {},
185
+ ...backfillTiming2(config.backfill)
186
+ };
187
+ try {
188
+ await sql.unsafe(`create schema ${quoteIdent(provided)}`);
189
+ await sql.unsafe(`create schema ${quoteIdent(replayed)}`);
190
+ const role = config.roles === undefined ? {} : { migrationRole: config.roles.migration, schema: provided };
191
+ await applyTarget2({
192
+ url,
193
+ target,
194
+ protected: false,
195
+ allowProtected: false,
196
+ allowPooler: flags.allowPooler || config.allowPooler === true,
197
+ searchPath: provided,
198
+ ...timing,
199
+ migrations: history.map((migration) => ({
200
+ id: migration.id,
201
+ catalogHash: migration.catalogHash,
202
+ steps: migration.steps
203
+ })),
204
+ snapshot: {
205
+ catalog: head.catalog,
206
+ migrationId: head.id,
207
+ catalogHash: head.catalogHash,
208
+ reference: [],
209
+ only: true
210
+ },
211
+ ...role
212
+ });
213
+ await applyTarget2({
214
+ url,
215
+ target,
216
+ protected: false,
217
+ allowProtected: false,
218
+ allowPooler: flags.allowPooler || config.allowPooler === true,
219
+ searchPath: replayed,
220
+ ...timing,
221
+ migrations: history.map((migration) => ({
222
+ id: migration.id,
223
+ catalogHash: migration.catalogHash,
224
+ steps: retargetSteps(migration.steps, replayed)
225
+ })),
226
+ ...config.roles !== undefined ? { migrationRole: config.roles.migration, schema: replayed } : {}
227
+ });
228
+ const runner = catalogQuery2(sql);
229
+ const liveProvided = await introspectSchema(runner, provided, "public", managedRoleOptions2(config.roles));
230
+ const liveReplayed = await introspectSchema(runner, replayed, "public", managedRoleOptions2(config.roles));
231
+ const difference = snapshotDifference(liveProvided, liveReplayed);
232
+ if (difference === undefined)
233
+ return;
234
+ return {
235
+ code: "OKM1521",
236
+ message: `Provisioning from the snapshot does not match the replayed history.
237
+ ${difference}`,
238
+ fix: "Regenerate the snapshot from the history. okm migrate check --provision is the command that reports this."
239
+ };
240
+ } finally {
241
+ await sql.unsafe(`drop schema if exists ${quoteIdent(provided)} cascade`).catch(() => {
242
+ return;
243
+ });
244
+ await sql.unsafe(`drop schema if exists ${quoteIdent(replayed)} cascade`).catch(() => {
245
+ return;
246
+ });
247
+ await sql.end({ timeout: 5 });
248
+ }
249
+ }
250
+ async function replayHistory(config, url, target, flags, history) {
251
+ if (history.length === 0)
252
+ return [];
253
+ const sql = postgres(url, {
254
+ max: 1,
255
+ connect_timeout: 5,
256
+ idle_timeout: 1,
257
+ onnotice: () => {}
258
+ });
259
+ const scratch = `${CHECK_SCHEMA_PREFIX}${crypto.randomUUID().replaceAll("-", "")}`;
260
+ const failures = [];
261
+ try {
262
+ await sql.unsafe(`create schema ${quoteIdent(scratch)}`);
263
+ const runner = catalogQuery2(sql);
264
+ for (let index = 0;index < history.length; index += 1) {
265
+ const migration = history[index];
266
+ if (migration === undefined)
267
+ continue;
268
+ await applyTarget2({
269
+ url,
270
+ target,
271
+ protected: false,
272
+ allowProtected: false,
273
+ allowPooler: flags.allowPooler || config.allowPooler === true,
274
+ searchPath: scratch,
275
+ ...flags.lockTimeoutMs !== undefined ? { lockTimeoutMs: flags.lockTimeoutMs } : config.timeouts?.lock !== undefined ? { lockTimeoutMs: config.timeouts.lock } : {},
276
+ ...flags.statementTimeoutMs !== undefined ? { statementTimeoutMs: flags.statementTimeoutMs } : config.timeouts?.statement !== undefined ? { statementTimeoutMs: config.timeouts.statement } : {},
277
+ ...backfillTiming2(config.backfill),
278
+ migrations: [
279
+ {
280
+ id: migration.id,
281
+ catalogHash: migration.catalogHash,
282
+ steps: retargetSteps(migration.steps, scratch)
283
+ }
284
+ ],
285
+ ...config.roles !== undefined ? { migrationRole: config.roles.migration, schema: scratch } : {}
286
+ });
287
+ const live = await introspectSchema(runner, scratch, "public", managedRoleOptions2(config.roles));
288
+ const sealed = await sealViews(runner, migration.catalog);
289
+ const back = planMigration({ before: live, after: sealed, name: migration.id });
290
+ if (back.steps.length === 0)
291
+ continue;
292
+ failures.push(historyFailure(history, index, back));
293
+ break;
294
+ }
295
+ } finally {
296
+ await sql.unsafe(`drop schema if exists ${quoteIdent(scratch)} cascade`).catch(() => {
297
+ return;
298
+ });
299
+ await sql.end({ timeout: 5 });
300
+ }
301
+ return failures;
302
+ }
303
+ function historyFailure(history, index, back) {
304
+ const migration = history[index];
305
+ const id = migration?.id ?? "migration";
306
+ const fork = migration === undefined ? undefined : forkMessage(history, index);
307
+ if (fork !== undefined)
308
+ return { code: HISTORY_CODE, message: fork, fix: FORK_FIX };
309
+ const steps = back.steps.map((step) => step.sql).join(`
310
+ `);
311
+ return {
312
+ code: HISTORY_CODE,
313
+ message: `${id}: history differs from the stored catalog
314
+ ${steps}`,
315
+ fix: HISTORY_FIX
316
+ };
317
+ }
318
+ function forkMessage(history, index) {
319
+ const current = history[index];
320
+ const previous = history[index - 1];
321
+ if (current === undefined || previous === undefined)
322
+ return;
323
+ if (samePlan(previous.catalog, current.catalog, current.plan))
324
+ return;
325
+ for (let parentIndex = 0;parentIndex < index; parentIndex += 1) {
326
+ const parent = parentIndex === 0 ? catalog([]) : history[parentIndex - 1]?.catalog;
327
+ if (parent === undefined)
328
+ continue;
329
+ if (!samePlan(parent, current.catalog, current.plan))
330
+ continue;
331
+ return `migration ${current.id} was generated from a different parent than ${previous.id}`;
332
+ }
333
+ return;
334
+ }
335
+ function samePlan(before, after, file) {
336
+ try {
337
+ return sameSql(planMigration({ before, after, name: "parent" }), file);
338
+ } catch (error) {
339
+ if (error instanceof OkmError2 && error.code === "OKM1530")
340
+ return false;
341
+ throw error;
342
+ }
343
+ }
344
+ function sameSql(planned, file) {
345
+ if (planned.steps.length !== file.steps.length)
346
+ return false;
347
+ return planned.steps.every((step, index) => step.sql === file.steps[index]?.sql);
348
+ }
349
+ function retargetSteps(steps, schema) {
350
+ const from = `${quoteIdent("public")}.`;
351
+ const to = `${quoteIdent(schema)}.`;
352
+ return steps.map((step) => ({
353
+ ...step,
354
+ sql: step.sql.replaceAll(from, to),
355
+ ...step.backfill === undefined ? {} : { backfill: { ...step.backfill, table: step.backfill.table.replaceAll(from, to) } }
356
+ }));
357
+ }
358
+ function readHistory(directory) {
359
+ return loadMigrations(directory).map((migration) => ({
360
+ id: migration.id,
361
+ catalogHash: migration.catalogHash,
362
+ steps: migration.steps,
363
+ plan: parsePlan(readFileSync(join(directory, `${migration.id}.sql`), "utf8")),
364
+ catalog: parseCatalog2(readFileSync(join(directory, `${migration.id}.catalog.json`), "utf8"))
365
+ }));
366
+ }
367
+ function throwFailure(failures) {
368
+ const first = failures[0];
369
+ if (first === undefined)
370
+ throw new Error("okm migrate check has no failure to report.");
371
+ const message = failures.length === 1 ? first.message : failures.map((failure) => `${failure.code} ${failure.message}`).join(`
372
+ `);
373
+ throw new OkmError2(first.code, message, { fix: { summary: first.fix } });
374
+ }
375
+ function checkedKind(kind) {
376
+ return kind === "table" || kind === "column" || kind === "constraint" || kind === "type";
377
+ }
378
+ function columnGaps(before, after) {
379
+ const gaps = [];
380
+ const place = objectLabel(before);
381
+ if (canonicalTypeName(before.definition.dataType) !== canonicalTypeName(after.definition.dataType)) {
382
+ gaps.push(`${place} changed type from ${before.definition.dataType} to ${after.definition.dataType}`);
383
+ }
384
+ if (before.definition.nullable && !after.definition.nullable && !columnHasDefault(after)) {
385
+ gaps.push(`${place} nullability tightened without a default`);
386
+ }
387
+ return gaps;
388
+ }
389
+ function columnHasDefault(column) {
390
+ return column.definition.defaultExpression !== undefined || column.definition.identity !== undefined || column.definition.generated !== undefined;
391
+ }
392
+ function sameType(before, after) {
393
+ const beforeDomain = isDomain(before);
394
+ const afterDomain = isDomain(after);
395
+ if (beforeDomain !== afterDomain)
396
+ return false;
397
+ if (beforeDomain && afterDomain) {
398
+ return canonicalTypeName(before.base) === canonicalTypeName(after.base) && before.check === after.check;
399
+ }
400
+ if (!beforeDomain && !afterDomain) {
401
+ if (before.labels.length !== after.labels.length)
402
+ return false;
403
+ return before.labels.every((label, index) => label === after.labels[index]);
404
+ }
405
+ return false;
406
+ }
407
+ function objectLabel(object) {
408
+ if (object.kind === "column" || object.kind === "constraint") {
409
+ return `${object.kind} ${object.identity.parent.name}.${object.identity.name}`;
410
+ }
411
+ if (object.kind === "table" || object.kind === "type") {
412
+ return `${object.kind} ${object.identity.name}`;
413
+ }
414
+ return object.kind;
415
+ }
416
+ export {
417
+ checkMigrations
418
+ };
@@ -1,15 +1,13 @@
1
1
  import {
2
- catalog
3
- } from "./jkc6ws1p.js";
4
- import {
2
+ catalog,
5
3
  enumType,
6
4
  sameEnumLabels
7
- } from "./qbxzvwwc.js";
5
+ } from "./g7ez901n.js";
8
6
  import {
9
7
  snakeCase,
10
8
  emittedTypeName,
11
9
  rejectLater
12
- } from "./6w5j844a.js";
10
+ } from "./jsd07prz.js";
13
11
  import {
14
12
  withLocation
15
13
  } from "./k7dwkhvq.js";
@@ -1,6 +1,9 @@
1
+ import {
2
+ creationOrder2
3
+ } from "./8jb4ymh2.js";
1
4
  import {
2
5
  isDomain
3
- } from "./qbxzvwwc.js";
6
+ } from "./g7ez901n.js";
4
7
  import {
5
8
  quoteLiteral
6
9
  } from "./94ez8kzh.js";
@@ -15,6 +18,61 @@ import {
15
18
  function quoteIdent(name) {
16
19
  return `"${name.replaceAll('"', '""')}"`;
17
20
  }
21
+ function renderCatalog(source, schema) {
22
+ const folded = foldedKeys(source);
23
+ const statements = [];
24
+ const ordered = creationOrder2(source);
25
+ for (const object of ordered) {
26
+ if (object.kind !== "type" || object.owner === "ignored")
27
+ continue;
28
+ const sql = createObjectSql(object, schema);
29
+ if (sql !== undefined)
30
+ statements.push(sql);
31
+ }
32
+ for (const object of ordered) {
33
+ if (object.kind === "type" || object.kind === "function" || object.kind === "trigger" || object.kind === "view" || object.kind === "materializedView" || ownedByView(object)) {
34
+ continue;
35
+ }
36
+ if (object.owner === "ignored")
37
+ continue;
38
+ const key = identityKey2(object.identity);
39
+ if (object.kind === "table") {
40
+ statements.push(createTableSql(object, source, schema));
41
+ continue;
42
+ }
43
+ if (folded.has(key))
44
+ continue;
45
+ const sql = createObjectSql(object, schema);
46
+ if (sql !== undefined)
47
+ statements.push(sql);
48
+ }
49
+ for (const kind of ["function", "trigger"]) {
50
+ for (const object of ordered) {
51
+ if (object.kind !== kind || object.owner === "ignored")
52
+ continue;
53
+ const sql = createObjectSql(object, schema);
54
+ if (sql !== undefined)
55
+ statements.push(sql);
56
+ }
57
+ }
58
+ for (const kind of ["view", "materializedView"]) {
59
+ for (const object of ordered) {
60
+ if (object.kind !== kind || object.owner === "ignored")
61
+ continue;
62
+ const sql = createObjectSql(object, schema);
63
+ if (sql !== undefined)
64
+ statements.push(sql);
65
+ }
66
+ }
67
+ for (const object of ordered) {
68
+ if (!ownedByView(object) || object.owner === "ignored")
69
+ continue;
70
+ const sql = createObjectSql(object, schema);
71
+ if (sql !== undefined)
72
+ statements.push(sql);
73
+ }
74
+ return statements;
75
+ }
18
76
  function ownedByView(object) {
19
77
  if (object.kind !== "index")
20
78
  return false;
@@ -145,6 +203,20 @@ function identitySequence(sequence, source) {
145
203
  return object.dependencies.some((edge) => identityKey2(edge.target) === key);
146
204
  });
147
205
  }
206
+ function foldedKeys(source) {
207
+ const keys = new Set;
208
+ for (const object of source.objects) {
209
+ if (object.kind === "column")
210
+ keys.add(identityKey2(object.identity));
211
+ if (object.kind === "constraint" && object.definition.constraintKind === "primaryKey") {
212
+ keys.add(identityKey2(object.identity));
213
+ }
214
+ if (object.kind === "sequence" && identitySequence(object, source)) {
215
+ keys.add(identityKey2(object.identity));
216
+ }
217
+ }
218
+ return keys;
219
+ }
148
220
  function createTableSql(tableObject, source, schema) {
149
221
  const parent = tableObject.identity.name;
150
222
  const columns = source.objects.filter((object) => object.kind === "column" && object.identity.parent.name === parent);
@@ -243,4 +315,4 @@ function qualify(schema, name) {
243
315
  return `${quoteIdent(schema)}.${quoteIdent(name)}`;
244
316
  }
245
317
 
246
- export { quoteIdent, ownedByView, dropObjectSql, createObjectSql, functionSql, viewSql, refreshMaterializedViewSql, alterColumnSql, identitySequence, createTableSql, qualify };
318
+ export { quoteIdent, renderCatalog, ownedByView, dropObjectSql, createObjectSql, functionSql, viewSql, refreshMaterializedViewSql, alterColumnSql, identitySequence, createTableSql, qualify };
@@ -2,13 +2,13 @@ import {
2
2
  send2,
3
3
  reserve,
4
4
  park
5
- } from "./01yr20s5.js";
5
+ } from "./sf8m6tfy.js";
6
6
  import {
7
7
  isConnectionLost
8
8
  } from "./tbszx8mz.js";
9
9
  import {
10
10
  WireSession
11
- } from "./0jc3ffzf.js";
11
+ } from "./zvbjc949.js";
12
12
  import {
13
13
  rejectClosed,
14
14
  runCall
@@ -0,0 +1,94 @@
1
+ import {
2
+ BEHIND_EXPAND,
3
+ BEHIND_CONTRACT,
4
+ AHEAD_CONTRACT
5
+ } from "./9yn6a2vd.js";
6
+ import {
7
+ OkmError2
8
+ } from "./52szzakm.js";
9
+
10
+ // src/runtime/drift-detail.ts
11
+ function driftVerdict(codeHash, recordedHash, migrations) {
12
+ const codeAt = indexOfHash(migrations, codeHash);
13
+ const recordedAt = indexOfHash(migrations, recordedHash);
14
+ if (codeAt >= 0 && recordedAt >= codeAt) {
15
+ for (let index = codeAt + 1;index <= recordedAt; index += 1) {
16
+ const migration = migrations[index];
17
+ if (migration !== undefined && migration.expand !== true) {
18
+ return { state: "ahead by contract", migrationId: migration.id };
19
+ }
20
+ }
21
+ return { state: "ok" };
22
+ }
23
+ if (codeAt >= 0 && recordedAt >= 0 && recordedAt < codeAt) {
24
+ const next = migrations[recordedAt + 1];
25
+ if (next !== undefined) {
26
+ return {
27
+ state: next.expand ? "behind by expand" : "behind by contract",
28
+ migrationId: next.id
29
+ };
30
+ }
31
+ }
32
+ if (recordedAt >= 0) {
33
+ const at = migrations[recordedAt];
34
+ if (at !== undefined)
35
+ return { state: "behind", migrationId: at.id };
36
+ }
37
+ const last = migrations.at(-1);
38
+ return { state: "behind", migrationId: last?.id ?? "" };
39
+ }
40
+ async function assertDrift(pool, codeHash, recordedHash, options) {
41
+ let rows;
42
+ try {
43
+ const result = await pool.execute("select migration_id, class, catalog_hash from okm_history order by migration_id, step_index", undefined, options);
44
+ rows = result.rows;
45
+ } catch (error) {
46
+ throw gapError({ state: "behind", migrationId: "" }, error);
47
+ }
48
+ const verdict = driftVerdict(codeHash, recordedHash, groupMigrations(rows));
49
+ if (verdict.state === "ok")
50
+ return;
51
+ throw gapError(verdict);
52
+ }
53
+ function indexOfHash(migrations, hash) {
54
+ let found = -1;
55
+ for (let index = 0;index < migrations.length; index += 1) {
56
+ if (migrations[index]?.catalogHash === hash)
57
+ found = index;
58
+ }
59
+ return found;
60
+ }
61
+ function groupMigrations(rows) {
62
+ const grouped = [];
63
+ for (const row of rows) {
64
+ const id = row[0];
65
+ const stepClass = row[1];
66
+ const hash = row[2];
67
+ if (id == null || stepClass == null || hash == null)
68
+ continue;
69
+ const expand = stepClass === "expand";
70
+ const last = grouped.at(-1);
71
+ if (last !== undefined && last.id === id) {
72
+ grouped[grouped.length - 1] = {
73
+ id,
74
+ catalogHash: hash,
75
+ expand: last.expand && expand
76
+ };
77
+ continue;
78
+ }
79
+ grouped.push({ id, catalogHash: hash, expand });
80
+ }
81
+ return grouped;
82
+ }
83
+ function gapError(verdict, cause) {
84
+ const named = verdict.migrationId;
85
+ const phrase = verdict.state === "ahead by contract" ? `${AHEAD_CONTRACT} migration ${named}` : verdict.state === "behind by expand" ? `${BEHIND_EXPAND} migration ${named}` : verdict.state === "behind by contract" ? `${BEHIND_CONTRACT} migration ${named}` : named.length > 0 ? `behind the app at migration ${named}` : "behind the app";
86
+ const fix = named.length > 0 ? `Apply ${named}, or change the deploy order.` : "Apply migrations, or change the deploy order.";
87
+ return new OkmError2("OKM1520", `The database is ${phrase}.`, {
88
+ ...cause === undefined ? {} : { cause },
89
+ fix: { summary: fix }
90
+ });
91
+ }
92
+ export {
93
+ assertDrift
94
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  PgSession
3
- } from "./xw1d69vd.js";
3
+ } from "./wqem4jed.js";
4
4
  import {
5
5
  isConnectionLost
6
6
  } from "./tbszx8mz.js";
@@ -6,7 +6,7 @@ import {
6
6
  catalogHash2,
7
7
  loadTrustedCatalog2,
8
8
  parseCatalog2
9
- } from "./t616ynfn.js";
9
+ } from "./8jb4ymh2.js";
10
10
  export {
11
11
  catalogHash2 as catalogHash,
12
12
  creationOrder2 as creationOrder,