@uncutsql/core 0.3.0 → 0.5.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({
@@ -690,6 +1322,54 @@ function swap(value) {
690
1322
  before: value.after
691
1323
  };
692
1324
  }
1325
+ // src/dialect.ts
1326
+ var StatementEditError = class extends effect.Data.TaggedError("StatementEditError") {};
1327
+ // src/structure.ts
1328
+ const changesOf = (before, after, keyOf) => {
1329
+ const known = new Map((before ?? []).map((item) => [keyOf(item), item]));
1330
+ return (after ?? []).flatMap((external) => {
1331
+ const key = keyOf(external);
1332
+ const old = known.get(key);
1333
+ if (old !== void 0 && schemaValueEqual(old, external)) return [];
1334
+ return [{
1335
+ change: old === void 0 ? "new" : "changed",
1336
+ external,
1337
+ key
1338
+ }];
1339
+ });
1340
+ };
1341
+ /**
1342
+ * The externals that are new or changed from `before` to `after`: enums, extensions, functions,
1343
+ * then tables, each in the order of `after`. An external is changed when its declaration is not
1344
+ * structurally equal. Removed externals are not listed.
1345
+ */
1346
+ const changedExternals = (before, after) => [
1347
+ ...changesOf(before?.enums, after?.enums, (item) => tableKey(item.identity)).map((item) => ({
1348
+ ...item,
1349
+ kind: "enum"
1350
+ })),
1351
+ ...changesOf(before?.extensions, after?.extensions, (item) => item.name).map((item) => ({
1352
+ ...item,
1353
+ kind: "extension"
1354
+ })),
1355
+ ...changesOf(before?.functions, after?.functions, functionKey).map((item) => ({
1356
+ ...item,
1357
+ kind: "function"
1358
+ })),
1359
+ ...changesOf(before?.tables, after?.tables, (item) => tableKey(item.identity)).map((item) => ({
1360
+ ...item,
1361
+ kind: "table"
1362
+ }))
1363
+ ];
1364
+ /**
1365
+ * Structural comparison of two models (ADR 0036 Decision 5): `diffDatabases` after the
1366
+ * dialect's `normalizeSchema`, applied to both sides, or the identity when absent. The two
1367
+ * structures are equal when the result has no change.
1368
+ */
1369
+ const diffStructures = (dialect, a, b) => {
1370
+ const normal = (schema) => dialect.normalizeSchema?.(schema) ?? effect.Effect.succeed(schema);
1371
+ return effect.Effect.flatMap(effect.Effect.all([normal(a), normal(b)]), ([before, after]) => diffDatabases(before, after));
1372
+ };
693
1373
  // src/decode.ts
694
1374
  var SchemaModelError = class extends effect.Data.TaggedError("SchemaModelError") {};
695
1375
  const fail = (path, expected) => {
@@ -728,9 +1408,20 @@ const properties = (value, path) => {
728
1408
  record$1(value, path);
729
1409
  semanticValue(value, path);
730
1410
  };
1411
+ const commentText = (value, path) => {
1412
+ if (typeof value !== "string" || value === "") fail(path, "a non-empty string");
1413
+ };
1414
+ const comment = (item, path) => {
1415
+ if (Object.hasOwn(item, "comment")) commentText(item.comment, `${path}.comment`);
1416
+ };
731
1417
  const constraint = (value, path) => {
732
1418
  const item = record$1(value, path);
733
- fields(item, ["kind", "properties"], path);
1419
+ fields(item, [
1420
+ "kind",
1421
+ "properties",
1422
+ "comment"
1423
+ ], path);
1424
+ comment(item, path);
734
1425
  text(item.kind, `${path}.kind`);
735
1426
  properties(item.properties, `${path}.properties`);
736
1427
  };
@@ -740,8 +1431,10 @@ const column = (value, path) => {
740
1431
  "key",
741
1432
  "name",
742
1433
  "dataType",
743
- "constraints"
1434
+ "constraints",
1435
+ "comment"
744
1436
  ], path);
1437
+ comment(item, path);
745
1438
  text(item.key, `${path}.key`);
746
1439
  text(item.name, `${path}.name`);
747
1440
  semanticValue(item.dataType, `${path}.dataType`);
@@ -755,8 +1448,10 @@ const index = (value, path) => {
755
1448
  "unique",
756
1449
  "terms",
757
1450
  "where",
758
- "options"
1451
+ "options",
1452
+ "comment"
759
1453
  ], path);
