@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.js CHANGED
@@ -5,6 +5,7 @@ const tableKey = (table) => JSON.stringify([
5
5
  table.schema ?? null,
6
6
  table.name
7
7
  ]);
8
+ const triggerKey = (trigger) => trigger.scope === "target" ? JSON.stringify([tableKey(trigger.target), trigger.identity.name]) : tableKey(trigger.identity);
8
9
  const functionKey = (fn) => JSON.stringify([
9
10
  fn.identity.catalog ?? null,
10
11
  fn.identity.schema ?? null,
@@ -40,6 +41,142 @@ const externalObjects = (...databases) => {
40
41
  }
41
42
  return [...found.values()];
42
43
  };
44
+ /** The managed and external enums of the models, each listed once by its key. */
45
+ const enumObjects = (...databases) => {
46
+ const found = /* @__PURE__ */ new Map();
47
+ for (const database of databases) for (const [kind, enums] of [["Enum", database.enums], ["External enum", database.externals?.enums]]) for (const { identity } of enums ?? []) {
48
+ const name = [
49
+ identity.catalog,
50
+ identity.schema,
51
+ identity.name
52
+ ].filter((part) => part !== void 0).join(".");
53
+ found.set(tableKey(identity), {
54
+ identity,
55
+ label: `${kind} ${name}`
56
+ });
57
+ }
58
+ return [...found.values()];
59
+ };
60
+ /** The managed and external extensions of the models, each listed once by its name. */
61
+ const extensionObjects = (...databases) => {
62
+ const found = /* @__PURE__ */ new Map();
63
+ for (const database of databases) for (const extension of [...database.extensions ?? [], ...database.externals?.extensions ?? []]) found.set(extension.name, extension);
64
+ return [...found.values()];
65
+ };
66
+ const dotted = ({ catalog, name, schema }) => [
67
+ catalog,
68
+ schema,
69
+ name
70
+ ].filter((part) => part !== void 0).join(".");
71
+ const commentObject = (target) => {
72
+ const on = (identity, text) => ({
73
+ identity,
74
+ label: `Comment on ${text}`
75
+ });
76
+ switch (target.kind) {
77
+ case "enum":
78
+ case "sequence":
79
+ case "table":
80
+ case "view": return on(target.identity, `${target.kind} ${dotted(target.identity)}`);
81
+ case "column": return on(target.table, `column ${dotted(target.table)}.${target.column}`);
82
+ case "viewColumn": return on(target.view, `view column ${dotted(target.view)}.${target.column}`);
83
+ case "index": return on(target.table, `index ${target.index} of table ${dotted(target.table)}`);
84
+ case "constraint": return on(target.table, `${target.constraint.kind} constraint of ${dotted(target.table)}`);
85
+ case "function": return on(target.identity, `function ${functionLabel(target)}`);
86
+ case "trigger": return on(target.target, `trigger ${target.name} on ${dotted(target.target)}`);
87
+ case "namespace": return on(target.identity, `schema ${dotted(target.identity)}`);
88
+ case "extension": return on({ name: target.name }, `extension ${target.name}`);
89
+ }
90
+ };
91
+ /** The targets of a model's own comments; externals are not included. */
92
+ const commentTargets = (database) => {
93
+ const targets = [];
94
+ const add = (item, target) => {
95
+ if (item.comment !== void 0) targets.push(target());
96
+ };
97
+ for (const item of database.namespaces ?? []) add(item, () => ({
98
+ identity: item.identity,
99
+ kind: "namespace"
100
+ }));
101
+ for (const item of database.extensions ?? []) add(item, () => ({
102
+ kind: "extension",
103
+ name: item.name
104
+ }));
105
+ for (const item of database.enums ?? []) add(item, () => ({
106
+ identity: item.identity,
107
+ kind: "enum"
108
+ }));
109
+ for (const table of database.tables ?? []) {
110
+ const { identity } = table;
111
+ const constraints = (items) => {
112
+ for (const item of items ?? []) add(item, () => ({
113
+ constraint: {
114
+ kind: item.kind,
115
+ properties: item.properties
116
+ },
117
+ kind: "constraint",
118
+ table: identity
119
+ }));
120
+ };
121
+ add(table, () => ({
122
+ identity,
123
+ kind: "table"
124
+ }));
125
+ for (const column of table.columns ?? []) {
126
+ add(column, () => ({
127
+ column: column.key,
128
+ kind: "column",
129
+ table: identity
130
+ }));
131
+ constraints(column.constraints);
132
+ }
133
+ constraints(table.constraints);
134
+ for (const index of table.indexes ?? []) add(index, () => ({
135
+ index: index.key,
136
+ kind: "index",
137
+ table: identity
138
+ }));
139
+ }
140
+ for (const view of database.views ?? []) {
141
+ add(view, () => ({
142
+ identity: view.identity,
143
+ kind: "view"
144
+ }));
145
+ for (const column of Object.keys(view.columnComments ?? {})) targets.push({
146
+ column,
147
+ kind: "viewColumn",
148
+ view: view.identity
149
+ });
150
+ }
151
+ for (const item of database.triggers ?? []) add(item, () => ({
152
+ kind: "trigger",
153
+ name: item.identity.name,
154
+ target: item.target
155
+ }));
156
+ for (const item of database.sequences ?? []) add(item, () => ({
157
+ identity: item.identity,
158
+ kind: "sequence"
159
+ }));
160
+ for (const item of database.functions ?? []) add(item, () => ({
161
+ identity: item.identity,
162
+ kind: "function",
163
+ signature: item.signature
164
+ }));
165
+ return targets;
166
+ };
167
+ /**
168
+ * Every commented object of the models, externals included, and of `targets` (for example those of
169
+ * `SetComment` procedures), each listed once by its label. A dialect without comments refuses them.
170
+ */
171
+ const commentObjects = (databases, targets = []) => {
172
+ const found = /* @__PURE__ */ new Map();
173
+ const all = [...databases.flatMap((database) => [...commentTargets(database), ...commentTargets(database.externals ?? {})]), ...targets];
174
+ for (const target of all) {
175
+ const object = commentObject(target);
176
+ found.set(object.label, object);
177
+ }
178
+ return [...found.values()];
179
+ };
43
180
  const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
44
181
  /** The namespace that contains an object, or undefined when its identity has no schema level. */
45
182
  const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
@@ -118,8 +255,9 @@ const validateDatabase = (database, side) => {
118
255
  views.add(id);
119
256
  }
120
257
  const triggers = /* @__PURE__ */ new Set();
258
+ const externalTables = new Set((database.externals?.tables ?? []).map((table) => tableKey(table.identity)));
121
259
  for (const trigger of database.triggers ?? []) {
122
- const id = tableKey(trigger.identity);
260
+ const id = triggerKey(trigger);
123
261
  if (triggers.has(id)) diagnostics.push({
124
262
  code: "DuplicateTrigger",
125
263
  message: `Duplicate trigger ${id}`,
@@ -127,6 +265,22 @@ const validateDatabase = (database, side) => {
127
265
  table: trigger.identity
128
266
  });
129
267
  triggers.add(id);
268
+ const target = tableKey(trigger.target);
269
+ if (!tables.has(target) && !views.has(target)) {
270
+ const { catalog, name, schema } = trigger.target;
271
+ const label = [
272
+ catalog,
273
+ schema,
274
+ name
275
+ ].filter((part) => part !== void 0).join(".");
276
+ const isExternal = externalTables.has(target);
277
+ diagnostics.push({
278
+ code: isExternal ? "ExternalTriggerTarget" : "UnknownTriggerTarget",
279
+ 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`,
280
+ side,
281
+ table: trigger.identity
282
+ });
283
+ }
130
284
  }
131
285
  const sequences = /* @__PURE__ */ new Set();
132
286
  for (const sequence of database.sequences ?? []) {
@@ -198,6 +352,98 @@ const validateDatabase = (database, side) => {
198
352
  duplicateColumns(table);
199
353
  }
200
354
  for (const fn of database.externals?.functions ?? []) external(`function ${functionKey(fn)}`, fn.identity, `function ${functionLabel(fn)}`, "CREATE FUNCTION");
355
+ for (const item of commentObjects([{
356
+ externals: database.externals ?? {},
357
+ tables: []
358
+ }])) diagnostics.push({
359
+ code: "ExternalComment",
360
+ message: `${item.label} is on an external object, which migrations never alter; remove the comment`,
361
+ side,
362
+ table: item.identity
363
+ });
364
+ const enums = /* @__PURE__ */ new Set();
365
+ const duplicateEnum = (identity, message) => diagnostics.push({
366
+ code: "DuplicateEnum",
367
+ message,
368
+ side,
369
+ table: identity
370
+ });
371
+ const duplicateValues = ({ identity, values }) => {
372
+ const labels = /* @__PURE__ */ new Set();
373
+ for (const label of values) {
374
+ if (labels.has(label)) diagnostics.push({
375
+ code: "DuplicateEnumValue",
376
+ message: `Duplicate value ${JSON.stringify(label)} in enum ${tableKey(identity)}`,
377
+ side,
378
+ table: identity
379
+ });
380
+ labels.add(label);
381
+ }
382
+ };
383
+ for (const item of database.enums ?? []) {
384
+ const id = tableKey(item.identity);
385
+ if (enums.has(id)) duplicateEnum(item.identity, `Duplicate enum ${id}`);
386
+ enums.add(id);
387
+ duplicateValues(item);
388
+ }
389
+ for (const item of database.externals?.enums ?? []) {
390
+ const { catalog, name, schema } = item.identity;
391
+ const id = tableKey(item.identity);
392
+ if (enums.has(id)) duplicateEnum(item.identity, `Enum ${id} is both managed and external`);
393
+ external(`enum ${id}`, item.identity, `enum ${[
394
+ catalog,
395
+ schema,
396
+ name
397
+ ].filter((part) => part !== void 0).join(".")}`, "CREATE TYPE");
398
+ duplicateValues(item);
399
+ }
400
+ const extensions = /* @__PURE__ */ new Set();
401
+ const extensionIdentity = ({ name, schema }) => schema === void 0 ? { name } : {
402
+ name,
403
+ schema
404
+ };
405
+ const managedNamespace = (identity) => {
406
+ const namespace = namespaceOf(identity);
407
+ return namespace && namespaces.has(namespaceKey(namespace));
408
+ };
409
+ for (const extension of database.extensions ?? []) {
410
+ if (extensions.has(extension.name)) diagnostics.push({
411
+ code: "DuplicateExtension",
412
+ message: `Duplicate extension ${extension.name}`,
413
+ side,
414
+ table: extensionIdentity(extension)
415
+ });
416
+ extensions.add(extension.name);
417
+ if (database.namespaces && extension.schema !== void 0 && !managedNamespace(extensionIdentity(extension))) diagnostics.push({
418
+ code: "UndeclaredNamespace",
419
+ message: `Extension ${extension.name} belongs to undeclared namespace ${namespaceKey({ name: extension.schema })}; declare an extension that another tool installs with DECLARE EXTERNAL EXTENSION`,
420
+ side,
421
+ table: extensionIdentity(extension)
422
+ });
423
+ }
424
+ const externalExtensions = /* @__PURE__ */ new Set();
425
+ for (const extension of database.externals?.extensions ?? []) {
426
+ const table = extensionIdentity(extension);
427
+ if (externalExtensions.has(extension.name)) diagnostics.push({
428
+ code: "DuplicateExternal",
429
+ message: `Duplicate extension ${extension.name}`,
430
+ side,
431
+ table
432
+ });
433
+ else if (extensions.has(extension.name)) diagnostics.push({
434
+ code: "DuplicateExtension",
435
+ message: `Extension ${extension.name} is both managed and external`,
436
+ side,
437
+ table
438
+ });
439
+ externalExtensions.add(extension.name);
440
+ if (managedNamespace(table)) diagnostics.push({
441
+ code: "ExternalInManagedNamespace",
442
+ message: `External extension ${extension.name} is in managed schema ${extension.schema}; declare it with CREATE EXTENSION`,
443
+ side,
444
+ table
445
+ });
446
+ }
201
447
  if (database.namespaces) {
202
448
  const undeclared = (identity, owner, role) => {
203
449
  const namespace = namespaceOf(identity);
@@ -219,6 +465,7 @@ const validateDatabase = (database, side) => {
219
465
  if (sequence.owner) undeclared(sequence.owner.table, sequence.identity, "Owner table of sequence");
220
466
  }
221
467
  for (const fn of database.functions ?? []) undeclared(fn.identity, fn.identity, "Function");
468
+ for (const item of database.enums ?? []) undeclared(item.identity, item.identity, "Enum");
222
469
  }
223
470
  return diagnostics;
224
471
  };
@@ -238,6 +485,7 @@ const checkManagedScope = (model, managedSchemas) => {
238
485
  });
239
486
  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`))];
240
487
  };
488
+ /** Same kinds and properties in the same order; comments are compared by `diffComments`. */
241
489
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
242
490
  const compareTable = (before, after) => {
243
491
  const changes = [];
@@ -418,6 +666,287 @@ const diffSequences = (before, after, renames = {
418
666
  });
419
667
  return changes;
420
668
  };
669
+ /** The `before` triggers keyed as in the after model, and those that lose their key to another. */
670
+ const triggersAfterRenames = (before, renames) => {
671
+ const keyed = /* @__PURE__ */ new Map();
672
+ const displaced = [];
673
+ const moved = (trigger) => renames.tables.has(tableKey(trigger.target));
674
+ const ordered = [...before.triggers ?? []].sort((a, b) => Number(moved(a)) - Number(moved(b)));
675
+ for (const trigger of ordered) {
676
+ const target = renames.tables.get(tableKey(trigger.target)) ?? trigger.target;
677
+ const key = triggerKey({
678
+ ...trigger,
679
+ target
680
+ });
681
+ const previous = keyed.get(key);
682
+ if (previous) displaced.push(previous.trigger);
683
+ keyed.set(key, {
684
+ target,
685
+ trigger
686
+ });
687
+ }
688
+ return {
689
+ displaced,
690
+ keyed
691
+ };
692
+ };
693
+ /**
694
+ * Trigger changes, paired by `triggerKey`. `renames` are the table renames the migration applies: a
695
+ * trigger follows its renamed target. There are no trigger renames.
696
+ */
697
+ const diffTriggers = (before, after, renames = {
698
+ columns: /* @__PURE__ */ new Map(),
699
+ tables: /* @__PURE__ */ new Map()
700
+ }) => {
701
+ const { displaced, keyed: oldTriggers } = triggersAfterRenames(before, renames);
702
+ const changes = displaced.map((trigger) => ({
703
+ _tag: "TriggerRemoved",
704
+ trigger
705
+ }));
706
+ const newTriggers = new Map((after.triggers ?? []).map((item) => [triggerKey(item), item]));
707
+ for (const [key, { trigger }] of oldTriggers) if (!newTriggers.has(key)) changes.push({
708
+ _tag: "TriggerRemoved",
709
+ trigger
710
+ });
711
+ for (const [key, trigger] of newTriggers) {
712
+ const old = oldTriggers.get(key);
713
+ if (!old) changes.push({
714
+ _tag: "TriggerAdded",
715
+ trigger
716
+ });
717
+ else if (tableKey(old.target) !== tableKey(trigger.target) || !schemaValueEqual(old.trigger.definition, trigger.definition)) changes.push({
718
+ _tag: "TriggerChanged",
719
+ after: trigger,
720
+ before: old.trigger
721
+ });
722
+ }
723
+ return changes;
724
+ };
725
+ /**
726
+ * Enum changes, paired by `tableKey`. A renamed enum has one `EnumRenamed`, whether or not its
727
+ * labels differ too. Removals and order are not judged here; external enums are ignored.
728
+ */
729
+ const diffEnums = (before, after, renames = {
730
+ enums: /* @__PURE__ */ new Map(),
731
+ values: /* @__PURE__ */ new Map()
732
+ }) => {
733
+ const changes = [];
734
+ const oldEnums = new Map((before.enums ?? []).map((item) => [tableKey(item.identity), item]));
735
+ const newEnums = new Map((after.enums ?? []).map((item) => [tableKey(item.identity), item]));
736
+ const valueRenames = (item) => {
737
+ const renamed = renames.values.get(tableKey(item.identity));
738
+ return item.values.flatMap((label) => {
739
+ const target = renamed?.get(label);
740
+ return target === void 0 ? [] : [{
741
+ after: target,
742
+ before: label
743
+ }];
744
+ });
745
+ };
746
+ const renamed = /* @__PURE__ */ new Map();
747
+ for (const [key, item] of oldEnums) {
748
+ const target = renames.enums.get(key);
749
+ if (target && tableKey(target) !== key && newEnums.has(tableKey(target))) renamed.set(tableKey(target), item);
750
+ }
751
+ const sources = new Set(renamed.values());
752
+ for (const [key, item] of oldEnums) if (!sources.has(item) && (!newEnums.has(key) || renamed.has(key))) changes.push({
753
+ _tag: "EnumRemoved",
754
+ enum: item
755
+ });
756
+ for (const [key, item] of newEnums) {
757
+ const source = renamed.get(key);
758
+ if (source) {
759
+ changes.push({
760
+ _tag: "EnumRenamed",
761
+ after: item,
762
+ before: source,
763
+ values: valueRenames(source)
764
+ });
765
+ continue;
766
+ }
767
+ const old = oldEnums.get(key);
768
+ if (!old || sources.has(old)) changes.push({
769
+ _tag: "EnumAdded",
770
+ enum: item
771
+ });
772
+ else if (!schemaValueEqual(old.values, item.values)) changes.push({
773
+ _tag: "EnumChanged",
774
+ after: item,
775
+ before: old,
776
+ values: valueRenames(old)
777
+ });
778
+ }
779
+ return changes;
780
+ };
781
+ /** Extensions are compared by name. Unpinning a version is no change. */
782
+ const diffExtensions = (before, after) => {
783
+ const changes = [];
784
+ const oldExtensions = new Map((before.extensions ?? []).map((item) => [item.name, item]));
785
+ const newExtensions = new Map((after.extensions ?? []).map((item) => [item.name, item]));
786
+ for (const [name, extension] of oldExtensions) if (!newExtensions.has(name)) changes.push({
787
+ _tag: "ExtensionRemoved",
788
+ extension
789
+ });
790
+ for (const [name, extension] of newExtensions) {
791
+ const old = oldExtensions.get(name);
792
+ if (!old) {
793
+ changes.push({
794
+ _tag: "ExtensionAdded",
795
+ extension
796
+ });
797
+ continue;
798
+ }
799
+ if (old.schema !== extension.schema) changes.push({
800
+ _tag: "ExtensionSchemaChanged",
801
+ after: extension,
802
+ before: old
803
+ });
804
+ if (extension.version !== void 0 && extension.version !== old.version) changes.push({
805
+ _tag: "ExtensionVersionChanged",
806
+ after: extension,
807
+ before: old
808
+ });
809
+ }
810
+ return changes;
811
+ };
812
+ /**
813
+ * The objects that both lists hold, as `[before, after]` in after order. `renamed` maps the key of a
814
+ * renamed after object to its key before; the source of a rename pairs with nothing else.
815
+ */
816
+ const pairs = (before, after, key, renamed = /* @__PURE__ */ new Map()) => {
817
+ const old = new Map((before ?? []).map((item) => [key(item), item]));
818
+ const sources = new Set(renamed.values());
819
+ return (after ?? []).flatMap((item) => {
820
+ const own = key(item);
821
+ const source = renamed.get(own) ?? (sources.has(own) ? void 0 : own);
822
+ const previous = source === void 0 ? void 0 : old.get(source);
823
+ return previous === void 0 ? [] : [[previous, item]];
824
+ });
825
+ };
826
+ /** Constraints that are equal apart from their comment, preferring those with the same comment. */
827
+ const constraintPairs = (before, after) => {
828
+ const unused = new Set(before.keys());
829
+ const found = /* @__PURE__ */ new Map();
830
+ for (const sameComment of [true, false]) for (const [position, item] of after.entries()) {
831
+ if (found.has(position)) continue;
832
+ const match = [...unused].find((index) => constraintsEqual([before[index]], [item]) && (!sameComment || before[index].comment === item.comment));
833
+ if (match !== void 0) {
834
+ unused.delete(match);
835
+ found.set(position, before[match]);
836
+ }
837
+ }
838
+ return after.flatMap((item, position) => {
839
+ const previous = found.get(position);
840
+ return previous ? [[previous, item]] : [];
841
+ });
842
+ };
843
+ /**
844
+ * Comment changes of the managed objects that both models hold. `changes` are the changes of the
845
+ * migration: their table, column, sequence and enum renames pair objects across a rename. Added and
846
+ * removed objects have no change here.
847
+ */
848
+ const diffComments = (before, after, changes = []) => {
849
+ const found = [];
850
+ const compare = (previous, next, target) => {
851
+ if (previous !== next) found.push({
852
+ _tag: "CommentChanged",
853
+ ...next === void 0 ? {} : { after: next },
854
+ ...previous === void 0 ? {} : { before: previous },
855
+ target
856
+ });
857
+ };
858
+ const tables = /* @__PURE__ */ new Map();
859
+ const columns = /* @__PURE__ */ new Map();
860
+ const sequences = /* @__PURE__ */ new Map();
861
+ const enums = /* @__PURE__ */ new Map();
862
+ for (const change of changes) if (change._tag === "TableChanged" || change._tag === "TableRenamed") {
863
+ const key = tableKey(change.after.identity);
864
+ if (change._tag === "TableRenamed") tables.set(key, tableKey(change.before.identity));
865
+ for (const item of change.changes) if (item._tag === "ColumnRenamed") {
866
+ const renamed = columns.get(key) ?? /* @__PURE__ */ new Map();
867
+ renamed.set(item.after.key, item.before.key);
868
+ columns.set(key, renamed);
869
+ }
870
+ } else if (change._tag === "SequenceRenamed") sequences.set(tableKey(change.after.identity), tableKey(change.before.identity));
871
+ else if (change._tag === "EnumRenamed") enums.set(tableKey(change.after.identity), tableKey(change.before.identity));
872
+ for (const [old, item] of pairs(before.namespaces, after.namespaces, (item) => namespaceKey(item.identity))) compare(old.comment, item.comment, {
873
+ identity: item.identity,
874
+ kind: "namespace"
875
+ });
876
+ for (const [old, item] of pairs(before.extensions, after.extensions, (item) => item.name)) compare(old.comment, item.comment, {
877
+ kind: "extension",
878
+ name: item.name
879
+ });
880
+ const identityKey = (item) => tableKey(item.identity);
881
+ for (const [old, item] of pairs(before.enums, after.enums, identityKey, enums)) compare(old.comment, item.comment, {
882
+ identity: item.identity,
883
+ kind: "enum"
884
+ });
885
+ for (const [old, table] of pairs(before.tables, after.tables, identityKey, tables)) {
886
+ const identity = table.identity;
887
+ const constraints = (previous, next) => {
888
+ for (const [source, { comment, kind, properties }] of constraintPairs(previous, next)) compare(source.comment, comment, {
889
+ constraint: {
890
+ kind,
891
+ properties
892
+ },
893
+ kind: "constraint",
894
+ table: identity
895
+ });
896
+ };
897
+ compare(old.comment, table.comment, {
898
+ identity,
899
+ kind: "table"
900
+ });
901
+ for (const [source, column] of pairs(old.columns, table.columns, (item) => item.key, columns.get(tableKey(identity)))) {
902
+ compare(source.comment, column.comment, {
903
+ column: column.key,
904
+ kind: "column",
905
+ table: identity
906
+ });
907
+ constraints(source.constraints, column.constraints);
908
+ }
909
+ constraints(old.constraints, table.constraints);
910
+ for (const [source, index] of pairs(old.indexes, table.indexes, (item) => item.key)) compare(source.comment, index.comment, {
911
+ index: index.key,
912
+ kind: "index",
913
+ table: identity
914
+ });
915
+ }
916
+ for (const [old, view] of pairs(before.views, after.views, identityKey)) {
917
+ compare(old.comment, view.comment, {
918
+ identity: view.identity,
919
+ kind: "view"
920
+ });
921
+ const previous = new Map(Object.entries(old.columnComments ?? {}));
922
+ const next = new Map(Object.entries(view.columnComments ?? {}));
923
+ for (const column of /* @__PURE__ */ new Set([...next.keys(), ...previous.keys()])) compare(previous.get(column), next.get(column), {
924
+ column,
925
+ kind: "viewColumn",
926
+ view: view.identity
927
+ });
928
+ }
929
+ const renames = sequenceRenames(changes);
930
+ const oldTriggers = triggersAfterRenames(before, renames).keyed;
931
+ for (const trigger of after.triggers ?? []) {
932
+ const old = oldTriggers.get(triggerKey(trigger));
933
+ if (old) compare(old.trigger.comment, trigger.comment, {
934
+ kind: "trigger",
935
+ name: trigger.identity.name,
936
+ target: trigger.target
937
+ });
938
+ }
939
+ for (const [old, item] of pairs(before.sequences, after.sequences, identityKey, sequences)) compare(old.comment, item.comment, {
940
+ identity: item.identity,
941
+ kind: "sequence"
942
+ });
943
+ for (const [old, item] of pairs(before.functions, after.functions, functionKey)) compare(old.comment, item.comment, {
944
+ identity: item.identity,
945
+ kind: "function",
946
+ signature: item.signature
947
+ });
948
+ return found;
949
+ };
421
950
  /** Compare normalized relational models without parsing SQL or consulting a dialect. */
422
951
  const diffDatabases = (before, after) => Effect.gen(function* () {
423
952
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
@@ -441,6 +970,8 @@ const diffDatabases = (before, after) => Effect.gen(function* () {
441
970
  before: old
442
971
  });
443
972
  }
973
+ changes.push(...diffExtensions(before, after));
974
+ changes.push(...diffEnums(before, after));
444
975
  const previous = new Map(before.tables.map((table) => [tableKey(table.identity), table]));
445
976
  const next = new Map(after.tables.map((table) => [tableKey(table.identity), table]));
446
977
  for (const [key, table] of previous) if (!next.has(key)) changes.push({
@@ -484,26 +1015,10 @@ const diffDatabases = (before, after) => Effect.gen(function* () {
484
1015
  before: old
485
1016
  });
486
1017
  }
487
- const oldTriggers = new Map((before.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
488
- const newTriggers = new Map((after.triggers ?? []).map((trigger) => [tableKey(trigger.identity), trigger]));
489
- for (const [key, trigger] of oldTriggers) if (!newTriggers.has(key)) changes.push({
490
- _tag: "TriggerRemoved",
491
- trigger
492
- });
493
- for (const [key, trigger] of newTriggers) {
494
- const old = oldTriggers.get(key);
495
- if (!old) changes.push({
496
- _tag: "TriggerAdded",
497
- trigger
498
- });
499
- else if (tableKey(old.target) !== tableKey(trigger.target) || !schemaValueEqual(old.definition, trigger.definition)) changes.push({
500
- _tag: "TriggerChanged",
501
- after: trigger,
502
- before: old
503
- });
504
- }
1018
+ changes.push(...diffTriggers(before, after));
505
1019
  changes.push(...diffSequences(before, after));
506
1020
  changes.push(...diffFunctions(before, after));
1021
+ changes.push(...diffComments(before, after, changes));
507
1022
  return { changes };
508
1023
  });
509
1024
  // src/migration.ts
@@ -522,6 +1037,33 @@ const planDatabaseMigration = (diff) => ({
522
1037
  after: change.after,
523
1038
  before: change.before
524
1039
  };
1040
+ case "EnumAdded":
1041
+ case "EnumRemoved": return {
1042
+ _tag: change._tag === "EnumAdded" ? "CreateEnum" : "DropEnum",
1043
+ enum: change.enum
1044
+ };
1045
+ case "EnumRenamed":
1046
+ case "EnumChanged": return {
1047
+ _tag: change._tag === "EnumRenamed" ? "RenameEnum" : "AlterEnum",
1048
+ after: change.after,
1049
+ before: change.before,
1050
+ values: change.values
1051
+ };
1052
+ case "ExtensionAdded":
1053
+ case "ExtensionRemoved": return {
1054
+ _tag: change._tag === "ExtensionAdded" ? "CreateExtension" : "DropExtension",
1055
+ extension: change.extension
1056
+ };
1057
+ case "ExtensionVersionChanged":
1058
+ case "ExtensionSchemaChanged": return change._tag === "ExtensionVersionChanged" ? {
1059
+ _tag: "UpdateExtension",
1060
+ after: change.after,
1061
+ before: change.before
1062
+ } : {
1063
+ _tag: "MoveExtension",
1064
+ after: change.after,
1065
+ before: change.before
1066
+ };
525
1067
  case "FunctionAdded":
526
1068
  case "FunctionRemoved": return {
527
1069
  _tag: change._tag === "FunctionAdded" ? "CreateFunction" : "DropFunction",
@@ -582,14 +1124,79 @@ const planDatabaseMigration = (diff) => ({
582
1124
  before: change.before,
583
1125
  changes: change.changes
584
1126
  };
1127
+ case "CommentChanged": {
1128
+ const { _tag, ...comment } = change;
1129
+ return {
1130
+ _tag: "SetComment",
1131
+ ...comment
1132
+ };
1133
+ }
585
1134
  }
586
1135
  })
587
1136
  });
1137
+ /** Names a comment target of the `up` migration's after model as its before model names it. */
1138
+ const targetBeforeRenames = (up) => {
1139
+ const tables = /* @__PURE__ */ new Map();
1140
+ const columns = /* @__PURE__ */ new Map();
1141
+ const sequences = /* @__PURE__ */ new Map();
1142
+ const enums = /* @__PURE__ */ new Map();
1143
+ for (const step of up.procedures) if (step._tag === "AlterTable" || step._tag === "RenameTable") {
1144
+ const key = tableKey(step.after.identity);
1145
+ if (step._tag === "RenameTable") tables.set(key, step.before.identity);
1146
+ const renamed = /* @__PURE__ */ new Map();
1147
+ for (const change of step.changes) if (change._tag === "ColumnRenamed") renamed.set(change.after.key, change.before.key);
1148
+ columns.set(key, renamed);
1149
+ } else if (step._tag === "RenameSequence") sequences.set(tableKey(step.after.identity), step.before.identity);
1150
+ else if (step._tag === "RenameEnum") enums.set(tableKey(step.after.identity), step.before.identity);
1151
+ const renamed = (names, identity) => names.get(tableKey(identity)) ?? identity;
1152
+ return (target) => {
1153
+ switch (target.kind) {
1154
+ case "table": return {
1155
+ ...target,
1156
+ identity: renamed(tables, target.identity)
1157
+ };
1158
+ case "sequence": return {
1159
+ ...target,
1160
+ identity: renamed(sequences, target.identity)
1161
+ };
1162
+ case "enum": return {
1163
+ ...target,
1164
+ identity: renamed(enums, target.identity)
1165
+ };
1166
+ case "column": return {
1167
+ ...target,
1168
+ column: columns.get(tableKey(target.table))?.get(target.column) ?? target.column,
1169
+ table: renamed(tables, target.table)
1170
+ };
1171
+ case "index":
1172
+ case "constraint": return {
1173
+ ...target,
1174
+ table: renamed(tables, target.table)
1175
+ };
1176
+ case "trigger": return {
1177
+ ...target,
1178
+ target: renamed(tables, target.target)
1179
+ };
1180
+ default: return target;
1181
+ }
1182
+ };
1183
+ };
588
1184
  /** Reverse reviewed intent, retaining rename pairs and guarding newly added data. */
589
1185
  const planDownMigration = (up) => {
590
1186
  const procedures = [];
591
1187
  const dropGuards = [];
1188
+ const downTarget = targetBeforeRenames(up);
592
1189
  for (const step of up.procedures) switch (step._tag) {
1190
+ case "SetComment": {
1191
+ const { after, before, target } = step;
1192
+ procedures.push({
1193
+ _tag: "SetComment",
1194
+ ...before === void 0 ? {} : { after: before },
1195
+ ...after === void 0 ? {} : { before: after },
1196
+ target: downTarget(target)
1197
+ });
1198
+ break;
1199
+ }
593
1200
  case "DropTable": return `The up migration removed table ${step.table.name}.`;
594
1201
  case "CreateTable":
595
1202
  dropGuards.push({ table: step.table.identity });
@@ -598,6 +1205,31 @@ const planDownMigration = (up) => {
598
1205
  _tag: "DropTable"
599
1206
  });
600
1207
  break;
1208
+ case "CreateEnum":
1209
+ case "DropEnum":
1210
+ procedures.push({
1211
+ ...step,
1212
+ _tag: step._tag === "CreateEnum" ? "DropEnum" : "CreateEnum"
1213
+ });
1214
+ break;
1215
+ case "RenameEnum":
1216
+ case "AlterEnum":
1217
+ procedures.push({
1218
+ ...swap(step),
1219
+ values: step.values.map(swap)
1220
+ });
1221
+ break;
1222
+ case "CreateExtension":
1223
+ case "DropExtension":
1224
+ procedures.push({
1225
+ ...step,
1226
+ _tag: step._tag === "CreateExtension" ? "DropExtension" : "CreateExtension"
1227
+ });
1228
+ break;
1229
+ case "UpdateExtension": return `extension ${step.after.name} cannot be downgraded from ${step.after.version} to ${step.before.version ?? "an unpinned version"}`;
1230
+ case "MoveExtension":
1231
+ procedures.push(swap(step));
1232
+ break;
601
1233
  case "CreateFunction":
602
1234
  case "DropFunction":
603
1235
  procedures.push({
@@ -727,9 +1359,20 @@ const properties = (value, path) => {
727
1359
  record$1(value, path);
728
1360
  semanticValue(value, path);
729
1361
  };
1362
+ const commentText = (value, path) => {
1363
+ if (typeof value !== "string" || value === "") fail(path, "a non-empty string");
1364
+ };
1365
+ const comment = (item, path) => {
1366
+ if (Object.hasOwn(item, "comment")) commentText(item.comment, `${path}.comment`);
1367
+ };
730
1368
  const constraint = (value, path) => {
731
1369
  const item = record$1(value, path);
732
- fields(item, ["kind", "properties"], path);
1370
+ fields(item, [
1371
+ "kind",
1372
+ "properties",
1373
+ "comment"
1374
+ ], path);
1375
+ comment(item, path);
733
1376
  text(item.kind, `${path}.kind`);
734
1377
  properties(item.properties, `${path}.properties`);
735
1378
  };
@@ -739,8 +1382,10 @@ const column = (value, path) => {
739
1382
  "key",
740
1383
  "name",
741
1384
  "dataType",
742
- "constraints"
1385
+ "constraints",
1386
+ "comment"
743
1387
  ], path);
1388
+ comment(item, path);
744
1389
  text(item.key, `${path}.key`);
745
1390
  text(item.name, `${path}.name`);
746
1391
  semanticValue(item.dataType, `${path}.dataType`);
@@ -754,8 +1399,10 @@ const index = (value, path) => {
754
1399
  "unique",
755
1400
  "terms",
756
1401
  "where",
757
- "options"
1402
+ "options",
1403
+ "comment"
758
1404
  ], path);
1405
+ comment(item, path);
759
1406
  text(item.key, `${path}.key`);
760
1407
  text(item.name, `${path}.name`);
761
1408
  if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
@@ -778,11 +1425,15 @@ const trigger = (value, path) => {
778
1425
  fields(item, [
779
1426
  "identity",
780
1427
  "name",
1428
+ "scope",
781
1429
  "target",
782
- "definition"
1430
+ "definition",
1431
+ "comment"
783
1432
  ], path);
1433
+ comment(item, path);
784
1434
  identity(item.identity, `${path}.identity`);
785
1435
  text(item.name, `${path}.name`);
1436
+ if (Object.hasOwn(item, "scope") && item.scope !== "target") fail(`${path}.scope`, "\"target\"");
786
1437
  identity(item.target, `${path}.target`);
787
1438
  semanticValue(item.definition, `${path}.definition`);
788
1439
  };
@@ -792,8 +1443,10 @@ const sequence = (value, path) => {
792
1443
  "identity",
793
1444
  "name",
794
1445
  "definition",
795
- "owner"
1446
+ "owner",
1447
+ "comment"
796
1448
  ], path);
1449
+ comment(item, path);
797
1450
  identity(item.identity, `${path}.identity`);
798
1451
  text(item.name, `${path}.name`);
799
1452
  properties(item.definition, `${path}.definition`);
@@ -810,8 +1463,10 @@ const databaseFunction = (value, path) => {
810
1463
  "identity",
811
1464
  "name",
812
1465
  "signature",
813
- "definition"
1466
+ "definition",
1467
+ "comment"
814
1468
  ], path);
1469
+ comment(item, path);
815
1470
  identity(item.identity, `${path}.identity`);
816
1471
  text(item.name, `${path}.name`);
817
1472
  array(item.signature, `${path}.signature`, semanticValue);
@@ -824,8 +1479,16 @@ const view = (value, path) => {
824
1479
  "name",
825
1480
  "columns",
826
1481
  "query",
827
- "options"
1482
+ "options",
1483
+ "comment",
1484
+ "columnComments"
828
1485
  ], path);
