@uncutsql/core 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.
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ 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);
9
10
  const functionKey = (fn) => JSON.stringify([
10
11
  fn.identity.catalog ?? null,
11
12
  fn.identity.schema ?? null,
@@ -41,6 +42,142 @@ const externalObjects = (...databases) => {
41
42
  }
42
43
  return [...found.values()];
43
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
+ };
44
181
  const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
45
182
  /** The namespace that contains an object, or undefined when its identity has no schema level. */
46
183
  const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
@@ -119,8 +256,9 @@ const validateDatabase = (database, side) => {
119
256
  views.add(id);
120
257
  }
121
258
  const triggers = /* @__PURE__ */ new Set();
259
+ const externalTables = new Set((database.externals?.tables ?? []).map((table) => tableKey(table.identity)));
122
260
  for (const trigger of database.triggers ?? []) {
123
- const id = tableKey(trigger.identity);
261
+ const id = triggerKey(trigger);
124
262
  if (triggers.has(id)) diagnostics.push({
125
263
  code: "DuplicateTrigger",
126
264
  message: `Duplicate trigger ${id}`,
@@ -128,6 +266,22 @@ const validateDatabase = (database, side) => {
128
266
  table: trigger.identity
129
267
  });
130
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
+ }
131
285
  }
132
286
  const sequences = /* @__PURE__ */ new Set();
133
287
  for (const sequence of database.sequences ?? []) {
@@ -199,6 +353,98 @@ const validateDatabase = (database, side) => {
199
353
  duplicateColumns(table);
200
354
  }
201
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
+ }
202
448
  if (database.namespaces) {
203
449
  const undeclared = (identity, owner, role) => {
204
450
  const namespace = namespaceOf(identity);
@@ -220,6 +466,7 @@ const validateDatabase = (database, side) => {
220
466
  if (sequence.owner) undeclared(sequence.owner.table, sequence.identity, "Owner table of sequence");
221
467
  }
222
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");
223
470
  }
224
471
  return diagnostics;
225
472
  };
@@ -239,6 +486,7 @@ const checkManagedScope = (model, managedSchemas) => {
239
486
  });