1454
+ comment(item, path);
760
1455
  text(item.key, `${path}.key`);
761
1456
  text(item.name, `${path}.name`);
762
1457
  if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
@@ -779,11 +1474,15 @@ const trigger = (value, path) => {
779
1474
  fields(item, [
780
1475
  "identity",
781
1476
  "name",
1477
+ "scope",
782
1478
  "target",
783
- "definition"
1479
+ "definition",
1480
+ "comment"
784
1481
  ], path);
1482
+ comment(item, path);
785
1483
  identity(item.identity, `${path}.identity`);
786
1484
  text(item.name, `${path}.name`);
1485
+ if (Object.hasOwn(item, "scope") && item.scope !== "target") fail(`${path}.scope`, "\"target\"");
787
1486
  identity(item.target, `${path}.target`);
788
1487
  semanticValue(item.definition, `${path}.definition`);
789
1488
  };
@@ -793,8 +1492,10 @@ const sequence = (value, path) => {
793
1492
  "identity",
794
1493
  "name",
795
1494
  "definition",
796
- "owner"
1495
+ "owner",
1496
+ "comment"
797
1497
  ], path);
1498
+ comment(item, path);
798
1499
  identity(item.identity, `${path}.identity`);
799
1500
  text(item.name, `${path}.name`);
800
1501
  properties(item.definition, `${path}.definition`);
@@ -811,8 +1512,10 @@ const databaseFunction = (value, path) => {
811
1512
  "identity",
812
1513
  "name",
813
1514
  "signature",
814
- "definition"
1515
+ "definition",
1516
+ "comment"
815
1517
  ], path);
1518
+ comment(item, path);
816
1519
  identity(item.identity, `${path}.identity`);
817
1520
  text(item.name, `${path}.name`);
818
1521
  array(item.signature, `${path}.signature`, semanticValue);
@@ -825,8 +1528,16 @@ const view = (value, path) => {
825
1528
  "name",
826
1529
  "columns",
827
1530
  "query",
828
- "options"
1531
+ "options",
1532
+ "comment",
1533
+ "columnComments"
829
1534
  ], path);
1535
+ comment(item, path);
1536
+ if (Object.hasOwn(item, "columnComments")) {
1537
+ const columns = record$1(item.columnComments, `${path}.columnComments`);
1538
+ for (const key of Reflect.ownKeys(columns)) if (typeof key !== "string") fail(`${path}.columnComments`, "string property keys");
1539
+ else commentText(columns[key], `${path}.columnComments.${key}`);
1540
+ }
830
1541
  identity(item.identity, `${path}.identity`);
831
1542
  text(item.name, `${path}.name`);
832
1543
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
@@ -838,8 +1549,10 @@ const namespace = (value, path) => {
838
1549
  fields(item, [
839
1550
  "identity",
840
1551
  "name",
841
- "options"
1552
+ "options",
1553
+ "comment"
842
1554
  ], path);
1555
+ comment(item, path);
843
1556
  const identity = record$1(item.identity, `${path}.identity`);
844
1557
  fields(identity, ["catalog", "name"], `${path}.identity`);
845
1558
  text(identity.name, `${path}.identity.name`);
@@ -855,8 +1568,10 @@ const table = (value, path) => {
855
1568
  "columns",
856
1569
  "constraints",
857
1570
  "options",
858
- "indexes"
1571
+ "indexes",
1572
+ "comment"
859
1573
  ], path);
1574
+ comment(item, path);
860
1575
  identity(item.identity, `${path}.identity`);
861
1576
  text(item.name, `${path}.name`);
862
1577
  array(item.columns, `${path}.columns`, column);
@@ -864,9 +1579,46 @@ const table = (value, path) => {
864
1579
  array(item.constraints, `${path}.constraints`, constraint);
865
1580
  properties(item.options, `${path}.options`);
866
1581
  };