1486
+ comment(item, path);
1487
+ if (Object.hasOwn(item, "columnComments")) {
1488
+ const columns = record$1(item.columnComments, `${path}.columnComments`);
1489
+ for (const key of Reflect.ownKeys(columns)) if (typeof key !== "string") fail(`${path}.columnComments`, "string property keys");
1490
+ else commentText(columns[key], `${path}.columnComments.${key}`);
1491
+ }
829
1492
  identity(item.identity, `${path}.identity`);
830
1493
  text(item.name, `${path}.name`);
831
1494
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
@@ -837,8 +1500,10 @@ const namespace = (value, path) => {
837
1500
  fields(item, [
838
1501
  "identity",
839
1502
  "name",
840
- "options"
1503
+ "options",
1504
+ "comment"
841
1505
  ], path);
1506
+ comment(item, path);
842
1507
  const identity = record$1(item.identity, `${path}.identity`);
843
1508
  fields(identity, ["catalog", "name"], `${path}.identity`);
844
1509
  text(identity.name, `${path}.identity.name`);
@@ -854,8 +1519,10 @@ const table = (value, path) => {
854
1519
  "columns",
855
1520
  "constraints",
856
1521
  "options",
857
- "indexes"
1522
+ "indexes",
1523
+ "comment"
858
1524
  ], path);
