@happyvertical/smrt-core 0.40.14 → 0.40.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -11
- package/dist/browser.js +2 -2
- package/dist/change-feed.d.ts.map +1 -1
- package/dist/change-feed.js +21 -4
- package/dist/change-feed.js.map +1 -1
- package/dist/class.d.ts.map +1 -1
- package/dist/class.js +5 -3
- package/dist/class.js.map +1 -1
- package/dist/dispatch/bus.d.ts.map +1 -1
- package/dist/dispatch/bus.js +11 -6
- package/dist/dispatch/bus.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/manifest/static-manifest.js +2 -2
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/test-manifest-stub.d.ts.map +1 -1
- package/dist/manifest/test-manifest-stub.js +132 -2
- package/dist/manifest/test-manifest-stub.js.map +1 -1
- package/dist/manifest.json +2 -2
- package/dist/migrations/backfill-tracker.d.ts +1 -0
- package/dist/migrations/backfill-tracker.d.ts.map +1 -1
- package/dist/migrations/backfill-tracker.js +9 -3
- package/dist/migrations/backfill-tracker.js.map +1 -1
- package/dist/migrations/differ.d.ts +18 -0
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +28 -5
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/generator.d.ts +8 -0
- package/dist/migrations/generator.d.ts.map +1 -1
- package/dist/migrations/generator.js +5 -1
- package/dist/migrations/generator.js.map +1 -1
- package/dist/migrations/orchestrate.d.ts +10 -0
- package/dist/migrations/orchestrate.d.ts.map +1 -1
- package/dist/migrations/orchestrate.js +8 -2
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/migrations/tracker.d.ts.map +1 -1
- package/dist/migrations/tracker.js +4 -2
- package/dist/migrations/tracker.js.map +1 -1
- package/dist/registry/schema-builder.d.ts +13 -6
- package/dist/registry/schema-builder.d.ts.map +1 -1
- package/dist/registry/schema-builder.js +54 -15
- package/dist/registry/schema-builder.js.map +1 -1
- package/dist/registry.d.ts +3 -2
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +4 -4
- package/dist/registry.js.map +1 -1
- package/dist/schema/code-generator.js +123 -0
- package/dist/schema/code-generator.js.map +1 -0
- package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/base-strategy.js +2 -2
- package/dist/schema/ddl/base-strategy.js.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.js +2 -3
- package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
- package/dist/schema/ddl/index.js +26 -2
- package/dist/schema/ddl/index.js.map +1 -1
- package/dist/schema/ddl/materialize-manifest.d.ts +36 -0
- package/dist/schema/ddl/materialize-manifest.d.ts.map +1 -0
- package/dist/schema/ddl/materialize-manifest.js +361 -0
- package/dist/schema/ddl/materialize-manifest.js.map +1 -0
- package/dist/schema/ddl/postgres-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/postgres-strategy.js +1 -1
- package/dist/schema/ddl/postgres-strategy.js.map +1 -1
- package/dist/schema/index.js +12 -0
- package/dist/schema/override-system.js +205 -0
- package/dist/schema/override-system.js.map +1 -0
- package/dist/schema/schema-aggregator.d.ts.map +1 -1
- package/dist/schema/schema-aggregator.js +261 -0
- package/dist/schema/schema-aggregator.js.map +1 -0
- package/dist/schema/schema-manager.js +11 -1
- package/dist/schema/schema-manager.js.map +1 -1
- package/dist/schema/utils.d.ts +1 -0
- package/dist/schema/utils.d.ts.map +1 -1
- package/dist/schema/utils.js +2 -1
- package/dist/schema/utils.js.map +1 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +13 -0
- package/dist/smrt-knowledge.json +5 -4
- package/dist/system/compatibility.d.ts +25 -0
- package/dist/system/compatibility.d.ts.map +1 -1
- package/dist/system/compatibility.js +61 -1
- package/dist/system/compatibility.js.map +1 -1
- package/dist/system/index.js +2 -2
- package/dist/system/schema.d.ts +17 -9
- package/dist/system/schema.d.ts.map +1 -1
- package/dist/system/schema.js +25 -11
- package/dist/system/schema.js.map +1 -1
- package/dist/testing/database.d.ts.map +1 -1
- package/dist/testing/database.js +5 -2
- package/dist/testing/database.js.map +1 -1
- package/package.json +10 -5
package/dist/manifest.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": "1.0.0",
|
|
3
|
-
"timestamp":
|
|
3
|
+
"timestamp": 1784534099516,
|
|
4
4
|
"packageName": "@happyvertical/smrt-core",
|
|
5
|
-
"packageVersion": "0.40.
|
|
5
|
+
"packageVersion": "0.40.16",
|
|
6
6
|
"objects": {
|
|
7
7
|
"@happyvertical/smrt-core:SmrtClass": {
|
|
8
8
|
"name": "smrtclass",
|
|
@@ -37,6 +37,7 @@ export declare class BackfillTracker {
|
|
|
37
37
|
static requireExistingTable(db: DatabaseInterface): void;
|
|
38
38
|
/** Forget a root initialization after a schema lifecycle reset. */
|
|
39
39
|
static invalidateInitialization(db: DatabaseInterface): void;
|
|
40
|
+
private createTable;
|
|
40
41
|
/**
|
|
41
42
|
* Create the `_smrt_backfills` table if it doesn't already exist.
|
|
42
43
|
* Safe to call repeatedly and concurrently.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backfill-tracker.d.ts","sourceRoot":"","sources":["../../src/migrations/backfill-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"backfill-tracker.d.ts","sourceRoot":"","sources":["../../src/migrations/backfill-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAU5D,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,iBAAiB,CAAC;CACv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O,GAC3D,OAAO,CAAC;QAAE,GAAG,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,GAAG,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,CAAC,CAAA;KAAE,CAAC;IAOnE,kDAAkD;IAC5C,WAAW,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;YAYhC,kBAAkB;IAgBhC,OAAO,CAAC,mBAAmB;CAM5B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { CREATE_SMRT_BACKFILLS_TABLE } from "../system/schema.js";
|
|
1
|
+
import { CREATE_SMRT_BACKFILLS_TABLE, getSystemTableDDLForEngine } from "../system/schema.js";
|
|
2
|
+
import { assertPostgresSystemTimestampsCurrent, getDatabaseEngine } from "../system/compatibility.js";
|
|
2
3
|
//#region src/migrations/backfill-tracker.ts
|
|
3
4
|
/**
|
|
4
5
|
* A tracker query proved that its inherited root initialization is stale.
|
|
@@ -42,6 +43,11 @@ var BackfillTracker = class {
|
|
|
42
43
|
static invalidateInitialization(db) {
|
|
43
44
|
deleteSharedInitialization(databaseTargetIdentity(db));
|
|
44
45
|
}
|
|
46
|
+
async createTable() {
|
|
47
|
+
const ddl = getSystemTableDDLForEngine(CREATE_SMRT_BACKFILLS_TABLE, getDatabaseEngine(this.db));
|
|
48
|
+
await this.db.query(ddl);
|
|
49
|
+
await assertPostgresSystemTimestampsCurrent(this.db);
|
|
50
|
+
}
|
|
45
51
|
/**
|
|
46
52
|
* Create the `_smrt_backfills` table if it doesn't already exist.
|
|
47
53
|
* Safe to call repeatedly and concurrently.
|
|
@@ -63,14 +69,14 @@ var BackfillTracker = class {
|
|
|
63
69
|
}
|
|
64
70
|
}
|
|
65
71
|
if (isRootDatabase(this.db)) {
|
|
66
|
-
const initialization = this.
|
|
72
|
+
const initialization = this.createTable().then(() => void 0).catch((error) => {
|
|
67
73
|
if (getSharedInitialization(target) === initialization) deleteSharedInitialization(target);
|
|
68
74
|
throw error;
|
|
69
75
|
});
|
|
70
76
|
setSharedInitialization(target, initialization);
|
|
71
77
|
return initialization;
|
|
72
78
|
}
|
|
73
|
-
if (!this.initializePromise) this.initializePromise = this.
|
|
79
|
+
if (!this.initializePromise) this.initializePromise = this.createTable().then(() => void 0).catch((error) => {
|
|
74
80
|
this.initializePromise = null;
|
|
75
81
|
throw error;
|
|
76
82
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backfill-tracker.js","names":[],"sources":["../../src/migrations/backfill-tracker.ts"],"sourcesContent":["/**\n * Tracks application-specific data backfills (not schema migrations).\n *\n * Sits next to `MigrationTracker` but is intentionally minimal — backfills\n * have no checksum, no rollback semantics, no DDL. They're \"this data\n * correction has run, don't run it again\" markers, keyed by a stable\n * backfill name the app chooses.\n *\n * Backed by the `_smrt_backfills` system table (see\n * `../system/schema.ts`). The table is created lazily on first use —\n * every public method (`isApplied`, `recordApplied`, `runIfPending`,\n * `listApplied`) awaits `initialize()` itself, so consumers never need\n * to call `initialize()` explicitly.\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { CREATE_SMRT_BACKFILLS_TABLE } from '../system/schema.js';\n\nexport interface BackfillTrackerOptions {\n db: DatabaseInterface;\n}\n\nexport interface BackfillRecord {\n name: string;\n appliedAt: string;\n description: string | null;\n packageName: string | null;\n}\n\n/**\n * A tracker query proved that its inherited root initialization is stale.\n *\n * Transaction coordinators must roll back the current transaction, refresh\n * the root tracker outside that transaction, and retry with a fresh handle.\n */\nexport class BackfillTableUnavailableError extends Error {\n constructor(cause: unknown) {\n super('The shared _smrt_backfills table is unavailable.', { cause });\n this.name = 'BackfillTableUnavailableError';\n }\n}\n\n// Only root adapters can establish a durable shared initialization. A tracker\n// created around a transaction handle may have its DDL rolled back later, so\n// transaction-local successes must never poison this cache.\nconst initializationByObject = new WeakMap<object, Promise<void>>();\nconst inheritedInitializationByHandle = new WeakMap<object, object>();\n\nexport class BackfillTracker {\n private readonly db: DatabaseInterface;\n private initializePromise: Promise<void> | null = null;\n\n constructor(options: BackfillTrackerOptions) {\n this.db = options.db;\n }\n\n /**\n * Mark a transaction handle as inheriting a table initialized durably by its\n * root adapter. Framework transaction coordinators use this after root DDL\n * commits so transaction-local trackers can skip redundant `CREATE TABLE`.\n */\n static inheritInitialization(\n db: DatabaseInterface,\n rootDb: DatabaseInterface,\n ): void {\n inheritedInitializationByHandle.set(\n db as object,\n databaseTargetIdentity(rootDb),\n );\n }\n\n /**\n * Suppress lazy DDL on a caller-owned transaction.\n *\n * Marker reads may proceed when the table already exists. A missing table\n * raises `BackfillTableUnavailableError` so the caller can fail closed or\n * retry with a root adapter.\n */\n static requireExistingTable(db: DatabaseInterface): void {\n inheritedInitializationByHandle.set(\n db as object,\n databaseTargetIdentity(db),\n );\n }\n\n /** Forget a root initialization after a schema lifecycle reset. */\n static invalidateInitialization(db: DatabaseInterface): void {\n deleteSharedInitialization(databaseTargetIdentity(db));\n }\n\n /**\n * Create the `_smrt_backfills` table if it doesn't already exist.\n * Safe to call repeatedly and concurrently.\n */\n async initialize(): Promise<void> {\n if (inheritedInitializationByHandle.has(this.db as object)) {\n return;\n }\n\n const target = databaseTargetIdentity(this.db);\n const existing = getSharedInitialization(target);\n if (existing) {\n await existing;\n if (!isRootDatabase(this.db)) return;\n try {\n await this.db.query('SELECT 1 FROM _smrt_backfills LIMIT 1');\n return;\n } catch (error) {\n if (!isMissingBackfillTableError(error)) throw error;\n if (getSharedInitialization(target) === existing) {\n deleteSharedInitialization(target);\n }\n return this.initialize();\n }\n }\n\n if (isRootDatabase(this.db)) {\n const initialization = this.db\n .query(CREATE_SMRT_BACKFILLS_TABLE)\n .then(() => undefined)\n .catch((error) => {\n if (getSharedInitialization(target) === initialization) {\n deleteSharedInitialization(target);\n }\n throw error;\n });\n setSharedInitialization(target, initialization);\n return initialization;\n }\n\n if (!this.initializePromise) {\n this.initializePromise = this.db\n .query(CREATE_SMRT_BACKFILLS_TABLE)\n .then(() => undefined)\n .catch((error) => {\n this.initializePromise = null;\n throw error;\n });\n }\n return this.initializePromise;\n }\n\n /** Has the backfill named `name` already run? */\n async isApplied(name: string): Promise<boolean> {\n const result = await this.queryBackfillTable(\n 'SELECT 1 FROM _smrt_backfills WHERE name = ? LIMIT 1',\n name,\n );\n return result.rows.length > 0;\n }\n\n /**\n * Record that the backfill named `name` ran. Uses INSERT ... ON CONFLICT\n * so callers don't need to check `isApplied` first if they don't care\n * about distinguishing \"already applied\" from \"just applied\".\n */\n async recordApplied(\n name: string,\n options: { description?: string; packageName?: string } = {},\n ): Promise<void> {\n await this.queryBackfillTable(\n `INSERT INTO _smrt_backfills (name, description, package_name)\n VALUES (?, ?, ?)\n ON CONFLICT (name) DO NOTHING`,\n name,\n options.description ?? null,\n options.packageName ?? null,\n );\n }\n\n /**\n * Convenience wrapper: if `name` hasn't been applied, run `fn` and\n * record the result. Returns `{ ran, result }`:\n * - `{ ran: true, result: T }` — backfill was pending and `fn` ran\n * - `{ ran: false, result: null }` — backfill was already applied\n *\n * The discriminator avoids the `T | null` ambiguity an earlier shape had\n * (a backfill that legitimately returns `null` was indistinguishable\n * from \"already applied\"). Callers check `ran` to decide whether `fn`\n * executed; `result` carries whatever `fn` returned.\n *\n * This is the common pattern an app's migrate orchestration follows:\n * a list of `(name, runner)` pairs, each guarded by isApplied/run/record.\n *\n * **Single-runner only.** This is a check-then-act pattern with no\n * locking: two processes that call `runIfPending` for the same `name`\n * concurrently can both observe `isApplied === false`, both execute\n * `fn`, and only then race to `recordApplied`. The `ON CONFLICT DO\n * NOTHING` in `recordApplied` keeps the table clean but does NOT prevent\n * `fn` from running twice. Acceptable when backfills are run from a\n * single deploy-time migration step (the common case); if you need to\n * fan out backfills across multiple workers, wrap the call in your own\n * mutex (e.g. a Postgres advisory lock keyed by backfill name).\n *\n * **`fn` MUST be idempotent.** The order is `fn` → `recordApplied`, with\n * no surrounding transaction. If `fn` succeeds but `recordApplied`\n * throws (DB connection drops, transient error), the work has happened\n * but is not recorded — the next call sees `isApplied === false` and\n * re-runs `fn`. For non-idempotent work (slug rewrites that consume\n * source rows, one-shot lookups), wrap the entire call in a transaction\n * yourself or structure `fn` so a second execution is a no-op.\n */\n async runIfPending<T>(\n name: string,\n fn: () => Promise<T>,\n options: { description?: string; packageName?: string } = {},\n ): Promise<{ ran: false; result: null } | { ran: true; result: T }> {\n if (await this.isApplied(name)) return { ran: false, result: null };\n const result = await fn();\n await this.recordApplied(name, options);\n return { ran: true, result };\n }\n\n /** List every recorded backfill, oldest first. */\n async listApplied(): Promise<BackfillRecord[]> {\n const result = await this.queryBackfillTable(\n 'SELECT name, applied_at, description, package_name FROM _smrt_backfills ORDER BY applied_at ASC, name ASC',\n );\n return result.rows.map((row) => ({\n name: String(row.name ?? ''),\n appliedAt: normalizeAppliedAt(row.applied_at),\n description: row.description == null ? null : String(row.description),\n packageName: row.package_name == null ? null : String(row.package_name),\n }));\n }\n\n private async queryBackfillTable(sql: string, ...params: unknown[]) {\n await this.initialize();\n try {\n return await this.db.query(sql, ...params);\n } catch (error) {\n if (!isMissingBackfillTableError(error)) throw error;\n const inheritedRoot = inheritedInitializationByHandle.get(\n this.db as object,\n );\n this.resetInitialization(inheritedRoot);\n if (inheritedRoot) throw new BackfillTableUnavailableError(error);\n await this.initialize();\n return this.db.query(sql, ...params);\n }\n }\n\n private resetInitialization(inheritedRoot?: object): void {\n this.initializePromise = null;\n inheritedInitializationByHandle.delete(this.db as object);\n deleteSharedInitialization(databaseTargetIdentity(this.db));\n if (inheritedRoot) deleteSharedInitialization(inheritedRoot);\n }\n}\n\nfunction databaseTargetIdentity(db: DatabaseInterface): object {\n const client = db.client;\n return client !== null &&\n (typeof client === 'object' || typeof client === 'function')\n ? client\n : db;\n}\n\nfunction isRootDatabase(db: DatabaseInterface): boolean {\n return typeof db.beginTransaction === 'function';\n}\n\nfunction getSharedInitialization(target: object): Promise<void> | undefined {\n return initializationByObject.get(target);\n}\n\nfunction setSharedInitialization(\n target: object,\n initialization: Promise<void>,\n): void {\n initializationByObject.set(target, initialization);\n}\n\nfunction deleteSharedInitialization(target: object): void {\n initializationByObject.delete(target);\n}\n\nfunction isMissingBackfillTableError(error: unknown): boolean {\n const pending: unknown[] = [error];\n const seen = new Set<unknown>();\n const missingPattern =\n /(?:no such table|does not exist|doesn't exist|unknown table|not found)/iu;\n while (pending.length > 0) {\n const current = pending.pop();\n if (typeof current === 'string') {\n if (current.includes('_smrt_backfills') && missingPattern.test(current)) {\n return true;\n }\n continue;\n }\n if (!current || typeof current !== 'object' || seen.has(current)) continue;\n seen.add(current);\n if (\n current instanceof Error &&\n current.message.includes('_smrt_backfills') &&\n missingPattern.test(current.message)\n ) {\n return true;\n }\n const details = current as {\n cause?: unknown;\n context?: unknown;\n details?: unknown;\n originalError?: unknown;\n };\n pending.push(\n details.cause,\n details.context,\n details.details,\n details.originalError,\n );\n if (current instanceof AggregateError) pending.push(...current.errors);\n }\n return false;\n}\n\n/**\n * Convert a raw `applied_at` cell into an ISO 8601 string.\n *\n * Different DB drivers return this column in different shapes:\n * - Postgres `node-pg` returns a JS `Date` directly.\n * - SQLite drivers typically return the `CURRENT_TIMESTAMP` literal\n * `'YYYY-MM-DD HH:MM:SS'` (no `T`, no timezone). V8's `Date`\n * constructor parses this as local time, but that's\n * implementation-defined and other runtimes may return Invalid Date.\n * - A corrupted row could return any string.\n *\n * If the value parses to a valid Date we return `toISOString()`. If it\n * doesn't (or the column is null/empty), we fall back to the raw string —\n * better to surface a non-ISO timestamp than crash `listApplied()` with a\n * `RangeError` and take down the caller.\n */\nfunction normalizeAppliedAt(value: unknown): string {\n if (value == null || value === '') return '';\n const raw = String(value);\n const parsed = new Date(raw);\n if (Number.isNaN(parsed.getTime())) {\n return raw;\n }\n return parsed.toISOString();\n}\n"],"mappings":";;;;;;;;AAkCA,IAAa,gCAAb,cAAmD,MAAM;CACvD,YAAY,OAAgB;EAC1B,MAAM,oDAAoD,EAAE,MAAM,CAAC;EACnE,KAAK,OAAO;CACd;AACF;AAKA,IA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ClD,IAAI,SAAS,QAAQ,UAAU,IAAI,OAAO;CAC1C,MAAM,MAAM,OAAO,KAAK;CACxB,MAAM,SAAS,IAAI,KAAK,GAAG;CAC3B,IAAI,OAAO,MAAM,OAAO,QAAQ,CAAC,GAC/B,OAAO;CAET,OAAO,OAAO,YAAY;AAC5B"}
|
|
1
|
+
{"version":3,"file":"backfill-tracker.js","names":[],"sources":["../../src/migrations/backfill-tracker.ts"],"sourcesContent":["/**\n * Tracks application-specific data backfills (not schema migrations).\n *\n * Sits next to `MigrationTracker` but is intentionally minimal — backfills\n * have no checksum, no rollback semantics, no DDL. They're \"this data\n * correction has run, don't run it again\" markers, keyed by a stable\n * backfill name the app chooses.\n *\n * Backed by the `_smrt_backfills` system table (see\n * `../system/schema.ts`). The table is created lazily on first use —\n * every public method (`isApplied`, `recordApplied`, `runIfPending`,\n * `listApplied`) awaits `initialize()` itself, so consumers never need\n * to call `initialize()` explicitly.\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n assertPostgresSystemTimestampsCurrent,\n getDatabaseEngine,\n} from '../system/compatibility.js';\nimport {\n CREATE_SMRT_BACKFILLS_TABLE,\n getSystemTableDDLForEngine,\n} from '../system/schema.js';\n\nexport interface BackfillTrackerOptions {\n db: DatabaseInterface;\n}\n\nexport interface BackfillRecord {\n name: string;\n appliedAt: string;\n description: string | null;\n packageName: string | null;\n}\n\n/**\n * A tracker query proved that its inherited root initialization is stale.\n *\n * Transaction coordinators must roll back the current transaction, refresh\n * the root tracker outside that transaction, and retry with a fresh handle.\n */\nexport class BackfillTableUnavailableError extends Error {\n constructor(cause: unknown) {\n super('The shared _smrt_backfills table is unavailable.', { cause });\n this.name = 'BackfillTableUnavailableError';\n }\n}\n\n// Only root adapters can establish a durable shared initialization. A tracker\n// created around a transaction handle may have its DDL rolled back later, so\n// transaction-local successes must never poison this cache.\nconst initializationByObject = new WeakMap<object, Promise<void>>();\nconst inheritedInitializationByHandle = new WeakMap<object, object>();\n\nexport class BackfillTracker {\n private readonly db: DatabaseInterface;\n private initializePromise: Promise<void> | null = null;\n\n constructor(options: BackfillTrackerOptions) {\n this.db = options.db;\n }\n\n /**\n * Mark a transaction handle as inheriting a table initialized durably by its\n * root adapter. Framework transaction coordinators use this after root DDL\n * commits so transaction-local trackers can skip redundant `CREATE TABLE`.\n */\n static inheritInitialization(\n db: DatabaseInterface,\n rootDb: DatabaseInterface,\n ): void {\n inheritedInitializationByHandle.set(\n db as object,\n databaseTargetIdentity(rootDb),\n );\n }\n\n /**\n * Suppress lazy DDL on a caller-owned transaction.\n *\n * Marker reads may proceed when the table already exists. A missing table\n * raises `BackfillTableUnavailableError` so the caller can fail closed or\n * retry with a root adapter.\n */\n static requireExistingTable(db: DatabaseInterface): void {\n inheritedInitializationByHandle.set(\n db as object,\n databaseTargetIdentity(db),\n );\n }\n\n /** Forget a root initialization after a schema lifecycle reset. */\n static invalidateInitialization(db: DatabaseInterface): void {\n deleteSharedInitialization(databaseTargetIdentity(db));\n }\n\n private async createTable(): Promise<void> {\n const ddl = getSystemTableDDLForEngine(\n CREATE_SMRT_BACKFILLS_TABLE,\n getDatabaseEngine(this.db),\n );\n await this.db.query(ddl);\n await assertPostgresSystemTimestampsCurrent(this.db);\n }\n\n /**\n * Create the `_smrt_backfills` table if it doesn't already exist.\n * Safe to call repeatedly and concurrently.\n */\n async initialize(): Promise<void> {\n if (inheritedInitializationByHandle.has(this.db as object)) {\n return;\n }\n\n const target = databaseTargetIdentity(this.db);\n const existing = getSharedInitialization(target);\n if (existing) {\n await existing;\n if (!isRootDatabase(this.db)) return;\n try {\n await this.db.query('SELECT 1 FROM _smrt_backfills LIMIT 1');\n return;\n } catch (error) {\n if (!isMissingBackfillTableError(error)) throw error;\n if (getSharedInitialization(target) === existing) {\n deleteSharedInitialization(target);\n }\n return this.initialize();\n }\n }\n\n if (isRootDatabase(this.db)) {\n const initialization = this.createTable()\n .then(() => undefined)\n .catch((error) => {\n if (getSharedInitialization(target) === initialization) {\n deleteSharedInitialization(target);\n }\n throw error;\n });\n setSharedInitialization(target, initialization);\n return initialization;\n }\n\n if (!this.initializePromise) {\n this.initializePromise = this.createTable()\n .then(() => undefined)\n .catch((error) => {\n this.initializePromise = null;\n throw error;\n });\n }\n return this.initializePromise;\n }\n\n /** Has the backfill named `name` already run? */\n async isApplied(name: string): Promise<boolean> {\n const result = await this.queryBackfillTable(\n 'SELECT 1 FROM _smrt_backfills WHERE name = ? LIMIT 1',\n name,\n );\n return result.rows.length > 0;\n }\n\n /**\n * Record that the backfill named `name` ran. Uses INSERT ... ON CONFLICT\n * so callers don't need to check `isApplied` first if they don't care\n * about distinguishing \"already applied\" from \"just applied\".\n */\n async recordApplied(\n name: string,\n options: { description?: string; packageName?: string } = {},\n ): Promise<void> {\n await this.queryBackfillTable(\n `INSERT INTO _smrt_backfills (name, description, package_name)\n VALUES (?, ?, ?)\n ON CONFLICT (name) DO NOTHING`,\n name,\n options.description ?? null,\n options.packageName ?? null,\n );\n }\n\n /**\n * Convenience wrapper: if `name` hasn't been applied, run `fn` and\n * record the result. Returns `{ ran, result }`:\n * - `{ ran: true, result: T }` — backfill was pending and `fn` ran\n * - `{ ran: false, result: null }` — backfill was already applied\n *\n * The discriminator avoids the `T | null` ambiguity an earlier shape had\n * (a backfill that legitimately returns `null` was indistinguishable\n * from \"already applied\"). Callers check `ran` to decide whether `fn`\n * executed; `result` carries whatever `fn` returned.\n *\n * This is the common pattern an app's migrate orchestration follows:\n * a list of `(name, runner)` pairs, each guarded by isApplied/run/record.\n *\n * **Single-runner only.** This is a check-then-act pattern with no\n * locking: two processes that call `runIfPending` for the same `name`\n * concurrently can both observe `isApplied === false`, both execute\n * `fn`, and only then race to `recordApplied`. The `ON CONFLICT DO\n * NOTHING` in `recordApplied` keeps the table clean but does NOT prevent\n * `fn` from running twice. Acceptable when backfills are run from a\n * single deploy-time migration step (the common case); if you need to\n * fan out backfills across multiple workers, wrap the call in your own\n * mutex (e.g. a Postgres advisory lock keyed by backfill name).\n *\n * **`fn` MUST be idempotent.** The order is `fn` → `recordApplied`, with\n * no surrounding transaction. If `fn` succeeds but `recordApplied`\n * throws (DB connection drops, transient error), the work has happened\n * but is not recorded — the next call sees `isApplied === false` and\n * re-runs `fn`. For non-idempotent work (slug rewrites that consume\n * source rows, one-shot lookups), wrap the entire call in a transaction\n * yourself or structure `fn` so a second execution is a no-op.\n */\n async runIfPending<T>(\n name: string,\n fn: () => Promise<T>,\n options: { description?: string; packageName?: string } = {},\n ): Promise<{ ran: false; result: null } | { ran: true; result: T }> {\n if (await this.isApplied(name)) return { ran: false, result: null };\n const result = await fn();\n await this.recordApplied(name, options);\n return { ran: true, result };\n }\n\n /** List every recorded backfill, oldest first. */\n async listApplied(): Promise<BackfillRecord[]> {\n const result = await this.queryBackfillTable(\n 'SELECT name, applied_at, description, package_name FROM _smrt_backfills ORDER BY applied_at ASC, name ASC',\n );\n return result.rows.map((row) => ({\n name: String(row.name ?? ''),\n appliedAt: normalizeAppliedAt(row.applied_at),\n description: row.description == null ? null : String(row.description),\n packageName: row.package_name == null ? null : String(row.package_name),\n }));\n }\n\n private async queryBackfillTable(sql: string, ...params: unknown[]) {\n await this.initialize();\n try {\n return await this.db.query(sql, ...params);\n } catch (error) {\n if (!isMissingBackfillTableError(error)) throw error;\n const inheritedRoot = inheritedInitializationByHandle.get(\n this.db as object,\n );\n this.resetInitialization(inheritedRoot);\n if (inheritedRoot) throw new BackfillTableUnavailableError(error);\n await this.initialize();\n return this.db.query(sql, ...params);\n }\n }\n\n private resetInitialization(inheritedRoot?: object): void {\n this.initializePromise = null;\n inheritedInitializationByHandle.delete(this.db as object);\n deleteSharedInitialization(databaseTargetIdentity(this.db));\n if (inheritedRoot) deleteSharedInitialization(inheritedRoot);\n }\n}\n\nfunction databaseTargetIdentity(db: DatabaseInterface): object {\n const client = db.client;\n return client !== null &&\n (typeof client === 'object' || typeof client === 'function')\n ? client\n : db;\n}\n\nfunction isRootDatabase(db: DatabaseInterface): boolean {\n return typeof db.beginTransaction === 'function';\n}\n\nfunction getSharedInitialization(target: object): Promise<void> | undefined {\n return initializationByObject.get(target);\n}\n\nfunction setSharedInitialization(\n target: object,\n initialization: Promise<void>,\n): void {\n initializationByObject.set(target, initialization);\n}\n\nfunction deleteSharedInitialization(target: object): void {\n initializationByObject.delete(target);\n}\n\nfunction isMissingBackfillTableError(error: unknown): boolean {\n const pending: unknown[] = [error];\n const seen = new Set<unknown>();\n const missingPattern =\n /(?:no such table|does not exist|doesn't exist|unknown table|not found)/iu;\n while (pending.length > 0) {\n const current = pending.pop();\n if (typeof current === 'string') {\n if (current.includes('_smrt_backfills') && missingPattern.test(current)) {\n return true;\n }\n continue;\n }\n if (!current || typeof current !== 'object' || seen.has(current)) continue;\n seen.add(current);\n if (\n current instanceof Error &&\n current.message.includes('_smrt_backfills') &&\n missingPattern.test(current.message)\n ) {\n return true;\n }\n const details = current as {\n cause?: unknown;\n context?: unknown;\n details?: unknown;\n originalError?: unknown;\n };\n pending.push(\n details.cause,\n details.context,\n details.details,\n details.originalError,\n );\n if (current instanceof AggregateError) pending.push(...current.errors);\n }\n return false;\n}\n\n/**\n * Convert a raw `applied_at` cell into an ISO 8601 string.\n *\n * Different DB drivers return this column in different shapes:\n * - Postgres `node-pg` returns a JS `Date` directly.\n * - SQLite drivers typically return the `CURRENT_TIMESTAMP` literal\n * `'YYYY-MM-DD HH:MM:SS'` (no `T`, no timezone). V8's `Date`\n * constructor parses this as local time, but that's\n * implementation-defined and other runtimes may return Invalid Date.\n * - A corrupted row could return any string.\n *\n * If the value parses to a valid Date we return `toISOString()`. If it\n * doesn't (or the column is null/empty), we fall back to the raw string —\n * better to surface a non-ISO timestamp than crash `listApplied()` with a\n * `RangeError` and take down the caller.\n */\nfunction normalizeAppliedAt(value: unknown): string {\n if (value == null || value === '') return '';\n const raw = String(value);\n const parsed = new Date(raw);\n if (Number.isNaN(parsed.getTime())) {\n return raw;\n }\n return parsed.toISOString();\n}\n"],"mappings":";;;;;;;;;AAyCA,IAA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,OAAO,GAEnC,OAAO;EAET,MAAM,UAAU;EAMhB,QAAQ,KACN,QAAQ,OACR,QAAQ,SACR,QAAQ,SACR,QAAQ,aACV;EACA,IAAI,mBAAmB,gBAAgB,QAAQ,KAAK,GAAG,QAAQ,MAAM;CACvE;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAS,mBAAmB,OAAwB;CAClD,IAAI,SAAS,QAAQ,UAAU,IAAI,OAAO;CAC1C,MAAM,MAAM,OAAO,KAAK;CACxB,MAAM,SAAS,IAAI,KAAK,GAAG;CAC3B,IAAI,OAAO,MAAM,OAAO,QAAQ,CAAC,GAC/B,OAAO;CAET,OAAO,OAAO,YAAY;AAC5B"}
|
|
@@ -28,6 +28,15 @@ export interface DiffOptions {
|
|
|
28
28
|
* flavored SQL on a connection whose caller meant Postgres or DuckDB.
|
|
29
29
|
*/
|
|
30
30
|
engineHint?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Explicit confirmation that every historical writer of legacy PostgreSQL
|
|
33
|
+
* Date columns used UTC wall times. Without this acknowledgement,
|
|
34
|
+
* TIMESTAMP/TEXT/JSON to TIMESTAMPTZ drift is reported as manual rather
|
|
35
|
+
* than reinterpreted automatically.
|
|
36
|
+
*/
|
|
37
|
+
postgresTimestampMigration?: {
|
|
38
|
+
legacyTimezone: 'UTC';
|
|
39
|
+
};
|
|
31
40
|
}
|
|
32
41
|
/**
|
|
33
42
|
* Normalize a partial-index `WHERE` predicate so semantically-identical
|
|
@@ -196,6 +205,9 @@ export declare class SchemaComparer {
|
|
|
196
205
|
* - TEXT→JSON: The column stores JSON data serialized as text (arrays, objects)
|
|
197
206
|
* - TEXT/JSON→TIMESTAMP: Legacy system columns stored timestamp strings
|
|
198
207
|
* before newer manifests normalized the column type.
|
|
208
|
+
* - PostgreSQL TIMESTAMP→TIMESTAMPTZ: Legacy SMRT Date values were written
|
|
209
|
+
* as UTC ISO wall times, so interpreting the naive value as UTC preserves
|
|
210
|
+
* the originally supplied instant.
|
|
199
211
|
* - INTEGER→REAL: Safe widening of integer to floating point
|
|
200
212
|
* - TEXT/REAL→INTEGER on PostgreSQL: explicit data-checked repairs for
|
|
201
213
|
* legacy integer columns that were previously stored as text/real.
|
|
@@ -224,6 +236,12 @@ export declare class SchemaComparer {
|
|
|
224
236
|
* generated migration must fail before the ALTER can silently change data.
|
|
225
237
|
*/
|
|
226
238
|
private generatePostgresIntegerPreflightSQL;
|
|
239
|
+
/**
|
|
240
|
+
* Require a UTC migration session before reattaching the offset discarded by
|
|
241
|
+
* legacy PostgreSQL TIMESTAMP columns. This is a guardrail, not provenance:
|
|
242
|
+
* operators must also confirm historical default/raw writers used UTC.
|
|
243
|
+
*/
|
|
244
|
+
private generatePostgresTimestampPreflightSQL;
|
|
227
245
|
private quoteLiteral;
|
|
228
246
|
/**
|
|
229
247
|
* Generate SQL for adding a column
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"differ.d.ts","sourceRoot":"","sources":["../../src/migrations/differ.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,OAAO,KAAK,EAGV,YAAY,EACZ,gBAAgB,EAChB,UAAU,EAEX,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,iBAAiB,EAAsB,MAAM,YAAY,CAAC;AA8BxE;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,iEAAiE;IACjE,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,kEAAkE;IAClE,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;;;;OAOG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,iDAAiD;IACjD,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"differ.d.ts","sourceRoot":"","sources":["../../src/migrations/differ.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,OAAO,KAAK,EAGV,YA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) {
|
|
469
|
-
const upper = type.toUpperCase().trim();
|
|
469
|
+
const upper = type.toUpperCase().trim().replace(/\(\s*\d+\s*\)/g, "");
|
|
470
470
|
if (/^(INTEGER|INT|BIGINT|SMALLINT|TINYINT)$/i.test(upper)) return "INTEGER";
|
|
471
471
|
if (/^(TEXT|CLOB|STRING|VARCHAR|CHAR)/i.test(upper)) return "TEXT";
|
|
472
472
|
if (/^UUID$/i.test(upper)) return "UUID";
|
|
473
473
|
if (/^(REAL|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER)/i.test(upper)) return "REAL";
|
|
474
474
|
if (/^(BOOLEAN|BOOL)/i.test(upper)) return "BOOLEAN";
|
|
475
|
-
if (/^(
|
|
475
|
+
if (/^(TIMESTAMPTZ|TIMESTAMP\s+WITH\s+TIME\s+ZONE)$/i.test(upper)) return "TIMESTAMPTZ";
|
|
476
|
+
if (/^(DATETIME|TIMESTAMP(?:\s+WITHOUT\s+TIME\s+ZONE)?|DATE|TIME)$/i.test(upper)) return "TIMESTAMP";
|
|
476
477
|
if (/^(BLOB|BINARY|BYTEA)/i.test(upper)) return "BLOB";
|
|
477
478
|
if (/^(JSON|JSONB)/i.test(upper)) return "JSON";
|
|
478
479
|
return upper;
|
|
@@ -484,6 +485,9 @@ var SchemaComparer = class {
|
|
|
484
485
|
* - TEXT→JSON: The column stores JSON data serialized as text (arrays, objects)
|
|
485
486
|
* - TEXT/JSON→TIMESTAMP: Legacy system columns stored timestamp strings
|
|
486
487
|
* before newer manifests normalized the column type.
|
|
488
|
+
* - PostgreSQL TIMESTAMP→TIMESTAMPTZ: Legacy SMRT Date values were written
|
|
489
|
+
* as UTC ISO wall times, so interpreting the naive value as UTC preserves
|
|
490
|
+
* the originally supplied instant.
|
|
487
491
|
* - INTEGER→REAL: Safe widening of integer to floating point
|
|
488
492
|
* - TEXT/REAL→INTEGER on PostgreSQL: explicit data-checked repairs for
|
|
489
493
|
* legacy integer columns that were previously stored as text/real.
|
|
@@ -495,12 +499,17 @@ var SchemaComparer = class {
|
|
|
495
499
|
isCompatibleTypeUpgrade(manifestType, dbType) {
|
|
496
500
|
const manifest = this.normalizeType(manifestType);
|
|
497
501
|
const db = this.normalizeType(dbType);
|
|
502
|
+
if (this.engine === "postgres" && manifest === "TIMESTAMP" && [
|
|
503
|
+
"TIMESTAMP",
|
|
504
|
+
"TEXT",
|
|
505
|
+
"JSON"
|
|
506
|
+
].includes(db) && this.ddlStrategy.mapType("TIMESTAMP") === "TIMESTAMPTZ") return this.options.postgresTimestampMigration?.legacyTimezone === "UTC";
|
|
498
507
|
if (manifest === "JSON" && db === "TEXT") return true;
|
|
499
508
|
if (manifest === "TEXT" && db === "JSON") return true;
|
|
500
509
|
if (manifest === "TEXT" && db === "UUID") return true;
|
|
501
510
|
if (manifest === "REAL" && db === "INTEGER") return true;
|
|
502
511
|
if (this.engine === "postgres" && manifest === "INTEGER" && (db === "TEXT" || db === "REAL")) return true;
|
|
503
|
-
if (manifest === "TIMESTAMP" && (db === "TEXT" || db === "JSON")) return true;
|
|
512
|
+
if (manifest === "TIMESTAMP" && (db === "TEXT" || db === "JSON") && this.engine !== "postgres") return true;
|
|
504
513
|
return false;
|
|
505
514
|
}
|
|
506
515
|
/**
|
|
@@ -524,7 +533,11 @@ var SchemaComparer = class {
|
|
|
524
533
|
case "postgres": {
|
|
525
534
|
const manifestNormalized = this.normalizeType(manifestType);
|
|
526
535
|
const dbNormalized = this.normalizeType(dbType);
|
|
527
|
-
const preflightSQL = manifestNormalized === "INTEGER" && (dbNormalized === "TEXT" || dbNormalized === "REAL") ? this.generatePostgresIntegerPreflightSQL(quotedTable, quotedCol, tableName, colName, dbNormalized) :
|
|
536
|
+
const preflightSQL = manifestNormalized === "INTEGER" && (dbNormalized === "TEXT" || dbNormalized === "REAL") ? this.generatePostgresIntegerPreflightSQL(quotedTable, quotedCol, tableName, colName, dbNormalized) : manifestNormalized === "TIMESTAMP" && [
|
|
537
|
+
"TIMESTAMP",
|
|
538
|
+
"TEXT",
|
|
539
|
+
"JSON"
|
|
540
|
+
].includes(dbNormalized) && this.normalizeType(targetType) === "TIMESTAMPTZ" ? this.generatePostgresTimestampPreflightSQL(tableName, colName) : null;
|
|
528
541
|
const clauses = [];
|
|
529
542
|
if (colDef.defaultValue !== void 0) clauses.push(`ALTER COLUMN ${quotedCol} DROP DEFAULT`);
|
|
530
543
|
let typeClause = `ALTER COLUMN ${quotedCol} TYPE ${targetType}`;
|
|
@@ -533,7 +546,8 @@ var SchemaComparer = class {
|
|
|
533
546
|
else if (manifestNormalized === "TEXT" && dbNormalized === "UUID") typeClause += ` USING ${quotedCol}::text`;
|
|
534
547
|
else if (manifestNormalized === "INTEGER" && dbNormalized === "TEXT") typeClause += ` USING trim(${quotedCol}::text)::integer`;
|
|
535
548
|
else if (manifestNormalized === "INTEGER" && dbNormalized === "REAL") typeClause += ` USING ${quotedCol}::integer`;
|
|
536
|
-
else if (manifestNormalized === "TIMESTAMP" && (dbNormalized === "TEXT" || dbNormalized === "JSON")) typeClause += ` USING NULLIF(NULLIF(trim(both '"' from ${quotedCol}::text), ''), 'null')::
|
|
549
|
+
else if (manifestNormalized === "TIMESTAMP" && (dbNormalized === "TEXT" || dbNormalized === "JSON")) typeClause += ` USING NULLIF(NULLIF(trim(both '"' from ${quotedCol}::text), ''), 'null')::timestamptz`;
|
|
550
|
+
else if (manifestNormalized === "TIMESTAMP" && dbNormalized === "TIMESTAMP" && this.normalizeType(targetType) === "TIMESTAMPTZ") typeClause += ` USING ${quotedCol} AT TIME ZONE 'UTC'`;
|
|
537
551
|
clauses.push(typeClause);
|
|
538
552
|
if (colDef.defaultValue !== void 0) {
|
|
539
553
|
const formattedDefault = this.ddlStrategy.formatDefaultValue(colDef.defaultValue, validatedType);
|
|
@@ -566,6 +580,15 @@ var SchemaComparer = class {
|
|
|
566
580
|
const message = `Cannot convert ${tableName}.${colName} to INTEGER: found non-integer values`;
|
|
567
581
|
return `DO $$ BEGIN IF EXISTS (SELECT 1 FROM ${quotedTable} WHERE ${invalidCondition}) THEN RAISE EXCEPTION ${this.quoteLiteral(message)}; END IF; END $$`;
|
|
568
582
|
}
|
|
583
|
+
/**
|
|
584
|
+
* Require a UTC migration session before reattaching the offset discarded by
|
|
585
|
+
* legacy PostgreSQL TIMESTAMP columns. This is a guardrail, not provenance:
|
|
586
|
+
* operators must also confirm historical default/raw writers used UTC.
|
|
587
|
+
*/
|
|
588
|
+
generatePostgresTimestampPreflightSQL(tableName, colName) {
|
|
589
|
+
const message = `Cannot convert ${tableName}.${colName} to TIMESTAMPTZ outside a UTC PostgreSQL session; confirm historical writers used UTC and SET TIME ZONE UTC`;
|
|
590
|
+
return `DO $$ BEGIN IF upper(current_setting('TimeZone')) NOT IN ('UTC', 'ETC/UTC', 'GMT') THEN RAISE EXCEPTION ${this.quoteLiteral(message)}; END IF; END $$`;
|
|
591
|
+
}
|
|
569
592
|
quoteLiteral(value) {
|
|
570
593
|
return `'${value.replace(/'/g, "''")}'`;
|
|
571
594
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"differ.js","names":[],"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 * 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"],"mappings":";;;;;;;;;;;AAqBA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;;;AAK7C,IAAM,uCAAyC,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;AAUD,SAAS,mBAAmB,MAAmC;CAC7D,OAAO,qBAAqB,IAAI,IAAmB;AACrD;;;;;;;;;AAwCA,IAAM,2BAA2B,CAAC,SAAS,MAAM;AAEjD,SAAS,uBAAuB,MAAuB;CACrD,OAAO,yBAAyB,MAAM,WAAW,KAAK,SAAS,MAAM,CAAC;AACxE;AAEA,SAAS,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D,IAAI,KAAK,uBAAuB,KAAK,OACnC,OAAO,UAAU;EAEnB,OAAO;CACT;;;;;;;;;;;;;;;CAgBA,qBAA6B,WAA2B;EACtD,OAAO,wBAAwB,KAAK,gBAAgB,SAAS;CAC/D;AACF;;;;AAKA,eAAsB,mBACpB,IACA,iBACA,UAAuB,CAAC,GACH;CAErB,OAAO,IADc,eAAe,IAAI,OACjC,CAAA,CAAS,QAAQ,eAAe;AACzC;;;;AAKA,SAAgB,qBAAqB,MAA2B;CAC9D,IAAI,KAAK,aAAa,SAAS,GAAG,OAAO;CACzC,IAAI,KAAK,eAAe,SAAS,GAAG,OAAO;CAC3C,OAAO,KAAK,QAAQ,MAAM,MAAM,EAAE,SAAS,eAAe;AAC5D;;;;AAKA,SAAgB,eAAe,MAA4B;CACzD,MAAM,aAAuB,CAAC;CAM9B,KAAK,MAAM,UAAU,KAAK,SACxB,IAAI,OAAO,SAAS,iBAClB,WAAW,KACT,GAAI,OAAO,kBAAkB,OAAO,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC,EAC5D;CAIJ,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"differ.js","names":[],"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 * Explicit confirmation that every historical writer of legacy PostgreSQL\n * Date columns used UTC wall times. Without this acknowledgement,\n * TIMESTAMP/TEXT/JSON to TIMESTAMPTZ drift is reported as manual rather\n * than reinterpreted automatically.\n */\n postgresTimestampMigration?: { legacyTimezone: 'UTC' };\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\n .toUpperCase()\n .trim()\n .replace(/\\(\\s*\\d+\\s*\\)/g, '');\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 // PostgreSQL distinguishes instants from timezone-naive wall times. Keep\n // those in separate comparison buckets so legacy TIMESTAMP columns are\n // migrated to the TIMESTAMPTZ representation used for JavaScript Date.\n if (/^(TIMESTAMPTZ|TIMESTAMP\\s+WITH\\s+TIME\\s+ZONE)$/i.test(upper)) {\n return 'TIMESTAMPTZ';\n }\n\n // Date/time types without timezone semantics\n if (\n /^(DATETIME|TIMESTAMP(?:\\s+WITHOUT\\s+TIME\\s+ZONE)?|DATE|TIME)$/i.test(\n upper,\n )\n ) {\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 * - PostgreSQL TIMESTAMP→TIMESTAMPTZ: Legacy SMRT Date values were written\n * as UTC ISO wall times, so interpreting the naive value as UTC preserves\n * the originally supplied instant.\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 if (\n this.engine === 'postgres' &&\n manifest === 'TIMESTAMP' &&\n ['TIMESTAMP', 'TEXT', 'JSON'].includes(db) &&\n this.ddlStrategy.mapType('TIMESTAMP') === 'TIMESTAMPTZ'\n ) {\n return this.options.postgresTimestampMigration?.legacyTimezone === 'UTC';\n }\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 (\n manifest === 'TIMESTAMP' &&\n (db === 'TEXT' || db === 'JSON') &&\n this.engine !== 'postgres'\n ) {\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 : manifestNormalized === 'TIMESTAMP' &&\n ['TIMESTAMP', 'TEXT', 'JSON'].includes(dbNormalized) &&\n this.normalizeType(targetType) === 'TIMESTAMPTZ'\n ? this.generatePostgresTimestampPreflightSQL(tableName, colName)\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')::timestamptz`;\n } else if (\n manifestNormalized === 'TIMESTAMP' &&\n dbNormalized === 'TIMESTAMP' &&\n this.normalizeType(targetType) === 'TIMESTAMPTZ'\n ) {\n // SMRT's PostgreSQL adapter serialized Date values to UTC ISO strings.\n // A legacy TIMESTAMP column discarded the trailing offset but kept\n // that UTC wall time. Reattach UTC explicitly so migration is\n // deterministic regardless of the database/session timezone.\n typeClause += ` USING ${quotedCol} AT TIME ZONE 'UTC'`;\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 /**\n * Require a UTC migration session before reattaching the offset discarded by\n * legacy PostgreSQL TIMESTAMP columns. This is a guardrail, not provenance:\n * operators must also confirm historical default/raw writers used UTC.\n */\n private generatePostgresTimestampPreflightSQL(\n tableName: string,\n colName: string,\n ): string {\n const message =\n `Cannot convert ${tableName}.${colName} to TIMESTAMPTZ outside a UTC ` +\n 'PostgreSQL session; confirm historical writers used UTC and SET TIME ZONE UTC';\n return `DO $$ BEGIN IF upper(current_setting('TimeZone')) NOT IN ('UTC', 'ETC/UTC', 'GMT') 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.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