1582
+ const extension = (value, path) => {
1583
+ const item = record$1(value, path);
1584
+ fields(item, [
1585
+ "name",
1586
+ "schema",
1587
+ "version",
1588
+ "comment"
1589
+ ], path);
1590
+ comment(item, path);
1591
+ text(item.name, `${path}.name`);
1592
+ for (const key of ["schema", "version"]) if (Object.hasOwn(item, key)) text(item[key], `${path}.${key}`);
1593
+ };
1594
+ const databaseEnum = (value, path) => {
1595
+ const item = record$1(value, path);
1596
+ fields(item, [
1597
+ "identity",
1598
+ "name",
1599
+ "values",
1600
+ "comment"
1601
+ ], path);
1602
+ comment(item, path);
1603
+ identity(item.identity, `${path}.identity`);
1604
+ text(item.name, `${path}.name`);
1605
+ const labels = /* @__PURE__ */ new Set();
1606
+ array(item.values, `${path}.values`, (label, at) => {
1607
+ text(label, at);
1608
+ if (labels.has(label)) fail(at, "a distinct label");
1609
+ labels.add(label);
1610
+ });
1611
+ };
867
1612
  const externals = (value, path) => {
868
1613
  const item = record$1(value, path);
869
- fields(item, ["functions", "tables"], path);
1614
+ fields(item, [
1615
+ "enums",
1616
+ "extensions",
1617
+ "functions",
1618
+ "tables"
1619
+ ], path);
1620
+ if (Object.hasOwn(item, "enums")) array(item.enums, `${path}.enums`, databaseEnum);
1621
+ if (Object.hasOwn(item, "extensions")) array(item.extensions, `${path}.extensions`, extension);
870
1622
  if (Object.hasOwn(item, "functions")) array(item.functions, `${path}.functions`, databaseFunction);
871
1623
  if (Object.hasOwn(item, "tables")) array(item.tables, `${path}.tables`, table);
872
1624
  };
@@ -885,8 +1637,12 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
885
1637
  "triggers",
886
1638
  "sequences",
887
1639
  "functions",
888
- "externals"
1640
+ "externals",
1641
+ "extensions",
1642
+ "enums"
889
1643
  ], "$database");
1644
+ if (Object.hasOwn(database, "enums")) array(database.enums, "$database.enums", databaseEnum);
1645
+ if (Object.hasOwn(database, "extensions")) array(database.extensions, "$database.extensions", extension);
890
1646
  if (Object.hasOwn(database, "externals")) externals(database.externals, "$database.externals");
891
1647
  if (Object.hasOwn(database, "functions")) array(database.functions, "$database.functions", databaseFunction);
892
1648
  if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
@@ -898,6 +1654,21 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
898
1654
  }
899
1655
  });
900
1656
  // src/executor.ts
1657
+ const omissionOrder = {
1658
+ dependent: 2,
1659
+ unmanaged: 1,
1660
+ unsupported: 0
1661
+ };
1662
+ const compareCodePoints = (left, right) => {
1663
+ const a = Array.from(left, (character) => character.codePointAt(0));
1664
+ const b = Array.from(right, (character) => character.codePointAt(0));
1665
+ const index = a.findIndex((point, position) => point !== b[position]);
1666
+ return index < 0 ? a.length - b.length : b[index] === void 0 ? 1 : a[index] - b[index];
1667
+ };
1668
+ /** One line per omission, ordered by category (unsupported, unmanaged, dependent), then name. */
1669
+ const formatExtractOmissions = (omitted) => [...omitted].sort((left, right) => omissionOrder[left.category] - omissionOrder[right.category] || compareCodePoints(left.name, right.name)).map(({ category, detail, kind, name }) => {
1670
+ return `${category} ${kind} ${name}${detail === void 0 ? "" : ` (${category === "dependent" ? "depends on " : ""}${detail})`}`;
1671
+ });
901
1672
  const checksumPattern = /^[a-f0-9]{64}$/;
902
1673
  /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