1525
+ comment(item, path);
859
1526
  identity(item.identity, `${path}.identity`);
860
1527
  text(item.name, `${path}.name`);
861
1528
  array(item.columns, `${path}.columns`, column);
@@ -863,9 +1530,46 @@ const table = (value, path) => {
863
1530
  array(item.constraints, `${path}.constraints`, constraint);
864
1531
  properties(item.options, `${path}.options`);
865
1532
  };
1533
+ const extension = (value, path) => {
1534
+ const item = record$1(value, path);
1535
+ fields(item, [
1536
+ "name",
1537
+ "schema",
1538
+ "version",
1539
+ "comment"
1540
+ ], path);
1541
+ comment(item, path);
1542
+ text(item.name, `${path}.name`);
1543
+ for (const key of ["schema", "version"]) if (Object.hasOwn(item, key)) text(item[key], `${path}.${key}`);
1544
+ };
1545
+ const databaseEnum = (value, path) => {
1546
+ const item = record$1(value, path);
1547
+ fields(item, [
1548
+ "identity",
1549
+ "name",
1550
+ "values",
1551
+ "comment"
1552
+ ], path);
1553
+ comment(item, path);
1554
+ identity(item.identity, `${path}.identity`);
1555
+ text(item.name, `${path}.name`);
1556
+ const labels = /* @__PURE__ */ new Set();
1557
+ array(item.values, `${path}.values`, (label, at) => {
1558
+ text(label, at);
1559
+ if (labels.has(label)) fail(at, "a distinct label");
1560
+ labels.add(label);
1561
+ });
1562
+ };
866
1563
  const externals = (value, path) => {
867
1564
  const item = record$1(value, path);
868
- fields(item, ["functions", "tables"], path);
1565
+ fields(item, [
1566
+ "enums",
1567
+ "extensions",
1568
+ "functions",
1569
+ "tables"
1570
+ ], path);
1571
+ if (Object.hasOwn(item, "enums")) array(item.enums, `${path}.enums`, databaseEnum);
1572
+ if (Object.hasOwn(item, "extensions")) array(item.extensions, `${path}.extensions`, extension);
869
1573
  if (Object.hasOwn(item, "functions")) array(item.functions, `${path}.functions`, databaseFunction);
870
1574
  if (Object.hasOwn(item, "tables")) array(item.tables, `${path}.tables`, table);
871
1575
  };
