@uncutsql/core 0.2.1 → 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.
package/dist/index.cjs CHANGED
@@ -6,6 +6,178 @@ const tableKey = (table) => JSON.stringify([
6
6
  table.schema ?? null,
7
7
  table.name
8
8
  ]);
9
+ const triggerKey = (trigger) => trigger.scope === "target" ? JSON.stringify([tableKey(trigger.target), trigger.identity.name]) : tableKey(trigger.identity);
10
+ const functionKey = (fn) => JSON.stringify([
11
+ fn.identity.catalog ?? null,
12
+ fn.identity.schema ?? null,
13
+ fn.identity.name,
14
+ fn.signature
15
+ ]);
16
+ /** `schema.name(type, …)` for diagnostics; signature entries that are not strings print as JSON. */
17
+ const functionLabel = (fn) => `${[
18
+ fn.identity.catalog,
19
+ fn.identity.schema,
20
+ fn.identity.name
21
+ ].filter((part) => part !== void 0).join(".")}(${fn.signature.map((item) => typeof item === "string" ? item : JSON.stringify(item)).join(", ")})`;
22
+ /** The external objects of the models, tables before functions, each listed once by its key. */
23
+ const externalObjects = (...databases) => {
24
+ const found = /* @__PURE__ */ new Map();
25
+ for (const { externals } of databases) {
26
+ for (const { identity } of externals?.tables ?? []) {
27
+ const name = [
28
+ identity.catalog,
29
+ identity.schema,
30
+ identity.name
31
+ ].filter((part) => part !== void 0).join(".");
32
+ found.set(`table ${tableKey(identity)}`, {
33
+ identity,
34
+ label: `External table ${name}`
35
+ });
36
+ }
37
+ for (const fn of externals?.functions ?? []) found.set(`function ${functionKey(fn)}`, {
38
+ function: fn,
39
+ identity: fn.identity,
40
+ label: `External function ${functionLabel(fn)}`
41
+ });
42
+ }
43
+ return [...found.values()];
44
+ };
45
+ /** The managed and external enums of the models, each listed once by its key. */
46
+ const enumObjects = (...databases) => {
47
+ const found = /* @__PURE__ */ new Map();
48
+ for (const database of databases) for (const [kind, enums] of [["Enum", database.enums], ["External enum", database.externals?.enums]]) for (const { identity } of enums ?? []) {
49
+ const name = [
50
+ identity.catalog,
51
+ identity.schema,
52
+ identity.name
53
+ ].filter((part) => part !== void 0).join(".");
54
+ found.set(tableKey(identity), {
55
+ identity,
56
+ label: `${kind} ${name}`
57
+ });
58
+ }
59
+ return [...found.values()];
60
+ };
61
+ /** The managed and external extensions of the models, each listed once by its name. */
62
+ const extensionObjects = (...databases) => {
63
+ const found = /* @__PURE__ */ new Map();
64
+ for (const database of databases) for (const extension of [...database.extensions ?? [], ...database.externals?.extensions ?? []]) found.set(extension.name, extension);
65
+ return [...found.values()];
66
+ };
67
+ const dotted = ({ catalog, name, schema }) => [
68
+ catalog,
69
+ schema,
70
+ name
71
+ ].filter((part) => part !== void 0).join(".");
72
+ const commentObject = (target) => {
73
+ const on = (identity, text) => ({
74
+ identity,
75
+ label: `Comment on ${text}`
76
+ });
77
+ switch (target.kind) {
78
+ case "enum":
79
+ case "sequence":
80
+ case "table":
81
+ case "view": return on(target.identity, `${target.kind} ${dotted(target.identity)}`);
82
+ case "column": return on(target.table, `column ${dotted(target.table)}.${target.column}`);
83
+ case "viewColumn": return on(target.view, `view column ${dotted(target.view)}.${target.column}`);
84
+ case "index": return on(target.table, `index ${target.index} of table ${dotted(target.table)}`);
85
+ case "constraint": return on(target.table, `${target.constraint.kind} constraint of ${dotted(target.table)}`);
86
+ case "function": return on(target.identity, `function ${functionLabel(target)}`);
87
+ case "trigger": return on(target.target, `trigger ${target.name} on ${dotted(target.target)}`);
88
+ case "namespace": return on(target.identity, `schema ${dotted(target.identity)}`);
89
+ case "extension": return on({ name: target.name }, `extension ${target.name}`);
90
+ }
91
+ };
92
+ /** The targets of a model's own comments; externals are not included. */
93
+ const commentTargets = (database) => {
94
+ const targets = [];
95
+ const add = (item, target) => {
96
+ if (item.comment !== void 0) targets.push(target());
97
+ };
98
+ for (const item of database.namespaces ?? []) add(item, () => ({
99
+ identity: item.identity,
100
+ kind: "namespace"
101
+ }));
102
+ for (const item of database.extensions ?? []) add(item, () => ({
103
+ kind: "extension",
104
+ name: item.name
105
+ }));
106
+ for (const item of database.enums ?? []) add(item, () => ({
107
+ identity: item.identity,
108
+ kind: "enum"
109
+ }));
110
+ for (const table of database.tables ?? []) {
111
+ const { identity } = table;
112
+ const constraints = (items) => {
113
+ for (const item of items ?? []) add(item, () => ({
114
+ constraint: {
115
+ kind: item.kind,
116
+ properties: item.properties
117
+ },
118
+ kind: "constraint",
119
+ table: identity
120
+ }));
121
+ };
122
+ add(table, () => ({
123
+ identity,
124
+ kind: "table"
125
+ }));
126
+ for (const column of table.columns ?? []) {
127
+ add(column, () => ({
128
+ column: column.key,
129
+ kind: "column",
130
+ table: identity
131
+ }));
132
+ constraints(column.constraints);
133
+ }
134
+ constraints(table.constraints);
135
+ for (const index of table.indexes ?? []) add(index, () => ({
136
+ index: index.key,
137
+ kind: "index",
138
+ table: identity
139
+ }));
140
+ }
141
+ for (const view of database.views ?? []) {
142
+ add(view, () => ({
143
+ identity: view.identity,
144
+ kind: "view"
145
+ }));
146
+ for (const column of Object.keys(view.columnComments ?? {})) targets.push({
147
+ column,
148
+ kind: "viewColumn",
149
+ view: view.identity
150
+ });
151
+ }
152
+ for (const item of database.triggers ?? []) add(item, () => ({
153
+ kind: "trigger",
154
+ name: item.identity.name,
155
+ target: item.target
156
+ }));
157
+ for (const item of database.sequences ?? []) add(item, () => ({
158
+ identity: item.identity,
159
+ kind: "sequence"
160
+ }));
161
+ for (const item of database.functions ?? []) add(item, () => ({
162
+ identity: item.identity,
163
+ kind: "function",
164
+ signature: item.signature
165
+ }));
166
+ return targets;
167
+ };
168
+ /**
169
+ * Every commented object of the models, externals included, and of `targets` (for example those of
170
+ * `SetComment` procedures), each listed once by its label. A dialect without comments refuses them.
171
+ */
172
+ const commentObjects = (databases, targets = []) => {
173
+ const found = /* @__PURE__ */ new Map();
174
+ const all = [...databases.flatMap((database) => [...commentTargets(database), ...commentTargets(database.externals ?? {})]), ...targets];
175
+ for (const target of all) {
176
+ const object = commentObject(target);
177
+ found.set(object.label, object);
178
+ }
179
+ return [...found.values()];
180
+ };
9
181
  const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
10
182
  /** The namespace that contains an object, or undefined when its identity has no schema level. */
11
183
  const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