240
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`))];
241
488
  };
489
+ /** Same kinds and properties in the same order; comments are compared by `diffComments`. */
242
490
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
243
491
  const compareTable = (before, after) => {
244
492
  const changes = [];
@@ -419,6 +667,287 @@ const diffSequences = (before, after, renames = {
419
667
  });
420
668
  return changes;
421
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
+ };
422
951
  /** Compare normalized relational models without parsing SQL or consulting a dialect. */
423
952
  const diffDatabases = (before, after) => effect.Effect.gen(function* () {
424
953
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
@@ -442,6 +971,8 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
442
971
  before: old
443
972
  });
444
973
  }
974
+ changes.push(...diffExtensions(before, after));
975
+ changes.push(...diffEnums(before, after));
445
976
  const previous = new Map(before.tables.map((table) => [tableKey(table.identity), table]));
446
977
  const next = new Map(after.tables.map((table) => [tableKey(table.identity), table]));
447
978
  for (const [key, table] of previous) if (!next.has(key)) changes.push({
@@ -485,26 +1016,10 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
485
1016
  before: old
486
1017
  });
487
1018
  }
488
- const oldTriggers = new Map((before.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
489
- const newTriggers = new Map((after.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
490
- for (const [key, trigger] of oldTriggers) if (!newTriggers.has(key)) changes.push({
491
- _tag: "TriggerRemoved",
492
- trigger
493
- });
494
- for (const [key, trigger] of newTriggers) {
495
- const old = oldTriggers.get(key);
496
- if (!old) changes.push({
497
- _tag: "TriggerAdded",
498
- trigger
499
- });
500
- else if (tableKey(old.target) !== tableKey(trigger.target) || !schemaValueEqual(old.definition, trigger.definition)) changes.push({
501
- _tag: "TriggerChanged",
502
- after: trigger,
503
- before: old
504
- });
505
- }
1019
+ changes.push(...diffTriggers(before, after));
506
1020
  changes.push(...diffSequences(before, after));
507
1021
  changes.push(...diffFunctions(before, after));
1022
+ changes.push(...diffComments(before, after, changes));
508
1023
  return { changes };
509
1024
  });
510
1025
  // src/migration.ts
@@ -523,6 +1038,33 @@ const planDatabaseMigration = (diff) => ({
523
1038
  after: change.after,
524
1039
  before: change.before
525
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
+ };
526
1068
  case "FunctionAdded":
527
1069
  case "FunctionRemoved": return {
528
1070
  _tag: change._tag === "FunctionAdded" ? "CreateFunction" : "DropFunction",
@@ -583,14 +1125,79 @@ const planDatabaseMigration = (diff) => ({
583
1125
  before: change.before,
584
1126
  changes: change.changes
585
1127
  };
1128
+ case "CommentChanged": {
1129
+ const { _tag, ...comment } = change;
1130
+ return {
1131
+ _tag: "SetComment",
1132
+ ...comment
1133
+ };
1134
+ }
586
1135
  }
587
1136
  })
588
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
+ };
589
1185
  /** Reverse reviewed intent, retaining rename pairs and guarding newly added data. */
590
1186
  const planDownMigration = (up) => {
591
1187
  const procedures = [];
592
1188
  const dropGuards = [];
1189
+ const downTarget = targetBeforeRenames(up);
593
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
+ }
594
1201
  case "DropTable": return `The up migration removed table ${step.table.name}.`;
595
1202
  case "CreateTable":
596
1203
  dropGuards.push({ table: step.table.identity });
@@ -599,6 +1206,31 @@ const planDownMigration = (up) => {
599
1206
  _tag: "DropTable"
600
1207
  });
601
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;
602
1234
  case "CreateFunction":
603
1235
  case "DropFunction":
604
1236
  procedures.push({
@@ -728,9 +1360,20 @@ const properties = (value, path) => {
728
1360
  record$1(value, path);
729
1361
  semanticValue(value, path);
730
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
+ };
731
1369
  const constraint = (value, path) => {
732
1370
  const item = record$1(value, path);
733
- fields(item, ["kind", "properties"], path);
1371
+ fields(item, [
1372
+ "kind",
1373
+ "properties",
1374
+ "comment"
1375
+ ], path);
1376
+ comment(item, path);
734
1377
  text(item.kind, `${path}.kind`);
735
1378
  properties(item.properties, `${path}.properties`);
736
1379
  };
@@ -740,8 +1383,10 @@ const column = (value, path) => {
740
1383
  "key",
741
1384
  "name",
742
1385
  "dataType",
743
- "constraints"
1386
+ "constraints",
1387
+ "comment"
744
1388
  ], path);
1389
+ comment(item, path);
745
1390
  text(item.key, `${path}.key`);
746
1391
  text(item.name, `${path}.name`);
747
1392
  semanticValue(item.dataType, `${path}.dataType`);
@@ -755,8 +1400,10 @@ const index = (value, path) => {
755
1400
  "unique",
756
1401
  "terms",
757
1402
  "where",
758
- "options"
1403
+ "options",
1404
+ "comment"
759
1405
  ], path);
1406
+ comment(item, path);
760
1407
  text(item.key, `${path}.key`);
761
1408
  text(item.name, `${path}.name`);
762
1409
  if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
@@ -779,11 +1426,15 @@ const trigger = (value, path) => {
779
1426
  fields(item, [
780
1427
  "identity",
781
1428
  "name",
1429
+ "scope",
782
1430
  "target",
783
- "definition"
1431
+ "definition",
1432
+ "comment"
784
1433
  ], path);
1434
+ comment(item, path);
785
1435
  identity(item.identity, `${path}.identity`);
786
1436
  text(item.name, `${path}.name`);
1437
+ if (Object.hasOwn(item, "scope") && item.scope !== "target") fail(`${path}.scope`, "\"target\"");
787
1438
  identity(item.target, `${path}.target`);
788
1439
  semanticValue(item.definition, `${path}.definition`);
789
1440
  };
@@ -793,8 +1444,10 @@ const sequence = (value, path) => {
793
1444
  "identity",
794
1445
  "name",
795
1446
  "definition",
796
- "owner"
1447
+ "owner",
1448
+ "comment"
797
1449
  ], path);
1450
+ comment(item, path);
798
1451
  identity(item.identity, `${path}.identity`);
799
1452
  text(item.name, `${path}.name`);
800
1453
  properties(item.definition, `${path}.definition`);
@@ -811,8 +1464,10 @@ const databaseFunction = (value, path) => {
811
1464
  "identity",
812
1465
  "name",
813
1466
  "signature",
814
- "definition"
1467
+ "definition",
1468
+ "comment"
815
1469
  ], path);
1470
+ comment(item, path);
816
1471
  identity(item.identity, `${path}.identity`);
817
1472
  text(item.name, `${path}.name`);
818
1473
  array(item.signature, `${path}.signature`, semanticValue);
@@ -825,8 +1480,16 @@ const view = (value, path) => {
825
1480
  "name",
826
1481
  "columns",
827
1482
  "query",
828
- "options"
1483
+ "options",
1484
+ "comment",
1485
+ "columnComments"
829
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
+ }
830
1493
  identity(item.identity, `${path}.identity`);
831
1494
  text(item.name, `${path}.name`);
832
1495
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
@@ -838,8 +1501,10 @@ const namespace = (value, path) => {
838
1501
  fields(item, [
839
1502
  "identity",
840
1503
  "name",
841
- "options"
1504
+ "options",
1505
+ "comment"
842
1506
  ], path);
1507
+ comment(item, path);
843
1508
  const identity = record$1(item.identity, `${path}.identity`);
844
1509
  fields(identity, ["catalog", "name"], `${path}.identity`);
845
1510
  text(identity.name, `${path}.identity.name`);
@@ -855,8 +1520,10 @@ const table = (value, path) => {
855
1520
  "columns",
856
1521
  "constraints",
857
1522
  "options",
858
- "indexes"
1523
+ "indexes",
1524
+ "comment"
859
1525
  ], path);
1526
+ comment(item, path);
860
1527
  identity(item.identity, `${path}.identity`);
861
1528
  text(item.name, `${path}.name`);
862
1529
  array(item.columns, `${path}.columns`, column);
@@ -864,9 +1531,46 @@ const table = (value, path) => {
864
1531
  array(item.constraints, `${path}.constraints`, constraint);
865
1532
  properties(item.options, `${path}.options`);
866
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
+ };
867
1564
  const externals = (value, path) => {
868
1565
  const item = record$1(value, path);
869
- fields(item, ["functions", "tables"], 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);
870
1574
  if (Object.hasOwn(item, "functions")) array(item.functions, `${path}.functions`, databaseFunction);
871
1575
  if (Object.hasOwn(item, "tables")) array(item.tables, `${path}.tables`, table);
872
1576
  };
@@ -885,8 +1589,12 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
885
1589
  "triggers",
886
1590
  "sequences",
887
1591
  "functions",
888
- "externals"
1592
+ "externals",
1593
+ "extensions",
1594
+ "enums"
889
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);
890
1598
  if (Object.hasOwn(database, "externals")) externals(database.externals, "$database.externals");
891
1599
  if (Object.hasOwn(database, "functions")) array(database.functions, "$database.functions", databaseFunction);
892
1600
  if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
@@ -898,6 +1606,21 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
898
1606
  }
899
1607
  });
900
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
+ });
901
1624
  const checksumPattern = /^[a-f0-9]{64}$/;
902
1625
  /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
903
1626
  const migrationRun = (direction, migrations, checkpoint, sha256) => {
@@ -932,7 +1655,49 @@ const renamedColumnId = (source, target, column) => JSON.stringify([
932
1655
  column
933
1656
  ]);
934
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
+ };
935
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);
936
1701
  if (change._tag === "TableRemoved") {
937
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] : []);
938
1703
  return [{
@@ -972,23 +1737,26 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
972
1737
  if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
973
1738
  const question = expected.get(input.id);
974
1739
  if (!question || answers.has(input.id)) return yield* fail(`Unknown or duplicate decision: ${input.id}`);
975
- 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}`);
976
1741
  const resolution = input.resolution;