@@ -884,8 +1588,12 @@ const decodeDatabaseSchema = (value) => Effect.try({
884
1588
  "triggers",
885
1589
  "sequences",
886
1590
  "functions",
887
- "externals"
1591
+ "externals",
1592
+ "extensions",
1593
+ "enums"
888
1594
  ], "$database");
1595
+ if (Object.hasOwn(database, "enums")) array(database.enums, "$database.enums", databaseEnum);
1596
+ if (Object.hasOwn(database, "extensions")) array(database.extensions, "$database.extensions", extension);
889
1597
  if (Object.hasOwn(database, "externals")) externals(database.externals, "$database.externals");
890
1598
  if (Object.hasOwn(database, "functions")) array(database.functions, "$database.functions", databaseFunction);
891
1599
  if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
@@ -897,6 +1605,21 @@ const decodeDatabaseSchema = (value) => Effect.try({
897
1605
  }
898
1606
  });
899
1607
  // src/executor.ts
1608
+ const omissionOrder = {
1609
+ dependent: 2,
1610
+ unmanaged: 1,
1611
+ unsupported: 0
1612
+ };
1613
+ const compareCodePoints = (left, right) => {
1614
+ const a = Array.from(left, (character) => character.codePointAt(0));
1615
+ const b = Array.from(right, (character) => character.codePointAt(0));
1616
+ const index = a.findIndex((point, position) => point !== b[position]);
1617
+ return index < 0 ? a.length - b.length : b[index] === void 0 ? 1 : a[index] - b[index];
1618
+ };
1619
+ /** One line per omission, ordered by category (unsupported, unmanaged, dependent), then name. */
1620
+ const formatExtractOmissions = (omitted) => [...omitted].sort((left, right) => omissionOrder[left.category] - omissionOrder[right.category] || compareCodePoints(left.name, right.name)).map(({ category, detail, kind, name }) => {
1621
+ return `${category} ${kind} ${name}${detail === void 0 ? "" : ` (${category === "dependent" ? "depends on " : ""}${detail})`}`;
1622
+ });
900
1623
  const checksumPattern = /^[a-f0-9]{64}$/;
