@happyvertical/smrt-core 0.36.8 → 0.37.1

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.
Files changed (105) hide show
  1. package/dist/child-accessors.d.ts +1 -1
  2. package/dist/child-accessors.d.ts.map +1 -1
  3. package/dist/child-accessors.js +1 -1
  4. package/dist/child-accessors.js.map +1 -1
  5. package/dist/class.d.ts.map +1 -1
  6. package/dist/class.js +3 -1
  7. package/dist/class.js.map +1 -1
  8. package/dist/collection-cache.d.ts.map +1 -1
  9. package/dist/collection-cache.js +5 -3
  10. package/dist/collection-cache.js.map +1 -1
  11. package/dist/collection.d.ts +39 -16
  12. package/dist/collection.d.ts.map +1 -1
  13. package/dist/collection.js +40 -19
  14. package/dist/collection.js.map +1 -1
  15. package/dist/consumer-plugin/index.js.map +1 -1
  16. package/dist/decorators/compatibility.d.ts +1 -1
  17. package/dist/decorators/compatibility.d.ts.map +1 -1
  18. package/dist/decorators/compatibility.js.map +1 -1
  19. package/dist/decorators/index.d.ts +4 -4
  20. package/dist/decorators/index.d.ts.map +1 -1
  21. package/dist/decorators/index.js.map +1 -1
  22. package/dist/hierarchical.d.ts.map +1 -1
  23. package/dist/hierarchical.js.map +1 -1
  24. package/dist/junction.d.ts.map +1 -1
  25. package/dist/junction.js.map +1 -1
  26. package/dist/manifest/discover-smrt-packages.d.ts +10 -0
  27. package/dist/manifest/discover-smrt-packages.d.ts.map +1 -1
  28. package/dist/manifest/discover-smrt-packages.js.map +1 -1
  29. package/dist/manifest/generator.d.ts.map +1 -1
  30. package/dist/manifest/generator.js +34 -37
  31. package/dist/manifest/generator.js.map +1 -1
  32. package/dist/manifest/index.js +2 -2
  33. package/dist/manifest/index.js.map +1 -1
  34. package/dist/manifest/manifest-loader.d.ts +10 -0
  35. package/dist/manifest/manifest-loader.d.ts.map +1 -1
  36. package/dist/manifest/manifest-loader.js.map +1 -1
  37. package/dist/manifest/static-manifest.d.ts.map +1 -1
  38. package/dist/manifest/static-manifest.js +39 -20
  39. package/dist/manifest/static-manifest.js.map +1 -1
  40. package/dist/manifest/store.js +2 -2
  41. package/dist/manifest/store.js.map +1 -1
  42. package/dist/manifest/test-manifest-stub.d.ts.map +1 -1
  43. package/dist/manifest/test-manifest-stub.js +2301 -629
  44. package/dist/manifest/test-manifest-stub.js.map +1 -1
  45. package/dist/manifest.json +39 -20
  46. package/dist/migrations/differ.d.ts +104 -13
  47. package/dist/migrations/differ.d.ts.map +1 -1
  48. package/dist/migrations/differ.js +199 -26
  49. package/dist/migrations/differ.js.map +1 -1
  50. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map +1 -1
  51. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/ast.js +1 -7
  52. package/dist/node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/ast.js.map +1 -0
  53. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/brace-expressions.js.map +1 -1
  54. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/escape.js.map +1 -1
  55. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/index.js +17 -14
  56. package/dist/node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js.map +1 -0
  57. package/dist/node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/unescape.js +10 -0
  58. package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/unescape.js.map +1 -1
  59. package/dist/object.d.ts +64 -17
  60. package/dist/object.d.ts.map +1 -1
  61. package/dist/object.js +76 -30
  62. package/dist/object.js.map +1 -1
  63. package/dist/registry/class-registration.d.ts +3 -3
  64. package/dist/registry/class-registration.d.ts.map +1 -1
  65. package/dist/registry/class-registration.js +39 -42
  66. package/dist/registry/class-registration.js.map +1 -1
  67. package/dist/registry/inheritance-resolver.d.ts +17 -3
  68. package/dist/registry/inheritance-resolver.d.ts.map +1 -1
  69. package/dist/registry/inheritance-resolver.js +1 -1
  70. package/dist/registry/inheritance-resolver.js.map +1 -1
  71. package/dist/registry/manifest-field-merge.d.ts +17 -3
  72. package/dist/registry/manifest-field-merge.d.ts.map +1 -1
  73. package/dist/registry/manifest-field-merge.js +8 -6
  74. package/dist/registry/manifest-field-merge.js.map +1 -1
  75. package/dist/registry/schema-builder.d.ts +1 -1
  76. package/dist/registry/schema-builder.d.ts.map +1 -1
  77. package/dist/registry/schema-builder.js.map +1 -1
  78. package/dist/registry/shared-state.d.ts +3 -3
  79. package/dist/registry/shared-state.d.ts.map +1 -1
  80. package/dist/registry/shared-state.js.map +1 -1
  81. package/dist/registry/types.d.ts +78 -19
  82. package/dist/registry/types.d.ts.map +1 -1
  83. package/dist/registry/validator.d.ts +2 -1
  84. package/dist/registry/validator.d.ts.map +1 -1
  85. package/dist/registry/validator.js +38 -39
  86. package/dist/registry/validator.js.map +1 -1
  87. package/dist/registry.d.ts +84 -57
  88. package/dist/registry.d.ts.map +1 -1
  89. package/dist/registry.js +31 -25
  90. package/dist/registry.js.map +1 -1
  91. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  92. package/dist/scanner/manifest-generator.js +22 -20
  93. package/dist/scanner/manifest-generator.js.map +1 -1
  94. package/dist/smrt-knowledge.json +8 -7
  95. package/dist/system-fields.d.ts +1 -1
  96. package/dist/system-fields.d.ts.map +1 -1
  97. package/dist/system-fields.js.map +1 -1
  98. package/dist/vite-plugin/index.js +1 -1
  99. package/package.json +7 -7
  100. package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/ast.js.map +0 -1
  101. package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/index.js.map +0 -1
  102. package/dist/node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/unescape.js +0 -10
  103. /package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/assert-valid-pattern.js +0 -0
  104. /package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/brace-expressions.js +0 -0
  105. /package/dist/node_modules/.pnpm/{minimatch@10.2.3 → minimatch@10.2.5}/node_modules/minimatch/dist/esm/escape.js +0 -0
@@ -25,6 +25,50 @@ function resolveDatabaseUrl(db) {
25
25
  const dbWithConfig = db;
26
26
  return db.url || dbWithConfig.config?.url || "";
27
27
  }