903
1674
  const migrationRun = (direction, migrations, checkpoint, sha256) => {
@@ -932,7 +1703,49 @@ const renamedColumnId = (source, target, column) => JSON.stringify([
932
1703
  column
933
1704
  ]);
934
1705
  const columnId = (change, column) => change._tag === "TableRenamed" ? renamedColumnId(change.before.identity, change.after.identity, column) : idFor(change.table, column);
1706
+ const enumId = (identity) => JSON.stringify(["enum", tableKey(identity)]);
1707
+ const valueId = (source, target, value) => JSON.stringify([
1708
+ "enum",
1709
+ tableKey(source),
1710
+ tableKey(target),
1711
+ value
1712
+ ]);
1713
+ const enumLabel = (identity) => [
1714
+ identity.catalog,
1715
+ identity.schema,
1716
+ identity.name
1717
+ ].filter((part) => part !== void 0).join(".");
1718
+ const quoted = (value) => `'${JSON.stringify(value).slice(1, -1)}'`;
1719
+ const missingFrom = (values, other) => {
1720
+ const present = new Set(other);
1721
+ return values.filter((value) => !present.has(value));
1722
+ };
1723
+ const enumQuestions = (change, diff) => {
1724
+ if ("enum" in change) {
1725
+ if (change._tag === "EnumAdded") return [];
1726
+ const identity = change.enum.identity;
1727
+ 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] : []);
1728
+ return candidates.length ? [{
1729
+ candidates,
1730
+ enum: identity,
1731
+ id: enumId(identity),
1732
+ question: `Drop type ${enumLabel(identity)}, or rename it to an added type?`,
1733
+ resolution: { action: "pending" }
1734
+ }] : [];
1735
+ }
1736
+ const { after, before } = change;
1737
+ const candidates = missingFrom(after.values, before.values);
1738
+ return candidates.length ? missingFrom(before.values, after.values).map((value) => ({
1739
+ candidates,
1740
+ enum: before.identity,
1741
+ id: valueId(before.identity, after.identity, value),
1742
+ question: `Rename value ${quoted(value)} of ${enumLabel(before.identity)} to an added value?`,
1743
+ resolution: { action: "pending" },
1744
+ value
1745
+ })) : [];
1746
+ };
935
1747
  const questions = (diff) => diff.changes.flatMap((change) => {
1748
+ if (change._tag === "EnumAdded" || change._tag === "EnumRemoved" || change._tag === "EnumRenamed" || change._tag === "EnumChanged") return enumQuestions(change, diff);
936
1749
  if (change._tag === "TableRemoved") {
937
1750
  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
1751
  return [{
@@ -972,23 +1785,26 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
972
1785
  if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
973
1786
  const question = expected.get(input.id);
974
1787
  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}`);
1788
+ 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
1789
  const resolution = input.resolution;
977
1790
  if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
978
1791
  answers.set(input.id, question);
979
1792
  continue;
980
1793
  }
981
1794
  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, {
1795
+ if ((resolution.action === "drop" || resolution.action === "drop_if_empty" && !("enum" in question)) && Object.keys(resolution).length === 1) answers.set(input.id, {
983
1796
  ...question,
984
1797
  resolution: { action: resolution.action }
985
1798
  });
986
1799
  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({
1800
+ const [kind, target] = "enum" in question ? question.value === void 0 ? ["enums", enumId({
1801
+ ...question.enum,
1802
+ name: resolution.target
1803
+ })] : ["values", valueId(question.enum, question.enum, resolution.target)] : question.column === void 0 ? ["tables", idFor({
988
1804
  ...question.table,
989
1805
  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}.`);
1806
+ })] : ["columns", idFor(question.table, resolution.target)];
1807
+ if (targets.has(target)) return yield* fail(`Multiple source ${kind} map to ${resolution.target}.`);
992
1808
  targets.add(target);