@@ -32,26 +204,29 @@ const validateDatabase = (database, side) => {
32
204
  const diagnostics = [];
33
205
  const tables = /* @__PURE__ */ new Set();
34
206
  const indexes = /* @__PURE__ */ new Set();
35
- for (const table of database.tables) {
36
- const id = tableKey(table.identity);
37
- if (tables.has(id)) diagnostics.push({
38
- code: "DuplicateTable",
39
- message: `Duplicate table ${id}`,
40
- side,
41
- table: table.identity
42
- });
43
- tables.add(id);
207
+ const duplicateColumns = (table) => {
44
208
  const columns = /* @__PURE__ */ new Set();
45
209
  for (const column of table.columns) {
46
210
  if (columns.has(column.key)) diagnostics.push({
47
211
  code: "DuplicateColumn",
48
212
  column: column.key,
49
- message: `Duplicate column ${JSON.stringify(column.key)} in table ${id}`,
213
+ message: `Duplicate column ${JSON.stringify(column.key)} in table ${tableKey(table.identity)}`,
50
214
  side,
51
215
  table: table.identity
52
216
  });
53
217
  columns.add(column.key);
54
218
  }
219
+ };
220
+ for (const table of database.tables) {
221
+ const id = tableKey(table.identity);
222
+ if (tables.has(id)) diagnostics.push({
223
+ code: "DuplicateTable",
224
+ message: `Duplicate table ${id}`,
225
+ side,
226
+ table: table.identity
227
+ });
228
+ tables.add(id);
229
+ duplicateColumns(table);
55
230
  }
56
231
  for (const table of database.tables) for (const index of table.indexes ?? []) {
57
232
  const id = JSON.stringify([tableKey(table.identity), index.key]);
@@ -81,8 +256,9 @@ const validateDatabase = (database, side) => {
81
256
  views.add(id);
82
257
  }
83
258
  const triggers = /* @__PURE__ */ new Set();
259
+ const externalTables = new Set((database.externals?.tables ?? []).map((table) => tableKey(table.identity)));
84
260
  for (const trigger of database.triggers ?? []) {
85
- const id = tableKey(trigger.identity);
261
+ const id = triggerKey(trigger);
86
262
  if (triggers.has(id)) diagnostics.push({
87
263
  code: "DuplicateTrigger",
88
264
  message: `Duplicate trigger ${id}`,
@@ -90,6 +266,54 @@ const validateDatabase = (database, side) => {
90
266
  table: trigger.identity
91
267
  });
92
268
  triggers.add(id);
269
+ const target = tableKey(trigger.target);
270
+ if (!tables.has(target) && !views.has(target)) {
271
+ const { catalog, name, schema } = trigger.target;
272
+ const label = [
273
+ catalog,
274
+ schema,
275
+ name
276
+ ].filter((part) => part !== void 0).join(".");
277
+ const isExternal = externalTables.has(target);
278
+ diagnostics.push({
279
+ code: isExternal ? "ExternalTriggerTarget" : "UnknownTriggerTarget",
280
+ message: isExternal ? `Trigger ${trigger.name} on ${label} cannot be created: ${label} is external, and a trigger on it would alter an object outside the managed scope` : `Trigger ${trigger.name} targets ${label}, which is not a table or view of the model`,
281
+ side,
282
+ table: trigger.identity
283
+ });
284
+ }
285
+ }
286
+ const sequences = /* @__PURE__ */ new Set();
287
+ for (const sequence of database.sequences ?? []) {
288
+ const id = tableKey(sequence.identity);
289
+ if (sequences.has(id)) diagnostics.push({
290
+ code: "DuplicateSequence",
291
+ message: `Duplicate sequence ${id}`,
292
+ side,
293
+ table: sequence.identity
294
+ });
295
+ sequences.add(id);
296
+ const owner = sequence.owner;
297
+ if (owner) {
298
+ if (!database.tables.find((table) => tableKey(table.identity) === tableKey(owner.table))?.columns.some((column) => column.key === owner.column)) diagnostics.push({
299
+ code: "UndeclaredSequenceOwner",
300
+ column: owner.column,
301
+ message: `Sequence ${id} is owned by ${tableKey(owner.table)} column ${JSON.stringify(owner.column)}, which is not in the model`,
302
+ side,
303
+ table: sequence.identity
304
+ });
305
+ }
306
+ }
307
+ const functions = /* @__PURE__ */ new Set();
308
+ for (const fn of database.functions ?? []) {
309
+ const id = functionKey(fn);
310
+ if (functions.has(id)) diagnostics.push({
311
+ code: "DuplicateFunction",
312
+ message: `Duplicate function ${id}`,
313
+ side,
314
+ table: fn.identity
315
+ });
316
+ functions.add(id);
93
317
  }
94
318
  const namespaces = /* @__PURE__ */ new Set();
95
319
  for (const namespace of database.namespaces ?? []) {
@@ -102,6 +326,125 @@ const validateDatabase = (database, side) => {
102
326
  });
103
327
  namespaces.add(id);
104
328
  }
329
+ const externals = /* @__PURE__ */ new Set();
330
+ const external = (key, identity, label, statement) => {
331
+ if (externals.has(key)) diagnostics.push({
332
+ code: "DuplicateExternal",
333
+ message: `Duplicate ${label}`,
334
+ side,
335
+ table: identity
336
+ });
337
+ externals.add(key);
338
+ const namespace = namespaceOf(identity);
339
+ if (namespace && namespaces.has(namespaceKey(namespace))) diagnostics.push({
340
+ code: "ExternalInManagedNamespace",
341
+ message: `External ${label} is in managed schema ${namespace.name}; declare it with ${statement}, or move it out of the managed scope`,
342
+ side,
343
+ table: identity
344
+ });
345
+ };
346
+ for (const table of database.externals?.tables ?? []) {
347
+ const { catalog, name, schema } = table.identity;
348
+ external(`table ${tableKey(table.identity)}`, table.identity, `table ${[
349
+ catalog,
350
+ schema,
351
+ name
352
+ ].filter((part) => part !== void 0).join(".")}`, "CREATE TABLE");
353
+ duplicateColumns(table);
354
+ }
355
+ for (const fn of database.externals?.functions ?? []) external(`function ${functionKey(fn)}`, fn.identity, `function ${functionLabel(fn)}`, "CREATE FUNCTION");
356
+ for (const item of commentObjects([{
357
+ externals: database.externals ?? {},
358
+ tables: []
359
+ }])) diagnostics.push({
360
+ code: "ExternalComment",
361
+ message: `${item.label} is on an external object, which migrations never alter; remove the comment`,
362
+ side,
363
+ table: item.identity
364
+ });
365
+ const enums = /* @__PURE__ */ new Set();
366
+ const duplicateEnum = (identity, message) => diagnostics.push({
367
+ code: "DuplicateEnum",
368
+ message,
369
+ side,
370
+ table: identity
371
+ });
372
+ const duplicateValues = ({ identity, values }) => {
373
+ const labels = /* @__PURE__ */ new Set();
374
+ for (const label of values) {
375
+ if (labels.has(label)) diagnostics.push({
376
+ code: "DuplicateEnumValue",
377
+ message: `Duplicate value ${JSON.stringify(label)} in enum ${tableKey(identity)}`,
378
+ side,
379
+ table: identity
380
+ });
381
+ labels.add(label);
382
+ }
383
+ };
384
+ for (const item of database.enums ?? []) {
385
+ const id = tableKey(item.identity);
386
+ if (enums.has(id)) duplicateEnum(item.identity, `Duplicate enum ${id}`);
387
+ enums.add(id);
388
+ duplicateValues(item);
389
+ }
390
+ for (const item of database.externals?.enums ?? []) {
391
+ const { catalog, name, schema } = item.identity;
392
+ const id = tableKey(item.identity);
393
+ if (enums.has(id)) duplicateEnum(item.identity, `Enum ${id} is both managed and external`);
394
+ external(`enum ${id}`, item.identity, `enum ${[
395
+ catalog,
396
+ schema,
397
+ name
398
+ ].filter((part) => part !== void 0).join(".")}`, "CREATE TYPE");
399
+ duplicateValues(item);
400
+ }
401
+ const extensions = /* @__PURE__ */ new Set();
402
+ const extensionIdentity = ({ name, schema }) => schema === void 0 ? { name } : {
403
+ name,
404
+ schema
405
+ };
406
+ const managedNamespace = (identity) => {
407
+ const namespace = namespaceOf(identity);
408
+ return namespace && namespaces.has(namespaceKey(namespace));
409
+ };
410
+ for (const extension of database.extensions ?? []) {
411
+ if (extensions.has(extension.name)) diagnostics.push({
412
+ code: "DuplicateExtension",
413
+ message: `Duplicate extension ${extension.name}`,
414
+ side,
415
+ table: extensionIdentity(extension)
416
+ });
417
+ extensions.add(extension.name);
418
+ if (database.namespaces && extension.schema !== void 0 && !managedNamespace(extensionIdentity(extension))) diagnostics.push({
419
+ code: "UndeclaredNamespace",
420
+ message: `Extension ${extension.name} belongs to undeclared namespace ${namespaceKey({ name: extension.schema })}; declare an extension that another tool installs with DECLARE EXTERNAL EXTENSION`,
421
+ side,
422
+ table: extensionIdentity(extension)
423
+ });
424
+ }
425
+ const externalExtensions = /* @__PURE__ */ new Set();
426
+ for (const extension of database.externals?.extensions ?? []) {
427
+ const table = extensionIdentity(extension);
428
+ if (externalExtensions.has(extension.name)) diagnostics.push({
429
+ code: "DuplicateExternal",
430
+ message: `Duplicate extension ${extension.name}`,
431
+ side,
432
+ table
433
+ });
434
+ else if (extensions.has(extension.name)) diagnostics.push({
435
+ code: "DuplicateExtension",
436
+ message: `Extension ${extension.name} is both managed and external`,
437
+ side,
438
+ table
439
+ });
440
+ externalExtensions.add(extension.name);
441
+ if (managedNamespace(table)) diagnostics.push({
442
+ code: "ExternalInManagedNamespace",
443
+ message: `External extension ${extension.name} is in managed schema ${extension.schema}; declare it with CREATE EXTENSION`,
444
+ side,
445
+ table
446
+ });
447
+ }
105
448
  if (database.namespaces) {
106
449
  const undeclared = (identity, owner, role) => {
107
450
  const namespace = namespaceOf(identity);
@@ -118,9 +461,32 @@ const validateDatabase = (database, side) => {
118
461
  undeclared(trigger.identity, trigger.identity, "Trigger");
119
462
  undeclared(trigger.target, trigger.identity, "Target of trigger");
120
463
  }
464
+ for (const sequence of database.sequences ?? []) {
465
+ undeclared(sequence.identity, sequence.identity, "Sequence");
466
+ if (sequence.owner) undeclared(sequence.owner.table, sequence.identity, "Owner table of sequence");
467
+ }
468
+ for (const fn of database.functions ?? []) undeclared(fn.identity, fn.identity, "Function");
469
+ for (const item of database.enums ?? []) undeclared(item.identity, item.identity, "Enum");
121
470
  }
122
471
  return diagnostics;
123
472
  };
473
+ /**
474
+ * Checks an explicit list of managed schemas against the namespaces of a model built from schema
475
+ * files. Names are compared as catalog names, case-sensitively. The shape of the list (non-empty,
476
+ * unique, including `public`) is the caller's to validate.
477
+ */
478
+ const checkManagedScope = (model, managedSchemas) => {
479
+ const managed = new Set(managedSchemas);
480
+ const created = new Set((model.namespaces ?? []).map((namespace) => namespace.identity.name));
481
+ const diagnostic = (code, name, message) => ({
482
+ code,
483
+ message,
484
+ side: "after",
485
+ table: { name }
486
+ });
487
+ return [...[...created].filter((name) => !managed.has(name)).map((name) => diagnostic("UnmanagedSchema", name, `Schema ${name} is created by the schema files but is not in managedSchemas; add it to managedSchemas or declare its objects external`)), ...[...managed].filter((name) => name !== "public" && !created.has(name)).map((name) => diagnostic("ManagedSchemaNotCreated", name, `Schema ${name} is in managedSchemas but no schema file creates it`))];
488
+ };
489
+ /** Same kinds and properties in the same order; comments are compared by `diffComments`. */
124
490
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
125
491
  const compareTable = (before, after) => {
126
492
  const changes = [];
@@ -180,7 +546,7 @@ const compareTable = (before, after) => {
180
546
  _tag: "IndexAdded",
181
547
  index
182
548
  });
183
- else if (old.unique !== index.unique || !schemaValueEqual(old.terms, index.terms) || !schemaValueEqual(old.where, index.where)) changes.push({
549
+ else if (old.unique !== index.unique || !schemaValueEqual(old.terms, index.terms) || !schemaValueEqual(old.where, index.where) || !schemaValueEqual(old.options ?? {}, index.options ?? {})) changes.push({
184
550
  _tag: "IndexChanged",
185
551
  after: index,
186
552
  before: old
@@ -188,6 +554,400 @@ const compareTable = (before, after) => {
188
554
  }
189
555
  return changes;
190
556
  };
557
+ /** Collect the table and column renames that a list of changes carries. */
558
+ const sequenceRenames = (changes) => {
559
+ const tables = /* @__PURE__ */ new Map();
560
+ const columns = /* @__PURE__ */ new Map();
561
+ for (const change of changes) {
562
+ if (change._tag !== "TableChanged" && change._tag !== "TableRenamed") continue;
563
+ const key = tableKey(change.before.identity);
564
+ if (change._tag === "TableRenamed") tables.set(key, change.after.identity);
565
+ for (const item of change.changes) if (item._tag === "ColumnRenamed") {
566
+ const renamed = columns.get(key) ?? /* @__PURE__ */ new Map();
567
+ renamed.set(item.before.key, item.after.key);
568
+ columns.set(key, renamed);
569
+ }
570
+ }
571
+ return {
572
+ columns,
573
+ tables
574
+ };
575
+ };
576
+ /** The owner of a `before` sequence expressed in the `after` model, or its key when unowned. */
577
+ const ownerAfterRenames = (sequence, renames) => {
578
+ const owner = sequence.owner;
579
+ if (!owner) return;
580
+ const source = tableKey(owner.table);
581
+ return {
582
+ column: renames.columns.get(source)?.get(owner.column) ?? owner.column,
583
+ table: renames.tables.get(source) ?? owner.table
584
+ };
585
+ };
586
+ const ownerKey = (owner) => owner ? JSON.stringify([tableKey(owner.table), owner.column]) : null;
587
+ /** Function changes. A changed signature is another key: a removal and an addition. */
588
+ const diffFunctions = (before, after) => {
589
+ const changes = [];
590
+ const oldFunctions = new Map((before.functions ?? []).map((item) => [functionKey(item), item]));
591
+ const newFunctions = new Map((after.functions ?? []).map((item) => [functionKey(item), item]));
592
+ for (const [key, fn] of oldFunctions) if (!newFunctions.has(key)) changes.push({
593
+ _tag: "FunctionRemoved",
594
+ function: fn
595
+ });
596
+ for (const [key, fn] of newFunctions) {
597
+ const old = oldFunctions.get(key);
598
+ if (!old) changes.push({
599
+ _tag: "FunctionAdded",
600
+ function: fn
601
+ });
602
+ else if (!schemaValueEqual(old.definition, fn.definition)) changes.push({
603
+ _tag: "FunctionChanged",
604
+ after: fn,
605
+ before: old
606
+ });
607
+ }
608
+ return changes;
609
+ };
610
+ /** Sequence changes. `renames` are the table and column renames the migration applies. */
611
+ const diffSequences = (before, after, renames = {
612
+ columns: /* @__PURE__ */ new Map(),
613
+ tables: /* @__PURE__ */ new Map()
614
+ }) => {
615
+ const changes = [];
616
+ const oldSequences = new Map((before.sequences ?? []).map((item) => [tableKey(item.identity), item]));
617
+ const newSequences = new Map((after.sequences ?? []).map((item) => [tableKey(item.identity), item]));
618
+ const removed = [];
619
+ const added = [];
620
+ for (const [key, sequence] of oldSequences) if (!newSequences.has(key)) removed.push(sequence);
621
+ for (const [key, sequence] of newSequences) {
622
+ const old = oldSequences.get(key);
623
+ if (!old) added.push(sequence);
624
+ else if (!schemaValueEqual(old.definition, sequence.definition) || ownerKey(ownerAfterRenames(old, renames)) !== ownerKey(sequence.owner)) changes.push({
625
+ _tag: "SequenceChanged",
626
+ after: sequence,
627
+ before: old
628
+ });
629
+ }
630
+ const groupKey = (sequence, owner) => JSON.stringify([namespaceOf(sequence.identity) ?? null, owner]);
631
+ const groups = /* @__PURE__ */ new Map();
632
+ const group = (key) => {
633
+ const found = groups.get(key) ?? {
634
+ added: [],
635
+ removed: []
636
+ };
637
+ groups.set(key, found);
638
+ return found;
639
+ };
640
+ for (const sequence of removed) {
641
+ const owner = ownerKey(ownerAfterRenames(sequence, renames));
642
+ if (owner !== null) group(groupKey(sequence, owner)).removed.push(sequence);
643
+ }
644
+ for (const sequence of added) {
645
+ const owner = ownerKey(sequence.owner);
646
+ if (owner !== null) group(groupKey(sequence, owner)).added.push(sequence);
647
+ }
648
+ const paired = /* @__PURE__ */ new Set();
649
+ for (const found of groups.values()) if (found.removed.length === 1 && found.added.length === 1) {
650
+ const [old] = found.removed;
651
+ const [next] = found.added;
652
+ paired.add(old);
653
+ paired.add(next);
654
+ changes.push({
655
+ _tag: "SequenceRenamed",
656
+ after: next,
657
+ before: old
658
+ });
659
+ }
660
+ for (const sequence of removed) if (!paired.has(sequence)) changes.push({
661
+ _tag: "SequenceRemoved",
662
+ sequence
663
+ });
664
+ for (const sequence of added) if (!paired.has(sequence)) changes.push({
665
+ _tag: "SequenceAdded",
666
+ sequence
667
+ });
668
+ return changes;
669
+ };
670
+ /** The `before` triggers keyed as in the after model, and those that lose their key to another. */
671
+ const triggersAfterRenames = (before, renames) => {
672
+ const keyed = /* @__PURE__ */ new Map();
673
+ const displaced = [];
674
+ const moved = (trigger) => renames.tables.has(tableKey(trigger.target));
675
+ const ordered = [...before.triggers ?? []].sort((a, b) => Number(moved(a)) - Number(moved(b)));
676
+ for (const trigger of ordered) {
677
+ const target = renames.tables.get(tableKey(trigger.target)) ?? trigger.target;
678
+ const key = triggerKey({
679
+ ...trigger,
680
+ target
681
+ });
682
+ const previous = keyed.get(key);
683
+ if (previous) displaced.push(previous.trigger);
684
+ keyed.set(key, {
685
+ target,
686
+ trigger
687
+ });
688
+ }
689
+ return {
690
+ displaced,
691
+ keyed
692
+ };
693
+ };
694
+ /**
695
+ * Trigger changes, paired by `triggerKey`. `renames` are the table renames the migration applies: a
696
+ * trigger follows its renamed target. There are no trigger renames.
697
+ */
698
+ const diffTriggers = (before, after, renames = {
699
+ columns: /* @__PURE__ */ new Map(),
700
+ tables: /* @__PURE__ */ new Map()
701
+ }) => {
702
+ const { displaced, keyed: oldTriggers } = triggersAfterRenames(before, renames);
703
+ const changes = displaced.map((trigger) => ({
704
+ _tag: "TriggerRemoved",
705
+ trigger
706
+ }));
707
+ const newTriggers = new Map((after.triggers ?? []).map((item) => [triggerKey(item), item]));
708
+ for (const [key, { trigger }] of oldTriggers) if (!newTriggers.has(key)) changes.push({
709
+ _tag: "TriggerRemoved",
710
+ trigger
711
+ });
712
+ for (const [key, trigger] of newTriggers) {
713
+ const old = oldTriggers.get(key);
714
+ if (!old) changes.push({
715
+ _tag: "TriggerAdded",
716
+ trigger
717
+ });
718
+ else if (tableKey(old.target) !== tableKey(trigger.target) || !schemaValueEqual(old.trigger.definition, trigger.definition)) changes.push({
719
+ _tag: "TriggerChanged",
720
+ after: trigger,
721
+ before: old.trigger
722
+ });
723
+ }
724
+ return changes;
725
+ };
726
+ /**
727
+ * Enum changes, paired by `tableKey`. A renamed enum has one `EnumRenamed`, whether or not its
728
+ * labels differ too. Removals and order are not judged here; external enums are ignored.
729
+ */
730
+ const diffEnums = (before, after, renames = {
731
+ enums: /* @__PURE__ */ new Map(),
732
+ values: /* @__PURE__ */ new Map()
733
+ }) => {
734
+ const changes = [];
735
+ const oldEnums = new Map((before.enums ?? []).map((item) => [tableKey(item.identity), item]));
736
+ const newEnums = new Map((after.enums ?? []).map((item) => [tableKey(item.identity), item]));
737
+ const valueRenames = (item) => {
738
+ const renamed = renames.values.get(tableKey(item.identity));
739
+ return item.values.flatMap((label) => {
740
+ const target = renamed?.get(label);
741
+ return target === void 0 ? [] : [{
742
+ after: target,
743
+ before: label
744
+ }];
745
+ });
746
+ };
747
+ const renamed = /* @__PURE__ */ new Map();
748
+ for (const [key, item] of oldEnums) {
749
+ const target = renames.enums.get(key);
750
+ if (target && tableKey(target) !== key && newEnums.has(tableKey(target))) renamed.set(tableKey(target), item);
751
+ }
752
+ const sources = new Set(renamed.values());
753
+ for (const [key, item] of oldEnums) if (!sources.has(item) && (!newEnums.has(key) || renamed.has(key))) changes.push({
754
+ _tag: "EnumRemoved",
755
+ enum: item
756
+ });
757
+ for (const [key, item] of newEnums) {
758
+ const source = renamed.get(key);
759
+ if (source) {
760
+ changes.push({
761
+ _tag: "EnumRenamed",
762
+ after: item,
763
+ before: source,
764
+ values: valueRenames(source)
765
+ });
766
+ continue;
767
+ }
768
+ const old = oldEnums.get(key);
769
+ if (!old || sources.has(old)) changes.push({
770
+ _tag: "EnumAdded",
771
+ enum: item
772
+ });
773
+ else if (!schemaValueEqual(old.values, item.values)) changes.push({
774
+ _tag: "EnumChanged",
775
+ after: item,
776
+ before: old,
777
+ values: valueRenames(old)
778
+ });
779
+ }
780
+ return changes;
781
+ };
782
+ /** Extensions are compared by name. Unpinning a version is no change. */
783
+ const diffExtensions = (before, after) => {
784
+ const changes = [];
785
+ const oldExtensions = new Map((before.extensions ?? []).map((item) => [item.name, item]));
786
+ const newExtensions = new Map((after.extensions ?? []).map((item) => [item.name, item]));
787
+ for (const [name, extension] of oldExtensions) if (!newExtensions.has(name)) changes.push({
788
+ _tag: "ExtensionRemoved",
789
+ extension
790
+ });
791
+ for (const [name, extension] of newExtensions) {
792
+ const old = oldExtensions.get(name);
793
+ if (!old) {
794
+ changes.push({
795
+ _tag: "ExtensionAdded",
796
+ extension
797
+ });
798
+ continue;
799
+ }
800
+ if (old.schema !== extension.schema) changes.push({
801
+ _tag: "ExtensionSchemaChanged",
802
+ after: extension,
803
+ before: old
804
+ });
805
+ if (extension.version !== void 0 && extension.version !== old.version) changes.push({
806
+ _tag: "ExtensionVersionChanged",
807
+ after: extension,
808
+ before: old
809
+ });
810
+ }
811
+ return changes;
812
+ };
813
+ /**
814
+ * The objects that both lists hold, as `[before, after]` in after order. `renamed` maps the key of a
815
+ * renamed after object to its key before; the source of a rename pairs with nothing else.
816
+ */
817
+ const pairs = (before, after, key, renamed = /* @__PURE__ */ new Map()) => {
818
+ const old = new Map((before ?? []).map((item) => [key(item), item]));
819
+ const sources = new Set(renamed.values());
820
+ return (after ?? []).flatMap((item) => {
821
+ const own = key(item);
822
+ const source = renamed.get(own) ?? (sources.has(own) ? void 0 : own);
823
+ const previous = source === void 0 ? void 0 : old.get(source);
824
+ return previous === void 0 ? [] : [[previous, item]];
825
+ });
826
+ };
827
+ /** Constraints that are equal apart from their comment, preferring those with the same comment. */
828
+ const constraintPairs = (before, after) => {
829
+ const unused = new Set(before.keys());
830
+ const found = /* @__PURE__ */ new Map();
831
+ for (const sameComment of [true, false]) for (const [position, item] of after.entries()) {
832
+ if (found.has(position)) continue;
833
+ const match = [...unused].find((index) => constraintsEqual([before[index]], [item]) && (!sameComment || before[index].comment === item.comment));
834
+ if (match !== void 0) {
835
+ unused.delete(match);
836
+ found.set(position, before[match]);
837
+ }
838
+ }
839
+ return after.flatMap((item, position) => {
840
+ const previous = found.get(position);
841
+ return previous ? [[previous, item]] : [];
842
+ });
843
+ };
844
+ /**
845
+ * Comment changes of the managed objects that both models hold. `changes` are the changes of the
846
+ * migration: their table, column, sequence and enum renames pair objects across a rename. Added and
847
+ * removed objects have no change here.
848
+ */
849
+ const diffComments = (before, after, changes = []) => {
850
+ const found = [];
851
+ const compare = (previous, next, target) => {
852
+ if (previous !== next) found.push({
853
+ _tag: "CommentChanged",
854
+ ...next === void 0 ? {} : { after: next },
855
+ ...previous === void 0 ? {} : { before: previous },
856
+ target
857
+ });
858
+ };
859
+ const tables = /* @__PURE__ */ new Map();
860
+ const columns = /* @__PURE__ */ new Map();
861
+ const sequences = /* @__PURE__ */ new Map();
862
+ const enums = /* @__PURE__ */ new Map();
863
+ for (const change of changes) if (change._tag === "TableChanged" || change._tag === "TableRenamed") {
864
+ const key = tableKey(change.after.identity);
865
+ if (change._tag === "TableRenamed") tables.set(key, tableKey(change.before.identity));
866
+ for (const item of change.changes) if (item._tag === "ColumnRenamed") {
867
+ const renamed = columns.get(key) ?? /* @__PURE__ */ new Map();
868
+ renamed.set(item.after.key, item.before.key);
869
+ columns.set(key, renamed);
870
+ }
871
+ } else if (change._tag === "SequenceRenamed") sequences.set(tableKey(change.after.identity), tableKey(change.before.identity));
872
+ else if (change._tag === "EnumRenamed") enums.set(tableKey(change.after.identity), tableKey(change.before.identity));
873
+ for (const [old, item] of pairs(before.namespaces, after.namespaces, (item) => namespaceKey(item.identity))) compare(old.comment, item.comment, {
874
+ identity: item.identity,
875
+ kind: "namespace"
876
+ });
877
+ for (const [old, item] of pairs(before.extensions, after.extensions, (item) => item.name)) compare(old.comment, item.comment, {
878
+ kind: "extension",
879
+ name: item.name
880
+ });
881
+ const identityKey = (item) => tableKey(item.identity);
882
+ for (const [old, item] of pairs(before.enums, after.enums, identityKey, enums)) compare(old.comment, item.comment, {
883
+ identity: item.identity,
884
+ kind: "enum"
885
+ });
886
+ for (const [old, table] of pairs(before.tables, after.tables, identityKey, tables)) {
887
+ const identity = table.identity;
888
+ const constraints = (previous, next) => {
889
+ for (const [source, { comment, kind, properties }] of constraintPairs(previous, next)) compare(source.comment, comment, {
890
+ constraint: {
891
+ kind,
892
+ properties
893
+ },
894
+ kind: "constraint",
895
+ table: identity
896
+ });
897
+ };
898
+ compare(old.comment, table.comment, {
899
+ identity,
900
+ kind: "table"
901
+ });
902
+ for (const [source, column] of pairs(old.columns, table.columns, (item) => item.key, columns.get(tableKey(identity)))) {
903
+ compare(source.comment, column.comment, {
904
+ column: column.key,
905
+ kind: "column",
906
+ table: identity
907
+ });
908
+ constraints(source.constraints, column.constraints);
909
+ }
910
+ constraints(old.constraints, table.constraints);
911
+ for (const [source, index] of pairs(old.indexes, table.indexes, (item) => item.key)) compare(source.comment, index.comment, {
912
+ index: index.key,
913
+ kind: "index",
914
+ table: identity
915
+ });
916
+ }
917
+ for (const [old, view] of pairs(before.views, after.views, identityKey)) {
918
+ compare(old.comment, view.comment, {
919
+ identity: view.identity,
920
+ kind: "view"
921
+ });
922
+ const previous = new Map(Object.entries(old.columnComments ?? {}));
923
+ const next = new Map(Object.entries(view.columnComments ?? {}));
924
+ for (const column of /* @__PURE__ */ new Set([...next.keys(), ...previous.keys()])) compare(previous.get(column), next.get(column), {
925
+ column,
926
+ kind: "viewColumn",
927
+ view: view.identity
928
+ });
929
+ }
930
+ const renames = sequenceRenames(changes);
931
+ const oldTriggers = triggersAfterRenames(before, renames).keyed;
932
+ for (const trigger of after.triggers ?? []) {
933
+ const old = oldTriggers.get(triggerKey(trigger));
934
+ if (old) compare(old.trigger.comment, trigger.comment, {
935
+ kind: "trigger",
936
+ name: trigger.identity.name,
937
+ target: trigger.target
938
+ });
939
+ }
940
+ for (const [old, item] of pairs(before.sequences, after.sequences, identityKey, sequences)) compare(old.comment, item.comment, {
941
+ identity: item.identity,
942
+ kind: "sequence"
943
+ });
944
+ for (const [old, item] of pairs(before.functions, after.functions, functionKey)) compare(old.comment, item.comment, {
945
+ identity: item.identity,
946
+ kind: "function",
947
+ signature: item.signature
948
+ });
949
+ return found;
950
+ };
191
951
  /** Compare normalized relational models without parsing SQL or consulting a dialect. */
192
952
  const diffDatabases = (before, after) => effect.Effect.gen(function* () {
193
953
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
@@ -211,6 +971,8 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
211
971
  before: old
212
972
  });
213
973
  }
974
+ changes.push(...diffExtensions(before, after));
975
+ changes.push(...diffEnums(before, after));
214
976
  const previous = new Map(before.tables.map((table) => [tableKey(table.identity), table]));
215
977
  const next = new Map(after.tables.map((table) => [tableKey(table.identity), table]));
216
978
  for (const [key, table] of previous) if (!next.has(key)) changes.push({
@@ -248,30 +1010,16 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
248
1010
  _tag: "ViewAdded",
249
1011
  view
250
1012
  });
251
- else if (!schemaValueEqual(old.columns ?? null, view.columns ?? null) || !schemaValueEqual(old.query, view.query)) changes.push({
1013
+ else if (!schemaValueEqual(old.columns ?? null, view.columns ?? null) || !schemaValueEqual(old.query, view.query) || !schemaValueEqual(old.options ?? {}, view.options ?? {})) changes.push({
252
1014
  _tag: "ViewChanged",
253
1015
  after: view,
254
1016
  before: old
255
1017
  });
256
1018
  }
257
- const oldTriggers = new Map((before.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
258
- const newTriggers = new Map((after.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
259
- for (const [key, trigger] of oldTriggers) if (!newTriggers.has(key)) changes.push({
260
- _tag: "TriggerRemoved",
261
- trigger
262
- });
263
- for (const [key, trigger] of newTriggers) {
264
- const old = oldTriggers.get(key);
265
- if (!old) changes.push({
266
- _tag: "TriggerAdded",
267
- trigger
268
- });
269
- else if (tableKey(old.target) !== tableKey(trigger.target) || !schemaValueEqual(old.definition, trigger.definition)) changes.push({
270
- _tag: "TriggerChanged",
271
- after: trigger,
272
- before: old
273
- });
274
- }
1019
+ changes.push(...diffTriggers(before, after));
1020
+ changes.push(...diffSequences(before, after));
1021
+ changes.push(...diffFunctions(before, after));
1022
+ changes.push(...diffComments(before, after, changes));
275
1023
  return { changes };
276
1024
  });
277
1025
  // src/migration.ts
@@ -290,6 +1038,58 @@ const planDatabaseMigration = (diff) => ({
290
1038
  after: change.after,
291
1039
  before: change.before
292
1040
  };
1041
+ case "EnumAdded":
1042
+ case "EnumRemoved": return {
1043
+ _tag: change._tag === "EnumAdded" ? "CreateEnum" : "DropEnum",
1044
+ enum: change.enum
1045
+ };
1046
+ case "EnumRenamed":
1047
+ case "EnumChanged": return {
1048
+ _tag: change._tag === "EnumRenamed" ? "RenameEnum" : "AlterEnum",
1049
+ after: change.after,
1050
+ before: change.before,
1051
+ values: change.values
1052
+ };
1053
+ case "ExtensionAdded":
1054
+ case "ExtensionRemoved": return {
1055
+ _tag: change._tag === "ExtensionAdded" ? "CreateExtension" : "DropExtension",
1056
+ extension: change.extension
1057
+ };
1058
+ case "ExtensionVersionChanged":
1059
+ case "ExtensionSchemaChanged": return change._tag === "ExtensionVersionChanged" ? {
1060
+ _tag: "UpdateExtension",
1061
+ after: change.after,
1062
+ before: change.before
1063
+ } : {
1064
+ _tag: "MoveExtension",
1065
+ after: change.after,
1066
+ before: change.before
1067
+ };
1068
+ case "FunctionAdded":
1069
+ case "FunctionRemoved": return {
1070
+ _tag: change._tag === "FunctionAdded" ? "CreateFunction" : "DropFunction",
1071
+ function: change.function
1072
+ };
1073
+ case "FunctionChanged": return {
1074
+ _tag: "ReplaceFunction",
1075
+ after: change.after,
1076
+ before: change.before
1077
+ };
1078
+ case "SequenceAdded":
1079
+ case "SequenceRemoved": return {
1080
+ _tag: change._tag === "SequenceAdded" ? "CreateSequence" : "DropSequence",
1081
+ sequence: change.sequence
1082
+ };
1083
+ case "SequenceChanged": return {
1084
+ _tag: "AlterSequence",
1085
+ after: change.after,
1086
+ before: change.before
1087
+ };
1088
+ case "SequenceRenamed": return {
1089
+ _tag: "RenameSequence",
1090
+ after: change.after,
1091
+ before: change.before
1092
+ };
293
1093
  case "TriggerAdded":
294
1094
  case "TriggerRemoved": return {
295
1095
  _tag: change._tag === "TriggerAdded" ? "CreateTrigger" : "DropTrigger",
@@ -325,14 +1125,79 @@ const planDatabaseMigration = (diff) => ({
325
1125
  before: change.before,
326
1126
  changes: change.changes
327
1127
  };
1128
+ case "CommentChanged": {
1129
+ const { _tag, ...comment } = change;
1130
+ return {
1131
+ _tag: "SetComment",
1132
+ ...comment
1133
+ };
1134
+ }
328
1135
  }
329
1136
  })
330
1137
  });
1138
+ /** Names a comment target of the `up` migration's after model as its before model names it. */
1139
+ const targetBeforeRenames = (up) => {
1140
+ const tables = /* @__PURE__ */ new Map();
1141
+ const columns = /* @__PURE__ */ new Map();
1142
+ const sequences = /* @__PURE__ */ new Map();
1143
+ const enums = /* @__PURE__ */ new Map();
1144
+ for (const step of up.procedures) if (step._tag === "AlterTable" || step._tag === "RenameTable") {
1145
+ const key = tableKey(step.after.identity);
1146
+ if (step._tag === "RenameTable") tables.set(key, step.before.identity);
1147
+ const renamed = /* @__PURE__ */ new Map();
1148
+ for (const change of step.changes) if (change._tag === "ColumnRenamed") renamed.set(change.after.key, change.before.key);
1149
+ columns.set(key, renamed);
1150
+ } else if (step._tag === "RenameSequence") sequences.set(tableKey(step.after.identity), step.before.identity);
1151
+ else if (step._tag === "RenameEnum") enums.set(tableKey(step.after.identity), step.before.identity);
1152
+ const renamed = (names, identity) => names.get(tableKey(identity)) ?? identity;
1153
+ return (target) => {
1154
+ switch (target.kind) {
1155
+ case "table": return {
1156
+ ...target,
1157
+ identity: renamed(tables, target.identity)
1158
+ };
1159
+ case "sequence": return {
1160
+ ...target,
1161
+ identity: renamed(sequences, target.identity)
1162
+ };
1163
+ case "enum": return {
1164
+ ...target,
1165
+ identity: renamed(enums, target.identity)
1166
+ };
1167
+ case "column": return {
1168
+ ...target,
1169
+ column: columns.get(tableKey(target.table))?.get(target.column) ?? target.column,
1170
+ table: renamed(tables, target.table)
1171
+ };
1172
+ case "index":
1173
+ case "constraint": return {
1174
+ ...target,
1175
+ table: renamed(tables, target.table)
1176
+ };
1177
+ case "trigger": return {
1178
+ ...target,
1179
+ target: renamed(tables, target.target)
1180
+ };
1181
+ default: return target;
1182
+ }
1183
+ };
1184
+ };
331
1185
  /** Reverse reviewed intent, retaining rename pairs and guarding newly added data. */
332
1186
  const planDownMigration = (up) => {
333
1187
  const procedures = [];
334
1188
  const dropGuards = [];
1189
+ const downTarget = targetBeforeRenames(up);
335
1190
  for (const step of up.procedures) switch (step._tag) {
1191
+ case "SetComment": {
1192
+ const { after, before, target } = step;
1193
+ procedures.push({
1194
+ _tag: "SetComment",
1195
+ ...before === void 0 ? {} : { after: before },
1196
+ ...after === void 0 ? {} : { before: after },
1197
+ target: downTarget(target)
1198
+ });
1199
+ break;
1200
+ }
336
1201
  case "DropTable": return `The up migration removed table ${step.table.name}.`;
337
1202
  case "CreateTable":
338
1203
  dropGuards.push({ table: step.table.identity });
@@ -341,6 +1206,52 @@ const planDownMigration = (up) => {
341
1206
  _tag: "DropTable"
342
1207
  });
343
1208
  break;
1209
+ case "CreateEnum":
1210
+ case "DropEnum":
1211
+ procedures.push({
1212
+ ...step,
1213
+ _tag: step._tag === "CreateEnum" ? "DropEnum" : "CreateEnum"
1214
+ });
1215
+ break;
1216
+ case "RenameEnum":
1217
+ case "AlterEnum":
1218
+ procedures.push({
1219
+ ...swap(step),
1220
+ values: step.values.map(swap)
1221
+ });
1222
+ break;
1223
+ case "CreateExtension":
1224
+ case "DropExtension":
1225
+ procedures.push({
1226
+ ...step,
1227
+ _tag: step._tag === "CreateExtension" ? "DropExtension" : "CreateExtension"
1228
+ });
1229
+ break;
1230
+ case "UpdateExtension": return `extension ${step.after.name} cannot be downgraded from ${step.after.version} to ${step.before.version ?? "an unpinned version"}`;
1231
+ case "MoveExtension":
1232
+ procedures.push(swap(step));
1233
+ break;
1234
+ case "CreateFunction":
1235
+ case "DropFunction":
1236
+ procedures.push({
1237
+ ...step,
1238
+ _tag: step._tag === "CreateFunction" ? "DropFunction" : "CreateFunction"
1239
+ });
1240
+ break;
1241
+ case "ReplaceFunction":
1242
+ procedures.push(swap(step));
1243
+ break;
1244
+ case "CreateSequence":
1245
+ case "DropSequence":
1246
+ procedures.push({
1247
+ ...step,
1248
+ _tag: step._tag === "CreateSequence" ? "DropSequence" : "CreateSequence"
1249
+ });
1250
+ break;
1251
+ case "AlterSequence":
1252
+ case "RenameSequence":
1253
+ procedures.push(swap(step));
1254
+ break;
344
1255
  case "CreateTrigger":
345
1256
  case "DropTrigger":
346
1257
  procedures.push({
@@ -449,9 +1360,20 @@ const properties = (value, path) => {
449
1360
  record$1(value, path);
450
1361
  semanticValue(value, path);
451
1362
  };
1363
+ const commentText = (value, path) => {
1364
+ if (typeof value !== "string" || value === "") fail(path, "a non-empty string");
1365
+ };
1366
+ const comment = (item, path) => {
1367
+ if (Object.hasOwn(item, "comment")) commentText(item.comment, `${path}.comment`);
1368
+ };
452
1369
  const constraint = (value, path) => {
453
1370
  const item = record$1(value, path);
454
- fields(item, ["kind", "properties"], path);
1371
+ fields(item, [
1372
+ "kind",
1373
+ "properties",
1374
+ "comment"
1375
+ ], path);
1376
+ comment(item, path);
455
1377
  text(item.kind, `${path}.kind`);
456
1378
  properties(item.properties, `${path}.properties`);
457
1379
  };
@@ -461,8 +1383,10 @@ const column = (value, path) => {
461
1383
  "key",
462
1384
  "name",
463
1385
  "dataType",
464
- "constraints"
1386
+ "constraints",
1387
+ "comment"
465
1388
  ], path);
1389
+ comment(item, path);
466
1390
  text(item.key, `${path}.key`);
467
1391
  text(item.name, `${path}.name`);
468
1392
  semanticValue(item.dataType, `${path}.dataType`);
@@ -475,10 +1399,14 @@ const index = (value, path) => {
475
1399
  "name",
476
1400
  "unique",
477
1401
  "terms",
478
- "where"
1402
+ "where",
1403
+ "options",
1404
+ "comment"
479
1405
  ], path);
1406
+ comment(item, path);
480
1407
  text(item.key, `${path}.key`);
481
1408
  text(item.name, `${path}.name`);
1409
+ if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
482
1410
  if (typeof item.unique !== "boolean") fail(`${path}.unique`, "a boolean");
483
1411
  array(item.terms, `${path}.terms`, semanticValue);
484
1412
  semanticValue(item.where, `${path}.where`);
@@ -498,25 +1426,74 @@ const trigger = (value, path) => {
498
1426
  fields(item, [
499
1427
  "identity",
500
1428
  "name",
1429
+ "scope",
501
1430
  "target",
502
- "definition"
1431
+ "definition",
1432
+ "comment"
503
1433
  ], path);
1434
+ comment(item, path);
504
1435
  identity(item.identity, `${path}.identity`);
505
1436
  text(item.name, `${path}.name`);
1437
+ if (Object.hasOwn(item, "scope") && item.scope !== "target") fail(`${path}.scope`, "\"target\"");
506
1438
  identity(item.target, `${path}.target`);
507
1439
  semanticValue(item.definition, `${path}.definition`);
508
1440
  };
1441
+ const sequence = (value, path) => {
1442
+ const item = record$1(value, path);
1443
+ fields(item, [
1444
+ "identity",
1445
+ "name",
1446
+ "definition",
1447
+ "owner",
1448
+ "comment"
1449
+ ], path);
1450
+ comment(item, path);
1451
+ identity(item.identity, `${path}.identity`);
1452
+ text(item.name, `${path}.name`);
1453
+ properties(item.definition, `${path}.definition`);
1454
+ if (Object.hasOwn(item, "owner")) {
1455
+ const owner = record$1(item.owner, `${path}.owner`);
1456
+ fields(owner, ["column", "table"], `${path}.owner`);
1457
+ text(owner.column, `${path}.owner.column`);
1458
+ identity(owner.table, `${path}.owner.table`);
1459
+ }
1460
+ };
1461
+ const databaseFunction = (value, path) => {
1462
+ const item = record$1(value, path);
1463
+ fields(item, [
1464
+ "identity",
1465
+ "name",
1466
+ "signature",
1467
+ "definition",
1468
+ "comment"
1469
+ ], path);
1470
+ comment(item, path);
1471
+ identity(item.identity, `${path}.identity`);
1472
+ text(item.name, `${path}.name`);
1473
+ array(item.signature, `${path}.signature`, semanticValue);
1474
+ properties(item.definition, `${path}.definition`);
1475
+ };
509
1476
  const view = (value, path) => {
510
1477
  const item = record$1(value, path);
511
1478
  fields(item, [
512
1479
  "identity",
513
1480
  "name",
514
1481
  "columns",
515
- "query"
1482
+ "query",
1483
+ "options",
1484
+ "comment",
1485
+ "columnComments"
516
1486
  ], path);
1487
+ comment(item, path);
1488
+ if (Object.hasOwn(item, "columnComments")) {
1489
+ const columns = record$1(item.columnComments, `${path}.columnComments`);
1490
+ for (const key of Reflect.ownKeys(columns)) if (typeof key !== "string") fail(`${path}.columnComments`, "string property keys");
1491
+ else commentText(columns[key], `${path}.columnComments.${key}`);
1492
+ }
517
1493
  identity(item.identity, `${path}.identity`);
518
1494
  text(item.name, `${path}.name`);
519
1495
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
1496
+ if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
520
1497
  semanticValue(item.query, `${path}.query`);
521
1498
  };
522
1499
  const namespace = (value, path) => {
@@ -524,8 +1501,10 @@ const namespace = (value, path) => {
524
1501
  fields(item, [
525
1502
  "identity",
526
1503
  "name",
527
- "options"
1504
+ "options",
1505
+ "comment"
528
1506
  ], path);
1507
+ comment(item, path);
529
1508
  const identity = record$1(item.identity, `${path}.identity`);
530
1509
  fields(identity, ["catalog", "name"], `${path}.identity`);
531
1510
  text(identity.name, `${path}.identity.name`);
@@ -541,8 +1520,10 @@ const table = (value, path) => {
541
1520
  "columns",
542
1521
  "constraints",
543
1522
  "options",
544
- "indexes"
1523
+ "indexes",
1524
+ "comment"
545
1525
  ], path);
1526
+ comment(item, path);
546
1527
  identity(item.identity, `${path}.identity`);
547
1528
  text(item.name, `${path}.name`);
548
1529
  array(item.columns, `${path}.columns`, column);
@@ -550,6 +1531,49 @@ const table = (value, path) => {
550
1531
  array(item.constraints, `${path}.constraints`, constraint);
551
1532
  properties(item.options, `${path}.options`);
552
1533
  };
1534
+ const extension = (value, path) => {
1535
+ const item = record$1(value, path);
1536
+ fields(item, [
1537
+ "name",
1538
+ "schema",
1539
+ "version",
1540
+ "comment"
1541
+ ], path);
1542
+ comment(item, path);
1543
+ text(item.name, `${path}.name`);
1544
+ for (const key of ["schema", "version"]) if (Object.hasOwn(item, key)) text(item[key], `${path}.${key}`);
1545
+ };
1546
+ const databaseEnum = (value, path) => {
1547
+ const item = record$1(value, path);
1548
+ fields(item, [
1549
+ "identity",
1550
+ "name",
1551
+ "values",
1552
+ "comment"
1553
+ ], path);
1554
+ comment(item, path);
1555
+ identity(item.identity, `${path}.identity`);
1556
+ text(item.name, `${path}.name`);
1557
+ const labels = /* @__PURE__ */ new Set();
1558
+ array(item.values, `${path}.values`, (label, at) => {
1559
+ text(label, at);
1560
+ if (labels.has(label)) fail(at, "a distinct label");
1561
+ labels.add(label);
1562
+ });
1563
+ };
1564
+ const externals = (value, path) => {
1565
+ const item = record$1(value, path);
1566
+ fields(item, [
1567
+ "enums",
1568
+ "extensions",
1569
+ "functions",
1570
+ "tables"
1571
+ ], path);
1572
+ if (Object.hasOwn(item, "enums")) array(item.enums, `${path}.enums`, databaseEnum);
1573
+ if (Object.hasOwn(item, "extensions")) array(item.extensions, `${path}.extensions`, extension);
1574
+ if (Object.hasOwn(item, "functions")) array(item.functions, `${path}.functions`, databaseFunction);
1575
+ if (Object.hasOwn(item, "tables")) array(item.tables, `${path}.tables`, table);
1576
+ };
553
1577
  /** Validate external/JSON-restored models before core or a dialect consumes them. */
554
1578
  const decodeDatabaseSchema = (value) => effect.Effect.try({
555
1579
  catch: (cause) => cause instanceof SchemaModelError ? cause : new SchemaModelError({
@@ -562,16 +1586,41 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
562
1586
  "namespaces",
563
1587
  "tables",
564
1588
  "views",
565
- "triggers"
1589
+ "triggers",
1590
+ "sequences",
1591
+ "functions",
1592
+ "externals",
1593
+ "extensions",
1594
+ "enums"
566
1595
  ], "$database");
1596
+ if (Object.hasOwn(database, "enums")) array(database.enums, "$database.enums", databaseEnum);
1597
+ if (Object.hasOwn(database, "extensions")) array(database.extensions, "$database.extensions", extension);
1598
+ if (Object.hasOwn(database, "externals")) externals(database.externals, "$database.externals");
1599
+ if (Object.hasOwn(database, "functions")) array(database.functions, "$database.functions", databaseFunction);
567
1600
  if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
568
1601
  array(database.tables, "$database.tables", table);
569
1602
  if (Object.hasOwn(database, "views")) array(database.views, "$database.views", view);
570
1603
  if (Object.hasOwn(database, "triggers")) array(database.triggers, "$database.triggers", trigger);
1604
+ if (Object.hasOwn(database, "sequences")) array(database.sequences, "$database.sequences", sequence);
571
1605
  return value;
572
1606
  }
573
1607
  });
574
1608
  // src/executor.ts
1609
+ const omissionOrder = {
1610
+ dependent: 2,
1611
+ unmanaged: 1,
1612
+ unsupported: 0
1613
+ };
1614
+ const compareCodePoints = (left, right) => {
1615
+ const a = Array.from(left, (character) => character.codePointAt(0));
1616
+ const b = Array.from(right, (character) => character.codePointAt(0));
1617
+ const index = a.findIndex((point, position) => point !== b[position]);
1618
+ return index < 0 ? a.length - b.length : b[index] === void 0 ? 1 : a[index] - b[index];
1619
+ };
1620
+ /** One line per omission, ordered by category (unsupported, unmanaged, dependent), then name. */
1621
+ const formatExtractOmissions = (omitted) => [...omitted].sort((left, right) => omissionOrder[left.category] - omissionOrder[right.category] || compareCodePoints(left.name, right.name)).map(({ category, detail, kind, name }) => {
1622
+ return `${category} ${kind} ${name}${detail === void 0 ? "" : ` (${category === "dependent" ? "depends on " : ""}${detail})`}`;
1623
+ });
575
1624
  const checksumPattern = /^[a-f0-9]{64}$/;
576
1625
  /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
577
1626
  const migrationRun = (direction, migrations, checkpoint, sha256) => {
@@ -606,7 +1655,49 @@ const renamedColumnId = (source, target, column) => JSON.stringify([
606
1655
  column
607
1656
  ]);
608
1657
  const columnId = (change, column) => change._tag === "TableRenamed" ? renamedColumnId(change.before.identity, change.after.identity, column) : idFor(change.table, column);
1658
+ const enumId = (identity) => JSON.stringify(["enum", tableKey(identity)]);
1659
+ const valueId = (source, target, value) => JSON.stringify([
1660
+ "enum",
1661
+ tableKey(source),
1662
+ tableKey(target),
1663
+ value
1664
+ ]);
1665
+ const enumLabel = (identity) => [
1666
+ identity.catalog,
1667
+ identity.schema,
1668
+ identity.name
1669
+ ].filter((part) => part !== void 0).join(".");
1670
+ const quoted = (value) => `'${JSON.stringify(value).slice(1, -1)}'`;
1671
+ const missingFrom = (values, other) => {
1672
+ const present = new Set(other);
1673
+ return values.filter((value) => !present.has(value));
1674
+ };
1675
+ const enumQuestions = (change, diff) => {
1676
+ if ("enum" in change) {
1677
+ if (change._tag === "EnumAdded") return [];
1678
+ const identity = change.enum.identity;
1679
+ const candidates = diff.changes.flatMap((item) => item._tag === "EnumAdded" && item.enum.identity.catalog === identity.catalog && item.enum.identity.schema === identity.schema ? [item.enum.identity.name] : []);
1680
+ return candidates.length ? [{
1681
+ candidates,
1682
+ enum: identity,
1683
+ id: enumId(identity),
1684
+ question: `Drop type ${enumLabel(identity)}, or rename it to an added type?`,
1685
+ resolution: { action: "pending" }
1686
+ }] : [];
1687
+ }
1688
+ const { after, before } = change;
1689
+ const candidates = missingFrom(after.values, before.values);
1690
+ return candidates.length ? missingFrom(before.values, after.values).map((value) => ({
1691
+ candidates,
1692
+ enum: before.identity,
1693
+ id: valueId(before.identity, after.identity, value),
1694
+ question: `Rename value ${quoted(value)} of ${enumLabel(before.identity)} to an added value?`,
1695
+ resolution: { action: "pending" },
1696
+ value
1697
+ })) : [];
1698
+ };
609
1699
  const questions = (diff) => diff.changes.flatMap((change) => {
1700
+ if (change._tag === "EnumAdded" || change._tag === "EnumRemoved" || change._tag === "EnumRenamed" || change._tag === "EnumChanged") return enumQuestions(change, diff);
610
1701
  if (change._tag === "TableRemoved") {
611
1702
  const candidates = diff.changes.flatMap((item) => item._tag === "TableAdded" && item.table.catalog === change.table.catalog && item.table.schema === change.table.schema ? [item.table.name] : []);
612
1703
  return [{
@@ -646,23 +1737,26 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
646
1737
  if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
647
1738
  const question = expected.get(input.id);
648
1739
  if (!question || answers.has(input.id)) return yield* fail(`Unknown or duplicate decision: ${input.id}`);
649
- if (!equal(input.table, question.table) || input.column !== question.column) return yield* fail(`Decision identity changed: ${input.id}`);
1740
+ if (!("enum" in question ? input.table === void 0 && input.column === void 0 && equal(input.enum, question.enum) && input.value === question.value : input.enum === void 0 && input.value === void 0 && equal(input.table, question.table) && input.column === question.column)) return yield* fail(`Decision identity changed: ${input.id}`);
650
1741
  const resolution = input.resolution;
651
1742
  if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
652
1743
  answers.set(input.id, question);
653
1744
  continue;
654
1745
  }
655
1746
  if (!record(resolution) || resolution.action === "pending") return yield* fail(`Unresolved decision: ${question.question}`);
656
- if ((resolution.action === "drop" || resolution.action === "drop_if_empty") && Object.keys(resolution).length === 1) answers.set(input.id, {
1747
+ if ((resolution.action === "drop" || resolution.action === "drop_if_empty" && !("enum" in question)) && Object.keys(resolution).length === 1) answers.set(input.id, {
657
1748
  ...question,
658
1749
  resolution: { action: resolution.action }
659
1750
  });
660
1751
  else if (resolution.action === "rename" && Object.keys(resolution).length === 2 && typeof resolution.target === "string" && question.candidates.includes(resolution.target)) {
661
- const target = question.column === void 0 ? idFor({
1752
+ const [kind, target] = "enum" in question ? question.value === void 0 ? ["enums", enumId({
1753
+ ...question.enum,
1754
+ name: resolution.target
1755
+ })] : ["values", valueId(question.enum, question.enum, resolution.target)] : question.column === void 0 ? ["tables", idFor({
662
1756
  ...question.table,
663
1757
  name: resolution.target
664
- }) : idFor(question.table, resolution.target);
665
- if (targets.has(target)) return yield* fail(`Multiple source ${question.column === void 0 ? "tables" : "columns"} map to ${resolution.target}.`);
1758
+ })] : ["columns", idFor(question.table, resolution.target)];
1759
+ if (targets.has(target)) return yield* fail(`Multiple source ${kind} map to ${resolution.target}.`);
666
1760
  targets.add(target);
667
1761
  answers.set(input.id, {
668
1762
  ...question,
@@ -677,18 +1771,18 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
677
1771
  return answers;
678
1772
  });
679
1773
  const expandRenames = (diff, answers) => {
680
- const additions = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1774
+ const tables = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1775
+ const enums = new Map(diff.changes.flatMap((item) => "enum" in item && item._tag === "EnumAdded" ? [[tableKey(item.enum.identity), item]] : []));
681
1776
  const renames = [];
682
- for (const source of diff.changes) {
683
- if (source._tag !== "TableRemoved") continue;
1777
+ const consumed = /* @__PURE__ */ new Set();
1778
+ for (const source of diff.changes) if (source._tag === "TableRemoved") {
684
1779
  const choice = answers.get(idFor(source.table))?.resolution;
685
1780
  if (choice?.action !== "rename") continue;
686
- const key = tableKey({
1781
+ const target = tables.get(tableKey({
687
1782
  ...source.table,
688
1783
  name: choice.target
689
- });
690
- const target = additions.get(key);
691
- additions.delete(key);
1784
+ }));
1785
+ consumed.add(source).add(target);
692
1786
  renames.push({
693
1787
  _tag: "TableRenamed",
694
1788
  after: target.definition,
@@ -696,15 +1790,41 @@ const expandRenames = (diff, answers) => {
696
1790
  changes: compareTable(source.definition, target.definition),
697
1791
  table: source.table
698
1792
  });
1793
+ } else if (source._tag === "EnumRemoved") {
1794
+ const identity = source.enum.identity;
1795
+ const choice = answers.get(enumId(identity))?.resolution;
1796
+ if (choice?.action !== "rename") continue;
1797
+ const target = enums.get(tableKey({
1798
+ ...identity,
1799
+ name: choice.target
1800
+ }));
1801
+ consumed.add(source).add(target);
1802
+ renames.push({
1803
+ _tag: "EnumRenamed",
1804
+ after: target.enum,
1805
+ before: source.enum,
1806
+ values: []
1807
+ });
699
1808
  }
700
1809
  return {
701
- diff: { changes: [...diff.changes.filter((item) => {
702
- if (item._tag === "TableAdded") return additions.has(tableKey(item.table));
703
- return item._tag !== "TableRemoved" || answers.get(idFor(item.table))?.resolution.action !== "rename";
704
- }), ...renames] },
1810
+ diff: { changes: [...diff.changes.filter((item) => !consumed.has(item)), ...renames] },
705
1811
  nested: questions({ changes: renames })
706
1812
  };
707
1813
  };
1814
+ const issuedForPairing = (pending, input) => pending.decisions.some((parent) => {
1815
+ if ("enum" in parent) {
1816
+ const value = input.value;
1817
+ return parent.value === void 0 && typeof value === "string" && equal(parent.enum, input.enum) && parent.candidates.some((name) => input.id === valueId(parent.enum, {
1818
+ ...parent.enum,
1819
+ name
1820
+ }, value));
1821
+ }
1822
+ const column = input.column;
1823
+ return parent.column === void 0 && typeof column === "string" && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
1824
+ ...parent.table,
1825
+ name
1826
+ }, column));
1827
+ });
708
1828
  const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(function* () {
709
1829
  const rootIds = new Set(pending.decisions.map((item) => item.id));
710
1830
  const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
@@ -715,25 +1835,40 @@ const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(func
715
1835
  decisions: [...rootAnswers.values(), ...expanded.nested]
716
1836
  };
717
1837
  const expected = new Set(review.decisions.map((item) => item.id));
718
- const current = inputs.filter((input) => {
719
- if (!merging || !record(input) || typeof input.column !== "string" || typeof input.id !== "string" || expected.has(input.id)) return true;
720
- const column = input.column;
721
- return !pending.decisions.some((parent) => parent.column === void 0 && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
722
- ...parent.table,
723
- name
724
- }, column)));
725
- });
1838
+ const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
726
1839
  const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
727
1840
  const missing = expanded.nested.filter((item) => !ids.has(item.id));
728
- if (!merging && missing.length) return yield* effect.Effect.fail(new MigrationDecisionError({
729
- message: "Table rename requires column decisions. Run --merge-decisions to review them.",
730
- pending: review
731
- }));
1841
+ if (!merging && missing.length) {
1842
+ const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : "Table rename requires column decisions";
1843
+ return yield* effect.Effect.fail(new MigrationDecisionError({
1844
+ message: `${required}. Run --merge-decisions to review them.`,
1845
+ pending: review
1846
+ }));
1847
+ }
732
1848
  return {
733
1849
  answers: yield* readAnswers(review, [...current, ...missing], merging),
734
1850
  diff: expanded.diff
735
1851
  };
736
1852
  });
1853
+ /** The enum and value renames that the reviewer accepted. */
1854
+ const enumRenames = (diff, answers) => {
1855
+ const enums = /* @__PURE__ */ new Map();
1856
+ const values = /* @__PURE__ */ new Map();
1857
+ for (const change of diff.changes) {
1858
+ if (change._tag !== "EnumRenamed" && change._tag !== "EnumChanged") continue;
1859
+ const { after, before } = change;
1860
+ const key = tableKey(before.identity);
1861
+ if (change._tag === "EnumRenamed") enums.set(key, after.identity);
1862
+ values.set(key, new Map(before.values.flatMap((value) => {
1863
+ const choice = answers.get(valueId(before.identity, after.identity, value))?.resolution;
1864
+ return choice?.action === "rename" ? [[value, choice.target]] : [];
1865
+ })));
1866
+ }
1867
+ return {
1868
+ enums,
1869
+ values
1870
+ };
1871
+ };
737
1872
  /** Refresh the questions and snapshots, carrying forward applicable reviewed choices. */
738
1873
  const mergeMigrationDecisions = (fresh, previous) => effect.Effect.gen(function* () {
739
1874
  if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* effect.Effect.fail(new MigrationDecisionError({
@@ -791,40 +1926,51 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
791
1926
  const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false);
792
1927
  const answers = reviewed.answers;
793
1928
  const dropGuards = [];
1929
+ const changes = reviewed.diff.changes.map((change) => {
1930
+ if (!("changes" in change)) {
1931
+ if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
1932
+ return change;
1933
+ }
1934
+ const renamedTargets = /* @__PURE__ */ new Set();
1935
+ const changes = [];
1936
+ for (const item of change.changes) {
1937
+ if (item._tag !== "ColumnRemoved") continue;
1938
+ const answer = answers.get(columnId(change, item.column.key));
1939
+ if (answer.resolution.action === "drop_if_empty") dropGuards.push({
1940
+ column: item.column.name,
1941
+ table: change.table
1942
+ });
1943
+ if (answer.resolution.action !== "rename") continue;
1944
+ const targetKey = answer.resolution.target;
1945
+ const afterColumn = change.after.columns.find((column) => column.key === targetKey);
1946
+ renamedTargets.add(afterColumn.key);
1947
+ const fields = [];
1948
+ if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
1949
+ if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1950
+ changes.push({
1951
+ _tag: "ColumnRenamed",
1952
+ after: afterColumn,
1953
+ before: item.column,
1954
+ fields
1955
+ });
1956
+ }
1957
+ return {
1958
+ ...change,
1959
+ changes: [...changes, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "rename"))]
1960
+ };
1961
+ });
1962
+ const renames = sequenceRenames(changes);
1963
+ const kept = changes.filter((change) => !/^(Comment|Enum|Sequence|Trigger)/.test(change._tag));
1964
+ const leading = (change) => /^(Namespace|Extension)/.test(change._tag);
1965
+ const withRenames = [
1966
+ ...kept.filter(leading),
1967
+ ...diffEnums(before, after, enumRenames(reviewed.diff, answers)),
1968
+ ...kept.filter((change) => !leading(change)),
1969
+ ...diffTriggers(before, after, renames),
1970
+ ...diffSequences(before, after, renames)
1971
+ ];
794
1972
  const resolved = {
795
- changes: reviewed.diff.changes.map((change) => {
796
- if (!("changes" in change)) {
797
- if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
798
- return change;
799
- }
800
- const renamedTargets = /* @__PURE__ */ new Set();
801
- const changes = [];
802
- for (const item of change.changes) {
803
- if (item._tag !== "ColumnRemoved") continue;
804
- const answer = answers.get(columnId(change, item.column.key));
805
- if (answer.resolution.action === "drop_if_empty") dropGuards.push({
806
- column: item.column.name,
807
- table: change.table
808
- });
809
- if (answer.resolution.action !== "rename") continue;
810
- const targetKey = answer.resolution.target;
811
- const afterColumn = change.after.columns.find((column) => column.key === targetKey);
812
- renamedTargets.add(afterColumn.key);
813
- const fields = [];
814
- if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
815
- if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
816
- changes.push({
817
- _tag: "ColumnRenamed",
818
- after: afterColumn,
819
- before: item.column,
820
- fields
821
- });
822
- }
823
- return {
824
- ...change,
825
- changes: [...changes, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "rename"))]
826
- };
827
- }),
1973
+ changes: [...withRenames, ...diffComments(before, after, withRenames)],
828
1974
  ...dropGuards.length ? { dropGuards } : {}
829
1975
  };
830
1976
  return {
@@ -836,10 +1982,68 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
836
1982
  };
837
1983
  });
838
1984
  // src/language-service.ts
1985
+ /**
1986
+ * Selects the completion candidates for `completion` from the analyses, in analysis then declaration order.
1987
+ * A declaration is a candidate when its `kind` is `expected` and it has `text`, and either its `scope` is the
1988
+ * completion's scope (inserting `text`), or the completion sets `qualify`, the declaration is a table with
1989
+ * `qualifiedText` and another scope (inserting `qualifiedText`). One candidate per key: the first one wins.
1990
+ */
1991
+ const completionCandidates = (completion, analyses) => {
1992
+ const keys = /* @__PURE__ */ new Set();
1993
+ const candidates = [];
1994
+ analyses.forEach((analysis, source) => {
1995
+ for (const declaration of analysis.declarations) {
1996
+ if (declaration.kind !== completion.expected || keys.has(declaration.key)) continue;
1997
+ let text;
1998
+ if (declaration.scope === completion.scope) text = declaration.text;
1999
+ else if (completion.qualify && declaration.kind === "table" && declaration.qualifiedText !== void 0) text = declaration.qualifiedText;
2000
+ if (text === void 0) continue;
2001
+ keys.add(declaration.key);
2002
+ candidates.push({
2003
+ key: declaration.key,
2004
+ kind: completion.expected,
2005
+ source,
2006
+ text
2007
+ });
2008
+ }
2009
+ });
2010
+ return candidates;
2011
+ };
839
2012
  /** Returns the first reference whose half-open span contains `offset`. */
840
2013
  const referenceAt = (analysis, offset) => analysis.references.find((reference) => reference.start <= offset && offset < reference.end);
2014
+ /** Returns the first declaration whose half-open selection contains `offset`. */
2015
+ const declarationAt = (analysis, offset) => analysis.declarations.find((declaration) => declaration.selection.start <= offset && offset < declaration.selection.end);
2016
+ /** Returns the spans of the references whose key equals `key`, then the declaration selections with that key when `includeDeclaration` is set. */
2017
+ const referencesTo = (key, analysis, includeDeclaration) => [...analysis.references.filter((reference) => reference.key === key).map(({ end, start }) => ({
2018
+ end,
2019
+ start
2020
+ })), ...includeDeclaration ? analysis.declarations.filter((declaration) => declaration.key === key).map((declaration) => declaration.selection) : []];
841
2021
  /** Returns the selections of the declarations whose key equals the reference key, in declaration order. */
842
2022
  const definitions = (reference, analysis) => analysis.declarations.filter((declaration) => declaration.key === reference.key).map((declaration) => declaration.selection);
2023
+ /** The span that rename replaces: `selection` when present, else the reference span. */
2024
+ const nameSpan = (reference) => reference.selection ?? {
2025
+ end: reference.end,
2026
+ start: reference.start
2027
+ };
2028
+ const contains = (span, offset) => span.start <= offset && offset < span.end;
2029
+ /** The declaration, reference or occurrence whose name span contains `offset`. */
2030
+ const renameSiteAt = (analysis, offset) => {
2031
+ const declaration = analysis.declarations.find((candidate) => contains(candidate.selection, offset));
2032
+ if (declaration) return {
2033
+ key: declaration.key,
2034
+ span: declaration.selection
2035
+ };
2036
+ const site = [...analysis.references, ...analysis.occurrences ?? []].find((reference) => contains(nameSpan(reference), offset));
2037
+ return site ? {
2038
+ key: site.key,
2039
+ span: nameSpan(site)
2040
+ } : void 0;
2041
+ };
2042
+ /** The name spans of every declaration, reference and occurrence with `key`, in document order. */
2043
+ const renameSpans = (key, analysis) => [...analysis.declarations.filter((declaration) => declaration.key === key).map((declaration) => declaration.selection), ...[...analysis.references, ...analysis.occurrences ?? []].filter((reference) => reference.key === key).map(nameSpan)].map(({ end, start }) => ({
2044
+ end,
2045
+ start
2046
+ })).sort((left, right) => left.start - right.start);
843
2047
  // src/codegen.ts
844
2048
  var CodegenError = class extends effect.Data.TaggedError("CodegenError") {};
845
2049
  const generatedFileHeader = "// Generated by UncutSQL. Do not edit.";
@@ -999,18 +2203,35 @@ exports.MigrationDecisionError = MigrationDecisionError;
999
2203
  exports.SchemaDiffError = SchemaDiffError;
1000
2204
  exports.SchemaModelError = SchemaModelError;
1001
2205
  exports.artifactPathSchema = artifactPathSchema;
2206
+ exports.checkManagedScope = checkManagedScope;
1002
2207
  exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
2208
+ exports.commentObjects = commentObjects;
1003
2209
  exports.compareTable = compareTable;
2210
+ exports.completionCandidates = completionCandidates;
2211
+ exports.constraintsEqual = constraintsEqual;
1004
2212
  exports.continuesRun = continuesRun;
2213
+ exports.declarationAt = declarationAt;
1005
2214
  exports.decodeDatabaseSchema = decodeDatabaseSchema;
1006
2215
  exports.decodeGenerationResult = decodeGenerationResult;
1007
2216
  exports.decodeGeneratorPlugin = decodeGeneratorPlugin;
1008
2217
  exports.decodeMapperPlugin = decodeMapperPlugin;
1009
2218
  exports.definitions = definitions;
2219
+ exports.diffComments = diffComments;
1010
2220
  exports.diffDatabases = diffDatabases;
2221
+ exports.diffEnums = diffEnums;
2222
+ exports.diffFunctions = diffFunctions;
2223
+ exports.diffSequences = diffSequences;
2224
+ exports.diffTriggers = diffTriggers;
2225
+ exports.enumObjects = enumObjects;
2226
+ exports.extensionObjects = extensionObjects;
2227
+ exports.externalObjects = externalObjects;
2228
+ exports.formatExtractOmissions = formatExtractOmissions;
2229
+ exports.functionKey = functionKey;
2230
+ exports.functionLabel = functionLabel;
1011
2231
  exports.generatedFileHeader = generatedFileHeader;
1012
2232
  exports.mergeMigrationDecisions = mergeMigrationDecisions;
1013
2233
  exports.migrationRun = migrationRun;
2234
+ exports.nameSpan = nameSpan;
1014
2235
  exports.namespaceKey = namespaceKey;
1015
2236
  exports.namespaceOf = namespaceOf;
1016
2237
  exports.nextMigration = nextMigration;
@@ -1018,9 +2239,14 @@ exports.planDatabaseMigration = planDatabaseMigration;
1018
2239
  exports.planDownMigration = planDownMigration;
1019
2240
  exports.prepareMigrationDecisions = prepareMigrationDecisions;
1020
2241
  exports.referenceAt = referenceAt;
2242
+ exports.referencesTo = referencesTo;
1021
2243
  exports.relationIdentitySchema = relationIdentitySchema;
2244
+ exports.renameSiteAt = renameSiteAt;
2245
+ exports.renameSpans = renameSpans;
1022
2246
  exports.resolveMigrationDecisions = resolveMigrationDecisions;
1023
2247
  exports.schemaValueEqual = schemaValueEqual;
2248
+ exports.sequenceRenames = sequenceRenames;
1024
2249
  exports.tableKey = tableKey;
2250
+ exports.triggerKey = triggerKey;
1025
2251
  exports.validateApplicationCompatibility = validateApplicationCompatibility;
1026
2252
  exports.validateDatabase = validateDatabase;