28
+ function normalizeIndexPredicate(where) {
29
+ if (!where) return "";
30
+ const stripped = where.trim().replace(/^WHERE\s+/i, "");
31
+ if (!stripped) return "";
32
+ let out = "";
33
+ let i = 0;
34
+ while (i < stripped.length) {
35
+ if (stripped[i] === "'") {
36
+ let literal = "'";
37
+ i++;
38
+ while (i < stripped.length) {
39
+ if (stripped[i] === "'") {
40
+ if (stripped[i + 1] === "'") {
41
+ literal += "''";
42
+ i += 2;
43
+ continue;
44
+ }
45
+ literal += "'";
46
+ i++;
47
+ break;
48
+ }
49
+ literal += stripped[i];
50
+ i++;
51
+ }
52
+ out += literal;
53
+ } else {
54
+ let run = "";
55
+ while (i < stripped.length && stripped[i] !== "'") {
56
+ run += stripped[i];
57
+ i++;
58
+ }
59
+ out += normalizeNonLiteralPredicateRun(run);
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+ function normalizeNonLiteralPredicateRun(run) {
65
+ return run.replace(/::[A-Za-z_]\w*/g, "").replace(/[()]/g, "").toLowerCase().replace(/\s+/g, " ").replace(/\s*([=<>!]+)\s*/g, "$1").trim();
66
+ }
67
+ function extractIndexPredicate(createIndexSql) {
68
+ const match = createIndexSql.match(/\)\s*WHERE\s+([\s\S]+?)\s*;?\s*$/i);
69
+ if (!match) return "";
70
+ return normalizeIndexPredicate(match[1]);
71
+ }
28
72
  class SchemaComparer {
29
73
  db;
30
74
  options;
@@ -89,7 +133,13 @@ class SchemaComparer {
89
133
  }
90
134
  const columnChanges = this.compareColumns(tableName, manifest, dbSchema);
91
135
  changes.push(...columnChanges);
92
- const indexChanges = this.compareIndexes(tableName, manifest, dbSchema);
136
+ const dbIndexPredicates = await this.getDbIndexPredicates(tableName);
137
+ const indexChanges = this.compareIndexes(
138
+ tableName,
139
+ manifest,
140
+ dbSchema,
141
+ dbIndexPredicates
142
+ );
93
143
  changes.push(...indexChanges);
94
144
  return changes;
95
145
  }
@@ -190,7 +240,7 @@ class SchemaComparer {
190
240
  /**
191
241
  * Compare indexes between manifest and database
192
242
  *
193
- * Three classes of drift the differ now detects:
243
+ * Four classes of drift the differ now detects:
194
244
  *
195
245
  * 1. **Missing index** — manifest has an index neither the DB has by name
196
246
  * nor any equivalent-by-signature. Emit `add_index`. (Issue #741: the
@@ -198,11 +248,13 @@ class SchemaComparer {
198
248
  * classes register indexes with different name prefixes.)
199
249
  *
200
250
  * 2. **Same-name shape drift** — DB has an index with the manifest's name,
201
- * but its columns or uniqueness flag differ. This is the failure mode
202
- * in issue #1165: `tenants_slug_context_meta_type_idx` exists but is
203
- * non-unique, while the manifest declares it unique. Emit
204
- * `drop_index` + `add_index` so the next migrate cycle recreates it
205
- * with the correct shape.
251
+ * but its columns, uniqueness flag, or partial-index `WHERE` predicate
252
+ * differ. This covers the uniqueness flip in issue #1165
253
+ * (`tenants_slug_context_meta_type_idx` materialized non-unique while
254
+ * the manifest declares it unique) and the predicate drift in issue
255
+ * #1692 (a partial index whose `WHERE` clause was added, removed, or
256
+ * altered). Emit `drop_index` + `add_index` so the next migrate cycle
257
+ * recreates it with the correct shape.
206
258
  *
207
259
  * 3. **Orphan in DB** — DB has an index with no manifest counterpart by
208
260
  * name and no signature equivalent. Emit `drop_index` *only* when the
@@ -210,15 +262,34 @@ class SchemaComparer {
210
262
  * PostgreSQL implicit indexes (`*_pkey`, `*_key`) — those are owned by
211
263
  * table-level constraints and need a separate `DROP CONSTRAINT` path
212
264
  * that the differ does not emit yet.
265
+ *
266
+ * 4. **Partial-index predicate drift / collision** — two indexes on the
267
+ * same column(s) and uniqueness that differ only by their `WHERE`
268
+ * predicate (e.g. distinct STI child partial indexes) are no longer
269
+ * collapsed to one signature, so the signature-equivalence path (b)
270
+ * won't claim one for the other.
271
+ *
272
+ * @param dbIndexPredicates - Normalized `WHERE` predicate per DB index
273
+ * name from {@link getDbIndexPredicates}. `null` means predicate
274
+ * introspection was unavailable for this engine/adapter, in which case
275
+ * the comparison falls back to predicate-unaware signatures (the prior
276
+ * behavior) so existing partial indexes are never flagged as false drift.
213
277
  */
214
- compareIndexes(tableName, manifest, dbSchema) {
278
+ compareIndexes(tableName, manifest, dbSchema, dbIndexPredicates = null) {
215
279
  const changes = [];
280
+ const predicateAware = dbIndexPredicates !== null;
281
+ const dbPredicateFor = (name) => predicateAware ? dbIndexPredicates?.get(name) ?? "" : "";
282
+ const manifestPredicateFor = (idx) => predicateAware ? normalizeIndexPredicate(idx.where) : "";
216
283
  const dbIndexesByName = /* @__PURE__ */ new Map();
217
284
  const dbIndexSignatures = /* @__PURE__ */ new Map();
218
285
  for (const idx of dbSchema.indexes) {
219
286
  const unique = idx.unique ?? false;
220
287
  dbIndexesByName.set(idx.name, { columns: idx.columns, unique });
221
- const signature = this.getIndexSignature(idx.columns, unique);
288
+ const signature = this.getIndexSignature(
289
+ idx.columns,
290
+ unique,
291
+ dbPredicateFor(idx.name)
292
+ );
222
293
  let bucket = dbIndexSignatures.get(signature);
223
294
  if (!bucket) {
224
295
  bucket = /* @__PURE__ */ new Set();
@@ -228,11 +299,17 @@ class SchemaComparer {
228
299
  }
229
300
  const manifestSignatureSet = /* @__PURE__ */ new Set();
230
301
  for (const idx of manifest.indexes) {
231
- manifestSignatureSet.add(this.getIndexSignature(idx));
302
+ manifestSignatureSet.add(
303
+ this.getIndexSignature(idx, void 0, manifestPredicateFor(idx))
304
+ );
232
305
  }
233
306
  const claimedDbIndexes = /* @__PURE__ */ new Set();
234
307
  for (const idx of manifest.indexes) {
235
- const manifestSignature = this.getIndexSignature(idx);
308
+ const manifestSignature = this.getIndexSignature(
309
+ idx,
310
+ void 0,
311
+ manifestPredicateFor(idx)
312
+ );
236
313
  const dbByName = dbIndexesByName.get(idx.name);
237
314
  if (dbByName) {
238
315
  claimedDbIndexes.add(idx.name);
@@ -241,7 +318,8 @@ class SchemaComparer {
241
318
  }
242
319
  const dbSignature = this.getIndexSignature(
243
320
  dbByName.columns,
244
- dbByName.unique
321
+ dbByName.unique,
322
+ dbPredicateFor(idx.name)
245
323
  );
246
324
  if (dbSignature === manifestSignature) {
247
325
  continue;
@@ -282,7 +360,8 @@ class SchemaComparer {
282
360
  if (isProtectedDbIndexName(idx.name)) continue;
283
361
  const idxSignature = this.getIndexSignature(
284
362
  idx.columns,
285
- idx.unique ?? false
363
+ idx.unique ?? false,
364
+ dbPredicateFor(idx.name)
286
365
  );
287
366
  if (manifestSignatureSet.has(idxSignature)) continue;
288
367
  changes.push({
@@ -296,17 +375,21 @@ class SchemaComparer {
296
375
  return changes;
297
376
  }
298
377
  /**
299
- * Generate a signature for an index based on its columns and uniqueness.
300
- * Used for functional equivalence checking (Issue #741).
378
+ * Generate a signature for an index based on its columns, uniqueness, and
379
+ * (normalized) partial-index predicate. Used for functional equivalence
380
+ * checking (Issue #741) and predicate-drift detection (Issue #1692).
301
381
  *
302
382
  * Note: Column order is preserved because it is semantically significant for
303
383
  * composite indexes. An index on (a, b) is NOT equivalent to (b, a) - they
304
384
  * have different query performance characteristics.
305
385
  *
306
- * Limitation: Partial indexes (with WHERE clauses) are not fully supported.
307
- * The database introspection layer doesn't provide WHERE clause information,
308
- * so two partial indexes with the same columns but different WHERE clauses
309
- * cannot be distinguished and may be incorrectly treated as equivalent.
386
+ * The trailing predicate component distinguishes partial indexes that share
387
+ * columns and uniqueness but differ by their `WHERE` clause (e.g. distinct
388
+ * STI child partial indexes). Callers pass the already-normalized predicate
389
+ * so both the manifest (desired) and introspected (DB) sides compare equal
390
+ * for semantically-identical clauses. An empty string means "no predicate"
391
+ * (a non-partial index) and is also used on both sides when predicate
392
+ * introspection is unavailable, preserving the prior behavior.
310
393
  *
311
394
  * For JSON-path indexes (`@meta({ indexed: true })`) the signature is
312
395
  * derived from the JSON path instead of an empty column list, so the
@@ -314,17 +397,91 @@ class SchemaComparer {
314
397
  *
315
398
  * @param idxOrColumns - Either an IndexDefinition or a column array (legacy)
316
399
  * @param uniqueArg - Unique flag (used when first arg is a column array)
400
+ * @param predicateArg - Normalized partial-index predicate (default '')
317
401
  * @returns Signature string
318
402
  */
319
- getIndexSignature(idxOrColumns, uniqueArg) {
403
+ getIndexSignature(idxOrColumns, uniqueArg, predicateArg = "") {
320
404
  if (Array.isArray(idxOrColumns)) {
321
- return `${idxOrColumns.join(",")}:${Boolean(uniqueArg)}`;
405
+ return `${idxOrColumns.join(",")}:${Boolean(uniqueArg)}:${predicateArg}`;
322
406
  }
323
407
  const idx = idxOrColumns;
324
408
  if (isJsonPathIndex(idx) && idx.jsonPath) {
325
- return `json:${idx.jsonPath.column}.${idx.jsonPath.path}:${Boolean(idx.unique)}`;
409
+ return `json:${idx.jsonPath.column}.${idx.jsonPath.path}:${Boolean(idx.unique)}:${predicateArg}`;
410
+ }
411
+ return `${(idx.columns ?? []).join(",")}:${Boolean(idx.unique)}:${predicateArg}`;
412
+ }
413
+ /**
414
+ * Whether the active engine supports partial indexes (`CREATE INDEX … WHERE`).
415
+ *
416
+ * SQLite and PostgreSQL do. DuckDB rejects them outright, and the JSON
417
+ * adapter is DuckDB-backed, so on those engines a "partial" index can only
418
+ * ever exist as a full index. Treating the predicate as significant there
419
+ * would (a) flag existing full indexes as false drift and (b) emit
420
+ * `CREATE INDEX … WHERE` DDL the engine rejects, breaking the migration.
421
+ * Gating on this keeps both the comparison and the generated DDL aligned
422
+ * with what the engine actually accepts (a partial index degrades to a
423
+ * full index), matching the pre-#1692 behavior on those engines.
424
+ */
425
+ supportsPartialIndexes() {
426
+ return this.engine === "sqlite" || this.engine === "postgres";
427
+ }
428
+ /**
429
+ * Introspect partial-index predicates for a table, keyed by index name.
430
+ *
431
+ * `getTableSchema()` (the @happyvertical/sql introspection) returns only
432
+ * name/columns/unique, so the `WHERE` predicate is read directly here:
433
+ *
434
+ * - PostgreSQL: `pg_indexes.indexdef` carries the full CREATE INDEX text.
435
+ * - SQLite: the `sqlite_master.sql` column carries the original CREATE INDEX
436
+ * text.
437
+ *
438
+ * Engines that don't support partial indexes (DuckDB / the DuckDB-backed
439
+ * JSON adapter) short-circuit to `null` so the comparison stays
440
+ * predicate-unaware there — see {@link supportsPartialIndexes}.
441
+ *
442
+ * Non-partial indexes are omitted from the map (callers treat a missing
443
+ * entry as the empty predicate). Returns `null` when the catalog query
444
+ * fails — e.g. an adapter exposing neither catalog — so the index
445
+ * comparison can fall back to predicate-unaware behavior rather than
446
+ * flagging every existing partial index as false drift.
447
+ */
448
+ async getDbIndexPredicates(tableName) {
449
+ if (!this.supportsPartialIndexes()) {
450
+ return null;
451
+ }
452
+ const predicates = /* @__PURE__ */ new Map();
453
+ try {
454
+ if (this.engine === "postgres") {
455
+ const result2 = await this.db.query(
456
+ `SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename = ${this.quoteLiteral(
457
+ tableName
458
+ )}`
459
+ );
460
+ for (const row of result2.rows) {
461
+ if (!row.indexname || !row.indexdef) continue;
462
+ const predicate = extractIndexPredicate(row.indexdef);
463
+ if (predicate) predicates.set(row.indexname, predicate);
464
+ }
465
+ return predicates;
466
+ }
467
+ const result = await this.db.query(
468
+ `SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${this.quoteLiteral(
469
+ tableName
470
+ )} AND name NOT LIKE 'sqlite_%'`
471
+ );
472
+ for (const row of result.rows) {
473
+ if (!row.name || !row.sql) continue;
474
+ const predicate = extractIndexPredicate(row.sql);
475
+ if (predicate) predicates.set(row.name, predicate);
476
+ }
477
+ return predicates;
478
+ } catch (err) {
479
+ logger.debug(
480
+ `[SchemaComparer] Partial-index predicate introspection unavailable for ${tableName}; falling back to predicate-unaware index comparison`,
481
+ { error: err instanceof Error ? err.message : String(err) }
482
+ );
483
+ return null;
326
484
  }
327
- return `${(idx.columns ?? []).join(",")}:${Boolean(idx.unique)}`;
328
485
  }
329
486
  /**
330
487
  * Get list of existing tables from database
@@ -547,12 +704,26 @@ class SchemaComparer {
547
704
  return `ALTER TABLE ${this.quoteIdentifier(tableName)} DROP COLUMN ${this.quoteIdentifier(colName)}`;
548
705
  }
549
706
  /**
550
- * Generate SQL for adding an index
707
+ * Generate SQL for adding an index.
708
+ *
709
+ * On engines that support partial indexes (SQLite/PostgreSQL) this mirrors
710
+ * the canonical CREATE INDEX path in the DDL strategies: a partial index
711
+ * appends its `WHERE` predicate so a detected predicate add/alter (issue
712
+ * #1692) recreates the index with the correct partial condition rather than
713
+ * silently widening it to a full index. On DuckDB / the JSON adapter — which
714
+ * reject partial indexes — the predicate is dropped so the emitted DDL stays
715
+ * executable (a partial index degrades to a full index there). The predicate
716
+ * is trimmed and a redundant leading `WHERE` stripped for robustness.
551
717
  */
552
718
  generateAddIndexSQL(tableName, idx) {
553
719
  const uniqueStr = idx.unique ? "UNIQUE " : "";
554
720
  const target = renderIndexTarget(idx, this.engine);
555
- return `CREATE ${uniqueStr}INDEX ${this.quoteIdentifier(idx.name)} ON ${this.quoteIdentifier(tableName)} (${target})`;
721
+ let sql = `CREATE ${uniqueStr}INDEX ${this.quoteIdentifier(idx.name)} ON ${this.quoteIdentifier(tableName)} (${target})`;
722
+ const where = idx.where?.trim().replace(/^WHERE\s+/i, "");
723
+ if (this.supportsPartialIndexes() && where) {
724
+ sql += ` WHERE ${where}`;
725
+ }
726
+ return sql;
556
727
  }
557
728
  /**
558
729
  * Generate SQL for dropping an index.
@@ -594,8 +765,10 @@ function getSQLFromDiff(diff) {
594
765
  }
595
766
  export {
596
767
  SchemaComparer,
768
+ extractIndexPredicate,
597
769
  generateSchemaDiff,
598
770
  getSQLFromDiff,
599
- hasActionableChanges
771
+ hasActionableChanges,
772
+ normalizeIndexPredicate
600
773
  };
601
774
  //# sourceMappingURL=differ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"differ.js","sources":["../../src/migrations/differ.ts"],"sourcesContent":["/**\n * Schema Differ\n *\n * Compares manifest schemas to database schemas and generates\n * a SchemaDiff with the differences.\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { detectEngine, getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaChange,\n SchemaDefinition,\n SchemaDiff,\n SQLDataType,\n} from '../schema/types.js';\nimport { isJsonPathIndex, renderIndexTarget } from '../schema/utils.js';\nimport type { DatabaseInterface, SqlTableSchemaInfo } from './types.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Valid SQLDataType values for validation\n */\nconst VALID_SQL_DATA_TYPES: Set<SQLDataType> = new Set([\n 'TEXT',\n 'INTEGER',\n 'REAL',\n 'BLOB',\n 'BOOLEAN',\n 'JSON',\n 'TIMESTAMP',\n 'UUID',\n]);\n\ninterface GeneratedTypeUpgradeSQL {\n sql: string;\n statements?: string[];\n}\n\n/**\n * Check if a string is a valid SQLDataType\n */\nfunction isValidSQLDataType(type: string): type is SQLDataType {\n return VALID_SQL_DATA_TYPES.has(type as SQLDataType);\n}\n\n/**\n * Options for schema comparison\n */\nexport interface DiffOptions {\n /** Include dropped tables in diff (default: false for safety) */\n includeDroppedTables?: boolean;\n /** Include dropped columns in diff (default: false for safety) */\n includeDroppedColumns?: boolean;\n /**\n * Drop indexes that exist in the database but are absent from the manifest\n * AND are not functionally equivalent to anything in the manifest. Default:\n * false. The differ always skips primary-key indexes (`*_pkey`) and the\n * implicit indexes that PostgreSQL creates from inline UNIQUE constraints\n * (`*_key`) — those are owned by table-level constraints, not by the\n * index list, and dropping them here would break the constraint.\n */\n includeDroppedIndexes?: boolean;\n /** Ignore type mismatches (just log warnings) */\n ignoreTypeMismatches?: boolean;\n /**\n * Explicit engine hint forwarded to `detectEngine` when picking the DDL\n * strategy used for *existing-table* SQL (ALTER/CREATE INDEX/etc.). Use\n * this when `db.url` is empty or ambiguous (e.g. JSON adapter, in-memory\n * wrappers where the URL lives on `db.config?.url`). Without it the\n * comparer falls back to URL-only detection, which can produce SQLite-\n * flavored SQL on a connection whose caller meant Postgres or DuckDB.\n */\n engineHint?: string;\n}\n\n/**\n * Suffix patterns for indexes that the differ refuses to drop.\n * - `_pkey`: PostgreSQL primary key implicit index.\n * - `_key`: PostgreSQL implicit index for inline `UNIQUE (...)` table\n * constraints. Dropping these by name does not drop the underlying\n * constraint, and dropping the constraint requires a separate DDL path\n * (`ALTER TABLE ... DROP CONSTRAINT`) the differ does not emit today.\n */\nconst PROTECTED_INDEX_SUFFIXES = ['_pkey', '_key'];\n\nfunction isProtectedDbIndexName(name: string): boolean {\n return PROTECTED_INDEX_SUFFIXES.some((suffix) => name.endsWith(suffix));\n}\n\nfunction resolveDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseInterface & {\n config?: { url?: string };\n };\n return db.url || dbWithConfig.config?.url || '';\n}\n\n/**\n * SchemaComparer class for comparing manifest schemas to database\n */\nexport class SchemaComparer {\n private db: DatabaseInterface;\n private options: DiffOptions;\n private engine: DatabaseEngine;\n private ddlStrategy: ReturnType<typeof getDDLStrategy>;\n\n constructor(db: DatabaseInterface, options: DiffOptions = {}) {\n this.db = db;\n this.options = {\n includeDroppedTables: false,\n includeDroppedColumns: false,\n includeDroppedIndexes: false,\n ignoreTypeMismatches: false,\n ...options,\n };\n // Use the shared detectEngine utility for consistent detection.\n // Handles :memory:, .json, and other edge cases. The JSON adapter is\n // detected structurally (it exposes `exportTable`) because its url can be\n // empty; otherwise fall back to URL-based detection, where `engineHint`\n // lets callers override when `db.url` is empty or points at an adapter\n // whose engine isn't obvious from the URL alone (some in-memory wrappers).\n this.engine =\n typeof (this.db as { exportTable?: unknown }).exportTable === 'function'\n ? 'json'\n : detectEngine(resolveDatabaseUrl(this.db), this.options.engineHint);\n this.ddlStrategy = getDDLStrategy(this.engine);\n }\n\n /**\n * Compare manifest schemas to database and return differences\n */\n async compare(\n manifestSchemas: Record<string, SchemaDefinition>,\n ): Promise<SchemaDiff> {\n const diff: SchemaDiff = {\n added_tables: [],\n dropped_tables: [],\n changes: [],\n has_changes: false,\n };\n\n // Get list of existing tables\n const existingTables = await this.getExistingTables();\n\n // Check each manifest schema against database\n for (const [tableName, schema] of Object.entries(manifestSchemas)) {\n if (!existingTables.has(tableName)) {\n // Table doesn't exist - add to added_tables\n diff.added_tables.push(schema);\n diff.has_changes = true;\n } else {\n // Table exists - compare columns and indexes\n const tableChanges = await this.compareTable(tableName, schema);\n if (tableChanges.length > 0) {\n diff.changes.push(...tableChanges);\n diff.has_changes = true;\n }\n }\n }\n\n // Check for dropped tables (if enabled)\n if (this.options.includeDroppedTables) {\n for (const tableName of existingTables) {\n // Skip system tables\n if (tableName.startsWith('_smrt_') || tableName.startsWith('sqlite_')) {\n continue;\n }\n if (!manifestSchemas[tableName]) {\n diff.dropped_tables.push(tableName);\n diff.has_changes = true;\n }\n }\n }\n\n return diff;\n }\n\n /**\n * Compare a single table's schema to manifest\n */\n async compareTable(\n tableName: string,\n manifest: SchemaDefinition,\n ): Promise<SchemaChange[]> {\n const changes: SchemaChange[] = [];\n\n // Get current table schema from database\n const dbSchema = await this.db.getTableSchema?.(tableName);\n if (!dbSchema) {\n // Table doesn't exist - this is an add_table case\n return changes;\n }\n\n // Compare columns\n const columnChanges = this.compareColumns(tableName, manifest, dbSchema);\n changes.push(...columnChanges);\n\n // Compare indexes\n const indexChanges = this.compareIndexes(tableName, manifest, dbSchema);\n changes.push(...indexChanges);\n\n return changes;\n }\n\n /**\n * Compare columns between manifest and database\n */\n private compareColumns(\n tableName: string,\n manifest: SchemaDefinition,\n dbSchema: SqlTableSchemaInfo,\n ): SchemaChange[] {\n const changes: SchemaChange[] = [];\n const dbColumnNames = new Set(Object.keys(dbSchema.columns));\n\n // Check for new and modified columns\n for (const [colName, colDef] of Object.entries(manifest.columns)) {\n if (!dbColumnNames.has(colName)) {\n // Column doesn't exist - add it\n changes.push({\n type: 'add_column',\n table: tableName,\n name: colName,\n column: colDef,\n sql: this.generateAddColumnSQL(tableName, colName, colDef),\n });\n } else {\n // Column exists - check for type mismatch\n const dbCol = dbSchema.columns[colName];\n\n // Map manifest's abstract type to engine-specific type\n // e.g., JSON → TEXT for SQLite, JSON → JSONB for PostgreSQL\n // Validate the manifest type before mapping\n const manifestType = colDef.type;\n if (!isValidSQLDataType(manifestType)) {\n // Invalid manifest type - treat as TEXT (safest fallback)\n logger.warn(\n `[SchemaComparer] Invalid manifest type \"${manifestType}\" for ${tableName}.${colName}, treating as TEXT`,\n );\n }\n const validatedType: SQLDataType = isValidSQLDataType(manifestType)\n ? manifestType\n : 'TEXT';\n const expectedEngineType = this.ddlStrategy.mapType(validatedType);\n const normalizedExpected = this.normalizeType(expectedEngineType);\n const normalizedActual = this.normalizeType(dbCol.type);\n\n // R11: native `uuid` and `text` are interchangeable for SMRT-owned\n // identifiers/references, but not for arbitrary provenance text. Keep\n // the tolerance directional:\n // - manifest UUID + DB text is tolerated for structural ID/ref\n // columns so old deployments are not forced into native UUID.\n // - manifest TEXT + DB uuid is tolerated only for structural ID/ref\n // columns that are intentionally UUID-compatible.\n // Plain TEXT columns with DB uuid now surface as repairable drift.\n const isUuidTextEquivalent = this.isUuidTextEquivalentColumn(\n colName,\n colDef,\n normalizedExpected,\n normalizedActual,\n );\n\n // #1335: native `json`/`jsonb` (DB) and `text` (manifest) are\n // interchangeable for SMRT — the convention is to serialize JSON values\n // into TEXT columns, and a native-json column already holds exactly that\n // data. So the differ must NOT flag a json<->text difference in EITHER\n // direction:\n // - manifest TEXT vs DB json (native-json column, text-convention manifest)\n // - manifest JSON vs DB text (the canary case: an enum/plain field\n // mis-inferred as JSON by a downstream scanner, sitting on a real\n // `text` column holding bare values like 'active')\n // Generating an ALTER here is pure churn at best and data-destroying at\n // worst: `status::jsonb` on a column holding 'active' raises\n // \"invalid input syntax for type json\" and aborts the whole atomic\n // migration. Like the uuid/text tolerance, this lives at the equality\n // gate only (not in `normalizeType`) so `isCompatibleTypeUpgrade` still\n // treats JSON and TEXT as distinct buckets for OTHER upgrade paths.\n const isJsonTextEquivalent =\n (normalizedExpected === 'JSON' && normalizedActual === 'TEXT') ||\n (normalizedExpected === 'TEXT' && normalizedActual === 'JSON');\n\n if (\n normalizedExpected !== normalizedActual &&\n !isUuidTextEquivalent &&\n !isJsonTextEquivalent\n ) {\n // Check if this is a safe type upgrade that SMRT can handle\n // Since SMRT owns the data lifecycle, we know the intent from the manifest\n if (this.isCompatibleTypeUpgrade(colDef.type, dbCol.type)) {\n // Generate type upgrade SQL\n const generatedSQL = this.generateTypeUpgradeSQL(\n tableName,\n colName,\n colDef,\n dbCol.type,\n );\n changes.push({\n type: 'type_upgrade',\n table: tableName,\n name: colName,\n column: colDef,\n mismatch: {\n expected: colDef.type,\n actual: dbCol.type,\n },\n sql: generatedSQL.sql,\n ...(generatedSQL.statements\n ? { sqlStatements: generatedSQL.statements }\n : {}),\n });\n } else if (!this.options.ignoreTypeMismatches) {\n changes.push({\n type: 'type_mismatch',\n table: tableName,\n name: colName,\n mismatch: {\n expected: colDef.type,\n actual: dbCol.type,\n },\n });\n }\n }\n }\n }\n\n // Check for dropped columns (if enabled)\n if (this.options.includeDroppedColumns) {\n const manifestColumnNames = new Set(Object.keys(manifest.columns));\n for (const colName of dbColumnNames) {\n if (!manifestColumnNames.has(colName)) {\n changes.push({\n type: 'drop_column',\n table: tableName,\n name: colName,\n sql: this.generateDropColumnSQL(tableName, colName),\n });\n }\n }\n }\n\n return changes;\n }\n\n private isUuidTextEquivalentColumn(\n columnName: string,\n colDef: ColumnDefinition,\n normalizedExpected: string,\n normalizedActual: string,\n ): boolean {\n const expectedUuidActualText =\n normalizedExpected === 'UUID' && normalizedActual === 'TEXT';\n const expectedTextActualUuid =\n normalizedExpected === 'TEXT' && normalizedActual === 'UUID';\n\n if (!expectedUuidActualText && !expectedTextActualUuid) {\n return false;\n }\n\n return this.isStructuralUuidCompatibleColumn(columnName, colDef);\n }\n\n private isStructuralUuidCompatibleColumn(\n columnName: string,\n colDef: ColumnDefinition,\n ): boolean {\n return (\n colDef.primaryKey === true ||\n Boolean(colDef.foreignKey) ||\n colDef.referenceKind === 'id' ||\n colDef.referenceKind === 'foreignKey' ||\n colDef.referenceKind === 'crossPackageRef' ||\n colDef.referenceKind === 'tenantId' ||\n (columnName === 'id' && colDef.type === 'TEXT')\n );\n }\n\n /**\n * Compare indexes between manifest and database\n *\n * Three classes of drift the differ now detects:\n *\n * 1. **Missing index** — manifest has an index neither the DB has by name\n * nor any equivalent-by-signature. Emit `add_index`. (Issue #741: the\n * signature check protects against creating duplicates when STI child\n * classes register indexes with different name prefixes.)\n *\n * 2. **Same-name shape drift** — DB has an index with the manifest's name,\n * but its columns or uniqueness flag differ. This is the failure mode\n * in issue #1165: `tenants_slug_context_meta_type_idx` exists but is\n * non-unique, while the manifest declares it unique. Emit\n * `drop_index` + `add_index` so the next migrate cycle recreates it\n * with the correct shape.\n *\n * 3. **Orphan in DB** — DB has an index with no manifest counterpart by\n * name and no signature equivalent. Emit `drop_index` *only* when the\n * caller opts in via `includeDroppedIndexes`, and even then never for\n * PostgreSQL implicit indexes (`*_pkey`, `*_key`) — those are owned by\n * table-level constraints and need a separate `DROP CONSTRAINT` path\n * that the differ does not emit yet.\n */\n private compareIndexes(\n tableName: string,\n manifest: SchemaDefinition,\n dbSchema: SqlTableSchemaInfo,\n ): SchemaChange[] {\n const changes: SchemaChange[] = [];\n\n // Index DB indexes by name and by signature for fast lookup.\n // dbIndexSignatures groups *all* DB index names sharing a signature so\n // duplicates under different names all get claimed by a single matching\n // manifest entry — otherwise the orphan sweep would drop the un-claimed\n // siblings even though they are functionally equivalent to the manifest.\n const dbIndexesByName = new Map<\n string,\n { columns: string[]; unique: boolean }\n >();\n const dbIndexSignatures = new Map<string, Set<string>>();\n for (const idx of dbSchema.indexes) {\n const unique = idx.unique ?? false;\n dbIndexesByName.set(idx.name, { columns: idx.columns, unique });\n const signature = this.getIndexSignature(idx.columns, unique);\n let bucket = dbIndexSignatures.get(signature);\n if (!bucket) {\n bucket = new Set();\n dbIndexSignatures.set(signature, bucket);\n }\n bucket.add(idx.name);\n }\n\n // Manifest signatures — used during the orphan sweep to skip DB indexes\n // that match a manifest entry's signature even if no specific manifest\n // entry \"claimed\" them by name.\n const manifestSignatureSet = new Set<string>();\n for (const idx of manifest.indexes) {\n manifestSignatureSet.add(this.getIndexSignature(idx));\n }\n\n // Track which DB indexes a manifest entry has claimed, so the orphan\n // pass below doesn't re-flag indexes that match by signature alone.\n const claimedDbIndexes = new Set<string>();\n\n for (const idx of manifest.indexes) {\n const manifestSignature = this.getIndexSignature(idx);\n\n // (a) Same name in DB — verify shape matches.\n const dbByName = dbIndexesByName.get(idx.name);\n if (dbByName) {\n claimedDbIndexes.add(idx.name);\n\n // JSON-path indexes (`@meta({ indexed: true })`) cannot be reliably\n // compared by DB introspection — SQLite expression indexes surface\n // as `[null]` columns, so the signature would always mismatch and\n // every diff run would emit drop+recreate. Trust the name match\n // here; if the json path itself changes, the index name changes\n // too (we encode the field name into it), so a name match is a\n // stronger guarantee than the column list for this index family.\n if (isJsonPathIndex(idx)) {\n continue;\n }\n\n const dbSignature = this.getIndexSignature(\n dbByName.columns,\n dbByName.unique,\n );\n if (dbSignature === manifestSignature) {\n continue; // Same name, same shape — nothing to do.\n }\n\n // Same name, drifted shape. Most often this is a uniqueness flip\n // (issue #1165: 3-column index materialized non-unique). Recreate.\n //\n // Rollback caveat: the auto-generated DOWN script for the\n // `add_index` half drops the (newly correct) index, and the\n // `drop_index` half has no DOWN. Rolling back a recreate leaves\n // the table without the index entirely instead of restoring the\n // wrong-shape original. Capturing the original shape would\n // require richer DB introspection than the differ currently has,\n // so this asymmetry is accepted — the failure mode after an\n // un-rolled-back recreate is \"missing index\" rather than\n // \"permanently broken UPSERT,\" which is recoverable.\n changes.push({\n type: 'drop_index',\n table: tableName,\n name: idx.name,\n sql: this.generateDropIndexSQL(idx.name),\n });\n changes.push({\n type: 'add_index',\n table: tableName,\n name: idx.name,\n index: idx,\n sql: this.generateAddIndexSQL(tableName, idx),\n });\n continue;\n }\n\n // (b) Different name in DB but functionally equivalent — keep as-is.\n // Claim *every* DB name sharing this signature so duplicate-shape\n // indexes (e.g., a stale `<name>_idx` plus the implicit `<name>_key`\n // from the same constraint) all survive the orphan sweep.\n const equivalentIndexNames = dbIndexSignatures.get(manifestSignature);\n if (equivalentIndexNames && equivalentIndexNames.size > 0) {\n for (const name of equivalentIndexNames) {\n claimedDbIndexes.add(name);\n }\n continue;\n }\n\n // (c) Genuinely missing — add it.\n changes.push({\n type: 'add_index',\n table: tableName,\n name: idx.name,\n index: idx,\n sql: this.generateAddIndexSQL(tableName, idx),\n });\n }\n\n // Orphan-index sweep (opt-in via includeDroppedIndexes).\n if (this.options.includeDroppedIndexes) {\n for (const idx of dbSchema.indexes) {\n if (claimedDbIndexes.has(idx.name)) continue;\n if (isProtectedDbIndexName(idx.name)) continue;\n\n // Belt-and-suspenders: even if a DB index wasn't formally claimed\n // by a manifest entry (e.g., shape-drift recreate consumed the\n // claim slot), don't drop it if its signature still matches\n // something the manifest declares. That would contradict the\n // option doc (\"not functionally equivalent to anything in the\n // manifest\") and risk dropping a still-needed index.\n const idxSignature = this.getIndexSignature(\n idx.columns,\n idx.unique ?? false,\n );\n if (manifestSignatureSet.has(idxSignature)) continue;\n\n changes.push({\n type: 'drop_index',\n table: tableName,\n name: idx.name,\n sql: this.generateDropIndexSQL(idx.name),\n });\n }\n }\n\n return changes;\n }\n\n /**\n * Generate a signature for an index based on its columns and uniqueness.\n * Used for functional equivalence checking (Issue #741).\n *\n * Note: Column order is preserved because it is semantically significant for\n * composite indexes. An index on (a, b) is NOT equivalent to (b, a) - they\n * have different query performance characteristics.\n *\n * Limitation: Partial indexes (with WHERE clauses) are not fully supported.\n * The database introspection layer doesn't provide WHERE clause information,\n * so two partial indexes with the same columns but different WHERE clauses\n * cannot be distinguished and may be incorrectly treated as equivalent.\n *\n * For JSON-path indexes (`@meta({ indexed: true })`) the signature is\n * derived from the JSON path instead of an empty column list, so the\n * differ can distinguish two jsonPath indexes against different paths.\n *\n * @param idxOrColumns - Either an IndexDefinition or a column array (legacy)\n * @param uniqueArg - Unique flag (used when first arg is a column array)\n * @returns Signature string\n */\n private getIndexSignature(\n idxOrColumns: IndexDefinition | string[],\n uniqueArg?: boolean,\n ): string {\n if (Array.isArray(idxOrColumns)) {\n return `${idxOrColumns.join(',')}:${Boolean(uniqueArg)}`;\n }\n const idx = idxOrColumns;\n if (isJsonPathIndex(idx) && idx.jsonPath) {\n return `json:${idx.jsonPath.column}.${idx.jsonPath.path}:${Boolean(idx.unique)}`;\n }\n return `${(idx.columns ?? []).join(',')}:${Boolean(idx.unique)}`;\n }\n\n /**\n * Get list of existing tables from database\n */\n private async getExistingTables(): Promise<Set<string>> {\n let query: string;\n if (this.engine === 'postgres') {\n query = `SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`;\n } else {\n // SQLite and DuckDB\n query = `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`;\n }\n\n const result = await this.db.query(query);\n const rows = result.rows as { name?: string; table_name?: string }[];\n return new Set(\n rows.map((r) => r.name || r.table_name || '').filter(Boolean),\n );\n }\n\n /**\n * Normalize SQL types for comparison\n */\n private normalizeType(type: string): string {\n const upper = type.toUpperCase().trim();\n\n // Integer types\n if (/^(INTEGER|INT|BIGINT|SMALLINT|TINYINT)$/i.test(upper)) {\n return 'INTEGER';\n }\n\n // Text types\n if (/^(TEXT|CLOB|STRING|VARCHAR|CHAR)/i.test(upper)) {\n return 'TEXT';\n }\n\n // UUID normalizes to its own bucket — deliberately NOT folded into TEXT.\n // The text<->uuid drift tolerance (R11) is applied at the equality gate\n // in `compare()` only, so that `isCompatibleTypeUpgrade` (which also\n // calls normalizeType) still treats `uuid` as distinct from text and\n // won't mis-classify e.g. `uuid`->`timestamp` as a compatible\n // \"TEXT->TIMESTAMP\" upgrade.\n if (/^UUID$/i.test(upper)) {\n return 'UUID';\n }\n\n // Decimal types\n if (/^(REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER)/i.test(upper)) {\n return 'REAL';\n }\n\n // Boolean types\n if (/^(BOOLEAN|BOOL)/i.test(upper)) {\n return 'BOOLEAN';\n }\n\n // Date/time types\n if (/^(DATETIME|TIMESTAMP|DATE|TIME)/i.test(upper)) {\n return 'TIMESTAMP';\n }\n\n // Blob types\n if (/^(BLOB|BINARY|BYTEA)/i.test(upper)) {\n return 'BLOB';\n }\n\n // JSON types\n if (/^(JSON|JSONB)/i.test(upper)) {\n return 'JSON';\n }\n\n return upper;\n }\n\n /**\n * Check if a type change is a safe upgrade that can be auto-migrated.\n *\n * SMRT controls the data lifecycle for these columns, so we know:\n * - TEXT→JSON: The column stores JSON data serialized as text (arrays, objects)\n * - TEXT/JSON→TIMESTAMP: Legacy system columns stored timestamp strings\n * before newer manifests normalized the column type.\n * - INTEGER→REAL: Safe widening of integer to floating point\n * - TEXT/REAL→INTEGER on PostgreSQL: explicit data-checked repairs for\n * legacy integer columns that were previously stored as text/real.\n *\n * @param manifestType - The abstract type from the manifest (e.g., 'JSON')\n * @param dbType - The actual type in the database (e.g., 'TEXT')\n * @returns true if the change from dbType to manifestType is a safe upgrade\n */\n private isCompatibleTypeUpgrade(\n manifestType: string,\n dbType: string,\n ): boolean {\n const manifest = this.normalizeType(manifestType);\n const db = this.normalizeType(dbType);\n\n // TEXT → JSON is safe: SMRT serializes arrays/objects as JSON text\n // When the manifest says JSON, the data is already valid JSON in TEXT column\n if (manifest === 'JSON' && db === 'TEXT') {\n return true;\n }\n\n // JSON → TEXT is also safe (downgrade, but data is preserved as-is)\n if (manifest === 'TEXT' && db === 'JSON') {\n return true;\n }\n\n // UUID → TEXT is safe for plain text/provenance fields that were\n // mistakenly materialized as native uuid: the stored UUID value can be\n // rendered losslessly as text.\n if (manifest === 'TEXT' && db === 'UUID') {\n return true;\n }\n\n // INTEGER → REAL is safe (widening)\n if (manifest === 'REAL' && db === 'INTEGER') {\n return true;\n }\n\n // PostgreSQL can safely repair legacy integer columns when the generated\n // migration validates that every existing value is already an integer.\n if (\n this.engine === 'postgres' &&\n manifest === 'INTEGER' &&\n (db === 'TEXT' || db === 'REAL')\n ) {\n return true;\n }\n\n // TEXT/JSON → TIMESTAMP is a legacy-drift repair. Invalid values fail\n // explicitly during migration rather than being silently coerced.\n if (manifest === 'TIMESTAMP' && (db === 'TEXT' || db === 'JSON')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Generate SQL for a type upgrade migration.\n *\n * Engine-specific SQL:\n * - SQLite: TEXT and JSON are equivalent, no-op or comment\n * - DuckDB: ALTER COLUMN TYPE (native type conversion)\n * - PostgreSQL: ALTER COLUMN TYPE with USING clause\n */\n private generateTypeUpgradeSQL(\n tableName: string,\n colName: string,\n colDef: ColumnDefinition,\n dbType: string,\n ): GeneratedTypeUpgradeSQL {\n const quotedTable = this.quoteIdentifier(tableName);\n const quotedCol = this.quoteIdentifier(colName);\n const manifestType = colDef.type;\n\n // Validate manifestType before mapping\n const validatedType: SQLDataType = isValidSQLDataType(manifestType)\n ? manifestType\n : 'TEXT';\n const targetType = this.ddlStrategy.mapType(validatedType);\n\n switch (this.engine) {\n case 'sqlite':\n // SQLite has dynamic typing - TEXT and JSON are functionally equivalent\n // For SQLite, we just return a comment since no actual change is needed\n if (\n this.normalizeType(manifestType) === 'JSON' &&\n this.normalizeType(dbType) === 'TEXT'\n ) {\n return {\n sql: `-- SQLite: ${quotedCol} already stores JSON as TEXT (no change needed)`,\n };\n }\n // For other type upgrades, SQLite requires recreating the table\n return {\n sql: `-- SQLite: Type upgrade for ${quotedCol} requires table recreation`,\n };\n\n case 'postgres': {\n // PostgreSQL defaults must be dropped/reset around some type changes\n // so drift repairs can succeed even when an existing default cannot\n // be cast automatically to the target type.\n const manifestNormalized = this.normalizeType(manifestType);\n const dbNormalized = this.normalizeType(dbType);\n const preflightSQL =\n manifestNormalized === 'INTEGER' &&\n (dbNormalized === 'TEXT' || dbNormalized === 'REAL')\n ? this.generatePostgresIntegerPreflightSQL(\n quotedTable,\n quotedCol,\n tableName,\n colName,\n dbNormalized,\n )\n : null;\n const clauses: string[] = [];\n\n if (colDef.defaultValue !== undefined) {\n clauses.push(`ALTER COLUMN ${quotedCol} DROP DEFAULT`);\n }\n\n let typeClause = `ALTER COLUMN ${quotedCol} TYPE ${targetType}`;\n if (manifestNormalized === 'JSON' && dbNormalized === 'TEXT') {\n // #1335: a bare `${col}::jsonb` cast raises \"invalid input syntax for\n // type json\" on any row whose text is not already valid JSON (e.g. a\n // legacy enum column holding 'active'). `to_jsonb(col)` instead wraps\n // ANY text value as a JSON string and never errors, so a genuine\n // TEXT->JSON widening survives non-JSON legacy data. (Note: with the\n // json<->text equality tolerance added in this fix, the normal\n // compare path no longer reaches here; this keeps the SQL safe for\n // callers that construct a type_upgrade directly.)\n typeClause += ` USING to_jsonb(${quotedCol})`;\n } else if (manifestNormalized === 'TEXT' && dbNormalized === 'JSON') {\n // #1335: a native-json column cast back to text is value-preserving\n // (`::text` renders the stored JSON as its text form), so this arm is\n // safe. (Note: like the TEXT->JSON arm above, the json<->text equality\n // tolerance means the normal compare path no longer reaches here; this\n // keeps the SQL safe for callers that construct a type_upgrade\n // directly.)\n typeClause += ` USING ${quotedCol}::text`;\n } else if (manifestNormalized === 'TEXT' && dbNormalized === 'UUID') {\n typeClause += ` USING ${quotedCol}::text`;\n } else if (\n manifestNormalized === 'INTEGER' &&\n dbNormalized === 'TEXT'\n ) {\n typeClause += ` USING trim(${quotedCol}::text)::integer`;\n } else if (\n manifestNormalized === 'INTEGER' &&\n dbNormalized === 'REAL'\n ) {\n typeClause += ` USING ${quotedCol}::integer`;\n } else if (\n manifestNormalized === 'TIMESTAMP' &&\n (dbNormalized === 'TEXT' || dbNormalized === 'JSON')\n ) {\n typeClause += ` USING NULLIF(NULLIF(trim(both '\"' from ${quotedCol}::text), ''), 'null')::timestamp`;\n }\n\n clauses.push(typeClause);\n\n if (colDef.defaultValue !== undefined) {\n const formattedDefault = this.ddlStrategy.formatDefaultValue(\n colDef.defaultValue,\n validatedType,\n );\n const defaultSql =\n manifestNormalized === 'JSON'\n ? `${formattedDefault}::${targetType.toLowerCase()}`\n : formattedDefault;\n clauses.push(`ALTER COLUMN ${quotedCol} SET DEFAULT ${defaultSql}`);\n }\n\n const alterSql = `ALTER TABLE ${quotedTable} ${clauses.join(', ')}`;\n\n return preflightSQL\n ? { sql: alterSql, statements: [preflightSQL, alterSql] }\n : { sql: alterSql };\n }\n\n case 'duckdb':\n // DuckDB supports ALTER COLUMN TYPE for type conversions\n return {\n sql: `ALTER TABLE ${quotedTable} ALTER COLUMN ${quotedCol} TYPE ${targetType}`,\n };\n\n default: {\n // Escape special characters in type names for safe comment generation\n const safeDbType = dbType.replace(/[^\\w]/g, '_');\n const safeManifestType = manifestType.replace(/[^\\w]/g, '_');\n return {\n sql: `-- Type upgrade for ${quotedCol}: ${safeDbType} → ${safeManifestType}`,\n };\n }\n }\n }\n\n /**\n * Quote a SQL identifier\n */\n private quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * Generate a PostgreSQL preflight guard for narrowing legacy columns to\n * INTEGER. PostgreSQL's REAL→INTEGER cast rounds fractional values, so the\n * generated migration must fail before the ALTER can silently change data.\n */\n private generatePostgresIntegerPreflightSQL(\n quotedTable: string,\n quotedCol: string,\n tableName: string,\n colName: string,\n dbNormalized: string,\n ): string {\n const invalidCondition =\n dbNormalized === 'REAL'\n ? `${quotedCol} IS NOT NULL AND ${quotedCol} <> trunc(${quotedCol})`\n : `${quotedCol} IS NOT NULL AND trim(${quotedCol}::text) !~ '^[+-]?[0-9]+$'`;\n const message = `Cannot convert ${tableName}.${colName} to INTEGER: found non-integer values`;\n\n return `DO $$ BEGIN IF EXISTS (SELECT 1 FROM ${quotedTable} WHERE ${invalidCondition}) THEN RAISE EXCEPTION ${this.quoteLiteral(message)}; END IF; END $$`;\n }\n\n private quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Generate SQL for adding a column\n */\n private generateAddColumnSQL(\n tableName: string,\n colName: string,\n colDef: ColumnDefinition,\n ): string {\n // Build the ADD COLUMN definition inline (main) rather than delegating to\n // the DDL strategy's generateColumnDefinition: that builder is for CREATE\n // TABLE and would emit `PRIMARY KEY` (invalid in ALTER ... ADD COLUMN) and\n // suppress single-column UNIQUE on engines that require inline unique at\n // table-create time (DuckDB) — but an ADD COLUMN has no inline-constraint\n // pass, so the UNIQUE must be emitted here. mapType still maps abstract\n // types per dialect (UUID→native uuid / TEXT — R11); invalid types fall\n // back to TEXT, matching the compareColumns guard.\n const validatedType: SQLDataType = isValidSQLDataType(colDef.type)\n ? colDef.type\n : 'TEXT';\n if (!isValidSQLDataType(colDef.type)) {\n logger.warn(\n `[SchemaComparer] Invalid manifest type \"${colDef.type}\" for ${tableName}.${colName}, treating as TEXT`,\n );\n }\n\n const parts: string[] = [\n this.quoteIdentifier(colName),\n this.ddlStrategy.mapType(validatedType),\n ];\n\n if (colDef.notNull) {\n parts.push('NOT NULL');\n }\n if (colDef.unique) {\n parts.push('UNIQUE');\n }\n if (colDef.defaultValue !== undefined) {\n const defaultVal = this.ddlStrategy.formatDefaultValue(\n colDef.defaultValue,\n validatedType,\n );\n parts.push(`DEFAULT ${defaultVal}`);\n }\n if (colDef.check) {\n parts.push(`CHECK (${colDef.check})`);\n }\n\n const columnDefinition = parts.join(' ');\n\n return `ALTER TABLE ${this.quoteIdentifier(tableName)} ADD COLUMN ${columnDefinition}`;\n }\n\n /**\n * Generate SQL for dropping a column\n */\n private generateDropColumnSQL(tableName: string, colName: string): string {\n return `ALTER TABLE ${this.quoteIdentifier(tableName)} DROP COLUMN ${this.quoteIdentifier(colName)}`;\n }\n\n /**\n * Generate SQL for adding an index\n */\n private generateAddIndexSQL(tableName: string, idx: IndexDefinition): string {\n const uniqueStr = idx.unique ? 'UNIQUE ' : '';\n const target = renderIndexTarget(idx, this.engine);\n return `CREATE ${uniqueStr}INDEX ${this.quoteIdentifier(idx.name)} ON ${this.quoteIdentifier(tableName)} (${target})`;\n }\n\n /**\n * Generate SQL for dropping an index.\n *\n * This SQL is consumed by the manifest-driven execution path:\n *\n * - `db:migrate` runs the SQL we put in `change.sql` directly, with the\n * tracker's `executePostgresStatements` adding CONCURRENTLY when\n * `--postgres-safe` is on.\n *\n * PostgreSQL ends up with `CONCURRENTLY` when it should.\n * Keeping this method engine-agnostic also means the diff preview text\n * stays readable (no engine-specific noise) for engines like SQLite\n * where CONCURRENTLY isn't a thing.\n */\n private generateDropIndexSQL(indexName: string): string {\n return `DROP INDEX IF EXISTS ${this.quoteIdentifier(indexName)}`;\n }\n}\n\n/**\n * Generate a SchemaDiff from manifest and database\n */\nexport async function generateSchemaDiff(\n db: DatabaseInterface,\n manifestSchemas: Record<string, SchemaDefinition>,\n options: DiffOptions = {},\n): Promise<SchemaDiff> {\n const comparer = new SchemaComparer(db, options);\n return comparer.compare(manifestSchemas);\n}\n\n/**\n * Check if a diff has any actionable changes (excluding type mismatches)\n */\nexport function hasActionableChanges(diff: SchemaDiff): boolean {\n if (diff.added_tables.length > 0) return true;\n if (diff.dropped_tables.length > 0) return true;\n return diff.changes.some((c) => c.type !== 'type_mismatch');\n}\n\n/**\n * Get SQL statements from a diff for execution\n */\nexport function getSQLFromDiff(diff: SchemaDiff): string[] {\n const statements: string[] = [];\n\n // Add table creation (requires full DDL generation - not included here)\n // This is typically handled by ensureSchema()\n\n // Add column and index changes\n for (const change of diff.changes) {\n if (change.type !== 'type_mismatch') {\n statements.push(\n ...(change.sqlStatements ?? (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rations/differ.ts"],"sourcesContent":["/**\n * Schema Differ\n *\n * Compares manifest schemas to database schemas and generates\n * a SchemaDiff with the differences.\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { detectEngine, getDDLStrategy } from '../schema/ddl/index.js';\nimport type { DatabaseEngine } from '../schema/ddl/types.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaChange,\n SchemaDefinition,\n SchemaDiff,\n SQLDataType,\n} from '../schema/types.js';\nimport { isJsonPathIndex, renderIndexTarget } from '../schema/utils.js';\nimport type { DatabaseInterface, SqlTableSchemaInfo } from './types.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Valid SQLDataType values for validation\n */\nconst VALID_SQL_DATA_TYPES: Set<SQLDataType> = new Set([\n 'TEXT',\n 'INTEGER',\n 'REAL',\n 'BLOB',\n 'BOOLEAN',\n 'JSON',\n 'TIMESTAMP',\n 'UUID',\n]);\n\ninterface GeneratedTypeUpgradeSQL {\n sql: string;\n statements?: string[];\n}\n\n/**\n * Check if a string is a valid SQLDataType\n */\nfunction isValidSQLDataType(type: string): type is SQLDataType {\n return VALID_SQL_DATA_TYPES.has(type as SQLDataType);\n}\n\n/**\n * Options for schema comparison\n */\nexport interface DiffOptions {\n /** Include dropped tables in diff (default: false for safety) */\n includeDroppedTables?: boolean;\n /** Include dropped columns in diff (default: false for safety) */\n includeDroppedColumns?: boolean;\n /**\n * Drop indexes that exist in the database but are absent from the manifest\n * AND are not functionally equivalent to anything in the manifest. Default:\n * false. The differ always skips primary-key indexes (`*_pkey`) and the\n * implicit indexes that PostgreSQL creates from inline UNIQUE constraints\n * (`*_key`) — those are owned by table-level constraints, not by the\n * index list, and dropping them here would break the constraint.\n */\n includeDroppedIndexes?: boolean;\n /** Ignore type mismatches (just log warnings) */\n ignoreTypeMismatches?: boolean;\n /**\n * Explicit engine hint forwarded to `detectEngine` when picking the DDL\n * strategy used for *existing-table* SQL (ALTER/CREATE INDEX/etc.). Use\n * this when `db.url` is empty or ambiguous (e.g. JSON adapter, in-memory\n * wrappers where the URL lives on `db.config?.url`). Without it the\n * comparer falls back to URL-only detection, which can produce SQLite-\n * flavored SQL on a connection whose caller meant Postgres or DuckDB.\n */\n engineHint?: string;\n}\n\n/**\n * Suffix patterns for indexes that the differ refuses to drop.\n * - `_pkey`: PostgreSQL primary key implicit index.\n * - `_key`: PostgreSQL implicit index for inline `UNIQUE (...)` table\n * constraints. Dropping these by name does not drop the underlying\n * constraint, and dropping the constraint requires a separate DDL path\n * (`ALTER TABLE ... DROP CONSTRAINT`) the differ does not emit today.\n */\nconst PROTECTED_INDEX_SUFFIXES = ['_pkey', '_key'];\n\nfunction isProtectedDbIndexName(name: string): boolean {\n return PROTECTED_INDEX_SUFFIXES.some((suffix) => name.endsWith(suffix));\n}\n\nfunction resolveDatabaseUrl(db: DatabaseInterface): string {\n const dbWithConfig = db as DatabaseInterface & {\n config?: { url?: string };\n };\n return db.url || dbWithConfig.config?.url || '';\n}\n\n/**\n * Normalize a partial-index `WHERE` predicate so semantically-identical\n * clauses from different sources compare equal (issue #1692).\n *\n * The manifest stores predicates roughly as written (`_meta_type = 'Article'`),\n * SQLite/DuckDB echo the original CREATE INDEX text verbatim, and PostgreSQL\n * re-renders them with type casts and extra parentheses\n * (`((_meta_type)::text = 'Article'::text)`). Normalization:\n *\n * - strips a leading `WHERE` keyword,\n * - removes PostgreSQL `::type` casts (single-word type names — the only kind\n * SMRT-generated partial predicates produce, e.g. `_meta_type::text`),\n * - removes parentheses (SMRT only emits simple `col = 'literal'` predicates,\n * so grouping carries no meaning here),\n * - lowercases everything OUTSIDE single-quoted string literals (SQL keywords\n * and identifiers are case-insensitive; literals such as STI discriminator\n * class names are case-sensitive, so they are preserved verbatim),\n * - collapses whitespace and tightens spacing around comparison operators.\n *\n * Returns '' for an absent/empty predicate (i.e. a non-partial index).\n */\nexport function normalizeIndexPredicate(where?: string | null): string {\n if (!where) return '';\n const stripped = where.trim().replace(/^WHERE\\s+/i, '');\n if (!stripped) return '';\n\n let out = '';\n let i = 0;\n while (i < stripped.length) {\n if (stripped[i] === \"'\") {\n // Consume a single-quoted string literal verbatim, honoring the SQL\n // `''` escape for an embedded quote.\n let literal = \"'\";\n i++;\n while (i < stripped.length) {\n if (stripped[i] === \"'\") {\n if (stripped[i + 1] === \"'\") {\n literal += \"''\";\n i += 2;\n continue;\n }\n literal += \"'\";\n i++;\n break;\n }\n literal += stripped[i];\n i++;\n }\n out += literal;\n } else {\n let run = '';\n while (i < stripped.length && stripped[i] !== \"'\") {\n run += stripped[i];\n i++;\n }\n out += normalizeNonLiteralPredicateRun(run);\n }\n }\n return out;\n}\n\n/**\n * Normalize the non-literal portion of a predicate (everything outside a\n * single-quoted string literal). Type casts and parentheses are dropped,\n * keywords/identifiers are lowercased, and whitespace is canonicalized.\n */\nfunction normalizeNonLiteralPredicateRun(run: string): string {\n return run\n .replace(/::[A-Za-z_]\\w*/g, '') // drop single-word PostgreSQL type casts\n .replace(/[()]/g, '') // drop parentheses\n .toLowerCase()\n .replace(/\\s+/g, ' ')\n .replace(/\\s*([=<>!]+)\\s*/g, '$1') // tighten comparison operators\n .trim();\n}\n\n/**\n * Extract the normalized partial-index predicate from a `CREATE INDEX`\n * statement — the `WHERE` tail that follows the column-list close paren.\n * Works for both SQLite/DuckDB `sqlite_master.sql` text and PostgreSQL\n * `pg_indexes.indexdef`. Returns '' for a non-partial index.\n */\nexport function extractIndexPredicate(createIndexSql: string): string {\n // The predicate is the tail after the column-list ')': `... (cols) WHERE x`.\n // Anchoring on `) WHERE` (rather than a bare `WHERE`) avoids matching a\n // column literally named \"where\" inside the indexed column list.\n const match = createIndexSql.match(/\\)\\s*WHERE\\s+([\\s\\S]+?)\\s*;?\\s*$/i);\n if (!match) return '';\n return normalizeIndexPredicate(match[1]);\n}\n\n/**\n * SchemaComparer class for comparing manifest schemas to database\n */\nexport class SchemaComparer {\n private db: DatabaseInterface;\n private options: DiffOptions;\n private engine: DatabaseEngine;\n private ddlStrategy: ReturnType<typeof getDDLStrategy>;\n\n constructor(db: DatabaseInterface, options: DiffOptions = {}) {\n this.db = db;\n this.options = {\n includeDroppedTables: false,\n includeDroppedColumns: false,\n includeDroppedIndexes: false,\n ignoreTypeMismatches: false,\n ...options,\n };\n // Use the shared detectEngine utility for consistent detection.\n // Handles :memory:, .json, and other edge cases. The JSON adapter is\n // detected structurally (it exposes `exportTable`) because its url can be\n // empty; otherwise fall back to URL-based detection, where `engineHint`\n // lets callers override when `db.url` is empty or points at an adapter\n // whose engine isn't obvious from the URL alone (some in-memory wrappers).\n this.engine =\n typeof (this.db as { exportTable?: unknown }).exportTable === 'function'\n ? 'json'\n : detectEngine(resolveDatabaseUrl(this.db), this.options.engineHint);\n this.ddlStrategy = getDDLStrategy(this.engine);\n }\n\n /**\n * Compare manifest schemas to database and return differences\n */\n async compare(\n manifestSchemas: Record<string, SchemaDefinition>,\n ): Promise<SchemaDiff> {\n const diff: SchemaDiff = {\n added_tables: [],\n dropped_tables: [],\n changes: [],\n has_changes: false,\n };\n\n // Get list of existing tables\n const existingTables = await this.getExistingTables();\n\n // Check each manifest schema against database\n for (const [tableName, schema] of Object.entries(manifestSchemas)) {\n if (!existingTables.has(tableName)) {\n // Table doesn't exist - add to added_tables\n diff.added_tables.push(schema);\n diff.has_changes = true;\n } else {\n // Table exists - compare columns and indexes\n const tableChanges = await this.compareTable(tableName, schema);\n if (tableChanges.length > 0) {\n diff.changes.push(...tableChanges);\n diff.has_changes = true;\n }\n }\n }\n\n // Check for dropped tables (if enabled)\n if (this.options.includeDroppedTables) {\n for (const tableName of existingTables) {\n // Skip system tables\n if (tableName.startsWith('_smrt_') || tableName.startsWith('sqlite_')) {\n continue;\n }\n if (!manifestSchemas[tableName]) {\n diff.dropped_tables.push(tableName);\n diff.has_changes = true;\n }\n }\n }\n\n return diff;\n }\n\n /**\n * Compare a single table's schema to manifest\n */\n async compareTable(\n tableName: string,\n manifest: SchemaDefinition,\n ): Promise<SchemaChange[]> {\n const changes: SchemaChange[] = [];\n\n // Get current table schema from database\n const dbSchema = await this.db.getTableSchema?.(tableName);\n if (!dbSchema) {\n // Table doesn't exist - this is an add_table case\n return changes;\n }\n\n // Compare columns\n const columnChanges = this.compareColumns(tableName, manifest, dbSchema);\n changes.push(...columnChanges);\n\n // Partial-index predicates are not surfaced by `getTableSchema()` (the\n // @happyvertical/sql introspection returns only name/columns/unique), so\n // introspect them separately. Without this, two indexes on the same\n // column(s) that differ only by their WHERE clause — e.g. distinct STI\n // child partial indexes — would compare equal and the differ would miss\n // adds/drops/changes of the predicate (issue #1692).\n const dbIndexPredicates = await this.getDbIndexPredicates(tableName);\n\n // Compare indexes\n const indexChanges = this.compareIndexes(\n tableName,\n manifest,\n dbSchema,\n dbIndexPredicates,\n );\n changes.push(...indexChanges);\n\n return changes;\n }\n\n /**\n * Compare columns between manifest and database\n */\n private compareColumns(\n tableName: string,\n manifest: SchemaDefinition,\n dbSchema: SqlTableSchemaInfo,\n ): SchemaChange[] {\n const changes: SchemaChange[] = [];\n const dbColumnNames = new Set(Object.keys(dbSchema.columns));\n\n // Check for new and modified columns\n for (const [colName, colDef] of Object.entries(manifest.columns)) {\n if (!dbColumnNames.has(colName)) {\n // Column doesn't exist - add it\n changes.push({\n type: 'add_column',\n table: tableName,\n name: colName,\n column: colDef,\n sql: this.generateAddColumnSQL(tableName, colName, colDef),\n });\n } else {\n // Column exists - check for type mismatch\n const dbCol = dbSchema.columns[colName];\n\n // Map manifest's abstract type to engine-specific type\n // e.g., JSON → TEXT for SQLite, JSON → JSONB for PostgreSQL\n // Validate the manifest type before mapping\n const manifestType = colDef.type;\n if (!isValidSQLDataType(manifestType)) {\n // Invalid manifest type - treat as TEXT (safest fallback)\n logger.warn(\n `[SchemaComparer] Invalid manifest type \"${manifestType}\" for ${tableName}.${colName}, treating as TEXT`,\n );\n }\n const validatedType: SQLDataType = isValidSQLDataType(manifestType)\n ? manifestType\n : 'TEXT';\n const expectedEngineType = this.ddlStrategy.mapType(validatedType);\n const normalizedExpected = this.normalizeType(expectedEngineType);\n const normalizedActual = this.normalizeType(dbCol.type);\n\n // R11: native `uuid` and `text` are interchangeable for SMRT-owned\n // identifiers/references, but not for arbitrary provenance text. Keep\n // the tolerance directional:\n // - manifest UUID + DB text is tolerated for structural ID/ref\n // columns so old deployments are not forced into native UUID.\n // - manifest TEXT + DB uuid is tolerated only for structural ID/ref\n // columns that are intentionally UUID-compatible.\n // Plain TEXT columns with DB uuid now surface as repairable drift.\n const isUuidTextEquivalent = this.isUuidTextEquivalentColumn(\n colName,\n colDef,\n normalizedExpected,\n normalizedActual,\n );\n\n // #1335: native `json`/`jsonb` (DB) and `text` (manifest) are\n // interchangeable for SMRT — the convention is to serialize JSON values\n // into TEXT columns, and a native-json column already holds exactly that\n // data. So the differ must NOT flag a json<->text difference in EITHER\n // direction:\n // - manifest TEXT vs DB json (native-json column, text-convention manifest)\n // - manifest JSON vs DB text (the canary case: an enum/plain field\n // mis-inferred as JSON by a downstream scanner, sitting on a real\n // `text` column holding bare values like 'active')\n // Generating an ALTER here is pure churn at best and data-destroying at\n // worst: `status::jsonb` on a column holding 'active' raises\n // \"invalid input syntax for type json\" and aborts the whole atomic\n // migration. Like the uuid/text tolerance, this lives at the equality\n // gate only (not in `normalizeType`) so `isCompatibleTypeUpgrade` still\n // treats JSON and TEXT as distinct buckets for OTHER upgrade paths.\n const isJsonTextEquivalent =\n (normalizedExpected === 'JSON' && normalizedActual === 'TEXT') ||\n (normalizedExpected === 'TEXT' && normalizedActual === 'JSON');\n\n if (\n normalizedExpected !== normalizedActual &&\n !isUuidTextEquivalent &&\n !isJsonTextEquivalent\n ) {\n // Check if this is a safe type upgrade that SMRT can handle\n // Since SMRT owns the data lifecycle, we know the intent from the manifest\n if (this.isCompatibleTypeUpgrade(colDef.type, dbCol.type)) {\n // Generate type upgrade SQL\n const generatedSQL = this.generateTypeUpgradeSQL(\n tableName,\n colName,\n colDef,\n dbCol.type,\n );\n changes.push({\n type: 'type_upgrade',\n table: tableName,\n name: colName,\n column: colDef,\n mismatch: {\n expected: colDef.type,\n actual: dbCol.type,\n },\n sql: generatedSQL.sql,\n ...(generatedSQL.statements\n ? { sqlStatements: generatedSQL.statements }\n : {}),\n });\n } else if (!this.options.ignoreTypeMismatches) {\n changes.push({\n type: 'type_mismatch',\n table: tableName,\n name: colName,\n mismatch: {\n expected: colDef.type,\n actual: dbCol.type,\n },\n });\n }\n }\n }\n }\n\n // Check for dropped columns (if enabled)\n if (this.options.includeDroppedColumns) {\n const manifestColumnNames = new Set(Object.keys(manifest.columns));\n for (const colName of dbColumnNames) {\n if (!manifestColumnNames.has(colName)) {\n changes.push({\n type: 'drop_column',\n table: tableName,\n name: colName,\n sql: this.generateDropColumnSQL(tableName, colName),\n });\n }\n }\n }\n\n return changes;\n }\n\n private isUuidTextEquivalentColumn(\n columnName: string,\n colDef: ColumnDefinition,\n normalizedExpected: string,\n normalizedActual: string,\n ): boolean {\n const expectedUuidActualText =\n normalizedExpected === 'UUID' && normalizedActual === 'TEXT';\n const expectedTextActualUuid =\n normalizedExpected === 'TEXT' && normalizedActual === 'UUID';\n\n if (!expectedUuidActualText && !expectedTextActualUuid) {\n return false;\n }\n\n return this.isStructuralUuidCompatibleColumn(columnName, colDef);\n }\n\n private isStructuralUuidCompatibleColumn(\n columnName: string,\n colDef: ColumnDefinition,\n ): boolean {\n return (\n colDef.primaryKey === true ||\n Boolean(colDef.foreignKey) ||\n colDef.referenceKind === 'id' ||\n colDef.referenceKind === 'foreignKey' ||\n colDef.referenceKind === 'crossPackageRef' ||\n colDef.referenceKind === 'tenantId' ||\n (columnName === 'id' && colDef.type === 'TEXT')\n );\n }\n\n /**\n * Compare indexes between manifest and database\n *\n * Four classes of drift the differ now detects:\n *\n * 1. **Missing index** — manifest has an index neither the DB has by name\n * nor any equivalent-by-signature. Emit `add_index`. (Issue #741: the\n * signature check protects against creating duplicates when STI child\n * classes register indexes with different name prefixes.)\n *\n * 2. **Same-name shape drift** — DB has an index with the manifest's name,\n * but its columns, uniqueness flag, or partial-index `WHERE` predicate\n * differ. This covers the uniqueness flip in issue #1165\n * (`tenants_slug_context_meta_type_idx` materialized non-unique while\n * the manifest declares it unique) and the predicate drift in issue\n * #1692 (a partial index whose `WHERE` clause was added, removed, or\n * altered). Emit `drop_index` + `add_index` so the next migrate cycle\n * recreates it with the correct shape.\n *\n * 3. **Orphan in DB** — DB has an index with no manifest counterpart by\n * name and no signature equivalent. Emit `drop_index` *only* when the\n * caller opts in via `includeDroppedIndexes`, and even then never for\n * PostgreSQL implicit indexes (`*_pkey`, `*_key`) — those are owned by\n * table-level constraints and need a separate `DROP CONSTRAINT` path\n * that the differ does not emit yet.\n *\n * 4. **Partial-index predicate drift / collision** — two indexes on the\n * same column(s) and uniqueness that differ only by their `WHERE`\n * predicate (e.g. distinct STI child partial indexes) are no longer\n * collapsed to one signature, so the signature-equivalence path (b)\n * won't claim one for the other.\n *\n * @param dbIndexPredicates - Normalized `WHERE` predicate per DB index\n * name from {@link getDbIndexPredicates}. `null` means predicate\n * introspection was unavailable for this engine/adapter, in which case\n * the comparison falls back to predicate-unaware signatures (the prior\n * behavior) so existing partial indexes are never flagged as false drift.\n */\n private compareIndexes(\n tableName: string,\n manifest: SchemaDefinition,\n dbSchema: SqlTableSchemaInfo,\n dbIndexPredicates: Map<string, string> | null = null,\n ): SchemaChange[] {\n const changes: SchemaChange[] = [];\n\n // Only fold predicates into signatures when we actually read them back\n // from the live DB. If introspection was unavailable both sides use the\n // empty predicate, which reproduces the prior column+unique-only behavior\n // and cannot manufacture false positives on existing partial indexes.\n const predicateAware = dbIndexPredicates !== null;\n const dbPredicateFor = (name: string): string =>\n predicateAware ? (dbIndexPredicates?.get(name) ?? '') : '';\n const manifestPredicateFor = (idx: IndexDefinition): string =>\n predicateAware ? normalizeIndexPredicate(idx.where) : '';\n\n // Index DB indexes by name and by signature for fast lookup.\n // dbIndexSignatures groups *all* DB index names sharing a signature so\n // duplicates under different names all get claimed by a single matching\n // manifest entry — otherwise the orphan sweep would drop the un-claimed\n // siblings even though they are functionally equivalent to the manifest.\n const dbIndexesByName = new Map<\n string,\n { columns: string[]; unique: boolean }\n >();\n const dbIndexSignatures = new Map<string, Set<string>>();\n for (const idx of dbSchema.indexes) {\n const unique = idx.unique ?? false;\n dbIndexesByName.set(idx.name, { columns: idx.columns, unique });\n const signature = this.getIndexSignature(\n idx.columns,\n unique,\n dbPredicateFor(idx.name),\n );\n let bucket = dbIndexSignatures.get(signature);\n if (!bucket) {\n bucket = new Set();\n dbIndexSignatures.set(signature, bucket);\n }\n bucket.add(idx.name);\n }\n\n // Manifest signatures — used during the orphan sweep to skip DB indexes\n // that match a manifest entry's signature even if no specific manifest\n // entry \"claimed\" them by name.\n const manifestSignatureSet = new Set<string>();\n for (const idx of manifest.indexes) {\n manifestSignatureSet.add(\n this.getIndexSignature(idx, undefined, manifestPredicateFor(idx)),\n );\n }\n\n // Track which DB indexes a manifest entry has claimed, so the orphan\n // pass below doesn't re-flag indexes that match by signature alone.\n const claimedDbIndexes = new Set<string>();\n\n for (const idx of manifest.indexes) {\n const manifestSignature = this.getIndexSignature(\n idx,\n undefined,\n manifestPredicateFor(idx),\n );\n\n // (a) Same name in DB — verify shape matches.\n const dbByName = dbIndexesByName.get(idx.name);\n if (dbByName) {\n claimedDbIndexes.add(idx.name);\n\n // JSON-path indexes (`@meta({ indexed: true })`) cannot be reliably\n // compared by DB introspection — SQLite expression indexes surface\n // as `[null]` columns, so the signature would always mismatch and\n // every diff run would emit drop+recreate. Trust the name match\n // here; if the json path itself changes, the index name changes\n // too (we encode the field name into it), so a name match is a\n // stronger guarantee than the column list for this index family.\n if (isJsonPathIndex(idx)) {\n continue;\n }\n\n const dbSignature = this.getIndexSignature(\n dbByName.columns,\n dbByName.unique,\n dbPredicateFor(idx.name),\n );\n if (dbSignature === manifestSignature) {\n continue; // Same name, same shape — nothing to do.\n }\n\n // Same name, drifted shape. Most often this is a uniqueness flip\n // (issue #1165: 3-column index materialized non-unique). Recreate.\n //\n // Rollback caveat: the auto-generated DOWN script for the\n // `add_index` half drops the (newly correct) index, and the\n // `drop_index` half has no DOWN. Rolling back a recreate leaves\n // the table without the index entirely instead of restoring the\n // wrong-shape original. Capturing the original shape would\n // require richer DB introspection than the differ currently has,\n // so this asymmetry is accepted — the failure mode after an\n // un-rolled-back recreate is \"missing index\" rather than\n // \"permanently broken UPSERT,\" which is recoverable.\n changes.push({\n type: 'drop_index',\n table: tableName,\n name: idx.name,\n sql: this.generateDropIndexSQL(idx.name),\n });\n changes.push({\n type: 'add_index',\n table: tableName,\n name: idx.name,\n index: idx,\n sql: this.generateAddIndexSQL(tableName, idx),\n });\n continue;\n }\n\n // (b) Different name in DB but functionally equivalent — keep as-is.\n // Claim *every* DB name sharing this signature so duplicate-shape\n // indexes (e.g., a stale `<name>_idx` plus the implicit `<name>_key`\n // from the same constraint) all survive the orphan sweep.\n const equivalentIndexNames = dbIndexSignatures.get(manifestSignature);\n if (equivalentIndexNames && equivalentIndexNames.size > 0) {\n for (const name of equivalentIndexNames) {\n claimedDbIndexes.add(name);\n }\n continue;\n }\n\n // (c) Genuinely missing — add it.\n changes.push({\n type: 'add_index',\n table: tableName,\n name: idx.name,\n index: idx,\n sql: this.generateAddIndexSQL(tableName, idx),\n });\n }\n\n // Orphan-index sweep (opt-in via includeDroppedIndexes).\n if (this.options.includeDroppedIndexes) {\n for (const idx of dbSchema.indexes) {\n if (claimedDbIndexes.has(idx.name)) continue;\n if (isProtectedDbIndexName(idx.name)) continue;\n\n // Belt-and-suspenders: even if a DB index wasn't formally claimed\n // by a manifest entry (e.g., shape-drift recreate consumed the\n // claim slot), don't drop it if its signature still matches\n // something the manifest declares. That would contradict the\n // option doc (\"not functionally equivalent to anything in the\n // manifest\") and risk dropping a still-needed index.\n const idxSignature = this.getIndexSignature(\n idx.columns,\n idx.unique ?? false,\n dbPredicateFor(idx.name),\n );\n if (manifestSignatureSet.has(idxSignature)) continue;\n\n changes.push({\n type: 'drop_index',\n table: tableName,\n name: idx.name,\n sql: this.generateDropIndexSQL(idx.name),\n });\n }\n }\n\n return changes;\n }\n\n /**\n * Generate a signature for an index based on its columns, uniqueness, and\n * (normalized) partial-index predicate. Used for functional equivalence\n * checking (Issue #741) and predicate-drift detection (Issue #1692).\n *\n * Note: Column order is preserved because it is semantically significant for\n * composite indexes. An index on (a, b) is NOT equivalent to (b, a) - they\n * have different query performance characteristics.\n *\n * The trailing predicate component distinguishes partial indexes that share\n * columns and uniqueness but differ by their `WHERE` clause (e.g. distinct\n * STI child partial indexes). Callers pass the already-normalized predicate\n * so both the manifest (desired) and introspected (DB) sides compare equal\n * for semantically-identical clauses. An empty string means \"no predicate\"\n * (a non-partial index) and is also used on both sides when predicate\n * introspection is unavailable, preserving the prior behavior.\n *\n * For JSON-path indexes (`@meta({ indexed: true })`) the signature is\n * derived from the JSON path instead of an empty column list, so the\n * differ can distinguish two jsonPath indexes against different paths.\n *\n * @param idxOrColumns - Either an IndexDefinition or a column array (legacy)\n * @param uniqueArg - Unique flag (used when first arg is a column array)\n * @param predicateArg - Normalized partial-index predicate (default '')\n * @returns Signature string\n */\n private getIndexSignature(\n idxOrColumns: IndexDefinition | string[],\n uniqueArg?: boolean,\n predicateArg = '',\n ): string {\n if (Array.isArray(idxOrColumns)) {\n return `${idxOrColumns.join(',')}:${Boolean(uniqueArg)}:${predicateArg}`;\n }\n const idx = idxOrColumns;\n if (isJsonPathIndex(idx) && idx.jsonPath) {\n return `json:${idx.jsonPath.column}.${idx.jsonPath.path}:${Boolean(idx.unique)}:${predicateArg}`;\n }\n return `${(idx.columns ?? []).join(',')}:${Boolean(idx.unique)}:${predicateArg}`;\n }\n\n /**\n * Whether the active engine supports partial indexes (`CREATE INDEX … WHERE`).\n *\n * SQLite and PostgreSQL do. DuckDB rejects them outright, and the JSON\n * adapter is DuckDB-backed, so on those engines a \"partial\" index can only\n * ever exist as a full index. Treating the predicate as significant there\n * would (a) flag existing full indexes as false drift and (b) emit\n * `CREATE INDEX … WHERE` DDL the engine rejects, breaking the migration.\n * Gating on this keeps both the comparison and the generated DDL aligned\n * with what the engine actually accepts (a partial index degrades to a\n * full index), matching the pre-#1692 behavior on those engines.\n */\n private supportsPartialIndexes(): boolean {\n return this.engine === 'sqlite' || this.engine === 'postgres';\n }\n\n /**\n * Introspect partial-index predicates for a table, keyed by index name.\n *\n * `getTableSchema()` (the @happyvertical/sql introspection) returns only\n * name/columns/unique, so the `WHERE` predicate is read directly here:\n *\n * - PostgreSQL: `pg_indexes.indexdef` carries the full CREATE INDEX text.\n * - SQLite: the `sqlite_master.sql` column carries the original CREATE INDEX\n * text.\n *\n * Engines that don't support partial indexes (DuckDB / the DuckDB-backed\n * JSON adapter) short-circuit to `null` so the comparison stays\n * predicate-unaware there — see {@link supportsPartialIndexes}.\n *\n * Non-partial indexes are omitted from the map (callers treat a missing\n * entry as the empty predicate). Returns `null` when the catalog query\n * fails — e.g. an adapter exposing neither catalog — so the index\n * comparison can fall back to predicate-unaware behavior rather than\n * flagging every existing partial index as false drift.\n */\n private async getDbIndexPredicates(\n tableName: string,\n ): Promise<Map<string, string> | null> {\n if (!this.supportsPartialIndexes()) {\n return null;\n }\n const predicates = new Map<string, string>();\n try {\n if (this.engine === 'postgres') {\n const result = await this.db.query(\n `SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename = ${this.quoteLiteral(\n tableName,\n )}`,\n );\n for (const row of result.rows as {\n indexname?: string;\n indexdef?: string;\n }[]) {\n if (!row.indexname || !row.indexdef) continue;\n const predicate = extractIndexPredicate(row.indexdef);\n if (predicate) predicates.set(row.indexname, predicate);\n }\n return predicates;\n }\n\n // SQLite exposes the `sqlite_master` catalog whose `sql` column preserves\n // the original CREATE INDEX text. Implicit indexes carry a NULL `sql` and\n // are skipped. (DuckDB / JSON already short-circuited above.)\n const result = await this.db.query(\n `SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${this.quoteLiteral(\n tableName,\n )} AND name NOT LIKE 'sqlite_%'`,\n );\n for (const row of result.rows as {\n name?: string;\n sql?: string | null;\n }[]) {\n if (!row.name || !row.sql) continue;\n const predicate = extractIndexPredicate(row.sql);\n if (predicate) predicates.set(row.name, predicate);\n }\n return predicates;\n } catch (err) {\n logger.debug(\n `[SchemaComparer] Partial-index predicate introspection unavailable for ${tableName}; falling back to predicate-unaware index comparison`,\n { error: err instanceof Error ? err.message : String(err) },\n );\n return null;\n }\n }\n\n /**\n * Get list of existing tables from database\n */\n private async getExistingTables(): Promise<Set<string>> {\n let query: string;\n if (this.engine === 'postgres') {\n query = `SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`;\n } else {\n // SQLite and DuckDB both expose the SQLite-compatible `sqlite_master`\n // catalog — DuckDB ships it as a built-in compatibility view, so a single\n // introspection query covers both engines. Verified against a live DuckDB\n // v1.4.3 (json mode): `SELECT name FROM sqlite_master WHERE type='table'`\n // returns user tables with the expected `name` column (#1579).\n query = `SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`;\n }\n\n const result = await this.db.query(query);\n const rows = result.rows as { name?: string; table_name?: string }[];\n return new Set(\n rows.map((r) => r.name || r.table_name || '').filter(Boolean),\n );\n }\n\n /**\n * Normalize SQL types for comparison\n */\n private normalizeType(type: string): string {\n const upper = type.toUpperCase().trim();\n\n // Integer types\n if (/^(INTEGER|INT|BIGINT|SMALLINT|TINYINT)$/i.test(upper)) {\n return 'INTEGER';\n }\n\n // Text types\n if (/^(TEXT|CLOB|STRING|VARCHAR|CHAR)/i.test(upper)) {\n return 'TEXT';\n }\n\n // UUID normalizes to its own bucket — deliberately NOT folded into TEXT.\n // The text<->uuid drift tolerance (R11) is applied at the equality gate\n // in `compare()` only, so that `isCompatibleTypeUpgrade` (which also\n // calls normalizeType) still treats `uuid` as distinct from text and\n // won't mis-classify e.g. `uuid`->`timestamp` as a compatible\n // \"TEXT->TIMESTAMP\" upgrade.\n if (/^UUID$/i.test(upper)) {\n return 'UUID';\n }\n\n // Decimal types\n if (/^(REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER)/i.test(upper)) {\n return 'REAL';\n }\n\n // Boolean types\n if (/^(BOOLEAN|BOOL)/i.test(upper)) {\n return 'BOOLEAN';\n }\n\n // Date/time types\n if (/^(DATETIME|TIMESTAMP|DATE|TIME)/i.test(upper)) {\n return 'TIMESTAMP';\n }\n\n // Blob types\n if (/^(BLOB|BINARY|BYTEA)/i.test(upper)) {\n return 'BLOB';\n }\n\n // JSON types\n if (/^(JSON|JSONB)/i.test(upper)) {\n return 'JSON';\n }\n\n return upper;\n }\n\n /**\n * Check if a type change is a safe upgrade that can be auto-migrated.\n *\n * SMRT controls the data lifecycle for these columns, so we know:\n * - TEXT→JSON: The column stores JSON data serialized as text (arrays, objects)\n * - TEXT/JSON→TIMESTAMP: Legacy system columns stored timestamp strings\n * before newer manifests normalized the column type.\n * - INTEGER→REAL: Safe widening of integer to floating point\n * - TEXT/REAL→INTEGER on PostgreSQL: explicit data-checked repairs for\n * legacy integer columns that were previously stored as text/real.\n *\n * @param manifestType - The abstract type from the manifest (e.g., 'JSON')\n * @param dbType - The actual type in the database (e.g., 'TEXT')\n * @returns true if the change from dbType to manifestType is a safe upgrade\n */\n private isCompatibleTypeUpgrade(\n manifestType: string,\n dbType: string,\n ): boolean {\n const manifest = this.normalizeType(manifestType);\n const db = this.normalizeType(dbType);\n\n // TEXT → JSON is safe: SMRT serializes arrays/objects as JSON text\n // When the manifest says JSON, the data is already valid JSON in TEXT column\n if (manifest === 'JSON' && db === 'TEXT') {\n return true;\n }\n\n // JSON → TEXT is also safe (downgrade, but data is preserved as-is)\n if (manifest === 'TEXT' && db === 'JSON') {\n return true;\n }\n\n // UUID → TEXT is safe for plain text/provenance fields that were\n // mistakenly materialized as native uuid: the stored UUID value can be\n // rendered losslessly as text.\n if (manifest === 'TEXT' && db === 'UUID') {\n return true;\n }\n\n // INTEGER → REAL is safe (widening)\n if (manifest === 'REAL' && db === 'INTEGER') {\n return true;\n }\n\n // PostgreSQL can safely repair legacy integer columns when the generated\n // migration validates that every existing value is already an integer.\n if (\n this.engine === 'postgres' &&\n manifest === 'INTEGER' &&\n (db === 'TEXT' || db === 'REAL')\n ) {\n return true;\n }\n\n // TEXT/JSON → TIMESTAMP is a legacy-drift repair. Invalid values fail\n // explicitly during migration rather than being silently coerced.\n if (manifest === 'TIMESTAMP' && (db === 'TEXT' || db === 'JSON')) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Generate SQL for a type upgrade migration.\n *\n * Engine-specific SQL:\n * - SQLite: TEXT and JSON are equivalent, no-op or comment\n * - DuckDB: ALTER COLUMN TYPE (native type conversion)\n * - PostgreSQL: ALTER COLUMN TYPE with USING clause\n */\n private generateTypeUpgradeSQL(\n tableName: string,\n colName: string,\n colDef: ColumnDefinition,\n dbType: string,\n ): GeneratedTypeUpgradeSQL {\n const quotedTable = this.quoteIdentifier(tableName);\n const quotedCol = this.quoteIdentifier(colName);\n const manifestType = colDef.type;\n\n // Validate manifestType before mapping\n const validatedType: SQLDataType = isValidSQLDataType(manifestType)\n ? manifestType\n : 'TEXT';\n const targetType = this.ddlStrategy.mapType(validatedType);\n\n switch (this.engine) {\n case 'sqlite':\n // SQLite has dynamic typing - TEXT and JSON are functionally equivalent\n // For SQLite, we just return a comment since no actual change is needed\n if (\n this.normalizeType(manifestType) === 'JSON' &&\n this.normalizeType(dbType) === 'TEXT'\n ) {\n return {\n sql: `-- SQLite: ${quotedCol} already stores JSON as TEXT (no change needed)`,\n };\n }\n // For other type upgrades, SQLite requires recreating the table\n return {\n sql: `-- SQLite: Type upgrade for ${quotedCol} requires table recreation`,\n };\n\n case 'postgres': {\n // PostgreSQL defaults must be dropped/reset around some type changes\n // so drift repairs can succeed even when an existing default cannot\n // be cast automatically to the target type.\n const manifestNormalized = this.normalizeType(manifestType);\n const dbNormalized = this.normalizeType(dbType);\n const preflightSQL =\n manifestNormalized === 'INTEGER' &&\n (dbNormalized === 'TEXT' || dbNormalized === 'REAL')\n ? this.generatePostgresIntegerPreflightSQL(\n quotedTable,\n quotedCol,\n tableName,\n colName,\n dbNormalized,\n )\n : null;\n const clauses: string[] = [];\n\n if (colDef.defaultValue !== undefined) {\n clauses.push(`ALTER COLUMN ${quotedCol} DROP DEFAULT`);\n }\n\n let typeClause = `ALTER COLUMN ${quotedCol} TYPE ${targetType}`;\n if (manifestNormalized === 'JSON' && dbNormalized === 'TEXT') {\n // #1335: a bare `${col}::jsonb` cast raises \"invalid input syntax for\n // type json\" on any row whose text is not already valid JSON (e.g. a\n // legacy enum column holding 'active'). `to_jsonb(col)` instead wraps\n // ANY text value as a JSON string and never errors, so a genuine\n // TEXT->JSON widening survives non-JSON legacy data. (Note: with the\n // json<->text equality tolerance added in this fix, the normal\n // compare path no longer reaches here; this keeps the SQL safe for\n // callers that construct a type_upgrade directly.)\n typeClause += ` USING to_jsonb(${quotedCol})`;\n } else if (manifestNormalized === 'TEXT' && dbNormalized === 'JSON') {\n // #1335: a native-json column cast back to text is value-preserving\n // (`::text` renders the stored JSON as its text form), so this arm is\n // safe. (Note: like the TEXT->JSON arm above, the json<->text equality\n // tolerance means the normal compare path no longer reaches here; this\n // keeps the SQL safe for callers that construct a type_upgrade\n // directly.)\n typeClause += ` USING ${quotedCol}::text`;\n } else if (manifestNormalized === 'TEXT' && dbNormalized === 'UUID') {\n typeClause += ` USING ${quotedCol}::text`;\n } else if (\n manifestNormalized === 'INTEGER' &&\n dbNormalized === 'TEXT'\n ) {\n typeClause += ` USING trim(${quotedCol}::text)::integer`;\n } else if (\n manifestNormalized === 'INTEGER' &&\n dbNormalized === 'REAL'\n ) {\n typeClause += ` USING ${quotedCol}::integer`;\n } else if (\n manifestNormalized === 'TIMESTAMP' &&\n (dbNormalized === 'TEXT' || dbNormalized === 'JSON')\n ) {\n typeClause += ` USING NULLIF(NULLIF(trim(both '\"' from ${quotedCol}::text), ''), 'null')::timestamp`;\n }\n\n clauses.push(typeClause);\n\n if (colDef.defaultValue !== undefined) {\n const formattedDefault = this.ddlStrategy.formatDefaultValue(\n colDef.defaultValue,\n validatedType,\n );\n const defaultSql =\n manifestNormalized === 'JSON'\n ? `${formattedDefault}::${targetType.toLowerCase()}`\n : formattedDefault;\n clauses.push(`ALTER COLUMN ${quotedCol} SET DEFAULT ${defaultSql}`);\n }\n\n const alterSql = `ALTER TABLE ${quotedTable} ${clauses.join(', ')}`;\n\n return preflightSQL\n ? { sql: alterSql, statements: [preflightSQL, alterSql] }\n : { sql: alterSql };\n }\n\n case 'duckdb':\n // DuckDB supports ALTER COLUMN TYPE for type conversions\n return {\n sql: `ALTER TABLE ${quotedTable} ALTER COLUMN ${quotedCol} TYPE ${targetType}`,\n };\n\n default: {\n // Escape special characters in type names for safe comment generation\n const safeDbType = dbType.replace(/[^\\w]/g, '_');\n const safeManifestType = manifestType.replace(/[^\\w]/g, '_');\n return {\n sql: `-- Type upgrade for ${quotedCol}: ${safeDbType} → ${safeManifestType}`,\n };\n }\n }\n }\n\n /**\n * Quote a SQL identifier\n */\n private quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * Generate a PostgreSQL preflight guard for narrowing legacy columns to\n * INTEGER. PostgreSQL's REAL→INTEGER cast rounds fractional values, so the\n * generated migration must fail before the ALTER can silently change data.\n */\n private generatePostgresIntegerPreflightSQL(\n quotedTable: string,\n quotedCol: string,\n tableName: string,\n colName: string,\n dbNormalized: string,\n ): string {\n const invalidCondition =\n dbNormalized === 'REAL'\n ? `${quotedCol} IS NOT NULL AND ${quotedCol} <> trunc(${quotedCol})`\n : `${quotedCol} IS NOT NULL AND trim(${quotedCol}::text) !~ '^[+-]?[0-9]+$'`;\n const message = `Cannot convert ${tableName}.${colName} to INTEGER: found non-integer values`;\n\n return `DO $$ BEGIN IF EXISTS (SELECT 1 FROM ${quotedTable} WHERE ${invalidCondition}) THEN RAISE EXCEPTION ${this.quoteLiteral(message)}; END IF; END $$`;\n }\n\n private quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Generate SQL for adding a column\n */\n private generateAddColumnSQL(\n tableName: string,\n colName: string,\n colDef: ColumnDefinition,\n ): string {\n // Build the ADD COLUMN definition inline (main) rather than delegating to\n // the DDL strategy's generateColumnDefinition: that builder is for CREATE\n // TABLE and would emit `PRIMARY KEY` (invalid in ALTER ... ADD COLUMN) and\n // suppress single-column UNIQUE on engines that require inline unique at\n // table-create time (DuckDB) — but an ADD COLUMN has no inline-constraint\n // pass, so the UNIQUE must be emitted here. mapType still maps abstract\n // types per dialect (UUID→native uuid / TEXT — R11); invalid types fall\n // back to TEXT, matching the compareColumns guard.\n const validatedType: SQLDataType = isValidSQLDataType(colDef.type)\n ? colDef.type\n : 'TEXT';\n if (!isValidSQLDataType(colDef.type)) {\n logger.warn(\n `[SchemaComparer] Invalid manifest type \"${colDef.type}\" for ${tableName}.${colName}, treating as TEXT`,\n );\n }\n\n const parts: string[] = [\n this.quoteIdentifier(colName),\n this.ddlStrategy.mapType(validatedType),\n ];\n\n if (colDef.notNull) {\n parts.push('NOT NULL');\n }\n if (colDef.unique) {\n parts.push('UNIQUE');\n }\n if (colDef.defaultValue !== undefined) {\n const defaultVal = this.ddlStrategy.formatDefaultValue(\n colDef.defaultValue,\n validatedType,\n );\n parts.push(`DEFAULT ${defaultVal}`);\n }\n if (colDef.check) {\n parts.push(`CHECK (${colDef.check})`);\n }\n\n const columnDefinition = parts.join(' ');\n\n return `ALTER TABLE ${this.quoteIdentifier(tableName)} ADD COLUMN ${columnDefinition}`;\n }\n\n /**\n * Generate SQL for dropping a column\n */\n private generateDropColumnSQL(tableName: string, colName: string): string {\n return `ALTER TABLE ${this.quoteIdentifier(tableName)} DROP COLUMN ${this.quoteIdentifier(colName)}`;\n }\n\n /**\n * Generate SQL for adding an index.\n *\n * On engines that support partial indexes (SQLite/PostgreSQL) this mirrors\n * the canonical CREATE INDEX path in the DDL strategies: a partial index\n * appends its `WHERE` predicate so a detected predicate add/alter (issue\n * #1692) recreates the index with the correct partial condition rather than\n * silently widening it to a full index. On DuckDB / the JSON adapter — which\n * reject partial indexes — the predicate is dropped so the emitted DDL stays\n * executable (a partial index degrades to a full index there). The predicate\n * is trimmed and a redundant leading `WHERE` stripped for robustness.\n */\n private generateAddIndexSQL(tableName: string, idx: IndexDefinition): string {\n const uniqueStr = idx.unique ? 'UNIQUE ' : '';\n const target = renderIndexTarget(idx, this.engine);\n let sql = `CREATE ${uniqueStr}INDEX ${this.quoteIdentifier(idx.name)} ON ${this.quoteIdentifier(tableName)} (${target})`;\n const where = idx.where?.trim().replace(/^WHERE\\s+/i, '');\n if (this.supportsPartialIndexes() && where) {\n sql += ` WHERE ${where}`;\n }\n return sql;\n }\n\n /**\n * Generate SQL for dropping an index.\n *\n * This SQL is consumed by the manifest-driven execution path:\n *\n * - `db:migrate` runs the SQL we put in `change.sql` directly, with the\n * tracker's `executePostgresStatements` adding CONCURRENTLY when\n * `--postgres-safe` is on.\n *\n * PostgreSQL ends up with `CONCURRENTLY` when it should.\n * Keeping this method engine-agnostic also means the diff preview text\n * stays readable (no engine-specific noise) for engines like SQLite\n * where CONCURRENTLY isn't a thing.\n */\n private generateDropIndexSQL(indexName: string): string {\n return `DROP INDEX IF EXISTS ${this.quoteIdentifier(indexName)}`;\n }\n}\n\n/**\n * Generate a SchemaDiff from manifest and database\n */\nexport async function generateSchemaDiff(\n db: DatabaseInterface,\n manifestSchemas: Record<string, SchemaDefinition>,\n options: DiffOptions = {},\n): Promise<SchemaDiff> {\n const comparer = new SchemaComparer(db, options);\n return comparer.compare(manifestSchemas);\n}\n\n/**\n * Check if a diff has any actionable changes (excluding type mismatches)\n */\nexport function hasActionableChanges(diff: SchemaDiff): boolean {\n if (diff.added_tables.length > 0) return true;\n if (diff.dropped_tables.length > 0) return true;\n return diff.changes.some((c) => c.type !== 'type_mismatch');\n}\n\n/**\n * Get SQL statements from a diff for execution\n */\nexport function getSQLFromDiff(diff: SchemaDiff): string[] {\n const statements: string[] = [];\n\n // Add table creation (requires full DDL generation - not included here)\n // This is typically handled by ensureSchema()\n\n // Add column and index changes\n for (const change of diff.changes) {\n if (change.type !== 'type_mismatch') {\n statements.push(\n ...(change.sqlStatements ?? (change.sql ? [change.sql] : [])),\n );\n }\n }\n\n return statements;\n}\n"],"names":["result"],"mappings":";;;;;AAqBA,MAAM,SAAS,aAAa,EAAE,OAAO,QAAQ;AAK7C,MAAM,2CAA6C,IAAI;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAUD,SAAS,mBAAmB,MAAmC;AAC7D,SAAO,qBAAqB,IAAI,IAAmB;AACrD;AAwCA,MAAM,2BAA2B,CAAC,SAAS,MAAM;AAEjD,SAAS,uBAAuB,MAAuB;AACrD,SAAO,yBAAyB,KAAK,CAAC,WAAW,KAAK,SAAS,MAAM,CAAC;AACxE;AAEA,SAAS,mBAAmB,IAA+B;AACzD,QAAM,eAAe;AAGrB,SAAO,GAAG,OAAO,aAAa,QAAQ,OAAO;AAC/C;AAuBO,SAAS,wBAAwB,OAA+B;AACrE,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,WAAW,MAAM,KAAA,EAAO,QAAQ,cAAc,EAAE;AACtD,MAAI,CAAC,SAAU,QAAO;AAEtB,MAAI,MAAM;AACV,MAAI,IAAI;AACR,SAAO,IAAI,SAAS,QAAQ;AAC1B,QAAI,SAAS,CAAC,MAAM,KAAK;AAGvB,UAAI,UAAU;AACd;AACA,aAAO,IAAI,SAAS,QAAQ;AAC1B,YAAI,SAAS,CAAC,MAAM,KAAK;AACvB,cAAI,SAAS,IAAI,CAAC,MAAM,KAAK;AAC3B,uBAAW;AACX,iBAAK;AACL;AAAA,UACF;AACA,qBAAW;AACX;AACA;AAAA,QACF;AACA,mBAAW,SAAS,CAAC;AACrB;AAAA,MACF;AACA,aAAO;AAAA,IACT,OAAO;AACL,UAAI,MAAM;AACV,aAAO,IAAI,SAAS,UAAU,S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AAAA,EAgBQ,qBAAqB,WAA2B;AACtD,WAAO,wBAAwB,KAAK,gBAAgB,SAAS,CAAC;AAAA,EAChE;AACF;AAKA,eAAsB,mBACpB,IACA,iBACA,UAAuB,CAAA,GACF;AACrB,QAAM,WAAW,IAAI,eAAe,IAAI,OAAO;AAC/C,SAAO,SAAS,QAAQ,eAAe;AACzC;AAKO,SAAS,qBAAqB,MAA2B;AAC9D,MAAI,KAAK,aAAa,SAAS,EAAG,QAAO;AACzC,MAAI,KAAK,eAAe,SAAS,EAAG,QAAO;AAC3C,SAAO,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,eAAe;AAC5D;AAKO,SAAS,eAAe,MAA4B;AACzD,QAAM,aAAuB,CAAA;AAM7B,aAAW,UAAU,KAAK,SAAS;AACjC,QAAI,OAAO,SAAS,iBAAiB;AACnC,iBAAW;AAAA,QACT,GAAI,OAAO,kBAAkB,OAAO,MAAM,CAAC,OAAO,GAAG,IAAI,CAAA;AAAA,MAAC;AAAA,IAE9D;AAAA,EACF;AAEA,SAAO;AACT;"}
@@ -1 +1 @@
1
- {"version":3,"file":"assert-valid-pattern.js","sources":["../../../../../../../../../../node_modules/.pnpm/minimatch@10.2.3/node_modules/minimatch/dist/esm/assert-valid-pattern.js"],"sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64;\nexport const assertValidPattern = (pattern) => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern');\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long');\n }\n};\n//# sourceMappingURL=assert-valid-pattern.js.map"],"names":[],"mappings":"AAAA,MAAM,qBAAqB,OAAO;AACtB,MAAC,qBAAqB,CAAC,YAAY;AAC3C,MAAI,OAAO,YAAY,UAAU;AAC7B,UAAM,IAAI,UAAU,iBAAiB;AAAA,EACzC;AACA,MAAI,QAAQ,SAAS,oBAAoB;AACrC,UAAM,IAAI,UAAU,qBAAqB;AAAA,EAC7C;AACJ;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"assert-valid-pattern.js","sources":["../../../../../../../../../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/assert-valid-pattern.js"],"sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64;\nexport const assertValidPattern = (pattern) => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern');\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long');\n }\n};\n//# sourceMappingURL=assert-valid-pattern.js.map"],"names":[],"mappings":"AAAA,MAAM,qBAAqB,OAAO;AACtB,MAAC,qBAAqB,CAAC,YAAY;AAC3C,MAAI,OAAO,YAAY,UAAU;AAC7B,UAAM,IAAI,UAAU,iBAAiB;AAAA,EACzC;AACA,MAAI,QAAQ,SAAS,oBAAoB;AACrC,UAAM,IAAI,UAAU,qBAAqB;AAAA,EAC7C;AACJ;","x_google_ignoreList":[0]}