901
1624
  /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
902
1625
  const migrationRun = (direction, migrations, checkpoint, sha256) => {
@@ -931,7 +1654,49 @@ const renamedColumnId = (source, target, column) => JSON.stringify([
931
1654
  column
932
1655
  ]);
933
1656
  const columnId = (change, column) => change._tag === "TableRenamed" ? renamedColumnId(change.before.identity, change.after.identity, column) : idFor(change.table, column);
1657
+ const enumId = (identity) => JSON.stringify(["enum", tableKey(identity)]);
1658
+ const valueId = (source, target, value) => JSON.stringify([
1659
+ "enum",
1660
+ tableKey(source),
1661
+ tableKey(target),
1662
+ value
1663
+ ]);
1664
+ const enumLabel = (identity) => [
1665
+ identity.catalog,
1666
+ identity.schema,
1667
+ identity.name
1668
+ ].filter((part) => part !== void 0).join(".");
1669
+ const quoted = (value) => `'${JSON.stringify(value).slice(1, -1)}'`;
1670
+ const missingFrom = (values, other) => {
1671
+ const present = new Set(other);
1672
+ return values.filter((value) => !present.has(value));
1673
+ };
1674
+ const enumQuestions = (change, diff) => {
1675
+ if ("enum" in change) {
1676
+ if (change._tag === "EnumAdded") return [];
1677
+ const identity = change.enum.identity;
1678
+ 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] : []);
1679
+ return candidates.length ? [{
1680
+ candidates,
1681
+ enum: identity,
1682
+ id: enumId(identity),
1683
+ question: `Drop type ${enumLabel(identity)}, or rename it to an added type?`,
1684
+ resolution: { action: "pending" }
1685
+ }] : [];
1686
+ }
1687
+ const { after, before } = change;
1688
+ const candidates = missingFrom(after.values, before.values);
1689
+ return candidates.length ? missingFrom(before.values, after.values).map((value) => ({
1690
+ candidates,
1691
+ enum: before.identity,
1692
+ id: valueId(before.identity, after.identity, value),
1693
+ question: `Rename value ${quoted(value)} of ${enumLabel(before.identity)} to an added value?`,
1694
+ resolution: { action: "pending" },
1695
+ value
1696
+ })) : [];
1697
+ };
934
1698
  const questions = (diff) => diff.changes.flatMap((change) => {
1699
+ if (change._tag === "EnumAdded" || change._tag === "EnumRemoved" || change._tag === "EnumRenamed" || change._tag === "EnumChanged") return enumQuestions(change, diff);
935
1700
  if (change._tag === "TableRemoved") {
936
1701
  const candidates = diff.changes.flatMap((item) => item._tag === "TableAdded" && item.table.catalog === change.table.catalog && item.table.schema === change.table.schema ? [item.table.name] : []);
937
1702
  return [{
@@ -971,23 +1736,26 @@ const readAnswers = (pending, inputs, allowPending) => Effect.gen(function* () {
971
1736
  if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
972
1737
  const question = expected.get(input.id);
973
1738
  if (!question || answers.has(input.id)) return yield* fail(`Unknown or duplicate decision: ${input.id}`);
974
- if (!equal(input.table, question.table) || input.column !== question.column) return yield* fail(`Decision identity changed: ${input.id}`);
1739
+ 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}`);
975
1740
  const resolution = input.resolution;
976
1741
  if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
977
1742
  answers.set(input.id, question);
978
1743
  continue;
979
1744
  }
980
1745
  if (!record(resolution) || resolution.action === "pending") return yield* fail(`Unresolved decision: ${question.question}`);
981
- if ((resolution.action === "drop" || resolution.action === "drop_if_empty") && Object.keys(resolution).length === 1) answers.set(input.id, {
1746
+ if ((resolution.action === "drop" || resolution.action === "drop_if_empty" && !("enum" in question)) && Object.keys(resolution).length === 1) answers.set(input.id, {
982
1747
  ...question,
983
1748
  resolution: { action: resolution.action }
984
1749
  });
985
1750
  else if (resolution.action === "rename" && Object.keys(resolution).length === 2 && typeof resolution.target === "string" && question.candidates.includes(resolution.target)) {
986
- const target = question.column === void 0 ? idFor({
1751
+ const [kind, target] = "enum" in question ? question.value === void 0 ? ["enums", enumId({
1752
+ ...question.enum,
1753
+ name: resolution.target
1754
+ })] : ["values", valueId(question.enum, question.enum, resolution.target)] : question.column === void 0 ? ["tables", idFor({
987
1755
  ...question.table,
988
1756
  name: resolution.target
989
- }) : idFor(question.table, resolution.target);
990
- if (targets.has(target)) return yield* fail(`Multiple source ${question.column === void 0 ? "tables" : "columns"} map to ${resolution.target}.`);
1757
+ })] : ["columns", idFor(question.table, resolution.target)];
1758
+ if (targets.has(target)) return yield* fail(`Multiple source ${kind} map to ${resolution.target}.`);
991
1759
  targets.add(target);
992
1760
  answers.set(input.id, {
993
1761
  ...question,
@@ -1002,18 +1770,18 @@ const readAnswers = (pending, inputs, allowPending) => Effect.gen(function* () {
1002
1770
  return answers;
1003
1771
  });
1004
1772
  const expandRenames = (diff, answers) => {
1005
- const additions = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1773
+ const tables = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1774
+ const enums = new Map(diff.changes.flatMap((item) => "enum" in item && item._tag === "EnumAdded" ? [[tableKey(item.enum.identity), item]] : []));
1006
1775
  const renames = [];
1007
- for (const source of diff.changes) {
1008
- if (source._tag !== "TableRemoved") continue;
1776
+ const consumed = /* @__PURE__ */ new Set();
1777
+ for (const source of diff.changes) if (source._tag === "TableRemoved") {
1009
1778
  const choice = answers.get(idFor(source.table))?.resolution;
1010
1779
  if (choice?.action !== "rename") continue;
1011
- const key = tableKey({
1780
+ const target = tables.get(tableKey({
1012
1781
  ...source.table,
1013
1782
  name: choice.target
1014
- });
1015
- const target = additions.get(key);
1016
- additions.delete(key);
1783
+ }));
1784
+ consumed.add(source).add(target);
1017
1785
  renames.push({
1018
1786
  _tag: "TableRenamed",
1019
1787
  after: target.definition,
@@ -1021,15 +1789,41 @@ const expandRenames = (diff, answers) => {
1021
1789
  changes: compareTable(source.definition, target.definition),
1022
1790
  table: source.table
1023
1791
  });
1792
+ } else if (source._tag === "EnumRemoved") {
1793
+ const identity = source.enum.identity;
1794
+ const choice = answers.get(enumId(identity))?.resolution;
1795
+ if (choice?.action !== "rename") continue;
1796
+ const target = enums.get(tableKey({
1797
+ ...identity,
1798
+ name: choice.target
1799
+ }));
1800
+ consumed.add(source).add(target);
1801
+ renames.push({
1802
+ _tag: "EnumRenamed",
1803
+ after: target.enum,
1804
+ before: source.enum,
1805
+ values: []
1806
+ });
1024
1807
  }
1025
1808
  return {
1026
- diff: { changes: [...diff.changes.filter((item) => {
1027
- if (item._tag === "TableAdded") return additions.has(tableKey(item.table));
1028
- return item._tag !== "TableRemoved" || answers.get(idFor(item.table))?.resolution.action !== "rename";
1029
- }), ...renames] },
1809
+ diff: { changes: [...diff.changes.filter((item) => !consumed.has(item)), ...renames] },
1030
1810
  nested: questions({ changes: renames })
1031
1811
  };
1032
1812
  };
1813
+ const issuedForPairing = (pending, input) => pending.decisions.some((parent) => {
1814
+ if ("enum" in parent) {
1815
+ const value = input.value;
1816
+ return parent.value === void 0 && typeof value === "string" && equal(parent.enum, input.enum) && parent.candidates.some((name) => input.id === valueId(parent.enum, {
1817
+ ...parent.enum,
1818
+ name
1819
+ }, value));
1820
+ }
1821
+ const column = input.column;
1822
+ return parent.column === void 0 && typeof column === "string" && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
1823
+ ...parent.table,
1824
+ name
1825
+ }, column));
1826
+ });
1033
1827
  const reviewAnswers = (pending, diff, inputs, merging) => Effect.gen(function* () {
1034
1828
  const rootIds = new Set(pending.decisions.map((item) => item.id));
1035
1829
  const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
@@ -1040,25 +1834,40 @@ const reviewAnswers = (pending, diff, inputs, merging) => Effect.gen(function* (
1040
1834
  decisions: [...rootAnswers.values(), ...expanded.nested]
1041
1835
  };
1042
1836
  const expected = new Set(review.decisions.map((item) => item.id));
1043
- const current = inputs.filter((input) => {
1044
- if (!merging || !record(input) || typeof input.column !== "string" || typeof input.id !== "string" || expected.has(input.id)) return true;
1045
- const column = input.column;
1046
- return !pending.decisions.some((parent) => parent.column === void 0 && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
1047
- ...parent.table,
1048
- name
1049
- }, column)));
1050
- });
1837
+ const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
1051
1838
  const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
1052
1839
  const missing = expanded.nested.filter((item) => !ids.has(item.id));
1053
- if (!merging && missing.length) return yield* Effect.fail(new MigrationDecisionError({
1054
- message: "Table rename requires column decisions. Run --merge-decisions to review them.",
1055
- pending: review
1056
- }));
1840
+ if (!merging && missing.length) {
1841
+ const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : "Table rename requires column decisions";
1842
+ return yield* Effect.fail(new MigrationDecisionError({
1843
+ message: `${required}. Run --merge-decisions to review them.`,
1844
+ pending: review
1845
+ }));
1846
+ }
1057
1847
  return {
1058
1848
  answers: yield* readAnswers(review, [...current, ...missing], merging),
1059
1849
  diff: expanded.diff
1060
1850
  };
1061
1851
  });
1852
+ /** The enum and value renames that the reviewer accepted. */
1853
+ const enumRenames = (diff, answers) => {
1854
+ const enums = /* @__PURE__ */ new Map();
1855
+ const values = /* @__PURE__ */ new Map();
1856
+ for (const change of diff.changes) {
1857
+ if (change._tag !== "EnumRenamed" && change._tag !== "EnumChanged") continue;
1858
+ const { after, before } = change;
1859
+ const key = tableKey(before.identity);
1860
+ if (change._tag === "EnumRenamed") enums.set(key, after.identity);
1861
+ values.set(key, new Map(before.values.flatMap((value) => {
1862
+ const choice = answers.get(valueId(before.identity, after.identity, value))?.resolution;
1863
+ return choice?.action === "rename" ? [[value, choice.target]] : [];
1864
+ })));
1865
+ }
1866
+ return {
1867
+ enums,
1868
+ values
1869
+ };
1870
+ };
1062
1871
  /** Refresh the questions and snapshots, carrying forward applicable reviewed choices. */
1063
1872
  const mergeMigrationDecisions = (fresh, previous) => Effect.gen(function* () {
1064
1873
  if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* Effect.fail(new MigrationDecisionError({
@@ -1136,7 +1945,7 @@ const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(functi
1136
1945
  renamedTargets.add(afterColumn.key);
1137
1946
  const fields = [];
1138
1947
  if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
1139
- if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1948
+ if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1140
1949
  changes.push({
1141
1950
  _tag: "ColumnRenamed",
1142
1951
  after: afterColumn,
@@ -1149,8 +1958,18 @@ const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(functi
1149
1958
  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"))]
1150
1959
  };
1151
1960
  });
1961
+ const renames = sequenceRenames(changes);
1962
+ const kept = changes.filter((change) => !/^(Comment|Enum|Sequence|Trigger)/.test(change._tag));
1963
+ const leading = (change) => /^(Namespace|Extension)/.test(change._tag);
1964
+ const withRenames = [
1965
+ ...kept.filter(leading),
1966
+ ...diffEnums(before, after, enumRenames(reviewed.diff, answers)),
1967
+ ...kept.filter((change) => !leading(change)),
1968
+ ...diffTriggers(before, after, renames),
1969
+ ...diffSequences(before, after, renames)
1970
+ ];
1152
1971
  const resolved = {
1153
- changes: [...changes.filter((change) => !change._tag.startsWith("Sequence")), ...diffSequences(before, after, sequenceRenames(changes))],
1972
+ changes: [...withRenames, ...diffComments(before, after, withRenames)],
1154
1973
  ...dropGuards.length ? { dropGuards } : {}
1155
1974
  };
1156
1975
  return {
@@ -1378,4 +2197,4 @@ const decodeGeneratorPlugin = (value) => validate(() => {
1378
2197
  })
1379
2198
  };
1380
2199
  }, "invalid-plugin", "generator");
1381
- export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, artifactPathSchema, checkManagedScope, codegenDiagnosticSchema, compareTable, completionCandidates, continuesRun, declarationAt, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffDatabases, diffFunctions, diffSequences, externalObjects, functionKey, functionLabel, generatedFileHeader, mergeMigrationDecisions, migrationRun, nameSpan, namespaceKey, namespaceOf, nextMigration, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, referencesTo, relationIdentitySchema, renameSiteAt, renameSpans, resolveMigrationDecisions, schemaValueEqual, sequenceRenames, tableKey, validateApplicationCompatibility, validateDatabase };
2200
+ export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, artifactPathSchema, checkManagedScope, codegenDiagnosticSchema, commentObjects, compareTable, completionCandidates, constraintsEqual, continuesRun, declarationAt, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffComments, diffDatabases, diffEnums, diffFunctions, diffSequences, diffTriggers, enumObjects, extensionObjects, externalObjects, formatExtractOmissions, functionKey, functionLabel, generatedFileHeader, mergeMigrationDecisions, migrationRun, nameSpan, namespaceKey, namespaceOf, nextMigration, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, referencesTo, relationIdentitySchema, renameSiteAt, renameSpans, resolveMigrationDecisions, schemaValueEqual, sequenceRenames, tableKey, triggerKey, validateApplicationCompatibility, validateDatabase };