993
1809
  answers.set(input.id, {
994
1810
  ...question,
@@ -1003,18 +1819,18 @@ const readAnswers = (pending, inputs, allowPending) => effect.Effect.gen(functio
1003
1819
  return answers;
1004
1820
  });
1005
1821
  const expandRenames = (diff, answers) => {
1006
- const additions = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1822
+ const tables = new Map(diff.changes.filter((item) => item._tag === "TableAdded").map((item) => [tableKey(item.table), item]));
1823
+ const enums = new Map(diff.changes.flatMap((item) => "enum" in item && item._tag === "EnumAdded" ? [[tableKey(item.enum.identity), item]] : []));
1007
1824
  const renames = [];
1008
- for (const source of diff.changes) {
1009
- if (source._tag !== "TableRemoved") continue;
1825
+ const consumed = /* @__PURE__ */ new Set();
1826
+ for (const source of diff.changes) if (source._tag === "TableRemoved") {
1010
1827
  const choice = answers.get(idFor(source.table))?.resolution;
1011
1828
  if (choice?.action !== "rename") continue;
1012
- const key = tableKey({
1829
+ const target = tables.get(tableKey({
1013
1830
  ...source.table,
1014
1831
  name: choice.target
1015
- });
1016
- const target = additions.get(key);
1017
- additions.delete(key);
1832
+ }));
1833
+ consumed.add(source).add(target);
1018
1834
  renames.push({
1019
1835
  _tag: "TableRenamed",
1020
1836
  after: target.definition,
@@ -1022,15 +1838,41 @@ const expandRenames = (diff, answers) => {
1022
1838
  changes: compareTable(source.definition, target.definition),
1023
1839
  table: source.table
1024
1840
  });
1841
+ } else if (source._tag === "EnumRemoved") {
1842
+ const identity = source.enum.identity;
1843
+ const choice = answers.get(enumId(identity))?.resolution;
1844
+ if (choice?.action !== "rename") continue;
1845
+ const target = enums.get(tableKey({
1846
+ ...identity,
1847
+ name: choice.target
1848
+ }));
1849
+ consumed.add(source).add(target);
1850
+ renames.push({
1851
+ _tag: "EnumRenamed",
1852
+ after: target.enum,
1853
+ before: source.enum,
1854
+ values: []
1855
+ });
1025
1856
  }
1026
1857
  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] },
1858
+ diff: { changes: [...diff.changes.filter((item) => !consumed.has(item)), ...renames] },
1031
1859
  nested: questions({ changes: renames })
1032
1860
  };
1033
1861
  };
1862
+ const issuedForPairing = (pending, input) => pending.decisions.some((parent) => {
1863
+ if ("enum" in parent) {
1864
+ const value = input.value;
1865
+ return parent.value === void 0 && typeof value === "string" && equal(parent.enum, input.enum) && parent.candidates.some((name) => input.id === valueId(parent.enum, {
1866
+ ...parent.enum,
1867
+ name
1868
+ }, value));
1869
+ }
1870
+ const column = input.column;
1871
+ return parent.column === void 0 && typeof column === "string" && equal(parent.table, input.table) && parent.candidates.some((name) => input.id === renamedColumnId(parent.table, {
1872
+ ...parent.table,
1873
+ name
1874
+ }, column));
1875
+ });
1034
1876
  const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(function* () {
1035
1877
  const rootIds = new Set(pending.decisions.map((item) => item.id));
1036
1878
  const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
@@ -1041,25 +1883,40 @@ const reviewAnswers = (pending, diff, inputs, merging) => effect.Effect.gen(func
1041
1883
  decisions: [...rootAnswers.values(), ...expanded.nested]
1042
1884
  };
1043
1885
  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
- });
1886
+ const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
1052
1887
  const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
1053
1888
  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
- }));
1889
+ if (!merging && missing.length) {
1890
+ const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : "Table rename requires column decisions";
1891
+ return yield* effect.Effect.fail(new MigrationDecisionError({
1892
+ message: `${required}. Run --merge-decisions to review them.`,
1893
+ pending: review
1894
+ }));
1895
+ }
1058
1896
  return {
1059
1897
  answers: yield* readAnswers(review, [...current, ...missing], merging),
1060
1898
  diff: expanded.diff
1061
1899
  };
1062
1900
  });
1901
+ /** The enum and value renames that the reviewer accepted. */
1902
+ const enumRenames = (diff, answers) => {
1903
+ const enums = /* @__PURE__ */ new Map();
1904
+ const values = /* @__PURE__ */ new Map();
1905
+ for (const change of diff.changes) {
1906
+ if (change._tag !== "EnumRenamed" && change._tag !== "EnumChanged") continue;
1907
+ const { after, before } = change;
1908
+ const key = tableKey(before.identity);
1909
+ if (change._tag === "EnumRenamed") enums.set(key, after.identity);
1910
+ values.set(key, new Map(before.values.flatMap((value) => {
1911
+ const choice = answers.get(valueId(before.identity, after.identity, value))?.resolution;
1912
+ return choice?.action === "rename" ? [[value, choice.target]] : [];
1913
+ })));
1914
+ }
1915
+ return {
1916
+ enums,
1917
+ values
1918
+ };
1919
+ };
1063
1920
  /** Refresh the questions and snapshots, carrying forward applicable reviewed choices. */
