@uncutsql/core 0.2.0 → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 François Germain (cahnory)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs CHANGED
@@ -6,6 +6,41 @@ const tableKey = (table) => JSON.stringify([
6
6
  table.schema ?? null,
7
7
  table.name
8
8
  ]);
9
+ const functionKey = (fn) => JSON.stringify([
10
+ fn.identity.catalog ?? null,
11
+ fn.identity.schema ?? null,
12
+ fn.identity.name,
13
+ fn.signature
14
+ ]);
15
+ /** `schema.name(type, …)` for diagnostics; signature entries that are not strings print as JSON. */
16
+ const functionLabel = (fn) => `${[
17
+ fn.identity.catalog,
18
+ fn.identity.schema,
19
+ fn.identity.name
20
+ ].filter((part) => part !== void 0).join(".")}(${fn.signature.map((item) => typeof item === "string" ? item : JSON.stringify(item)).join(", ")})`;
21
+ /** The external objects of the models, tables before functions, each listed once by its key. */
22
+ const externalObjects = (...databases) => {
23
+ const found = /* @__PURE__ */ new Map();
24
+ for (const { externals } of databases) {
25
+ for (const { identity } of externals?.tables ?? []) {
26
+ const name = [
27
+ identity.catalog,
28
+ identity.schema,
29
+ identity.name
30
+ ].filter((part) => part !== void 0).join(".");
31
+ found.set(`table ${tableKey(identity)}`, {
32
+ identity,
33
+ label: `External table ${name}`
34
+ });
35
+ }
36
+ for (const fn of externals?.functions ?? []) found.set(`function ${functionKey(fn)}`, {
37
+ function: fn,
38
+ identity: fn.identity,
39
+ label: `External function ${functionLabel(fn)}`
40
+ });
41
+ }
42
+ return [...found.values()];
43
+ };
9
44
  const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
10
45
  /** The namespace that contains an object, or undefined when its identity has no schema level. */
11
46
  const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
@@ -32,26 +67,29 @@ const validateDatabase = (database, side) => {
32
67
  const diagnostics = [];
33
68
  const tables = /* @__PURE__ */ new Set();
34
69
  const indexes = /* @__PURE__ */ new Set();
35
- for (const table of database.tables) {
36
- const id = tableKey(table.identity);
37
- if (tables.has(id)) diagnostics.push({
38
- code: "DuplicateTable",
39
- message: `Duplicate table ${id}`,
40
- side,
41
- table: table.identity
42
- });
43
- tables.add(id);
70
+ const duplicateColumns = (table) => {
44
71
  const columns = /* @__PURE__ */ new Set();
45
72
  for (const column of table.columns) {
46
73
  if (columns.has(column.key)) diagnostics.push({
47
74
  code: "DuplicateColumn",
48
75
  column: column.key,
49
- message: `Duplicate column ${JSON.stringify(column.key)} in table ${id}`,
76
+ message: `Duplicate column ${JSON.stringify(column.key)} in table ${tableKey(table.identity)}`,
50
77
  side,
51
78
  table: table.identity
52
79
  });
53
80
  columns.add(column.key);
54
81
  }
82
+ };
83
+ for (const table of database.tables) {
84
+ const id = tableKey(table.identity);
85
+ if (tables.has(id)) diagnostics.push({
86
+ code: "DuplicateTable",
87
+ message: `Duplicate table ${id}`,
88
+ side,
89
+ table: table.identity
90
+ });
91
+ tables.add(id);
92
+ duplicateColumns(table);
55
93
  }
56
94
  for (const table of database.tables) for (const index of table.indexes ?? []) {
57
95
  const id = JSON.stringify([tableKey(table.identity), index.key]);
@@ -91,6 +129,38 @@ const validateDatabase = (database, side) => {
91
129
  });
92
130
  triggers.add(id);
93
131
  }
132
+ const sequences = /* @__PURE__ */ new Set();
133
+ for (const sequence of database.sequences ?? []) {
134
+ const id = tableKey(sequence.identity);
135
+ if (sequences.has(id)) diagnostics.push({
136
+ code: "DuplicateSequence",
137
+ message: `Duplicate sequence ${id}`,
138
+ side,
139
+ table: sequence.identity
140
+ });
141
+ sequences.add(id);
142
+ const owner = sequence.owner;
143
+ if (owner) {
144
+ if (!database.tables.find((table) => tableKey(table.identity) === tableKey(owner.table))?.columns.some((column) => column.key === owner.column)) diagnostics.push({
145
+ code: "UndeclaredSequenceOwner",
146
+ column: owner.column,
147
+ message: `Sequence ${id} is owned by ${tableKey(owner.table)} column ${JSON.stringify(owner.column)}, which is not in the model`,
148
+ side,
149
+ table: sequence.identity
150
+ });
151
+ }
152
+ }
153
+ const functions = /* @__PURE__ */ new Set();
154
+ for (const fn of database.functions ?? []) {
155
+ const id = functionKey(fn);
156
+ if (functions.has(id)) diagnostics.push({
157
+ code: "DuplicateFunction",
158
+ message: `Duplicate function ${id}`,
159
+ side,
160
+ table: fn.identity
161
+ });
162
+ functions.add(id);
163
+ }
94
164
  const namespaces = /* @__PURE__ */ new Set();
95
165
  for (const namespace of database.namespaces ?? []) {
96
166
  const id = namespaceKey(namespace.identity);
@@ -102,6 +172,33 @@ const validateDatabase = (database, side) => {
102
172
  });
103
173
  namespaces.add(id);
104
174
  }