977
1742
  if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
978
1743
  answers.set(input.id, question);
979
1744
  continue;
980
1745
  }
981
1746
  if (!record(resolution) || resolution.action === "pending") return yield* fail(`Unresolved decision: ${question.question}`);
982
- 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, {
983
1748
  ...question,
984
1749
  resolution: { action: resolution.action }
985
1750
  });
986
1751
  else if (resolution.action === "rename" && Object.keys(resolution).length === 2 && typeof resolution.target === "string" && question.candidates.includes(resolution.target)) {
987
- 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({
988
1756
  ...question.table,
989
1757
  name: resolution.target
990
- }) : idFor(question.table, resolution.target);
991
- 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}.`);
992
1760
  targets.add(target);
993
1761
  answers.set(input.id, {
994
1762
  ...question,
@@ -1003,18 +1771,18 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
1003
1771
  return answers;
1004
1772
  });
1005
1773
  const expandRenames = (diff, answers) => {
1006
- 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]] : []));
1007
1776
  const renames = [];
1008
- for (const source of diff.changes) {
1009
- if (source._tag !== "TableRemoved") continue;
1777
+ const consumed = /* @__PURE__ */ new Set();
1778
+ for (const source of diff.changes) if (source._tag === "TableRemoved") {
1010
1779
  const choice = answers.get(idFor(source.table))?.resolution;
1011
1780
  if (choice?.action !== "rename") continue;
1012
- const key = tableKey({
1781
+ const target = tables.get(tableKey({
1013
1782
  ...source.table,
1014
1783
  name: choice.target
1015
- });
1016
- const target = additions.get(key);
1017
- additions.delete(key);
1784
+ }));
1785
+ consumed.add(source).add(target);
1018
1786
  renames.push({
1019
1787
  _tag: "TableRenamed",
1020
1788
  after: target.definition,
@@ -1022,15 +1790,41 @@ const expandRenames = (diff, answers) => {
1022
1790
  changes: compareTable(source.definition, target.definition),
1023
1791
  table: source.table
1024
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
+ });
1025
1808
  }
1026
1809
  return {
1027
- diff: { changes: [...diff.changes.filter((item) => {
1028
- if (item._tag === "TableAdded") return additions.has(tableKey(item.table));
1029
- return item._tag !== "TableRemoved" || answers.get(idFor(item.table))?.resolution.action !== "rename";
1030
- }), ...renames] },
1810
+ diff: { changes: [...diff.changes.filter((item) => !consumed.has(item)), ...renames] },
1031
1811
  nested: questions({ changes: renames })
1032
1812
  };
1033
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
+ });
1034
1828
  const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(function* () {
1035
1829
  const rootIds = new Set(pending.decisions.map((item) => item.id));
1036
1830
  const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
@@ -1041,25 +1835,40 @@ const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(func
1041
1835
  decisions: [...rootAnswers.values(), ...expanded.nested]
1042
1836
  };
1043
1837
  const expected = new Set(review.decisions.map((item) => item.id));
1044
- const current = inputs.filter((input) => {
1045
- if (!merging || !record(input) || typeof input.column !== "string" || typeof input.id !== "string" || expected.has(input.id)) return true;
1046
- const column = input.column;
1047
- return !pending.decisions.some((parent) => parent.column === void 0 && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
1048
- ...parent.table,
1049
- name
1050
- }, column)));
1051
- });
1838
+ const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
1052
1839
  const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
1053
1840
  const missing = expanded.nested.filter((item) => !ids.has(item.id));
1054
- if (!merging && missing.length) return yield* effect.Effect.fail(new MigrationDecisionError({
1055
- message: "Table rename requires column decisions. Run --merge-decisions to review them.",
1056
- pending: review
1057
- }));
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
+ }
1058
1848
  return {
1059
1849
  answers: yield* readAnswers(review, [...current, ...missing], merging),
1060
1850
  diff: expanded.diff
1061
1851
  };
1062
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
+ };
1063
1872
  /** Refresh the questions and snapshots, carrying forward applicable reviewed choices. */
1064
1873
  const mergeMigrationDecisions = (fresh, previous) => effect.Effect.gen(function* () {
1065
1874
  if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* effect.Effect.fail(new MigrationDecisionError({
@@ -1137,7 +1946,7 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
1137
1946
  renamedTargets.add(afterColumn.key);
1138
1947
  const fields = [];
1139
1948
  if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
1140
- if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1949
+ if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1141
1950
  changes.push({
1142
1951
  _tag: "ColumnRenamed",
1143
1952
  after: afterColumn,
@@ -1150,8 +1959,18 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
1150
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"))]
1151
1960
  };
1152
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
+ ];
1153
1972
  const resolved = {
1154
- changes: [...changes.filter((change) => !change._tag.startsWith("Sequence")), ...diffSequences(before, after, sequenceRenames(changes))],
1973
+ changes: [...withRenames, ...diffComments(before, after, withRenames)],
1155
1974
  ...dropGuards.length ? { dropGuards } : {}
1156
1975
  };
1157
1976
  return {
@@ -1386,8 +2205,10 @@ exports.SchemaModelError = SchemaModelError;
1386
2205
  exports.artifactPathSchema = artifactPathSchema;
1387
2206
  exports.checkManagedScope = checkManagedScope;
1388
2207
  exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
2208
+ exports.commentObjects = commentObjects;
1389
2209
  exports.compareTable = compareTable;
1390
2210
  exports.completionCandidates = completionCandidates;
2211
+ exports.constraintsEqual = constraintsEqual;
1391
2212
  exports.continuesRun = continuesRun;
1392
2213
  exports.declarationAt = declarationAt;
1393
2214
  exports.decodeDatabaseSchema = decodeDatabaseSchema;
@@ -1395,10 +2216,16 @@ exports.decodeGenerationResult = decodeGenerationResult;
1395
2216
  exports.decodeGeneratorPlugin = decodeGeneratorPlugin;
1396
2217
  exports.decodeMapperPlugin = decodeMapperPlugin;
1397
2218
  exports.definitions = definitions;
2219
+ exports.diffComments = diffComments;
1398
2220
  exports.diffDatabases = diffDatabases;
2221
+ exports.diffEnums = diffEnums;
1399
2222
  exports.diffFunctions = diffFunctions;
1400
2223
  exports.diffSequences = diffSequences;
2224
+ exports.diffTriggers = diffTriggers;
2225
+ exports.enumObjects = enumObjects;
2226
+ exports.extensionObjects = extensionObjects;
1401
2227
  exports.externalObjects = externalObjects;
2228
+ exports.formatExtractOmissions = formatExtractOmissions;
1402
2229
  exports.functionKey = functionKey;
1403
2230
  exports.functionLabel = functionLabel;
1404
2231
  exports.generatedFileHeader = generatedFileHeader;
@@ -1420,5 +2247,6 @@ exports.resolveMigrationDecisions = resolveMigrationDecisions;
1420
2247
  exports.schemaValueEqual = schemaValueEqual;
1421
2248
  exports.sequenceRenames = sequenceRenames;
1422
2249
  exports.tableKey = tableKey;
2250
+ exports.triggerKey = triggerKey;
1423
2251
  exports.validateApplicationCompatibility = validateApplicationCompatibility;
1424
2252
  exports.validateDatabase = validateDatabase;