1064
1921
  const mergeMigrationDecisions = (fresh, previous) => effect.Effect.gen(function* () {
1065
1922
  if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* effect.Effect.fail(new MigrationDecisionError({
@@ -1137,7 +1994,7 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
1137
1994
  renamedTargets.add(afterColumn.key);
1138
1995
  const fields = [];
1139
1996
  if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
1140
- if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1997
+ if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1141
1998
  changes.push({
1142
1999
  _tag: "ColumnRenamed",
1143
2000
  after: afterColumn,
@@ -1150,8 +2007,18 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
1150
2007
  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
2008
  };
1152
2009
  });
2010
+ const renames = sequenceRenames(changes);
2011
+ const kept = changes.filter((change) => !/^(Comment|Enum|Sequence|Trigger)/.test(change._tag));
2012
+ const leading = (change) => /^(Namespace|Extension)/.test(change._tag);
2013
+ const withRenames = [
2014
+ ...kept.filter(leading),
2015
+ ...diffEnums(before, after, enumRenames(reviewed.diff, answers)),
2016
+ ...kept.filter((change) => !leading(change)),
2017
+ ...diffTriggers(before, after, renames),
2018
+ ...diffSequences(before, after, renames)
2019
+ ];
1153
2020
  const resolved = {
1154
- changes: [...changes.filter((change) => !change._tag.startsWith("Sequence")), ...diffSequences(before, after, sequenceRenames(changes))],
2021
+ changes: [...withRenames, ...diffComments(before, after, withRenames)],
1155
2022
  ...dropGuards.length ? { dropGuards } : {}
1156
2023
  };
1157
2024
  return {
@@ -1383,11 +2250,15 @@ exports.CodegenError = CodegenError;
1383
2250
  exports.MigrationDecisionError = MigrationDecisionError;
1384
2251
  exports.SchemaDiffError = SchemaDiffError;
1385
2252
  exports.SchemaModelError = SchemaModelError;
2253
+ exports.StatementEditError = StatementEditError;
1386
2254
  exports.artifactPathSchema = artifactPathSchema;
2255
+ exports.changedExternals = changedExternals;
1387
2256
  exports.checkManagedScope = checkManagedScope;
1388
2257
  exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
2258
+ exports.commentObjects = commentObjects;
1389
2259
  exports.compareTable = compareTable;
1390
2260
  exports.completionCandidates = completionCandidates;
2261
+ exports.constraintsEqual = constraintsEqual;
1391
2262
  exports.continuesRun = continuesRun;
1392
2263
  exports.declarationAt = declarationAt;
1393
2264
  exports.decodeDatabaseSchema = decodeDatabaseSchema;
@@ -1395,10 +2266,17 @@ exports.decodeGenerationResult = decodeGenerationResult;
1395
2266
  exports.decodeGeneratorPlugin = decodeGeneratorPlugin;
1396
2267
  exports.decodeMapperPlugin = decodeMapperPlugin;
1397
2268
  exports.definitions = definitions;
2269
+ exports.diffComments = diffComments;
1398
2270
  exports.diffDatabases = diffDatabases;
2271
+ exports.diffEnums = diffEnums;
1399
2272
  exports.diffFunctions = diffFunctions;
1400
2273
  exports.diffSequences = diffSequences;
2274
+ exports.diffStructures = diffStructures;
2275
+ exports.diffTriggers = diffTriggers;
2276
+ exports.enumObjects = enumObjects;
2277
+ exports.extensionObjects = extensionObjects;
1401
2278
  exports.externalObjects = externalObjects;
2279
+ exports.formatExtractOmissions = formatExtractOmissions;
1402
2280
  exports.functionKey = functionKey;
1403
2281
  exports.functionLabel = functionLabel;
1404
2282
  exports.generatedFileHeader = generatedFileHeader;
@@ -1420,5 +2298,6 @@ exports.resolveMigrationDecisions = resolveMigrationDecisions;
1420
2298
  exports.schemaValueEqual = schemaValueEqual;
1421
2299
  exports.sequenceRenames = sequenceRenames;
1422
2300
  exports.tableKey = tableKey;
2301
+ exports.triggerKey = triggerKey;
1423
2302
  exports.validateApplicationCompatibility = validateApplicationCompatibility;
1424
2303
  exports.validateDatabase = validateDatabase;