175
+ const externals = /* @__PURE__ */ new Set();
176
+ const external = (key, identity, label, statement) => {
177
+ if (externals.has(key)) diagnostics.push({
178
+ code: "DuplicateExternal",
179
+ message: `Duplicate ${label}`,
180
+ side,
181
+ table: identity
182
+ });
183
+ externals.add(key);
184
+ const namespace = namespaceOf(identity);
185
+ if (namespace && namespaces.has(namespaceKey(namespace))) diagnostics.push({
186
+ code: "ExternalInManagedNamespace",
187
+ message: `External ${label} is in managed schema ${namespace.name}; declare it with ${statement}, or move it out of the managed scope`,
188
+ side,
189
+ table: identity
190
+ });
191
+ };
192
+ for (const table of database.externals?.tables ?? []) {
193
+ const { catalog, name, schema } = table.identity;
194
+ external(`table ${tableKey(table.identity)}`, table.identity, `table ${[
195
+ catalog,
196
+ schema,
197
+ name
198
+ ].filter((part) => part !== void 0).join(".")}`, "CREATE TABLE");
199
+ duplicateColumns(table);
200
+ }
201
+ for (const fn of database.externals?.functions ?? []) external(`function ${functionKey(fn)}`, fn.identity, `function ${functionLabel(fn)}`, "CREATE FUNCTION");
105
202
  if (database.namespaces) {
106
203
  const undeclared = (identity, owner, role) => {
107
204
  const namespace = namespaceOf(identity);
@@ -118,9 +215,30 @@ const validateDatabase = (database, side) => {
118
215
  undeclared(trigger.identity, trigger.identity, "Trigger");
119
216
  undeclared(trigger.target, trigger.identity, "Target of trigger");
120
217
  }
218
+ for (const sequence of database.sequences ?? []) {
219
+ undeclared(sequence.identity, sequence.identity, "Sequence");
220
+ if (sequence.owner) undeclared(sequence.owner.table, sequence.identity, "Owner table of sequence");
221
+ }
222
+ for (const fn of database.functions ?? []) undeclared(fn.identity, fn.identity, "Function");
121
223
  }
122
224
  return diagnostics;
123
225
  };
226
+ /**
227
+ * Checks an explicit list of managed schemas against the namespaces of a model built from schema
228
+ * files. Names are compared as catalog names, case-sensitively. The shape of the list (non-empty,
229
+ * unique, including `public`) is the caller's to validate.
230
+ */
231
+ const checkManagedScope = (model, managedSchemas) => {
232
+ const managed = new Set(managedSchemas);
233
+ const created = new Set((model.namespaces ?? []).map((namespace) => namespace.identity.name));
234
+ const diagnostic = (code, name, message) => ({
235
+ code,
236
+ message,
237
+ side: "after",
238
+ table: { name }
239
+ });
240
+ 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
+ };
124
242
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
125
243
  const compareTable = (before, after) => {
126
244
  const changes = [];
@@ -180,7 +298,7 @@ const compareTable = (before, after) => {
180
298
  _tag: "IndexAdded",
181
299
  index
182
300
  });
183
- else if (old.unique !== index.unique || !schemaValueEqual(old.terms, index.terms) || !schemaValueEqual(old.where, index.where)) changes.push({
301
+ else if (old.unique !== index.unique || !schemaValueEqual(old.terms, index.terms) || !schemaValueEqual(old.where, index.where) || !schemaValueEqual(old.options ?? {}, index.options ?? {})) changes.push({
184
302
  _tag: "IndexChanged",
185
303
  after: index,
186
304
  before: old
@@ -188,6 +306,119 @@ const compareTable = (before, after) => {
188
306
  }
189
307
  return changes;
190
308
  };
309
+ /** Collect the table and column renames that a list of changes carries. */
310
+ const sequenceRenames = (changes) => {
311
+ const tables = /* @__PURE__ */ new Map();
312
+ const columns = /* @__PURE__ */ new Map();
313
+ for (const change of changes) {
314
+ if (change._tag !== "TableChanged" && change._tag !== "TableRenamed") continue;
315
+ const key = tableKey(change.before.identity);
316
+ if (change._tag === "TableRenamed") tables.set(key, change.after.identity);
317
+ for (const item of change.changes) if (item._tag === "ColumnRenamed") {
318
+ const renamed = columns.get(key) ?? /* @__PURE__ */ new Map();
319
+ renamed.set(item.before.key, item.after.key);
320
+ columns.set(key, renamed);
321
+ }
322
+ }
323
+ return {
324
+ columns,
325
+ tables
326
+ };
327
+ };
328
+ /** The owner of a `before` sequence expressed in the `after` model, or its key when unowned. */
329
+ const ownerAfterRenames = (sequence, renames) => {
330
+ const owner = sequence.owner;
331
+ if (!owner) return;
332
+ const source = tableKey(owner.table);
333
+ return {
334
+ column: renames.columns.get(source)?.get(owner.column) ?? owner.column,
335
+ table: renames.tables.get(source) ?? owner.table
336
+ };
337
+ };
338
+ const ownerKey = (owner) => owner ? JSON.stringify([tableKey(owner.table), owner.column]) : null;
339
+ /** Function changes. A changed signature is another key: a removal and an addition. */
340
+ const diffFunctions = (before, after) => {
341
+ const changes = [];
342
+ const oldFunctions = new Map((before.functions ?? []).map((item) => [functionKey(item), item]));
343
+ const newFunctions = new Map((after.functions ?? []).map((item) => [functionKey(item), item]));
344
+ for (const [key, fn] of oldFunctions) if (!newFunctions.has(key)) changes.push({
345
+ _tag: "FunctionRemoved",
346
+ function: fn
347
+ });
348
+ for (const [key, fn] of newFunctions) {
349
+ const old = oldFunctions.get(key);
350
+ if (!old) changes.push({
351
+ _tag: "FunctionAdded",
352
+ function: fn
353
+ });
354
+ else if (!schemaValueEqual(old.definition, fn.definition)) changes.push({
355
+ _tag: "FunctionChanged",
356
+ after: fn,
357
+ before: old
358
+ });
359
+ }
360
+ return changes;
361
+ };
362
+ /** Sequence changes. `renames` are the table and column renames the migration applies. */
363
+ const diffSequences = (before, after, renames = {
364
+ columns: /* @__PURE__ */ new Map(),
365
+ tables: /* @__PURE__ */ new Map()
366
+ }) => {
367
+ const changes = [];
368
+ const oldSequences = new Map((before.sequences ?? []).map((item) => [tableKey(item.identity), item]));
369
+ const newSequences = new Map((after.sequences ?? []).map((item) => [tableKey(item.identity), item]));
370
+ const removed = [];
371
+ const added = [];
372
+ for (const [key, sequence] of oldSequences) if (!newSequences.has(key)) removed.push(sequence);
373
+ for (const [key, sequence] of newSequences) {
374
+ const old = oldSequences.get(key);
375
+ if (!old) added.push(sequence);
376
+ else if (!schemaValueEqual(old.definition, sequence.definition) || ownerKey(ownerAfterRenames(old, renames)) !== ownerKey(sequence.owner)) changes.push({
377
+ _tag: "SequenceChanged",
378
+ after: sequence,
379
+ before: old
380
+ });
381
+ }
382
+ const groupKey = (sequence, owner) => JSON.stringify([namespaceOf(sequence.identity) ?? null, owner]);
383
+ const groups = /* @__PURE__ */ new Map();
384
+ const group = (key) => {
385
+ const found = groups.get(key) ?? {
386
+ added: [],
387
+ removed: []
388
+ };
389
+ groups.set(key, found);
390
+ return found;
391
+ };
392
+ for (const sequence of removed) {
393
+ const owner = ownerKey(ownerAfterRenames(sequence, renames));
394
+ if (owner !== null) group(groupKey(sequence, owner)).removed.push(sequence);
395
+ }
396
+ for (const sequence of added) {
397
+ const owner = ownerKey(sequence.owner);
398
+ if (owner !== null) group(groupKey(sequence, owner)).added.push(sequence);
399
+ }
400
+ const paired = /* @__PURE__ */ new Set();
401
+ for (const found of groups.values()) if (found.removed.length === 1 && found.added.length === 1) {
402
+ const [old] = found.removed;
403
+ const [next] = found.added;
404
+ paired.add(old);
405
+ paired.add(next);
406
+ changes.push({
407
+ _tag: "SequenceRenamed",
408
+ after: next,
409
+ before: old
410
+ });
411
+ }
412
+ for (const sequence of removed) if (!paired.has(sequence)) changes.push({
413
+ _tag: "SequenceRemoved",
414
+ sequence
415
+ });
416
+ for (const sequence of added) if (!paired.has(sequence)) changes.push({
417
+ _tag: "SequenceAdded",
418
+ sequence
419
+ });
420
+ return changes;
421
+ };
191
422
  /** Compare normalized relational models without parsing SQL or consulting a dialect. */
192
423
  const diffDatabases = (before, after) => effect.Effect.gen(function* () {
193
424
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
@@ -248,7 +479,7 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
248
479
  _tag: "ViewAdded",
249
480
  view
250
481
  });
251
- else if (!schemaValueEqual(old.columns ?? null, view.columns ?? null) || !schemaValueEqual(old.query, view.query)) changes.push({
482
+ else if (!schemaValueEqual(old.columns ?? null, view.columns ?? null) || !schemaValueEqual(old.query, view.query) || !schemaValueEqual(old.options ?? {}, view.options ?? {})) changes.push({
252
483
  _tag: "ViewChanged",
253
484
  after: view,
254
485
  before: old
@@ -272,6 +503,8 @@ const diffDatabases = (before, after) => effect.Effect.gen(function* () {
272
503
  before: old
273
504
  });
274
505
  }
506
+ changes.push(...diffSequences(before, after));
507
+ changes.push(...diffFunctions(before, after));
275
508
  return { changes };
276
509
  });
277
510
  // src/migration.ts
@@ -290,6 +523,31 @@ const planDatabaseMigration = (diff) => ({
290
523
  after: change.after,
291
524
  before: change.before
292
525
  };
526
+ case "FunctionAdded":
527
+ case "FunctionRemoved": return {
528
+ _tag: change._tag === "FunctionAdded" ? "CreateFunction" : "DropFunction",
529
+ function: change.function
530
+ };
531
+ case "FunctionChanged": return {
532
+ _tag: "ReplaceFunction",
533
+ after: change.after,
534
+ before: change.before
535
+ };
536
+ case "SequenceAdded":
537
+ case "SequenceRemoved": return {
538
+ _tag: change._tag === "SequenceAdded" ? "CreateSequence" : "DropSequence",
539
+ sequence: change.sequence
540
+ };
541
+ case "SequenceChanged": return {
542
+ _tag: "AlterSequence",
543
+ after: change.after,
544
+ before: change.before
545
+ };
546
+ case "SequenceRenamed": return {
547
+ _tag: "RenameSequence",
548
+ after: change.after,
549
+ before: change.before
550
+ };
293
551
  case "TriggerAdded":
294
552
  case "TriggerRemoved": return {
295
553
  _tag: change._tag === "TriggerAdded" ? "CreateTrigger" : "DropTrigger",
@@ -341,6 +599,27 @@ const planDownMigration = (up) => {
341
599
  _tag: "DropTable"
342
600
  });
343
601
  break;
602
+ case "CreateFunction":
603
+ case "DropFunction":
604
+ procedures.push({
605
+ ...step,
606
+ _tag: step._tag === "CreateFunction" ? "DropFunction" : "CreateFunction"
607
+ });
608
+ break;
609
+ case "ReplaceFunction":
610
+ procedures.push(swap(step));
611
+ break;
612
+ case "CreateSequence":
613
+ case "DropSequence":
614
+ procedures.push({
615
+ ...step,
616
+ _tag: step._tag === "CreateSequence" ? "DropSequence" : "CreateSequence"
617
+ });
618
+ break;
619
+ case "AlterSequence":
620
+ case "RenameSequence":
621
+ procedures.push(swap(step));
622
+ break;
344
623
  case "CreateTrigger":
345
624
  case "DropTrigger":
346
625
  procedures.push({
@@ -475,10 +754,12 @@ const index = (value, path) => {
475
754
  "name",
476
755
  "unique",
477
756
  "terms",
478
- "where"
757
+ "where",
758
+ "options"
479
759
  ], path);
480
760
  text(item.key, `${path}.key`);
481
761
  text(item.name, `${path}.name`);
762
+ if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
482
763
  if (typeof item.unique !== "boolean") fail(`${path}.unique`, "a boolean");
483
764
  array(item.terms, `${path}.terms`, semanticValue);
484
765
  semanticValue(item.where, `${path}.where`);
@@ -506,17 +787,50 @@ const trigger = (value, path) => {
506
787
  identity(item.target, `${path}.target`);
507
788
  semanticValue(item.definition, `${path}.definition`);
508
789
  };
790
+ const sequence = (value, path) => {
791
+ const item = record$1(value, path);
792
+ fields(item, [
793
+ "identity",
794
+ "name",
795
+ "definition",
796
+ "owner"
797
+ ], path);
798
+ identity(item.identity, `${path}.identity`);
799
+ text(item.name, `${path}.name`);
800
+ properties(item.definition, `${path}.definition`);
801
+ if (Object.hasOwn(item, "owner")) {
802
+ const owner = record$1(item.owner, `${path}.owner`);
803
+ fields(owner, ["column", "table"], `${path}.owner`);
804
+ text(owner.column, `${path}.owner.column`);
805
+ identity(owner.table, `${path}.owner.table`);
806
+ }
807
+ };
808
+ const databaseFunction = (value, path) => {
809
+ const item = record$1(value, path);
810
+ fields(item, [
811
+ "identity",
812
+ "name",
813
+ "signature",
814
+ "definition"
815
+ ], path);
816
+ identity(item.identity, `${path}.identity`);
817
+ text(item.name, `${path}.name`);
818
+ array(item.signature, `${path}.signature`, semanticValue);
819
+ properties(item.definition, `${path}.definition`);
820
+ };
509
821
  const view = (value, path) => {
510
822
  const item = record$1(value, path);
511
823
  fields(item, [
512
824
  "identity",
513
825
  "name",
514
826
  "columns",
515
- "query"
827
+ "query",
828
+ "options"
516
829
  ], path);
517
830
  identity(item.identity, `${path}.identity`);
518
831
  text(item.name, `${path}.name`);
519
832
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
833
+ if (Object.hasOwn(item, "options")) properties(item.options, `${path}.options`);
520
834
  semanticValue(item.query, `${path}.query`);
521
835
  };
522
836
  const namespace = (value, path) => {
@@ -550,6 +864,12 @@ const table = (value, path) => {
550
864
  array(item.constraints, `${path}.constraints`, constraint);
551
865
  properties(item.options, `${path}.options`);
552
866
  };
867
+ const externals = (value, path) => {
868
+ const item = record$1(value, path);
869
+ fields(item, ["functions", "tables"], path);
870
+ if (Object.hasOwn(item, "functions")) array(item.functions, `${path}.functions`, databaseFunction);
871
+ if (Object.hasOwn(item, "tables")) array(item.tables, `${path}.tables`, table);
872
+ };
553
873
  /** Validate external/JSON-restored models before core or a dialect consumes them. */
554
874
  const decodeDatabaseSchema = (value) => effect.Effect.try({
555
875
  catch: (cause) => cause instanceof SchemaModelError ? cause : new SchemaModelError({
@@ -562,12 +882,18 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
562
882
  "namespaces",
563
883
  "tables",
564
884
  "views",
565
- "triggers"
885
+ "triggers",
886
+ "sequences",
887
+ "functions",
888
+ "externals"
566
889
  ], "$database");
890
+ if (Object.hasOwn(database, "externals")) externals(database.externals, "$database.externals");
891
+ if (Object.hasOwn(database, "functions")) array(database.functions, "$database.functions", databaseFunction);
567
892
  if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
568
893
  array(database.tables, "$database.tables", table);
569
894
  if (Object.hasOwn(database, "views")) array(database.views, "$database.views", view);
570
895
  if (Object.hasOwn(database, "triggers")) array(database.triggers, "$database.triggers", trigger);
896
+ if (Object.hasOwn(database, "sequences")) array(database.sequences, "$database.sequences", sequence);
571
897
  return value;
572
898
  }
573
899
  });
@@ -791,40 +1117,41 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
791
1117
  const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false);
792
1118
  const answers = reviewed.answers;
793
1119
  const dropGuards = [];
1120
+ const changes = reviewed.diff.changes.map((change) => {
1121
+ if (!("changes" in change)) {
1122
+ if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
1123
+ return change;
1124
+ }
1125
+ const renamedTargets = /* @__PURE__ */ new Set();
1126
+ const changes = [];
1127
+ for (const item of change.changes) {
1128
+ if (item._tag !== "ColumnRemoved") continue;
1129
+ const answer = answers.get(columnId(change, item.column.key));
1130
+ if (answer.resolution.action === "drop_if_empty") dropGuards.push({
1131
+ column: item.column.name,
1132
+ table: change.table
1133
+ });
1134
+ if (answer.resolution.action !== "rename") continue;
1135
+ const targetKey = answer.resolution.target;
1136
+ const afterColumn = change.after.columns.find((column) => column.key === targetKey);
1137
+ renamedTargets.add(afterColumn.key);
1138
+ const fields = [];
1139
+ if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
1140
+ if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
1141
+ changes.push({
1142
+ _tag: "ColumnRenamed",
1143
+ after: afterColumn,
1144
+ before: item.column,
1145
+ fields
1146
+ });
1147
+ }
1148
+ return {
1149
+ ...change,
1150
+ 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
+ };
1152
+ });
794
1153
  const resolved = {
795
- changes: reviewed.diff.changes.map((change) => {
796
- if (!("changes" in change)) {
797
- if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
798
- return change;
799
- }
800
- const renamedTargets = /* @__PURE__ */ new Set();
801
- const changes = [];
802
- for (const item of change.changes) {
803
- if (item._tag !== "ColumnRemoved") continue;
804
- const answer = answers.get(columnId(change, item.column.key));
805
- if (answer.resolution.action === "drop_if_empty") dropGuards.push({
806
- column: item.column.name,
807
- table: change.table
808
- });
809
- if (answer.resolution.action !== "rename") continue;
810
- const targetKey = answer.resolution.target;
811
- const afterColumn = change.after.columns.find((column) => column.key === targetKey);
812
- renamedTargets.add(afterColumn.key);
813
- const fields = [];
814
- if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
815
- if (!equal(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
816
- changes.push({
817
- _tag: "ColumnRenamed",
818
- after: afterColumn,
819
- before: item.column,
820
- fields
821
- });
822
- }
823
- return {
824
- ...change,
825
- changes: [...changes, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "rename"))]
826
- };
827
- }),
1154
+ changes: [...changes.filter((change) => !change._tag.startsWith("Sequence")), ...diffSequences(before, after, sequenceRenames(changes))],
828
1155
  ...dropGuards.length ? { dropGuards } : {}
829
1156
  };
830
1157
  return {
@@ -836,10 +1163,68 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
836
1163
  };
837
1164
  });
838
1165
  // src/language-service.ts
1166
+ /**
1167
+ * Selects the completion candidates for `completion` from the analyses, in analysis then declaration order.
1168
+ * A declaration is a candidate when its `kind` is `expected` and it has `text`, and either its `scope` is the
1169
+ * completion's scope (inserting `text`), or the completion sets `qualify`, the declaration is a table with
1170
+ * `qualifiedText` and another scope (inserting `qualifiedText`). One candidate per key: the first one wins.
1171
+ */
1172
+ const completionCandidates = (completion, analyses) => {
1173
+ const keys = /* @__PURE__ */ new Set();
1174
+ const candidates = [];
1175
+ analyses.forEach((analysis, source) => {
1176
+ for (const declaration of analysis.declarations) {
1177
+ if (declaration.kind !== completion.expected || keys.has(declaration.key)) continue;
1178
+ let text;
1179
+ if (declaration.scope === completion.scope) text = declaration.text;
1180
+ else if (completion.qualify && declaration.kind === "table" && declaration.qualifiedText !== void 0) text = declaration.qualifiedText;
1181
+ if (text === void 0) continue;
1182
+ keys.add(declaration.key);
1183
+ candidates.push({
1184
+ key: declaration.key,
1185
+ kind: completion.expected,
1186
+ source,
1187
+ text
1188
+ });
1189
+ }
1190
+ });
1191
+ return candidates;
1192
+ };
839
1193
  /** Returns the first reference whose half-open span contains `offset`. */
840
1194
  const referenceAt = (analysis, offset) => analysis.references.find((reference) => reference.start <= offset && offset < reference.end);
1195
+ /** Returns the first declaration whose half-open selection contains `offset`. */
1196
+ const declarationAt = (analysis, offset) => analysis.declarations.find((declaration) => declaration.selection.start <= offset && offset < declaration.selection.end);
1197
+ /** Returns the spans of the references whose key equals `key`, then the declaration selections with that key when `includeDeclaration` is set. */
1198
+ const referencesTo = (key, analysis, includeDeclaration) => [...analysis.references.filter((reference) => reference.key === key).map(({ end, start }) => ({
1199
+ end,
1200
+ start
1201
+ })), ...includeDeclaration ? analysis.declarations.filter((declaration) => declaration.key === key).map((declaration) => declaration.selection) : []];
841
1202
  /** Returns the selections of the declarations whose key equals the reference key, in declaration order. */
842
1203
  const definitions = (reference, analysis) => analysis.declarations.filter((declaration) => declaration.key === reference.key).map((declaration) => declaration.selection);
1204
+ /** The span that rename replaces: `selection` when present, else the reference span. */
1205
+ const nameSpan = (reference) => reference.selection ?? {
1206
+ end: reference.end,
1207
+ start: reference.start
1208
+ };
1209
+ const contains = (span, offset) => span.start <= offset && offset < span.end;
1210
+ /** The declaration, reference or occurrence whose name span contains `offset`. */
1211
+ const renameSiteAt = (analysis, offset) => {
1212
+ const declaration = analysis.declarations.find((candidate) => contains(candidate.selection, offset));
1213
+ if (declaration) return {
1214
+ key: declaration.key,
1215
+ span: declaration.selection
1216
+ };
1217
+ const site = [...analysis.references, ...analysis.occurrences ?? []].find((reference) => contains(nameSpan(reference), offset));
1218
+ return site ? {
1219
+ key: site.key,
1220
+ span: nameSpan(site)
1221
+ } : void 0;
1222
+ };
1223
+ /** The name spans of every declaration, reference and occurrence with `key`, in document order. */
1224
+ const renameSpans = (key, analysis) => [...analysis.declarations.filter((declaration) => declaration.key === key).map((declaration) => declaration.selection), ...[...analysis.references, ...analysis.occurrences ?? []].filter((reference) => reference.key === key).map(nameSpan)].map(({ end, start }) => ({
1225
+ end,
1226
+ start
1227
+ })).sort((left, right) => left.start - right.start);
843
1228
  // src/codegen.ts
844
1229
  var CodegenError = class extends effect.Data.TaggedError("CodegenError") {};
845
1230
  const generatedFileHeader = "// Generated by UncutSQL. Do not edit.";
@@ -999,18 +1384,27 @@ exports.MigrationDecisionError = MigrationDecisionError;
999
1384
  exports.SchemaDiffError = SchemaDiffError;
1000
1385
  exports.SchemaModelError = SchemaModelError;
1001
1386
  exports.artifactPathSchema = artifactPathSchema;
1387
+ exports.checkManagedScope = checkManagedScope;
1002
1388
  exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
1003
1389
  exports.compareTable = compareTable;
1390
+ exports.completionCandidates = completionCandidates;
1004
1391
  exports.continuesRun = continuesRun;
1392
+ exports.declarationAt = declarationAt;
1005
1393
  exports.decodeDatabaseSchema = decodeDatabaseSchema;
1006
1394
  exports.decodeGenerationResult = decodeGenerationResult;
1007
1395
  exports.decodeGeneratorPlugin = decodeGeneratorPlugin;
1008
1396
  exports.decodeMapperPlugin = decodeMapperPlugin;
1009
1397
  exports.definitions = definitions;
1010
1398
  exports.diffDatabases = diffDatabases;
1399
+ exports.diffFunctions = diffFunctions;
1400
+ exports.diffSequences = diffSequences;
1401
+ exports.externalObjects = externalObjects;
1402
+ exports.functionKey = functionKey;
1403
+ exports.functionLabel = functionLabel;
1011
1404
  exports.generatedFileHeader = generatedFileHeader;
1012
1405
  exports.mergeMigrationDecisions = mergeMigrationDecisions;
1013
1406
  exports.migrationRun = migrationRun;
1407
+ exports.nameSpan = nameSpan;
1014
1408
  exports.namespaceKey = namespaceKey;
1015
1409
  exports.namespaceOf = namespaceOf;
1016
1410
  exports.nextMigration = nextMigration;
@@ -1018,9 +1412,13 @@ exports.planDatabaseMigration = planDatabaseMigration;
1018
1412
  exports.planDownMigration = planDownMigration;
1019
1413
  exports.prepareMigrationDecisions = prepareMigrationDecisions;
1020
1414
  exports.referenceAt = referenceAt;
1415
+ exports.referencesTo = referencesTo;
1021
1416
  exports.relationIdentitySchema = relationIdentitySchema;
1417
+ exports.renameSiteAt = renameSiteAt;
1418
+ exports.renameSpans = renameSpans;
1022
1419
  exports.resolveMigrationDecisions = resolveMigrationDecisions;
1023
1420
  exports.schemaValueEqual = schemaValueEqual;
1421
+ exports.sequenceRenames = sequenceRenames;
1024
1422
  exports.tableKey = tableKey;
1025
1423
  exports.validateApplicationCompatibility = validateApplicationCompatibility;
1026
1424
  exports.validateDatabase = validateDatabase;