viborm 1.14.0 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/bun-sql.d.mts +1 -1
  3. package/dist/bun-sqlite.d.mts +1 -1
  4. package/dist/cache/cloudflare-kv.d.mts +1 -1
  5. package/dist/cache/memory.d.mts +1 -1
  6. package/dist/cache.d.mts +2 -2
  7. package/dist/cli.mjs +1 -1
  8. package/dist/{client-BDb96x1r.d.mts → client-CRxfhw2y.d.mts} +1 -1
  9. package/dist/client-y7TV0PRZ.mjs +9 -0
  10. package/dist/client-y7TV0PRZ.mjs.map +1 -0
  11. package/dist/client.d.mts +2 -2
  12. package/dist/config.d.mts +1 -1
  13. package/dist/d1.d.mts +1 -1
  14. package/dist/{database-adapter-BhQJPaTf.d.mts → database-adapter-BGqvjeEy.d.mts} +7 -6
  15. package/dist/{document-D2OQKsOc.d.mts → document-BVTQ-cF-.d.mts} +1 -1
  16. package/dist/{driver-AeJqJUQb.d.mts → driver-BBEmaJZy.d.mts} +1 -1
  17. package/dist/driver-BIXhOH2_.mjs.map +1 -1
  18. package/dist/driver.d.mts +1 -1
  19. package/dist/durable-object.d.mts +1 -1
  20. package/dist/every-tOgQmaIE.mjs +2 -0
  21. package/dist/{every-3LgBFWRs.mjs.map → every-tOgQmaIE.mjs.map} +1 -1
  22. package/dist/{exports-Crs9nBjW.d.mts → exports-COCJ8f2f.d.mts} +1 -1
  23. package/dist/index.d.mts +1 -1
  24. package/dist/index.mjs +1 -1
  25. package/dist/instrumentation.d.mts +1 -1
  26. package/dist/instrumentation.mjs +1 -1
  27. package/dist/{introspect-6m25Fg-d.mjs → introspect-Bm6xnXcG.mjs} +2 -2
  28. package/dist/{introspect-6m25Fg-d.mjs.map → introspect-Bm6xnXcG.mjs.map} +1 -1
  29. package/dist/{libsql-oBy9Irhf.mjs → libsql-DuGR904j.mjs} +3 -3
  30. package/dist/{libsql-oBy9Irhf.mjs.map → libsql-DuGR904j.mjs.map} +1 -1
  31. package/dist/libsql.d.mts +1 -1
  32. package/dist/{memory-CniC_5jH.mjs → memory-G4cSuc6A.mjs} +2 -2
  33. package/dist/{memory-CniC_5jH.mjs.map → memory-G4cSuc6A.mjs.map} +1 -1
  34. package/dist/migrations/mysql.d.mts +4 -4
  35. package/dist/migrations/mysql.mjs +1 -1
  36. package/dist/migrations/postgres.d.mts +4 -4
  37. package/dist/migrations/postgres.mjs +1 -1
  38. package/dist/migrations/snowflake.d.mts +4 -4
  39. package/dist/migrations/snowflake.mjs +1 -1
  40. package/dist/migrations/sqlite.d.mts +4 -4
  41. package/dist/migrations/sqlite.mjs +1 -1
  42. package/dist/migrations/surrealdb.d.mts +4 -4
  43. package/dist/migrations/surrealdb.mjs +1 -1
  44. package/dist/migrations/tenant.d.mts +2 -2
  45. package/dist/migrations/tenant.mjs +1 -1
  46. package/dist/migrations.d.mts +4 -4
  47. package/dist/migrations.mjs +1 -1
  48. package/dist/{mysql-CyEtis4b.mjs → mysql-BNXWfTOo.mjs} +8 -8
  49. package/dist/{mysql-CyEtis4b.mjs.map → mysql-BNXWfTOo.mjs.map} +1 -1
  50. package/dist/mysql2.d.mts +1 -1
  51. package/dist/neon-http.d.mts +1 -1
  52. package/dist/{object-store-D5bNfAF2.d.mts → object-store-B_YMoW8u.d.mts} +3 -3
  53. package/dist/on.d.mts +1 -1
  54. package/dist/ordering.d.mts +1 -1
  55. package/dist/permissions.d.mts +1 -1
  56. package/dist/pg.d.mts +1 -1
  57. package/dist/pglite.d.mts +1 -1
  58. package/dist/planetscale.d.mts +1 -1
  59. package/dist/{planner-Beph-ERw.d.mts → planner-DHjdvjwk.d.mts} +1 -1
  60. package/dist/{postgres-PJ2p5pPk.mjs → postgres-CDdh5dSP.mjs} +11 -11
  61. package/dist/{postgres-PJ2p5pPk.mjs.map → postgres-CDdh5dSP.mjs.map} +1 -1
  62. package/dist/postgres.d.mts +1 -1
  63. package/dist/schema/introspect.d.mts +2 -2
  64. package/dist/schema/introspect.mjs +1 -1
  65. package/dist/schema/json.d.mts +2 -2
  66. package/dist/schema.d.mts +1 -1
  67. package/dist/{serializer-DG5kl84q.mjs → serializer-rBq3v1xr.mjs} +3 -3
  68. package/dist/serializer-rBq3v1xr.mjs.map +1 -0
  69. package/dist/{snowflake-BgbbuBnq.mjs → snowflake-UOCC820W.mjs} +2 -2
  70. package/dist/{snowflake-BgbbuBnq.mjs.map → snowflake-UOCC820W.mjs.map} +1 -1
  71. package/dist/snowflake.d.mts +1 -1
  72. package/dist/soft-delete.d.mts +1 -1
  73. package/dist/{sql-DYyn6m_F.mjs → sql-Dl6nykFV.mjs} +2 -2
  74. package/dist/{sql-DYyn6m_F.mjs.map → sql-Dl6nykFV.mjs.map} +1 -1
  75. package/dist/sqlite3.d.mts +1 -1
  76. package/dist/surrealdb.d.mts +7 -2
  77. package/dist/surrealdb.mjs +1 -1
  78. package/dist/surrealdb.mjs.map +1 -1
  79. package/dist/surrealql-C1dp1sWw.mjs +2 -0
  80. package/dist/surrealql-C1dp1sWw.mjs.map +1 -0
  81. package/dist/validation.d.mts +1 -1
  82. package/dist/version-CXGIA82S.mjs +2 -0
  83. package/dist/{version-CP7sZdoU.mjs.map → version-CXGIA82S.mjs.map} +1 -1
  84. package/package.json +1 -1
  85. package/dist/client-Dkxy0fE6.mjs +0 -9
  86. package/dist/client-Dkxy0fE6.mjs.map +0 -1
  87. package/dist/every-3LgBFWRs.mjs +0 -2
  88. package/dist/serializer-DG5kl84q.mjs.map +0 -1
  89. package/dist/surrealql-CaTGnLkK.mjs +0 -2
  90. package/dist/surrealql-CaTGnLkK.mjs.map +0 -1
  91. package/dist/version-CP7sZdoU.mjs +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"serializer-DG5kl84q.mjs","names":["refuse","WHITESPACE","escapeIdentifier","escapeIdentifier","factor","quote","refuse","placeholder","refuse","actual","currentPk","desiredPk","droppedTable","quote","quote","control","QUALIFIED","RENAME_TO","refusal","refusal","resetFailure","value","refusal","result","table","namespace","namespace","epochMilliseconds","quote","managedTables","refusal","columns","members","getModelTableName","index"],"sources":["../src/migrations/input-boundary.ts","../src/migrations/limits.ts","../src/adapters/databases/sqlite/storage/sql-lexing.ts","../src/adapters/databases/sqlite/storage/column-constraints.ts","../src/adapters/databases/sqlite/storage/geo-point.ts","../src/adapters/databases/sqlite/storage/decimal.ts","../src/migrations/decimal.ts","../src/migrations/drivers/type-mapping.ts","../src/migrations/native-rename.ts","../src/migrations/types.ts","../src/migrations/drop-order.ts","../src/migrations/utils.ts","../src/migrations/base64.ts","../src/migrations/v1-parse-shared.ts","../src/migrations/v1-parse-dispatch.ts","../src/migrations/v1-parse-control.ts","../src/migrations/raw-index.ts","../src/migrations/v1-parse-snapshot.ts","../src/migrations/v1-parse.ts","../src/migrations/resolver.ts","../src/migrations/push/enum-removals.ts","../src/migrations/differ.ts","../src/migrations/catalog-probes.ts","../src/migrations/invert.ts","../src/migrations/sql-blob.ts","../src/migrations/statement-safety.ts","../src/migrations/compile.ts","../src/migrations/execute-dispatch.ts","../src/migrations/foreign-keys.ts","../src/migrations/pinned-session.ts","../src/migrations/push-fingerprint.ts","../src/migrations/drivers/postgres/catalog-refusal.ts","../src/migrations/control.ts","../src/migrations/target.ts","../src/migrations/binary-conversion.ts","../src/migrations/drivers/base.ts","../src/migrations/drivers/index.ts","../src/adapters/databases/sqlite/storage/datetime.ts","../src/migrations/drivers/utils.ts","../src/migrations/drivers/sqlite/introspect.ts","../src/migrations/serializer.ts"],"sourcesContent":["/** Settles one hostile record into an exact immutable property snapshot. */\n\nimport { errorCause } from \"../errors/diagnostic-safety\";\n\ntype RefuseInput = (message: string, cause?: Error) => never;\n\nexport function snapshotExactRecord(\n value: unknown,\n allowed: readonly string[],\n label: string,\n refuse: RefuseInput\n): Readonly<Record<string, unknown>> {\n let objectValue: object | undefined;\n let keys: readonly PropertyKey[] = [];\n try {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n objectValue = value;\n keys = Reflect.ownKeys(value);\n }\n } catch (failure) {\n return refuse(`${label} could not be inspected`, errorCause(failure));\n }\n if (!objectValue) return refuse(`${label} must be an object`);\n const snapshot: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\" || !allowed.includes(key)) {\n return refuse(`${label} contains unknown key ${String(key)}`);\n }\n try {\n snapshot[key] = Reflect.get(objectValue, key);\n } catch (failure) {\n return refuse(`${label}.${key} could not be read`, errorCause(failure));\n }\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotExactArray(\n value: unknown,\n label: string,\n refuse: RefuseInput\n): readonly unknown[] {\n let entries: unknown[] | undefined;\n try {\n if (Array.isArray(value)) entries = Array.from(value);\n } catch (failure) {\n return refuse(`${label} could not be read`, errorCause(failure));\n }\n if (!entries) return refuse(`${label} must be an array`);\n return Object.freeze(entries);\n}\n","/**\n * The limits of one migration command (plans S1, T5a): their type, their\n * defaults and the one resolver. Only migration code imports this module, so\n * an application bundle carries none of it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\n\n/**\n * The limits of one migration command's pinned session (plan S1), and the\n * table size it may rewrite in-request (plan T5a).\n *\n * Every value but `largeTableRows` is in milliseconds. `lockTimeout`, `statementTimeout` and\n * `idleTimeout` are PostgreSQL server settings, where 0 means \"no limit\";\n * `lockWait` and `connectionWait` are waits VibORM itself bounds. `lockWait`\n * also bounds SQLite's `BEGIN IMMEDIATE`, and `connectionWait` applies to\n * MySQL as well; the others, `largeTableRows` included, are PostgreSQL-only,\n * and MySQL keeps its fixed named-lock wait.\n */\nexport interface MigrationLimits {\n /**\n * `lock_timeout`, for the session and, with `SET LOCAL`, every migration\n * transaction: how long one DDL statement may queue for a table lock.\n */\n readonly lockTimeout?: number;\n /**\n * `statement_timeout`, for every migration transaction and for the session\n * around the lock and stepwise programs. 0, or longer than `lockWait`.\n */\n readonly statementTimeout?: number;\n /**\n * `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,\n * `idle_session_timeout`: how long the server keeps a migration session\n * whose client stopped talking — the one that vanished holding the lock.\n * It also bounds the client's own pauses between two statements of a\n * command, so the default (30 s) frees a dead client's lock within half a\n * minute while a loaded client's pause between parts never ends the\n * session (1 s did, before 1.2.3).\n */\n readonly idleTimeout?: number;\n /** How long the command waits for the migration lock another one holds. */\n readonly lockWait?: number;\n /** How long the command waits for its pinned connection. */\n readonly connectionWait?: number;\n /**\n * A row count, not milliseconds: the planner's estimate above which a\n * statement that rewrites or scans a table under a lock that blocks it (a\n * column type change, `SET NOT NULL`, a volatile `ADD COLUMN` default, a\n * FOREIGN KEY or CHECK added without `NOT VALID`) is refused before any\n * effect, because it would hold that lock longer than a request should.\n * 0 admits every size.\n */\n readonly largeTableRows?: number;\n}\n\nexport type ResolvedMigrationLimits = Readonly<Required<MigrationLimits>>;\n\nexport const DEFAULT_MIGRATION_LIMITS: ResolvedMigrationLimits = Object.freeze({\n lockTimeout: 4000,\n statementTimeout: 600_000,\n idleTimeout: 30_000,\n lockWait: 10_000,\n connectionWait: 10_000,\n largeTableRows: 1_000_000,\n});\n\n/** The largest PostgreSQL timeout setting, and the largest timer delay. */\nconst MAX_TIME_LIMIT_MS = 2_147_483_647;\n\nconst LIMIT_KEYS = [\n \"lockTimeout\",\n \"statementTimeout\",\n \"idleTimeout\",\n \"lockWait\",\n \"connectionWait\",\n \"largeTableRows\",\n] as const satisfies readonly (keyof MigrationLimits)[];\n\n/**\n * The limits a migration client was given, settled once: each key a whole\n * number (milliseconds, rows for `largeTableRows`), the defaults filling in\n * the rest.\n *\n * `lockWait` and `connectionWait` are waits VibORM bounds and must be\n * positive; the server settings accept 0 (\"no limit\"). Every key stops at\n * {@link MAX_TIME_LIMIT_MS}, the most both PostgreSQL's settings and a timer\n * hold. A `statementTimeout` must outlast `lockWait`, which runs as one\n * statement under it.\n */\nexport function resolveMigrationLimits(\n input: unknown\n): ResolvedMigrationLimits {\n if (input === undefined) return DEFAULT_MIGRATION_LIMITS;\n const record = snapshotExactRecord(\n input,\n LIMIT_KEYS,\n \"migration limits\",\n refuseLimits\n );\n const limits: Record<(typeof LIMIT_KEYS)[number], number> = {\n ...DEFAULT_MIGRATION_LIMITS,\n };\n for (const key of LIMIT_KEYS) {\n const value = record[key];\n if (value === undefined) continue;\n const least = key === \"lockWait\" || key === \"connectionWait\" ? 1 : 0;\n if (\n typeof value !== \"number\" ||\n !Number.isInteger(value) ||\n value < least ||\n value > MAX_TIME_LIMIT_MS\n ) {\n refuseLimits(\n `migration limit ${key} must be a whole number of ${key === \"largeTableRows\" ? \"rows\" : \"milliseconds\"}, from ${least} to ${MAX_TIME_LIMIT_MS}`\n );\n }\n limits[key] = value;\n }\n if (\n limits.statementTimeout !== 0 &&\n limits.statementTimeout <= limits.lockWait\n ) {\n refuseLimits(\n `migration limit statementTimeout (${limits.statementTimeout} ms) must be 0 or longer than lockWait (${limits.lockWait} ms): the lock wait runs as one statement under it`\n );\n }\n return Object.freeze(limits);\n}\n\nfunction refuseLimits(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/** SQLite token boundaries shared by stored-DDL readers. */\n\n/** An identifier token and where it ends. */\nexport interface SqliteIdentifierToken {\n readonly value: string;\n readonly quoted: boolean;\n readonly end: number;\n}\n\nconst IDENTIFIER_CLOSERS: Readonly<Record<string, string>> = {\n '\"': '\"',\n \"`\": \"`\",\n \"[\": \"]\",\n};\n\nconst BARE_IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\nconst WHITESPACE = /\\s/;\n\n/** Whether one character can occur in SQLite's bare identifier spelling. */\nexport function isSqliteBareIdentifierCharacter(character: string): boolean {\n return BARE_IDENTIFIER_CHARACTER.test(character);\n}\n\n/**\n * Read the identifier at or after `index`, in any of SQLite's four spellings.\n *\n * A doubled quote inside a `\"…\"` or a `` `…` `` token is an escaped one.\n */\nexport function readSqliteIdentifier(\n text: string,\n index: number\n): SqliteIdentifierToken | undefined {\n let cursor = index;\n while (cursor < text.length) {\n while (cursor < text.length && WHITESPACE.test(text.charAt(cursor))) {\n cursor++;\n }\n const isComment =\n (text[cursor] === \"-\" && text[cursor + 1] === \"-\") ||\n (text[cursor] === \"/\" && text[cursor + 1] === \"*\");\n if (!isComment) break;\n cursor = skipSqlNonStructuralRegion(text, cursor);\n }\n const opener = text[cursor];\n if (opener === undefined) return undefined;\n\n const closer = IDENTIFIER_CLOSERS[opener];\n if (closer !== undefined) {\n let value = \"\";\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n if (text[cursor + 1] === closer && closer !== \"]\") {\n value += closer;\n cursor += 2;\n continue;\n }\n return { value, quoted: true, end: cursor + 1 };\n }\n value += text[cursor];\n cursor++;\n }\n return undefined;\n }\n\n const start = cursor;\n while (\n cursor < text.length &&\n isSqliteBareIdentifierCharacter(text.charAt(cursor))\n ) {\n cursor++;\n }\n if (cursor === start) return undefined;\n return { value: text.slice(start, cursor), quoted: false, end: cursor };\n}\n\n/**\n * The offset just past the quoted token or SQL comment starting at `index`, or\n * `index` itself when structural SQL starts there.\n */\nexport function skipSqlNonStructuralRegion(\n text: string,\n index: number\n): number {\n const opener = text[index];\n if (opener === undefined) return index;\n if (opener === \"-\" && text[index + 1] === \"-\") {\n const end = text.indexOf(\"\\n\", index + 2);\n return end === -1 ? text.length : end;\n }\n if (opener === \"/\" && text[index + 1] === \"*\") {\n const end = text.indexOf(\"*/\", index + 2);\n return end === -1 ? text.length : end + 2;\n }\n const closer = opener === \"'\" ? \"'\" : IDENTIFIER_CLOSERS[opener];\n if (closer === undefined) return index;\n\n let cursor = index + 1;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n // A doubled quote is an escaped one, not the end of the token. `]` has\n // no escape in SQLite's bracket spelling.\n if (text[cursor + 1] === closer && closer !== \"]\") {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n cursor++;\n }\n return text.length;\n}\n","import {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"./sql-lexing\";\n\n/** One top-level entry of a `CREATE TABLE` definition list. */\nexport interface SqliteTableDefinition {\n readonly text: string;\n /** The column this entry defines, or `undefined` for a table constraint. */\n readonly columnName: string | undefined;\n}\n\n/** A `CONSTRAINT <name>` at the top level of one definition. */\nexport interface SqliteConstraintClause {\n readonly name: string;\n /** Where the `CONSTRAINT` keyword starts inside the definition text. */\n readonly offset: number;\n}\n\n/** Keywords that open a table constraint rather than a column definition. */\nconst TABLE_CONSTRAINT_KEYWORDS = new Set([\n \"CONSTRAINT\",\n \"PRIMARY\",\n \"UNIQUE\",\n \"CHECK\",\n \"FOREIGN\",\n]);\n\n/**\n * Every top-level entry of the definition list, with the column each one\n * defines. Quoted tokens and comments are skipped before structural commas and\n * parentheses are interpreted.\n */\nexport function sqliteTableDefinitions(sql: string): SqliteTableDefinition[] {\n let open = -1;\n let scan = 0;\n while (scan < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, scan);\n if (skipped !== scan) {\n scan = skipped;\n continue;\n }\n if (sql[scan] === \"(\") {\n open = scan;\n break;\n }\n scan++;\n }\n if (open === -1) return [];\n\n const definitions: SqliteTableDefinition[] = [];\n let depth = 1;\n let start = open + 1;\n let cursor = start;\n while (cursor < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = sql[cursor];\n if (char === \"(\") depth++;\n else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n } else if (char === \",\" && depth === 1) {\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n start = cursor + 1;\n }\n cursor++;\n }\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n return definitions;\n}\n\nfunction describeDefinition(raw: string): SqliteTableDefinition {\n const text = raw.trim();\n const first = readSqliteIdentifier(text, 0);\n if (first === undefined) return { text, columnName: undefined };\n if (first.quoted) return { text, columnName: first.value };\n return {\n text,\n columnName: TABLE_CONSTRAINT_KEYWORDS.has(first.value.toUpperCase())\n ? undefined\n : first.value,\n };\n}\n\n/** Every structural `CONSTRAINT <name>` at depth zero of one definition. */\nexport function sqliteConstraintClauses(\n definition: string\n): SqliteConstraintClause[] {\n const clauses: SqliteConstraintClause[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = definition.charAt(cursor);\n const word = isSqliteBareIdentifierCharacter(char)\n ? readSqliteIdentifier(definition, cursor)\n : undefined;\n if (word !== undefined) {\n if (depth === 0 && word.value.toUpperCase() === \"CONSTRAINT\") {\n const name = readSqliteIdentifier(definition, word.end);\n if (name) {\n clauses.push({ name: name.value, offset: cursor });\n cursor = name.end;\n continue;\n }\n }\n cursor = word.end;\n continue;\n }\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n cursor++;\n }\n return clauses;\n}\n\n/** Structural keywords outside expression bodies, quoted tokens and comments. */\nexport function sqliteDefinitionKeywords(definition: string): string[] {\n const words: string[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const word = readSqliteIdentifier(definition, cursor);\n if (word && !word.quoted) {\n if (depth === 0) words.push(word.value.toUpperCase());\n cursor = word.end;\n continue;\n }\n if (definition[cursor] === \"(\") depth++;\n else if (definition[cursor] === \")\") depth--;\n cursor++;\n }\n return words;\n}\n","import { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n} from \"../../../../validation/primitives/geo-values\";\nimport { sqliteBinary64JsonNumber } from \"./json-number\";\n\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nimport {\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/** TEXT-affinity spelling reserved for VibORM's canonical GeoPoint carrier. */\nexport const SQLITE_GEO_POINT_TYPE = \"VIBORM_GEO_TEXT\";\n\n/** Fixed so a native column rename cannot stale the constraint identity. */\nconst SQLITE_GEO_POINT_CONSTRAINT = \"viborm_geo\";\n\n/** The complete writer-owned column constraint for one GeoPoint carrier. */\nexport function sqliteGeoPointCheck(\n column: Pick<PhysicalColumn, \"name\" | \"nullable\">,\n escapeIdentifier: (name: string) => string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const col = escapeIdentifier(column.name);\n const longitude = `json_extract(${col}, '$.longitude')`;\n const latitude = `json_extract(${col}, '$.latitude')`;\n const valid =\n `CASE WHEN typeof(${col}) = 'text' AND json_valid(${col}) THEN (` +\n `json_type(${col}) = 'object' AND ` +\n `json_type(${col}, '$.longitude') IN ('integer', 'real') AND ` +\n `json_type(${col}, '$.latitude') IN ('integer', 'real') AND ` +\n `${longitude} > ${GEO_LONGITUDE_MIN} AND ${longitude} <= ${GEO_LONGITUDE_MAX} AND ` +\n `${latitude} >= ${GEO_LATITUDE_MIN} AND ${latitude} <= ${GEO_LATITUDE_MAX} AND ` +\n `${col} = ${sqliteGeoPointCarrier(col, encoding)}` +\n \") ELSE 0 END\";\n const body = column.nullable ? `${col} IS NULL OR (${valid})` : valid;\n return `CONSTRAINT ${escapeIdentifier(SQLITE_GEO_POINT_CONSTRAINT)} CHECK (${body})`;\n}\n\n/**\n * Proves that SQLite's reserved declared type is paired with the exact\n * writer-owned constraint. A reserved type without its proof is refused rather\n * than published as a GeoPoint or silently normalized into one.\n */\nexport function readSqliteGeoPointColumn(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): \"legacy\" | \"binary64\" | undefined {\n if (column.type.toUpperCase() !== SQLITE_GEO_POINT_TYPE) return undefined;\n const expected = sqliteGeoPointCheck(column, escapeIdentifier);\n const legacy = sqliteGeoPointCheck(column, escapeIdentifier, \"legacy\");\n let encoding: \"legacy\" | \"binary64\" = \"binary64\";\n let matching = 0;\n for (const definition of sqliteTableDefinitions(tableSql ?? \"\")) {\n if (definition.columnName !== column.name) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (clause.name !== SQLITE_GEO_POINT_CONSTRAINT) continue;\n if (definition.text.startsWith(expected, clause.offset))\n encoding = \"binary64\";\n else if (definition.text.startsWith(legacy, clause.offset))\n encoding = \"legacy\";\n else refuseUnprovenGeoPoint(column);\n matching++;\n }\n }\n if (matching !== 1) refuseUnprovenGeoPoint(column);\n return encoding;\n}\n\nfunction refuseUnprovenGeoPoint(\n column: Pick<PhysicalColumn, \"name\" | \"type\">\n): never {\n throw new MigrationError(\n `SQLite column \"${column.name}\" uses VibORM's reserved GeoPoint type \"${column.type}\" without the exact canonical GeoPoint CHECK constraint. ` +\n \"Migration introspection is refused rather than treating an unproven JSON carrier as a GeoPoint.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"sqlite\",\n column: column.name,\n type: column.type,\n },\n }\n );\n}\n\n/** Copying legacy storage preserves the double still present, not earlier lost digits. */\nexport function sqliteGeoPointCarrier(\n source: string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const longitude = `json_extract(${source}, '$.longitude')`;\n const latitude = `json_extract(${source}, '$.latitude')`;\n return `json_object('longitude', ${encoding === \"legacy\" ? longitude : sqliteBinary64JsonNumber(longitude)}, 'latitude', ${encoding === \"legacy\" ? latitude : sqliteBinary64JsonNumber(latitude)})`;\n}\n\n/** Format-1 snapshots predating the precision annotation describe the legacy CHECK. */\nexport function sqliteGeoPointEncoding(column: {\n readonly type: string;\n readonly geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}): \"legacy\" | \"binary64\" | undefined {\n return column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE\n ? (column.geoPointEncoding ?? \"legacy\")\n : undefined;\n}\n","/**\n * SQLite fixed-decimal migration storage.\n *\n * SQLite cannot carry a decimal descriptor in its declared storage type, so\n * this module owns the reserved CHECK carrier, its structural reader, and the\n * exact table-rebuild expressions that rescale scalar and list coefficients.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"../../../../validation/primitives/decimal-codec\";\nexport type DecimalStorageKind = \"scalar\" | \"list\";\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n readonly decimal?: DecimalDescriptor | undefined;\n}\nexport function sqliteDecimalStorageKind(\n column: Pick<PhysicalColumn, \"type\" | \"decimal\">\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase();\n if (type === decimalColumnType(\"sqlite\", column.decimal)) return \"scalar\";\n return type === \"TEXT\" ? \"list\" : undefined;\n}\n\nimport {\n type SqliteConstraintClause,\n type SqliteTableDefinition,\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/**\n * The reserved SQLite constraint name for one decimal column.\n *\n * SQLite's declared type is the wrong carrier twice over: it stores `INTEGER`\n * (or `TEXT` for a list) whatever the domain is, and a CHECK written INTO the\n * type string never reads back — `PRAGMA table_info.type` reports only the\n * `type-name` production, so the desired `TEXT CHECK(...)` can never equal the\n * introspected `TEXT` and a full table recreation is planned on every push,\n * forever. (That is measured behaviour of the enum column type, not a\n * hypothetical.) So the descriptor rides in a NAMED constraint, and\n * introspection recovers it from the name.\n */\nexport function sqliteDecimalConstraintName(\n columnName: string,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${columnName}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/** The namespace VibORM reserves for the constraints it writes itself. */\nconst RESERVED_CONSTRAINT_PREFIX = \"viborm_decimal_\";\n\n/** `<precision>_<scale>`: what follows the column name in a reserved name. */\nconst RESERVED_CONSTRAINT_TAIL = /^(\\d+)_(\\d+)$/;\n\n/**\n * The declared domain of one column, read back out of the `CREATE TABLE` text\n * SQLite stored — or `undefined` when this column carries no reserved\n * constraint. The matching PRAGMA type and nullability travel with the column:\n * the stored clause is owned only when it is the exact writer rendering for\n * those physical facts.\n *\n * This PARSES, it does not search. The name alone is not evidence: SQLite\n * stores the statement verbatim, so any string literal a user can write — an\n * enum value, a string default, an index predicate — appears in the same text\n * and can spell VibORM's reserved prefix. A first-hit substring scan therefore\n * reads a user's data as a descriptor, and with an earlier offset it OVERRIDES\n * the real constraint: the next push plans a conversion between two domains\n * neither side declared and rewrites every stored coefficient. So the reader\n * walks the column-definition list the same quote-aware way\n * `partialIndexPredicate` walks a `CREATE INDEX` (`introspect.ts`), finds real\n * `CONSTRAINT <name> CHECK (…)` clauses, and binds each to the column definition\n * it actually sits in.\n *\n * A reserved name the module could not have written is REFUSED, not ignored.\n * Ignoring it is not the safe reading: the name is in a namespace only this\n * module writes, so its presence means either a corrupted carrier or a\n * collision, and both make every later push either wrong (a conversion between\n * invented domains) or non-convergent (a descriptor the desired side can never\n * match). The refusal names the constraint so the estate can be repaired.\n *\n * Ownership is proved by RE-RENDERING: the clause must be, byte for byte, what\n * {@link sqliteDecimalCheck} would emit for this column at the descriptor the\n * name declares. That is the only test that cannot be forged by a name alone,\n * and it is exact because SQLite re-spells nothing it stores.\n */\nexport function readSqliteDecimalConstraint(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n if (!tableSql) return undefined;\n // The reserved namespace has to appear at all before the statement is worth\n // parsing: introspection reads every column of every table, and the\n // overwhelming majority carry no decimal.\n if (!tableSql.includes(RESERVED_CONSTRAINT_PREFIX)) return undefined;\n\n let found: DecimalDescriptor | undefined;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(RESERVED_CONSTRAINT_PREFIX)) continue;\n // This reader is invoked once for every PRAGMA column. A reserved\n // column constraint is adjudicated when its own physical column is in\n // hand, because only that invocation knows the type and nullability the\n // database actually reported. TABLE constraints have no such invocation\n // and are always namespace squatters.\n if (\n definition.columnName !== undefined &&\n definition.columnName !== column.name\n ) {\n continue;\n }\n const descriptor = ownedDescriptor(\n definition,\n clause,\n column,\n escapeIdentifier\n );\n if (descriptor === undefined) {\n throw new MigrationError(\n `The stored definition carries a constraint named \"${clause.name}\", which is inside the namespace VibORM reserves for the fixed-decimal descriptor it writes itself, but it is not a constraint VibORM wrote. ` +\n \"A reserved constraint is the ONLY place a SQLite column's declared precision and scale survive — the storage class is INTEGER or TEXT at every domain — so reading this one as a descriptor would plan conversions between domains the schema never declared, and ignoring it would re-plan the same alteration on every push. \" +\n \"Rename or drop the constraint, or restore the definition VibORM wrote for this column.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n constraint: clause.name,\n // Absent for a TABLE constraint, which belongs to no column.\n ...(definition.columnName === undefined\n ? {}\n : { column: definition.columnName }),\n },\n }\n );\n }\n if (found !== undefined) {\n throw new MigrationError(\n `The stored definition carries more than one fixed-decimal descriptor for column \"${column.name}\": ${describeDecimalDomain(found)} and ${describeDecimalDomain(descriptor)}. ` +\n \"One physical column can have only one logical decimal domain, so introspection refuses the ambiguous reserved carriers instead of choosing one by order.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { column: column.name } }\n );\n }\n found = descriptor;\n }\n }\n return found;\n}\n\n/**\n * Whether one catalog column is the checked scaled-integer storage VibORM\n * writes for `descriptor`: INTEGER (TEXT for a list) carrying exactly that\n * descriptor's reserved CHECK. Typed queries never ask; `viborm check --db`\n * does, for a table VibORM did not create.\n */\nexport function isSqliteDecimalStorage(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): boolean {\n const stored = readSqliteDecimalConstraint(\n tableSql,\n column,\n escapeIdentifier\n );\n return (\n sameDecimalDescriptor(stored, descriptor) &&\n sqliteDecimalStorageKind({ type: column.type, decimal: stored }) === kind\n );\n}\n\n/** One top-level entry of a `CREATE TABLE`'s parenthesized definition list. */\n/**\n * The reserved constraint this clause carries, or `undefined` when the clause\n * is one this module could not have written.\n *\n * Three things must hold together, and each is a way the namespace gets\n * squatted: the clause sits in a COLUMN definition (never a table constraint,\n * which VibORM never writes); its name is this column's name followed by the\n * two numbers; and the whole clause re-renders byte for byte.\n */\nfunction ownedDescriptor(\n definition: SqliteTableDefinition,\n clause: SqliteConstraintClause,\n physicalColumn: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n const column = definition.columnName;\n if (column === undefined) return undefined;\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${column}_`;\n if (!clause.name.startsWith(prefix)) return undefined;\n const match = RESERVED_CONSTRAINT_TAIL.exec(clause.name.slice(prefix.length));\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"sqlite\");\n if (descriptor === undefined) return undefined;\n // PRAGMA owns the physical type and nullability. Re-render ONLY the shape\n // those facts permit; trying all four writer spellings lets an impossible\n // INTEGER/list or nullable/non-null carrier masquerade as a valid domain.\n const kind = sqliteDecimalStorageKind({\n ...physicalColumn,\n decimal: descriptor,\n });\n if (kind === undefined) return undefined;\n const rendered = sqliteDecimalCheck(\n physicalColumn,\n descriptor,\n kind,\n escapeIdentifier\n );\n if (definition.text.startsWith(rendered, clause.offset)) {\n return descriptor;\n }\n return undefined;\n}\n\n/**\n * Whether one generated table definition carries this column's reserved\n * decimal descriptor name in the structural column clause that owns it.\n *\n * Apply uses this only after it has proved the surrounding statement sequence\n * is VibORM's exact generated table-recreation program. It distinguishes the\n * decimal-column rename variant, whose copy expression needs no conversion\n * sentinel, from an unrelated recreation of a table that merely contains some\n * other decimal column.\n */\nexport function sqliteColumnDefinitionCarriesDecimalDescriptor(\n tableSql: string,\n columnName: string\n): boolean {\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${columnName}_`;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n if (definition.columnName !== columnName) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(prefix)) continue;\n const match = RESERVED_CONSTRAINT_TAIL.exec(\n clause.name.slice(prefix.length)\n );\n if (\n match &&\n readStoredDecimalDescriptor(match[1], match[2], \"sqlite\") !== undefined\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** `10^precision - 1`: the widest coefficient the domain can hold. */\nfunction maxCoefficient(precision: number): bigint {\n return 10n ** BigInt(precision) - 1n;\n}\n\n/**\n * The reserved CHECK a SQLite decimal column carries, as a complete column\n * constraint (`CONSTRAINT <name> CHECK (<body>)`).\n *\n * A scalar is the signed integer coefficient. A list is TEXT holding a JSON\n * array of coefficient strings. NULL passes only for a nullable column.\n */\nexport function sqliteDecimalCheck(\n column: { readonly name: string; readonly nullable: boolean },\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): string {\n const col = escapeIdentifier(column.name);\n const name = escapeIdentifier(\n sqliteDecimalConstraintName(column.name, descriptor)\n );\n const bound = maxCoefficient(descriptor.precision).toString();\n const body =\n kind === \"list\"\n ? `typeof(${col}) = 'text' AND json_valid(${col}) AND json_type(${col}) = 'array'`\n : `typeof(${col}) = 'integer' AND ${col} BETWEEN -${bound} AND ${bound}`;\n const guarded = column.nullable ? `${col} IS NULL OR (${body})` : body;\n return `CONSTRAINT ${name} CHECK (${guarded})`;\n}\n\n/**\n * The value a row lands in the rebuilt table when it does not fit the target\n * domain. It fails the target column's own reserved CHECK and aborts the whole\n * recreation atomically.\n */\nconst SCALAR_SENTINEL = \"'viborm:decimal-out-of-domain'\";\nconst LIST_SENTINEL = \"'viborm:decimal-list-out-of-domain'\";\n\ninterface Rescale {\n /** `10^|scale delta|`, as an integer literal. */\n readonly factor: string;\n readonly direction: \"up\" | \"down\" | \"none\";\n /** The inclusive absolute bound the SOURCE coefficient must satisfy. */\n readonly bound: string;\n}\n\n/** The one arithmetic decision behind every SQLite conversion expression. */\nfunction rescale(\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor\n): Rescale {\n const targetMax = maxCoefficient(to.precision);\n const sourceMax = from ? maxCoefficient(from.precision) : targetMax;\n const delta = to.scale - (from?.scale ?? 0);\n if (delta === 0) {\n return {\n factor: \"1\",\n direction: \"none\",\n bound: min(sourceMax, targetMax).toString(),\n };\n }\n if (delta > 0) {\n const factor = 10n ** BigInt(delta);\n return {\n factor: factor.toString(),\n direction: \"up\",\n bound: min(sourceMax, targetMax / factor).toString(),\n };\n }\n const factor = 10n ** BigInt(-delta);\n return {\n factor: factor.toString(),\n direction: \"down\",\n bound: min(sourceMax, targetMax * factor).toString(),\n };\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n}\n\n/**\n * The per-column source expression used by SQLite table recreation. It\n * converts stored values from `from`'s physical spelling to `to`'s without a\n * REAL intermediate and routes every malformed or out-of-domain value to the\n * target CHECK's sentinel.\n */\nexport function sqliteDecimalCopyExpression(\n source: string,\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor,\n kind: DecimalStorageKind\n): string {\n const { factor, direction, bound } = rescale(from, to);\n const exact = direction === \"down\" ? ` AND ${source} % ${factor} = 0` : \"\";\n if (kind === \"scalar\") {\n const converted = convertedCoefficient(source, direction, factor);\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' ` +\n `AND ${source} BETWEEN -${bound} AND ${bound}${exact} THEN ${converted} ` +\n `ELSE ${SCALAR_SENTINEL} END`\n );\n }\n return listCopyExpression(source, direction, factor, bound);\n}\n\nfunction convertedCoefficient(\n operand: string,\n direction: Rescale[\"direction\"],\n factor: string\n): string {\n if (direction === \"up\") return `${operand} * ${factor}`;\n if (direction === \"down\") return `${operand} / ${factor}`;\n return operand;\n}\n\n/** Convert a SQLite JSON coefficient-string list without losing order. */\nfunction listCopyExpression(\n source: string,\n direction: Rescale[\"direction\"],\n factor: string,\n bound: string\n): string {\n const member = `\"m\".\"value\"`;\n const asInteger = `CAST(${member} AS INTEGER)`;\n const exact = direction === \"down\" ? ` AND ${asInteger} % ${factor} = 0` : \"\";\n const admissible =\n `\"m\".\"type\" = 'text' AND CAST(${asInteger} AS TEXT) = ${member} ` +\n `AND ${asInteger} BETWEEN -${bound} AND ${bound}${exact}`;\n const converted = `CAST(${convertedCoefficient(`CAST(\"value\" AS INTEGER)`, direction, factor)} AS TEXT)`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'text' AND json_valid(${source}) = 1 THEN ` +\n `CASE WHEN json_type(${source}) = 'array' THEN CASE WHEN ` +\n `(SELECT count(*) FROM json_each(${source}) AS \"m\" WHERE NOT (${admissible})) = 0 THEN ` +\n `(SELECT json_group_array(${converted}) FROM (SELECT \"value\" FROM json_each(${source}) AS \"m\" ORDER BY \"m\".\"key\")) ` +\n `ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END`\n );\n}\n","/**\n * The migration layer's decimal renders.\n *\n * `@validation/primitives/decimal-codec` owns everything VALUE-shaped: the\n * grammar, canonical text, the logical <-> coefficient conversion, and the two\n * DDL renderings (`decimalColumnType`, `decimalDefaultText`). This module owns\n * what only a MIGRATION asks — the questions whose subject is a pair of\n * descriptors or a stored column rather than a value:\n *\n * - whether two snapshots describe the same domain, whether a change narrows\n * it, and which scalar/list storage shape a decimal column carries;\n * - the MySQL column-comment marker for a JSON-backed list; and\n * - the shared validation predicates used by native-decimal migration drivers.\n *\n * Everything here is PURE and connection-free: migration DDL is generated into\n * durable artifacts, so none of it may consult a database.\n *\n * Nothing here re-derives a precision or a scale. Every entry takes the frozen\n * descriptor its caller already holds (plan §1.1: no migration component stores\n * an independent precision or scale decision).\n */\n\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ColumnDef } from \"./types\";\n\n/**\n * Whether moving from `from` to `to` SHRINKS the set of representable values —\n * the destructive half of a descriptor change.\n *\n * Two independent limits move: the fractional digits (`scale`) and the integer\n * digits (`precision - scale`). A change that lowers either one can find a\n * stored value it cannot hold, and the conversion then refuses; a change that\n * raises both is exact for every existing row. Widening the scale while keeping\n * the precision therefore counts as narrowing, because it takes an integer\n * digit away — `NUMERIC(10,2)` holds 99999999.99 and `NUMERIC(10,5)` does not.\n */\nexport function decimalDomainNarrows(\n from: DecimalDescriptor,\n to: DecimalDescriptor\n): boolean {\n const integerDigitsLost =\n to.precision - to.scale < from.precision - from.scale;\n return integerDigitsLost || to.scale < from.scale;\n}\n\n/**\n * Whether this alteration moves stored values INTO a declared decimal domain —\n * the ONE signal every provider's conversion route reads.\n *\n * Only the TARGET has to declare a domain. An absent source descriptor does not\n * make the change descriptor-free: it means the stored values were written\n * under some other reading, and adopting them under this one is exactly the\n * transition §7.3 governs. Skipping the conversion there is what silently\n * reinterprets a PostgreSQL `numeric` by rounding it through the `USING` cast,\n * and what copies a SQLite integer into a coefficient column at a scale it was\n * never written at. Each provider answers the absent source in its own terms —\n * PostgreSQL's target-domain CHECK is a complete proof on its own, and the\n * SQLite copy reads an untyped `INTEGER` as the logical integer it is — but the\n * QUESTION is one, so this is one predicate.\n *\n * The physical type is part of it beside the descriptor, because a scalar that\n * becomes a list keeps its precision and scale while changing storage class\n * completely. It is compared case-insensitively, the same reading the differ\n * takes: one snapshot side is the serializer's spelling and the other is\n * whatever the catalog answered.\n */\nexport function decimalConversionRequired(\n from: ColumnDef,\n to: ColumnDef\n): boolean {\n if (to.decimal === undefined) return false;\n return (\n !sameDecimalDescriptor(from.decimal, to.decimal) ||\n from.type.toUpperCase() !== to.type.toUpperCase()\n );\n}\n\n/**\n * Whether this alteration can lose data because the target domain is smaller.\n * The migration differ's destructive classifier is the sole consumer-facing\n * decision owner; this function owns only the decimal-domain question it asks.\n */\nexport function decimalChangeNarrows(from: ColumnDef, to: ColumnDef): boolean {\n if (from.decimal === undefined || to.decimal === undefined) return false;\n return decimalDomainNarrows(from.decimal, to.decimal);\n}\n\n/**\n * A storage shape, spelled for a refusal MESSAGE.\n *\n * `undefined` is a real answer here and it has to say so: it means the column's\n * declared type is neither of the two spellings this layer writes, which is a\n * different fact from \"the domain moved\" and must not be reported as one.\n */\nexport function describeDecimalStorageKind(\n kind: DecimalStorageKind | undefined\n): string {\n return kind ?? \"unrecognized\";\n}\n\n// =============================================================================\n// THE MYSQL DESCRIPTOR CARRIER\n// =============================================================================\n\n/**\n * The deterministic VibORM-owned column-comment marker for a JSON-backed MySQL\n * decimal list.\n *\n * A `DECIMAL(p,s)` column spells its own domain, but a decimal LIST is stored\n * as `JSON` (MySQL has no array type), and JSON carries nothing. The marker is\n * that column's descriptor, and it is the whole comment: introspection\n * recognizes only the exact marker (§6.2), so a hand-written comment that\n * merely mentions a decimal is not a descriptor.\n */\nexport function mysqlDecimalListMarker(descriptor: DecimalDescriptor): string {\n return `viborm:decimal(${descriptor.precision},${descriptor.scale})`;\n}\n\nconst MYSQL_LIST_MARKER = /^viborm:decimal\\((\\d+),(\\d+)\\)$/;\n\n/**\n * The domain a MySQL column comment declares, or `undefined` when it is not the\n * reserved marker. A marker-shaped comment with an invalid domain refuses.\n */\nexport function readMysqlDecimalListMarker(\n comment: string | null | undefined\n): DecimalDescriptor | undefined {\n if (!comment) return undefined;\n const match = MYSQL_LIST_MARKER.exec(comment);\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"mysql\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n \"The stored MySQL column comment uses VibORM's reserved decimal-list marker but carries an invalid fixed-decimal descriptor. \" +\n \"A reserved marker must contain finite safe integers inside the complete MySQL decimal domain; repair or remove the comment before running migrations.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n\n// =============================================================================\n// THE DIALECT STORAGE SHAPES\n// =============================================================================\n\n/**\n * How one dialect physically holds a decimal: one value, or a container of\n * them. The migration layer reads it off the column rather than the model,\n * because a snapshot side may have come from introspection.\n */\nexport type { DecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\nimport {\n type DecimalStorageKind,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\n\nexport {\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nexport { sqliteDecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\n/**\n * The storage shape of a MySQL decimal column, or `undefined` when the column\n * holds no decimal.\n *\n * A scalar spells its own domain in `DECIMAL(p,s)` — introspection reads it\n * back lowercased, so the comparison is case-insensitive — and a list is the\n * `JSON` container every MySQL list gets, carrying its domain in the\n * column-comment marker instead.\n *\n * A MODIFIER after the domain does not change the storage shape.\n * `decimal(10,2) unsigned` and `decimal(10,2) zerofill` are the same physical\n * decimal, introspected verbatim through `formatColumnType`'s modifier arm, and\n * a shape of `undefined` for them would refuse the very ALTER that normalizes\n * them — an estate that could never converge. The domain token itself still has\n * to match the descriptor EXACTLY, so `DECIMAL(10,20)` is not `DECIMAL(10,2)`\n * with a modifier.\n */\nexport function mysqlDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \" \").trim();\n const scalar = decimalColumnType(\"mysql\", column.decimal);\n if (type === scalar || type.startsWith(`${scalar} `)) return \"scalar\";\n return type === MYSQL_DECIMAL_LIST_TYPE ? \"list\" : undefined;\n}\n\n/** PostgreSQL's native scalar and native-array decimal storage shapes. */\nexport function postgresDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \"\").trim();\n const scalar = decimalColumnType(\"pg\", column.decimal);\n if (type === scalar) return \"scalar\";\n return type === `${scalar}[]` ? \"list\" : undefined;\n}\n\n/**\n * The provider-independent scalar/list identity of a migration decimal.\n *\n * Rename detection needs the shape, not typmod equality: changing a decimal\n * descriptor necessarily changes PostgreSQL/MySQL's physical type spelling,\n * while it keeps the same value/container identity and can still be a native\n * column rename followed by one exact conversion.\n */\nexport function migrationDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n return (\n postgresDecimalStorageKind(column) ??\n mysqlDecimalStorageKind(column) ??\n sqliteDecimalStorageKind(column)\n );\n}\n\n/** MySQL has no array type; every list is JSON, decimal lists included. */\nexport const MYSQL_DECIMAL_LIST_TYPE = \"JSON\";\n\n/**\n * TEXT, not the blanket `JSON` every other SQLite list gets: the list's\n * reserved CHECK asserts `typeof = 'text'`, and `JSON` has NUMERIC affinity\n * under SQLite's rules (it contains none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/\n * DOUB), which would try to convert a numeric-looking container on the way in.\n */\nexport const SQLITE_DECIMAL_LIST_TYPE = \"TEXT\";\n\n// =============================================================================\n// THE PostgreSQL / MySQL VALIDATION PREDICATE\n// =============================================================================\n\n/**\n * The transient constraint a native-decimal conversion validates through.\n *\n * It is added, kept live ACROSS the type change, and dropped after. That\n * ordering is the whole design: the constraint proves every EXISTING row\n * already fits the target domain, and — because it stays — no concurrent write\n * can land a value the target would have to round while the conversion runs.\n * It is how \"while writes are excluded\" is spelled on MySQL, whose `LOCK\n * TABLES` the artifact classifier refuses as a transaction leader.\n */\n/**\n * The compact identity of one transient conversion proof.\n *\n * The table and column deliberately stay out of this identity: MySQL can\n * publish a different table-name spelling through `lower_case_table_names`,\n * while an interrupted proof must authenticate before the original spelling\n * is available again. The exact catalog CHECK authenticates its table and\n * column instead. Kind, precision and scale are already a small, bounded,\n * collision-free identity, so spelling them directly is both shorter and\n * stronger than hashing them: recovery can authenticate the declared proof\n * without searching or trusting a lossy digest.\n */\nexport function decimalConversionConstraintName(\n kind: DecimalStorageKind,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${kind === \"scalar\" ? \"s\" : \"l\"}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/**\n * \"The target domain admits this value UNCHANGED\", as a CHECK body.\n *\n * One idea, spelled in each dialect's cast syntax: a cast to the target type\n * rounds a value with too many fractional digits and refuses one with too many\n * integer digits, so a value that survives the cast intact is exactly a value\n * the conversion does not have to change. That is §7.3's rule — \"convert only\n * when every value fits\", and \"no descriptor change rounds existing data\" —\n * without a per-digit predicate. PostgreSQL's `numeric` also admits special\n * non-finite values, and `NaN` compares equal to itself, so finiteness is an\n * independent part of the proof. Arrays prove it for every member beside the\n * existing NULL-member refusal, while the outer `column IS NULL` continues to\n * admit a nullable whole list.\n *\n * The type token is the one `decimalColumnType` produced for the target column,\n * array suffix included; nothing here re-spells it.\n */\nexport function postgresDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n const unchanged = `${column} = ${column}::${targetType}`;\n if (targetType.endsWith(\"[]\")) {\n const hasNoNonFiniteMember = [\"NaN\", \"Infinity\", \"-Infinity\"]\n .map((value) => `array_position(${column}, '${value}'::numeric) IS NULL`)\n .join(\" AND \");\n return `${column} IS NULL OR (array_position(${column}, NULL) IS NULL AND ${hasNoNonFiniteMember} AND ${unchanged})`;\n }\n const hasFiniteValue = `${column} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`;\n return `${column} IS NULL OR (${hasFiniteValue} AND ${unchanged})`;\n}\n\n/** {@link postgresDecimalFitsCheck}'s MySQL spelling. */\nexport function mysqlDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n return `${column} IS NULL OR ${column} = CAST(${column} AS ${targetType})`;\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalFitsCheck}. */\nexport function mysqlDecimalFitsCatalogCheck(\n column: string,\n targetType: string\n): string {\n return `((${column} is null) or (${column} = cast(${column} as ${targetType})))`;\n}\n\nfunction mysqlDecimalListCheckParts(\n column: string,\n descriptor: DecimalDescriptor\n): { readonly rendered: string; readonly normalizedContainer: string } {\n const coefficient = `(\"0\"|\"-?[1-9][0-9]{0,${descriptor.precision - 1}}\")`;\n return {\n rendered: `CAST(${column} AS CHAR CHARACTER SET utf8mb4)`,\n normalizedContainer: `^.(${coefficient}(, ${coefficient})*)?.$`,\n };\n}\n\n/**\n * A MySQL JSON decimal list is already in the target domain without changing\n * one stored byte.\n *\n * MySQL CHECK expressions cannot contain a subquery, so this validates the\n * provider's own normalized JSON rendering as one anchored language. Every\n * member must be a JSON string carrying the canonical coefficient grammar,\n * and the digit bound comes from the narrower descriptor that must remain true\n * across the marker change. `LEFT` and `RIGHT` prove the two brackets while\n * the anchored regular expression uses one character for each. That avoids a\n * backslash whose SQL meaning would depend on `NO_BACKSLASH_ESCAPES`.\n */\nexport function mysqlDecimalListFitsCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n return (\n `${column} IS NULL OR (` +\n `LEFT(${rendered}, 1) = '[' AND RIGHT(${rendered}, 1) = ']' AND ` +\n `REGEXP_LIKE(${rendered}, '${normalizedContainer}', 'c'))`\n );\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalListFitsCheck}. */\nexport function mysqlDecimalListFitsCatalogCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n const catalogRendered = rendered.replace(\n \"CHAR CHARACTER SET\",\n \"char charset\"\n );\n return (\n `((${column} is null) or (` +\n `(${`LEFT(${catalogRendered}, 1)`} = '[') and ` +\n `(${`RIGHT(${catalogRendered}, 1)`} = ']') and ` +\n `${`REGEXP_LIKE(${catalogRendered}, '${normalizedContainer}', 'c')`}))`\n );\n}\n","/**\n * Centralized Type Mapping for Migration Drivers\n *\n * Maps VibORM scalar types to native database column types.\n * Uses constants from native-types.ts to ensure consistency.\n */\n\nimport { PG, SQLITE } from \"@schema/scalars/native-types\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n} from \"@validation/primitives/decimal-codec\";\nimport { SQLITE_GEO_POINT_TYPE } from \"../../adapters/databases/sqlite/storage/geo-point\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { SQLITE_DECIMAL_LIST_TYPE } from \"../decimal\";\n\n// =============================================================================\n// TYPE MAPPING CONSTANTS\n// =============================================================================\n\n/**\n * Default PostgreSQL type mappings for each VibORM scalar type.\n * Uses the same type names as defined in native-types.ts.\n */\nexport const PG_TYPE_DEFAULTS = {\n string: PG.STRING.TEXT.type,\n int: PG.INT.INTEGER.type,\n number: PG.FLOAT.DOUBLE_PRECISION.type,\n boolean: PG.BOOLEAN.BOOLEAN.type,\n datetime: PG.DATETIME.TIMESTAMP(3).type,\n datetimetz: PG.DATETIME.TIMESTAMPTZ(3).type,\n date: PG.DATETIME.DATE.type,\n time: PG.DATETIME.TIME(3).type,\n timetz: PG.DATETIME.TIMETZ(3).type,\n bigint: PG.BIGINT.BIGINT.type,\n json: PG.JSON.JSONB.type,\n blob: PG.BLOB.BYTEA.type,\n vector: \"vector\",\n point: \"geography(Point,4326)\",\n enum: PG.STRING.TEXT.type,\n} as const;\n\n/**\n * Default SQLite type mappings for each VibORM scalar type.\n * SQLite has limited type affinity - most types map to TEXT, INTEGER, REAL, or BLOB.\n */\nexport const SQLITE_TYPE_DEFAULTS = {\n string: SQLITE.STRING.TEXT.type,\n int: SQLITE.INT.INTEGER.type,\n number: SQLITE.FLOAT.REAL.type,\n boolean: SQLITE.BOOLEAN.INTEGER.type,\n datetime: SQLITE.DATETIME.TEXT.type,\n date: SQLITE.DATETIME.TEXT.type,\n time: SQLITE.DATETIME.TEXT.type,\n bigint: SQLITE.BIGINT.INTEGER.type,\n json: \"JSON\", // SQLite JSON functions work with TEXT but JSON is more semantic\n blob: SQLITE.BLOB.BLOB.type,\n vector: \"JSON\", // Store as JSON array in SQLite\n point: SQLITE_GEO_POINT_TYPE,\n enum: SQLITE.STRING.TEXT.type,\n} as const;\n\n/**\n * Default MySQL type mappings for each VibORM scalar type.\n * MySQL has full type support but uses TINYINT(1) for booleans\n * and doesn't support native arrays (use JSON instead).\n */\nexport const MYSQL_TYPE_DEFAULTS = {\n string: \"TEXT\",\n int: \"INT\",\n number: \"DOUBLE\",\n boolean: \"TINYINT(1)\", // MySQL uses TINYINT(1) for boolean\n datetime: \"DATETIME(3)\", // Use DATETIME(3) to preserve JavaScript Date millisecond precision\n datetimetz: \"DATETIME(3)\", // MySQL DATETIME can store with timezone via application\n date: \"DATE\",\n time: \"TIME(3)\", // Use TIME(3) to preserve millisecond precision\n timetz: \"TIME(3)\", // MySQL TIME doesn't have timezone variant\n bigint: \"BIGINT\",\n json: \"JSON\",\n blob: \"BLOB\",\n vector: \"JSON\", // No native vector support, use JSON\n point: \"POINT SRID 4326\",\n enum: \"TEXT\", // Default for unspecified enums; usually use inline ENUM()\n} as const;\n\n/**\n * THE MySQL inline enum type — one spelling, both snapshot producers.\n *\n * MySQL has no standalone enum object: the values ARE the column type, so this\n * text is also the enum's identity in a snapshot. The desired side spells it\n * (`MySQLMigrationDriver.getEnumColumnType`) and the live side re-spells the\n * catalog's `COLUMN_TYPE` through the very same function\n * (`mysql/introspect.ts`), because `information_schema` prints its own\n * canonical rendering — `enum('a','b')`, no space after the comma, and an\n * identity of its own invention — and two spellings of ONE type read as a\n * changed column on every push and as the mismatch the final push attestation\n * refuses.\n *\n * A member IS a MySQL string literal, so it is spelled by the one function that\n * spells those (`mysqlStringLiteral` below) rather than by a second rule of its\n * own. Doubling `'` alone was that second rule: `ENUM('a\\b')` declared a member\n * holding a BACKSPACE, `ENUM('end\\')` did not parse at all, and once the\n * default beside such a member went through the shared spelling the two\n * disagreed and MySQL refused the CREATE/MODIFY with errno 1067 (all measured).\n */\nexport function mysqlEnumType(values: readonly string[]): string {\n return `ENUM(${values.map((value) => mysqlStringLiteral(value)).join(\", \")})`;\n}\n\n/**\n * THE characters MySQL's string literals carry as an escape — the one table\n * both directions read.\n *\n * MySQL reads `\\` inside a string literal as an escape introducer (only\n * `NO_BACKSLASH_ESCAPES` stops it, a mode this estate never sets and the\n * pinned session does not promise), so doubling `'` alone spells a DIFFERENT\n * value: `DEFAULT ('a\\b')` stored a BACKSPACE and `DEFAULT ('end\\')` did not\n * even parse. The four control characters are escaped for the same reason\n * they cannot be written raw: a generated statement is also the review blob,\n * which is UTF-8/LF with no carriage returns (`sql-blob.ts`).\n *\n * `information_schema` prints an expression default with exactly these escapes\n * plus `\\'` (measured on 8.4.11 — every other character, tab and backspace\n * included, is printed raw), so `mysql/introspect.ts` undoes this same table\n * before re-spelling the value through `mysqlStringLiteral` below.\n */\nexport const MYSQL_LITERAL_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"\\\\\", \"\\\\\\\\\"],\n [\"\\n\", \"\\\\n\"],\n [\"\\r\", \"\\\\r\"],\n [\"\\0\", \"\\\\0\"],\n [\"\\u001a\", \"\\\\Z\"],\n]);\n\n/**\n * THE MySQL string literal — one spelling, both snapshot producers.\n *\n * The desired side writes it (`MySQLMigrationDriver.escapeValue`) and the live\n * side re-spells the value it read out of the catalog through the very same\n * function (`mysql/introspect.ts`), because two spellings of ONE value read as\n * a changed column on every push and as the mismatch the final push\n * attestation refuses.\n */\nexport function mysqlStringLiteral(value: string): string {\n let escaped = \"\";\n for (const character of value) {\n escaped += MYSQL_LITERAL_ESCAPES.get(character) ?? character;\n }\n return `'${escaped.replace(/'/g, \"''\")}'`;\n}\n\nconst ENUM_VALUES_REGEX = /enum\\((.+)\\)/i;\n\n/**\n * What MySQL's printer writes, read backwards: the WRITE table\n * (`mysqlStringLiteral`) inverted, plus the apostrophe, which MySQL prints as\n * `\\'` although the DDL spelling doubles it instead. Every other character —\n * tab, backspace, `\"` — is printed raw (measured on 8.4.11), so an escape\n * outside this table is one this inverse does not own.\n *\n * ONE table, both catalog vocabularies, because both are MySQL printing a\n * string literal it parsed: the expression default below, and an ENUM's members\n * inside `COLUMN_TYPE`. The enum printer writes a strict SUBSET of it (`\\\\`,\n * `\\n`, `\\r`, `\\0`; it doubles `'` and prints ctrl-Z raw, measured), so reading\n * one table backwards covers both and leaves the same remainder unowned.\n */\nexport const MYSQL_PRINTED_CHARACTERS: ReadonlyMap<string, string> = new Map([\n [\"'\", \"'\"],\n ...[...MYSQL_LITERAL_ESCAPES].map(\n ([character, sequence]) =>\n [sequence.slice(1), character] as [string, string]\n ),\n]);\n\n/**\n * Parse enum values from MySQL COLUMN_TYPE string, or `null` when the catalog\n * spelled one this inverse does not own.\n *\n * Handles values containing commas, doubled single quotes (''), and the\n * backslash escapes MySQL's printer writes (`MYSQL_PRINTED_CHARACTERS`).\n * Example: \"enum('a,b','it''s','c')\" -> ['a,b', \"it's\", 'c']\n * Example: String.raw`enum('a\\\\b','line1\\nline2')` -> [\"a\\\\b\", \"line1\\nline2\"]\n *\n * Reading `\\x` as a bare `x` — which is what \"skip the backslash\" does — turned\n * the printed `\\n` of a declared NEWLINE into the letter `n`, a value the\n * declaration never held. An escape outside the table is not one this server\n * printed for a member the estate spelled, so inverting it would be a guess:\n * the column keeps MySQL's own `COLUMN_TYPE` instead and the push fails at the\n * final attestation, the same fail-closed direction the string inverse takes.\n */\nexport function parseMySqlEnumValues(columnType: string): string[] | null {\n const match = columnType.match(ENUM_VALUES_REGEX);\n if (!match?.[1]) return null;\n\n const content = match[1];\n const values: string[] = [];\n let i = 0;\n\n while (i < content.length) {\n // Skip whitespace and commas\n while (i < content.length && (content[i] === \" \" || content[i] === \",\")) {\n i++;\n }\n if (i >= content.length) break;\n\n // Expect opening quote\n if (content[i] !== \"'\") {\n i++;\n continue;\n }\n i++; // Skip opening quote\n\n // Collect value until closing quote (handle escaped quotes '' and \\')\n let value = \"\";\n while (i < content.length) {\n if (content[i] === \"\\\\\" && i + 1 < content.length) {\n // Backslash escape - the character MySQL's printer wrote it for\n const printed = MYSQL_PRINTED_CHARACTERS.get(content[i + 1] ?? \"\");\n if (printed === undefined) return null;\n value += printed;\n i += 2;\n } else if (content[i] === \"'\" && content[i + 1] === \"'\") {\n // Doubled quote escape - add single quote and skip both\n value += \"'\";\n i += 2;\n } else if (content[i] === \"'\") {\n // Closing quote\n i++;\n break;\n } else {\n value += content[i];\n i++;\n }\n }\n values.push(value);\n }\n\n return values.length > 0 ? values : null;\n}\n\n// =============================================================================\n// TYPE MAPPING FUNCTIONS\n// =============================================================================\n\nexport interface ScalarTypeContext {\n type: string;\n array?: boolean;\n withTimezone?: boolean;\n dimension?: number | undefined;\n /**\n * The declared fixed-decimal domain, for a `decimal` scalar. Every decimal\n * type on every dialect is DERIVED from it — there is no unconstrained\n * `numeric`, no `DECIMAL(65,30)`, and no TEXT decimal to fall back to.\n */\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * The declared domain of a decimal context.\n *\n * A decimal column with no descriptor has no physical type at all: the numbers\n * cannot be inferred from storage, a value, a driver, or an operation (plan\n * §1.1), so the alternative to refusing is inventing a second precision — which\n * is exactly the `DECIMAL(65,30)` this program deletes. The public decimal\n * factory cannot produce such a state; a hand-built or externally-deserialized\n * scalar state can, and this is where it stops.\n */\nfunction requireDecimalDomain(context: ScalarTypeContext): DecimalDescriptor {\n if (context.decimal) return context.decimal;\n throw new MigrationError(\n \"A decimal column has no declared precision and scale. \" +\n \"The fixed-decimal domain is declared once, on the scalar, and every physical type is derived from it.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { scalarType: \"decimal\" } }\n );\n}\n\n/**\n * The tables own ordinary defaults. Their timezone aliases are selected by\n * withTimezone, not admitted as independent scalar kinds. Unknown and inherited\n * keys retain the string fallback.\n */\nfunction defaultType(\n defaults: Readonly<Record<string, string>> & { readonly string: string },\n type: string\n): string {\n return type !== \"datetimetz\" &&\n type !== \"timetz\" &&\n Object.hasOwn(defaults, type)\n ? defaults[type]!\n : defaults.string;\n}\n\n/** PostgreSQL keeps native lists, exact decimal typmods and vector dimensions. */\nexport function getPostgresType(context: ScalarTypeContext): string {\n const type = context.type;\n let baseType: string;\n if (type === \"decimal\")\n baseType = decimalColumnType(\"pg\", requireDecimalDomain(context));\n else if (type === \"datetime\" && context.withTimezone)\n baseType = PG_TYPE_DEFAULTS.datetimetz;\n else if (type === \"time\" && context.withTimezone)\n baseType = PG_TYPE_DEFAULTS.timetz;\n else if (type === \"vector\" && context.dimension !== undefined)\n baseType = `${PG_TYPE_DEFAULTS.vector}(${context.dimension})`;\n else baseType = defaultType(PG_TYPE_DEFAULTS, type);\n return context.array ? `${baseType}[]` : baseType;\n}\n/** SQLite lists use JSON, except the checked decimal TEXT container. */\nexport function getSQLiteType(context: ScalarTypeContext): string {\n if (context.array)\n return context.type === \"decimal\" ? SQLITE_DECIMAL_LIST_TYPE : \"JSON\";\n const type = context.type;\n return type === \"decimal\"\n ? decimalColumnType(\"sqlite\", requireDecimalDomain(context))\n : defaultType(SQLITE_TYPE_DEFAULTS, type);\n}\n\n/** MySQL lists use JSON; scalar decimals retain their declared precision/scale. */\nexport function getMySQLType(context: ScalarTypeContext): string {\n if (context.array) return \"JSON\";\n const type = context.type;\n if (type === \"decimal\")\n return decimalColumnType(\"mysql\", requireDecimalDomain(context));\n if (type === \"datetime\")\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.datetimetz\n : MYSQL_TYPE_DEFAULTS.datetime;\n if (type === \"time\")\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.timetz\n : MYSQL_TYPE_DEFAULTS.time;\n return defaultType(MYSQL_TYPE_DEFAULTS, type);\n}\n","import type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\n\nconst DOLLAR_QUOTE = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/;\nconst IDENTIFIER_START = /[A-Za-z_]/;\nconst IDENTIFIER_PART = /[A-Za-z0-9_$]/;\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\nconst SQL_WHITESPACE = /\\s/;\n\nexport type NativeRenameOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" | \"renameColumn\" }\n>;\n\n/**\n * Applies the schema-wide effect a database native rename has already made.\n *\n * The resolver uses this as its next differ input, generated down migrations\n * use it to address definitions before the inverse rename runs, and SQLite's\n * batch replay uses it before a later table reconstruction. It never mutates\n * the snapshot supplied by the caller.\n */\nexport function applyNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables:\n operation.type === \"renameTable\"\n ? renameTable(snapshot.tables, operation.from, operation.to)\n : renameColumn(\n snapshot.tables,\n operation.tableName,\n operation.from,\n operation.to\n ),\n };\n}\n\nfunction renameTable(\n tables: readonly TableDef[],\n from: string,\n to: string\n): TableDef[] {\n return tables.map((table) => ({\n ...table,\n name: table.name === from ? to : table.name,\n foreignKeys: table.foreignKeys.map((foreignKey) =>\n foreignKey.referencedTable === from\n ? { ...foreignKey, referencedTable: to }\n : foreignKey\n ),\n }));\n}\n\nfunction renameColumn(\n tables: readonly TableDef[],\n tableName: string,\n from: string,\n to: string\n): TableDef[] {\n const renamed = (name: string) => (name === from ? to : name);\n\n return tables.map((table) => {\n const ownsColumn = table.name === tableName;\n return {\n ...table,\n columns: ownsColumn\n ? table.columns.map((column) =>\n column.name === from ? { ...column, name: to } : column\n )\n : table.columns,\n ...(ownsColumn && table.primaryKey\n ? {\n primaryKey: {\n ...table.primaryKey,\n columns: table.primaryKey.columns.map(renamed),\n },\n }\n : {}),\n indexes: ownsColumn\n ? table.indexes.map((index) => ({\n ...index,\n columns: index.columns.map(renamed),\n ...(index.where === undefined\n ? {}\n : { where: renameSqlIdentifier(index.where, from, to) }),\n }))\n : table.indexes,\n foreignKeys: table.foreignKeys.map((foreignKey) => ({\n ...foreignKey,\n columns: ownsColumn\n ? foreignKey.columns.map(renamed)\n : foreignKey.columns,\n referencedColumns:\n foreignKey.referencedTable === tableName\n ? foreignKey.referencedColumns.map(renamed)\n : foreignKey.referencedColumns,\n })),\n uniqueConstraints: ownsColumn\n ? table.uniqueConstraints.map((constraint) => ({\n ...constraint,\n columns: constraint.columns.map(renamed),\n }))\n : table.uniqueConstraints,\n };\n });\n}\n\n/**\n * Rewrites one identifier in an opaque SQL expression without touching values.\n *\n * PostgreSQL and SQLite persist partial-index predicates as SQL text, but a\n * native column rename changes the parsed column references in those\n * predicates. Snapshot replay must model the same effect before a later table\n * recreation. Quoted identifiers retain their delimiter; ordinary identifiers\n * retain their spelling style when the target can be written bare. Strings,\n * dollar-quoted bodies, and comments are copied byte-for-byte.\n */\nfunction renameSqlIdentifier(sql: string, from: string, to: string): string {\n let rewritten = \"\";\n let cursor = 0;\n\n while (cursor < sql.length) {\n const quote = sql[cursor];\n\n if (quote === \"'\") {\n const end = quotedRegionEnd(sql, cursor, \"'\", \"'\");\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === '\"' || quote === \"`\") {\n const end = quotedRegionEnd(sql, cursor, quote, quote);\n if (sql[end - 1] !== quote) {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(`${quote}${quote}`, quote);\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `${quote}${to.replaceAll(quote, `${quote}${quote}`)}${quote}`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"[\") {\n const end = quotedRegionEnd(sql, cursor, \"]\", \"]\");\n if (sql[end - 1] !== \"]\") {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(\"]]\", \"]\");\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `[${escapeBracketIdentifier(to)}]`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"-\" && sql[cursor + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", cursor + 2);\n const end = newline < 0 ? sql.length : newline;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"/\" && sql[cursor + 1] === \"*\") {\n const end = blockCommentEnd(sql, cursor);\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"$\") {\n const delimiter = dollarQuoteDelimiter(sql, cursor);\n if (delimiter !== undefined) {\n const closing = sql.indexOf(delimiter, cursor + delimiter.length);\n const end = closing < 0 ? sql.length : closing + delimiter.length;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n }\n if (isIdentifierStart(quote)) {\n let end = cursor + 1;\n while (end < sql.length && isIdentifierPart(sql[end]!)) end += 1;\n const identifier = sql.slice(cursor, end);\n const lowercaseIdentifier = identifier.toLowerCase();\n const escapeStringQuote =\n lowercaseIdentifier === \"e\" && sql[end] === \"'\"\n ? end\n : lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\"\n ? end + 1\n : undefined;\n if (escapeStringQuote !== undefined) {\n const literalEnd = quotedRegionEnd(\n sql,\n escapeStringQuote,\n \"'\",\n \"'\",\n true\n );\n rewritten += sql.slice(cursor, literalEnd);\n cursor = literalEnd;\n continue;\n }\n const isStringPrefix =\n sql[end] === \"'\" ||\n (lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\");\n rewritten +=\n !(isStringPrefix || isNonColumnIdentifier(sql, cursor, end)) &&\n unquotedIdentifierMatches(identifier, from)\n ? bareIdentifierOrQuoted(to)\n : identifier;\n cursor = end;\n continue;\n }\n\n rewritten += quote;\n cursor += 1;\n }\n\n return rewritten;\n}\n\nfunction quotedRegionEnd(\n sql: string,\n start: number,\n closingQuote: string,\n escapedQuote: string,\n backslashEscapes = false\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== closingQuote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === escapedQuote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\nfunction blockCommentEnd(sql: string, start: number): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length && depth > 0) {\n if (sql[cursor] === \"/\" && sql[cursor + 1] === \"*\") {\n depth += 1;\n cursor += 2;\n } else if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n } else {\n cursor += 1;\n }\n }\n return cursor;\n}\n\nfunction dollarQuoteDelimiter(sql: string, start: number): string | undefined {\n const rest = sql.slice(start);\n const match = DOLLAR_QUOTE.exec(rest);\n return match?.[0];\n}\n\nfunction isIdentifierStart(character: string | undefined): boolean {\n return character !== undefined && IDENTIFIER_START.test(character);\n}\n\nfunction isIdentifierPart(character: string): boolean {\n return IDENTIFIER_PART.test(character);\n}\n\nfunction unquotedIdentifierMatches(identifier: string, from: string): boolean {\n return from === from.toLowerCase() && identifier.toLowerCase() === from;\n}\n\nfunction isNonColumnIdentifier(\n sql: string,\n start: number,\n end: number\n): boolean {\n let next = end;\n while (next < sql.length && SQL_WHITESPACE.test(sql[next]!)) next += 1;\n if (sql[next] === \"(\" || (sql[next] === \"=\" && sql[next + 1] === \">\")) {\n return true;\n }\n\n let previous = start - 1;\n while (previous >= 0 && SQL_WHITESPACE.test(sql[previous]!)) previous -= 1;\n if (sql[previous] === \".\") return true;\n if (sql[previous] === \":\" && sql[previous - 1] === \":\") return true;\n\n const previousEnd = previous + 1;\n while (previous >= 0 && isIdentifierPart(sql[previous]!)) previous -= 1;\n const previousWord = sql.slice(previous + 1, previousEnd).toLowerCase();\n return previousWord === \"as\" || previousWord === \"collate\";\n}\n\nfunction bareIdentifierOrQuoted(identifier: string): string {\n return BARE_IDENTIFIER.test(identifier)\n ? identifier\n : `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction escapeBracketIdentifier(identifier: string): string {\n return identifier.split(\"]\").join(\"]]\");\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n// =============================================================================\n// SCHEMA SNAPSHOT (database-agnostic representation)\n// =============================================================================\n\nexport interface SchemaSnapshot {\n tables: TableDef[];\n enums?: EnumDef[] | undefined;\n /**\n * Generated-file history for polymorphic discriminator members.\n * This is descriptive metadata only; the structural differ ignores it.\n */\n polymorphicStorage?: readonly PolymorphicSnapshotStorage[] | undefined;\n}\n\nexport interface PolymorphicToOneSnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n}\n\n/**\n * Logical-only history for a to-one polymorphic relation. The physical\n * facts (columns, index) live in the owner's {@link TableDef} where the\n * structural differ owns them; `storageRef` is the join key into the owner\n * table's `relationStorage` registry — the physical type-column name at\n * serialization time, opaque to every reader and normalized through accepted\n * rename operations before history joins.\n */\nexport interface PolymorphicToOneSnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toOne\";\n readonly storageRef: string;\n readonly members: readonly PolymorphicToOneSnapshotMember[];\n}\n\nexport interface PolymorphicToManySnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n readonly memberJunctionTable: string;\n readonly inverseCardinality: \"one\" | \"many\";\n}\n\n/**\n * Logical-only history for a collection polymorphic relation: nothing\n * physical (no side columns, constraint names, or referential actions) — each\n * member names its junction table and the structural differ owns that table's\n * shape entirely.\n */\nexport interface PolymorphicToManySnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toMany\";\n readonly members: readonly PolymorphicToManySnapshotMember[];\n}\n\nexport type PolymorphicSnapshotStorage =\n | PolymorphicToOneSnapshot\n | PolymorphicToManySnapshot;\n\n/**\n * One relation-owned physical storage annotation on the table that carries it,\n * keyed in {@link TableDef.relationStorage} by the storage ref (the physical\n * type-column name at serialization time).\n */\nexport interface PolymorphicToOneStorageRegistryEntry {\n readonly kind: \"polymorphicToOne\";\n readonly typeColumn: string;\n readonly idColumn: string;\n readonly index: string;\n}\n\nexport interface TableDef {\n name: string;\n columns: ColumnDef[];\n primaryKey?: PrimaryKeyDef | undefined;\n indexes: IndexDef[];\n foreignKeys: ForeignKeyDef[];\n uniqueConstraints: UniqueConstraintDef[];\n /**\n * Relation-owned storage registry, annotation ONLY: the structural differ\n * ignores it, drivers pass it through `finalizeTable` untouched, no DDL\n * reads it, and introspected snapshots never carry it. Its sole reader is\n * polymorphic member history, which joins\n * {@link PolymorphicToOneSnapshot.storageRef} into it.\n */\n relationStorage?:\n | Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>>\n | undefined;\n /**\n * A generated junction, where a driver stores one differently from a table:\n * {@link MigrationDriver.markJunction} says so. No SQL driver sets it.\n */\n junction?: true | undefined;\n}\n\nexport interface ColumnDef {\n name: string;\n type: string; // Normalized type (e.g., \"varchar(255)\", \"integer\", \"boolean\")\n nullable: boolean;\n default?: string | undefined; // SQL expression for default value\n autoIncrement?: boolean | undefined;\n /**\n * The declared fixed-decimal domain this column stores, when it stores one.\n *\n * `type` is the ACTIVE PHYSICAL representation and this is the ONE logical\n * descriptor beside it — the pair every consumer reads (serializer, snapshot,\n * differ, DDL, introspection, defaults, table reconstruction). They are not\n * redundant: on PostgreSQL and MySQL the physical type spells the domain, but\n * on SQLite the class is `INTEGER` (scalar) or `TEXT` (list) whatever the\n * precision and scale are, so a descriptor change is invisible in `type`\n * alone and the differ would plan nothing for it.\n *\n * Every snapshot producer carries it — the serializer from\n * `ScalarState[\"decimal\"]`, and each introspection from the fact its dialect\n * can prove (a PostgreSQL typmod, a MySQL `DECIMAL(p,s)` or column-comment\n * marker, a SQLite reserved CHECK constraint name) — because a side that\n * cannot recover it would read as a change on every push, forever.\n *\n * There is no parallel decimal metadata map on `Model`, adapter, or\n * migration driver (plan §7.2): this field is the migration layer's only\n * copy, and it is a copy of the frozen descriptor the resolved scalar owns.\n */\n decimal?: DecimalDescriptor | undefined;\n /**\n * The declared SQLite storage vocabulary for one scalar DateTime column.\n *\n * SQLite's three physical types do not identify the logical domain: TEXT,\n * INTEGER, and REAL also store unrelated scalar families. The serializer\n * therefore carries the declaration beside the physical type so an explicit\n * migration can translate an existing DateTime instead of reinterpreting its\n * bytes. Live introspection cannot recover this logical fact and omits it.\n */\n dateTime?: DateTimePhysicalForm | undefined;\n /** SQLite writer CHECK version; physical metadata, never a public point language. */\n geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}\n\nexport interface PrimaryKeyDef {\n columns: string[];\n name?: string | undefined;\n /**\n * SQLite only: the table is `WITHOUT ROWID`, clustered by this key\n * (`Model.withoutRowid`). It lives on the key because it is a property of\n * how the key stores rows: a table without one cannot carry it, and a\n * change of it is the key's change (`dropPrimaryKey` + `addPrimaryKey`, a\n * recreation on SQLite). Absent on every other table and dialect, so their\n * snapshots and hashes are unchanged.\n */\n withoutRowid?: true | undefined;\n}\n\nexport interface IndexDef {\n name: string;\n columns: string[];\n unique: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"fulltext\" | \"spatial\" | undefined;\n where?: string | undefined; // For partial indexes\n /**\n * An index in the database's own language (`Model.rawIndex`). `columns` are\n * the columns its template names, in the order they first appear, and it is\n * never unique, typed or partial whatever the text says. `hash` is\n * `rawIndexHash(template)`; only an introspected snapshot lacks `template`,\n * since a database holds the rendered text and VibORM's marker beside it.\n */\n raw?: RawIndexDef | undefined;\n}\n\nexport interface RawIndexDef {\n readonly hash: string;\n readonly template?: string | undefined;\n}\n\nexport interface ForeignKeyDef {\n name: string;\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n onDelete?: ReferentialAction | undefined;\n onUpdate?: ReferentialAction | undefined;\n}\n\nexport type ReferentialAction =\n | \"cascade\"\n | \"setNull\"\n | \"restrict\"\n | \"noAction\"\n | \"setDefault\";\n\nexport interface UniqueConstraintDef {\n name: string;\n columns: string[];\n}\n\nexport interface EnumDef {\n name: string;\n values: string[];\n}\n\n/**\n * A CHECK constraint on a column a PostgreSQL enum recreation converts.\n *\n * A schema snapshot models no CHECK, so only `push` knows one: it reads it from\n * the live catalog while planning. The recreation drops it before its columns\n * become text, where PostgreSQL would re-parse it against the wrong type, and\n * adds it back under the same name once they are the enum again.\n */\nexport interface EnumDependentCheck {\n tableName: string;\n name: string;\n /** `pg_get_constraintdef`: `NOT VALID` included when it was never validated. */\n definition: string;\n /** The enum values its definition names as constants. */\n values: string[];\n}\n\n// =============================================================================\n// DIFF OPERATIONS (resolved, ready to execute)\n// =============================================================================\n\nexport type DiffOperation =\n | { type: \"createTable\"; table: TableDef }\n | { type: \"dropTable\"; tableName: string }\n | { type: \"renameTable\"; from: string; to: string }\n | { type: \"addColumn\"; tableName: string; column: ColumnDef }\n | { type: \"dropColumn\"; tableName: string; columnName: string }\n | { type: \"renameColumn\"; tableName: string; from: string; to: string }\n | {\n type: \"alterColumn\";\n tableName: string;\n columnName: string;\n from: ColumnDef;\n to: ColumnDef;\n }\n | { type: \"createIndex\"; tableName: string; index: IndexDef }\n | {\n type: \"dropIndex\";\n tableName: string;\n indexName: string;\n /**\n * A raw index's drop: its name never follows a column, so it need not\n * wait for a column rename (and a rollback then restores it after the\n * rename back, rendered with the column it names).\n */\n raw?: true | undefined;\n }\n | { type: \"addForeignKey\"; tableName: string; fk: ForeignKeyDef }\n | { type: \"dropForeignKey\"; tableName: string; fkName: string }\n | {\n type: \"addUniqueConstraint\";\n tableName: string;\n constraint: UniqueConstraintDef;\n }\n | { type: \"dropUniqueConstraint\"; tableName: string; constraintName: string }\n | { type: \"addPrimaryKey\"; tableName: string; primaryKey: PrimaryKeyDef }\n | { type: \"dropPrimaryKey\"; tableName: string; constraintName: string }\n | { type: \"createEnum\"; enumDef: EnumDef }\n | {\n type: \"dropEnum\";\n enumName: string;\n /**\n * Columns that depend on this enum.\n * Required for SQLite to know which columns need CHECK constraint removal.\n */\n dependentColumns?: Array<{ tableName: string; columnName: string }>;\n }\n | {\n type: \"alterEnum\";\n enumName: string;\n addValues?: string[] | undefined;\n removeValues?: string[] | undefined;\n /**\n * Full list of desired enum values (required when removing values)\n * Used to recreate the enum type in PostgreSQL\n */\n newValues?: string[] | undefined;\n /**\n * Columns that depend on this enum (required when removing values)\n * Each entry is { tableName, columnName }\n */\n dependentColumns?:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n /**\n * The live CHECK constraints on those columns (PostgreSQL push only;\n * offline generation cannot see them and leaves this unset).\n */\n dependentChecks?: EnumDependentCheck[] | undefined;\n /**\n * Global replacement values for removed enum values.\n * Used as fallback when no column-specific mapping exists.\n * Maps old value -> new value for data migration.\n *\n * Example: { \"pending\": \"inactive\" } - rows with \"pending\" become \"inactive\"\n * Use null to set rows to NULL: { \"pending\": null }\n */\n valueReplacements?: Record<string, string | null> | undefined;\n /**\n * Per-column replacement values for removed enum values.\n * Allows different columns to have different mappings.\n * Key is \"tableName.columnName\", value is the replacement map.\n *\n * Example: { \"users.status\": { \"pending\": \"inactive\" }, \"orders.status\": { \"pending\": \"cancelled\" } }\n */\n columnValueReplacements?:\n | Record<string, Record<string, string | null>>\n | undefined;\n /**\n * Default replacement for any removed values without explicit mapping.\n * Useful when the enum field has a default value - use that here.\n * Use null to set rows to NULL.\n *\n * Example: If your field has `.default(\"active\")`, set defaultReplacement: \"active\"\n */\n defaultReplacement?: string | null | undefined;\n };\n\n// =============================================================================\n// AMBIGUOUS CHANGES (require user input to resolve)\n// =============================================================================\n\n/** Detected when columns are added AND dropped in the same table */\nexport type AmbiguousColumnChange = {\n type: \"ambiguousColumn\";\n tableName: string;\n droppedColumn: ColumnDef;\n addedColumn: ColumnDef;\n};\n\n/** Detected when tables are added AND dropped */\nexport type AmbiguousTableChange = {\n type: \"ambiguousTable\";\n droppedTable: string;\n addedTable: string;\n droppedTableDef: TableDef;\n addedTableDef: TableDef;\n};\n\nexport type AmbiguousChange = AmbiguousColumnChange | AmbiguousTableChange;\n\n/** User's resolution for an ambiguous change */\nexport type ChangeResolution =\n | { type: \"rename\" } // Treat as rename (preserve data)\n | { type: \"addAndDrop\" }; // Treat as separate add + drop (data loss)\n\n// =============================================================================\n// DIFF RESULT (output of differ, before resolution)\n// =============================================================================\n\nexport interface DiffResult {\n /** Operations that are unambiguous and ready to execute */\n operations: DiffOperation[];\n /** Changes that need user input to resolve */\n ambiguousChanges: AmbiguousChange[];\n}\n\n// =============================================================================\n// RESOLVER (handles ambiguous changes)\n// =============================================================================\n\n/** Callback to resolve ambiguous changes (used by CLI or programmatic API) */\nexport type Resolver = (\n changes: AmbiguousChange[]\n) => Promise<Map<AmbiguousChange, ChangeResolution>>;\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACK\n// =============================================================================\n\n/**\n * Valid resolution results.\n * - \"proceed\": Accept the change (for destructive)\n * - \"reject\": Reject the change and abort\n * - \"rename\": Treat as a rename (for ambiguous)\n * - \"addAndDrop\": Treat as separate add + drop (for ambiguous)\n * - \"enumMapped\": Enum values have been mapped (for enumValueRemoval)\n */\nexport type ResolveResult =\n | \"proceed\"\n | \"reject\"\n | \"rename\"\n | \"addAndDrop\"\n | \"enumMapped\";\n\n/**\n * Base properties shared by destructive and ambiguous changes.\n */\ninterface BaseResolveChange {\n /** The specific operation type */\n operation:\n | \"dropTable\"\n | \"dropColumn\"\n | \"addColumn\"\n | \"alterColumn\"\n | \"renameTable\"\n | \"renameColumn\";\n\n /** The table involved */\n table: string;\n\n /** The column involved (if applicable) */\n column?: string;\n\n /** Human-readable description of the change */\n description: string;\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A destructive change that will cause data loss.\n * Available methods: `proceed()`, `reject()`\n */\nexport interface DestructiveResolveChange extends BaseResolveChange {\n type: \"destructive\";\n\n /** Accept the destructive change (causes data loss) */\n proceed(): \"proceed\";\n}\n\n/**\n * An ambiguous change that could be a rename or add+drop.\n * Available methods: `rename()`, `addAndDrop()`, `reject()`\n */\nexport interface AmbiguousResolveChange extends BaseResolveChange {\n type: \"ambiguous\";\n\n /** The old name (for renames) */\n oldName?: string;\n\n /** The new name (for renames) */\n newName?: string;\n\n /** The old type (for alterColumn) */\n oldType?: string;\n\n /** The new type (for alterColumn) */\n newType?: string;\n\n /** Treat as a rename (preserves data) */\n rename(): \"rename\";\n\n /** Treat as separate add + drop (causes data loss) */\n addAndDrop(): \"addAndDrop\";\n}\n\n/**\n * An enum value removal that needs replacement mappings for a specific column.\n * Called once per column that uses the enum, allowing different mappings per column.\n * Available methods: `mapValues()`, `useNull()`, `reject()`\n */\nexport interface EnumValueRemovalChange {\n type: \"enumValueRemoval\";\n\n /** The enum name */\n enumName: string;\n\n /** The table containing the column */\n tableName: string;\n\n /** The column using this enum */\n columnName: string;\n\n /** Whether this column is nullable (if true, useNull() is safe) */\n isNullable: boolean;\n\n /** Values being removed */\n removedValues: string[];\n\n /** Available values to map to */\n availableValues: string[];\n\n /** Human-readable description */\n description: string;\n\n /**\n * Map removed values to replacement values.\n * @param replacements - Map of old value → new value (or null for NULL)\n */\n mapValues(replacements: Record<string, string | null>): \"enumMapped\";\n\n /**\n * Set all removed values to NULL.\n * This is a shorthand for mapValues where all values map to null.\n * Note: Only safe if the column is nullable.\n */\n useNull(): \"enumMapped\";\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A change that requires user resolution.\n * Use the type discriminant to determine which methods are available:\n * - `destructive`: `proceed()`, `reject()`\n * - `ambiguous`: `rename()`, `addAndDrop()`, `reject()`\n * - `enumValueRemoval`: `mapValues()`, `reject()`\n */\nexport type ResolveChange =\n | DestructiveResolveChange\n | AmbiguousResolveChange\n | EnumValueRemovalChange;\n\nexport type EnumResolutionDecision =\n | {\n readonly kind: \"mapValues\";\n readonly mappings: Record<string, string | null>;\n }\n | { readonly kind: \"useNull\" }\n | { readonly kind: \"mixed\" };\n\nconst enumResolutionDecisions = new WeakMap<\n ResolveChange,\n EnumResolutionDecision\n>();\n\n/** Internal authoritative decision made through an enum change's own methods. */\nexport function readEnumResolutionDecision(\n change: ResolveChange\n): EnumResolutionDecision | undefined {\n return enumResolutionDecisions.get(change);\n}\n\nfunction recordEnumResolutionDecision(\n change: EnumValueRemovalChange,\n decision: Exclude<EnumResolutionDecision, { readonly kind: \"mixed\" }>\n): void {\n const previous = enumResolutionDecisions.get(change);\n enumResolutionDecisions.set(\n change,\n previous !== undefined && previous.kind !== decision.kind\n ? { kind: \"mixed\" }\n : decision\n );\n}\n\n/**\n * Unified callback for resolving changes that need user input.\n * Called once per change, allowing granular control over each decision.\n *\n * @param change - The change requiring resolution\n * @returns The resolution decision (call a method on change to get this)\n *\n * @example\n * ```ts\n * resolve: async (change) => {\n * console.log(change.description);\n *\n * if (change.type === \"destructive\") {\n * return confirm(\"Accept data loss?\") ? change.proceed() : change.reject();\n * }\n *\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n *\n * if (change.type === \"enumValueRemoval\") {\n * // Map removed enum values to new values\n * return change.mapValues({\n * 'PENDING': 'INACTIVE',\n * 'OLD_VALUE': null, // Set to NULL\n * });\n * }\n * }\n * ```\n */\nexport type ResolveCallback = (\n change: ResolveChange\n) =>\n | Promise<ResolveResult | undefined | void>\n | ResolveResult\n | undefined\n | void;\n\n/**\n * Create a destructive change object with resolution methods.\n */\nexport function createDestructiveChange(props: {\n operation: \"dropTable\" | \"dropColumn\" | \"addColumn\" | \"alterColumn\";\n table: string;\n column?: string;\n description: string;\n}): DestructiveResolveChange {\n return {\n type: \"destructive\",\n ...props,\n proceed: () => \"proceed\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an ambiguous change object with resolution methods.\n */\nexport function createAmbiguousChange(props: {\n operation: \"renameTable\" | \"renameColumn\";\n table: string;\n column?: string;\n oldName?: string;\n newName?: string;\n oldType?: string;\n newType?: string;\n description: string;\n}): AmbiguousResolveChange {\n return {\n type: \"ambiguous\",\n ...props,\n rename: () => \"rename\",\n addAndDrop: () => \"addAndDrop\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an enum value removal change object with resolution methods.\n */\nexport function createEnumValueRemovalChange(props: {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n description: string;\n}): EnumValueRemovalChange {\n const change: EnumValueRemovalChange = {\n type: \"enumValueRemoval\",\n ...props,\n mapValues: (replacements: Record<string, string | null>) => {\n const mappings: Record<string, string | null> = {};\n for (const [value, replacement] of Object.entries(replacements)) {\n mappings[value] = replacement;\n }\n Object.freeze(mappings);\n recordEnumResolutionDecision(change, { kind: \"mapValues\", mappings });\n return \"enumMapped\";\n },\n useNull: () => {\n recordEnumResolutionDecision(change, { kind: \"useNull\" });\n return \"enumMapped\";\n },\n reject: () => \"reject\",\n };\n return change;\n}\n\nexport type Dialect =\n | \"postgresql\"\n | \"sqlite\"\n | \"mysql\"\n | \"surrealql\"\n | \"snowflake\";\n\n/**\n * The durable estate target a migration history is generated for.\n *\n * PostgreSQL carries its schema because generated artifacts are\n * schema-qualified: a history generated for `billing` cannot be replayed as a\n * `public` estate. MySQL and SQLite arms carry ONLY their dialect — MySQL\n * artifacts are database-relative on purpose, so one estate deploys to\n * `app_dev`, `app_test` and `app_prod`, and SQLite has no namespace concept.\n *\n * This is the DURABLE compatibility claim, not the live execution destination.\n * The live destination is the adapter's namespace, which MySQL reads at its\n * live boundary and never persists here.\n */\nexport type MigrationTarget = (\n | { readonly dialect: \"postgresql\"; readonly namespace: string }\n | { readonly dialect: \"mysql\" }\n | { readonly dialect: \"sqlite\" }\n | { readonly dialect: \"surrealql\" }\n | { readonly dialect: \"snowflake\" }\n) & { readonly tables?: readonly string[] };\n","/**\n * The order in which tables are dropped: children before parents.\n *\n * Two callers need it, with different premises. A generated program\n * (`orderTableDrops`, reached through `prepareSchemaProgram`) still has live\n * foreign keys when it drops a table, so an order that violates one fails,\n * and a cycle is broken only where a key's delete action allows it. A\n * namespace reset (`live-reset.ts`) has already dropped every key it can see,\n * so its order is defence and a cycle falls back to inventory order.\n * `childrenBeforeParents` is the one rule they share; what a cycle means stays\n * with each caller.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DiffOperation, ReferentialAction, SchemaSnapshot } from \"./types\";\n\n/** `from` holds a foreign key that references `to`. */\nexport interface TableReference {\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * Orders `items` so that no item comes after a table it is referenced by.\n *\n * Each round takes every item no remaining item references, in input order, so\n * independent tables keep their given order. What a cycle leaves unordered is\n * returned as `blocked`, in input order; a reference from an item to itself\n * blocks that item.\n */\nexport function childrenBeforeParents<T>(\n items: readonly T[],\n nameOf: (item: T) => string,\n references: readonly TableReference[]\n): { ordered: T[]; blocked: T[] } {\n const referencedBy = new Map<string, string[]>();\n for (const { from, to } of references) {\n const children = referencedBy.get(to);\n if (children) {\n children.push(from);\n } else {\n referencedBy.set(to, [from]);\n }\n }\n\n let remaining = [...items];\n const ordered: T[] = [];\n for (;;) {\n const names = new Set(remaining.map(nameOf));\n const isFree = (item: T) =>\n !referencedBy.get(nameOf(item))?.some((child) => names.has(child));\n const free = remaining.filter(isFree);\n if (free.length === 0) {\n return { ordered, blocked: remaining };\n }\n ordered.push(...free);\n remaining = remaining.filter((item) => !isFree(item));\n }\n}\n\ntype DropTable = Extract<DiffOperation, { type: \"dropTable\" }>;\n\nconst tableOf = (drop: DropTable) => drop.tableName;\n\n/** A key still active when its tables are dropped. */\ninterface ActiveKey extends TableReference {\n readonly columns: readonly string[];\n readonly onDelete: ReferentialAction | undefined;\n}\n\n/**\n * Orders a prepared program's `dropTable` operations from the foreign keys\n * the CURRENT snapshot says exist, children first wherever the keys allow.\n *\n * A key matters while it is still active when its tables are dropped: both of\n * its tables are dropped, and the program does not remove it with an explicit\n * `dropForeignKey`. PostgreSQL and MySQL remove every such key first\n * (`materializeDroppedTableForeignKeys`), so their drops keep the order they\n * were given. A retained table never references a dropped one: the desired\n * schema cannot, so the differ removes that key, and `sortOperations` runs\n * every `dropForeignKey` before every `dropTable`.\n *\n * SQLite holds keys inline and drops with enforcement on. `DROP TABLE` first\n * deletes every row, applying each key's delete action (`refusalOf`), so a\n * cycle is broken at a table whose drop no key can refuse, and refused before\n * any statement exists when no such table remains. The drops replace the band\n * of drops `sortOperations` emitted, where that band begins.\n */\nexport function orderTableDrops(\n operations: DiffOperation[],\n current: SchemaSnapshot\n): DiffOperation[] {\n const drops = operations.filter(\n (operation): operation is DropTable => operation.type === \"dropTable\"\n );\n if (drops.length === 0) {\n return operations;\n }\n\n const dropped = new Set(drops.map(tableOf));\n const removedKeys = new Set<string>();\n for (const operation of operations) {\n if (operation.type === \"dropForeignKey\") {\n removedKeys.add(`${operation.tableName} ${operation.fkName}`);\n }\n }\n const keys: ActiveKey[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const active =\n dropped.has(table.name) &&\n dropped.has(fk.referencedTable) &&\n !removedKeys.has(`${table.name} ${fk.name}`);\n if (active) {\n keys.push({\n from: table.name,\n to: fk.referencedTable,\n columns: fk.columns,\n onDelete: fk.onDelete,\n });\n }\n }\n }\n // Children first: every key between two tables, and a self-reference that\n // refuses even its own table's delete.\n const childFirst = keys.filter(\n (key) => key.from !== key.to || key.onDelete === \"restrict\"\n );\n\n const ordered: DropTable[] = [];\n let remaining = drops;\n for (;;) {\n const step = childrenBeforeParents(remaining, tableOf, childFirst);\n ordered.push(...step.ordered);\n if (step.blocked.length === 0) {\n break;\n }\n const left = new Set(step.blocked.map(tableOf));\n const next = step.blocked.find(\n (drop) => !refusalOf(drop.tableName, keys, left)\n );\n if (!next) {\n throw cyclicDropRefusal(step.blocked.map(tableOf), keys);\n }\n ordered.push(next);\n remaining = step.blocked.filter((drop) => drop !== next);\n }\n\n const first = operations.findIndex(\n (operation) => operation.type === \"dropTable\"\n );\n const rest = operations.filter((operation) => operation.type !== \"dropTable\");\n return [...rest.slice(0, first), ...ordered, ...rest.slice(first)];\n}\n\n/**\n * The key that may refuse dropping `table` while the `existing` tables,\n * `table` among them, remain, if any.\n *\n * The implicit delete removes every row of `table`, and CASCADE extends it to\n * the rows of each remaining table that cascades from a deleted one. A\n * remaining key into a deleted table then decides: CASCADE deleted its rows\n * too and SET NULL clears them; RESTRICT refuses at once; NO ACTION and SET\n * DEFAULT are settled when the statement ends, by when a key held by `table`\n * has lost every row, while one held by another table may still point at\n * nothing. Measured on better-sqlite3 over random populated rows, for every\n * pair of actions on a two-table cycle in both orders and for each action on\n * a self-reference.\n */\nfunction refusalOf(\n table: string,\n keys: readonly ActiveKey[],\n existing: ReadonlySet<string>\n): ActiveKey | undefined {\n const deleted = new Set([table]);\n for (const name of deleted) {\n for (const key of keys) {\n if (\n key.to === name &&\n key.onDelete === \"cascade\" &&\n existing.has(key.from)\n ) {\n deleted.add(key.from);\n }\n }\n }\n return keys.find(\n (key) =>\n deleted.has(key.to) &&\n existing.has(key.from) &&\n key.onDelete !== \"cascade\" &&\n key.onDelete !== \"setNull\" &&\n (key.onDelete === \"restrict\" || key.from !== table)\n );\n}\n\nconst ACTION_SQL: Record<ReferentialAction, string> = {\n cascade: \"CASCADE\",\n setNull: \"SET NULL\",\n restrict: \"RESTRICT\",\n noAction: \"NO ACTION\",\n setDefault: \"SET DEFAULT\",\n};\n\n/**\n * Names every blocked table and a key that refuses its drop, by columns:\n * SQLite introspection cannot read a key's name back.\n */\nfunction cyclicDropRefusal(\n blocked: readonly string[],\n keys: readonly ActiveKey[]\n): MigrationError {\n const left = new Set(blocked);\n const reasons = blocked.flatMap((table) => {\n const key = refusalOf(table, keys, left);\n return key\n ? [\n `dropping \"${table}\" is refused by ${key.from}(${key.columns.join(\", \")}) -> ${key.to} ON DELETE ${ACTION_SQL[key.onDelete ?? \"noAction\"]}`,\n ]\n : [];\n });\n return new MigrationError(\n `Tables ${blocked.map((name) => `\"${name}\"`).join(\", \")} cannot be dropped in an order that satisfies their foreign keys: ${reasons.join(\"; \")}. This database enforces those keys while it drops a table and cannot drop a key without rebuilding its table, so the whole plan is refused before any statement runs. ` +\n \"Remove one of these relations, or change its delete action to SET NULL, in a separate change first; then drop the tables.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"cyclic-table-drop\" } }\n );\n}\n","/**\n * Shared migration helpers that do not own a V1 command.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { orderTableDrops } from \"./drop-order\";\nimport { sha256Hex, utf8Bytes } from \"./identity\";\nimport type { Dialect, DiffOperation, SchemaSnapshot } from \"./types\";\n\n/** PostgreSQL/MySQL derived identifiers keep their uniqueness under byte caps. */\nexport function derivedMigrationName(name: string): string {\n if (utf8Bytes(name).length <= 63) return name;\n let prefix = \"\";\n for (const character of name) {\n if (utf8Bytes(prefix + character).length > 54) break;\n prefix += character;\n }\n return `${prefix}_${sha256Hex(utf8Bytes(name)).slice(0, 8)}`;\n}\n\n/** Default generated-key spelling; dialects may supply their physical rule. */\nexport function defaultGeneratedPrimaryKeyName(\n tableName: string,\n name?: string\n): string {\n return name || `${tableName}_pkey`;\n}\n\n// DIALECT UTILITIES\n// =============================================================================\n\n/**\n * Validates and normalizes the database dialect for migrations.\n * Throws if the dialect is not supported.\n */\nexport function normalizeDialect(dialect: string): Dialect {\n if (dialect === \"postgresql\" || dialect === \"postgres\") {\n return \"postgresql\";\n }\n if (\n dialect === \"sqlite\" ||\n dialect === \"mysql\" ||\n dialect === \"surrealql\" ||\n dialect === \"snowflake\"\n ) {\n return dialect;\n }\n throw new MigrationError(\n `Unsupported dialect for migrations: \"${dialect}\". ` +\n \"Supported dialects: postgresql, sqlite, mysql.\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH,\n { meta: { dialect } }\n );\n}\n\n// QUERY EXECUTOR\n// =============================================================================\n\n/**\n * Type for executing SQL queries and returning rows.\n */\nexport type QueryExecutor = (\n sql: string,\n params?: unknown[]\n) => Promise<unknown[]>;\n\n/**\n * Creates a query executor from a driver.\n * Extracts rows from the QueryResult.\n */\nexport function createQueryExecutor(driver: AnyDriver): QueryExecutor {\n return async (sql: string, params?: unknown[]) => {\n const result = await driver._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n return result.rows;\n };\n}\n\n// =============================================================================\n// OPERATION UTILITIES\n// =============================================================================\n\n/**\n * Operation execution order priorities.\n * Lower numbers execute first.\n */\nconst OPERATION_PRIORITY: Record<DiffOperation[\"type\"], number> = {\n createEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n renameTable: 9,\n addColumn: 10,\n renameColumn: 11,\n alterColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n alterEnum: 1.5,\n dropEnum: 18,\n};\n\n/**\n * Slot for the index drops that have to run *after* the batch's index creates.\n * Between `createIndex` and `addForeignKey`, so a superseded index is gone\n * before a new constraint is bound to whatever is left.\n */\nconst SUPERSEDED_INDEX_DROP_PRIORITY =\n (OPERATION_PRIORITY.createIndex + OPERATION_PRIORITY.addForeignKey) / 2;\n\n/**\n * Picks out the `dropIndex` operations whose replacement has to exist first.\n *\n * MySQL binds a foreign key to whichever index covers its columns and refuses\n * to drop that index while it is the last one covering them (errno 1553). A\n * schema edit that supersedes such an index — widening it, or covering the same\n * columns with a unique constraint — plans the drop and its replacement in the\n * same batch, so the replacement has to be in place before the drop runs.\n *\n * Two arrangements keep a drop in its early slot instead:\n * - The batch creates an index of the *same name*, which the drop has to free\n * first. The name is matched on its own, not per table: PostgreSQL and SQLite\n * scope an index name to the schema/database, so a batch that frees a name on\n * one table and takes it on another collides too (Postgres 42P07). Matching\n * on the name alone can only keep a drop early, never defer one, so it cannot\n * reopen the 1553 case — there the created index has a different name.\n * - A table that also drops a column loses that column's indexes along with it,\n * so a drop deferred past the column drop would address an index already\n * gone. (A dropped *table* cannot collide: index diffs are only produced for\n * tables present in both snapshots.)\n */\nfunction supersededIndexDrops(operations: DiffOperation[]): Set<DiffOperation> {\n const createdIndexNames = new Set<string>();\n const tablesLosingColumns = new Set<string>();\n for (const op of operations) {\n if (op.type === \"createIndex\") {\n createdIndexNames.add(op.index.name);\n } else if (op.type === \"addUniqueConstraint\") {\n createdIndexNames.add(op.constraint.name);\n } else if (op.type === \"addPrimaryKey\" && op.primaryKey.name) {\n createdIndexNames.add(op.primaryKey.name);\n } else if (op.type === \"dropColumn\") {\n tablesLosingColumns.add(op.tableName);\n }\n }\n\n const superseded = new Set<DiffOperation>();\n for (const op of operations) {\n if (\n op.type === \"dropIndex\" &&\n // A raw index covers no foreign key, so 1553 never holds it; and a table\n // rebuild before its drop would have to re-create it, from a template\n // a removed declaration no longer has.\n !op.raw &&\n !createdIndexNames.has(op.indexName) &&\n !tablesLosingColumns.has(op.tableName)\n ) {\n superseded.add(op);\n }\n }\n return superseded;\n}\n\n/**\n * Sorts operations for proper execution order:\n * 1. Create enums (before tables that use them)\n * 2. Drop foreign keys (before dropping tables/columns)\n * 3. Drop indexes, constraints, columns\n * 4. Drop tables\n * 5. Create tables\n * 6. Establish table and column renames before operations using the new names\n * 7. Add or alter columns and constraints\n * 8. Create indexes\n * 9. Drop the indexes those creates supersede (see `supersededIndexDrops`)\n * 10. Add foreign keys (after tables/columns exist)\n */\nexport function sortOperations(operations: DiffOperation[]): DiffOperation[] {\n const superseded = supersededIndexDrops(operations);\n const priorityOf = (op: DiffOperation) =>\n superseded.has(op)\n ? SUPERSEDED_INDEX_DROP_PRIORITY\n : OPERATION_PRIORITY[op.type];\n const baseline = operations\n .map((operation, index) => ({ operation, index }))\n .sort((a, b) => priorityOf(a.operation) - priorityOf(b.operation));\n const renames = baseline.filter(\n ({ operation }) =>\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n );\n if (renames.length === 0) return baseline.map(({ operation }) => operation);\n const ordered: DiffOperation[] = [];\n const visited = new Set<number>();\n const active = new Set<number>();\n const visit = (entry: (typeof baseline)[number]): void => {\n if (visited.has(entry.index)) return;\n if (active.has(entry.index)) {\n throw new MigrationError(\n \"Migration operations contain a cyclic native rename dependency\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n active.add(entry.index);\n for (const prerequisite of renames) {\n if (prerequisite.index === entry.index) continue;\n const rename = prerequisite.operation;\n const operation = entry.operation;\n if (rename.type === \"renameTable\") {\n // A later producer can reuse an earlier table name. A column rename\n // before that name was consumed addresses the earlier identity.\n if (\n operation.type === \"renameColumn\" &&\n prerequisite.index > entry.index &&\n renames.some(\n (earlier) =>\n earlier.index > entry.index &&\n earlier.index < prerequisite.index &&\n earlier.operation.type === \"renameTable\" &&\n earlier.operation.from === operation.tableName\n )\n )\n continue;\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index && rename.to === operation.from\n : operationTargetsTable(operation, rename.to);\n if (needed) visit(prerequisite);\n } else if (rename.type === \"renameColumn\") {\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.from\n : operation.type === \"renameColumn\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.tableName &&\n rename.to === operation.from\n : operationTargetsColumn(operation, rename.tableName, rename.to);\n if (needed) visit(prerequisite);\n }\n }\n active.delete(entry.index);\n visited.add(entry.index);\n ordered.push(entry.operation);\n };\n for (const entry of baseline) visit(entry);\n return ordered;\n}\n\n/** A table operation that must address the post-rename identity. */\nfunction operationTargetsTable(\n operation: DiffOperation,\n tableName: string\n): boolean {\n if (operation.type === \"createTable\") {\n return operation.table.name === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) => column.tableName === tableName\n ) ?? false\n );\n }\n return \"tableName\" in operation && operation.tableName === tableName;\n}\n\nfunction operationTargetsColumn(\n operation: DiffOperation,\n tableName: string,\n columnName: string\n): boolean {\n // A drop names a key as the rename left it: on PostgreSQL a derived key\n // name follows its column. A raw index's name never does.\n if (operation.type === \"dropIndex\" && operation.raw) return false;\n if (\n operation.type === \"dropIndex\" ||\n operation.type === \"dropUniqueConstraint\" ||\n operation.type === \"dropForeignKey\"\n ) {\n return operation.tableName === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) =>\n column.tableName === tableName && column.columnName === columnName\n ) ?? false\n );\n }\n return (\n \"tableName\" in operation &&\n operation.tableName === tableName &&\n \"columnName\" in operation &&\n operation.columnName === columnName\n );\n}\n\n/**\n * Lifts *forward-reference* foreign keys out of `createTable` operations into\n * separate `addForeignKey` operations, so a table whose FK points at a table\n * created later in the same batch does not emit the constraint before its\n * referenced table exists.\n *\n * This is the DDL-ordering fix for `push()` / generated migrations: a schema\n * that declares a child model (the endpoint holding the FK) *before* its parent\n * would otherwise emit `ALTER TABLE child ADD ... FOREIGN KEY REFERENCES parent`\n * (Postgres) or an inline FK (MySQL) immediately after `CREATE TABLE child`,\n * before `CREATE TABLE parent` runs — Postgres `42P01`, MySQL analogous — and\n * the whole transactional push aborts with zero tables created.\n *\n * The transform is capability-gated and deliberately *surgical*:\n * - Drivers that cannot `ALTER TABLE ADD FOREIGN KEY` (SQLite/LibSQL) keep FKs\n * inline and are returned untouched — they resolve forward references lazily\n * and rewriting an FK into an `addForeignKey` op would trigger a table\n * recreation against an introspected-empty current schema.\n * - Only FKs that reference a table created *later* in this batch are lifted.\n * Backward references (referenced-first schemas, self-references, FKs to\n * pre-existing tables) already work and are left byte-identical, preserving\n * the DDL of schemas that were never broken.\n *\n * Lifted `addForeignKey` operations are appended after every other operation so\n * they run once all `CREATE TABLE`s have executed. Non-lifted operations retain\n * their exact input order.\n */\nexport function extractForwardReferenceForeignKeys(\n operations: DiffOperation[],\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n // Position of each table within the sequence of createTable operations.\n const createdTablePosition = new Map<string, number>();\n let position = 0;\n for (const op of operations) {\n if (op.type === \"createTable\") {\n createdTablePosition.set(op.table.name, position);\n position += 1;\n }\n }\n\n const result: DiffOperation[] = [];\n const liftedForeignKeys: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type !== \"createTable\") {\n result.push(op);\n continue;\n }\n\n const selfPosition = createdTablePosition.get(op.table.name);\n // Partition this table's FKs into those that must stay inline and those\n // that point forward to a table created later in the batch.\n const retained = op.table.foreignKeys.filter((fk) => {\n const targetPosition = createdTablePosition.get(fk.referencedTable);\n const isForwardReference =\n targetPosition !== undefined &&\n selfPosition !== undefined &&\n targetPosition > selfPosition;\n return !isForwardReference;\n });\n\n if (retained.length === op.table.foreignKeys.length) {\n // No forward references — leave the operation byte-identical.\n result.push(op);\n continue;\n }\n\n const forwardForeignKeys = op.table.foreignKeys.filter(\n (fk) => !retained.includes(fk)\n );\n\n result.push({\n ...op,\n table: { ...op.table, foreignKeys: retained },\n });\n for (const fk of forwardForeignKeys) {\n liftedForeignKeys.push({\n type: \"addForeignKey\",\n tableName: op.table.name,\n fk,\n });\n }\n }\n\n return [...result, ...liftedForeignKeys];\n}\n\n/**\n * Materializes the foreign-key drops a dropped-table graph needs, ONCE, for\n * every consumer: push, generated up SQL, and inverted generated down SQL.\n *\n * The differ omits a foreign-key drop when both endpoint tables disappear —\n * there is no surviving table to alter, so nothing produces the operation — and\n * §6.1 removes the `CASCADE` that used to paper over it. Without this stage a\n * `RESTRICT` drop of two mutually-referencing tables fails no matter which\n * order they are emitted in, and a cycle fails in every order.\n *\n * Every implicated key is included regardless of the table order the batch\n * happens to have, including keys whose owning AND referenced tables are both\n * being dropped, and including cycles. `sortOperations` then puts every\n * `dropForeignKey` (priority 2) ahead of every `dropTable` (priority 7).\n *\n * Drivers that cannot `ALTER TABLE ... DROP CONSTRAINT` keep their operations\n * byte-identical: SQLite and LibSQL hold foreign keys inline and rebuild tables\n * instead, so an explicit drop is not a statement they can emit.\n */\nexport function materializeDroppedTableForeignKeys(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n const droppedTables = new Set<string>();\n const plannedDrops = new Set<string>();\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n droppedTables.add(op.tableName);\n } else if (op.type === \"dropForeignKey\") {\n plannedDrops.add(`${op.tableName} ${op.fkName}`);\n }\n }\n if (droppedTables.size === 0) {\n return operations;\n }\n\n const materialized: DiffOperation[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const implicated =\n droppedTables.has(table.name) || droppedTables.has(fk.referencedTable);\n if (implicated && !plannedDrops.has(`${table.name} ${fk.name}`)) {\n materialized.push({\n type: \"dropForeignKey\",\n tableName: table.name,\n fkName: fk.name,\n });\n }\n }\n }\n\n return materialized.length === 0\n ? operations\n : [...materialized, ...operations];\n}\n\n/**\n * One compile-order owner for generated schema programs. Generate and push\n * both hand this result to the compiler, and nothing sorts it afterwards. Do\n * not lift, materialize or order drops at a second call site. Drops are\n * ordered last, once every foreign-key removal the program makes is known.\n */\nexport function prepareSchemaProgram(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n return orderTableDrops(\n materializeDroppedTableForeignKeys(\n extractForwardReferenceForeignKeys(operations, migrationDriver),\n current,\n migrationDriver\n ),\n current\n );\n}\n\n// =============================================================================\n// MIGRATION FILE UTILITIES\n// =============================================================================\n\n/**\n * Generate a migration name based on the operations.\n */\nexport function generateMigrationName(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"empty\";\n }\n\n const primaryOp = operations[0];\n if (!primaryOp) {\n return \"migration\";\n }\n\n switch (primaryOp.type) {\n case \"createTable\":\n return operations.length === 1\n ? `create-${primaryOp.table.name}`\n : \"initial\";\n case \"dropTable\":\n return `drop-${primaryOp.tableName}`;\n case \"addColumn\":\n return `add-${primaryOp.column.name}-to-${primaryOp.tableName}`;\n case \"dropColumn\":\n return `drop-${primaryOp.columnName}-from-${primaryOp.tableName}`;\n case \"renameTable\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"renameColumn\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"createIndex\":\n return `add-index-${primaryOp.index.name}`;\n case \"dropIndex\":\n return `drop-index-${primaryOp.indexName}`;\n case \"addForeignKey\":\n return `add-fk-${primaryOp.fk.name}`;\n case \"dropForeignKey\":\n return `drop-fk-${primaryOp.fkName}`;\n case \"createEnum\":\n return `create-enum-${primaryOp.enumDef.name}`;\n case \"dropEnum\":\n return `drop-enum-${primaryOp.enumName}`;\n case \"alterEnum\":\n return `alter-enum-${primaryOp.enumName}`;\n default:\n return \"migration\";\n }\n}\n","/** Runtime-neutral canonical Base64 for persisted migration parameters. */\nconst CANONICAL_SHAPE =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nexport function encodeBase64(bytes: Uint8Array): string {\n // Indexed reads preserve the byte view and ignore an overridden iterator;\n // spreading a large array into fromCharCode can overflow the call stack.\n let binary = \"\";\n // biome-ignore lint/style/useForOf: preserve indexed reads if the caller overrides iteration.\n for (let index = 0; index < bytes.length; index++)\n binary += String.fromCharCode(bytes[index]!);\n return btoa(binary);\n}\nexport function decodeCanonicalBase64(text: string): Uint8Array | undefined {\n if (!CANONICAL_SHAPE.test(text)) return;\n const binary = atob(text);\n const decoded = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++)\n decoded[index] = binary.charCodeAt(index);\n // atob also accepts nonzero padding bits; persisted parameters do not.\n return encodeBase64(decoded) === text ? decoded : undefined;\n}\n","/**\n * Shared hostile-parse primitives for Migration V1.\n *\n * Exact-key admission and primitive field readers. Artifact parsers own\n * their shapes; this file owns only the reusable refuse/key helpers.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isNumber, isRecord, isString } from \"../validation/value-guards\";\n\nexport function refuse(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\n}\n\nexport function exactObject(\n value: unknown,\n allowed: readonly string[],\n required: readonly string[],\n label: string\n): Record<string, unknown> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) refuse(`${label} has unknown key ${key}`);\n }\n for (const key of required) {\n if (!(key in value)) refuse(`${label} is missing ${key}`);\n }\n return value;\n}\n\nexport function parseFormat(value: unknown, label: string): \"1\" {\n if (value !== \"1\") refuse(`${label} format must be \"1\"`);\n return \"1\";\n}\n\nexport function parseFiniteInteger(value: unknown, label: string): number {\n if (\n !(isNumber(value) && Number.isInteger(value) && Number.isSafeInteger(value))\n ) {\n refuse(`${label} must be a safe integer`);\n }\n return value;\n}\n\nexport function parseRequiredString(value: unknown, label: string): string {\n if (!isString(value) || value.length === 0)\n refuse(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function parseStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) => {\n if (!isString(entry)) refuse(`${label}[${index}] must be a string`);\n return entry;\n });\n}\n\nexport function parseIdentifierArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) =>\n parseRequiredString(entry, `${label}[${index}]`)\n );\n}\n\n/** One of a closed list of literals, or the refusal `message`. */\nexport function parseMember<T>(\n value: unknown,\n allowed: readonly T[],\n message: string\n): T {\n const member = allowed.find((entry) => entry === value);\n if (member === undefined) refuse(message);\n return member;\n}\n\nconst TRUE_FLAGS: readonly unknown[] = [true, 1, 1n, \"1\", \"t\", \"true\"];\nconst FALSE_FLAGS: readonly unknown[] = [false, 0, 0n, \"0\", \"f\", \"false\"];\n\n/** A boolean as any provider spells it in a catalog row, or `undefined`. */\nexport function readFlag(value: unknown): boolean | undefined {\n if (TRUE_FLAGS.includes(value)) return true;\n return FALSE_FLAGS.includes(value) ? false : undefined;\n}\n\n/** Parse an already-admitted array with the artifact's indexed diagnostic path. */\nexport function parseItems<T>(\n items: readonly unknown[],\n label: string,\n parse: (value: unknown, label: string) => T\n): T[] {\n return items.map((value, index) => parse(value, `${label}[${index}]`));\n}\n","/**\n * Dispatch identity and hostile parameter admission.\n * Reset-plan and state parsers share this owner; they do not import each other.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeDecimal } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport { decodeCanonicalBase64 } from \"./base64\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { exactObject, parseFiniteInteger, refuse } from \"./v1-parse-shared\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\nconst DISPATCH_KEYS = [\n \"dispatchId\",\n \"length\",\n \"offset\",\n \"parameters\",\n \"sqlHash\",\n] as const;\n\nconst CANONICAL_BIGINT = /^(?:0|-?[1-9]\\d*)$/;\n\nexport function encodeDispatchIdentity(\n sqlHash: Sha256,\n offset: number,\n length: number,\n parameters: readonly MigrationParameterV1[]\n): Sha256 {\n return domainHash(\n HASH_DOMAIN.dispatch,\n canonicalizeJson({ sqlHash, offset, length, parameters })\n );\n}\n\nexport function parseDispatch(\n value: unknown,\n label: string\n): MigrationDispatchV1 {\n const record = exactObject(value, DISPATCH_KEYS, DISPATCH_KEYS, label);\n const offset = parseFiniteInteger(record.offset, `${label}.offset`);\n const length = parseFiniteInteger(record.length, `${label}.length`);\n if (offset < 0 || length < 0) refuse(`${label} range must be non-negative`);\n if (!Array.isArray(record.parameters))\n refuse(`${label}.parameters must be an array`);\n const parameters = record.parameters.map((parameter, index) =>\n parseParameter(parameter, `${label}.parameters[${index}]`)\n );\n const sqlHash = parseSha256(record.sqlHash, `${label}.sqlHash`);\n const dispatchId = parseSha256(record.dispatchId, `${label}.dispatchId`);\n const expected = encodeDispatchIdentity(sqlHash, offset, length, parameters);\n if (dispatchId !== expected) {\n throw new MigrationError(\n `${label}.dispatchId does not match its SQL range and parameters`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { dispatchId, sqlHash, offset, length, parameters };\n}\n\nfunction parseParameter(value: unknown, label: string): MigrationParameterV1 {\n if (!(isRecord(value) && isString(value.kind))) {\n refuse(`${label} must be a tagged parameter`);\n }\n switch (value.kind) {\n case \"null\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"null\" };\n case \"target-namespace\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"target-namespace\" };\n case \"boolean\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isBoolean(record.value)) refuse(`${label}.value must be boolean`);\n return { kind: \"boolean\", value: record.value };\n }\n case \"string\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value)) refuse(`${label}.value must be a string`);\n return { kind: \"string\", value: record.value };\n }\n case \"number\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!(isNumber(record.value) && Number.isFinite(record.value))) {\n refuse(`${label}.value must be a finite number`);\n }\n return { kind: \"number\", value: record.value };\n }\n case \"bigint\":\n case \"bytes\":\n case \"date-time\":\n case \"decimal\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value))\n refuse(`${label}.value must be canonical text`);\n assertCanonicalParameterText(value.kind, record.value, label);\n return { kind: value.kind, value: record.value };\n }\n case \"json\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n return { kind: \"json\", value: record.value };\n }\n default:\n refuse(`${label}.kind is not a V1 parameter tag`);\n }\n}\n\nfunction assertCanonicalParameterText(\n kind: \"bigint\" | \"bytes\" | \"date-time\" | \"decimal\",\n value: string,\n label: string\n): void {\n if (kind === \"bigint\" && !CANONICAL_BIGINT.test(value)) {\n refuse(`${label}.value must be canonical bigint text`);\n }\n if (kind === \"bytes\" && decodeCanonicalBase64(value) === undefined) {\n refuse(`${label}.value must be canonical base64 text`);\n }\n if (kind === \"date-time\") {\n try {\n if (new Date(value).toISOString() !== value) {\n refuse(`${label}.value must be canonical date-time text`);\n }\n } catch {\n refuse(`${label}.value must be canonical date-time text`);\n }\n }\n if (kind === \"decimal\" && canonicalizeDecimal(value) !== value) {\n refuse(`${label}.value must be canonical decimal text`);\n }\n}\n","/**\n * Hostile parsers and hash owner for Migration V1 marker and ledger rows.\n *\n * Path identity lives next to the marker it authenticates. Reset-plan\n * admission lives next to the ledger event that carries it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n exactObject,\n parseFiniteInteger,\n parseFormat,\n parseItems,\n parseMember,\n parseRequiredString,\n refuse,\n} from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n LedgerEventKindV1,\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ResetPlanV1,\n} from \"./v1-types\";\n\nexport function encodePathHash(path: readonly MarkerPathEdgeV1[]): Sha256 {\n return domainHash(HASH_DOMAIN.path, canonicalizeJson(path));\n}\n\nexport function eventIdFor(event: Omit<LedgerEventV1, \"eventId\">): Sha256 {\n return domainHash(HASH_DOMAIN.event, canonicalizeJson(event));\n}\n\nconst MARKER_KEYS = [\n \"estateHash\",\n \"format\",\n \"path\",\n \"pathHash\",\n \"revision\",\n \"snapshotHash\",\n \"stateId\",\n \"updatedAt\",\n] as const;\nconst PATH_EDGE_KEYS = [\n \"baselineBoundary\",\n \"stateId\",\n \"transitionHash\",\n] as const;\n\nexport function parseMarkerRow(value: unknown): MigrationMarkerV1 {\n const record = exactObject(\n value,\n MARKER_KEYS,\n MARKER_KEYS,\n \"migration marker\"\n );\n if (!Array.isArray(record.path)) refuse(\"marker.path must be an array\");\n const path = record.path.map((edge, index) => {\n const item = exactObject(\n edge,\n PATH_EDGE_KEYS,\n PATH_EDGE_KEYS,\n `marker.path[${index}]`\n );\n if (!isBoolean(item.baselineBoundary)) {\n refuse(`marker.path[${index}].baselineBoundary must be boolean`);\n }\n return {\n stateId: parseSha256(item.stateId, `marker.path[${index}].stateId`),\n transitionHash: parseSha256(\n item.transitionHash,\n `marker.path[${index}].transitionHash`\n ),\n baselineBoundary: item.baselineBoundary,\n };\n });\n const pathHash = parseSha256(record.pathHash, \"marker.pathHash\");\n if (pathHash !== encodePathHash(path)) {\n throw new MigrationError(\n \"marker.pathHash does not match the stored path\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (!isString(record.updatedAt) || record.updatedAt.length === 0) {\n refuse(\"marker.updatedAt must be an ISO timestamp\");\n }\n return {\n format: parseFormat(record.format, \"marker\"),\n estateHash: parseSha256(record.estateHash, \"marker.estateHash\"),\n stateId:\n record.stateId === null\n ? null\n : parseSha256(record.stateId, \"marker.stateId\"),\n snapshotHash: parseSha256(record.snapshotHash, \"marker.snapshotHash\"),\n path,\n pathHash,\n revision: parseFiniteInteger(record.revision, \"marker.revision\"),\n updatedAt: record.updatedAt,\n };\n}\n\nconst PREDICATE_KEYS = [\"deparsed\", \"index\", \"table\"] as const;\n\n/**\n * The marker row: the marker and, beside it, the partial-index predicates an\n * apply on PostgreSQL recorded as the server deparsed them (`casMarker`).\n */\nexport function parseMarkerPayload(value: unknown): {\n readonly marker: MigrationMarkerV1;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n} {\n if (!(isRecord(value) && \"predicates\" in value)) {\n return { marker: parseMarkerRow(value), predicates: [] };\n }\n const { predicates, ...marker } = value;\n if (!Array.isArray(predicates)) refuse(\"marker predicates must be an array\");\n return {\n marker: parseMarkerRow(marker),\n predicates: predicates.map((item: unknown, position) => {\n const label = `marker predicates[${position}]`;\n const record = exactObject(item, PREDICATE_KEYS, PREDICATE_KEYS, label);\n return {\n table: parseRequiredString(record.table, `${label}.table`),\n index: parseRequiredString(record.index, `${label}.index`),\n deparsed: parseRequiredString(record.deparsed, `${label}.deparsed`),\n };\n }),\n };\n}\n\nconst LEDGER_KINDS: readonly LedgerEventKindV1[] = [\n \"started\",\n \"step-confirmed\",\n \"applied\",\n \"failed\",\n \"rolled-back\",\n \"baselined\",\n \"reanchored\",\n \"resolved\",\n \"reset-started\",\n \"reset-step-confirmed\",\n \"reset-applied\",\n];\nconst EFFECT_STATES: readonly LedgerEffectStateV1[] = [\n \"none\",\n \"committed\",\n \"partial\",\n \"may-have-committed\",\n];\nconst DIRECTIONS: readonly LedgerEventV1[\"direction\"][] = [\n \"forward\",\n \"rollback\",\n \"reset\",\n \"baseline\",\n \"resolve\",\n];\nconst LEDGER_KEYS = [\n \"attemptId\",\n \"direction\",\n \"dispatchId\",\n \"effectState\",\n \"estateHash\",\n \"eventId\",\n \"failure\",\n \"finishedAt\",\n \"format\",\n \"fromState\",\n \"kind\",\n \"operationId\",\n \"snapshotHash\",\n \"sqlHash\",\n \"startedAt\",\n \"toState\",\n \"toolVersion\",\n \"transitionHash\",\n] as const;\nconst RESET_LEDGER_KEYS = [...LEDGER_KEYS, \"resetPlan\"] as const;\nconst RESET_PLAN_KEYS = [\n \"clearDispatches\",\n \"estateHash\",\n \"referencedStates\",\n \"replayPath\",\n \"resetPlanHash\",\n \"sourceFingerprint\",\n \"sourceRevision\",\n \"targetIdentity\",\n] as const;\n\nexport function parseLedgerEvent(value: unknown): LedgerEventV1 {\n if (!isRecord(value)) refuse(\"ledger event must be an object\");\n const kind = parseMember(\n value.kind,\n LEDGER_KINDS,\n \"ledger event.kind is not a V1 kind\"\n );\n const record = exactObject(\n value,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n \"ledger event\"\n );\n const event = {\n format: parseFormat(record.format, \"ledger event\"),\n eventId: parseSha256(record.eventId, \"ledger.eventId\"),\n attemptId: parseSha256(record.attemptId, \"ledger.attemptId\"),\n kind,\n estateHash: parseSha256(record.estateHash, \"ledger.estateHash\"),\n snapshotHash: parseSha256(record.snapshotHash, \"ledger.snapshotHash\"),\n sqlHash:\n record.sqlHash === null\n ? null\n : parseSha256(record.sqlHash, \"ledger.sqlHash\"),\n fromState:\n record.fromState === null\n ? null\n : parseSha256(record.fromState, \"ledger.fromState\"),\n toState:\n record.toState === null\n ? null\n : parseSha256(record.toState, \"ledger.toState\"),\n transitionHash:\n record.transitionHash === null\n ? null\n : parseSha256(record.transitionHash, \"ledger.transitionHash\"),\n direction: parseMember(\n record.direction,\n DIRECTIONS,\n \"ledger event.direction is invalid\"\n ),\n operationId:\n record.operationId === null\n ? null\n : parseRequiredString(record.operationId, \"ledger.operationId\"),\n dispatchId:\n record.dispatchId === null\n ? null\n : parseSha256(record.dispatchId, \"ledger.dispatchId\"),\n effectState: parseMember(\n record.effectState,\n EFFECT_STATES,\n \"ledger event.effectState is invalid\"\n ),\n startedAt: parseRequiredString(record.startedAt, \"ledger.startedAt\"),\n finishedAt:\n record.finishedAt === null\n ? null\n : parseRequiredString(record.finishedAt, \"ledger.finishedAt\"),\n toolVersion: parseRequiredString(record.toolVersion, \"ledger.toolVersion\"),\n failure:\n record.failure === null\n ? null\n : parseRequiredString(record.failure, \"ledger.failure\"),\n };\n const admitted =\n kind === \"reset-started\"\n ? { ...event, resetPlan: parseResetPlan(record.resetPlan) }\n : event;\n const { eventId, ...body } = admitted;\n if (eventId !== eventIdFor(body)) {\n throw new MigrationError(\n \"ledger eventId does not match the canonical event\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return admitted;\n}\n\nfunction parseResetPlan(value: unknown): ResetPlanV1 {\n const record = exactObject(\n value,\n RESET_PLAN_KEYS,\n RESET_PLAN_KEYS,\n \"reset plan\"\n );\n if (\n !(\n Array.isArray(record.replayPath) &&\n Array.isArray(record.clearDispatches) &&\n Array.isArray(record.referencedStates)\n )\n ) {\n refuse(\"reset plan arrays are malformed\");\n }\n const plan: ResetPlanV1 = {\n estateHash: parseSha256(record.estateHash, \"resetPlan.estateHash\"),\n targetIdentity: parseRequiredString(\n record.targetIdentity,\n \"resetPlan.targetIdentity\"\n ),\n sourceRevision: parseFiniteInteger(\n record.sourceRevision,\n \"resetPlan.sourceRevision\"\n ),\n sourceFingerprint: parseSha256(\n record.sourceFingerprint,\n \"resetPlan.sourceFingerprint\"\n ),\n replayPath: parseItems(\n record.replayPath,\n \"resetPlan.replayPath\",\n parseSha256\n ),\n clearDispatches: parseItems(\n record.clearDispatches,\n \"resetPlan.clearDispatches\",\n parseDispatch\n ),\n referencedStates: parseItems(\n record.referencedStates,\n \"resetPlan.referencedStates\",\n parseSha256\n ),\n resetPlanHash: parseSha256(record.resetPlanHash, \"resetPlan.resetPlanHash\"),\n };\n const { resetPlanHash, ...body } = plan;\n if (\n resetPlanHash !== domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(body))\n ) {\n throw new MigrationError(\n \"resetPlanHash does not match the canonical reset plan\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return plan;\n}\n","/**\n * Raw indexes: an index written in a database's own language\n * (`Model.rawIndex`), for what the index declaration cannot say.\n *\n * A template is held as written. `{name}` and `{table}` are the index and its\n * table; any other `{identifier}` is a scalar field of the model, and the\n * fields a template names, in the order they first appear, are the index's\n * `columns`: rendering puts the i-th of them where the i-th field stands, so a\n * snapshot needs no field-to-column map. Its identity is `rawIndexHash` of the\n * text; the database holds the rendered text and a marker beside it (the\n * columns, the name, the hash) that introspection reads back, since no catalog\n * can say which text a statement was rendered from.\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { RawIndexTemplates } from \"../schema/model\";\nimport { isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport {\n domainHash,\n HASH_DOMAIN,\n isSha256,\n type Sha256,\n utf8Bytes,\n} from \"./identity\";\nimport type { IndexDef } from \"./types\";\n\n/**\n * The template a dialect reads, by its key in `.rawIndex()`. Snowflake has\n * none: VibORM writes no DDL there. Every other dialect is stated, checked by\n * the type alone: one added to `Dialect` does not compile until it is here.\n */\nexport const RAW_INDEX_TEMPLATE_KEY: Readonly<\n Partial<Record<Dialect, keyof RawIndexTemplates>>\n> = {\n postgresql: \"pg\",\n mysql: \"mysql\",\n sqlite: \"sqlite\",\n surrealql: \"surrealdb\",\n} satisfies Record<Exclude<Dialect, \"snowflake\">, keyof RawIndexTemplates>;\n\n/** What a SQL database's catalog comment starts with when VibORM wrote it. */\nexport const RAW_INDEX_MARKER_PREFIX = \"viborm:raw:\";\n\nconst PLACEHOLDER = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\nconst RESERVED_PLACEHOLDERS: ReadonlySet<string> = new Set([\"name\", \"table\"]);\nconst SQL_HEADER =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+\\{name\\}\\s+ON\\s+\\{table\\}/i;\nconst SURREAL_HEADER =\n /^\\s*DEFINE\\s+INDEX\\s+\\{name\\}\\s+ON\\s+(?:TABLE\\s+)?\\{table\\}/i;\n/** A word read after the text: it ends the only statement unless a `;` or an open comment came first. */\nconst END = \"VIBORM_END\";\n\n/** The fields a template names, each once, in the order they first appear. */\nexport function rawIndexFields(template: string): string[] {\n const fields: string[] = [];\n for (const [, name] of template.matchAll(PLACEHOLDER)) {\n if (!(RESERVED_PLACEHOLDERS.has(name!) || fields.includes(name!)))\n fields.push(name!);\n }\n return fields;\n}\n\nexport function rawIndexHash(template: string): Sha256 {\n return domainHash(HASH_DOMAIN.rawIndex, utf8Bytes(template));\n}\n\n/**\n * One model's raw index as the serializer records it for `dialect`: its header\n * read, each field it names resolved to its column. `columnOf` answers a\n * scalar field's column, or undefined for anything else.\n */\nexport function declaredRawIndex(\n model: string,\n name: string,\n template: string,\n dialect: Dialect,\n columnOf: (field: string) => string | undefined\n): IndexDef {\n if (name === \"\")\n throw new MigrationError(\n `A raw index of \"${model}\" needs a name.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model } }\n );\n const header = dialect === \"surrealql\" ? SURREAL_HEADER : SQL_HEADER;\n if (!header.test(template))\n throw new MigrationError(\n `The raw index \"${model}.${name}\" must start with ${dialect === \"surrealql\" ? \"DEFINE INDEX {name} ON [TABLE] {table}\" : \"CREATE [UNIQUE] INDEX {name} ON {table}\"}, so that VibORM names it and finds its table.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name } }\n );\n const fields = rawIndexFields(template);\n if (fields.length === 0)\n throw new MigrationError(\n `The raw index \"${model}.${name}\" names no field: write each column it indexes as {field}, so that it follows renames and VibORM knows what it covers.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name } }\n );\n const columns = fields.map((field) => {\n const column = columnOf(field);\n if (column === undefined)\n throw new MigrationError(\n `The raw index \"${model}.${name}\" names {${field}}, which is not a scalar field of \"${model}\". Besides {name} and {table}, a placeholder is a scalar field.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model, indexName: name, field } }\n );\n return column;\n });\n return {\n name,\n columns,\n unique: false,\n raw: { hash: rawIndexHash(template), template },\n };\n}\n\n/** How a driver spells the parts a template leaves to it. */\nexport interface RawIndexSpelling {\n readonly name: string;\n readonly table: string;\n readonly column: (column: string) => string;\n}\n\n/** The statement a raw index's template renders to, its marker not included. */\nexport function renderRawIndex(\n index: IndexDef,\n spelling: RawIndexSpelling\n): string {\n const template = index.raw?.template;\n if (template === undefined)\n throw new MigrationError(\n `The index \"${index.name}\" was read from the database as a raw index this schema does not declare, so nothing says how to create it again. Declare it with .rawIndex(), or drop it in its own step first.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { indexName: index.name } }\n );\n const fields = rawIndexFields(template);\n return template.replace(PLACEHOLDER, (_, placeholder: string) => {\n if (placeholder === \"name\") return spelling.name;\n if (placeholder === \"table\") return spelling.table;\n return spelling.column(index.columns[fields.indexOf(placeholder)]!);\n });\n}\n\n/**\n * Refuses a rendered template the marker cannot be attached to: one whose\n * marker would land outside its statement (a top-level `;` anywhere, a\n * comment left open), or a word VibORM writes itself (`refused`), as an\n * executable word of the statement, so a quoted identifier or a string that\n * spells one is no refusal. The dialect's own statement reader decides both.\n */\nexport function refuseRawIndexStatement(\n index: IndexDef,\n rendered: string,\n read: (text: string) => readonly (readonly string[])[],\n refused: readonly string[]\n): void {\n const statements = read(`${rendered}\\n${END}`);\n if (statements.length !== 1 || statements[0]!.at(-1)?.toUpperCase() !== END)\n throw new MigrationError(\n `The raw index \"${index.name}\" must be one statement, with no semicolon and no comment left open: VibORM attaches its marker to it.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name } }\n );\n const word = refused.find((candidate) => statements[0]!.includes(candidate));\n if (word !== undefined)\n throw new MigrationError(\n `The raw index \"${index.name}\" says ${word}, which VibORM writes itself on this database: ${word === \"CONCURRENTLY\" ? \"a raw index is always built in the migration's own transaction\" : \"the index carries VibORM's marker there\"}. Remove it from the template.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name } }\n );\n}\n\n/**\n * What a database holds beside a raw index: canonical JSON of its columns,\n * name and hash, which is exactly the projection `fingerprintSnapshot` hashes.\n */\nexport function rawIndexMarker(index: IndexDef): string {\n return canonicalizeJsonText({\n columns: index.columns,\n name: index.name,\n raw: index.raw!.hash,\n });\n}\n\n/**\n * A raw index from the marker beside index `name`, or undefined when the text\n * is not one VibORM wrote for that index (an index renamed by hand keeps a\n * marker naming its old name, and is no longer the declared one).\n */\nexport function readRawIndexMarker(\n text: string,\n name: string\n): IndexDef | undefined {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (!isRecord(value)) return undefined;\n const keys = Object.keys(value).sort();\n if (keys.join() !== \"columns,name,raw\") return undefined;\n const { columns, raw } = value;\n if (\n value.name !== name ||\n !isSha256(raw) ||\n !Array.isArray(columns) ||\n columns.length === 0 ||\n !columns.every((column) => isString(column) && column !== \"\")\n )\n return undefined;\n return {\n name,\n columns: [...columns],\n unique: false,\n raw: { hash: raw },\n };\n}\n","/**\n * Hostile parser and hash owner for Migration V1 schema snapshots.\n *\n * Snapshot bytes are admitted only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { rawIndexFields, rawIndexHash } from \"./raw-index\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport {\n exactObject,\n parseIdentifierArray,\n parseItems,\n parseMember,\n parseRequiredString,\n parseStringArray,\n refuse,\n} from \"./v1-parse-shared\";\n\nconst SNAPSHOT_KEYS = [\"enums\", \"polymorphicStorage\", \"tables\"] as const;\nconst TABLE_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"junction\",\n \"name\",\n \"primaryKey\",\n \"relationStorage\",\n \"uniqueConstraints\",\n] as const;\nconst TABLE_REQUIRED_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"name\",\n \"uniqueConstraints\",\n] as const;\nconst COLUMN_KEYS = [\n \"autoIncrement\",\n \"dateTime\",\n \"geoPointEncoding\",\n \"decimal\",\n \"default\",\n \"name\",\n \"nullable\",\n \"type\",\n] as const;\nconst DECIMAL_KEYS = [\"precision\", \"scale\"] as const;\nconst PRIMARY_KEY_KEYS = [\"columns\", \"name\", \"withoutRowid\"] as const;\nconst INDEX_KEYS = [\n \"columns\",\n \"name\",\n \"raw\",\n \"type\",\n \"unique\",\n \"where\",\n] as const;\nconst RAW_INDEX_KEYS = [\"hash\", \"template\"] as const;\nconst FOREIGN_KEY_KEYS = [\n \"columns\",\n \"name\",\n \"onDelete\",\n \"onUpdate\",\n \"referencedColumns\",\n \"referencedTable\",\n] as const;\nconst UNIQUE_CONSTRAINT_KEYS = [\"columns\", \"name\"] as const;\nconst ENUM_KEYS = [\"name\", \"values\"] as const;\nconst RELATION_STORAGE_KEYS = [\n \"idColumn\",\n \"index\",\n \"kind\",\n \"typeColumn\",\n] as const;\nconst POLYMORPHIC_TO_ONE_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n \"storageRef\",\n] as const;\nconst POLYMORPHIC_TO_MANY_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n] as const;\nconst POLYMORPHIC_TO_ONE_MEMBER_KEYS = [\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\nconst POLYMORPHIC_TO_MANY_MEMBER_KEYS = [\n \"inverseCardinality\",\n \"memberJunctionTable\",\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\n\nfunction parseColumn(value: unknown, label: string): ColumnDef {\n const record = exactObject(\n value,\n COLUMN_KEYS,\n [\"name\", \"nullable\", \"type\"],\n label\n );\n if (!isBoolean(record.nullable)) refuse(`${label}.nullable must be boolean`);\n const column: ColumnDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n type: parseRequiredString(record.type, `${label}.type`),\n nullable: record.nullable,\n };\n if (\"default\" in record) {\n if (!isString(record.default)) refuse(`${label}.default must be a string`);\n column.default = record.default;\n }\n if (\"autoIncrement\" in record) {\n if (!isBoolean(record.autoIncrement)) {\n refuse(`${label}.autoIncrement must be boolean`);\n }\n column.autoIncrement = record.autoIncrement;\n }\n if (\"decimal\" in record) {\n column.decimal = parseDecimalDescriptor(record.decimal, `${label}.decimal`);\n }\n if (\"geoPointEncoding\" in record) {\n if (\n (record.geoPointEncoding !== \"legacy\" &&\n record.geoPointEncoding !== \"binary64\") ||\n column.type.toUpperCase() !== \"VIBORM_GEO_TEXT\" ||\n column.decimal !== undefined ||\n \"dateTime\" in record\n )\n refuse(`${label}.geoPointEncoding contradicts its physical type`);\n column.geoPointEncoding = record.geoPointEncoding;\n }\n if (\"dateTime\" in record) {\n if (\n !isString(record.dateTime) ||\n (record.dateTime !== \"text\" &&\n record.dateTime !== \"epochMillis\" &&\n record.dateTime !== \"julianDay\")\n ) {\n refuse(`${label}.dateTime must name a DateTime physical form`);\n }\n const physicalType =\n record.dateTime === \"text\"\n ? \"TEXT\"\n : record.dateTime === \"epochMillis\"\n ? \"INTEGER\"\n : \"REAL\";\n if (column.type.toUpperCase() !== physicalType) {\n refuse(`${label}.dateTime contradicts its physical type`);\n }\n if (column.decimal !== undefined) {\n refuse(`${label} cannot be both DateTime and fixed-decimal storage`);\n }\n column.dateTime = record.dateTime;\n }\n return column;\n}\n\nfunction parseDecimalDescriptor(\n value: unknown,\n label: string\n): DecimalDescriptor {\n const record = exactObject(value, DECIMAL_KEYS, DECIMAL_KEYS, label);\n if (\n !(isNumber(record.precision) && Number.isSafeInteger(record.precision)) ||\n record.precision < 1\n ) {\n refuse(`${label}.precision must be a positive safe integer`);\n }\n if (\n !(isNumber(record.scale) && Number.isSafeInteger(record.scale)) ||\n Object.is(record.scale, -0) ||\n record.scale < 0 ||\n record.scale > record.precision\n ) {\n refuse(`${label}.scale must be a safe integer between 0 and precision`);\n }\n return { precision: record.precision, scale: record.scale };\n}\n\nfunction parsePrimaryKey(value: unknown, label: string): PrimaryKeyDef {\n const record = exactObject(value, PRIMARY_KEY_KEYS, [\"columns\"], label);\n const primaryKey: PrimaryKeyDef = {\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n if (\"name\" in record) {\n primaryKey.name = parseRequiredString(record.name, `${label}.name`);\n }\n if (\"withoutRowid\" in record) {\n if (record.withoutRowid !== true)\n refuse(`${label}.withoutRowid must be true when present`);\n primaryKey.withoutRowid = true;\n }\n return primaryKey;\n}\n\nfunction parseIndex(value: unknown, label: string): IndexDef {\n const record = exactObject(\n value,\n INDEX_KEYS,\n [\"columns\", \"name\", \"unique\"],\n label\n );\n if (!isBoolean(record.unique)) refuse(`${label}.unique must be boolean`);\n const index: IndexDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n unique: record.unique,\n };\n if (\"type\" in record) {\n if (\n record.type !== \"btree\" &&\n record.type !== \"hash\" &&\n record.type !== \"gin\" &&\n record.type !== \"gist\" &&\n record.type !== \"fulltext\" &&\n record.type !== \"spatial\"\n ) {\n refuse(`${label}.type is invalid`);\n }\n index.type = record.type;\n }\n if (\"where\" in record) {\n if (!isString(record.where)) refuse(`${label}.where must be a string`);\n index.where = record.where;\n }\n if (\"raw\" in record) {\n const raw = exactObject(\n record.raw,\n RAW_INDEX_KEYS,\n RAW_INDEX_KEYS,\n `${label}.raw`\n );\n if (!isString(raw.template))\n refuse(`${label}.raw.template must be a string`);\n if (raw.hash !== rawIndexHash(raw.template))\n refuse(`${label}.raw.hash does not match its template`);\n if (index.unique || index.type !== undefined || index.where !== undefined)\n refuse(`${label} is raw and cannot also be unique, typed or partial`);\n if (rawIndexFields(raw.template).length !== index.columns.length)\n refuse(`${label}.columns are not the fields its template names`);\n index.raw = { hash: raw.hash, template: raw.template };\n }\n return index;\n}\n\nconst REFERENTIAL_ACTIONS: readonly ReferentialAction[] = [\n \"cascade\",\n \"setNull\",\n \"restrict\",\n \"noAction\",\n \"setDefault\",\n];\n\nfunction parseForeignKey(value: unknown, label: string): ForeignKeyDef {\n const record = exactObject(\n value,\n FOREIGN_KEY_KEYS,\n [\"columns\", \"name\", \"referencedColumns\", \"referencedTable\"],\n label\n );\n const foreignKey: ForeignKeyDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n referencedTable: parseRequiredString(\n record.referencedTable,\n `${label}.referencedTable`\n ),\n referencedColumns: parseIdentifierArray(\n record.referencedColumns,\n `${label}.referencedColumns`\n ),\n };\n if (\"onDelete\" in record) {\n foreignKey.onDelete = parseMember(\n record.onDelete,\n REFERENTIAL_ACTIONS,\n `${label}.onDelete is not a referential action`\n );\n }\n if (\"onUpdate\" in record) {\n foreignKey.onUpdate = parseMember(\n record.onUpdate,\n REFERENTIAL_ACTIONS,\n `${label}.onUpdate is not a referential action`\n );\n }\n return foreignKey;\n}\n\nfunction parseUniqueConstraint(\n value: unknown,\n label: string\n): UniqueConstraintDef {\n const record = exactObject(\n value,\n UNIQUE_CONSTRAINT_KEYS,\n UNIQUE_CONSTRAINT_KEYS,\n label\n );\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n}\n\nfunction parseRelationStorage(\n value: unknown,\n label: string\n): Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const entries: Record<string, PolymorphicToOneStorageRegistryEntry> = {};\n for (const [storageRef, rawEntry] of Object.entries(value)) {\n const entryLabel = `${label}.${storageRef}`;\n const record = exactObject(\n rawEntry,\n RELATION_STORAGE_KEYS,\n RELATION_STORAGE_KEYS,\n entryLabel\n );\n if (record.kind !== \"polymorphicToOne\") {\n refuse(`${entryLabel}.kind must be polymorphicToOne`);\n }\n Object.defineProperty(entries, storageRef, {\n configurable: true,\n enumerable: true,\n value: {\n kind: \"polymorphicToOne\",\n typeColumn: parseRequiredString(\n record.typeColumn,\n `${entryLabel}.typeColumn`\n ),\n idColumn: parseRequiredString(\n record.idColumn,\n `${entryLabel}.idColumn`\n ),\n index: parseRequiredString(record.index, `${entryLabel}.index`),\n },\n writable: true,\n });\n }\n return entries;\n}\n\nfunction parseTable(value: unknown, label: string): TableDef {\n const record = exactObject(value, TABLE_KEYS, TABLE_REQUIRED_KEYS, label);\n if (!Array.isArray(record.columns))\n refuse(`${label}.columns must be an array`);\n if (!Array.isArray(record.indexes))\n refuse(`${label}.indexes must be an array`);\n if (!Array.isArray(record.foreignKeys)) {\n refuse(`${label}.foreignKeys must be an array`);\n }\n if (!Array.isArray(record.uniqueConstraints)) {\n refuse(`${label}.uniqueConstraints must be an array`);\n }\n const table: TableDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseItems(record.columns, `${label}.columns`, parseColumn),\n indexes: parseItems(record.indexes, `${label}.indexes`, parseIndex),\n foreignKeys: parseItems(\n record.foreignKeys,\n `${label}.foreignKeys`,\n parseForeignKey\n ),\n uniqueConstraints: parseItems(\n record.uniqueConstraints,\n `${label}.uniqueConstraints`,\n parseUniqueConstraint\n ),\n };\n if (\"primaryKey\" in record) {\n table.primaryKey = parsePrimaryKey(\n record.primaryKey,\n `${label}.primaryKey`\n );\n }\n if (\"relationStorage\" in record) {\n table.relationStorage = parseRelationStorage(\n record.relationStorage,\n `${label}.relationStorage`\n );\n }\n if (record.junction === true) table.junction = true;\n return table;\n}\n\nfunction parseEnum(value: unknown, label: string): EnumDef {\n const record = exactObject(value, ENUM_KEYS, ENUM_KEYS, label);\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n values: parseStringArray(record.values, `${label}.values`),\n };\n}\n\nfunction parseToOneMember(\n value: unknown,\n label: string\n): PolymorphicToOneSnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n label\n );\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n };\n}\n\nfunction parseToManyMember(\n value: unknown,\n label: string\n): PolymorphicToManySnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n label\n );\n if (\n record.inverseCardinality !== \"one\" &&\n record.inverseCardinality !== \"many\"\n ) {\n refuse(`${label}.inverseCardinality must be one or many`);\n }\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n memberJunctionTable: parseRequiredString(\n record.memberJunctionTable,\n `${label}.memberJunctionTable`\n ),\n inverseCardinality: record.inverseCardinality,\n };\n}\n\nfunction parsePolymorphicStorage(\n value: unknown,\n label: string\n): PolymorphicSnapshotStorage {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n if (value.kind === \"toOne\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_KEYS,\n POLYMORPHIC_TO_ONE_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toOne\",\n storageRef: parseRequiredString(record.storageRef, `${label}.storageRef`),\n members: parseItems(record.members, `${label}.members`, parseToOneMember),\n };\n }\n if (value.kind === \"toMany\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_KEYS,\n POLYMORPHIC_TO_MANY_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toMany\",\n members: parseItems(\n record.members,\n `${label}.members`,\n parseToManyMember\n ),\n };\n }\n refuse(`${label}.kind must be toOne or toMany`);\n}\n\nexport function parseSnapshotDocument(\n bytes: Uint8Array,\n expectedHash: Sha256\n): SchemaSnapshot {\n const parsed = parseJsonBytes(bytes, `snapshots/${expectedHash}.json`);\n const record = exactObject(parsed, SNAPSHOT_KEYS, [\"tables\"], \"snapshot\");\n if (!Array.isArray(record.tables)) refuse(\"snapshot.tables must be an array\");\n const snapshot: SchemaSnapshot = {\n tables: parseItems(record.tables, \"snapshot.tables\", parseTable),\n };\n if (\"enums\" in record) {\n if (!Array.isArray(record.enums)) refuse(\"snapshot.enums must be an array\");\n snapshot.enums = parseItems(record.enums, \"snapshot.enums\", parseEnum);\n }\n if (\"polymorphicStorage\" in record) {\n if (!Array.isArray(record.polymorphicStorage)) {\n refuse(\"snapshot.polymorphicStorage must be an array\");\n }\n snapshot.polymorphicStorage = record.polymorphicStorage.map(\n (storage, index) =>\n parsePolymorphicStorage(\n storage,\n `snapshot.polymorphicStorage[${index}]`\n )\n );\n }\n assertCanonicalBytes(bytes, snapshot, `snapshots/${expectedHash}.json`);\n const actual = domainHash(HASH_DOMAIN.snapshot, bytes);\n if (actual !== expectedHash) {\n throw new MigrationError(\n \"snapshot filename does not match its canonical bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\nexport function encodeSnapshot(snapshot: SchemaSnapshot): {\n bytes: Uint8Array;\n snapshotHash: Sha256;\n} {\n const bytes = canonicalizeJson(omitUndefinedKeys(snapshot));\n return { bytes, snapshotHash: domainHash(HASH_DOMAIN.snapshot, bytes) };\n}\n\nfunction omitUndefinedKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => omitUndefinedKeys(item));\n }\n if (!isRecord(value)) return value;\n const admitted: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const item = value[key];\n if (item === undefined) continue;\n admitted[key] = omitUndefinedKeys(item);\n }\n return admitted;\n}\n","import { normalizeManagedTables } from \"./target\";\n/**\n * Hostile parsers and hash owners for Migration V1 estate, dispatch,\n * state, and transition artifacts.\n *\n * Snapshot and control admission live in sibling modules. This file\n * re-exports them so existing `./v1-parse` imports keep working.\n * Every JSON boundary admits a value only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n * No `JSON.parse(...) as SchemaSnapshot` remains.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport {\n domainHash,\n HASH_ALGORITHM,\n HASH_DOMAIN,\n parseSha256,\n type Sha256,\n} from \"./identity\";\nimport type { MigrationTarget } from \"./types\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n exactObject,\n parseFormat,\n parseItems,\n refuse,\n} from \"./v1-parse-shared\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStateManifestV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport {\n encodePathHash,\n eventIdFor,\n parseLedgerEvent,\n parseMarkerRow,\n} from \"./v1-parse-control\";\nexport { encodeDispatchIdentity, parseDispatch } from \"./v1-parse-dispatch\";\nexport {\n encodeSnapshot,\n parseSnapshotDocument,\n} from \"./v1-parse-snapshot\";\n\nconst ESTATE_KEYS = [\"format\", \"hash\", \"target\"] as const;\nconst PG_TARGET_KEYS = [\"dialect\", \"namespace\", \"tables\"] as const;\nconst DIALECT_ONLY_TARGET_KEYS = [\"dialect\", \"tables\"] as const;\nconst CHECK_KEYS = [\"equals\", \"id\", \"kind\", \"query\"] as const;\nconst PROVEN_STEP_KEYS = [\"execute\", \"postcheck\", \"precheck\", \"retry\"] as const;\nconst OPAQUE_STEP_KEYS = [\"execute\", \"retry\"] as const;\nconst OPERATION_KEYS = [\"id\", \"label\", \"origin\", \"risk\", \"steps\"] as const;\nconst SCHEMA_ROLLBACK_KEYS = [\"kind\", \"operations\"] as const;\nconst MANUAL_ROLLBACK_KEYS = [\n \"kind\",\n \"operations\",\n \"requestedBoundary\",\n] as const;\nconst IRREVERSIBLE_KEYS = [\"kind\", \"reason\"] as const;\nconst PARENT_KEYS = [\n \"adopts\",\n \"approvals\",\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n \"transitionHash\",\n] as const;\nconst STATE_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n \"stateId\",\n] as const;\nconst STATE_HASH_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n] as const;\nconst PARENT_REQUIRED_KEYS = PARENT_KEYS.filter(\n (key) => key !== \"adopts\" && key !== \"approvals\"\n);\nconst STATE_ALLOWED_KEYS = [...STATE_KEYS, \"snapshotArtifactHash\"];\nconst TRANSITION_HASH_KEYS = [\n \"adopts\",\n \"approvals\",\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n] as const;\nconst APPROVAL_KEYS = [\"column\", \"operation\", \"table\"] as const;\nconst APPROVAL_OPERATIONS: readonly MigrationApprovalV1[\"operation\"][] = [\n \"addColumn\",\n \"alterColumn\",\n \"dropColumn\",\n \"dropTable\",\n];\n\nfunction parseManagedTables(value: unknown, label: string): readonly string[] {\n try {\n const tables = normalizeManagedTables(value);\n if (tables !== undefined) return tables;\n } catch {\n refuse(\n `${label}.tables must be a sorted, unique array of physical table names`\n );\n }\n return refuse(`${label}.tables must be an array`);\n}\n\nexport function parseMigrationTarget(\n value: unknown,\n label: string\n): MigrationTarget {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const dialect = value.dialect;\n if (dialect === \"postgresql\") {\n const record = exactObject(\n value,\n PG_TARGET_KEYS,\n [\"dialect\", \"namespace\"],\n label\n );\n if (!isString(record.namespace) || record.namespace.length === 0) {\n refuse(`${label}.namespace must be a non-empty string`);\n }\n return {\n dialect: \"postgresql\",\n namespace: record.namespace,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n if (dialect === \"mysql\" || dialect === \"sqlite\" || dialect === \"surrealql\") {\n exactObject(value, DIALECT_ONLY_TARGET_KEYS, [\"dialect\"], label);\n return {\n dialect,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n refuse(`${label}.dialect is not a V1 migration target`);\n}\n\nexport function parseEstateDescriptor(bytes: Uint8Array): {\n descriptor: MigrationEstateDescriptorV1;\n estateHash: Sha256;\n} {\n const parsed = parseJsonBytes(bytes, \"estate.json\");\n const record = exactObject(parsed, ESTATE_KEYS, ESTATE_KEYS, \"estate.json\");\n if (record.hash !== HASH_ALGORITHM) {\n refuse('estate.json hash algorithm must be \"sha256\"');\n }\n const descriptor: MigrationEstateDescriptorV1 = {\n format: parseFormat(record.format, \"estate.json\"),\n target: parseMigrationTarget(record.target, \"estate.json.target\"),\n hash: \"sha256\",\n };\n assertCanonicalBytes(bytes, descriptor, \"estate.json\");\n return { descriptor, estateHash: domainHash(HASH_DOMAIN.estate, bytes) };\n}\n\nexport function encodeEstateDescriptor(target: MigrationTarget): {\n bytes: Uint8Array;\n estateHash: Sha256;\n descriptor: MigrationEstateDescriptorV1;\n} {\n const descriptor: MigrationEstateDescriptorV1 = {\n format: \"1\",\n target,\n hash: \"sha256\",\n };\n const bytes = canonicalizeJson(descriptor);\n return {\n bytes,\n estateHash: domainHash(HASH_DOMAIN.estate, bytes),\n descriptor,\n };\n}\n\nfunction parseCheck(value: unknown, label: string): MigrationBooleanCheckV1 {\n const record = exactObject(value, CHECK_KEYS, CHECK_KEYS, label);\n if (record.kind !== \"driver\" && record.kind !== \"trusted-read\") {\n refuse(`${label}.kind must be driver or trusted-read`);\n }\n if (!isString(record.id) || record.id.length === 0) {\n refuse(`${label}.id must be a non-empty string`);\n }\n if (!isBoolean(record.equals)) refuse(`${label}.equals must be boolean`);\n return {\n kind: record.kind,\n id: record.id,\n query: parseDispatch(record.query, `${label}.query`),\n equals: record.equals,\n };\n}\n\nfunction parseStep(value: unknown, label: string): MigrationStepV1 {\n if (\n !isRecord(value) ||\n (value.retry !== \"proven\" && value.retry !== \"opaque\")\n ) {\n refuse(`${label}.retry must be proven or opaque`);\n }\n if (value.retry === \"proven\") {\n const record = exactObject(\n value,\n PROVEN_STEP_KEYS,\n PROVEN_STEP_KEYS,\n label\n );\n return {\n retry: \"proven\",\n precheck: parseCheck(record.precheck, `${label}.precheck`),\n execute: parseDispatch(record.execute, `${label}.execute`),\n postcheck: parseCheck(record.postcheck, `${label}.postcheck`),\n };\n }\n const record = exactObject(value, OPAQUE_STEP_KEYS, OPAQUE_STEP_KEYS, label);\n return {\n retry: \"opaque\",\n execute: parseDispatch(record.execute, `${label}.execute`),\n };\n}\n\nfunction parseOperation(value: unknown, label: string): MigrationOperationV1 {\n const record = exactObject(value, OPERATION_KEYS, OPERATION_KEYS, label);\n if (!isString(record.id) || record.id.length === 0)\n refuse(`${label}.id is required`);\n if (!isString(record.label) || record.label.length === 0) {\n refuse(`${label}.label is required`);\n }\n if (record.origin !== \"generated\" && record.origin !== \"manual\") {\n refuse(`${label}.origin must be generated or manual`);\n }\n if (\n record.risk !== \"safe\" &&\n record.risk !== \"destructive\" &&\n record.risk !== \"opaque\"\n ) {\n refuse(`${label}.risk is not a V1 risk class`);\n }\n if (!Array.isArray(record.steps) || record.steps.length === 0) {\n refuse(`${label}.steps must be a non-empty array`);\n }\n return {\n id: record.id,\n label: record.label,\n origin: record.origin,\n risk: record.risk,\n steps: parseItems(record.steps, `${label}.steps`, parseStep),\n };\n}\n\nfunction parseRollback(value: unknown, label: string): MigrationRollbackV1 {\n if (!(isRecord(value) && isString(value.kind)))\n refuse(`${label} must be a tagged rollback`);\n if (value.kind === \"schema\") {\n const record = exactObject(\n value,\n SCHEMA_ROLLBACK_KEYS,\n SCHEMA_ROLLBACK_KEYS,\n label\n );\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"schema\",\n operations: parseItems(\n record.operations,\n `${label}.operations`,\n parseOperation\n ),\n };\n }\n if (value.kind === \"manual\") {\n const record = exactObject(\n value,\n MANUAL_ROLLBACK_KEYS,\n MANUAL_ROLLBACK_KEYS,\n label\n );\n if (\n record.requestedBoundary !== \"transactional\" &&\n record.requestedBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedBoundary must be transactional or stepwise`);\n }\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"manual\",\n requestedBoundary: record.requestedBoundary,\n operations: parseItems(\n record.operations,\n `${label}.operations`,\n parseOperation\n ),\n };\n }\n if (value.kind === \"irreversible\") {\n const record = exactObject(\n value,\n IRREVERSIBLE_KEYS,\n IRREVERSIBLE_KEYS,\n label\n );\n if (!isString(record.reason) || record.reason.trim().length === 0) {\n refuse(`${label}.reason must be a non-empty string`);\n }\n return { kind: \"irreversible\", reason: record.reason };\n }\n refuse(`${label}.kind is not a V1 rollback`);\n}\n\n/**\n * Absent, never empty: one encoding for \"adopts nothing\". Strictly ascending\n * physical names, so one adoption has one encoding.\n */\nfunction parseAdopts(value: unknown, label: string): readonly string[] {\n if (!Array.isArray(value) || value.length === 0) {\n refuse(`${label} must be a non-empty array`);\n }\n return value.map((name: unknown, index) => {\n if (!isString(name) || name.length === 0 || name.includes(\"\\0\")) {\n refuse(`${label}[${index}] must be a non-empty physical table name`);\n }\n const previous: unknown = value[index - 1];\n if (index > 0 && !(isString(previous) && previous < name)) {\n refuse(`${label} must be sorted and free of repeats`);\n }\n return name;\n });\n}\n\n/** Absent, never empty: one encoding for \"no destructive change\". */\nfunction parseApprovals(\n value: unknown,\n label: string\n): readonly MigrationApprovalV1[] {\n if (!Array.isArray(value) || value.length === 0) {\n refuse(`${label} must be a non-empty array`);\n }\n return value.map((entry, index) => {\n const at = `${label}[${index}]`;\n return parseApproval(\n exactObject(entry, APPROVAL_KEYS, APPROVAL_KEYS, at),\n at\n );\n });\n}\n\n/**\n * One approval's fields, wherever an approval is spelled: a stored\n * transition's, or a predefined resolver's `destructive` decision, which\n * refuses as its own input (`refuseWith`).\n */\nexport function parseApproval(\n fields: Readonly<Record<string, unknown>>,\n at: string,\n refuseWith: (message: string) => never = refuse\n): MigrationApprovalV1 {\n const { column, operation, table } = fields;\n const known = APPROVAL_OPERATIONS.find((name) => name === operation);\n if (!known) refuseWith(`${at}.operation is not a destructive operation`);\n if (!isString(table) || table.length === 0) {\n refuseWith(`${at}.table must be a non-empty string`);\n }\n if (column !== null && !(isString(column) && column.length > 0)) {\n refuseWith(`${at}.column must be a non-empty string or null`);\n }\n return { operation: known, table, column };\n}\n\nexport function encodeTransitionHash(\n transition: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of TRANSITION_HASH_KEYS) {\n if (transition[key] !== undefined) body[key] = transition[key];\n }\n return domainHash(HASH_DOMAIN.transition, canonicalizeJson(body));\n}\n\nfunction parseParent(\n value: unknown,\n label: string\n): MigrationParentTransitionV1 {\n const record = exactObject(value, PARENT_KEYS, PARENT_REQUIRED_KEYS, label);\n const fromState =\n record.fromState === null\n ? null\n : parseSha256(record.fromState, `${label}.fromState`);\n if (\n record.requestedForwardBoundary !== null &&\n record.requestedForwardBoundary !== \"transactional\" &&\n record.requestedForwardBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedForwardBoundary is invalid`);\n }\n if (!Array.isArray(record.originChecks))\n refuse(`${label}.originChecks must be an array`);\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n const operations = parseItems(\n record.operations,\n `${label}.operations`,\n parseOperation\n );\n const rollback = parseRollback(record.rollback, `${label}.rollback`);\n const origins = new Set(operations.map((operation) => operation.origin));\n if (origins.size > 1) {\n refuse(`${label} mixes generated and manual operations`);\n }\n if (record.requestedForwardBoundary !== null && origins.has(\"generated\")) {\n refuse(\n `${label}.requestedForwardBoundary is only valid on a manual transition`\n );\n }\n if (rollback.kind === \"manual\" && origins.has(\"generated\")) {\n refuse(`${label}.rollback cannot be manual on a generated transition`);\n }\n const parsed: Omit<MigrationParentTransitionV1, \"transitionHash\"> = {\n fromState,\n originChecks: parseItems(\n record.originChecks,\n `${label}.originChecks`,\n parseCheck\n ),\n requestedForwardBoundary: record.requestedForwardBoundary,\n operations,\n rollback,\n ...(record.approvals === undefined\n ? {}\n : { approvals: parseApprovals(record.approvals, `${label}.approvals`) }),\n ...(record.adopts === undefined\n ? {}\n : { adopts: parseAdopts(record.adopts, `${label}.adopts`) }),\n };\n const transitionHash = parseSha256(\n record.transitionHash,\n `${label}.transitionHash`\n );\n const expected = encodeTransitionHash(parsed);\n if (transitionHash !== expected) {\n throw new MigrationError(\n `${label}.transitionHash does not match its transition`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...parsed, transitionHash };\n}\n\nexport function compareFromState(\n left: Sha256 | null,\n right: Sha256 | null\n): number {\n if (left === right) return 0;\n if (left === null) return -1;\n if (right === null) return 1;\n return left < right ? -1 : 1;\n}\n\nexport function sortParents(\n parents: readonly MigrationParentTransitionV1[]\n): MigrationParentTransitionV1[] {\n return [...parents].sort((left, right) =>\n compareFromState(left.fromState, right.fromState)\n );\n}\n\nexport function encodeStateId(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of STATE_HASH_KEYS) {\n body[key] = manifest[key];\n }\n if (manifest.snapshotArtifactHash !== undefined) {\n body.snapshotArtifactHash = manifest.snapshotArtifactHash;\n }\n return domainHash(HASH_DOMAIN.state, canonicalizeJson(body));\n}\n\nexport function parseStateManifest(\n bytes: Uint8Array,\n expectedId: Sha256\n): MigrationStateManifestV1 {\n const parsed = parseJsonBytes(bytes, `states/${expectedId}.json`);\n const record = exactObject(\n parsed,\n STATE_ALLOWED_KEYS,\n STATE_KEYS,\n \"state manifest\"\n );\n if (!Array.isArray(record.parents) || record.parents.length === 0) {\n refuse(\"state manifest must have at least one parent transition\");\n }\n if (!Array.isArray(record.destinationChecks)) {\n refuse(\"state manifest.destinationChecks must be an array\");\n }\n if (!isString(record.name) || record.name.length === 0) {\n refuse(\"state manifest.name must be a non-empty string\");\n }\n const parents = parseItems(record.parents, \"state.parents\", parseParent);\n // Strictly ascending, so no fromState appears twice.\n for (let i = 1; i < parents.length; i++) {\n if (\n compareFromState(parents[i - 1]!.fromState, parents[i]!.fromState) >= 0\n ) {\n refuse(\n \"state manifest parents must be sorted by fromState with null first\"\n );\n }\n }\n const withoutId: Omit<MigrationStateManifestV1, \"stateId\"> = {\n format: parseFormat(record.format, \"state manifest\"),\n estateHash: parseSha256(record.estateHash, \"state.estateHash\"),\n name: record.name,\n snapshotHash: parseSha256(record.snapshotHash, \"state.snapshotHash\"),\n ...(\"snapshotArtifactHash\" in record\n ? {\n snapshotArtifactHash: parseSha256(\n record.snapshotArtifactHash,\n \"state.snapshotArtifactHash\"\n ),\n }\n : {}),\n sqlHash: parseSha256(record.sqlHash, \"state.sqlHash\"),\n destinationChecks: parseItems(\n record.destinationChecks,\n \"state.destinationChecks\",\n parseCheck\n ),\n parents,\n };\n assertCanonicalBytes(\n bytes,\n { ...withoutId, stateId: expectedId },\n `states/${expectedId}.json`\n );\n const stateId = parseSha256(record.stateId, \"state.stateId\");\n const expected = encodeStateId(withoutId);\n if (stateId !== expected || stateId !== expectedId) {\n throw new MigrationError(\n \"stateId does not match the canonical manifest or filename\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...withoutId, stateId };\n}\n\nexport function encodeStateManifest(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): { bytes: Uint8Array; stateId: Sha256; manifest: MigrationStateManifestV1 } {\n const parents = sortParents(manifest.parents);\n const sorted = { ...manifest, parents };\n const stateId = encodeStateId(sorted);\n const complete = { ...sorted, stateId };\n return { bytes: canonicalizeJson(complete), stateId, manifest: complete };\n}\n\nexport function encodeSqlBlob(bytes: Uint8Array): Sha256 {\n return domainHash(HASH_DOMAIN.sql, bytes);\n}\n","/**\n * Resolver System\n *\n * Handles ambiguous changes that require user input to resolve.\n * Provides utilities for converting user resolutions into concrete operations.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport {\n type DiffOptions,\n diff,\n getDestructiveOperationDescriptions,\n isDestructiveOperation,\n} from \"./differ\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { applyNativeRename } from \"./native-rename\";\nimport type {\n AmbiguousChange,\n AmbiguousResolveChange,\n ChangeResolution,\n DestructiveResolveChange,\n DiffOperation,\n DiffResult,\n EnumValueRemovalChange,\n ResolveCallback,\n ResolveChange,\n ResolveResult,\n Resolver,\n SchemaSnapshot,\n} from \"./types\";\nimport {\n createAmbiguousChange,\n createDestructiveChange,\n readEnumResolutionDecision,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\nimport { parseApproval } from \"./v1-parse\";\nimport type { MigrationApprovalV1, MigrationDecisionV1 } from \"./v1-types\";\n\nexport function validateResolveResult(\n expected: \"ambiguous\",\n change: AmbiguousResolveChange,\n result: unknown\n): \"rename\" | \"addAndDrop\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"destructive\",\n change: DestructiveResolveChange,\n result: unknown\n): \"proceed\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"enumValueRemoval\",\n change: EnumValueRemovalChange,\n result: unknown\n): \"enumMapped\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: ResolveChange[\"type\"],\n change: ResolveChange,\n result: unknown\n): ResolveResult | undefined {\n if (result === undefined) return undefined;\n\n if (result === \"reject\") return result;\n if (\n expected === \"ambiguous\" &&\n (result === \"rename\" || result === \"addAndDrop\")\n ) {\n return result;\n }\n if (expected === \"destructive\" && result === \"proceed\") {\n return result;\n }\n if (expected === \"enumValueRemoval\" && result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision !== undefined && decision.kind !== \"mixed\") return result;\n }\n\n const received =\n typeof result === \"string\"\n ? `\"${result}\"`\n : result === null\n ? \"null\"\n : typeof result;\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result ${received} for a ${expected} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n type: \"invalid-resolution-result\",\n },\n }\n );\n}\n\n// =============================================================================\n// RESOLUTION APPLICATION\n// =============================================================================\n\n/** The operations one resolved ambiguous change stands for. */\nexport function operationsFor(\n change: AmbiguousChange,\n resolution: ChangeResolution\n): DiffOperation[] {\n if (change.type === \"ambiguousColumn\") {\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n },\n ]\n : [\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n },\n ];\n }\n return resolution.type === \"rename\"\n ? [\n {\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n },\n ]\n : [\n { type: \"dropTable\", tableName: change.droppedTable },\n { type: \"createTable\", table: change.addedTableDef },\n ];\n}\n\n/**\n * Resolves every ambiguity exposed by accepted changes.\n *\n * Each decision is applied to a working source snapshot, then the ordinary\n * differ runs again with the original options. Native renames therefore expose\n * nested ambiguities and descriptor alterations through the same owner that\n * found the outer change; no local table differ or pre-rename operation list is\n * retained.\n */\nexport async function resolveAmbiguousChanges(\n initialDiffResult: DiffResult,\n currentSnapshot: SchemaSnapshot,\n desiredSnapshot: SchemaSnapshot,\n resolver: Resolver,\n options: DiffOptions = {}\n): Promise<DiffOperation[]> {\n let workingSnapshot = currentSnapshot;\n let diffResult = initialDiffResult;\n const resolutionOperations: DiffOperation[] = [];\n const resolvedAmbiguities = new Set<string>();\n const liveTableNames = new Map(\n currentSnapshot.tables.map((table) => [table.name, table.name])\n );\n\n while (diffResult.ambiguousChanges.length > 0) {\n const resolutions = await resolver(diffResult.ambiguousChanges);\n\n for (const change of diffResult.ambiguousChanges) {\n const key = ambiguityKey(change);\n if (resolvedAmbiguities.has(key)) {\n throw new MigrationError(\n `Ambiguous migration change did not converge after resolution: ${key}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n resolvedAmbiguities.add(key);\n\n const resolution = resolutions.get(change);\n if (!resolution)\n throw new MigrationError(\n `Missing resolution for ${formatAmbiguousChange(change)}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n const operations = operationsFor(change, resolution);\n resolutionOperations.push(...operations);\n\n for (const operation of operations) {\n workingSnapshot = applyResolutionEffect(\n workingSnapshot,\n operation,\n options.projectRename\n );\n if (operation.type === \"renameTable\") {\n const liveName = liveTableNames.get(operation.from) ?? operation.from;\n liveTableNames.delete(operation.from);\n liveTableNames.set(operation.to, liveName);\n } else if (operation.type === \"dropTable\") {\n liveTableNames.delete(operation.tableName);\n }\n }\n }\n\n diffResult = await diff(\n workingSnapshot,\n desiredSnapshot,\n optionsForWorkingSnapshot(options, liveTableNames)\n );\n }\n\n return sortOperations([...resolutionOperations, ...diffResult.operations]);\n}\n\nfunction ambiguityKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table:${change.droppedTable}\\u0000${change.addedTable}`\n : `column:${change.tableName}\\u0000${change.droppedColumn.name}\\u0000${change.addedColumn.name}`;\n}\n\nfunction optionsForWorkingSnapshot(\n options: DiffOptions,\n liveTableNames: ReadonlyMap<string, string>\n): DiffOptions {\n const canonicalize = options.canonicalizeIndexPredicate;\n if (!canonicalize) return options;\n return {\n ...options,\n canonicalizeIndexPredicate: (tableName, predicates) =>\n canonicalize(liveTableNames.get(tableName) ?? tableName, predicates),\n };\n}\n\nfunction applyResolutionEffect(\n snapshot: SchemaSnapshot,\n operation: DiffOperation,\n projectRename: typeof applyNativeRename = applyNativeRename\n): SchemaSnapshot {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n return projectRename(snapshot, operation);\n }\n if (operation.type === \"dropTable\") {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n }\n if (operation.type === \"createTable\") {\n return { ...snapshot, tables: [...snapshot.tables, operation.table] };\n }\n if (operation.type === \"dropColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== operation.columnName\n ),\n }\n : table\n ),\n };\n }\n if (operation.type === \"addColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? { ...table, columns: [...table.columns, operation.column] }\n : table\n ),\n };\n }\n return snapshot;\n}\n\nexport function ambiguousToResolveChange(\n change: AmbiguousChange\n): AmbiguousResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n\n/**\n * `admittedDrops` collects the drop each `addAndDrop` answer already decided,\n * so the destructive question is not asked a second time for it.\n */\nexport function callbackAsResolver(\n callback: ResolveCallback,\n admittedDrops?: Set<string>\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = await callback(resolveChange);\n if (result === \"rename\") {\n resolutions.set(change, { type: \"rename\" });\n continue;\n }\n if (result === \"addAndDrop\") {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedDrops?.add(ambiguousDropKey(change));\n continue;\n }\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n` +\n \"Generate requires change.rename() or change.addAndDrop() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return resolutions;\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE CHANGES\n// =============================================================================\n\nexport function ambiguousDropKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table\\u0000${change.droppedTable}`\n : `column\\u0000${change.tableName}\\u0000${change.droppedColumn.name}`;\n}\n\nfunction destructiveDropKey(operation: DiffOperation): string {\n if (operation.type === \"dropTable\") {\n return `table\\u0000${operation.tableName}`;\n }\n if (operation.type === \"dropColumn\") {\n return `column\\u0000${operation.tableName}\\u0000${operation.columnName}`;\n }\n return \"\";\n}\n\n/**\n * Puts every destructive operation (enum value removals excepted: they have\n * their own mapping question) to `resolve` once, for push and generate alike.\n * A rejected or unanswered change refuses, unless `force` admits an unanswered\n * one. Without a callback nothing is asked: the refusal names every change.\n * Returns the approval of every destructive change, in operation order; a drop\n * an `addAndDrop` answer already decided is approved by that answer.\n */\nexport async function approveDestructiveOperations(\n operations: readonly DiffOperation[],\n resolve: ResolveCallback | undefined,\n force: boolean,\n admittedDrops: ReadonlySet<string> = new Set()\n): Promise<MigrationApprovalV1[]> {\n const destructive = operations.filter(\n (operation) =>\n operation.type !== \"alterEnum\" && isDestructiveOperation(operation)\n );\n const facts = destructive.map(describeDestructiveOperation);\n const changes = facts.map(({ column, ...change }) =>\n createDestructiveChange(column === null ? change : { ...change, column })\n );\n if (!resolve && changes.length > 0) {\n throw new MigrationError(\n `Destructive changes need an approval:\\n${changes.map((change) => `- ${change.description}`).join(\"\\n\")}\\n\\n` +\n \"Pass a resolve callback that returns change.proceed() or change.reject() for each one.\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n hint: \"Review the changes, then pass a resolve callback (generate() or down()) that approves them with change.proceed(); for the CLI, set migrations.resolve in viborm.config.ts.\",\n },\n }\n );\n }\n for (const [index, change] of changes.entries()) {\n if (!admittedDrops.has(destructiveDropKey(destructive[index]!))) {\n const result = validateResolveResult(\n \"destructive\",\n change,\n await resolve?.(change)\n );\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined && !force) {\n throw new MigrationError(\n `Unresolved destructive change: ${change.description}\\n` +\n \"Return change.proceed() or change.reject() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n return facts.map(({ operation, table, column }) => ({\n operation,\n table,\n column,\n }));\n}\n\nfunction describeDestructiveOperation(\n op: DiffOperation\n): MigrationApprovalV1 & { readonly description: string } {\n switch (op.type) {\n case \"dropTable\":\n return {\n operation: \"dropTable\",\n table: op.tableName,\n column: null,\n description: `Drop table \"${op.tableName}\" (all data will be lost)`,\n };\n case \"dropColumn\":\n return {\n operation: \"dropColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`,\n };\n case \"addColumn\":\n return {\n operation: \"addColumn\",\n table: op.tableName,\n column: op.column.name,\n description: `Add required column \"${op.tableName}.${op.column.name}\" without a backfill default (fails on populated tables)`,\n };\n case \"alterColumn\":\n return {\n operation: \"alterColumn\",\n table: op.tableName,\n column: op.columnName,\n // The SAME sentences the differ already writes for this operation, and\n // not a second summary of it. Rendering `from.type → to.type` here was\n // silent about the one change whose type does not move: a narrowing\n // decimal domain on SQLite reads `(INTEGER → INTEGER)`, so the user was\n // asked to accept a data-refusing change with nothing on screen to say\n // what it was. Every destructive alterColumn produces at least one\n // description, because the differ's description and classifier share\n // the same owner and ask the same three questions.\n description: getDestructiveOperationDescriptions([op]).join(\"; \"),\n };\n default:\n throw new MigrationError(\n `Unexpected operation type: ${op.type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n}\n\n// =============================================================================\n// DEFAULT RESOLVERS\n// =============================================================================\n\n/**\n * Resolver that always chooses \"addAndDrop\" for all ambiguous changes.\n * Useful for clean slate scenarios where data loss is acceptable.\n */\nexport const alwaysAddDropResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"addAndDrop\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that throws an error if any ambiguous changes are detected.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const strictResolver: Resolver = async (changes) => {\n if (changes.length > 0) {\n const descriptions = changes.map((change) => {\n if (change.type === \"ambiguousColumn\") {\n return `Column \"${change.droppedColumn.name}\" was removed and \"${change.addedColumn.name}\" was added in table \"${change.tableName}\"`;\n }\n return `Table \"${change.droppedTable}\" was removed and \"${change.addedTable}\" was added`;\n });\n\n throw new MigrationError(\n `Ambiguous changes detected that require resolution:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Supply a resolve callback choosing rename() or addAndDrop() for each change.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return new Map();\n};\n\n// =============================================================================\n// RESOLVER HELPERS\n// =============================================================================\n\nconst DECISION_KEYS = {\n column: [\"type\", \"tableName\", \"from\", \"to\", \"resolution\"],\n table: [\"type\", \"from\", \"to\", \"resolution\"],\n enumValueRemoval: [\"type\", \"tableName\", \"columnName\", \"mapValues\"],\n destructive: [\"type\", \"operation\", \"table\", \"column\"],\n} as const satisfies Record<MigrationDecisionV1[\"type\"], readonly string[]>;\nconst DECISION_TYPES = Object.keys(\n DECISION_KEYS\n) as readonly (keyof typeof DECISION_KEYS)[];\nconst ALL_DECISION_KEYS = [...new Set(Object.values(DECISION_KEYS).flat())];\nconst RESOLUTIONS = [\"rename\", \"addAndDrop\"] as const;\n\n/** Each predefined resolver's decisions, and those a plan used since the last check. */\nconst decisionUse = new WeakMap<\n ResolveCallback,\n {\n readonly decisions: readonly MigrationDecisionV1[];\n readonly used: Set<MigrationDecisionV1>;\n }\n>();\n\n/**\n * Intent as data (plan T2): a resolve callback built from plain JSON\n * decisions, so an API can carry them. It answers each change one decision\n * names and leaves every other change unanswered, which refuses it. An entry\n * that is not a decision is refused here (V4002); `generate` refuses (V4002)\n * a decision that answered no change of its plan, such as one naming a table\n * or column the plan does not touch. It serves one request: build one per\n * `generate`.\n */\nexport function createPredefinedResolver(\n decisions: readonly MigrationDecisionV1[]\n): ResolveCallback {\n const admitted = snapshotExactArray(\n decisions,\n \"decisions\",\n refuseDecision\n ).map(parseDecision);\n const used = new Set<MigrationDecisionV1>();\n const resolve: ResolveCallback = (change) => {\n for (const decision of admitted) {\n const answer = answerChange(decision, change);\n if (answer === undefined) continue;\n used.add(decision);\n return answer;\n }\n return undefined;\n };\n decisionUse.set(resolve, { decisions: admitted, used });\n return resolve;\n}\n\n/** Refuses the decisions of a predefined resolver that answered no change. */\nexport function refuseUnusedDecisions(\n resolve: ResolveCallback | undefined\n): void {\n const use = resolve && decisionUse.get(resolve);\n if (!use) return;\n const unused = use.decisions.filter((decision) => !use.used.has(decision));\n use.used.clear();\n if (unused.length > 0) {\n refuseDecision(\n `These decisions match no change of the plan (an unknown table or column, or nothing to decide): ${JSON.stringify(unused)}`\n );\n }\n}\n\nfunction answerChange(\n decision: MigrationDecisionV1,\n change: ResolveChange\n): ResolveResult | undefined {\n switch (decision.type) {\n case \"destructive\":\n return change.type === \"destructive\" &&\n change.operation === decision.operation &&\n change.table === decision.table &&\n (change.column ?? null) === decision.column\n ? change.proceed()\n : undefined;\n case \"enumValueRemoval\":\n return change.type === \"enumValueRemoval\" &&\n change.tableName === decision.tableName &&\n change.columnName === decision.columnName\n ? change.mapValues(decision.mapValues)\n : undefined;\n default: {\n const named =\n change.type === \"ambiguous\" &&\n change.oldName === decision.from &&\n change.newName === decision.to &&\n (decision.type === \"table\"\n ? change.operation === \"renameTable\"\n : change.operation === \"renameColumn\" &&\n change.table === decision.tableName);\n if (!named) return undefined;\n return decision.resolution === \"rename\"\n ? change.rename()\n : change.addAndDrop();\n }\n }\n}\n\nfunction parseDecision(entry: unknown, index: number): MigrationDecisionV1 {\n const label = `decisions[${index}]`;\n const raw = snapshotExactRecord(\n entry,\n ALL_DECISION_KEYS,\n label,\n refuseDecision\n );\n const type =\n DECISION_TYPES.find((name) => name === raw.type) ??\n refuseDecision(`${label}.type must be one of ${DECISION_TYPES.join(\", \")}`);\n // A missing key is refused by its reader below.\n const record = snapshotExactRecord(\n raw,\n DECISION_KEYS[type],\n label,\n refuseDecision\n );\n const text = (key: string): string => {\n const value = record[key];\n return typeof value === \"string\"\n ? value\n : refuseDecision(`${label}.${key} must be a string`);\n };\n const resolution = () =>\n RESOLUTIONS.find((name) => name === record.resolution) ??\n refuseDecision(`${label}.resolution must be rename or addAndDrop`);\n switch (type) {\n case \"column\":\n return {\n type,\n tableName: text(\"tableName\"),\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"table\":\n return {\n type,\n from: text(\"from\"),\n to: text(\"to\"),\n resolution: resolution(),\n };\n case \"enumValueRemoval\":\n return {\n type,\n tableName: text(\"tableName\"),\n columnName: text(\"columnName\"),\n mapValues: parseValueMapping(record.mapValues, `${label}.mapValues`),\n };\n default:\n return {\n type,\n ...parseApproval(record, label, refuseDecision),\n };\n }\n}\n\nfunction parseValueMapping(\n value: unknown,\n label: string\n): Readonly<Record<string, string | null>> {\n if (!isRecord(value)) return refuseDecision(`${label} must be an object`);\n const mapping: Record<string, string | null> = {};\n for (const [from, to] of Object.entries(value)) {\n if (!(typeof to === \"string\" || to === null)) {\n refuseDecision(`${label}.${from} must be a string or null`);\n }\n mapping[from] = to;\n }\n return Object.freeze(mapping);\n}\n\nfunction refuseDecision(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\n/**\n * Formats ambiguous changes for display\n */\nexport function formatAmbiguousChange(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return (\n `Column rename detected in table \"${change.tableName}\":\\n` +\n ` \"${change.droppedColumn.name}\" (${change.droppedColumn.type}) → \"${change.addedColumn.name}\" (${change.addedColumn.type})`\n );\n }\n return (\n \"Table rename detected:\\n\" +\n ` \"${change.droppedTable}\" → \"${change.addedTable}\"`\n );\n}\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACKS\n// =============================================================================\n\n/**\n * Rejects all changes requiring resolution.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const rejectAllResolver: ResolveCallback = async (change) =>\n change.reject();\n\n/**\n * Accepts destructive changes, treats ambiguous column changes as renames,\n * and maps enum value removals to NULL.\n * A table pair stays undecided, so the plan refuses: the dropped side may be\n * another application's table, and only a callback naming the pair may\n * rename it.\n */\nexport const lenientResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.operation === \"renameColumn\" ? change.rename() : undefined;\n }\n\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Accepts destructive changes, treats ambiguous changes as add+drop,\n * and maps enum value removals to NULL.\n * Useful when you don't care about preserving data in ambiguous scenarios.\n */\nexport const addDropResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.addAndDrop();\n }\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n","import { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseMySqlEnumValues } from \"../drivers/type-mapping\";\nimport { validateResolveResult } from \"../resolver\";\nimport {\n createEnumValueRemovalChange,\n type DiffOperation,\n type ResolveCallback,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"../types\";\n\nconst INLINE_ENUM_TOKEN =\n /^(?:enum\\(|text check\\(\"(?:[^\"]|\"\")*\"\\s+in\\s+\\()(\\s*'(?:[^']|'')*'(?:\\s*,\\s*'(?:[^']|'')*')*\\s*)\\)\\)?$/i;\n\n/** The closed inline enum carriers emitted by MySQL and SQLite drivers. */\nexport function inlineEnumValues(type: string): string[] | undefined {\n const match = INLINE_ENUM_TOKEN.exec(type.trim());\n if (!match?.[1]) return;\n if (type.trim().toLowerCase().startsWith(\"enum(\"))\n return parseMySqlEnumValues(type) ?? undefined;\n return Array.from(match[1].matchAll(/'((?:[^']|'')*)'/g), (item) =>\n item[1]!.replaceAll(\"''\", \"'\")\n );\n}\n\nexport interface EnumRemoval {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n}\n\ntype ColumnMappings = Record<string, string | null>;\n\nexport type EnumColumnMappings = Map<string, Map<string, ColumnMappings>>;\n\n/**\n * Detects enum value removals that need resolution.\n * Returns one removal per column that uses the enum.\n * Nullability never supplies a data-mapping decision.\n */\nexport function detectEnumValueRemovals(\n operations: DiffOperation[],\n currentSchema: SchemaSnapshot\n): EnumRemoval[] {\n const removals: EnumRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n const unresolvedValues = op.removeValues.filter((value) => {\n const hasExplicit =\n op.valueReplacements !== undefined && value in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n const dependentColumns = op.dependentColumns || [];\n\n for (const dependentColumn of dependentColumns) {\n const table = currentSchema.tables.find(\n (tableDef) => tableDef.name === dependentColumn.tableName\n );\n if (!table) {\n throw new MigrationError(\n `Table \"${dependentColumn.tableName}\" not found in current schema for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n const column = table.columns.find(\n (columnDef) => columnDef.name === dependentColumn.columnName\n );\n if (!column) {\n throw new MigrationError(\n `Column \"${dependentColumn.columnName}\" not found in table \"${dependentColumn.tableName}\" for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n removals.push({\n enumName: op.enumName,\n tableName: dependentColumn.tableName,\n columnName: dependentColumn.columnName,\n isNullable: column.nullable,\n removedValues: unresolvedValues,\n availableValues: op.newValues || [],\n });\n }\n }\n }\n }\n\n return removals;\n}\n\n/**\n * Applies force mode resolutions for enum value removals.\n * Sets all removed values to NULL for each column.\n */\nexport function applyForceEnumResolutions(\n operations: DiffOperation[],\n enumRemovals: EnumRemoval[]\n): DiffOperation[] {\n if (enumRemovals.length === 0) {\n return operations;\n }\n\n const removalsByEnum = new Map<string, EnumRemoval[]>();\n for (const removal of enumRemovals) {\n const existing = removalsByEnum.get(removal.enumName) || [];\n existing.push(removal);\n removalsByEnum.set(removal.enumName, existing);\n }\n\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const removals = removalsByEnum.get(op.enumName);\n if (!removals || removals.length === 0) {\n return op;\n }\n\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const removal of removals) {\n const columnKey = getColumnKey(removal);\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...createNullMappings(removal.removedValues),\n };\n }\n\n return {\n ...op,\n columnValueReplacements,\n };\n });\n}\n\nexport async function resolveEnumValueRemovalMappings(\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force: boolean\n): Promise<EnumColumnMappings> {\n const columnMappings: EnumColumnMappings = new Map();\n\n for (const removal of enumRemovals) {\n const change = createEnumValueRemovalChange({\n enumName: removal.enumName,\n tableName: removal.tableName,\n columnName: removal.columnName,\n isNullable: removal.isNullable,\n removedValues: removal.removedValues,\n availableValues: removal.availableValues,\n description:\n `Column \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - ` +\n `removing values: ${removal.removedValues.join(\", \")}. ` +\n `Map to: ${removal.availableValues.join(\", \")} or NULL`,\n });\n\n const result = validateResolveResult(\n \"enumValueRemoval\",\n change,\n await resolve(change)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n const columnKey = getColumnKey(removal);\n\n if (result === undefined) {\n if (force) {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n } else {\n throw new MigrationError(\n `Unresolved enum value removal: ${change.description}\\n` +\n \"Return change.mapValues() or change.useNull() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n decision.mappings\n );\n } else if (decision?.kind === \"useNull\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n }\n }\n }\n\n return columnMappings;\n}\n\nexport function applyResolvedEnumMappings(\n operations: DiffOperation[],\n columnMappings: EnumColumnMappings\n): DiffOperation[] {\n const enumOperations: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterEnum\") {\n const enumColumnMappings = columnMappings.get(op.enumName);\n if (enumColumnMappings && enumColumnMappings.size > 0) {\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const [columnKey, mappings] of enumColumnMappings) {\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...mappings,\n };\n }\n\n enumOperations.push({\n ...op,\n columnValueReplacements,\n });\n } else {\n enumOperations.push(op);\n }\n }\n }\n\n return enumOperations;\n}\n\nfunction setColumnMappings(\n columnMappings: EnumColumnMappings,\n enumName: string,\n columnKey: string,\n mappings: ColumnMappings\n): void {\n let enumMappings = columnMappings.get(enumName);\n if (!enumMappings) {\n enumMappings = new Map();\n columnMappings.set(enumName, enumMappings);\n }\n enumMappings.set(columnKey, mappings);\n}\n\nfunction createNullMappings(values: string[]): Record<string, null> {\n const nullMappings: Record<string, null> = {};\n for (const value of values) {\n nullMappings[value] = null;\n }\n return nullMappings;\n}\n\nfunction getColumnKey(removal: EnumRemoval): string {\n return `${removal.tableName}.${removal.columnName}`;\n}\n","import { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\n\n/**\n * Schema Differ\n *\n * Compares two SchemaSnapshots and produces a list of DiffOperations,\n * detecting ambiguous changes that require user input.\n */\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n decimalChangeNarrows,\n describeDecimalDomain,\n migrationDecimalStorageKind,\n} from \"./decimal\";\nimport type { applyNativeRename } from \"./native-rename\";\nimport { inlineEnumValues } from \"./push/enum-removals\";\nimport {\n canonicalUniqueEntities,\n normalizeDefault,\n normalizeType,\n} from \"./push-fingerprint\";\nimport type {\n AmbiguousChange,\n ColumnDef,\n DiffOperation,\n DiffResult,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\n\n// =============================================================================\n// PARTIAL-INDEX PREDICATE CANONICALIZATION (Decision 7.4)\n// =============================================================================\n\n/**\n * Asks the database for its own spelling of each declared index predicate.\n *\n * The differ has no connection of its own; the push path owns one and hands\n * this in (`planPush`). One call carries every predicate of one table, so the\n * round trip is paid once per table that has a partial index whose two\n * spellings differ — usually never, at most once per push.\n *\n * The result is positional. `undefined` at a position means the database did\n * not answer for that predicate, and the differ then treats it as\n * uncomparable — never as equal.\n */\nexport type IndexPredicateCanonicalizer = (\n tableName: string,\n predicates: readonly string[]\n) => Promise<ReadonlyArray<string | undefined>>;\n\nexport interface DiffOptions {\n /**\n * Compares the declared SQLite DateTime storage vocabulary carried by V1\n * snapshots. Enable only when both sides preserve that declaration. Live\n * SQLite introspection cannot recover it from TEXT, INTEGER, or REAL and\n * therefore leaves this off so an unchanged push does not drift forever.\n */\n compareDateTimeDeclarations?: boolean;\n\n /**\n * Canonicalizes partial-index predicates through the live database. Omitted\n * by callers with no connection (`generate`, which diffs two snapshots) and\n * by dialects whose catalog stores the declared statement verbatim; the\n * differ then compares the two texts raw, which is the fail-closed reading.\n */\n canonicalizeIndexPredicate?: IndexPredicateCanonicalizer;\n\n /**\n * Recognizes a foreign key and a unique constraint by its SHAPE instead of by\n * its name — see `foreignKeyShape` below for why, and for what breaks without\n * it. Set by `planPush` from the migration driver's\n * `introspectionReadsConstraintNames` capability; left off by `generate`,\n * which diffs two snapshots the serializer wrote and where every name is\n * therefore the declared one.\n */\n matchConstraintsByShape?: boolean;\n\n /** Effectful planning admission; diagnostic diffs must retain drift evidence. */\n refuseConstraintNameChurn?: boolean;\n\n /** The exact producer's additional physical effects of an accepted rename. */\n projectRename?: typeof applyNativeRename;\n}\n\n/** Canonical spellings, keyed by table and by the predicate as declared. */\ntype CanonicalPredicates = ReadonlyMap<string, string>;\n\nconst EMPTY_CANONICAL_PREDICATES: CanonicalPredicates = new Map();\n\n/** NUL joins the halves: no table name and no SQL text can contain one. */\nfunction predicateKey(tableName: string, predicate: string): string {\n return `${tableName}\\u0000${predicate}`;\n}\n\n/**\n * Asks the database for its spelling of every predicate that a partial index\n * present in both snapshots spells two ways.\n *\n * Scoped on purpose. A predicate only one side carries, or that both sides\n * spell identically, is settled without a round trip — so a schema with no\n * partial index, or one that already converged, costs nothing.\n */\nasync function canonicalizeChangedPredicates(\n currentTables: ReadonlyMap<string, TableDef>,\n desiredTables: ReadonlyMap<string, TableDef>,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<CanonicalPredicates> {\n if (!canonicalize) return EMPTY_CANONICAL_PREDICATES;\n\n const canonical = new Map<string, string>();\n\n for (const [tableName, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(tableName);\n if (!currentTable) continue;\n\n const currentIndexes = new Map(\n currentTable.indexes.map((i) => [i.name, i])\n );\n const pending = new Set<string>();\n\n for (const desiredIndex of desiredTable.indexes) {\n const currentIndex = currentIndexes.get(desiredIndex.name);\n if (!currentIndex) continue;\n const left = normalizeIndexWhere(currentIndex.where);\n const right = normalizeIndexWhere(desiredIndex.where);\n if (left === undefined || right === undefined || left === right) continue;\n pending.add(left);\n pending.add(right);\n }\n\n if (pending.size === 0) continue;\n\n const predicates = [...pending];\n const spellings = await canonicalize(tableName, predicates);\n for (const [position, predicate] of predicates.entries()) {\n const spelling = spellings[position];\n if (spelling !== undefined) {\n canonical.set(predicateKey(tableName, predicate), spelling);\n }\n }\n }\n\n return canonical;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction columnPropertiesEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n normalizeType(a.type) === normalizeType(b.type) &&\n a.nullable === b.nullable &&\n normalizeDefault(a.default, a.type) ===\n normalizeDefault(b.default, b.type) &&\n // The declared domain is compared beside the physical type, not instead of\n // it, because the two carry different amounts of the fact per dialect: a\n // PostgreSQL `numeric(10,5)` spells its whole domain in the type, while a\n // SQLite decimal is `INTEGER` (or `TEXT` for a list) at every precision and\n // scale there is. Left out, a SQLite descriptor change plans NOTHING —\n // the type is byte-identical on both sides — and the column silently keeps\n // storing coefficients at the old scale.\n sqliteGeoPointEncoding(a) === sqliteGeoPointEncoding(b) &&\n sameDecimalDescriptor(a.decimal, b.decimal) &&\n (!compareDateTimeDeclarations || a.dateTime === b.dateTime)\n );\n}\n\nfunction columnsEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n a.name === b.name &&\n columnPropertiesEqual(a, b, compareDateTimeDeclarations)\n );\n}\n\nfunction columnsCanBeRenamed(a: ColumnDef, b: ColumnDef): boolean {\n if (normalizeType(a.type) === normalizeType(b.type)) return true;\n const aDecimalKind = migrationDecimalStorageKind(a);\n return (\n aDecimalKind !== undefined &&\n aDecimalKind === migrationDecimalStorageKind(b)\n );\n}\n\nfunction normalizeIndexType(type: IndexDef[\"type\"]): string {\n // An index with no declared type is a B-tree on every dialect. The two\n // snapshot producers spell that differently — introspection reads \"btree\"\n // back from the Postgres/MySQL catalog, SQLite reports no type at all, and\n // the serializer leaves an undeclared type undefined — so the same index\n // must not read as a change.\n return type ?? \"btree\";\n}\n\nfunction normalizeIndexUnique(unique: IndexDef[\"unique\"]): boolean {\n // `type`'s twin (above): the serializer leaves a plain `.index()`'s `unique`\n // undefined while every introspection reads a boolean back from the catalog,\n // so the same index must not read as a change. Left raw, every push re-plans\n // drop+create forever — and on MySQL the drop is a hard 1553 abort when the\n // declared index is the one InnoDB bound the FK to.\n return unique ?? false;\n}\n\nfunction normalizeIndexWhere(where: IndexDef[\"where\"]): string | undefined {\n // `type`'s and `unique`'s third twin, and the one place the partial index's\n // two spellings are reconciled. The serializer passes the declared predicate\n // through untouched; the emitter writes ` WHERE ${where}`, and SQLite stores\n // that statement verbatim, padding and all. Reading it back consumes the\n // whitespace run that separates `WHERE` from the predicate, so a declaration\n // written with padding comes back without its leading part — the same index\n // in two spellings. Left raw, every push re-plans drop+create forever.\n const trimmed = where?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * The one place the two snapshots' predicates are compared, and the reader of\n * the canonical spellings the database supplied (Decision 7.4).\n *\n * `normalizeIndexWhere` above reconciles the *padding* of one text; it cannot\n * reconcile two texts. PostgreSQL's catalog does not store the declared\n * statement — `pg_get_expr(indpred, indrelid)` deparses it, so a declared\n * `published = true` reads back as `(published = true)`, and every push drops\n * and re-creates every partial index. No client-side normalization closes that\n * while staying fail-closed: flatten whitespace and parentheses and\n * `a AND (b OR c)` starts comparing equal to `(a AND b) OR c`, so a real change\n * would stop being seen. So the database is asked, and `canonical` holds what\n * it answered. Two predicates are the same predicate only when BOTH were\n * canonicalized and the two canonical spellings are identical.\n */\nfunction indexWhereEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n const left = normalizeIndexWhere(a.where);\n const right = normalizeIndexWhere(b.where);\n if (left === right) return true;\n // A predicate that appears or disappears is a real change on every dialect,\n // and no round trip can make a partial index equal to a total one.\n if (left === undefined || right === undefined) return false;\n\n const leftCanonical = canonical.get(predicateKey(tableName, left));\n const rightCanonical = canonical.get(predicateKey(tableName, right));\n // Fail closed. Without both spellings — no canonicalizer, a dialect that has\n // none, a connection that refused, a predicate the database could not parse —\n // two texts that do not read alike stay a change.\n return leftCanonical !== undefined && leftCanonical === rightCanonical;\n}\n\nfunction indexesEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n // A raw index equals only a raw index of the same text over the same\n // columns: a hand-made index under its name is replaced by it.\n if (a.raw || b.raw)\n return (\n a.name === b.name &&\n a.raw?.hash === b.raw?.hash &&\n arraysEqual(a.columns, b.columns)\n );\n return (\n a.name === b.name &&\n normalizeIndexUnique(a.unique) === normalizeIndexUnique(b.unique) &&\n arraysEqual(a.columns, b.columns) &&\n normalizeIndexType(a.type) === normalizeIndexType(b.type) &&\n indexWhereEqual(tableName, a, b, canonical)\n );\n}\n\nfunction arraysEqual<T>(a: T[], b: T[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n}\n\n// =============================================================================\n// CONSTRAINT IDENTITY\n// =============================================================================\n\nfunction normalizeReferentialAction(\n action: ReferentialAction | undefined\n): ReferentialAction {\n // `normalizeIndexUnique`'s twin on the foreign-key side. Every introspection\n // reads a concrete action back from the catalog — \"NO ACTION\" when the DDL\n // declared none — while a snapshot may leave it undefined, and both spell the\n // same constraint: SQLite and MySQL omit the clause for `noAction`,\n // PostgreSQL writes `ON DELETE NO ACTION`, which is what omitting it means.\n // Left raw, the same key reads as a change and is dropped and re-added on\n // every push.\n return action ?? \"noAction\";\n}\n\n/**\n * What a foreign key IS, with the name left out: the columns it binds, what\n * they point at, and what happens on delete and on update. NUL joins the\n * columns and SOH the parts — no SQL identifier and no action name holds\n * either, so two shapes read alike only when every part does.\n *\n * The name is left out because on some dialects it is not readable. On\n * PostgreSQL and MySQL the catalog carries the name the DDL gave the\n * constraint, so a name IS an identity there and the differ matches on it.\n * SQLite carries no name for either constraint this file matches:\n * `PRAGMA foreign_key_list` has no name column at all, so introspection\n * synthesises `<table>_fk_<n>`, and an inline `CONSTRAINT x UNIQUE (...)` is\n * reported only under SQLite's own `sqlite_autoindex_<table>_<n>`. Matched by\n * name, the declared constraint is therefore missing and the read one extra on\n * every push of an unchanged schema, forever — and the two repairs the differ\n * plans are both wrong:\n *\n * - the foreign key is dropped and re-added, and SQLite has no\n * `ALTER TABLE ADD FOREIGN KEY`, so each of those rebuilds the whole table\n * — copy included — twice per push, for a schema nobody edited;\n * - the unique constraint's drop is `DROP INDEX \"sqlite_autoindex_...\"`,\n * which SQLite refuses (\"index associated with UNIQUE or PRIMARY KEY\n * constraint cannot be dropped\"), so the SECOND push of any SQLite schema\n * carrying a compound unique fails outright.\n *\n * So where the name cannot be read, the shape is the identity: two constraints\n * of one shape are one constraint, whatever the reader called them.\n */\nfunction foreignKeyShape(fk: ForeignKeyDef): string {\n return [\n fk.columns.join(\"\\u0000\"),\n fk.referencedTable,\n fk.referencedColumns.join(\"\\u0000\"),\n normalizeReferentialAction(fk.onDelete),\n normalizeReferentialAction(fk.onUpdate),\n ].join(\"\\u0001\");\n}\n\n/** `foreignKeyShape`'s twin: a unique constraint is its column list. */\nfunction uniqueConstraintShape(constraint: UniqueConstraintDef): string {\n return constraint.columns.join(\"\\u0000\");\n}\n\n/**\n * Pairs each `current` constraint with the `desired` one it is, under whichever\n * identity the dialect supports, and reports what `desired` had left over.\n *\n * Multisets, not maps, on purpose. A database written before\n * `SQLite3MigrationDriver.getCurrentTable` learned to replay the batch can hold\n * several byte-identical foreign keys on one table — they accumulated, one per\n * push, without bound. Keying by identity alone would collapse those into one\n * entry and leave the extras attached forever; pairing k of n leaves n-k\n * unmatched, and unmatched is what gets dropped.\n */\nfunction matchByIdentity<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string\n): { matches: Array<T | undefined>; unmatchedDesired: T[] } {\n const availableByIdentity = new Map<string, number[]>();\n for (const [position, item] of desired.entries()) {\n const identity = identityOf(item);\n const positions = availableByIdentity.get(identity);\n if (positions) {\n positions.push(position);\n } else {\n availableByIdentity.set(identity, [position]);\n }\n }\n\n const consumed = new Set<number>();\n const matches = current.map((item) => {\n const position = availableByIdentity.get(identityOf(item))?.shift();\n if (position === undefined) return undefined;\n consumed.add(position);\n return desired[position];\n });\n\n return {\n matches,\n unmatchedDesired: desired.filter(\n (_, position) => !consumed.has(position)\n ) as T[],\n };\n}\n\n/**\n * A table's keyed members: each current one is dropped when nothing desired\n * matches it, or dropped and re-added when its match differs; each unmatched\n * desired one is then added. Current order first, then desired order.\n */\nfunction diffKeyed<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string,\n equal: (from: T, to: T) => boolean,\n drop: (item: T) => DiffOperation,\n add: (item: T) => DiffOperation\n): DiffOperation[] {\n const { matches, unmatchedDesired } = matchByIdentity(\n current,\n desired,\n identityOf\n );\n return [\n ...current.flatMap((item, position) => {\n const match = matches[position];\n if (match === undefined) return [drop(item)];\n return equal(item, match) ? [] : [drop(item), add(match)];\n }),\n ...unmatchedDesired.map(add),\n ];\n}\n\nfunction enumsEqual(a: EnumDef, b: EnumDef): boolean {\n return a.name === b.name && arraysEqual(a.values, b.values);\n}\n\n// =============================================================================\n// TABLE DIFFER\n// =============================================================================\n\ninterface TableDiffResult {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n}\n\nfunction refuseConstraintNameMismatch(\n table: string,\n actual: string,\n desired: string\n): never {\n throw new MigrationError(\n `Constraint \"${table}.${actual}\" already enforces the desired definition under a different physical name (\"${desired}\"). This declaration cannot faithfully adopt that name. Synchronization refuses before effects instead of dropping and recreating an equivalent constraint. Public key names select fields; they do not declare physical constraint names.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table, constraint: actual } }\n );\n}\n\nfunction diffTable(\n tableName: string,\n current: TableDef,\n desired: TableDef,\n canonical: CanonicalPredicates,\n matchConstraintsByShape: boolean,\n compareDateTimeDeclarations: boolean,\n refuseConstraintNameChurn: boolean,\n projectRename: DiffOptions[\"projectRename\"]\n): TableDiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n if (!matchConstraintsByShape && refuseConstraintNameChurn) {\n for (const constraint of desired.foreignKeys) {\n if (current.foreignKeys.some((actual) => actual.name === constraint.name))\n continue;\n const actual = current.foreignKeys.find(\n (actual) => foreignKeyShape(actual) === foreignKeyShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n for (const constraint of desired.uniqueConstraints) {\n if (\n current.uniqueConstraints.some(\n (actual) => actual.name === constraint.name\n )\n )\n continue;\n const actual = current.uniqueConstraints.find(\n (actual) =>\n uniqueConstraintShape(actual) === uniqueConstraintShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n const currentPk = current.primaryKey,\n desiredPk = desired.primaryKey;\n if (\n currentPk &&\n desiredPk &&\n arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n const actual = currentPk.name ?? `${tableName}_pkey`,\n wanted = desiredPk.name ?? `${tableName}_pkey`;\n if (actual !== wanted)\n refuseConstraintNameMismatch(tableName, actual, wanted);\n }\n }\n\n // Build column maps\n const currentColumns = new Map(current.columns.map((c) => [c.name, c]));\n const desiredColumns = new Map(desired.columns.map((c) => [c.name, c]));\n\n // Find dropped and added columns\n const droppedColumns: ColumnDef[] = [];\n const addedColumns: ColumnDef[] = [];\n\n for (const [name, col] of currentColumns) {\n if (!desiredColumns.has(name)) {\n droppedColumns.push(col);\n }\n }\n\n for (const [name, col] of desiredColumns) {\n if (!currentColumns.has(name)) {\n addedColumns.push(col);\n }\n }\n\n // Detect potential column renames (ambiguous changes)\n // A rename is suspected when a column is dropped and another is added\n // with compatible types\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // The dropped column as the rename would leave it: a type derived from its\n // name (a PostgreSQL per-column enum) follows the column.\n const asRenamed = (dropped: ColumnDef, added: ColumnDef): ColumnDef =>\n projectRename?.(\n { tables: [current] },\n { type: \"renameColumn\", tableName, from: dropped.name, to: added.name }\n ).tables[0]?.columns.find((column) => column.name === added.name) ??\n dropped;\n\n for (const dropped of droppedColumns) {\n for (const added of addedColumns) {\n if (usedDropped.has(dropped.name) || usedAdded.has(added.name)) continue;\n\n if (columnsCanBeRenamed(asRenamed(dropped, added), added)) {\n // This could be a rename - mark as ambiguous\n ambiguousChanges.push({\n type: \"ambiguousColumn\",\n tableName,\n droppedColumn: dropped,\n addedColumn: added,\n });\n usedDropped.add(dropped.name);\n usedAdded.add(added.name);\n }\n }\n }\n\n // Add operations for non-ambiguous drops and adds\n for (const dropped of droppedColumns) {\n if (!usedDropped.has(dropped.name)) {\n operations.push({\n type: \"dropColumn\",\n tableName,\n columnName: dropped.name,\n });\n }\n }\n\n for (const added of addedColumns) {\n if (!usedAdded.has(added.name)) {\n operations.push({\n type: \"addColumn\",\n tableName,\n column: added,\n });\n }\n }\n\n // Check for column modifications (same name, different properties)\n for (const [name, desiredCol] of desiredColumns) {\n const currentCol = currentColumns.get(name);\n if (\n currentCol &&\n !columnsEqual(currentCol, desiredCol, compareDateTimeDeclarations)\n ) {\n const previousValues = inlineEnumValues(currentCol.type);\n const nextValues = inlineEnumValues(desiredCol.type);\n if (\n previousValues &&\n nextValues &&\n normalizeType(currentCol.type) !== normalizeType(desiredCol.type)\n ) {\n operations.push({\n type: \"alterEnum\",\n enumName: desiredCol.type,\n newValues: nextValues,\n addValues: nextValues.filter(\n (value) => !previousValues.includes(value)\n ),\n removeValues: previousValues.filter(\n (value) => !nextValues.includes(value)\n ),\n dependentColumns: [{ tableName, columnName: name }],\n });\n const converted = { ...currentCol, type: desiredCol.type };\n if (\n !columnPropertiesEqual(\n converted,\n desiredCol,\n compareDateTimeDeclarations\n )\n )\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: converted,\n to: desiredCol,\n });\n } else {\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: currentCol,\n to: desiredCol,\n });\n }\n }\n }\n\n // Foreign keys and uniques match under whichever identity this dialect's\n // introspection supports (see `foreignKeyShape`). Under shape identity a\n // pair IS one shape, so a changed definition — a referential action, a\n // referenced column — is the name-identity dialects' drop and re-add.\n operations.push(\n ...diffKeyed(\n current.indexes,\n desired.indexes,\n (index) => index.name,\n (from, to) => indexesEqual(tableName, from, to, canonical),\n (index) => ({\n type: \"dropIndex\",\n tableName,\n indexName: index.name,\n ...(index.raw ? { raw: true } : {}),\n }),\n (index) => ({ type: \"createIndex\", tableName, index })\n ),\n ...diffKeyed(\n current.foreignKeys,\n desired.foreignKeys,\n matchConstraintsByShape ? foreignKeyShape : (fk) => fk.name,\n (from, to) => foreignKeyShape(from) === foreignKeyShape(to),\n (fk) => ({ type: \"dropForeignKey\", tableName, fkName: fk.name }),\n (fk) => ({ type: \"addForeignKey\", tableName, fk })\n ),\n ...diffKeyed(\n current.uniqueConstraints,\n desired.uniqueConstraints,\n matchConstraintsByShape ? uniqueConstraintShape : (uq) => uq.name,\n (from, to) => uniqueConstraintShape(from) === uniqueConstraintShape(to),\n (uq) => ({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: uq.name,\n }),\n (constraint) => ({ type: \"addUniqueConstraint\", tableName, constraint })\n )\n );\n\n // Diff primary key\n const currentPk = current.primaryKey;\n const desiredPk = desired.primaryKey;\n\n if (currentPk && !desiredPk) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n } else if (!currentPk && desiredPk) {\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n } else if (\n currentPk &&\n desiredPk &&\n (!arraysEqual(currentPk.columns, desiredPk.columns) ||\n currentPk.withoutRowid !== desiredPk.withoutRowid)\n ) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n }\n\n return { operations, ambiguousChanges };\n}\n\n// =============================================================================\n// MAIN DIFFER\n// =============================================================================\n\n/**\n * Compares two schema snapshots and returns the operations needed to\n * transform the current schema into the desired schema.\n */\nexport async function diff(\n physicalCurrent: SchemaSnapshot,\n physicalDesired: SchemaSnapshot,\n options: DiffOptions = {}\n): Promise<DiffResult> {\n const current = canonicalUniqueEntities(physicalCurrent);\n const desired = canonicalUniqueEntities(physicalDesired);\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Logical polymorphic vocabulary is persisted only in authored snapshots.\n // Never publish an empty transition which changes the meaning of stored ids.\n for (const previous of current.polymorphicStorage ?? []) {\n const next = desired.polymorphicStorage?.find(\n (item) =>\n item.ownerTable === previous.ownerTable &&\n item.relation === previous.relation &&\n item.kind === previous.kind\n );\n if (!next) continue;\n for (const member of previous.members) {\n const destination = next.members.find(\n (item) => item.publicType === member.publicType\n );\n if (\n destination &&\n (destination.storedType !== member.storedType ||\n destination.targetTable !== member.targetTable)\n ) {\n throw new MigrationError(\n `Polymorphic storage \"${previous.ownerTable}.${previous.relation}\" changes stored meaning for \"${member.publicType}\"; author an explicit manual data transition`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n\n // Build table maps\n const currentTables = new Map(current.tables.map((t) => [t.name, t]));\n const desiredTables = new Map(desired.tables.map((t) => [t.name, t]));\n\n const canonicalPredicates = await canonicalizeChangedPredicates(\n currentTables,\n desiredTables,\n options.canonicalizeIndexPredicate\n );\n\n // Find dropped and added tables\n const droppedTables: string[] = [];\n const addedTables: string[] = [];\n\n for (const [name] of currentTables) {\n if (!desiredTables.has(name)) {\n droppedTables.push(name);\n }\n }\n\n for (const [name] of desiredTables) {\n if (!currentTables.has(name)) {\n addedTables.push(name);\n }\n }\n\n // Detect potential table renames (ambiguous changes)\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // Similarity orders questions, never answers them: even a zero-overlap\n // drop/create pair still requires an explicit author decision. Present the\n // strongest matches first so an unrelated drop cannot consume a clear rename.\n const candidates = droppedTables\n .flatMap((droppedName) => {\n const droppedTable = currentTables.get(droppedName)!;\n return addedTables.map((addedName) => {\n const addedTable = desiredTables.get(addedName)!;\n const matchingColumns = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => columnsEqual(column, other, true))\n ).length;\n const matchingNames = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => column.name === other.name)\n ).length;\n return {\n droppedName,\n addedName,\n droppedTable,\n addedTable,\n matchingColumns,\n matchingNames,\n };\n });\n })\n .sort(\n (a, b) =>\n b.matchingNames - a.matchingNames ||\n b.matchingColumns - a.matchingColumns\n );\n for (const candidate of candidates) {\n const { droppedName, addedName, droppedTable, addedTable } = candidate;\n if (usedDropped.has(droppedName) || usedAdded.has(addedName)) continue;\n ambiguousChanges.push({\n type: \"ambiguousTable\",\n droppedTable: droppedName,\n addedTable: addedName,\n droppedTableDef: droppedTable,\n addedTableDef: addedTable,\n });\n usedDropped.add(droppedName);\n usedAdded.add(addedName);\n }\n\n // Add operations for non-ambiguous table drops and creates\n for (const name of droppedTables) {\n if (!usedDropped.has(name)) {\n operations.push({ type: \"dropTable\", tableName: name });\n }\n }\n\n for (const name of addedTables) {\n if (!usedAdded.has(name)) {\n const table = desiredTables.get(name)!;\n operations.push({ type: \"createTable\", table });\n }\n }\n\n // Diff existing tables\n for (const [name, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(name);\n if (currentTable) {\n const tableDiff = diffTable(\n name,\n currentTable,\n desiredTable,\n canonicalPredicates,\n options.matchConstraintsByShape ?? false,\n options.compareDateTimeDeclarations ?? false,\n options.refuseConstraintNameChurn ?? false,\n options.projectRename\n );\n operations.push(...tableDiff.operations);\n ambiguousChanges.push(...tableDiff.ambiguousChanges);\n }\n }\n\n // Diff enums (PostgreSQL specific)\n if (current.enums || desired.enums) {\n const currentEnums = new Map((current.enums || []).map((e) => [e.name, e]));\n const desiredEnums = new Map((desired.enums || []).map((e) => [e.name, e]));\n\n // Dropped enums\n for (const [name] of currentEnums) {\n if (!desiredEnums.has(name)) {\n // Find all columns that depend on this enum\n const dependentColumns: Array<{\n tableName: string;\n columnName: string;\n }> = [];\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n operations.push({\n type: \"dropEnum\",\n enumName: name,\n dependentColumns:\n dependentColumns.length > 0 ? dependentColumns : undefined,\n });\n }\n }\n\n // Added enums\n for (const [name, enumDef] of desiredEnums) {\n if (!currentEnums.has(name)) {\n operations.push({ type: \"createEnum\", enumDef });\n }\n }\n\n // Modified enums\n for (const [name, desiredEnum] of desiredEnums) {\n const currentEnum = currentEnums.get(name);\n if (currentEnum && !enumsEqual(currentEnum, desiredEnum)) {\n const addValues = desiredEnum.values.filter(\n (v) => !currentEnum.values.includes(v)\n );\n const removeValues = currentEnum.values.filter(\n (v) => !desiredEnum.values.includes(v)\n );\n\n if (\n addValues.length > 0 ||\n removeValues.length > 0 ||\n !arraysEqual(currentEnum.values, desiredEnum.values)\n ) {\n // When removing values, we need to find all columns that use this enum\n // so we can temporarily convert them to text during the recreation\n let dependentColumns:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n dependentColumns = [];\n // Search through all tables (current schema) for columns using this enum\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n\n operations.push({\n type: \"alterEnum\",\n enumName: name,\n addValues: addValues.length > 0 ? addValues : undefined,\n removeValues: removeValues.length > 0 ? removeValues : undefined,\n newValues: desiredEnum.values,\n dependentColumns:\n dependentColumns && dependentColumns.length > 0\n ? dependentColumns\n : undefined,\n });\n }\n }\n }\n }\n\n // Sort operations for proper execution order\n return {\n operations: sortOperations(\n operations.map((operation): DiffOperation => {\n if (operation.type === \"createTable\")\n return {\n ...operation,\n table:\n physicalDesired.tables.find(\n (table) => table.name === operation.table.name\n ) ?? operation.table,\n };\n if (operation.type === \"addUniqueConstraint\") {\n const index = physicalDesired.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraint.name);\n if (index)\n return {\n type: \"createIndex\",\n tableName: operation.tableName,\n index,\n };\n }\n if (operation.type === \"dropUniqueConstraint\") {\n const index = physicalCurrent.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraintName);\n if (index)\n return {\n type: \"dropIndex\",\n tableName: operation.tableName,\n indexName: index.name,\n };\n }\n return operation;\n })\n ),\n ambiguousChanges,\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE OPERATION CHECKS\n// =============================================================================\n\n/** The one destructive-operation classification used by every consumer. */\nexport function isDestructiveOperation(operation: DiffOperation): boolean {\n if (operation.type === \"alterEnum\")\n return (operation.removeValues?.length ?? 0) > 0;\n if (operation.type === \"addColumn\")\n return !operation.column.nullable && operation.column.default === undefined;\n if (operation.type === \"dropTable\" || operation.type === \"dropColumn\") {\n return true;\n }\n return (\n operation.type === \"alterColumn\" &&\n (normalizeType(operation.from.type) !== normalizeType(operation.to.type) ||\n (operation.from.nullable && !operation.to.nullable) ||\n decimalChangeNarrows(operation.from, operation.to))\n );\n}\n\n/** What each destructive column alteration risks, one sentence per risk. */\nexport function getDestructiveOperationDescriptions(\n operations: DiffOperation[]\n): string[] {\n const descriptions: string[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterColumn\") {\n if (normalizeType(op.from.type) !== normalizeType(op.to.type)) {\n descriptions.push(\n `Change type of \"${op.tableName}\".\"${op.columnName}\" from ${op.from.type} to ${op.to.type} (may cause data loss)`\n );\n }\n if (op.from.nullable && !op.to.nullable) {\n descriptions.push(\n `Make \"${op.tableName}\".\"${op.columnName}\" NOT NULL (may fail if column contains NULL values)`\n );\n }\n if (\n op.from.decimal &&\n op.to.decimal &&\n decimalChangeNarrows(op.from, op.to)\n ) {\n // The numbers go in the SENTENCE: `precision` and `scale` are not\n // error-metadata keys, so a refusal that put them in `meta` would drop\n // them silently.\n descriptions.push(\n `Narrow the decimal domain of \"${op.tableName}\".\"${op.columnName}\" from ${describeDecimalDomain(op.from.decimal)} to ${describeDecimalDomain(op.to.decimal)} (the conversion refuses every value that no longer fits, rather than rounding it)`\n );\n }\n }\n }\n\n return descriptions;\n}\n","import { renderQualifiedIdentifier } from \"../sql/identifiers\";\n/**\n * Driver catalog probes. These are the only checks the ORM proves read-only.\n * Manual trusted-read checks are a different arm.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { RAW_INDEX_MARKER_PREFIX, rawIndexMarker } from \"./raw-index\";\nimport type { DiffOperation, IndexDef } from \"./types\";\nimport type { MigrationParameterV1 } from \"./v1-types\";\n\nexport interface CatalogProbe {\n readonly id: string;\n readonly sql: string;\n readonly parameters: readonly MigrationParameterV1[];\n readonly equals: boolean;\n}\n\ntype CatalogProbeLifetime = \"live-command\" | \"stored-artifact\";\n\nfunction namespace(driver: MigrationDriver): string | undefined {\n return (\n driver.namespace ??\n (driver.target?.dialect === \"postgresql\"\n ? driver.target.namespace\n : undefined)\n );\n}\n\nfunction boundCatalogNamespace(driver: MigrationDriver): string {\n const value = namespace(driver);\n if (value) return value;\n throw new MigrationError(\n \"A catalog probe needs the bound migration namespace and this driver has none\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.dialect } }\n );\n}\n\nfunction stringParam(value: string): MigrationParameterV1 {\n return { kind: \"string\", value };\n}\n\nfunction mysqlNamespaceParam(\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime\n): MigrationParameterV1 {\n return lifetime === \"stored-artifact\"\n ? { kind: \"target-namespace\" }\n : stringParam(boundCatalogNamespace(driver));\n}\n\nexport function tableExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"surrealql\")\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: \"RETURN [{ present: (INFO FOR DB STRUCTURE).tables.name CONTAINS $p1 }]\",\n parameters: [stringParam(tableName)],\n equals: exists,\n };\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'p'))`,\n parameters: [stringParam(schema), stringParam(tableName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n ],\n equals: exists,\n };\n }\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)`,\n parameters: [stringParam(tableName)],\n equals: exists,\n };\n}\n\nexport function columnExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n columnName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped)\",\n parameters: [\n stringParam(schema),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pragma_table_info(?) WHERE name = ?)\",\n parameters: [stringParam(tableName), stringParam(columnName)],\n equals: exists,\n };\n}\n\nexport function indexExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n indexName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n // An index exists only once it is VALID: an interrupted CONCURRENTLY\n // build leaves the relation behind with indisvalid = false. Absence\n // still means no relation of that name at all.\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace${exists ? \" JOIN pg_catalog.pg_index x ON x.indexrelid = c.oid AND x.indisvalid\" : \"\"} WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i')`,\n parameters: [stringParam(schema), stringParam(indexName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND index_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(indexName),\n ],\n equals: exists,\n };\n }\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?)`,\n parameters: [stringParam(indexName)],\n equals: exists,\n };\n}\n\n/**\n * Whether a raw index carries its marker (PostgreSQL holds it as the index's\n * comment, written by a statement of its own after the index's): an index\n * that exists says nothing about it, so a stepwise run would skip the comment.\n */\nfunction rawIndexMarkerProbe(\n driver: MigrationDriver,\n index: IndexDef,\n present: boolean\n): CatalogProbe {\n return {\n id: `index-marker:${present ? \"present\" : \"absent\"}:${index.name}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i' AND pg_catalog.obj_description(c.oid, 'pg_class') IS NOT DISTINCT FROM $3)\",\n parameters: [\n stringParam(boundCatalogNamespace(driver)),\n stringParam(index.name),\n stringParam(RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)),\n ],\n equals: present,\n };\n}\n\n/** The raw index whose marker a `COMMENT ON INDEX` statement writes. */\nfunction commentedRawIndex(\n operation: DiffOperation,\n statement: string\n): IndexDef | undefined {\n const indexes =\n operation.type === \"createIndex\"\n ? [operation.index]\n : operation.type === \"createTable\"\n ? operation.table.indexes\n : [];\n return indexes.find(\n (index) =>\n index.raw !== undefined &&\n statement.includes(\n (RAW_INDEX_MARKER_PREFIX + rawIndexMarker(index)).replaceAll(\"'\", \"''\")\n )\n );\n}\n\nconst CREATE_INDEX_HEADER =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+|SPATIAL\\s+|FULLTEXT\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"(?:[^\"]|\"\")+\"|`(?:[^`]|``)+`|[\\w$]+)\\s+ON\\b/i;\n\n/** The name a `CREATE INDEX` statement gives its index, unquoted. */\nfunction createdIndexName(statement: string): string | undefined {\n const name = CREATE_INDEX_HEADER.exec(statement)?.[1];\n if (name === undefined) return undefined;\n const quote = name[0];\n return quote === '\"' || quote === \"`\"\n ? name.slice(1, -1).replaceAll(quote + quote, quote)\n : name;\n}\n\nexport function probeForGeneratedStatement(\n driver: MigrationDriver,\n operation: DiffOperation,\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n // An operation here is several statements, and they run in the one transaction.\n if (driver.dialect === \"surrealql\") return null;\n if (\n (driver.dialect === \"postgresql\" || driver.dialect === \"mysql\") &&\n namespace(driver) === undefined\n ) {\n return null;\n }\n const text = statement.trim().toUpperCase();\n if (\n text.startsWith(\"PRAGMA\") ||\n text.startsWith(\"INSERT \") ||\n text.startsWith(\"--\")\n ) {\n return null;\n }\n if (text.startsWith(\"COMMENT ON INDEX\")) {\n const index = commentedRawIndex(operation, statement);\n return index === undefined\n ? null\n : {\n pre: rawIndexMarkerProbe(driver, index, false),\n post: rawIndexMarkerProbe(driver, index, true),\n };\n }\n switch (operation.type) {\n case \"createTable\":\n if (text.startsWith(\"CREATE TABLE\")) {\n return {\n pre: tableExistsProbe(\n driver,\n operation.table.name,\n false,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.table.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n if (text.startsWith(\"CREATE \") && text.includes(\"INDEX\")) {\n // The index this statement creates, read from its header: neither one\n // whose name it extends (`by_email_b`) nor a column it indexes is it.\n const created = createdIndexName(statement);\n const index = operation.table.indexes.find(\n (item) => item.name === created\n );\n if (!index) return null;\n return {\n pre: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n return null;\n case \"dropTable\":\n return {\n pre: tableExistsProbe(\n driver,\n operation.tableName,\n true,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.tableName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"addColumn\": {\n const pre = columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n false,\n \"stored-artifact\"\n );\n const required =\n !operation.column.nullable &&\n operation.column.default === undefined &&\n !operation.column.autoIncrement;\n const table = renderQualifiedIdentifier(\n (name) => driver.escapeIdentifier(name),\n driver.dialect === \"postgresql\" ? namespace(driver) : undefined,\n operation.tableName\n );\n return {\n pre: required\n ? {\n ...pre,\n id: `column:absent-and-empty-table:${operation.tableName}.${operation.column.name}`,\n sql: `SELECT (${pre.sql.slice(\"SELECT \".length)}) OR EXISTS (SELECT 1 FROM ${table} LIMIT 1)`,\n }\n : pre,\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n case \"dropColumn\":\n return {\n pre: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n true,\n \"stored-artifact\"\n ),\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"createIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n true,\n \"stored-artifact\"\n ),\n };\n case \"dropIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n true,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n false,\n \"stored-artifact\"\n ),\n };\n default:\n return null;\n }\n}\n\n/** One index an interrupted CONCURRENTLY build left INVALID. */\nexport interface InvalidIndex {\n readonly table: string;\n readonly index: string;\n}\n\n/**\n * The INVALID indexes on the estate's managed tables. Only PostgreSQL has the\n * state: MySQL and SQLite build an index or fail without leaving one behind.\n */\nexport async function readInvalidIndexes(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<readonly InvalidIndex[]> {\n if (driver.dialect !== \"postgresql\") return [];\n const result = await producer._executeRaw<InvalidIndex>(\n `SELECT t.relname AS \"table\", i.relname AS \"index\" FROM pg_catalog.pg_index x JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid JOIN pg_catalog.pg_class t ON t.oid = x.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT (x.indisvalid AND x.indisready) ORDER BY t.relname, i.relname`,\n [boundCatalogNamespace(driver)]\n );\n const managed = driver.target.tables;\n return result.rows.filter(\n (row) => managed === undefined || managed.includes(row.table)\n );\n}\n\nexport function boundNamespace(\n driver: BoundMigrationDriver\n): string | undefined {\n return namespace(driver);\n}\n\n/**\n * One object's name as a live statement spells it: qualified with the bound\n * namespace, or bare on SQLite and on unbound MySQL.\n */\nexport function qualifiedName(\n driver: BoundMigrationDriver,\n name: string\n): string {\n return renderQualifiedIdentifier(\n (part) => driver.escapeIdentifier(part),\n driver.target.dialect === \"sqlite\" || driver.target.dialect === \"surrealql\"\n ? undefined\n : namespace(driver),\n name\n );\n}\n","/**\n * Inverse owner for generated DiffOperation programs.\n * Empty programs invert to an empty schema rollback. Missing inverses are\n * irreversible. This is the only place that answers that question.\n */\n\nimport { applyNativeRename } from \"./native-rename\";\nimport type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\nimport { defaultGeneratedPrimaryKeyName } from \"./utils\";\n\nexport interface InvertedOperations {\n operations: DiffOperation[];\n warnings: string[];\n}\n\nexport function invertOperations(\n operations: DiffOperation[],\n previousSnapshot: SchemaSnapshot,\n projectRename: typeof applyNativeRename = applyNativeRename,\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName = defaultGeneratedPrimaryKeyName\n): InvertedOperations {\n const warnings: string[] = [];\n const inverted: DiffOperation[] = [];\n // At the inverse of operation i, every rename that preceded i in the up\n // program is still active and every rename that followed it has already been\n // inverted. Keep the previous definitions at each exact prefix so a restored\n // FK targets the identity that exists at that point — neither always-old nor\n // always-new is correct.\n let previousAtOperationIdentity = previousSnapshot;\n const previousIdentityBefore: SchemaSnapshot[] = [];\n // A key the up program drops by itself (PostgreSQL/MySQL drop every key of\n // a dropped table first) comes back through that drop's own inverse, which\n // runs after every recreated table exists. The recreated table leaves it\n // out: restored inline it would name a table not yet recreated, and then be\n // added a second time.\n const keysRestoredByTheirOwnInverse = new Set<string>();\n for (const op of operations) {\n previousIdentityBefore.push(previousAtOperationIdentity);\n if (op.type === \"dropForeignKey\") {\n keysRestoredByTheirOwnInverse.add(\n foreignKeyIdentity(op.tableName, op.fkName)\n );\n }\n if (op.type === \"renameTable\" || op.type === \"renameColumn\") {\n previousAtOperationIdentity = projectRename(\n previousAtOperationIdentity,\n op\n );\n }\n }\n\n for (let i = operations.length - 1; i >= 0; i--) {\n const op = operations[i]!;\n const previousAtIdentity = previousIdentityBefore[i] ?? previousSnapshot;\n const findPrevTable = (name: string): TableDef | undefined =>\n previousAtIdentity.tables.find((table) => table.name === name);\n const inverse = invertOperation(\n op,\n previousSnapshot,\n findPrevTable,\n keysRestoredByTheirOwnInverse,\n warnings,\n primaryKeyName\n );\n if (inverse) inverted.push(...inverse);\n }\n\n return { operations: inverted, warnings };\n}\n\nconst foreignKeyIdentity = (tableName: string, fkName: string) =>\n `${tableName}\\u0000${fkName}`;\n\nfunction invertOperation(\n op: DiffOperation,\n previousSnapshot: SchemaSnapshot,\n findPrevTable: (name: string) => TableDef | undefined,\n keysRestoredByTheirOwnInverse: ReadonlySet<string>,\n warnings: string[],\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName\n): DiffOperation[] | null {\n switch (op.type) {\n case \"createTable\":\n warnings.push(\n `createTable \"${op.table.name}\" inverts to dropTable: rolling back drops the table and every row created after this migration. No data is preserved.`\n );\n return [{ type: \"dropTable\", tableName: op.table.name }];\n\n case \"dropTable\": {\n const table = findPrevTable(op.tableName);\n if (!table) {\n warnings.push(\n `Cannot invert dropTable \"${op.tableName}\": table not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropTable \"${op.tableName}\" was lossy: rolling back recreates the table structure but not its data.`\n );\n const foreignKeys = table.foreignKeys.filter(\n (fk) =>\n !keysRestoredByTheirOwnInverse.has(\n foreignKeyIdentity(table.name, fk.name)\n )\n );\n return [{ type: \"createTable\", table: { ...table, foreignKeys } }];\n }\n\n case \"renameTable\":\n return [{ type: \"renameTable\", from: op.to, to: op.from }];\n\n case \"addColumn\":\n return [\n {\n type: \"dropColumn\",\n tableName: op.tableName,\n columnName: op.column.name,\n },\n ];\n\n case \"dropColumn\": {\n const table = findPrevTable(op.tableName);\n const column = table?.columns.find((c) => c.name === op.columnName);\n if (!column) {\n warnings.push(\n `Cannot invert dropColumn \"${op.tableName}.${op.columnName}\": column not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropColumn \"${op.tableName}.${op.columnName}\" was lossy: rolling back restores the column but not its data.`\n );\n return [{ type: \"addColumn\", tableName: op.tableName, column }];\n }\n\n case \"renameColumn\":\n return [\n {\n type: \"renameColumn\",\n tableName: op.tableName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"alterColumn\":\n return [\n {\n type: \"alterColumn\",\n tableName: op.tableName,\n columnName: op.columnName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"createIndex\":\n return [\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: op.index.name,\n ...(op.index.raw ? { raw: true } : {}),\n },\n ];\n\n case \"dropIndex\": {\n const table = findPrevTable(op.tableName);\n const index = table?.indexes.find((i) => i.name === op.indexName);\n if (!index) {\n warnings.push(\n `Cannot invert dropIndex \"${op.indexName}\" on \"${op.tableName}\": index not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createIndex\", tableName: op.tableName, index }];\n }\n\n case \"addForeignKey\":\n return [\n { type: \"dropForeignKey\", tableName: op.tableName, fkName: op.fk.name },\n ];\n\n case \"dropForeignKey\": {\n const table = findPrevTable(op.tableName);\n const fk = table?.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n warnings.push(\n `Cannot invert dropForeignKey \"${op.fkName}\" on \"${op.tableName}\": foreign key not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"addForeignKey\", tableName: op.tableName, fk }];\n }\n\n case \"addUniqueConstraint\":\n return [\n {\n type: \"dropUniqueConstraint\",\n tableName: op.tableName,\n constraintName: op.constraint.name,\n },\n ];\n\n case \"dropUniqueConstraint\": {\n const table = findPrevTable(op.tableName);\n const constraint = table?.uniqueConstraints.find(\n (u) => u.name === op.constraintName\n );\n if (!constraint) {\n warnings.push(\n `Cannot invert dropUniqueConstraint \"${op.constraintName}\" on \"${op.tableName}\": constraint not found in previous snapshot.`\n );\n return null;\n }\n return [\n { type: \"addUniqueConstraint\", tableName: op.tableName, constraint },\n ];\n }\n\n case \"addPrimaryKey\":\n return [\n {\n type: \"dropPrimaryKey\",\n tableName: op.tableName,\n constraintName: primaryKeyName(op.tableName, op.primaryKey.name),\n },\n ];\n\n case \"dropPrimaryKey\": {\n const table = findPrevTable(op.tableName);\n if (!table?.primaryKey) {\n warnings.push(\n `Cannot invert dropPrimaryKey on \"${op.tableName}\": primary key not found in previous snapshot.`\n );\n return null;\n }\n return [\n {\n type: \"addPrimaryKey\",\n tableName: op.tableName,\n primaryKey: table.primaryKey,\n },\n ];\n }\n\n case \"createEnum\":\n return [{ type: \"dropEnum\", enumName: op.enumDef.name }];\n\n case \"dropEnum\": {\n const enumDef = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!enumDef) {\n warnings.push(\n `Cannot invert dropEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createEnum\", enumDef }];\n }\n\n case \"alterEnum\": {\n const prevEnum = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!prevEnum) {\n warnings.push(\n `Cannot invert alterEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n if (op.removeValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" removed values [${op.removeValues.join(\", \")}]: rolling back restores the values but not replaced row data.`\n );\n }\n if (op.addValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" rollback removes values [${op.addValues.join(\", \")}]: rows using them will fail unless remapped manually.`\n );\n }\n return [\n {\n type: \"alterEnum\",\n enumName: op.enumName,\n addValues: op.removeValues,\n removeValues: op.addValues,\n newValues: prevEnum.values,\n dependentColumns: op.dependentColumns,\n },\n ];\n }\n\n default:\n warnings.push(\"Cannot invert an unknown generated operation.\");\n return null;\n }\n}\n","/**\n * Exact SQL framing for Migration V1.\n *\n * The blob is the human review artifact. Execution slices UTF-8 byte ranges.\n * There is no delimiter parser, breakpoint marker, or comment search.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { decodeUtf8, type Sha256 } from \"./identity\";\nimport { encodeSqlBlob } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationSqlRangeV1 } from \"./v1-types\";\n\nconst DISPLAY_SEPARATOR = new TextEncoder().encode(\"\\n\\n\");\n\nexport function encodeSqlText(text: string): Uint8Array {\n if (text.includes(\"\\r\")) {\n throw new MigrationError(\n \"Manual SQL fragments containing carriage returns are refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (text.startsWith(\"\\uFEFF\")) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return new TextEncoder().encode(text);\n}\n\nexport function composeSqlBlob(fragments: readonly string[]): {\n bytes: Uint8Array;\n ranges: MigrationSqlRangeV1[];\n sqlHash: Sha256;\n} {\n const encoded = fragments.map(encodeSqlText);\n let total = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) total += DISPLAY_SEPARATOR.length;\n total += encoded[i]!.length;\n }\n const bytes = new Uint8Array(total);\n const ranges: MigrationSqlRangeV1[] = [];\n let offset = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) {\n bytes.set(DISPLAY_SEPARATOR, offset);\n offset += DISPLAY_SEPARATOR.length;\n }\n const fragment = encoded[i]!;\n bytes.set(fragment, offset);\n ranges.push({\n dispatchId: \"\",\n offset,\n length: fragment.length,\n });\n offset += fragment.length;\n }\n return {\n bytes,\n sqlHash: encodeSqlBlob(bytes),\n ranges,\n };\n}\n\nexport function validateSqlRanges(\n bytes: Uint8Array,\n dispatches: readonly MigrationDispatchV1[]\n): void {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes.includes(0x0d)) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8/LF without carriage returns\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n decodeUtf8(bytes);\n } catch {\n throw new MigrationError(\n \"SQL blobs must be valid UTF-8\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const sqlHash = encodeSqlBlob(bytes);\n const unique: MigrationDispatchV1[] = [];\n const seen = new Set<string>();\n for (const dispatch of dispatches) {\n if (seen.has(dispatch.dispatchId)) continue;\n seen.add(dispatch.dispatchId);\n unique.push(dispatch);\n }\n const ordered = unique.sort(\n (left, right) => left.offset - right.offset || left.length - right.length\n );\n let previousEnd = 0;\n for (let index = 0; index < ordered.length; index++) {\n const dispatch = ordered[index]!;\n if (dispatch.sqlHash !== sqlHash) {\n throw new MigrationError(\n \"Dispatch sqlHash does not match the SQL blob\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (\n !(\n Number.isSafeInteger(dispatch.offset) &&\n Number.isSafeInteger(dispatch.length)\n ) ||\n dispatch.offset < 0 ||\n dispatch.length < 0\n ) {\n throw new MigrationError(\n \"SQL ranges must use non-negative safe integers\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (dispatch.offset + dispatch.length > bytes.length) {\n throw new MigrationError(\n \"SQL range exceeds the blob\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (index === 0) {\n if (dispatch.offset !== 0) {\n throw new MigrationError(\n \"SQL ranges must begin at byte zero\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else {\n const expectedOffset = previousEnd + DISPLAY_SEPARATOR.length;\n if (dispatch.offset !== expectedOffset) {\n throw new MigrationError(\n dispatch.offset < expectedOffset\n ? \"SQL ranges overlap or omit their separator\"\n : \"SQL ranges contain an unclaimed gap\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes[previousEnd] !== 0x0a || bytes[previousEnd + 1] !== 0x0a) {\n throw new MigrationError(\n \"SQL range separators must be exactly two newline bytes\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n previousEnd = dispatch.offset + dispatch.length;\n }\n if (ordered.length === 0) {\n if (bytes.length === 0) return;\n throw new MigrationError(\n \"A SQL blob without dispatches must be empty\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (previousEnd === bytes.length) return;\n if (previousEnd + 1 === bytes.length && bytes[previousEnd] === 0x0a) {\n return;\n }\n throw new MigrationError(\n \"SQL blobs contain bytes after the final range\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nexport function sliceDispatch(\n bytes: Uint8Array,\n dispatch: MigrationDispatchV1\n): string {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n bytes.subarray(dispatch.offset, dispatch.offset + dispatch.length)\n );\n}\n\nconst MYSQL_DELIMITER = /(^|\\s)DELIMITER\\s/i;\n\nexport function refuseMysqlDelimiter(text: string): void {\n if (MYSQL_DELIMITER.test(text)) {\n throw new MigrationError(\n \"MySQL DELIMITER is a client command, not server SQL\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n","/**\n * The ONE lexical classifier for migration-artifact execution safety.\n *\n * VibORM opens an enclosing boundary around every artifact it executes: an\n * apply/down/reset transaction on PostgreSQL, and a session lock on both\n * PostgreSQL and MySQL. This module refuses the DIRECT statements that would\n * end or reframe it — a `COMMIT` inside an artifact ends the rollback scope\n * VibORM promised, and a `RELEASE_LOCK`/`pg_advisory_unlock` inside one frees\n * the lock that is excluding every other migration command (§3.5).\n *\n * It refuses direct lexical controls and is NOT a sandbox for procedural or\n * dynamic SQL. That distinction is the module's contract, not a caveat on it.\n * Manual migration SQL is trusted last-mile authority: its author owns what it\n * does, this included. A dollar-quoted body is DATA to this scan — it has to\n * be, or every ordinary `CREATE FUNCTION` is refused — and the same bytes are a\n * statement to the server, so `DO $$ BEGIN PERFORM pg_advisory_unlock_all();\n * END $$` frees the migration lock while the command holds it. A pre-existing\n * safe-named function, a function the artifact creates, and `EXECUTE` over a\n * built string are the same escape by another route. It is executed rather than\n * asserted: `tests/unit/migrations/pinned-migration-session.core.test.ts` runs\n * that exact artifact through `apply()` on a real PostgreSQL and pins the lock\n * gone. Do not answer a procedural escape with another spelling here — the\n * enumeration does not close, and every addition costs valid author SQL.\n *\n * What the refusals do buy is the ACCIDENT and the audit: an author who typed a\n * `COMMIT` or a `pg_advisory_unlock(...)` straight into an artifact learns\n * before any of it runs, and a deliberate escape has to be WRITTEN as one, in\n * the artifact, where a reviewer sees it. The deliberate case is answered\n * afterwards instead, by the release proof in `pinned-session.ts`: a lock the\n * command acquired and no longer holds fails that command loudly and discards\n * the session, rather than letting it report a migration that ran outside the\n * boundary it published.\n *\n * The scanner is comment- and string-safe, which is the whole reason this is a\n * classifier rather than a regular expression: `-- COMMIT`, `'COMMIT'`, a\n * column named `\"commit\"`, and a dollar-quoted body that merely mentions\n * `pg_advisory_unlock` are all valid SQL and must stay valid. Only executable\n * tokens are classified.\n *\n * Executable is not enough on its own, because a spelling is not a role. A\n * table named `pg_advisory_notes`, a column named `release_lock`, and MySQL's\n * `@autocommit` user variable are executable tokens that call nothing and set\n * nothing, and refusing them refused valid author SQL over a resemblance. So\n * every scanned word carries the role its POSITION gives it, and the lock\n * refusals key on a call — one owner deciding it for bare and quoted\n * identifiers alike.\n *\n * Comment- and string-safety is DIALECT-SPECIFIC, so the scan takes the dialect\n * rather than reading one lexical grammar into both servers. Every arm below\n * that branches exists because the two servers disagree about what is data:\n * MySQL's `#` line comments and its `--` whitespace rule, its executable\n * `/*!…` comments whose contents the server RUNS, its backslash escapes inside\n * string literals, PostgreSQL's `E'…'` escape strings, and PostgreSQL's nested\n * block comments. Reading one server's grammar on the other either blinds the\n * scanner to a real statement or refuses an artifact that is entirely a\n * comment.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationTarget } from \"./types\";\n\n/**\n * Statement-leading PHRASES that open, close, or reframe a transaction.\n *\n * The test is on the LEADING word because that is what makes the word a\n * statement rather than a name: `END` opens nothing in `CREATE TABLE end_state`,\n * and `RELEASE` is only `RELEASE SAVEPOINT` at the start of a statement.\n *\n * `PREPARE TRANSACTION` is the entry that needs a second word, and it needs it\n * in both directions. It DETACHES the running transaction from this session for\n * a later `COMMIT PREPARED`, so where the server allows it at all\n * (`max_prepared_transactions > 0`) the entry's DDL is left unresolved while\n * the tracking write that records it lands in the autocommit that follows. And\n * `PREPARE plan AS SELECT …` begins with the same word while controlling\n * nothing, so refusing the leader alone would ban ordinary author SQL. The\n * phrase is the unit of the test; `PREPARE` alone is not an entry. Its two\n * siblings need no entry of their own — `COMMIT PREPARED` and\n * `ROLLBACK PREPARED` already lead with a refused word.\n */\nconst POSTGRES_TRANSACTION_LEADERS = new Set([\n \"ABORT\",\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"PREPARE TRANSACTION\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n]);\n\nconst MYSQL_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"LOCK\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n \"UNLOCK\",\n \"XA\",\n]);\n\n/** SQLite controls over the transaction boundary owned by the migration run. */\nconst SQLITE_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n]);\n\n/**\n * PostgreSQL's advisory-lock family, by prefix.\n *\n * A prefix rather than a list because the family is closed by naming\n * convention and open by variant: session and transaction scope, shared and\n * exclusive, blocking and `try_`. Enumerating them invites the one that is\n * missed.\n *\n * Being this wide is only safe because the prefix is read at a CALL and nowhere\n * else. `pg_advisory_notes` is a table an author may have kept for years, and\n * `pg_advisory_note` a column in it; the family's spelling makes neither of them\n * a function, and refusing them refused valid SQL over a resemblance.\n */\nconst POSTGRES_ADVISORY_PREFIXES = [\"PG_ADVISORY\", \"PG_TRY_ADVISORY\"];\n\n/**\n * Words after which an identifier is the NAME of the object a statement\n * defines, never a function it calls — even with a `(` right behind it.\n *\n * `CREATE TABLE pg_advisory_notes (id INT)` opens a COLUMN list, and\n * `CREATE FUNCTION \"pg_advisory_unlock_all\"()` an argument declaration; neither\n * calls anything. These are the only words a `(`-followed identifier can sit\n * behind without being a call, and the two servers agree on them: neither has\n * an expression in which a called function's name follows the bare word TABLE,\n * VIEW, FUNCTION, PROCEDURE, AGGREGATE, or the EXISTS of `IF NOT EXISTS`.\n *\n * MySQL's inline index names — `UNIQUE KEY get_lock (id)` — are the one\n * definition this set does not reach, and `KEY`/`INDEX` stay out of it on\n * purpose: unlike the six above, each is also an ordinary column name, so the\n * set would start being reached from expressions and exempt what follows one.\n * A refused index name costs its author a rename; that exemption costs the\n * boundary.\n */\nconst OBJECT_NAME_KEYWORDS = new Set([\n \"AGGREGATE\",\n \"EXISTS\",\n \"FUNCTION\",\n \"PROCEDURE\",\n \"TABLE\",\n \"VIEW\",\n]);\n\n/** MySQL's named-lock family: acquisition, release, and both probes. */\nconst MYSQL_LOCK_FUNCTIONS = new Set([\n \"GET_LOCK\",\n \"IS_FREE_LOCK\",\n \"IS_USED_LOCK\",\n \"RELEASE_ALL_LOCKS\",\n \"RELEASE_LOCK\",\n]);\n\n/** The tag body of a PostgreSQL dollar quote: `$tag$`. */\nconst DOLLAR_TAG_PART = /[A-Za-z0-9_]/;\nconst WORD_START = /[A-Za-z_]/;\nconst WORD_PART = /\\w/;\nconst WHITESPACE = /\\s/;\n/** The optional server-version prefix of a MySQL executable comment. */\nconst VERSION_DIGIT = /[0-9]/;\n\n/**\n * MySQL's SYSTEM-variable sigil, which the bare spelling of the same name also\n * reaches: `SET @@autocommit = 0` and `SET autocommit = 0` change one setting,\n * so the sigil folds away and both meet the same refusal.\n *\n * ONE `@` does not fold. `@autocommit` is a user variable — a slot with a name\n * that happens to read like the setting, which no server behavior consults —\n * and folding it refused `SET @autocommit = 0`, valid MySQL, as a commit-\n * boundary change. `SELECT @release_lock` was refused as a lock call the same\n * way.\n */\nconst SYSTEM_VARIABLE_SIGIL = /^@@/;\n\n/**\n * The dialects this classifier reads.\n */\nexport type ClassifiedDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\n/**\n * The characters that make a bare word, per dialect.\n *\n * `@` is the whole difference and it is not cosmetic. In MySQL the sigil is\n * part of the identifier — `@name` and `@@name` are two different names, and\n * neither is the bare one. PostgreSQL has no variable sigil at all: `@` is an\n * operator character there, so joining it to the word behind it would read\n * `SELECT @pg_advisory_unlock(1)` as one name the advisory prefix no longer\n * matches, hiding a call the server still makes.\n */\nconst WORD_CHARACTERS: Record<\n ClassifiedDialect,\n { readonly start: RegExp; readonly part: RegExp }\n> = {\n mysql: { start: /[A-Za-z_@]/, part: /[A-Za-z0-9_$@]/ },\n postgresql: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n sqlite: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n};\n\n/**\n * One executable word and the syntactic role its POSITION gives it.\n *\n * The role is the point. A lock-function refusal that reads spelling alone\n * refuses `CREATE TABLE get_lock (id INT)` and `CREATE TABLE t (release_lock\n * INT)`, which call nothing and are the author's to keep. `calls` is decided\n * once, by {@link callsArguments}, for bare and quoted identifiers alike.\n */\ntype ScannedWord = {\n /**\n * The folded spelling. A bare word arrives uppercased, minus MySQL's system\n * sigil; a called quoted identifier arrives in its own lowercase spelling,\n * which is the only one that names a PostgreSQL built-in.\n */\n readonly text: string;\n /** Whether an argument list opens behind it, in a position that may call. */\n readonly calls: boolean;\n};\n\n/**\n * What sits immediately in front of the cursor, whitespace and comments apart.\n *\n * `qualifier` is the `.` of a qualified name, and it is why the role of\n * `alpha.pg_advisory_notes` is decided by the word in front of `alpha`:\n * `CREATE TABLE` defines that name and `SELECT` calls it, and the qualifier\n * between them changes neither.\n */\ntype PrecedingToken = \"word\" | \"qualifier\" | \"other\";\n\n/**\n * The EXECUTABLE bare words of an artifact chunk, grouped per statement.\n *\n * Grouping on the top-level `;` is load-bearing, not cosmetic: VibORM's\n * artifact parser splits on its own breakpoint marker, so ONE parsed chunk\n * routinely holds several SQL statements. A classifier that only looked at the\n * first word of the chunk would read `CREATE TABLE t; COMMIT;` as a `CREATE`\n * and let the `COMMIT` through — which is precisely the statement that ends the\n * transaction VibORM promised.\n *\n * Quoted identifiers are excluded rather than included WHEN THEY ARE NAMED: a\n * table or column the author quoted is a name, never a keyword, so\n * `CREATE TABLE \"commit\"` and a column named `` `get_lock` `` stay valid. Text\n * inside comments, single-quoted literals and PostgreSQL dollar-quoted bodies\n * is skipped for the same reason — it is data, not a statement.\n *\n * A quoted identifier the statement CALLS is the exception: quoting a\n * function's name does not stop PostgreSQL calling it, so\n * `pg_catalog.\"pg_advisory_unlock_all\"()` frees the lock excluding every other\n * migration command while every word the scan retained says\n * `SELECT pg_catalog`. Which of the two a quoted run is comes from\n * {@link callsArguments}, the same owner that decides it for bare words.\n *\n * The dialect decides which runs are data. A MySQL executable comment is the\n * clearest case: its contents are not data at all, and the server runs them.\n */\nexport function readExecutableStatements(\n sql: string,\n dialect: ClassifiedDialect\n): string[][] {\n return scanStatements(sql, dialect).map((words) =>\n words.map((word) => word.text)\n );\n}\n\n/**\n * The scan itself: executable words with the role their position gives them,\n * grouped per statement.\n *\n * {@link readExecutableStatements} is this without the roles, which is all the\n * enum-boundary question needs; {@link classifyOne} needs them, because a\n * spelling in a name position is not the call it refuses.\n */\nfunction scanStatements(\n sql: string,\n dialect: ClassifiedDialect\n): ScannedWord[][] {\n const characters = WORD_CHARACTERS[dialect];\n const statements: ScannedWord[][] = [];\n let words: ScannedWord[] = [];\n let index = 0;\n let preceding: PrecedingToken = \"other\";\n /** The previous identifier RUN, whether or not the scan retained it. */\n let previousWord: string | undefined;\n /** The word governing the identifier position the cursor stands in. */\n let governing: string | undefined;\n\n while (index < sql.length) {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n\n if (char === \"-\" && next === \"-\" && opensLineComment(sql, index, dialect)) {\n index = skipLine(sql, index);\n continue;\n }\n // MySQL's second line-comment spelling. PostgreSQL has none: `#` is an\n // operator character there, and skipping to end of line on it would blind\n // the scan to whatever followed on that line.\n if (dialect === \"mysql\" && char === \"#\") {\n index = skipLine(sql, index);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n if (dialect === \"mysql\" && sql[index + 2] === \"!\") {\n index = openExecutableComment(sql, index);\n continue;\n }\n index = skipBlockComment(sql, index, dialect);\n continue;\n }\n if (char === \"'\" || char === '\"' || char === \"`\") {\n const quoteEnd = skipQuoted(\n sql,\n index,\n char,\n escapesWithBackslash(dialect, char)\n );\n governing = governingWord(preceding, previousWord, governing);\n const name = readQuotedIdentifier(sql, index, quoteEnd, char, dialect);\n if (name !== null && callsArguments(sql, quoteEnd, governing, dialect)) {\n words.push({ text: name, calls: true });\n }\n // A quoted run ends the reach of whatever governed it: nothing that\n // follows a closing quote directly is the name of a defined object.\n preceding = \"other\";\n index = quoteEnd;\n continue;\n }\n if (dialect === \"sqlite\" && char === \"[\") {\n index = skipBracketQuoted(sql, index);\n preceding = \"other\";\n continue;\n }\n if (dialect === \"postgresql\" && char === \"$\") {\n const dollarEnd = skipDollarQuoted(sql, index);\n if (dollarEnd !== null) {\n index = dollarEnd;\n preceding = \"other\";\n continue;\n }\n }\n if (char === \";\") {\n if (words.length > 0) {\n statements.push(words);\n words = [];\n }\n index += 1;\n preceding = \"other\";\n continue;\n }\n if (characters.start.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && characters.part.test(sql.charAt(index))) {\n index += 1;\n }\n const text = sql\n .slice(start, index)\n .toUpperCase()\n .replace(SYSTEM_VARIABLE_SIGIL, \"\");\n // PostgreSQL's `E'…'` escape string. The `E` is the literal's prefix, not\n // a bare word, and it is the ONE PostgreSQL string form where a backslash\n // escapes the closing quote — reading it as a standard literal closes it\n // early at `\\'` and hides every statement up to the next quote.\n if (dialect === \"postgresql\" && text === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n preceding = \"other\";\n continue;\n }\n governing = governingWord(preceding, previousWord, governing);\n words.push({\n text,\n calls: callsArguments(sql, index, governing, dialect),\n });\n previousWord = text;\n preceding = \"word\";\n continue;\n }\n if (char.trim() !== \"\") {\n preceding = char === \".\" ? \"qualifier\" : \"other\";\n }\n index += 1;\n }\n\n if (words.length > 0) {\n statements.push(words);\n }\n return statements;\n}\n\n/**\n * The word that governs the identifier position at the cursor, or undefined\n * when no word reaches it.\n *\n * Directly in front of an identifier, a word governs it: the `TABLE` of\n * `CREATE TABLE get_lock (…)` says that name is being defined. Across a `.`\n * the governor is inherited rather than replaced, so a qualified name is\n * decided by whatever opened the chain — `CREATE TABLE alpha.pg_advisory_notes\n * (…)` defines, `SELECT pg_catalog.\"pg_advisory_unlock_all\"()` calls.\n *\n * Any other punctuation ends the reach, and that is the half that keeps the\n * exemption honest: a comma away from a column named `view`,\n * `SELECT view, \"pg_advisory_unlock\"(1)` is a call, and reading the previous\n * WORD alone admitted it as a definition.\n */\nfunction governingWord(\n preceding: PrecedingToken,\n previousWord: string | undefined,\n chainGovernor: string | undefined\n): string | undefined {\n if (preceding === \"word\") {\n return previousWord;\n }\n if (preceding === \"qualifier\") {\n return chainGovernor;\n }\n return undefined;\n}\n\n/**\n * The unquoted-equivalent spelling of a quoted identifier, or null when the\n * quoted run is a literal or a spelling no built-in answers to.\n *\n * PostgreSQL is the only dialect that reaches a decision here. MySQL's `\"` is a\n * STRING quote, so the same bytes are data there, and its backtick-quoted names\n * resolve to stored functions rather than to the built-in named-lock family —\n * `` SELECT `release_lock`('k') `` does not run MySQL's `RELEASE_LOCK`.\n *\n * A quoted identifier is CASE-SENSITIVE, so only the folded spelling names the\n * built-in: `\"PG_ADVISORY_UNLOCK_ALL\"` is a function PostgreSQL does not have,\n * and refusing it would ban a name over a call that cannot happen. The name is\n * returned in that folded (lowercase) spelling, which is also what keeps it out\n * of every keyword test in this module — bare words arrive uppercased.\n */\nfunction readQuotedIdentifier(\n sql: string,\n start: number,\n end: number,\n quote: string,\n dialect: ClassifiedDialect\n): string | null {\n if (dialect !== \"postgresql\" || quote !== '\"') {\n return null;\n }\n // An UNTERMINATED quote ran to the end of the input; nothing follows it, so\n // nothing calls it.\n if (end - start < 2 || sql[end - 1] !== '\"') {\n return null;\n }\n const name = sql.slice(start + 1, end - 1).replaceAll('\"\"', '\"');\n return name === name.toLowerCase() ? name : null;\n}\n\n/**\n * The ONE call-position owner: whether the identifier ending at `end` is CALLED\n * where it stands.\n *\n * Two halves, and both are needed. A governing keyword makes the identifier the\n * name of an object being defined, `(` behind it or not — that is what keeps\n * `CREATE TABLE pg_advisory_notes (id INT)` and\n * `CREATE TABLE \"pg_advisory_unlock_all\" (id INT)` valid, since both open a\n * column list. Otherwise an argument list has to actually open, modulo what\n * sits between a function's name and its `(`: whitespace is the obvious case\n * and comments are the one that matters, because\n * `pg_catalog.\"pg_advisory_unlock_all\"/**\\/()` is one call to the server and a\n * lookahead that stopped at the first non-space would read it as a name.\n *\n * A qualifier is not read: `myschema.\"pg_advisory_unlock\"()` is a call too,\n * because a `search_path` this classifier cannot see decides what that name\n * resolves to. Whitespace before the `(` is admitted on MySQL as well, where\n * only `IGNORE_SPACE` makes the server accept it — refusing a call the server\n * might make is the direction this classifier can afford to be wrong in.\n */\nfunction callsArguments(\n sql: string,\n end: number,\n governing: string | undefined,\n dialect: ClassifiedDialect\n): boolean {\n if (governing !== undefined && OBJECT_NAME_KEYWORDS.has(governing)) {\n return false;\n }\n let cursor = end;\n while (cursor < sql.length) {\n const char = sql.charAt(cursor);\n if (\n char === \"-\" &&\n sql[cursor + 1] === \"-\" &&\n opensLineComment(sql, cursor, dialect)\n ) {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (dialect === \"mysql\" && char === \"#\") {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (char === \"/\" && sql[cursor + 1] === \"*\") {\n cursor = skipBlockComment(sql, cursor, dialect);\n continue;\n }\n if (char.trim() !== \"\") {\n return char === \"(\";\n }\n cursor += 1;\n }\n return false;\n}\n\n/**\n * Whether the `--` at `start` opens a line comment.\n *\n * PostgreSQL's always does. MySQL's requires whitespace (or a control\n * character, or end of input) after the second dash, so\n * `SELECT 1--RELEASE_LOCK('viborm_migration_…')` is arithmetic over a REAL\n * function call there rather than a comment. Reading it as a comment hides\n * exactly the statement this classifier exists to refuse.\n */\nfunction opensLineComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): boolean {\n if (dialect !== \"mysql\") {\n return true;\n }\n const after = sql[start + 2];\n if (after === undefined) {\n return true;\n }\n return after.trim() === \"\" || after.charCodeAt(0) < 0x20;\n}\n\n/** Past SQLite's square-bracket identifier quote. */\nfunction skipBracketQuoted(sql: string, start: number): number {\n const end = sql.indexOf(\"]\", start + 1);\n return end < 0 ? sql.length : end + 1;\n}\n\n/** Past a line comment, including its newline. */\nfunction skipLine(sql: string, start: number): number {\n const lineEnd = sql.indexOf(\"\\n\", start);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\n/**\n * Past the OPENING of a MySQL executable comment (`/*!`, optionally followed by\n * a server-version prefix), leaving its contents to be scanned as statements.\n *\n * MySQL RUNS what is inside these — that is what they are for — so skipping\n * them the way an ordinary comment is skipped admits\n * `/*!50000 DO RELEASE_LOCK('viborm_migration_…')`, which frees the lock the\n * running command holds, and `/*!40101 SET AUTOCOMMIT=0`, which reframes the\n * commit boundary of everything after it. The closing delimiter needs no arm of\n * its own: neither of its characters starts a word.\n */\nfunction openExecutableComment(sql: string, start: number): number {\n let cursor = start + 3;\n while (cursor < sql.length && VERSION_DIGIT.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Past a block comment.\n *\n * PostgreSQL NESTS them, so an outer comment holding a complete inner one is\n * entirely a comment there; stopping at the first close would leave the outer\n * comment's tail scanned as SQL and refuse a valid artifact over a `COMMIT` no\n * server ever sees. MySQL does not nest, so its depth never rises and it stops\n * at the first close — which is also where the server stops.\n */\nfunction skipBlockComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length) {\n if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n if (depth === 0) {\n return cursor;\n }\n continue;\n }\n if (\n dialect === \"postgresql\" &&\n sql[cursor] === \"/\" &&\n sql[cursor + 1] === \"*\"\n ) {\n depth += 1;\n cursor += 2;\n continue;\n }\n cursor += 1;\n }\n return sql.length;\n}\n\n/**\n * Whether a backslash escapes the next character inside this quote.\n *\n * MySQL's default mode treats `\\` as an escape inside both string quotes, so\n * `'a\\'b'` is ONE literal there; its backtick identifiers take no escapes.\n * PostgreSQL's strings are standard-conforming, so a backslash is an ordinary\n * character in `'…'` and `\"…\"` — its one escape-bearing form, `E'…'`, is\n * recognised at the `E` in the scan above.\n */\nfunction escapesWithBackslash(\n dialect: ClassifiedDialect,\n quote: string\n): boolean {\n return dialect === \"mysql\" && quote !== \"`\";\n}\n\n/**\n * Past a quoted run, honoring the doubling escape every admitted dialect uses\n * (`''`, `\"\"`, ` `` `) and, where the dialect has them, backslash escapes. An\n * unterminated quote consumes the rest of the statement, which is what a\n * database would also do with it.\n */\nfunction skipQuoted(\n sql: string,\n start: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\n/**\n * Past a PostgreSQL dollar-quoted body (`$$…$$`, `$tag$…$tag$`), or null when\n * this `$` does not open one.\n *\n * Function bodies are the common shape of a hand-written PostgreSQL artifact,\n * and their contents are a string, not statements. Reading them as statements\n * would refuse a perfectly ordinary `CREATE FUNCTION` whose body happens to\n * contain `COMMIT` or `BEGIN`.\n */\nfunction skipDollarQuoted(sql: string, start: number): number | null {\n let cursor = start + 1;\n while (cursor < sql.length && DOLLAR_TAG_PART.test(sql.charAt(cursor))) {\n cursor += 1;\n }\n if (sql[cursor] !== \"$\") {\n return null;\n }\n const tag = sql.slice(start, cursor + 1);\n const bodyEnd = sql.indexOf(tag, cursor + 1);\n return bodyEnd < 0 ? sql.length : bodyEnd + tag.length;\n}\n\n/** The refusal a classified statement raises, naming its artifact and cause. */\nfunction refuse(\n artifact: string,\n statement: string,\n reason: string\n): MigrationError {\n return new MigrationError(\n `Migration \"${artifact}\" contains a statement VibORM cannot execute inside the boundary it publishes: ${reason}. ` +\n `The offending statement begins \"${statement.trim().slice(0, 80)}\". ` +\n \"Manual migration SQL owns its object effects; VibORM refuses only the direct controls over its rollback scope, its migration lock, and its tracking boundary, so write the migration without them.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n}\n\nconst SURREAL_QUOTES: Readonly<Record<string, string>> = {\n \"'\": \"'\",\n '\"': '\"',\n \"`\": \"`\",\n \"\\u27E8\": \"\\u27E9\",\n};\nconst SURREAL_TRANSACTION_WORDS = new Set([\"BEGIN\", \"COMMIT\", \"CANCEL\"]);\n\n/**\n * Refuses an artifact that DIRECTLY reframes the execution boundary.\n *\n * Runs BEFORE any of the artifact's effects, so a refusal leaves the estate\n * exactly as it was. SQLite has no advisory lock, but the migration runner\n * still owns its transaction and savepoint boundary.\n */\nexport function assertArtifactExecutionSafe(\n statements: readonly string[],\n dialect: MigrationTarget[\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"surrealql\") {\n for (const chunk of statements) assertSurrealStatementSafe(chunk, artifact);\n return;\n }\n const sqlDialect = dialect as ClassifiedDialect;\n for (const chunk of statements) {\n const scanned = scanStatements(chunk, sqlDialect);\n if (dialect === \"sqlite\" && isSqliteTrigger(scanned[0])) {\n continue;\n }\n for (const words of scanned) {\n classifyOne(words, chunk, sqlDialect, artifact);\n }\n }\n}\n\n/**\n * SurrealQL's own lexical grammar, kept apart from SQL's: a comment is `--`, `//`, `#`\n * or a block, a string or a name is quoted four ways, and a block is `{ … }`.\n * `visit` sees each bare word, uppercased, whether it opens its statement, and\n * how deep in brackets it stands; `end` sees each top-level `;`.\n */\nfunction scanSurreal(\n chunk: string,\n visit: (word: string, atStart: boolean, depth: number) => void,\n end: () => void = () => undefined\n): void {\n let depth = 0;\n let atStart = true;\n for (let index = 0; index < chunk.length; ) {\n const char = chunk.charAt(index);\n const two = chunk.slice(index, index + 2);\n if (two === \"--\" || two === \"//\" || char === \"#\") {\n const close = chunk.indexOf(\"\\n\", index);\n index = close < 0 ? chunk.length : close + 1;\n continue;\n }\n if (two === \"/*\") {\n const close = chunk.indexOf(\"*/\", index + 2);\n index = close < 0 ? chunk.length : close + 2;\n continue;\n }\n const closing = SURREAL_QUOTES[char];\n if (closing) {\n index += 1;\n while (index < chunk.length && chunk.charAt(index) !== closing)\n index += chunk.charAt(index) === \"\\\\\" ? 2 : 1;\n index += 1;\n atStart = false;\n continue;\n }\n if (char === \"(\" || char === \"[\" || char === \"{\") depth += 1;\n else if (char === \")\" || char === \"]\" || char === \"}\") depth -= 1;\n if (char === \";\" && depth === 0) {\n atStart = true;\n end();\n index += 1;\n continue;\n }\n if (WORD_START.test(char)) {\n let stop = index + 1;\n while (stop < chunk.length && WORD_PART.test(chunk.charAt(stop)))\n stop += 1;\n visit(chunk.slice(index, stop).toUpperCase(), atStart, depth);\n atStart = false;\n index = stop;\n continue;\n }\n if (!WHITESPACE.test(char)) atStart = false;\n index += 1;\n }\n}\n\n/** A transaction control at the top level would end the boundary the command opened. */\nfunction assertSurrealStatementSafe(chunk: string, artifact: string): void {\n scanSurreal(chunk, (word, atStart, depth) => {\n if (atStart && depth === 0 && SURREAL_TRANSACTION_WORDS.has(word))\n throw refuse(\n artifact,\n chunk,\n `the transaction-control statement \"${word}\", which would end the transaction the command runs it in`\n );\n });\n}\n\n/**\n * The executable bare words of a SurrealQL chunk, grouped per top-level\n * statement: what {@link readExecutableStatements} is for SQL. A quoted name,\n * a string and a comment hold none.\n */\nexport function readSurrealStatements(chunk: string): string[][] {\n const statements: string[][] = [[]];\n scanSurreal(\n chunk,\n (word) => statements.at(-1)!.push(word),\n () => statements.push([])\n );\n return statements.filter((words) => words.length > 0);\n}\n\n/**\n * A SQLite trigger body uses `BEGIN … END` as grammar, not transaction control.\n * Stock SQLite execution accepts one prepared statement per dispatch, so the\n * whole trigger is the provider statement and its body controls stay inside it.\n */\nfunction isSqliteTrigger(first: readonly ScannedWord[] | undefined): boolean {\n if (first?.[0]?.text !== \"CREATE\") {\n return false;\n }\n const second = first[1]?.text;\n return (\n second === \"TRIGGER\" ||\n ((second === \"TEMP\" || second === \"TEMPORARY\") &&\n first[2]?.text === \"TRIGGER\")\n );\n}\n\n/**\n * The refusable leading phrase of one statement, or undefined.\n *\n * Two lookups, because an entry is one word or two and the longer one decides:\n * `COMMIT PREPARED 'g'` is refused for its `COMMIT`, `PREPARE TRANSACTION 'g'`\n * for the pair, and `PREPARE plan AS …` for neither. These are the statement's\n * EXECUTABLE words, so the pair is already case-folded and already free of\n * whatever whitespace or comment the author wrote between the two.\n */\nfunction leadingTransactionCommand(\n words: readonly ScannedWord[],\n leaders: ReadonlySet<string>\n): string | undefined {\n const first = words[0]?.text;\n const second = words[1]?.text;\n const pair = second === undefined ? undefined : `${first} ${second}`;\n if (pair !== undefined && leaders.has(pair)) {\n return pair;\n }\n return first !== undefined && leaders.has(first) ? first : undefined;\n}\n\n/** Classifies ONE statement's executable words. */\nfunction classifyOne(\n words: readonly ScannedWord[],\n statement: string,\n dialect: ClassifiedDialect,\n artifact: string\n): void {\n // `scanStatements` keeps only statements with at least one word.\n const leader = words[0]!.text;\n\n if (dialect === \"postgresql\") {\n const control = leadingTransactionCommand(\n words,\n POSTGRES_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would end the transaction this migration runs inside`\n );\n }\n // One fold reaches both forms the scan retains: a bare word arrives\n // uppercased, and a called quoted identifier arrives in its own folded\n // spelling, which is the only spelling that names the built-in.\n const advisory = words.find(\n (word) =>\n word.calls &&\n POSTGRES_ADVISORY_PREFIXES.some((prefix) =>\n word.text.toUpperCase().startsWith(prefix)\n )\n );\n if (advisory !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${advisory.text.toLowerCase()}\", which would change the advisory-lock state this migration command holds`\n );\n }\n return;\n }\n\n if (dialect === \"sqlite\") {\n const control = leadingTransactionCommand(\n words,\n SQLITE_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would change the transaction boundary this migration runs inside`\n );\n }\n return;\n }\n\n const control = leadingTransactionCommand(words, MYSQL_TRANSACTION_LEADERS);\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction- or table-lock statement \"${control}\", which would change the boundary this migration runs inside`\n );\n }\n // `SET autocommit` reframes every following statement's commit boundary, and\n // it is a SET, not a leader of its own — hence the word test. The scan folds\n // `@@autocommit` to that same word and leaves `@autocommit` under its own\n // name, so the setting is reached under both its spellings and the user\n // variable under neither.\n if (leader === \"SET\" && words.some((word) => word.text === \"AUTOCOMMIT\")) {\n throw refuse(\n artifact,\n statement,\n \"a change to `autocommit`, which would change the commit boundary of every statement that follows\"\n );\n }\n const named = words.find(\n (word) => word.calls && MYSQL_LOCK_FUNCTIONS.has(word.text)\n );\n if (named !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${named.text.toLowerCase()}\", which would change the named-lock state this migration command holds`\n );\n }\n}\n\n/**\n * Whether a PostgreSQL migration edge must commit before the next one runs.\n *\n * `ALTER TYPE ... ADD VALUE` cannot be used by a later statement of the\n * transaction that added it (55P04), so apply, rollback and reset end their\n * shared transaction after such an edge. Reset creates the type in its own\n * transaction, but only PostgreSQL 17 and later exempt such a type's values.\n *\n * The question is PostgreSQL's alone — no other dialect has the statement — so\n * the scan reads PostgreSQL's lexical grammar rather than taking a dialect its\n * callers would each have to answer for.\n */\nexport function needsEnumAdditionCommitBoundary(\n statements: readonly string[]\n): boolean {\n for (const chunk of statements) {\n for (const words of readExecutableStatements(chunk, \"postgresql\")) {\n if (\n words[0] === \"ALTER\" &&\n words[1] === \"TYPE\" &&\n words.includes(\"ADD\") &&\n words.includes(\"VALUE\")\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** A PostgreSQL statement that changes the schema. */\nconst SCHEMA_CHANGES = new Set([\"ALTER\", \"COMMENT\", \"CREATE\", \"DROP\"]);\n/**\n * Statements that are neither schema changes nor planned against the\n * committed schema on Neki: each ran there as on PostgreSQL after any schema\n * change of its own transaction (measured: see {@link catalogCommitBoundaries}).\n */\nconst UNPLANNED = new Set([\"GRANT\", \"SET\", \"TRUNCATE\"]);\n/** A block, a procedure or a prepared statement: what it changes is not in its text. */\nconst OPAQUE = new Set([\"CALL\", \"DO\", \"EXECUTE\"]);\n\nconst NAME_START = /[A-Za-z_]/;\nconst NAME_PART = /[A-Za-z0-9_$]/;\nconst NAME_UNSAFE = /[^A-Za-z0-9_$]/g;\nconst LEADING_WORDS = /^([A-Za-z_]+)(?:\\s+([A-Za-z_]+))?/;\nconst NAME = String.raw`(?:\"[^\"]*\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${NAME}(?:\\s*\\.\\s*${NAME}){0,2}`;\n/** A parenthesized run, three levels deep; the structural text has no literal. */\nconst GROUP = String.raw`\\((?:[^()]|\\((?:[^()]|\\([^()]*\\))*\\))*\\)`;\nconst LAST_NAME = new RegExp(`${NAME}$`);\nconst ALTER_TABLE = new RegExp(\n String.raw`^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})\\s*\\*?\\s*([\\s\\S]*)$`,\n \"i\"\n);\nconst TABLE_PREFIX = String.raw`^CREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*`;\nconst CREATE_TABLE = new RegExp(\n String.raw`${TABLE_PREFIX}TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(${QUALIFIED})`,\n \"i\"\n);\n/** `CREATE TABLE … AS` and `CREATE MATERIALIZED VIEW … AS` plan a query. */\nconst CREATE_AS = new RegExp(\n String.raw`${TABLE_PREFIX}(?:TABLE|MATERIALIZED\\s+VIEW)\\b[\\s\\S]*\\bAS\\s+(?:SELECT|WITH|TABLE|VALUES|EXECUTE)\\b`,\n \"i\"\n);\nconst RENAME_TO = new RegExp(String.raw`^RENAME\\s+TO\\s+(${NAME})\\s*$`, \"i\");\n/**\n * The unregistered-relation refusal's actions (NK316): a type change, a\n * column rename, a column drop, a move to another schema.\n */\nconst UNREGISTERED_ACTION = new RegExp(\n String.raw`(?:^|,)\\s*(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DATA\\s+)?TYPE\\b|RENAME\\s+(?:COLUMN\\s+)?(?!(?:TO|CONSTRAINT)\\b)${NAME}\\s+TO\\b|DROP\\s+(?:COLUMN\\s+)?(?!(?:CONSTRAINT|DEFAULT|NOT|IDENTITY|EXPRESSION)\\b)(?:IF\\s+EXISTS\\s+)?${NAME}|SET\\s+SCHEMA\\b)`,\n \"i\"\n);\n/**\n * The `ALTER TABLE` actions Neki's planner needs no commit for: what they\n * change is enforced where the row is written, never resolved where the\n * statement is planned (defaults, NOT NULL, CHECK and foreign keys, a\n * validated constraint). A relation created or dropped, an index or a\n * constraint's own included, is not one: a literal naming it resolves\n * against the committed schema (`to_regclass`, `::regclass`, measured stale).\n */\nconst SEEN_ACTION = String.raw`(?:ALTER\\s+(?:COLUMN\\s+)?${NAME}\\s+(?:SET\\s+DEFAULT\\s+(?:[^,()]|${GROUP})+|DROP\\s+DEFAULT|(?:SET|DROP)\\s+NOT\\s+NULL)|ADD\\s+(?:CONSTRAINT\\s+${NAME}\\s+)?(?:CHECK\\s*${GROUP}|FOREIGN\\s+KEY\\s*${GROUP}\\s*REFERENCES\\s+${QUALIFIED}(?:\\s*${GROUP})?)(?:\\s+[A-Za-z]+|\\s*${GROUP})*|VALIDATE\\s+CONSTRAINT\\s+${NAME})`;\nconst SEEN_ALTERATION = new RegExp(\n String.raw`^${SEEN_ACTION}(?:\\s*,\\s*${SEEN_ACTION})*\\s*$`,\n \"i\"\n);\nconst SEEN_STATEMENT = /^COMMENT\\b/i;\n\n/**\n * The PostgreSQL statements of `sql` as their structure alone: comments\n * dropped, every literal, dollar-quoted body and `BEGIN ATOMIC … END` body\n * emptied (`''`), and every quoted identifier spelled with characters that\n * open or close nothing, so a pattern over what is left reads clauses, never\n * data. Its only readers are {@link catalogCommitBoundaries}' patterns.\n */\nfunction structuralStatements(sql: string): string[] {\n const statements: string[] = [];\n let text = \"\";\n let index = 0;\n let previous = \"\";\n // The CASE … END depth inside an open `BEGIN ATOMIC` body, whose `;` end\n // its own statements, not this one.\n let body = 0;\n const emit = (part: string) => {\n if (body === 0) text += part;\n };\n const end = () => {\n if (text.trim() !== \"\") statements.push(text.trim());\n text = \"\";\n };\n while (index < sql.length) {\n const char = sql.charAt(index);\n const next = sql.charAt(index + 1);\n if (char === \"-\" && next === \"-\") {\n index = skipLine(sql, index);\n emit(\" \");\n } else if (char === \"/\" && next === \"*\") {\n index = skipBlockComment(sql, index, \"postgresql\");\n emit(\" \");\n } else if (char === \"'\") {\n index = skipQuoted(sql, index, \"'\", false);\n emit(\"''\");\n } else if (char === '\"') {\n const close = skipQuoted(sql, index, '\"', false);\n const name = sql.slice(index + 1, close - 1).replaceAll('\"\"', '\"');\n emit(\n `\"${name.replace(NAME_UNSAFE, (unsafe) => `_${unsafe.charCodeAt(0).toString(16)}_`)}\"`\n );\n index = close;\n } else if (char === \"$\" && skipDollarQuoted(sql, index) !== null) {\n index = skipDollarQuoted(sql, index)!;\n emit(\"''\");\n } else if (char === \";\") {\n if (body === 0) end();\n index += 1;\n } else if (NAME_START.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && NAME_PART.test(sql.charAt(index))) {\n index += 1;\n }\n const word = sql.slice(start, index);\n const upper = word.toUpperCase();\n // `E'…'`, the one PostgreSQL string a backslash escapes in.\n if (upper === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n emit(\"''\");\n } else if (body > 0) {\n if (upper === \"CASE\") body += 1;\n if (upper === \"END\") body -= 1;\n if (body === 0) text += \"'' END\";\n } else {\n text += word;\n if (upper === \"ATOMIC\" && previous === \"BEGIN\") body = 1;\n }\n previous = upper;\n } else {\n emit(char);\n index += 1;\n }\n }\n end();\n return statements;\n}\n\n/** A relation as {@link structuralStatements} spells it, schema dropped: quoted as written, bare folded. */\nfunction relationName(qualified: string): string {\n const last = LAST_NAME.exec(qualified)?.[0] ?? qualified;\n return last.startsWith('\"') ? last.slice(1, -1) : last.toLowerCase();\n}\n\n/** One statement of a program: its position there and its leading words. */\nexport interface CatalogStatement {\n readonly position: number;\n readonly words: string;\n}\n\n/** What one Neki transaction changed since it began that a later statement may not see. */\nexport interface CatalogChanges {\n /** Its first change Neki plans later row statements without. */\n readonly unseen?: CatalogStatement;\n /** The relations it created or renamed, by name: Neki has not registered them (NK316). */\n readonly unregistered: ReadonlyMap<string, CatalogStatement>;\n}\n\n/** A statement that needs `change` committed before it runs on Neki. */\nexport interface CatalogHazard {\n /**\n * `rows`: a statement planned against the committed schema after a change\n * its planner does not see (`42P01`, `42703`, `42704`, `42883`, `22P02`, or\n * a silently stale `*` or column type); `columns`: a column type change,\n * rename or drop of a relation created or renamed in the same transaction\n * (`NK316`).\n */\n readonly kind: \"rows\" | \"columns\";\n readonly change: CatalogStatement;\n readonly statement: CatalogStatement;\n}\n\nexport const UNCHANGED_CATALOG: CatalogChanges = { unregistered: new Map() };\n\n/** One program entry read against `since`: its first hazard, and the changes after it. */\nfunction readCatalogChunk(\n chunk: string,\n position: number,\n since: CatalogChanges\n): { readonly hazard?: CatalogHazard; readonly changes: CatalogChanges } {\n let { unseen } = since;\n const unregistered = new Map(since.unregistered);\n let hazard: CatalogHazard | undefined;\n for (const text of structuralStatements(chunk)) {\n const [, first = \"\", second] = LEADING_WORDS.exec(text) ?? [];\n const leader = first.toUpperCase();\n const site = {\n position,\n words: [leader, second?.toUpperCase()].filter(Boolean).join(\" \"),\n };\n const schema = SCHEMA_CHANGES.has(leader);\n const plans = !(schema || UNPLANNED.has(leader)) || CREATE_AS.test(text);\n const table = leader === \"ALTER\" ? ALTER_TABLE.exec(text) : null;\n const created = table ? undefined : CREATE_TABLE.exec(text)?.[1];\n const relation = table ? relationName(table[1]!) : undefined;\n const clause = table?.[2] ?? \"\";\n const registering = relation && unregistered.get(relation);\n if (hazard === undefined && plans && unseen) {\n hazard = {\n kind: \"rows\",\n change: unseen,\n statement: { position, words: leader },\n };\n } else if (\n hazard === undefined &&\n registering &&\n UNREGISTERED_ACTION.test(clause)\n ) {\n hazard = { kind: \"columns\", change: registering, statement: site };\n }\n const seen =\n SEEN_STATEMENT.test(text) ||\n (table !== null && SEEN_ALTERATION.test(clause));\n if (unseen === undefined && (schema ? !seen : OPAQUE.has(leader))) {\n unseen = site;\n }\n const renamed = RENAME_TO.exec(clause)?.[1];\n if (created) unregistered.set(relationName(created), site);\n if (renamed) unregistered.set(relationName(renamed), site);\n }\n return { hazard, changes: { unseen, unregistered } };\n}\n\n/**\n * Where PlanetScale's Neki needs a commit inside a PostgreSQL transaction\n * that runs `chunks` in order, its changes since its last commit `since`.\n *\n * Neki's router plans a statement against the schema committed before its\n * transaction, and only the server it routes to sees the transaction's own\n * changes. Measured on Neki's PostgreSQL 18.6 (2026-10-13), and held by\n * `tests/providers/hosted/neki-migrations.test.ts` and the simulation in\n * `tests/unit/migrations/postgres-neki-apply.test.ts`: a statement that\n * resolves a name, a `*`, a column's type, an enum label or an ON CONFLICT\n * target the transaction changed fails there, or reads the old schema without\n * an error; a schema statement sees the transaction, except that a relation it\n * created or renamed has no column it can retype, rename or drop, and cannot\n * move to another schema (`NK316`). Defaults, NOT NULL, CHECK and foreign\n * keys, validated constraints and comments change nothing a statement is\n * planned by. A routine, a view's body or a literal (`nextval('…')`,\n * `to_regclass('…')`, stale for a created or dropped table, index or\n * constraint) can reach any relation, so a row statement after any other\n * schema change needs the commit, whichever relation it names; a `DO` block,\n * a `CALL` or an `EXECUTE` may change the schema itself (what it creates is\n * not read for `NK316`).\n *\n * `boundaries` are the entries a commit must precede, each counted with the\n * changes since the previous one; `first` is the first hazard as `since`\n * leaves it; `inside` is the first entry whose own statements need a commit\n * between them, where none can be placed; `changes` are what the last\n * boundary leaves for whatever follows.\n */\nexport function catalogCommitBoundaries(\n chunks: readonly string[],\n since: CatalogChanges = UNCHANGED_CATALOG\n): {\n readonly boundaries: readonly number[];\n readonly first?: CatalogHazard;\n readonly inside?: CatalogHazard;\n readonly changes: CatalogChanges;\n} {\n let changes = since;\n const boundaries: number[] = [];\n let first: CatalogHazard | undefined;\n let inside: CatalogHazard | undefined;\n for (const [position, chunk] of chunks.entries()) {\n let read = readCatalogChunk(chunk, position, changes);\n if (read.hazard) {\n first ??= read.hazard;\n read = readCatalogChunk(chunk, position, UNCHANGED_CATALOG);\n inside ??= read.hazard;\n boundaries.push(position);\n }\n changes = read.changes;\n }\n return { boundaries, first, inside, changes };\n}\n\n/**\n * Whether `sql` holds a PostgreSQL statement run `CONCURRENTLY` that refuses\n * a transaction block: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX\n * CONCURRENTLY`, a `REINDEX … CONCURRENTLY` or `ALTER TABLE … DETACH\n * PARTITION … CONCURRENTLY`. Only these wait, by design, for every older\n * transaction without blocking anyone (plan S1). Read from each statement's\n * executable words, so the words in a comment or a literal are not one, and\n * neither is `REFRESH MATERIALIZED VIEW CONCURRENTLY`.\n */\nexport function runsConcurrently(sql: string): boolean {\n return readExecutableStatements(sql, \"postgresql\").some((words) => {\n const [verb] = words;\n if (verb === \"REINDEX\") return words.includes(\"CONCURRENTLY\");\n if (verb === \"ALTER\") {\n return [\"DETACH\", \"PARTITION\", \"CONCURRENTLY\"].every((word) =>\n words.includes(word)\n );\n }\n const index = verb === \"CREATE\" && words[1] === \"UNIQUE\" ? 2 : 1;\n return (\n (verb === \"CREATE\" || verb === \"DROP\") &&\n words[index] === \"INDEX\" &&\n words[index + 1] === \"CONCURRENTLY\"\n );\n });\n}\n","import { isDestructiveOperation } from \"./differ\";\n/**\n * One compiler: DiffOperation and manual Sql become structured operations\n * that share one SQL blob. No delimiter split.\n */\n\nimport type { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalDecimalText } from \"../validation/primitives/decimal-value\";\nimport { decodeCanonicalBase64, encodeBase64 } from \"./base64\";\nimport {\n type CatalogProbe,\n probeForGeneratedStatement,\n} from \"./catalog-probes\";\nimport type { DDLContext, MigrationDriver } from \"./drivers\";\nimport { invertOperations } from \"./invert\";\nimport type { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n needsEnumAdditionCommitBoundary,\n runsConcurrently,\n} from \"./statement-safety\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { encodeTransitionHash } from \"./v1-parse\";\nimport type {\n AtomicityClass,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationCheckInput,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParameterV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport interface CompiledTransition {\n readonly operations: readonly MigrationOperationV1[];\n readonly rollback: MigrationRollbackV1;\n readonly originChecks: readonly MigrationBooleanCheckV1[];\n readonly requestedForwardBoundary: \"transactional\" | \"stepwise\" | null;\n readonly atomicity: AtomicityClass;\n readonly warnings?: readonly string[];\n}\n\n/** The SQL each step of `operations` executes, in order. */\nexport function stepStatements(\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[]\n): string[] {\n return operations.flatMap((operation) =>\n operation.steps.map((step) => sliceDispatch(blob, step.execute))\n );\n}\n\nconst VALIDATE_CONSTRAINT = /\\bVALIDATE\\s+CONSTRAINT\\b/i;\n\n/**\n * Contiguous edges of one boundary share a commit, except that an edge adding\n * a PostgreSQL enum value ends its group: a later edge may use that value,\n * which PostgreSQL refuses until the addition commits (55P04). An edge that\n * validates a constraint commits alone (T5b): sharing a transaction with the\n * edge that added it `NOT VALID` would hold that addition's lock through the\n * scan the split exists to free.\n */\nexport function groupContiguousAtomicity<\n T extends { readonly boundary: string },\n>(\n items: readonly T[],\n statementsOf: (item: T) => readonly string[]\n): readonly {\n readonly boundary: T[\"boundary\"];\n readonly items: readonly T[];\n}[] {\n const groups: {\n boundary: T[\"boundary\"];\n items: T[];\n }[] = [];\n let mustCommit = false;\n for (const item of items) {\n const statements = statementsOf(item);\n const alone = statements.some((text) => VALIDATE_CONSTRAINT.test(text));\n const current = groups.at(-1);\n if (current?.boundary === item.boundary && !(mustCommit || alone)) {\n current.items.push(item);\n } else {\n groups.push({ boundary: item.boundary, items: [item] });\n }\n mustCommit = alone || needsEnumAdditionCommitBoundary(statements);\n }\n return groups;\n}\n\n/**\n * The context a generated statement compiles in. `lowLock` asks PostgreSQL\n * for the form of a step that blocks no write while it reads the table (T5b):\n * `\"add\"` builds an index `CONCURRENTLY` or adds a foreign key `NOT VALID`,\n * `\"validate\"` validates that key. Only `generate({ lowLock: true })` sets\n * it, and only on a table that existed before the migration.\n */\nexport type LowLockContext = DDLContext & {\n readonly lowLock?: \"add\" | \"validate\";\n};\n\n/** One state of a generated program split at its low-lock steps. */\nexport interface LowLockState {\n readonly operations: readonly DiffOperation[];\n /** The schema the state reaches. */\n readonly snapshot: SchemaSnapshot;\n /** Whether it validates the keys an earlier state added `NOT VALID`. */\n readonly validates: boolean;\n}\n\n/**\n * Splits a generated PostgreSQL program into the states that give each\n * low-lock step its own commit (T5b), or returns `undefined` when it has none\n * to give. A step is an index built on, or a foreign key added to, a table\n * the program does not create (a table it creates is empty). Each index build\n * is a state of its own: `CREATE INDEX CONCURRENTLY` runs outside any\n * transaction, and an interrupted build is then one unfinished single-step\n * attempt that `resolve` repairs either way. The keys are added `NOT VALID`\n * with the last state, and a final state validates them in a commit of its\n * own; a failed validation rolls back alone and `apply` resumes from the\n * marker.\n *\n * The schemas between states are the target's with the later states' effects\n * undone, so only an index build, an index drop or a key may follow the first\n * build; otherwise, or when a dropped index cannot be read back from the\n * origin, the program is not split and keeps its blocking forms.\n */\nexport function lowLockStates(\n operations: readonly DiffOperation[],\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): { states: LowLockState[]; steps: ReadonlySet<DiffOperation> } | undefined {\n const steps = lowLockSteps(operations);\n if (steps.size === 0) return;\n const first = operations.findIndex(\n (op) => op.type === \"createIndex\" && steps.has(op)\n );\n const tail = first < 0 ? [] : operations.slice(first);\n const renames = operations.some(\n (op) => op.type === \"renameTable\" || op.type === \"renameColumn\"\n );\n if (\n !tail.every((op) =>\n op.type === \"createIndex\"\n ? steps.has(op)\n : op.type === \"addForeignKey\" || (op.type === \"dropIndex\" && !renames)\n )\n ) {\n return;\n }\n const ends: number[] = [];\n for (const [index, op] of operations.entries()) {\n if (op.type === \"createIndex\" && steps.has(op)) {\n if (index > (ends.at(-1) ?? 0)) ends.push(index);\n ends.push(index + 1);\n }\n }\n if (ends.at(-1) !== operations.length) ends.push(operations.length);\n const states: LowLockState[] = [];\n for (const [index, end] of ends.entries()) {\n const snapshot = withoutEffects(desired, current, operations.slice(end));\n if (!snapshot) return;\n states.push({\n operations: operations.slice(ends[index - 1] ?? 0, end),\n snapshot,\n validates: false,\n });\n }\n const keys = operations.filter(\n (op) => op.type === \"addForeignKey\" && steps.has(op)\n );\n if (keys.length > 0) {\n states.push({ operations: keys, snapshot: desired, validates: true });\n }\n return { states, steps };\n}\n\n/**\n * The index builds and keys of `operations` on tables it does not create. A\n * raw index is not one: its text is the author's, and it is built blocking.\n */\nexport function lowLockSteps(\n operations: readonly DiffOperation[]\n): ReadonlySet<DiffOperation> {\n const created = new Set(\n operations.flatMap((op) => (op.type === \"createTable\" ? op.table.name : []))\n );\n return new Set(\n operations.filter(\n (op) =>\n ((op.type === \"createIndex\" && !op.index.raw) ||\n op.type === \"addForeignKey\") &&\n !created.has(op.tableName)\n )\n );\n}\n\n/** `desired` before `later`: an index build, an index drop or a key. */\nfunction withoutEffects(\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n later: readonly DiffOperation[]\n): SchemaSnapshot | undefined {\n let readable = later.every(\n (op) =>\n \"tableName\" in op &&\n desired.tables.some((table) => table.name === op.tableName)\n );\n const tables = desired.tables.map((table) => {\n const own = later.filter(\n (op) => \"tableName\" in op && op.tableName === table.name\n );\n if (own.length === 0) return table;\n const built = new Set(\n own.flatMap((op) => (op.type === \"createIndex\" ? op.index.name : []))\n );\n const keys = new Set(\n own.flatMap((op) => (op.type === \"addForeignKey\" ? op.fk.name : []))\n );\n const restored = own.flatMap((op) => {\n if (op.type !== \"dropIndex\") return [];\n const index = current.tables\n .find((origin) => origin.name === table.name)\n ?.indexes.find((item) => item.name === op.indexName);\n if (!index) readable = false;\n return index ?? [];\n });\n return {\n ...table,\n indexes: [\n ...table.indexes.filter((index) => !built.has(index.name)),\n ...restored,\n ],\n foreignKeys: table.foreignKeys.filter((key) => !keys.has(key.name)),\n };\n });\n return readable ? { ...desired, tables } : undefined;\n}\n\nexport function compileGeneratedTransition(\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n desiredSchema: SchemaSnapshot,\n assembly: SqlAssembly,\n lowLock: ReadonlySet<DiffOperation> = new Set()\n): CompiledTransition {\n const compiled = operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n currentSchema,\n operations,\n index,\n assembly,\n lowLock.has(operation) ? \"add\" : undefined\n )\n )\n .filter((operation) => operation.steps.length > 0);\n const inverse = invertOperations(\n [...operations],\n currentSchema,\n driver.projectNativeRename.bind(driver),\n driver.generatedPrimaryKeyName.bind(driver)\n );\n const missingBackfill = inverse.operations.find(\n (operation) =>\n operation.type === \"addColumn\" &&\n !operation.column.nullable &&\n operation.column.default === undefined\n );\n const irreversibleReason =\n missingBackfill && missingBackfill.type === \"addColumn\"\n ? `Rollback cannot restore required column \"${missingBackfill.tableName}.${missingBackfill.column.name}\" without its lost data or an explicit backfill. Author a manual rollback.`\n : inverse.operations\n .map((operation) => driver.getIrreversibleRollbackReason(operation))\n .find((reason) => reason !== undefined);\n const rollback: MigrationRollbackV1 =\n inverse.operations.length === 0 && operations.length === 0\n ? { kind: \"schema\", operations: [] }\n : irreversibleReason !== undefined\n ? { kind: \"irreversible\", reason: irreversibleReason }\n : inverse.operations.length === 0\n ? {\n kind: \"irreversible\",\n reason:\n inverse.warnings[0] ??\n \"Generated operations have no automatic inverse\",\n }\n : {\n kind: \"schema\",\n operations: inverse.operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n desiredSchema,\n inverse.operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0),\n };\n return {\n operations: compiled,\n rollback,\n warnings: inverse.warnings,\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: classifyGeneratedAtomicity(driver, operations),\n };\n}\n\n/**\n * The state that validates the foreign keys an earlier state added `NOT VALID`\n * (T5b). Undoing it is nothing: the keys stay, as their state declares them.\n */\nexport function compileValidationTransition(\n keys: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot,\n assembly: SqlAssembly\n): CompiledTransition {\n return {\n operations: keys.map((key, index) =>\n compileGeneratedOperation(\n key,\n driver,\n \"artifact\",\n currentSchema,\n keys,\n index,\n assembly,\n \"validate\"\n )\n ),\n rollback: { kind: \"schema\", operations: [] },\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: \"transactional\",\n };\n}\n\nfunction compileGeneratedOperation(\n operation: DiffOperation,\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n batch: readonly DiffOperation[],\n index: number,\n assembly: SqlAssembly,\n lowLock?: LowLockContext[\"lowLock\"]\n): MigrationOperationV1 {\n const context: LowLockContext = {\n destination,\n currentSchema,\n precedingOperations: batch.slice(0, index),\n followingOperations: batch.slice(index + 1),\n ...(lowLock === undefined ? {} : { lowLock }),\n };\n const statements = driver.compileStatements(operation, context);\n const steps: MigrationStepV1[] = statements.map((statement) => {\n const probes = probeForGeneratedStatement(driver, operation, statement);\n const execute = addDispatch(assembly, statement, []);\n if (!probes) {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: checkFromProbe(assembly, probes.pre),\n execute,\n postcheck: checkFromProbe(assembly, probes.post),\n };\n });\n return {\n id: `${operation.type}:${index}`,\n label:\n \"tableName\" in operation\n ? `${operation.type} ${operation.tableName}${\"columnName\" in operation ? `.${operation.columnName}` : \"column\" in operation ? `.${operation.column.name}` : \"\"}`\n : operation.type,\n origin: \"generated\",\n risk: isDestructiveOperation(operation) ? \"destructive\" : \"safe\",\n steps,\n };\n}\n\nexport function compileManualTransition(\n up: readonly Sql[],\n rollback:\n | {\n readonly kind: \"manual\";\n readonly execution: AtomicityClass;\n readonly sql: readonly Sql[];\n }\n | { readonly kind: \"irreversible\"; readonly reason: string },\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n requested: AtomicityClass,\n originChecks: readonly MigrationCheckInput[] | undefined,\n assembly: SqlAssembly\n): CompiledTransition {\n const operations = compileManualOperations(\n up,\n dialect,\n assembly,\n \"forward\",\n requested\n );\n if (rollback.kind === \"irreversible\" && rollback.reason.trim().length === 0) {\n throw new MigrationError(\n \"Irreversible rollback requires a non-empty reason\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const compiledRollback: MigrationRollbackV1 =\n rollback.kind === \"irreversible\"\n ? rollback\n : {\n kind: \"manual\",\n requestedBoundary: rollback.execution,\n operations: compileManualOperations(\n rollback.sql,\n dialect,\n assembly,\n \"rollback\",\n rollback.execution\n ),\n };\n return {\n operations,\n rollback: compiledRollback,\n originChecks: (originChecks ?? []).map((check, index) =>\n compileTrustedCheck(check, dialect, assembly, `origin:${index}`)\n ),\n requestedForwardBoundary: requested,\n atomicity: requested,\n };\n}\n\nexport function assertManualStepwiseProof(\n compiled: CompiledTransition,\n destinationChecks: readonly MigrationBooleanCheckV1[]\n): void {\n const forwardStepwise = compiled.requestedForwardBoundary === \"stepwise\";\n const rollbackStepwise =\n compiled.rollback.kind === \"manual\" &&\n compiled.rollback.requestedBoundary === \"stepwise\";\n if (!(forwardStepwise || rollbackStepwise)) return;\n if (compiled.originChecks.length === 0 || destinationChecks.length === 0) {\n throw new MigrationError(\n \"Stepwise data-only manual work without complete origin and destination checks is refused before dispatch\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction compileManualOperations(\n fragments: readonly Sql[],\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n prefix: string,\n execution: AtomicityClass\n): MigrationOperationV1[] {\n if (fragments.length === 0) {\n throw new MigrationError(\n `Manual ${prefix} program must contain at least one SQL dispatch`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n // Plan S5, refused before the state is published: apply refuses it, so no\n // SQLite database could ever reach the state.\n if (execution === \"stepwise\" && dialect === \"sqlite\") {\n throw new MigrationError(\n `SQLite runs no stepwise manual ${prefix} program: only a transaction holds the write lock under which a migration runs exactly once, and every SQLite statement can run in one. Declare execution: \"transactional\" for it.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect, feature: \"stepwise execution\" } }\n );\n }\n return fragments.map((fragment, index) => {\n const text = fragment.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n if (text.trim().length === 0) {\n throw new MigrationError(\n `Manual ${prefix} SQL dispatch ${index} must contain non-whitespace text`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n // Refused before the state is published: sent after BEGIN, PostgreSQL\n // rejects it (25001), so the transition could never apply.\n if (\n execution === \"transactional\" &&\n dialect === \"postgresql\" &&\n runsConcurrently(text)\n ) {\n throw new MigrationError(\n `Manual ${prefix} SQL dispatch ${index} runs CONCURRENTLY, which PostgreSQL refuses inside a transaction. Declare execution: \"stepwise\" for it.`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const parameters = fragment.values.map((value) => encodeParameter(value));\n return {\n id: `manual:${prefix}:${index}`,\n label: \"manual\",\n origin: \"manual\" as const,\n risk: \"opaque\" as const,\n steps: [\n {\n retry: \"opaque\" as const,\n execute: addDispatch(assembly, text, parameters),\n },\n ],\n };\n });\n}\n\nexport function compileTrustedCheck(\n input: MigrationCheckInput,\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n id: string\n): MigrationBooleanCheckV1 & { readonly kind: \"trusted-read\" } {\n const text = input.query.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n const parameters = input.query.values.map((value) => encodeParameter(value));\n return {\n kind: \"trusted-read\" as const,\n id,\n query: addDispatch(assembly, text, parameters),\n equals: input.equals,\n };\n}\n\nexport function sealParent(\n fromState: string | null,\n compiled: CompiledTransition,\n approvals: readonly MigrationApprovalV1[] = [],\n adopts: readonly string[] = []\n): Omit<MigrationParentTransitionV1, \"transitionHash\"> {\n return {\n fromState,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n operations: compiled.operations,\n rollback: compiled.rollback,\n ...(approvals.length === 0 ? {} : { approvals }),\n ...(adopts.length === 0 ? {} : { adopts }),\n };\n}\n\nexport function hashParent(\n parent: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): MigrationParentTransitionV1 {\n return { ...parent, transitionHash: encodeTransitionHash(parent) };\n}\n\nfunction addDispatch(\n assembly: SqlAssembly,\n text: string,\n parameters: readonly MigrationParameterV1[]\n): MigrationDispatchV1 {\n const index = assembly.add(text, parameters);\n return {\n dispatchId: \"0\".repeat(64),\n sqlHash: \"0\".repeat(64),\n offset: index,\n length: 0,\n parameters,\n };\n}\n\nfunction checkFromProbe(\n assembly: SqlAssembly,\n probe: CatalogProbe\n): MigrationBooleanCheckV1 {\n return {\n kind: \"driver\",\n id: probe.id,\n query: addDispatch(assembly, probe.sql, probe.parameters),\n equals: probe.equals,\n };\n}\n\nexport function rebindDispatches(\n operations: readonly MigrationOperationV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationOperationV1[] {\n return operations.map((operation) => ({\n ...operation,\n steps: operation.steps.map((step) => rebindStep(step, dispatches)),\n }));\n}\n\nfunction rebindStep(\n step: MigrationStepV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationStepV1 {\n const execute = dispatchAt(dispatches, step.execute.offset);\n if (step.retry === \"opaque\") {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: {\n ...step.precheck,\n query: dispatchAt(dispatches, step.precheck.query.offset),\n },\n execute,\n postcheck: {\n ...step.postcheck,\n query: dispatchAt(dispatches, step.postcheck.query.offset),\n },\n };\n}\n\n/** The sealed dispatch at an index the same assembly handed out. */\nexport function dispatchAt(\n dispatches: readonly MigrationDispatchV1[],\n index: number\n): MigrationDispatchV1 {\n const found = dispatches[index];\n if (!found) {\n throw new MigrationError(\n \"Compiled dispatch is missing from the SQL assembly\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nexport function rebindChecks(\n checks: readonly MigrationBooleanCheckV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationBooleanCheckV1[] {\n return checks.map((check) => ({\n ...check,\n query: dispatchAt(dispatches, check.query.offset),\n }));\n}\n\nexport function rebindRollback(\n rollback: MigrationRollbackV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationRollbackV1 {\n if (rollback.kind === \"irreversible\") return rollback;\n return {\n ...rollback,\n operations: rebindDispatches(rollback.operations, dispatches),\n };\n}\n\nconst IDENTIFIER = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)`;\nconst QUALIFIED = String.raw`${IDENTIFIER}(?:\\.${IDENTIFIER})?`;\n\nconst ALTER_TYPE_ADD_VALUE = /ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE/i;\n\n/** `CREATE TABLE <name>` (group 1), or `ALTER TABLE <name>` (2) and its actions (3). */\nconst TABLE_STATEMENT = new RegExp(\n String.raw`\\bCREATE\\s+(?:(?:GLOBAL|LOCAL|TEMP|TEMPORARY|UNLOGGED)\\s+)*TABLE\\s+(?!IF\\s+NOT\\s+EXISTS\\b)(${QUALIFIED})|\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})([^;]*)`,\n \"gi\"\n);\n/** `RENAME TO <name>`, the whole action of an `ALTER TABLE`. */\nconst RENAME_TO = new RegExp(\n String.raw`^\\s*RENAME\\s+TO\\s+(${IDENTIFIER})\\s*$`,\n \"i\"\n);\nconst LAST_IDENTIFIER = new RegExp(`${IDENTIFIER}$`);\n/** Each action that rewrites or scans the table, and how a refusal names it. */\nconst TABLE_REWRITES: readonly (readonly [RegExp, (name: string) => string])[] =\n [\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+(?:SET\\s+DATA\\s+)?TYPE\\b`,\n \"i\"\n ),\n (column) => `column type change of ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+SET\\s+NOT\\s+NULL\\b`,\n \"i\"\n ),\n (column) => `SET NOT NULL on ${column}`,\n ],\n [\n new RegExp(\n String.raw`\\bADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(?!(?:CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)\\b)(${IDENTIFIER})[\\s\\S]*?(?:\\b(?:gen_random_uuid|uuidv[47]|uuid_generate_v[14]|random|clock_timestamp|timeofday|nextval)\\s*\\(|\\b(?:SMALL|BIG)?SERIAL\\b|\\bGENERATED\\b)`,\n \"i\"\n ),\n (column) => `volatile default on new column ${column}`,\n ],\n [\n // `NOT VALID` counts up to the next `, ADD` action, not past it.\n new RegExp(\n String.raw`\\bADD\\s+(?:CONSTRAINT\\s+${IDENTIFIER}\\s+)?(FOREIGN\\s+KEY|CHECK)\\b(?!(?:(?!,\\s*ADD\\b)[\\s\\S])*\\bNOT\\s+VALID\\b)`,\n \"i\"\n ),\n (constraint) => `${constraint.toUpperCase()} validation`,\n ],\n ];\n\n/**\n * The PostgreSQL statements of `program` that rewrite or scan an existing\n * table while holding a lock that blocks it (T5a): a column type change (an\n * enum replacement and a decimal descriptor change are ones), `SET NOT NULL`,\n * a new column whose default is volatile, and a FOREIGN KEY or CHECK added\n * without `NOT VALID`. One entry per `ALTER TABLE`, naming its table as the\n * statement spells it and its first such action; a table an earlier\n * `RENAME TO` of the program renamed is named by its spelling before the\n * program ran, the one the live catalog holds. A table the program has\n * already created by that spelling is empty, so it is left out (a force\n * reset, a drop and recreate), as it is once renamed. A plain `CREATE INDEX`\n * (writes blocked, reads not) is not one.\n */\nexport function tableRewrites(\n program: readonly string[]\n): { readonly table: string; readonly operation: string }[] {\n const created = new Set<string>();\n const before = new Map<string, string>();\n return program.flatMap((statement) =>\n [...statement.matchAll(TABLE_STATEMENT)].flatMap(\n ([, made, table, clause]) => {\n if (made) created.add(made);\n if (!table) return [];\n const renamedTo = RENAME_TO.exec(clause ?? \"\")?.[1];\n if (renamedTo) {\n const next = table.replace(LAST_IDENTIFIER, renamedTo);\n if (created.has(table)) created.add(next);\n else before.set(next, before.get(table) ?? table);\n return [];\n }\n if (created.has(table)) return [];\n for (const [pattern, name] of TABLE_REWRITES) {\n const action = pattern.exec(clause ?? \"\")?.[1];\n if (action) {\n return [\n { table: before.get(table) ?? table, operation: name(action) },\n ];\n }\n }\n return [];\n }\n )\n );\n}\n\nfunction isNonTransactionalSql(driver: MigrationDriver, sql: string): boolean {\n if (runsConcurrently(sql)) return true;\n return (\n ALTER_TYPE_ADD_VALUE.test(sql) &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n );\n}\n\nexport function classifyGeneratedAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[],\n reset?: boolean\n): AtomicityClass {\n if (driver.dialect === \"mysql\" || driver.buildsApart?.(operations, reset))\n return \"stepwise\";\n if (\n operations.some(\n (operation) =>\n operation.type === \"alterEnum\" &&\n (operation.addValues?.length ?? 0) > 0 &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function assertTransactionalBoundaryHonored(\n supportsTransactions: boolean,\n requested: \"transactional\" | \"stepwise\" | null\n): void {\n if (requested === \"transactional\" && !supportsTransactions) {\n throw new MigrationError(\n \"This producer cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n}\n\n/**\n * Plan S5, refused while a stored path is prepared, before any of it runs:\n * only a transaction holds SQLite's write lock, under which a migration runs\n * exactly once, and every SQLite statement can run in one. Generate refuses\n * such a program since 1.2.0; this refuses one 1.1.0 published, whichever\n * command would run it. Resolve's retry does not ask: it finishes an attempt\n * 1.1.0 left open.\n */\nexport function refuseSqliteStepwise(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n toState: string\n): void {\n if (requested !== \"stepwise\" || driver.dialect !== \"sqlite\") return;\n throw new MigrationError(\n 'SQLite runs no stepwise program: only a transaction holds the write lock under which a migration runs exactly once, and every SQLite statement can run in one. Nothing ran. Run it with VibORM 1.1.0, or, if no database applied it, remove its state from migration storage and generate it again with `execution: \"transactional\"`.',\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect: \"sqlite\", toState, feature: \"stepwise execution\" } }\n );\n}\n\nexport function classifyStoredAtomicity(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n operations: readonly MigrationOperationV1[],\n blob?: Uint8Array\n): AtomicityClass {\n if (requested === \"transactional\" && driver.dialect === \"mysql\") {\n throw new MigrationError(\n \"This provider cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n // Neki refuses any statement after a schema change in its transaction, a\n // control write included: there every step commits alone, as before an\n // edge whose statements needed a commit was already cut into parts.\n if (driver.commitsSchemaChangesAlone()) return \"stepwise\";\n if (requested === \"transactional\") return \"transactional\";\n if (requested === \"stepwise\") return \"stepwise\";\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n blob &&\n stepStatements(blob, operations).some((text) =>\n isNonTransactionalSql(driver, text)\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function encodeParameter(value: unknown): MigrationParameterV1 {\n if (value === null || value === undefined) return { kind: \"null\" };\n if (typeof value === \"boolean\") return { kind: \"boolean\", value };\n if (typeof value === \"string\") return { kind: \"string\", value };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"SQL parameters refuse NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"number\", value };\n }\n if (typeof value === \"bigint\")\n return { kind: \"bigint\", value: value.toString() };\n if (value instanceof Date)\n return { kind: \"date-time\", value: value.toISOString() };\n if (value instanceof Uint8Array) {\n return { kind: \"bytes\", value: encodeBase64(value) };\n }\n const decimal = canonicalDecimalText(value);\n if (decimal !== undefined) return { kind: \"decimal\", value: decimal };\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n throw new MigrationError(\n \"SQL parameters refuse functions and symbols\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"json\", value };\n}\n\nexport function decodeParameter(\n parameter: MigrationParameterV1,\n targetNamespace?: string\n): unknown {\n switch (parameter.kind) {\n case \"null\":\n return null;\n case \"target-namespace\":\n if (targetNamespace === undefined) {\n throw new MigrationError(\n \"A stored target-namespace parameter requires a resolved migration namespace\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return targetNamespace;\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"json\":\n return parameter.value;\n case \"bigint\":\n return BigInt(parameter.value);\n case \"bytes\": {\n const bytes = decodeCanonicalBase64(parameter.value);\n if (bytes === undefined) {\n throw new MigrationError(\n \"Stored bytes parameter is not canonical Base64\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return bytes;\n }\n case \"date-time\":\n return new Date(parameter.value);\n case \"decimal\":\n return parameter.value;\n default: {\n const kind: never = parameter;\n throw new MigrationError(\n `Unknown SQL parameter kind: ${JSON.stringify(kind)}`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * One execution owner for authenticated SQL slices and typed parameters.\n * Apply, down, reset, and push consume this. There is no second executor.\n */\n\nimport type { AnyDriver, CommitRerunningDriver } from \"../drivers/driver\";\nimport { attachMissingMeta } from \"../drivers/driver-error-context\";\nimport type { SqlDialect } from \"../drivers/types\";\nimport {\n ConnectionError,\n isVibORMError,\n MigrationError,\n type MigrationErrorMeta,\n type VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { decodeParameter } from \"./compile\";\nimport type { MigrationBatch } from \"./pinned-session\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { readExecutableStatements } from \"./statement-safety\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\n/**\n * Every statement a migration runs, as the engine built it: the driver may run\n * it again where its own transaction around it was refused at its commit\n * (`rerunRefusedCommit`, SurrealDB), which a caller's raw statement never is.\n */\nexport async function executeExactSql(\n producer: AnyDriver,\n sql: string,\n parameters: readonly unknown[] = []\n): Promise<void> {\n const send = () => producer._executeRaw(sql, [...parameters]);\n await (reruns(producer) ? producer.rerunRefusedCommit(sql, send) : send());\n}\n\nconst reruns = (\n driver: AnyDriver\n): driver is AnyDriver & CommitRerunningDriver =>\n typeof Reflect.get(driver, \"rerunRefusedCommit\") === \"function\";\n\n/** A dispatch's exact text and its decoded parameters. */\nfunction dispatchQuery(\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n return {\n sql: sliceDispatch(blob, dispatch),\n params: dispatch.parameters.map((parameter) =>\n decodeParameter(parameter, targetNamespace)\n ),\n };\n}\n\nexport async function executeDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace?: string\n): Promise<void> {\n const { sql, params } = dispatchQuery(blob, dispatch, targetNamespace);\n await executeExactSql(producer, sql, params);\n}\n\nexport async function evaluateCheck(\n producer: AnyDriver,\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace?: string\n): Promise<boolean> {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const result = await producer._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one row`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const values = Object.values(result.rows[0]!);\n if (values.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one column`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const flag = readFlag(values[0]);\n if (flag === undefined) {\n throw new MigrationError(\n `Check ${check.id} did not return a boolean`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return flag === check.equals;\n}\n\nconst TRAILING_SEMICOLON = /;\\s*$/;\n\n/**\n * {@link evaluateCheck} as a condition one request asserts (plan D7): the\n * check's one row holds one value, `check.equals` in a spelling\n * `readFlag` reads. No row, more rows, or another value do not hold. A\n * check with another number of columns is refused, as `evaluateCheck`\n * refuses it: the `UNION ALL` with one column fails the request, which rolls\n * back. Columns are named, never read as one whole row, which PlanetScale\n * Neki refuses.\n */\nexport function checkCondition(\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace: string | undefined\n): { readonly sql: string; readonly params: unknown[] } {\n const { sql, params } = dispatchQuery(blob, check.query, targetNamespace);\n const spellings = check.equals ? \"'true', 't', '1'\" : \"'false', 'f', '0'\";\n return {\n sql: `(SELECT CASE WHEN count(*) = 1 THEN min(one.value::text) END FROM (SELECT * FROM (\\n${sql.replace(TRAILING_SEMICOLON, \"\")}\\n) AS checked UNION ALL SELECT NULL WHERE false) AS one(value)) IN (${spellings})`,\n params,\n };\n}\n\n/**\n * Whether `error` is the provider refusing a statement — its answer carries a\n * provider code — rather than a failure of the transport.\n */\nexport function providerRefused(error: unknown): error is VibORMError {\n return (\n isVibORMError(error) &&\n !(error instanceof ConnectionError) &&\n (error.meta.providerCode !== undefined ||\n error.meta.providerSqlState !== undefined)\n );\n}\n\n/**\n * The provider's SQLSTATE and code of a refusal, for the meta of the\n * migration error that wraps it (both are on the error-metadata allow-list;\n * the provider's text stays in the cause, disclosed as the driver's\n * diagnostics allow), and the statement when those diagnostics disclosed it:\n * a wrapped cause keeps no meta of its own. Nothing for a transport failure.\n */\nexport function providerFacts(error: unknown): {\n readonly providerCode?: unknown;\n readonly providerSqlState?: unknown;\n readonly query?: string;\n} {\n if (!providerRefused(error)) return {};\n const { providerCode, providerSqlState, query } = error.meta;\n return {\n ...(providerCode === undefined ? {} : { providerCode }),\n ...(providerSqlState === undefined ? {} : { providerSqlState }),\n ...(query === undefined ? {} : { query }),\n };\n}\n\nexport interface StepProgress {\n readonly operationId: string;\n readonly dispatchId: string;\n readonly skipped: boolean;\n}\n\n/**\n * Records one step's progress. An opaque stepwise step is announced (`none`)\n * before it runs, then answered: `committed`, or — refused whole, nothing of\n * it committed — `none` again with the refusal as `failure`. An announcement\n * never answered may have committed.\n */\ntype OnProgress = (\n progress: StepProgress,\n effect: LedgerEffectStateV1,\n failure?: string\n) => Promise<void>;\n\n/** The edge a program runs, and its command step: every failure names both. */\nexport interface DispatchEdge {\n readonly fromState: string | null;\n readonly toState: string | null;\n /** `apply`, `down`, `resolve` or `reset-replay`. */\n readonly step: string;\n}\n\n/** Where one dispatch sits: its edge, operation, statement and boundary. */\ninterface DispatchSite {\n readonly edge: DispatchEdge | undefined;\n readonly operationId: string;\n readonly statementIndex: number;\n readonly strategy: \"transactional\" | \"stepwise\" | \"atomic\";\n}\n\n/**\n * `failure`, naming where in the command it happened: the keys it already has\n * stay its own. A transport failure keeps its class, so a lost connection is\n * still the retryable `ConnectionError` it is (plan S2).\n */\nexport function annotateMigrationFailure(\n failure: unknown,\n meta: MigrationErrorMeta\n): unknown {\n return isVibORMError(failure) ? attachMissingMeta(failure, meta) : failure;\n}\n\n/**\n * `atomic` is a program inside a real transaction (plan D5): its rollback\n * undoes whatever a failure leaves half done, so no step is probed, and the\n * caller proves the destination once. Its progress is reported only when\n * asked (one part of an edge split at Neki's commit boundaries,\n * `apply-v1.ts`): each report lands in the step's own transaction, so it\n * commits with the step or not at all.\n */\nexport async function executeOperations(\n producer: AnyDriver,\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[],\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string,\n edge?: DispatchEdge\n): Promise<void> {\n let statementIndex = 0;\n for (const operation of operations) {\n for (const step of operation.steps) {\n await executeStep(\n producer,\n blob,\n {\n edge,\n operationId: operation.id,\n statementIndex,\n strategy: boundary,\n },\n step,\n boundary,\n onProgress,\n targetNamespace\n );\n statementIndex += 1;\n }\n }\n}\n\nfunction siteMeta(site: DispatchSite, dispatchId: string): MigrationErrorMeta {\n const { edge } = site;\n return {\n ...(edge ? { step: edge.step } : {}),\n strategy: site.strategy,\n ...(edge?.fromState ? { fromState: edge.fromState } : {}),\n ...(edge?.toState ? { toState: edge.toState, stateId: edge.toState } : {}),\n operationId: site.operationId,\n dispatchId,\n statementIndex: site.statementIndex,\n };\n}\n\n/**\n * Runs one dispatch. A statement the provider refused — its answer carries a\n * provider code — becomes a MigrationError naming its edge, operation,\n * dispatch and statement, with that code; SQL and parameters stay on the\n * cause, behind diagnostics. A transport failure is not a refusal: it stays\n * what it is, and the pinned session reports a lost connection as the\n * retryable failure it is (plan S2).\n */\nasync function runDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n dispatch: MigrationDispatchV1,\n targetNamespace: string | undefined\n): Promise<void> {\n try {\n await executeDispatch(producer, blob, dispatch, targetNamespace);\n } catch (error) {\n if (!providerRefused(error))\n throw annotateMigrationFailure(\n error,\n siteMeta(site, dispatch.dispatchId)\n );\n throw refusal(site, dispatch.dispatchId, error);\n }\n}\n\nfunction refusal(\n site: DispatchSite,\n dispatchId: string,\n error: VibORMError,\n meta?: MigrationErrorMeta\n): MigrationError {\n return new MigrationError(\n `Migration statement ${site.statementIndex} of operation ${site.operationId} failed`,\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: error,\n meta: {\n ...siteMeta(site, dispatchId),\n ...providerFacts(error),\n ...meta,\n },\n }\n );\n}\n\n/**\n * Leaders of a statement that may COMMIT part of its work before it fails: a\n * procedure, a PostgreSQL `DO` block, a statement prepared earlier.\n */\nconst COMMITS_INSIDE = new Set([\"CALL\", \"DO\", \"EXECUTE\"]);\n\n/**\n * Whether the provider's refusal of `sql` proves none of it committed: one\n * statement, run bare as a transaction of its own, which the server undoes\n * whole when it refuses it (VibORM's MySQL tables are InnoDB). Not one led by\n * {@link COMMITS_INSIDE}, nor a `CONCURRENTLY` statement, which commits in\n * phases.\n */\nfunction refusedWhole(\n error: unknown,\n sql: string,\n dialect: AnyDriver[\"dialect\"]\n): error is VibORMError {\n if (!providerRefused(error)) return false;\n const statements = readExecutableStatements(sql, dialect as SqlDialect);\n const [leader = \"\", ...rest] = statements[0] ?? [];\n return (\n statements.length === 1 &&\n !COMMITS_INSIDE.has(leader) &&\n !rest.includes(\"CONCURRENTLY\")\n );\n}\n\nasync function executeStep(\n producer: AnyDriver,\n blob: Uint8Array,\n site: DispatchSite,\n step: MigrationStepV1,\n boundary: \"transactional\" | \"stepwise\" | \"atomic\",\n onProgress?: OnProgress,\n targetNamespace?: string\n): Promise<void> {\n const { operationId } = site;\n if (boundary === \"atomic\") {\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n // Recorded, when asked, in the transaction the step ran in: with it.\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n if (step.retry === \"proven\") {\n if (await evaluateCheck(producer, blob, step.postcheck, targetNamespace)) {\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: true },\n \"none\"\n );\n return;\n }\n if (\n !(await evaluateCheck(producer, blob, step.precheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} is neither at origin nor destination`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { lastConfirmedStep: step.execute.dispatchId } }\n );\n }\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n if (\n !(await evaluateCheck(producer, blob, step.postcheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} failed its postcheck`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n {\n meta: {\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"partial\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n\n if (boundary === \"stepwise\") {\n const progress = {\n operationId,\n dispatchId: step.execute.dispatchId,\n skipped: false,\n };\n await onProgress?.(progress, \"none\");\n try {\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n } catch (error) {\n const sql = sliceDispatch(blob, step.execute);\n if (refusedWhole(error, sql, producer.dialect)) {\n const refused = refusal(site, step.execute.dispatchId, error, {\n effectState: \"none\",\n partial: true,\n });\n // Unrecorded, the announcement stands: it may have committed.\n await onProgress?.(\n progress,\n \"none\",\n `${refused.code}: ${refused.message}`\n )?.catch(() => undefined);\n throw refused;\n }\n throw new MigrationError(\n `Opaque stepwise dispatch ${step.execute.dispatchId} failed with an ambiguous outcome`,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: errorCause(error),\n meta: {\n ...siteMeta(site, step.execute.dispatchId),\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(progress, \"committed\");\n return;\n }\n\n await runDispatch(producer, blob, site, step.execute, targetNamespace);\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n}\n\nexport async function evaluateAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace?: string\n): Promise<boolean> {\n for (const check of checks) {\n if (!(await evaluateCheck(producer, blob, check, targetNamespace))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The one owner of \"authored checks must hold\": every one of `checks` holds,\n * else `refusal` is the command's MIGRATION_DRIFT. Inside one request (plan\n * D7) each is asserted there instead, as its {@link checkCondition}.\n */\nexport async function assertAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace: string | undefined,\n refusal: string,\n batch?: MigrationBatch\n): Promise<void> {\n const drift = () =>\n new MigrationError(refusal, VibORMErrorCode.MIGRATION_DRIFT);\n if (batch) {\n for (const check of checks) {\n const { sql, params } = checkCondition(blob, check, targetNamespace);\n batch.assert(sql, params, drift());\n }\n return;\n }\n if (!(await evaluateAllChecks(producer, blob, checks, targetNamespace))) {\n throw drift();\n }\n}\n","/**\n * The one DDL statement a transaction silently swallows.\n *\n * SQLite cannot alter a table in place, so `alterColumn`, `addForeignKey` and\n * both halves of a unique-constraint change go through\n * `SQLite3MigrationDriver.generateTableRecreation`: create `__new_<t>`, copy\n * the rows, `DROP TABLE <t>`, rename. `DROP TABLE` is the step that needs\n * foreign keys really disabled — with enforcement on, SQLite performs an\n * implicit `DELETE FROM` before removing the table, which either raises the\n * constraint or fires the referential action on every child row.\n *\n * `PRAGMA foreign_keys` is documented by SQLite as a NO-OP inside a\n * transaction, and all three places that execute generated DDL run the batch\n * inside one — `execute-dispatch.ts` and the SQLite recreation path.\n * MEASURED on better-sqlite3 at `5e5bc60`, recreating a populated table a\n * single child row pointed at:\n *\n * - `onDelete: noAction` -> `DROP TABLE` threw `FOREIGN KEY constraint\n * failed` and the push applied nothing;\n * - `onDelete: cascade` -> no error, and every child row was gone;\n * - `onDelete: setNull` -> no error, and every child's key was NULL.\n *\n * `PRAGMA defer_foreign_keys=ON` — the spelling SQLite does honor inside a\n * transaction — does not close it: it defers the violation counter the\n * implicit delete already incremented, so `noAction` merely moves its failure\n * from `DROP TABLE` to `COMMIT`, and the two silent halves stay silent.\n *\n * So the pragma is lifted out to bracket the transaction, which is SQLite's own\n * documented procedure — its step 1 (`PRAGMA foreign_keys=OFF`) precedes its\n * step 2 (`BEGIN`). Lifting it is what makes the disable real for the first\n * time, and a real disable is fail-open for the rest of the batch: a\n * `dropTable` sharing the batch would now orphan its children instead of\n * refusing. `assertForeignKeysIntact` is that hole closed — step 10 of the same\n * procedure — and it runs inside the transaction so a violation rolls the whole\n * batch back.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\n\n/**\n * `PRAGMA foreign_keys = OFF` / `= ON`, the only statement any migration driver\n * emits whose effect a transaction discards. Written by\n * `generateTableRecreation`; no other dialect emits it.\n */\nconst MATCH_FOREIGN_KEYS_PRAGMA =\n /^PRAGMA\\s+foreign_keys\\s*=\\s*(ON|OFF)\\s*;?$/i;\n\n/** A statement's leading whitespace and SQL comments. */\nconst LEADING_TRIVIA = /^(?:\\s+|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*/;\n\nconst DROPS_TABLE = /^DROP\\s+TABLE\\b/i;\n\n/**\n * The `DROP TABLE` a recreation or a `dropTable` renders (`\"name\"`), and the\n * plain spelling a hand-written transition may use, optionally in `main`.\n */\nconst MATCH_DROP_TABLE =\n /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:(?:main|\"main\")\\s*\\.\\s*)?(?:\"((?:[^\"]|\"\")+)\"|([A-Za-z_][\\w$]*))\\s*;?\\s*$/i;\n\nconst quote = createIdentifierQuoter('\"');\n\nexport interface ForeignKeyBracket {\n /** Runs before the transaction opens. */\n readonly disable: string;\n /** Runs after it closes, however it closes. */\n readonly enable: string;\n}\n\nexport interface LiftedStatements {\n /** `null` when nothing was lifted; the statements are then untouched. */\n readonly bracket: ForeignKeyBracket | null;\n readonly statements: string[];\n}\n\n/**\n * Whether this driver has no transaction to lift the pragmas out of — and so\n * nothing to prove the lift in.\n *\n * What the pragma does is the driver's declared claim: effectful SQLite work is\n * admitted only on a driver declaring `sqliteMigrationCapability`, whose\n * `foreignKeys: \"pragma\"` says `PRAGMA foreign_keys` between transactions takes\n * effect and reads back (`admission.ts` is that claim's one reader). The claim\n * is then verified on every lift. What is left is the transaction: without one,\n * a recreation that went wrong can neither be checked before it commits nor\n * rolled back, so it is refused (D1 is the stock case: one native batch, no\n * transaction).\n *\n * Exported because the SQLite driver asks the same question before it plans a\n * relation-bearing domain conversion (plan §7.4's D1 prerequisite).\n */\nexport function foreignKeyPragmasCannotBeLifted(driver: AnyDriver): boolean {\n return !driver.supportsTransactions;\n}\n\n/**\n * Takes the foreign-key pragmas out of a DDL batch so the caller can run them\n * around its transaction instead of inside it.\n *\n * Returns `bracket: null` — and the statements unchanged — when there is\n * nothing to lift, so every caller can run the result unconditionally. A batch\n * that needs the lift on a driver that cannot prove one is refused here,\n * before any of it runs.\n */\nexport function liftForeignKeyPragmas(\n driver: AnyDriver,\n statements: string[]\n): LiftedStatements {\n let disable: string | null = null;\n let enable: string | null = null;\n const rest: string[] = [];\n\n for (const statement of statements) {\n const trimmed = statement.trim();\n const match = trimmed.match(MATCH_FOREIGN_KEYS_PRAGMA);\n if (!match) {\n rest.push(statement);\n continue;\n }\n if (match[1]?.toUpperCase() === \"OFF\") {\n disable ??= trimmed;\n } else {\n enable ??= trimmed;\n }\n }\n\n // Half a bracket would leave enforcement off past the batch. Leave the batch\n // exactly as it came instead, so it fails the way it failed before rather\n // than succeeding with the database unguarded.\n if (!(disable && enable)) {\n return { bracket: null, statements };\n }\n if (foreignKeyPragmasCannotBeLifted(driver)) {\n throw new MigrationError(\n `The driver \"${driver.driverName}\" runs migrations without a transaction, so a SQLite table recreation cannot be proven to keep the rows that reference it: if \\`PRAGMA foreign_keys=OFF\\` did not take, \\`DROP TABLE\\` would delete or null every child row and nothing could roll it back. ` +\n \"The change is refused before any statement runs. Run it through a driver with transactions.\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n {\n meta: { driver: driver.driverName, feature: \"SQLite table recreation\" },\n }\n );\n }\n\n return { bracket: { disable, enable }, statements: rest };\n}\n\ninterface ForeignKeyCheckRow {\n table?: unknown;\n parent?: unknown;\n}\n\n/**\n * Runs one body inside the lifted transaction: on `transaction`, with every\n * `DROP TABLE` counted around, then `PRAGMA foreign_key_check`.\n */\nexport type InsideLift = <R>(\n transaction: AnyDriver,\n body: (producer: AnyDriver) => Promise<R>\n) => Promise<R>;\n\nconst unlifted: InsideLift = (transaction, body) => body(transaction);\n\n/**\n * Runs `work` with enforcement really off, restoring it however `work` ends.\n * Call it OUTSIDE the transaction `work` opens — that placement is the whole\n * point — and run that transaction's statements through the `inside` it is\n * handed. Without a bracket nothing is lifted and `inside` adds nothing.\n *\n * The lift is verified, not assumed. The driver's `beforeForeignKeysOff` hook\n * runs first, and `PRAGMA foreign_keys` must read 0 after the disable — or the\n * change is refused before any of it runs — and 1 after the re-enable. Inside,\n * every table referencing a dropped table must keep its rows and its keys\n * across that `DROP TABLE`, which still catches a driver whose read-back lies,\n * and `PRAGMA foreign_key_check` must find nothing before the commit.\n */\nexport async function withForeignKeysLifted<T>(\n driver: AnyDriver,\n bracket: ForeignKeyBracket | null,\n work: (inside: InsideLift) => Promise<T>\n): Promise<T> {\n if (!bracket) {\n return await work(unlifted);\n }\n\n await driver[\"beforeForeignKeysOff\"]?.();\n await driver._executeRaw(terminate(bracket.disable));\n let completed = false;\n try {\n await assertEnforcement(driver, 0);\n const result = await work(async (transaction, body) => {\n const value = await body(keepingChildren(transaction));\n await assertForeignKeysIntact(transaction);\n return value;\n });\n completed = true;\n return result;\n } finally {\n await driver._executeRaw(terminate(bracket.enable));\n if (completed) await assertEnforcement(driver, 1);\n }\n}\n\nfunction terminate(statement: string): string {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n}\n\nasync function assertEnforcement(\n driver: AnyDriver,\n expected: 0 | 1\n): Promise<void> {\n const { rows } = await driver._executeRaw<{ foreign_keys?: unknown }>(\n \"PRAGMA foreign_keys;\"\n );\n const read = rows[0]?.foreign_keys;\n if (Number(read) === expected) return;\n throw new MigrationError(\n expected === 0\n ? `PRAGMA foreign_keys reads ${String(read)} after PRAGMA foreign_keys=OFF on the driver \"${driver.driverName}\", so a SQLite table recreation would delete or null the rows that reference it. The change is refused before any statement runs; foreign keys were re-enabled.`\n : `The change committed, but PRAGMA foreign_keys reads ${String(read)} after PRAGMA foreign_keys=ON on the driver \"${driver.driverName}\": foreign keys may not be enforced on this connection. Disconnect the client before running other queries on it.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { driver: driver.driverName, pragma: \"foreign_keys\", expected } }\n );\n}\n\n/**\n * `transaction`, with every `DROP TABLE` run between two counts of each table\n * that references the dropped one (built the way every execution view in this\n * layer is: an `Object.create` restating one member).\n *\n * With enforcement really off, `DROP TABLE` touches no other table. With it on\n * — a driver whose `PRAGMA foreign_keys` read-back lies — it deletes or nulls\n * every child row, which `foreign_key_check` cannot see afterwards. Counting\n * right around the statement, rather than around the whole batch, leaves the\n * batch free to write those rows itself.\n */\nfunction keepingChildren(transaction: AnyDriver): AnyDriver {\n const view: AnyDriver = Object.create(transaction);\n Object.defineProperty(view, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const parent = droppedTable(sql);\n if (parent === undefined) {\n return await transaction._executeRaw(sql, params);\n }\n const children = await referencingColumns(transaction, parent);\n const before = await countChildren(transaction, children);\n const result = await transaction._executeRaw(sql, params);\n const after = await countChildren(transaction, children);\n const changed = [...children].flatMap(([child, columns], i) =>\n [`\"${child}\" rows`, ...columns.map((c) => `\"${child}\".\"${c}\" non-null`)]\n .map((label, k) => `${label} ${before[i]?.[k]} -> ${after[i]?.[k]}`)\n .filter((_, k) => before[i]?.[k] !== after[i]?.[k])\n );\n if (changed.length > 0) {\n throw new MigrationError(\n `Rows referencing \"${parent}\" changed when it was dropped with foreign keys lifted (${changed.join(\", \")}), so the batch was rolled back. ` +\n \"The driver did not really disable foreign keys, and DROP TABLE fired the referential actions.\",\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { driver: transaction.driverName, table: parent } }\n );\n }\n return result;\n },\n });\n return view;\n}\n\n/**\n * The table a `DROP TABLE` statement drops, or `undefined` for any other\n * statement. A drop whose name it cannot read is refused: its children could\n * not be counted, and the census must not be skipped silently.\n */\nfunction droppedTable(sql: string): string | undefined {\n const statement = sql.replace(LEADING_TRIVIA, \"\");\n if (!DROPS_TABLE.test(statement)) return;\n const match = statement.match(MATCH_DROP_TABLE);\n const name = match?.[1]?.replaceAll('\"\"', '\"') ?? match?.[2];\n if (name !== undefined) return name;\n throw new MigrationError(\n \"A SQLite migration that recreates a table also runs a DROP TABLE whose table name cannot be read, so the rows referencing that table cannot be counted around the drop. \" +\n 'The batch was rolled back. Spell the drop as DROP TABLE \"name\" (or a plain identifier) in its own statement.',\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n\n/** Every other table with a foreign key to `parent`, and its referencing columns. */\nasync function referencingColumns(\n transaction: AnyDriver,\n parent: string\n): Promise<Map<string, string[]>> {\n const { rows } = await transaction._executeRaw<{\n child: unknown;\n column: unknown;\n }>(\n `SELECT DISTINCT m.\"name\" AS \"child\", f.\"from\" AS \"column\" FROM sqlite_master AS m, pragma_foreign_key_list(m.\"name\") AS f WHERE m.\"type\" = 'table' AND f.\"table\" = ? COLLATE NOCASE AND m.\"name\" <> ? COLLATE NOCASE`,\n [parent, parent]\n );\n const children = new Map<string, string[]>();\n for (const row of rows) {\n const child = String(row.child);\n const columns = children.get(child) ?? [];\n columns.push(String(row.column));\n children.set(child, columns);\n }\n return children;\n}\n\n/** Per child: its row count, then the non-null count of each referencing column. */\nasync function countChildren(\n transaction: AnyDriver,\n children: ReadonlyMap<string, readonly string[]>\n): Promise<number[][]> {\n const counts: number[][] = [];\n for (const [child, columns] of children) {\n const keys = columns.map(\n (column, k) => `, count(${quote(column)}) AS \"k${k}\"`\n );\n const { rows } = await transaction._executeRaw<Record<string, unknown>>(\n `SELECT count(*) AS \"rows\"${keys.join(\"\")} FROM ${quote(child)}`\n );\n const row = rows[0] ?? {};\n counts.push([row.rows, ...columns.map((_, k) => row[`k${k}`])].map(Number));\n }\n return counts;\n}\n\n/**\n * Refuses a lifted batch that would commit against a broken reference: the\n * last statement `inside` runs, in the transaction, so the throw takes the\n * batch back.\n *\n * This is why the lift is not a fail-open trade. Lifting the pragma disables\n * enforcement for the whole batch, not just the recreation, so a `dropTable`\n * or a rebuild that sheds a referenced column could commit orphans the\n * un-lifted — and therefore never actually disabled — batch would have refused.\n * `PRAGMA foreign_key_check` is step 10 of SQLite's own recreation procedure.\n *\n * It cannot tell a reference the batch broke from one it merely found, and\n * refuses either way: SQLite's procedure says a reported violation means the\n * schema change is to be abandoned.\n */\nexport async function assertForeignKeysIntact(\n transaction: AnyDriver\n): Promise<void> {\n const result = await transaction._executeRaw<ForeignKeyCheckRow>(\n \"PRAGMA foreign_key_check;\"\n );\n if (result.rows.length === 0) {\n return;\n }\n\n const offenders = [\n ...new Set(\n result.rows.map(\n (row) => `${String(row.table)} -> ${String(row.parent ?? \"?\")}`\n )\n ),\n ];\n throw new MigrationError(\n `Migration left ${result.rows.length} row(s) violating a foreign key (${offenders.join(\", \")}). ` +\n \"A SQLite table recreation runs with foreign keys disabled, so the batch was rolled back rather than committed against a broken reference.\",\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n","/**\n * The ONE pinned migration session (§3.5): one physical producer reserved for\n * a command, the lock proven on it, its loss and limits tracked, and the\n * producer condemned whenever a lock or unlock proof fails. PostgreSQL and\n * SQLite hold the lock in their transactions instead (plans D1, S5); only\n * PostgreSQL stepwise work, PlanetScale's Neki (the whole command) and MySQL\n * keep a session lock. The dialect's lock and session statements come from\n * the bound migration driver.\n */\n\nimport type {\n AnyDriver,\n MigrationFrame,\n MigrationFrameDriver,\n} from \"../drivers/driver\";\nimport { normalizeDriverError } from \"../drivers/error-mapping\";\nimport {\n createExecutionContext,\n snapshotExecutionContext,\n} from \"../drivers/execution-context\";\nimport {\n CLEANUP_BOUND_MS,\n leasePinnedCommand,\n type PinnedSessionControl,\n type PinnedSessionReservation,\n} from \"../drivers/shared/pinned-session\";\nimport { settleWithin } from \"../drivers/shared/settle\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport type { TransactionOptionSupport } from \"../drivers/shared/transaction-options\";\nimport { runTransactionLifecycle } from \"../drivers/shared/transactions\";\nimport type { BatchQuery, QueryExecutionContext } from \"../drivers/types\";\nimport {\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n MigrationError,\n VibORMError,\n VibORMErrorCode,\n} from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ResolvedExtensionChain } from \"../extensions/chain\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { providerFacts, providerRefused } from \"./execute-dispatch\";\nimport { liftForeignKeyPragmas, withForeignKeysLifted } from \"./foreign-keys\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"./limits\";\nimport { runsConcurrently } from \"./statement-safety\";\nimport { type CatalogRead, readsCommandNamespace } from \"./target\";\nimport { createQueryExecutor } from \"./utils\";\n\n/**\n * The migration lock's key, \"viborm\" in hex. PostgreSQL's advisory lock is\n * database-wide, so estates in one database serialize with each other; MySQL\n * names its lock after the database instead (`drivers/mysql/pinned-session.ts`).\n */\nconst MIGRATION_LOCK_ID = 0x76_69_62_6f_72_6d;\n/**\n * The first pause between two PostgreSQL lock tries, doubled up to the cap. A\n * longer cap sends fewer tries but lets newcomers take a freed lock first: at\n * 1 s, waits under contention stretched to `lockWait`.\n */\nconst LOCK_RETRY_MS = 50;\nconst LOCK_RETRY_CAP_MS = 250;\n\n/**\n * A condition true while no command holds the migration lock (plan D5), for a\n * decision read before the lock.\n */\nexport function migrationLockFree(command: BoundMigrationDriver): string {\n return command.generateLockFree(MIGRATION_LOCK_ID);\n}\n\n/**\n * Whether this driver can pin a session: the provider's `pinnedSession()`\n * hook is the capability, asked by admission before any provider work.\n */\nexport function canPinSession(driver: AnyDriver): boolean {\n return driver[\"pinnedSession\"] !== undefined;\n}\n\n/**\n * Whether `driver` runs migration work with no session, one atomic request per\n * transactional group (plan D7): Neon HTTP is the shipped case.\n */\nexport function runsMigrationBatches(driver: AnyDriver): boolean {\n return (\n driver.dialect === \"postgresql\" &&\n !canPinSession(driver) &&\n driver.supportsBatch &&\n driver.supportsOrderedCommittedSegments\n );\n}\n\n/**\n * One transactional group as ONE request on a transport with no session\n * (plan D7). Statements sent to `producer` are recorded, not run; the request\n * opens with the limits and the bounded transaction lock, and what the command\n * would read inside its transaction is asserted there instead.\n */\nexport interface MigrationBatch {\n readonly producer: AnyDriver;\n /** `condition`, SQL with its own `$n` parameters, holds here, else `refusal` is the command's failure. */\n assert(\n condition: string,\n params: readonly unknown[],\n refusal: MigrationError\n ): void;\n /**\n * Resolves once the request committed, even when its reply was then\n * unreadable. Throws a `MigrationError` when the server refused (and rolled\n * back) the request; any other failure is a lost reply, after which the\n * request may have committed.\n */\n send(): Promise<void>;\n}\n\n/**\n * An assertion's refusal leaves its SQLSTATE (`P0V` + its position in base 36)\n * in a transaction-local setting, which this block raises: the SQLSTATE\n * survives diagnostics redaction where the message does not.\n */\nconst RAISE_REFUSAL = `DO $viborm$BEGIN IF current_setting('viborm.refusal') <> '' THEN RAISE EXCEPTION 'VibORM migration assertion %', current_setting('viborm.refusal') USING ERRCODE = current_setting('viborm.refusal'); END IF; END$viborm$`;\nconst REFUSAL = /^P0V([0-9A-Z]{2})$/;\n\nexport function openMigrationBatch(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): MigrationBatch {\n const queries: BatchQuery[] = [\n { sql: postgresSessionLimits(migrationDriver.limits).transaction },\n ];\n const refusals: MigrationError[] = [];\n const producer: AnyDriver = Object.create(driver);\n Object.defineProperty(producer, \"_executeRaw\", {\n value: (sql: string, params?: unknown[]) => {\n queries.push({ sql, params });\n return Promise.resolve({ rows: [], rowCount: 0 });\n },\n });\n const batch: MigrationBatch = {\n producer,\n assert(condition, params, refusal) {\n queries.push(\n {\n sql: `SELECT set_config('viborm.refusal', CASE WHEN ${condition} THEN '' ELSE 'P0V${refusals.length.toString(36).toUpperCase().padStart(2, \"0\")}' END, true)`,\n params: [...params],\n },\n { sql: RAISE_REFUSAL }\n );\n refusals.push(refusal);\n },\n async send() {\n let committed = false;\n try {\n await driver._executeBatch(queries, undefined, undefined, () => {\n committed = true;\n return Promise.resolve();\n });\n } catch (failure) {\n if (committed) return;\n if (!providerRefused(failure)) throw failure;\n const position = REFUSAL.exec(String(failure.meta.providerSqlState));\n const refusal = position && refusals[Number.parseInt(position[1]!, 36)];\n if (refusal) throw refusal;\n throw new MigrationError(\n \"The server refused the migration request, which rolled back: nothing of it was applied.\",\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: failure,\n meta: { providerSqlState: failure.meta.providerSqlState },\n }\n );\n }\n },\n };\n batch.assert(\n `(SELECT acquired FROM (${migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)}) AS lock)`,\n [],\n lockNotConfirmed(migrationDriver)\n );\n return batch;\n}\n\n/**\n * What a pinned session runs under besides its body (plan S1): the bound on\n * its reservation, the PostgreSQL command's limits, and, for a driver whose\n * one connection IS the session (SQLite), that session.\n */\nexport interface PinnedSessionScope {\n readonly connectionWait: number;\n readonly limits?: PostgresSessionLimits | undefined;\n readonly session?: () => Promise<PinnedSessionReservation<unknown>>;\n /** The command's `diagnostics`, disclosed by every statement of the session. */\n readonly diagnostics?: DiagnosticDisclosure | undefined;\n}\n\n/** The statements that impose, lift and reset one PostgreSQL session's limits. */\ninterface PostgresSessionLimits {\n /** Which of the optional settings this server has, read before `enter`. */\n readonly settings: string;\n /** Imposes the limits on the session, naming only `present` settings. */\n enter(present: readonly string[]): string;\n /** Resets what `enter(present)` set, one constant `RESET` each. */\n exit(present: readonly string[]): readonly string[];\n readonly transaction: string;\n readonly unbound: string;\n readonly rebound: string;\n}\n\nconst DEFAULT_SCOPE: PinnedSessionScope = {\n connectionWait: DEFAULT_MIGRATION_LIMITS.connectionWait,\n};\n\n/**\n * Runs `body` against ONE reserved producer: this driver with its client\n * pinned to the reservation, so every statement, transactions included, runs\n * on one physical session (§3.5).\n *\n * The producer is discarded rather than released when the body throws or\n * condemns it; a LOST session is never written to again, and its failure\n * surfaces as the retryable connection error it is (plan S2).\n */\nexport async function withPinnedSession<D extends AnyDriver, T>(\n driver: D,\n body: (pinned: D, control: SessionControl) => Promise<T>,\n scope: PinnedSessionScope = DEFAULT_SCOPE\n): Promise<T> {\n const reserve = scope.session ?? driver[\"pinnedSession\"];\n if (reserve === undefined) {\n // A custom driver with no hook, or a view that IS a reserved session\n // (`createPinnedSessionView` withdraws the hook); admission refuses the\n // shipped paths earlier.\n throw new FeatureNotSupportedError(\n driver.driverName,\n \"pinnedSession\",\n \"No session can be reserved through this driver: either the transport has no interactive session at all, or this view is itself one reserved session and reserving again would take a SECOND connection. A migration lock is session-scoped, so either way it could be released by a different connection — or never released at all.\"\n );\n }\n\n const runSession = async (): Promise<T> => {\n // A server that accepts the socket and never answers is bounded here.\n const reservation = await settleWithin(\n reserve.call(driver),\n scope.connectionWait,\n () => connectionWaitError(driver.driverName, scope.connectionWait),\n (late) => {\n late.release(true).catch(() => undefined);\n }\n );\n const control = controlSession(driver, reservation);\n const { limits } = scope;\n const view = createPinnedSessionView(\n driver,\n reservation.session,\n control,\n limits,\n scope.diagnostics\n );\n\n // Converted only when the failure IS the loss: a failure the command hit\n // first, whose cleanup then went unanswered, stays primary.\n const surface = (failure: unknown): unknown =>\n control.lost(failure, true)\n ? connectionLostError(driver.driverName, failure)\n : failure;\n\n // Limits a stepwise program set on the session must not go back to the\n // pool; a failed reset is RETURNED, so the release after it always runs.\n // A session whose reset failed still carries them: it is abandoned\n // (destroyed, never released to the pool) and the failure surfaces.\n const resetLimits = async (): Promise<unknown> => {\n const present = control.limited();\n if (limits === undefined || present === undefined || control.lost()) {\n return undefined;\n }\n try {\n // Each reset is one cleanup statement, bounded on its own.\n for (const statement of limits.exit(present)) {\n await control.cleanup(() => view._executeRaw(statement));\n }\n return undefined;\n } catch (resetFailure) {\n const lostConnection = control.lost(resetFailure, true);\n control.abandon();\n return lostConnection\n ? resetFailure\n : limitsRefused(driver.driverName, \"reset\", resetFailure);\n }\n };\n\n // The first failure stays primary; later ones are recorded beside it.\n const releaseAfter = async (\n surfaced: unknown,\n resetFailure: unknown\n ): Promise<unknown> => {\n let failure =\n resetFailure === undefined\n ? surfaced\n : withSuppressedFailure(surfaced, resetFailure);\n try {\n await reservation.release(true, control.lost());\n } catch (releaseFailure) {\n failure = withSuppressedFailure(failure, releaseFailure);\n }\n return failure;\n };\n\n let value: T;\n try {\n value = await body(view, control);\n } catch (bodyFailure) {\n // Surfaced first: it is what tells the reset the session is lost.\n throw await releaseAfter(surface(bodyFailure), await resetLimits());\n }\n const resetFailure = await resetLimits();\n if (resetFailure !== undefined) {\n throw await releaseAfter(surface(resetFailure), undefined);\n }\n // Nothing else failed, so a release failure IS the failure.\n await reservation.release(control.discarded(), false);\n return value;\n };\n\n // A dedicated connection needs no lease: the real lock arbitrates.\n if (!driver[\"serializeTransactions\"]) {\n return runSession();\n }\n // A single-connection driver runs the whole session as ONE job of its queue\n // (§3.5): a narrower lease lets a second command in, and a PostgreSQL\n // session advisory lock is reentrant. A transaction-bound caller is refused\n // before the lease rather than waiting on its own holder.\n driver[\"assertBaseOperationAllowedDuringTransaction\"](\n driver[\"resolveExecutionContext\"](undefined, \"pinnedSession\")\n );\n const queue = driver[\"connectionQueue\"];\n const identify = driver[\"physicalPinnedSession\"];\n if (identify === undefined) {\n return queue.enqueue(runSession);\n }\n // The physical lease keeps ANOTHER driver over the same client out, and\n // refuses one whose advisory-lock state was condemned.\n const session = await identify.call(driver);\n return leasePinnedCommand(driver.driverName, session, () =>\n queue.enqueue(runSession)\n );\n}\n\n/** The control of one reserved session, and what it knows about its connection. */\ninterface SessionControl extends PinnedSessionControl {\n discarded(): boolean;\n lost(failure?: unknown, reported?: boolean): boolean;\n /** Sends nothing more on this session, whose state can no longer be made clean. */\n abandon(): void;\n /** Records that the session itself now carries the command's limits, with the optional settings `present`. */\n limit(present: readonly string[]): void;\n /** The optional settings it carries when it does, and so must be reset before it goes back. */\n limited(): readonly string[] | undefined;\n}\n\nfunction controlSession(\n driver: AnyDriver,\n reservation: PinnedSessionReservation<unknown>\n): SessionControl {\n let discarded = false;\n let lost = false;\n let limited: readonly string[] | undefined;\n const control = {\n discard: () => {\n discarded = true;\n },\n discarded: () => discarded,\n abandon: () => {\n lost = true;\n },\n limit: (present: readonly string[]) => {\n limited = present;\n },\n limited: () => limited,\n /** With `reported`, whether `failure` itself reports the loss. */\n lost: (failure?: unknown, reported = false) => {\n const reports =\n reservation.lost?.() !== undefined ||\n reportsLostConnection(driver, failure);\n lost ||= reports;\n return reported ? reports : lost;\n },\n cleanup: <R>(run: () => Promise<R>) =>\n settleWithin(run(), CLEANUP_BOUND_MS, () => {\n lost = true;\n return new ConnectionError(\n `A cleanup statement of the pinned migration session on driver \"${driver.driverName}\" went unanswered for ${CLEANUP_BOUND_MS} ms; its connection is treated as lost.`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driver.driverName, operation: \"pinnedSession\" },\n }\n );\n }),\n };\n return control;\n}\n\n/**\n * Whether `failure`, or anything it was caused by, is the provider reporting\n * that the connection itself failed, by the driver error mapping's one\n * classifier.\n */\nfunction reportsLostConnection(driver: AnyDriver, failure: unknown): boolean {\n let link: unknown = failure;\n for (let depth = 0; depth < 8 && link instanceof Error; depth += 1) {\n const normalized =\n link instanceof VibORMError\n ? link\n : normalizeDriverError(link, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n });\n if (normalized instanceof ConnectionError) return true;\n link = link.cause;\n }\n return false;\n}\n\n/**\n * The failure a command on a lost session surfaces: the provider's own report\n * when it already is a connection error or a migration outcome, otherwise a\n * retryable connection error carrying it (pg reports a dead socket as an\n * ordinary query failure).\n */\nfunction connectionLostError(driverName: string, failure: unknown): unknown {\n if (failure instanceof ConnectionError || failure instanceof MigrationError) {\n return failure;\n }\n return new ConnectionError(\n `The connection of the pinned migration session on driver \"${driverName}\" was lost. VibORM sent nothing more on it: the server rolls back its open transaction and frees its migration lock when that session ends. Run the command again; it re-reads the marker under the lock.`,\n {\n code: VibORMErrorCode.CONNECTION_FAILED,\n cause: errorCause(failure),\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\nfunction connectionWaitError(driverName: string, ms: number): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" got no connection for the migration session within ${ms} ms (connectionWait). Nothing was sent; the command can be retried.`,\n {\n code: VibORMErrorCode.CONNECTION_TIMEOUT,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * A chain of no extension that carries the client's `disclosure` alone: a\n * driver discloses a failure as the client would, and this one has no\n * observer, transform or row scope of the client's to bring.\n */\nfunction disclosingChain(\n disclosure: DiagnosticDisclosure\n): ResolvedExtensionChain {\n return { extensions: [], disclosure };\n}\n\n/**\n * This driver, viewed with its client pinned to one reserved session: the\n * same driver in every other respect, with the transport assertion forwarded\n * exactly. Every statement it sends records a lost connection (plan S2).\n */\nfunction createPinnedSessionView<D extends AnyDriver>(\n driver: D,\n session: unknown,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined,\n diagnostics: DiagnosticDisclosure | undefined\n): D {\n const view: D = Object.create(driver);\n // The session's statements, its transactions' included, disclose failures\n // as the command's client does: only its `diagnostics`, not its chain.\n if (diagnostics !== undefined) {\n Object.defineProperty(view, \"boundContext\", {\n value: snapshotExecutionContext(\n createExecutionContext({}, undefined, disclosingChain(diagnostics)),\n driver[\"boundContext\"]\n ),\n });\n }\n const support = driver[\"transactionOptionSupport\"]();\n const executeRaw = driver[\"executeRaw\"];\n const beforeForeignKeysOff = driver[\"beforeForeignKeysOff\"];\n Object.defineProperties(view, {\n client: { value: session, writable: true },\n // A pinned view must never start a second connection.\n initPromise: { value: null, writable: true },\n // The view IS the queue's serialized job: waiting on the queue would wait\n // for its own holder.\n serializeTransactions: { value: false },\n // The view is the reservation, so it has none to give (§3.5): a nested\n // lock refuses instead of taking a second connection.\n pinnedSession: { value: undefined },\n // The provider's own `transaction()` acquires a connection.\n transaction: {\n value(\n this: AnyDriver,\n pinned: unknown,\n fn: (tx: unknown) => Promise<unknown>,\n context?: QueryExecutionContext\n ) {\n return runPinnedTransaction(this, pinned, fn, context, control, limits);\n },\n },\n executeRaw: {\n async value(\n this: AnyDriver,\n client: unknown,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ) {\n // Nothing more is sent on a lost connection (plan S2).\n if (control.lost())\n throw connectionLostError(driver.driverName, undefined);\n const locked = LOCKED.get(this);\n await locked?.before(sql);\n // A `CONCURRENTLY` statement runs without the session's limits, which\n // would cut it short: an INVALID index, a pending detach (plan S1).\n const send = (statement: string, parameters?: unknown[]) =>\n executeRaw.call(this, client, statement, parameters, context);\n const run = async () => {\n try {\n if (limits === undefined || !runsConcurrently(sql)) {\n return await send(sql, params);\n }\n await send(limits.unbound);\n const result = await send(sql, params);\n await send(limits.rebound);\n return result;\n } catch (failure) {\n control.lost(failure);\n throw failure;\n }\n };\n // Awaited, never returned or chained: `run` and `failed` can reject\n // before an `async` frame or a `.catch` adopts their promise a\n // microtask later, which workerd's process emulation reports as\n // unhandled (`nodejs-compat-rejections.test.ts`).\n try {\n return await run();\n } catch (failure) {\n if (locked === undefined) throw failure;\n return await locked.failed(failure);\n }\n },\n },\n // The lease holds the queue for the whole session, so there is no queue\n // wait left to bound.\n transactionOptionSupport: {\n value: (): TransactionOptionSupport =>\n support.maxWait === \"queue\"\n ? {\n ...support,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"the pinned session holds the connection queue's lease for its whole duration, so there is no queue wait to bound\",\n }\n : support,\n },\n migrationNamespaceAttestation: {\n value: driver.migrationNamespaceAttestation,\n },\n // The hook runs outside any transaction: a SQLite command's locked\n // transaction ends before it.\n beforeForeignKeysOff: {\n async value(this: AnyDriver) {\n await LOCKED.get(this)?.between();\n await beforeForeignKeysOff?.call(this);\n },\n },\n });\n return view;\n}\n\n/**\n * One transaction on the already-reserved session, as `BEGIN`/`COMMIT`/\n * `ROLLBACK` on that producer: under a lock the session already holds\n * (MySQL's, or a PostgreSQL stepwise program's), opening with the PostgreSQL\n * limits (plan S1), and sending no `ROLLBACK` after a lost connection (S2).\n */\nfunction runPinnedTransaction<T>(\n view: AnyDriver,\n session: unknown,\n fn: (tx: unknown) => Promise<T>,\n context: QueryExecutionContext | undefined,\n control: PinnedSessionControl,\n limits: PostgresSessionLimits | undefined\n): Promise<T> {\n const locked = LOCKED.get(view)?.group(() => fn(session));\n if (locked !== undefined) return locked;\n const statement = (sql: string) =>\n view[\"executeRaw\"](session, sql, undefined, context);\n return runTransactionLifecycle({\n begin: () => statement(\"BEGIN\"),\n // The session IS the transaction: a nested `$transaction` is a SAVEPOINT.\n callback: async () => {\n if (limits !== undefined) await statement(limits.transaction);\n return fn(session);\n },\n commit: () => statement(\"COMMIT\"),\n rollback: () =>\n control.lost() ? undefined : control.cleanup(() => statement(\"ROLLBACK\")),\n });\n}\n\n/**\n * Runs `body` on ONE reserved producer holding this estate's migration lock,\n * with the migration driver THIS command renders from (§5.2).\n *\n * MySQL holds a session lock for the whole command, and so does PostgreSQL\n * where the server mixes no session and transaction advisory locks\n * (`holdsSessionLock`, PlanetScale's Neki); PostgreSQL and SQLite otherwise\n * run it in locked transactions ({@link lockTransactions}); a batch transport\n * locks each request (plan D7). `unlocked` (PostgreSQL) runs first, before any\n * lock, for a decision one statement proves while no command holds the lock\n * (plan D5); a failure that is not the lost connection only means it could not\n * decide. It is not asked where the session lock is held alone: its proof\n * takes the transaction lock.\n */\nexport function withLockedMigrationProducer<T>(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (pinned: AnyDriver, command: BoundMigrationDriver) => Promise<T>,\n unlocked?: (session: AnyDriver, lockFree: string) => Promise<T | undefined>\n): Promise<T> {\n const { dialect } = migrationDriver.target;\n const limits = migrationDriver.limits;\n const run = async (producer: AnyDriver) =>\n body(\n producer,\n await validateAndSelectMigrationTarget(producer, migrationDriver)\n );\n if (migrationDriver.holdLock)\n return migrationDriver.holdLock(driver, limits.lockWait, () => run(driver));\n const lockFree = migrationLockFree(migrationDriver);\n const scope: PinnedSessionScope = {\n connectionWait: limits.connectionWait,\n diagnostics: migrationDriver.diagnostics,\n limits:\n dialect === \"postgresql\" ? postgresSessionLimits(limits) : undefined,\n session:\n dialect === \"sqlite\"\n ? async () => ({\n session: await driver[\"getClient\"]({ operation: \"pinnedSession\" }),\n release: () => Promise.resolve(),\n })\n : undefined,\n };\n if (runsMigrationBatches(driver)) {\n return (async () => {\n const answer = await unlocked?.(driver, lockFree).catch(() => undefined);\n if (answer !== undefined) return answer;\n return run(driver);\n })();\n }\n if (dialect === \"mysql\") {\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // A lock never proven is not this session's to release (§3.5).\n await acquireLock(pinned, migrationDriver, control);\n let result: T;\n try {\n result = await run(pinned);\n } catch (error) {\n await releaseAfterFailure(pinned, migrationDriver, control, error);\n throw error;\n }\n await releaseLock(pinned, migrationDriver, control);\n return result;\n },\n scope\n );\n }\n return withPinnedSession(\n driver,\n async (pinned, control) => {\n // PlanetScale's Neki holds the session lock alone, for the whole\n // command; its decision is read under that lock, never before it.\n const holdsSession =\n dialect === \"postgresql\" &&\n (await migrationDriver.holdsSessionLock((sql, params) =>\n pinned._executeRaw(sql, params)\n ));\n try {\n const answer = holdsSession\n ? undefined\n : await unlocked?.(pinned, lockFree);\n if (answer !== undefined) return answer;\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n }\n // An admitted SQLite driver without transactions runs under the\n // driver's queue lease alone.\n if (!pinned.supportsTransactions) return run(pinned);\n const locked = lockTransactions(\n pinned,\n migrationDriver,\n control,\n scope.limits\n );\n LOCKED.set(pinned, locked);\n let result: T;\n try {\n if (holdsSession) await locked.hold();\n result = await run(pinned);\n } catch (error) {\n await locked.abort(error);\n throw error;\n }\n await locked.finish();\n return result;\n },\n scope\n );\n}\n\n/**\n * The locked transactions one PostgreSQL or SQLite command runs in (plans D1,\n * S5), opened on demand before each statement: PostgreSQL `BEGIN`, its limits\n * and the bounded transaction lock; SQLite `BEGIN IMMEDIATE`. The first opens\n * before the namespace proof, so every decision is read under the lock.\n *\n * PostgreSQL stepwise work and `CONCURRENTLY` statements take the session lock\n * inside the open locked transaction, so the lock is never let go between the\n * decision and the work; where the command holds the session lock from its\n * start (`hold`, PlanetScale's Neki), no transaction lock is taken at all. SQLite's `PRAGMA foreign_keys` switch runs between\n * two transactions. A commit without the session lock lets the lock go, and\n * {@link lockedSinceDecision} is then false.\n */\ninterface LockedTransactions {\n /** Readies the session for one statement sent outside a group. */\n before(sql: string): Promise<void>;\n /** Ends what one statement's failure ended, then rethrows it. */\n failed(failure: unknown): Promise<never>;\n /** Runs one transactional group, or `undefined` once stepwise work took the session lock. */\n group<T>(fn: () => Promise<T>): Promise<T> | undefined;\n /** Marks the work about to run as stepwise (PostgreSQL). */\n stepwise(): void;\n /**\n * Takes the session lock alone, in autocommit, before the command's first\n * statement, waiting as `begin` does; the session's limits follow it\n * (PlanetScale's Neki). Every transaction after it is a plain one.\n */\n hold(): Promise<void>;\n /** Ends the open locked transaction: SQLite's pragma, a PostgreSQL bootstrap. */\n between(): Promise<void>;\n /**\n * Ends it before the caller's own work. A session lock held alone (Neki) is\n * released too, the session's limits reset first, and both are taken again\n * before the next statement: the lock is then not continuous.\n */\n letGo(): Promise<void>;\n /** Whether the lock has been held without a gap since the first read. */\n continuous(): boolean;\n /** Ends a command that succeeded: commits, then releases the session lock. */\n finish(): Promise<void>;\n /** Ends a command that failed: rolls back, releases, never replaces `cause`. */\n abort(cause: unknown): Promise<void>;\n}\n\nconst LOCKED = new WeakMap<object, LockedTransactions>();\n\n/**\n * A frame from the driver the capability says opens them. A declaration that\n * claims frames without the hook would lock nothing, so it is refused here,\n * before the command's first statement.\n */\nfunction openFrame(driver: AnyDriver): Promise<MigrationFrame> {\n if (!opensFrames(driver))\n throw new MigrationError(\n `The SQLite driver \"${driver.driverName}\" declares \\`exclusion: \"frame\"\\` and implements no \\`openMigrationFrame()\\`, so no migration lock can be taken.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { driver: driver.driverName } }\n );\n return driver.openMigrationFrame();\n}\nconst opensFrames = (\n driver: AnyDriver\n): driver is AnyDriver & MigrationFrameDriver =>\n typeof Reflect.get(driver, \"openMigrationFrame\") === \"function\";\n\n/** The switch SQLite ignores inside a transaction; its read form runs anywhere. */\nconst FOREIGN_KEYS_SWITCH = /^\\s*PRAGMA\\s+foreign_keys\\s*=/i;\n\nfunction lockTransactions(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: SessionControl,\n limits: PostgresSessionLimits | undefined\n): LockedTransactions {\n const sqlite = migrationDriver.target.dialect === \"sqlite\";\n // `exclusion: \"frame\"`: the driver's platform transaction is the lock, and\n // it stands where the statements below would be sent.\n const frames =\n migrationDriver.sqliteMigrationCapability?.exclusion === \"frame\";\n // The protocol's own statements, on the same session, past `before`.\n const direct: AnyDriver = Object.create(pinned);\n const run = <T = Record<string, unknown>>(sql: string) =>\n direct._executeRaw<T>(sql);\n let frame: MigrationFrame | undefined;\n const end = async (outcome: \"commit\" | \"rollback\"): Promise<void> => {\n if (frame === undefined) {\n await run(outcome === \"commit\" ? \"COMMIT\" : \"ROLLBACK\");\n return;\n }\n const settled = frame;\n frame = undefined;\n await settled[outcome]();\n };\n let open = false;\n let sessionLocked = false;\n // Held from the command's start (`hold`): each committed group still ends\n // `continuous`, so every group re-reads the marker as one under\n // transaction locks does, and Neki's split parts prove their attempt.\n let heldAlone = false;\n let armed = false;\n let continuous = true;\n let grouped = false;\n\n const rollback = async (): Promise<void> => {\n if (!open) return;\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n // A frame is the driver's own pending transaction, not a statement on the\n // connection: left unsettled, it would hold every later statement.\n if (control.lost() && frame === undefined) return;\n await control.cleanup(() => end(\"rollback\"));\n };\n const commit = async (): Promise<void> => {\n await end(\"commit\");\n open = false;\n continuous &&= sessionLocked && !heldAlone;\n };\n // SQLite's lock IS its BEGIN IMMEDIATE: `lockWait` bounds that one\n // statement's busy wait, then the connection's own timeout is restored.\n // A frame has no wait to bound: the driver's queue lease is already held.\n const beginImmediate = async (): Promise<void> => {\n if (frames) {\n frame = await openFrame(direct);\n return;\n }\n const [own] = (await run<{ timeout: unknown }>(\"PRAGMA busy_timeout\")).rows;\n await run(`PRAGMA busy_timeout = ${migrationDriver.limits.lockWait}`);\n try {\n await run(\"BEGIN IMMEDIATE\");\n } finally {\n // Interpolated, so only an integer is written back.\n if (Number.isInteger(own?.timeout)) {\n await run(`PRAGMA busy_timeout = ${own?.timeout}`);\n }\n }\n };\n // A PostgreSQL transaction takes its limits and tries the lock in one\n // statement. A refused try waits outside any transaction, so the wait holds\n // no snapshot: another command's `CREATE INDEX CONCURRENTLY` under the\n // session lock would otherwise wait for this one to give up. Each jittered\n // pause doubles up to the cap and ends in one autocommit try, which lets go\n // of what it takes, until the lock is free or `lockWait` is spent.\n const lockFree = `${migrationLockFree(migrationDriver)} AS acquired`;\n const tryLock = sqlite ? null : `SELECT ${lockFree}`;\n const enter =\n limits === undefined ? tryLock : `${limits.transaction}, ${lockFree}`;\n // Each jittered pause doubles up to the cap; past `lockWait` the lock is\n // not held.\n const waiting = () => {\n const deadline = Date.now() + migrationDriver.limits.lockWait;\n let pause = LOCK_RETRY_MS;\n return async (): Promise<void> => {\n const left = deadline - Date.now();\n if (left <= 0) throw lockNotConfirmed(migrationDriver);\n const jittered = pause * (0.5 + Math.random() / 2);\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(left, jittered))\n );\n pause = Math.min(pause * 2, LOCK_RETRY_CAP_MS);\n };\n };\n const begin = async (): Promise<void> => {\n const wait = waiting();\n for (;;) {\n try {\n await (sqlite ? beginImmediate() : run(\"BEGIN\"));\n } catch (error) {\n // SQLite's lock IS its BEGIN IMMEDIATE: a busy database is a lock wait.\n if (!sqlite || control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n open = true;\n let held: boolean;\n try {\n held = await lockHeld(direct, migrationDriver, control, enter);\n } catch (error) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(error, cleanup);\n });\n throw error;\n }\n if (held) return;\n // Nothing was read under a lock never held: not a gap in `continuous`.\n open = false;\n await control.cleanup(() => end(\"rollback\"));\n do {\n await wait();\n } while (!(await lockHeld(direct, migrationDriver, control, tryLock)));\n }\n };\n const sessionLock = migrationDriver.generateSessionLock(MIGRATION_LOCK_ID);\n const imposeLimits = async (): Promise<void> => {\n if (limits === undefined) return;\n try {\n const { rows } = await run<{ name: unknown }>(limits.settings);\n const present = rows.flatMap(({ name }) =>\n typeof name === \"string\" ? [name] : []\n );\n await run(limits.enter(present));\n control.limit(present);\n } catch (failure) {\n if (control.lost(failure)) throw failure;\n throw limitsRefused(pinned.driverName, \"enter\", failure);\n }\n };\n // A transaction under the session lock held alone: its limits, no lock.\n const beginUnderSessionLock = async (): Promise<void> => {\n if (!sessionLocked) await hold();\n await run(\"BEGIN\");\n open = true;\n if (limits !== undefined) await run(limits.transaction);\n };\n const hold = async (): Promise<void> => {\n const wait = waiting();\n while (!(await lockHeld(direct, migrationDriver, control, sessionLock))) {\n await wait();\n }\n sessionLocked = true;\n heldAlone = true;\n await imposeLimits();\n };\n const escalate = async (): Promise<void> => {\n if (!open) await begin();\n await acquireLock(direct, migrationDriver, control, sessionLock);\n sessionLocked = true;\n armed = false;\n await imposeLimits();\n await commit();\n };\n\n const between = async (): Promise<void> => {\n if (open) await commit();\n };\n // No idle limit cuts the session, and no other command waits, while the\n // caller works; a refused reset leaves the limits on a session no one can\n // clean, which is abandoned.\n const letGo = async (): Promise<void> => {\n await between();\n if (!(heldAlone && sessionLocked)) return;\n const present = control.limited();\n if (limits !== undefined && present !== undefined) {\n // Each reset is bounded like every cleanup statement (plan S2): one no\n // one answers loses the session, and its lock with it, within\n // CLEANUP_BOUND_MS instead of holding both while other commands wait.\n try {\n for (const statement of limits.exit(present)) {\n await control.cleanup(() => run(statement));\n }\n } catch (failure) {\n const lostConnection = control.lost(failure, true);\n control.abandon();\n if (lostConnection) throw failure;\n throw limitsRefused(pinned.driverName, \"reset\", failure);\n }\n }\n await releaseLock(direct, migrationDriver, control);\n sessionLocked = false;\n continuous = false;\n };\n const abort = async (cause: unknown): Promise<void> => {\n // A failure that IS the lost connection: nothing more is sent (plan S2).\n control.lost(cause);\n try {\n await rollback();\n } catch (cleanup) {\n throw withSuppressedFailure(cause, cleanup);\n }\n if (sessionLocked) {\n await releaseAfterFailure(direct, migrationDriver, control, cause);\n }\n };\n\n return {\n async failed(failure) {\n if (!(sqlite || grouped || control.lost(failure))) {\n await rollback().catch((cleanup: unknown) => {\n throw withSuppressedFailure(failure, cleanup);\n });\n }\n throw failure;\n },\n async before(sql) {\n if (heldAlone && !sessionLocked) await hold();\n if (grouped || sessionLocked) return;\n if (sqlite && FOREIGN_KEYS_SWITCH.test(sql)) {\n await between();\n return;\n }\n if (!sqlite && (armed || runsConcurrently(sql))) {\n await escalate();\n return;\n }\n if (!open) await begin();\n },\n group(fn) {\n if (sessionLocked && !heldAlone) return undefined;\n return runTransactionLifecycle({\n begin: () => {\n if (open) return undefined;\n return heldAlone ? beginUnderSessionLock() : begin();\n },\n callback: async () => {\n grouped = true;\n try {\n return await fn();\n } finally {\n grouped = false;\n }\n },\n commit,\n rollback,\n });\n },\n stepwise() {\n armed = true;\n },\n hold,\n between,\n letGo,\n continuous: () => continuous,\n async finish() {\n if (open) {\n try {\n await commit();\n } catch (failure) {\n await abort(failure);\n throw failure;\n }\n }\n if (sessionLocked) await releaseLock(direct, migrationDriver, control);\n },\n abort,\n };\n}\n\n/**\n * Commits a PostgreSQL command's open locked transaction after a bootstrap,\n * before any statement writes the control tables: PlanetScale's Neki plans a\n * statement against the schema committed before its transaction, so a control\n * table created in the same one is not there for it. SQLite writes them in the\n * transaction that made them; MySQL commits each DDL as it runs. The next\n * statement opens another, and {@link lockedSinceDecision} is then false.\n */\nexport async function commitLockedTransaction(\n pinned: AnyDriver,\n command: BoundMigrationDriver\n): Promise<void> {\n if (command.target.dialect === \"postgresql\") {\n await LOCKED.get(pinned)?.between();\n }\n}\n\n/**\n * Lets the command's lock go before the caller's own work, such as a\n * `resolve` callback, which no lock waits on: past `idleTimeout` PostgreSQL\n * ends the session, and SQLite's `BEGIN IMMEDIATE` holds every other writer.\n * The open locked transaction ends; on Neki the session lock held alone is\n * released, its limits reset. The next statement takes the lock again, and\n * {@link lockedSinceDecision} is then false.\n */\nexport async function letLockGo(pinned: AnyDriver): Promise<void> {\n await LOCKED.get(pinned)?.letGo();\n}\n\n/**\n * Whether `producer`'s command has held its migration lock without a gap since\n * it read its decision; always true on MySQL, which holds a session lock.\n */\nexport function lockedSinceDecision(producer: AnyDriver): boolean {\n return LOCKED.get(producer)?.continuous() ?? true;\n}\n\n/** The settings a session's limits set only where the server has them. */\nconst OPTIONAL_SESSION_SETTINGS = [\n \"idle_in_transaction_session_timeout\",\n \"idle_session_timeout\",\n \"client_connection_check_interval\",\n] as const;\n\n/**\n * The PostgreSQL statements behind one command's time limits (plan S1).\n *\n * Every migration transaction opens with its own `SET LOCAL` limits, which\n * leave with it (plan D1); the session carries them only while it holds the\n * session lock (stepwise work, or PlanetScale's Neki for the whole command),\n * and is `RESET` before it goes back. Every setting is named by a constant:\n * Neki refuses `set_config` with a computed name in a routine body (`42501`)\n * and a `set_config` over `pg_settings` rows (`NK013`). Which optional\n * settings the server has is read first (`settings`); the idle limits are\n * never set on PGlite, whose in-process backend hangs on either idle timer.\n */\nfunction postgresSessionLimits(\n limits: ResolvedMigrationLimits\n): PostgresSessionLimits {\n const bound = (lock: number, statement: number, local: boolean) =>\n `set_config('lock_timeout', '${lock}', ${local}), set_config('statement_timeout', '${statement}', ${local})`;\n const { lockTimeout, statementTimeout, idleTimeout } = limits;\n const set = (name: string, value: number) =>\n `, set_config('${name}', '${value}', false)`;\n return {\n settings: `SELECT name FROM pg_catalog.pg_settings WHERE name IN (${OPTIONAL_SESSION_SETTINGS.map((name) => `'${name}'`).join(\", \")}) AND pg_catalog.version() NOT LIKE '%emscripten%' ORDER BY name`,\n enter: (present) => {\n const idle = OPTIONAL_SESSION_SETTINGS.slice(0, 2)\n .filter((name) => present.includes(name))\n .map((name) => set(name, idleTimeout))\n .join(\"\");\n // Refused where the platform cannot check the socket, which is no\n // reason to refuse the command.\n const check = present.includes(\"client_connection_check_interval\")\n ? `\nBEGIN\nPERFORM set_config('client_connection_check_interval', '1000', false);\nEXCEPTION WHEN invalid_parameter_value THEN NULL;\nEND;`\n : \"\";\n return `DO $viborm_limits$BEGIN\nPERFORM ${bound(lockTimeout, statementTimeout, false)}${idle};${check}\nEND$viborm_limits$`;\n },\n exit: (present) =>\n [\"lock_timeout\", \"statement_timeout\", ...present].map(\n (name) => `RESET ${name}`\n ),\n // Repeated in each transaction under the session lock too: a migration's\n // own SQL may change the session's values.\n transaction: `SELECT ${bound(lockTimeout, statementTimeout, true)}, set_config('idle_in_transaction_session_timeout', CASE WHEN pg_catalog.version() LIKE '%emscripten%' THEN pg_catalog.current_setting('idle_in_transaction_session_timeout') ELSE '${idleTimeout}' END, true)`,\n unbound: `SELECT ${bound(0, 0, false)}`,\n rebound: `SELECT ${bound(lockTimeout, statementTimeout, false)}`,\n };\n}\n\n/**\n * The server refused to impose (`enter`) or reset (`reset`) the migration\n * session's limits: part of holding the session lock, so a lock failure\n * (V11005), named as itself rather than as the statement it preceded. A\n * session whose reset was refused is never returned to the pool.\n */\nfunction limitsRefused(\n driverName: string,\n step: \"enter\" | \"reset\",\n failure: unknown\n): MigrationError {\n const what =\n step === \"enter\"\n ? \"refused the migration session's time limits, so the command stopped there and its session lock was let go\"\n : \"refused to reset the migration session's time limits; the connection was closed rather than returned to the pool\";\n return new MigrationError(\n `Driver \"${driverName}\": the server ${what}.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n {\n cause: errorCause(failure),\n meta: {\n driver: driverName,\n operation: \"pinnedSession\",\n ...providerFacts(failure),\n },\n }\n );\n}\n\n/**\n * Selects the live migration target on a pinned producer, if this dialect has\n * one: when the lock is taken and again before every relative artifact, since\n * a manual artifact may issue its own `USE` (§10).\n */\nexport async function selectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n const statement = migrationDriver.generateSelectTarget();\n if (statement === null) {\n return;\n }\n await pinned._executeRaw(statement);\n}\n\n/**\n * §5.3's step 2, once per locked session: the namespace proof (§3.3), the\n * target selection, then the dialect's own proof of the session.\n */\nasync function validateAndSelectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const command = await resolveCommandDriver(pinned, migrationDriver);\n await selectMigrationTarget(pinned, command);\n return command.proveSession((sql, params) => pinned._executeRaw(sql, params));\n}\n\n/**\n * The ONE owner of the migration driver a command renders from, after its\n * namespace proof (§5.2): on the dialect that resolves a command-local\n * spelling (MySQL), a frozen view carrying the server's own spelling, which\n * lives exactly as long as the command. Read-only commands reach it too.\n */\nexport async function resolveCommandDriver(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const read: CatalogRead = (sql, params) => producer._executeRaw(sql, params);\n if (!readsCommandNamespace(migrationDriver)) {\n await migrationDriver.proveNamespaceExists(read);\n return migrationDriver;\n }\n\n const spelling = await migrationDriver.resolveCommandNamespace(read);\n const command: BoundMigrationDriver = Object.create(migrationDriver);\n Object.defineProperty(command, \"namespace\", {\n value: spelling,\n enumerable: true,\n });\n Object.freeze(command);\n return command;\n}\n\n/**\n * Whether a group of `transactional` work runs in a transaction on this\n * producer: never on MySQL, nor without transactions. Asked of each group\n * right before it runs, which is where a PostgreSQL command hears of stepwise\n * work and takes the session lock it needs (plan D1).\n */\nexport function mayWrapTransaction(\n producer: Pick<AnyDriver, \"supportsTransactions\">,\n dialect: string,\n transactional: boolean\n): boolean {\n if (!transactional) LOCKED.get(producer)?.stepwise();\n return transactional && dialect !== \"mysql\" && producer.supportsTransactions;\n}\n\n/**\n * Runs one program of a command, the one owner of how it runs: on MySQL as a\n * sequential program; else, given its `program`, in a transaction where\n * {@link mayWrapTransaction} admits one, SQLite's foreign-key pragmas lifted\n * around it (a recreation is refused where nothing can lift them), and\n * directly otherwise; without one, directly. `atomic` tells the body which.\n * Once a given program has committed, what it left building is waited for\n * (`awaitIndexBuilds`), the lock still held.\n * `phase` records how far a transaction got: past its body and checks\n * (`committing`), past its COMMIT (`committed`), for a caller that classifies\n * a failure at COMMIT (plan S3).\n */\nexport async function runProgram<T>(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n program:\n | {\n readonly transactional: boolean;\n readonly statements: string[];\n readonly phase?: { committing: boolean; committed: boolean };\n }\n | undefined,\n body: (producer: AnyDriver, atomic: boolean) => Promise<T>\n): Promise<T> {\n const { dialect } = command.target;\n if (dialect === \"mysql\") {\n return runSequentialProgram(pinned, command, (producer) =>\n body(producer, false)\n );\n }\n if (!program) return body(pinned, false);\n const { bracket } = liftForeignKeyPragmas(pinned, program.statements);\n // What the program builds in the background, once it has committed.\n const settle = () => command.awaitIndexBuilds?.(pinned, program.statements);\n // Neki refuses any statement after a schema change in its transaction:\n // the body's own ledger and marker writes run outside one.\n if (\n !mayWrapTransaction(\n pinned,\n dialect,\n program.transactional && !command.commitsSchemaChangesAlone()\n )\n ) {\n // A statement that fails leaves the ones before it committed, builds too:\n // they are waited for, and the statement's failure stays the one reported.\n const result = await body(pinned, false).catch(async (failure) => {\n await settle()?.catch((wait) => {\n throw withSuppressedFailure(failure, wait);\n });\n throw failure;\n });\n await settle();\n return result;\n }\n const { phase } = program;\n return withForeignKeysLifted(pinned, bracket, async (inside) => {\n const result = await pinned.withTransaction(async (transaction) => {\n const value = await inside(transaction, (producer) =>\n body(producer, true)\n );\n if (phase) phase.committing = true;\n return value;\n });\n if (phase) phase.committed = true;\n await settle();\n return result;\n });\n}\n\n/**\n * Runs a MySQL sequential program on `producer`, after the command's\n * `programPreamble`, and reports the boundary it reached (§6.2, §6.3): MySQL\n * commits DDL as each statement runs, so a failure part-way through is the\n * partial commit it is, recorded by the producer the body runs on.\n */\nexport async function runSequentialProgram<T>(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (recording: AnyDriver) => Promise<T>\n): Promise<T> {\n const preamble = await migrationDriver.programPreamble(producer);\n /** The last statement that RAN TO COMPLETION, which here IS committed. */\n let committed: string | undefined;\n const recording: AnyDriver = Object.create(producer);\n Object.defineProperty(recording, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const result = await producer._executeRaw(sql, params);\n committed = sql;\n return result;\n },\n });\n\n try {\n for (const statement of preamble) {\n await recording._executeRaw(statement);\n }\n return await body(recording);\n } catch (cause) {\n throw partialProgramFailure(cause, committed);\n }\n}\n\n/**\n * The honest report for a program that cannot be undone (§6.2, §6.3): the\n * last statement known to have completed, no claim of a rollback, and the\n * provider's failure as the cause.\n */\nfunction partialProgramFailure(\n cause: unknown,\n committed: string | undefined\n): MigrationError {\n const boundary =\n committed ?? \"(none — the failure came before any statement completed)\";\n return new MigrationError(\n \"This migration program failed partway through. MySQL commits DDL as each statement runs, so NOTHING was rolled back: every statement that completed stands, and VibORM makes no claim about whether the statement that failed took effect. \" +\n `The last statement that completed was: ${boundary}. ` +\n \"Estate artifacts and the control plane were not rewritten as a successful apply — fix the cause and re-run.\",\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n { cause: errorCause(cause), meta: providerFacts(cause) }\n );\n}\n\n/**\n * Acquires the lock and PROVES it. The target is selected after the lock\n * (§5.3), by the caller's scope that releases.\n */\nasync function acquireLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement = migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID)\n): Promise<void> {\n if (!(await lockHeld(pinned, migrationDriver, control, statement))) {\n throw lockNotConfirmed(migrationDriver);\n }\n}\n\n/** Runs one lock statement: whether the provider proved the lock held. */\nasync function lockHeld(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n statement: string | null\n): Promise<boolean> {\n if (statement === null) {\n return true;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await executor(statement);\n } catch (error) {\n // A lost connection is retryable, not a lock failure.\n if (control.lost(error)) throw error;\n throw lockStatementFailed(migrationDriver, error);\n }\n return migrationDriver.provesLockAcquired(rows);\n}\n\nfunction lockNotConfirmed(\n migrationDriver: BoundMigrationDriver\n): MigrationError {\n return new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the lock. ` +\n \"A wait that timed out, an error, or a malformed answer all mean the lock is NOT held; VibORM will not run migration work on that assumption.\",\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n}\n\nfunction lockStatementFailed(\n migrationDriver: BoundMigrationDriver,\n error: unknown\n): MigrationError {\n return new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the lock statement itself failed.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: errorCause(error), meta: providerFacts(error) }\n );\n}\n\n/**\n * Releases the lock after the protected work FAILED: the release still runs\n * and its own failure is recorded beside `cause` (§3.5), never replacing it.\n * A lost session holds no lock to release (plan S2).\n */\nasync function releaseAfterFailure(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl,\n cause: unknown\n): Promise<void> {\n if (control.lost(cause)) return;\n try {\n await releaseLock(pinned, migrationDriver, control);\n } catch (releaseFailure) {\n throw withSuppressedFailure(cause, releaseFailure);\n }\n}\n\n/**\n * Releases the lock and PROVES the release, through the driver the command\n * was GIVEN (only it names the lock acquired); an unproven release condemns\n * the producer.\n */\nasync function releaseLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: PinnedSessionControl\n): Promise<void> {\n const statement = migrationDriver.generateReleaseLock(MIGRATION_LOCK_ID);\n if (statement === null) {\n return;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await control.cleanup(() => executor(statement));\n } catch (error) {\n control.discard();\n if (control.lost(error)) throw error;\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}. The pinned session was discarded rather than returned to the pool.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: errorCause(error), meta: providerFacts(error) }\n );\n }\n\n if (!migrationDriver.provesLockReleased(rows)) {\n control.discard();\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the release. The pinned session was discarded rather than returned to the pool, so the lock cannot outlive the connection.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n }\n}\n\n/** The estate a lock failure is about. */\nfunction describeEstate(migrationDriver: BoundMigrationDriver): string {\n const { target } = migrationDriver;\n if (target.dialect === \"sqlite\") return \"the SQLite database\";\n if (target.dialect === \"surrealql\") return \"the SurrealDB database\";\n return target.dialect === \"postgresql\"\n ? `schema \"${target.namespace}\"`\n : `database \"${migrationDriver.namespace ?? \"(unbound)\"}\"`;\n}\n","import { readArrayLiteralText } from \"../adapters/databases/postgres/array-literal\";\nimport { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\nimport { decodeProviderTimestamp } from \"../validation/primitives/datetime-physical-codec\";\n/**\n * Live schema fingerprint and push target identity.\n *\n * The target identity names the database itself (dialect, database and\n * namespace), never a client instance: a consent previewed by one client is\n * replayed by any other on the same database, and the plan hash it carries\n * still binds it to the exact live fingerprint and statements. This module\n * hashes the snapshot it is given; callers strip control tables before\n * fingerprinting.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport type { IndexPredicateCanonicalizer } from \"./differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodeSnapshot } from \"./v1-parse-snapshot\";\nimport type { MarkerIndexPredicateV1, PushTargetIdentity } from \"./v1-types\";\n\nexport async function pushTargetIdentity(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PushTargetIdentity> {\n if (driver.target.dialect === \"postgresql\") {\n const result = await producer._executeRaw<{ database: unknown }>(\n \"SELECT current_database() AS database\"\n );\n const database = result.rows[0]?.database;\n if (typeof database !== \"string\" || database.length === 0) {\n throw new MigrationError(\n \"PostgreSQL did not return its current database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"postgresql\",\n database,\n namespace: driver.namespace ?? driver.target.namespace,\n };\n }\n if (driver.target.dialect === \"mysql\") {\n if (!driver.namespace) {\n throw new MigrationError(\n \"MySQL push has no resolved database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"mysql\",\n database: driver.namespace,\n };\n }\n return (\n (await driver.pushTarget?.((sql, params) =>\n producer._executeRaw(sql, params)\n )) ?? { dialect: \"sqlite\", location: null }\n );\n}\n\nexport function hashSnapshot(snapshot: SchemaSnapshot): Sha256 {\n return encodeSnapshot(snapshot).snapshotHash;\n}\n\nexport function bindIndexPredicateCanonicalizer(\n producer: AnyDriver,\n driver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = driver.canonicalizeIndexPredicates;\n if (!canonicalize) return;\n return async (tableName, predicates) => {\n const run = (on: AnyDriver) =>\n canonicalize.call(\n driver,\n tableName,\n predicates,\n (sql, params) => on._executeRaw(sql, params),\n runsMigrationBatches(on)\n ? <T>(statements: readonly string[]) =>\n on._executeBatch<T>(statements.map((sql) => ({ sql })))\n : undefined\n );\n try {\n // Its scratch views exist only inside their transaction, so on a\n // pool, or behind a transaction pooler, its statements share one. A\n // locked command's pinned producer is already inside one (plan D1).\n // With no session at all, each pass is one request (plan D7).\n return await (canPinSession(producer) && producer.supportsTransactions\n ? producer.withTransaction(run)\n : run(producer));\n } catch {\n return predicates.map(() => undefined);\n }\n };\n}\n\nexport async function canonicalizeSnapshotPredicates(\n snapshot: SchemaSnapshot,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<SchemaSnapshot> {\n if (!canonicalize) return snapshot;\n const tables: TableDef[] = [];\n for (const table of snapshot.tables) {\n const pending = table.indexes.filter((index) => index.where);\n if (pending.length === 0) {\n tables.push(table);\n continue;\n }\n const predicates = pending.map((index) => index.where!);\n const spellings = await canonicalize(table.name, predicates);\n let next = 0;\n tables.push({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.where) return index;\n const spelling = spellings[next++];\n return spelling === undefined ? index : { ...index, where: spelling };\n }),\n });\n }\n return { ...snapshot, tables };\n}\n\nexport async function fingerprintLive(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver,\n producer: AnyDriver\n): Promise<Sha256> {\n return fingerprintSnapshot(\n await canonicalizeSnapshotPredicates(\n snapshot,\n bindIndexPredicateCanonicalizer(producer, driver)\n ),\n driver\n );\n}\n\n/**\n * `fingerprintSnapshot` with each partial-index predicate as PostgreSQL\n * deparsed it, from the record beside the marker: what the catalog digest\n * hashes when it reads predicates as deparsed. `undefined` when the record\n * lacks one of them.\n */\nexport function fingerprintDeparsed(\n snapshot: SchemaSnapshot,\n predicates: readonly MarkerIndexPredicateV1[],\n driver: MigrationDriver\n): Sha256 | undefined {\n let recorded = true;\n const tables = snapshot.tables.map((table) => ({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.where) return index;\n const where = predicates.find(\n (record) => record.table === table.name && record.index === index.name\n )?.deparsed;\n recorded &&= where !== undefined;\n return { ...index, where };\n }),\n }));\n return recorded\n ? fingerprintSnapshot({ ...snapshot, tables }, driver)\n : undefined;\n}\n\nexport function fingerprintSnapshot(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver\n): Sha256 {\n const tables = canonicalUniqueEntities(snapshot)\n .tables.map((table) => ({\n name: table.name,\n columns: table.columns\n .map((column) => ({\n name: column.name,\n type: normalizeType(column.type),\n nullable: column.nullable,\n default: normalizeDefault(column.default, column.type) ?? null,\n autoIncrement: column.autoIncrement ?? false,\n ...(sqliteGeoPointEncoding(column)\n ? { geoPointEncoding: sqliteGeoPointEncoding(column) }\n : {}),\n }))\n .sort(byName),\n primaryKey: table.primaryKey\n ? {\n columns: table.primaryKey.columns,\n ...(driver.dialect === \"postgresql\"\n ? { name: table.primaryKey.name || `${table.name}_pkey` }\n : {}),\n // Present only where set, so every other key hashes as before.\n ...(table.primaryKey.withoutRowid ? { withoutRowid: true } : {}),\n }\n : null,\n indexes: table.indexes\n .map((index) =>\n // A raw index is its text: what the database calls its method, its\n // uniqueness or its predicate is the text's, and the hash says it.\n index.raw\n ? { name: index.name, raw: index.raw.hash, columns: index.columns }\n : {\n name: index.name,\n columns: index.columns,\n unique: index.unique ?? false,\n type: index.type ?? \"btree\",\n where: index.where?.trim() || null,\n }\n )\n .sort(byName),\n foreignKeys: table.foreignKeys\n .map((foreignKey) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? foreignKey.name\n : null,\n columns: foreignKey.columns,\n referencedTable: foreignKey.referencedTable,\n referencedColumns: foreignKey.referencedColumns,\n onDelete: foreignKey.onDelete ?? \"noAction\",\n onUpdate: foreignKey.onUpdate ?? \"noAction\",\n }))\n .sort(byCanonicalValue),\n uniqueConstraints: table.uniqueConstraints\n .map((constraint) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? constraint.name\n : null,\n columns: constraint.columns,\n }))\n .sort(byCanonicalValue),\n }))\n .sort(byName);\n const enums = [...(snapshot.enums ?? [])]\n .map((item) => ({ name: item.name, values: item.values }))\n .sort(byName);\n return domainHash(HASH_DOMAIN.snapshot, canonicalizeJson({ tables, enums }));\n}\n\n/** A total btree unique index and a unique constraint enforce the same key. */\nexport function canonicalUniqueEntities(\n snapshot: SchemaSnapshot\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) => ({\n ...table,\n uniqueConstraints: [\n ...table.uniqueConstraints,\n ...table.indexes\n .filter(\n (index) =>\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n .map((index) => ({ name: index.name, columns: index.columns })),\n ],\n indexes: table.indexes.filter(\n (index) =>\n !(\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n ),\n })),\n };\n}\n\nexport function normalizeType(type: string): string {\n const tokens =\n type.trim().match(/'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|[^'\"]+/g) ?? [];\n return tokens\n .map((token) => {\n if (token.startsWith(\"'\") || token.startsWith('\"')) return token;\n return token\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \",\")\n .replace(/\\s+\\[\\]/g, \"[]\")\n .replace(/\\bcharacter varying\\b/g, \"varchar\")\n .replace(/\\bcharacter\\b/g, \"char\")\n .replace(/\\bbit varying\\b/g, \"varbit\")\n .replace(/\\btimestamptz(\\(\\d+\\))?/g, \"timestamp$1 with time zone\")\n .replace(/\\btimetz(\\(\\d+\\))?/g, \"time$1 with time zone\")\n .replace(/\\b(timestamp|time)(\\(\\d+\\))? without time zone/g, \"$1$2\")\n .replace(/\\bint4\\b/g, \"integer\")\n .replace(/\\bint8\\b/g, \"bigint\")\n .replace(/\\bint2\\b/g, \"smallint\")\n .replace(/\\bfloat4\\b/g, \"real\")\n .replace(/\\bfloat8\\b/g, \"double precision\")\n .replace(/\\bbool\\b/g, \"boolean\");\n })\n .join(\"\");\n}\n\nconst UTC_NOW_DEFAULT =\n /^(?:now\\(\\) at time zone 'utc'|timezone\\(\\s*'utc'\\s*,\\s*now\\(\\)\\s*\\))$/;\nconst MILLISECOND_NOW_DEFAULT =\n /^date_trunc\\(\\s*'milliseconds'\\s*,([\\s\\S]+)\\)$/;\nconst UTC_CURRENT_TIME_DEFAULT =\n /^timezone\\(\\s*'utc'\\s*,\\s*current_time(?:\\(3\\))?\\s*\\)$/;\nconst NUMERIC_PHYSICAL_TYPE =\n /^(integer|bigint|smallint|real|double precision|float|int|tinyint)/;\nconst INTEGER_PHYSICAL_TYPE = /^(integer|bigint|smallint|int|tinyint)/;\nconst INTEGER_LITERAL = /^[-+]?\\d+$/;\nconst TEMPORAL_PHYSICAL_TYPE = /^(timestamp|time|date)/;\nconst ISO_UTC_SUFFIX = /Z$/;\nconst TEMPORAL_UTC_SUFFIX = /(?:Z|[+]00(?::00)?)$/;\nconst MINUTE_CLOCK_SUFFIX = /(^| )(\\d{2}:\\d{2})(?=$|[+-])/;\nconst TRAILING_FRACTION_ZEROES = /(\\.\\d*?)0+(?=$|[+-])/;\nconst EMPTY_FRACTION = /\\.(?=$|[+-])/;\nconst BARE_FUNCTION_DEFAULT = /^[a-z_][a-z0-9_]*\\(\\)$/;\nconst NUMBER_LITERAL = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\nfunction stripDefaultParentheses(value: string): string {\n let text = value.trim();\n while (text.startsWith(\"(\") && text.endsWith(\")\")) {\n const structural = text.replace(\n /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"/g,\n (literal) => \" \".repeat(literal.length)\n );\n let depth = 0;\n let whole = true;\n for (let index = 0; index < structural.length; index++) {\n if (structural[index] === \"(\") depth++;\n else if (structural[index] === \")\") depth--;\n if (depth === 0 && index < structural.length - 1) {\n whole = false;\n break;\n }\n }\n if (!whole || depth !== 0) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n}\n\nexport function normalizeDefault(\n value: string | undefined,\n type?: string\n): string | undefined {\n if (value === undefined) return;\n const spelling = stripDefaultParentheses(value);\n const normalized = spelling.toLowerCase();\n if (normalized === \"null\") return;\n const utcNow = normalized\n .replaceAll(\"::text\", \"\")\n .replaceAll(\"current_timestamp\", \"now()\");\n if (UTC_NOW_DEFAULT.test(utcNow)) return \"now() at time zone 'utc'\";\n const truncated = MILLISECOND_NOW_DEFAULT.exec(utcNow);\n if (truncated?.[1]) {\n const clock = normalizeDefault(truncated[1], type);\n if (clock === \"now()\" || clock === \"now() at time zone 'utc'\")\n return `date_trunc('milliseconds',${clock})`;\n }\n if (UTC_CURRENT_TIME_DEFAULT.test(utcNow))\n return utcNow.includes(\"current_time(3)\")\n ? \"timezone('utc',current_time(3))\"\n : \"timezone('utc',current_time)\";\n if (normalized === \"current_timestamp\" || normalized === \"now()\")\n return \"now()\";\n const boolean = type === undefined || normalizeType(type) === \"boolean\";\n if (\n boolean &&\n (normalized === \"true\" || normalized === \"'t'\" || normalized === \"1\")\n )\n return \"true\";\n if (\n boolean &&\n (normalized === \"false\" || normalized === \"'f'\" || normalized === \"0\")\n )\n return \"false\";\n if (BARE_FUNCTION_DEFAULT.test(normalized)) return normalized;\n const unquoted =\n normalized.startsWith(\"'\") && normalized.endsWith(\"'\")\n ? normalized.slice(1, -1)\n : normalized;\n const physical = type === undefined ? \"\" : normalizeType(type);\n if (spelling.startsWith(\"'\") && spelling.endsWith(\"'\")) {\n const literal = spelling.slice(1, -1).replaceAll(\"''\", \"'\");\n if (physical.endsWith(\"[]\")) {\n const values = readArrayLiteralText(literal);\n if (values)\n return canonicalizeJsonText(\n values.map((value) =>\n value === null\n ? null\n : normalizeDefault(\n `'${(physical.slice(0, -2) === \"boolean\" && (value === \"t\" || value === \"f\") ? (value === \"t\" ? \"true\" : \"false\") : value).replaceAll(\"'\", \"''\")}'`,\n physical.slice(0, -2)\n )\n )\n );\n }\n if (physical === \"json\" || physical === \"jsonb\") {\n try {\n return canonicalizeJsonText(JSON.parse(literal));\n } catch {\n /* A SQL expression is not a JSON document literal. */\n }\n }\n }\n if (NUMERIC_PHYSICAL_TYPE.test(physical) && NUMBER_LITERAL.test(unquoted)) {\n // BigInt keeps integer columns exact; a float catalog spells 1e21 as\n // '1000000000000000000000', which only Number() reads back as 1e+21.\n return INTEGER_PHYSICAL_TYPE.test(physical) &&\n INTEGER_LITERAL.test(unquoted)\n ? BigInt(unquoted).toString()\n : String(Number(unquoted));\n }\n if (\n TEMPORAL_PHYSICAL_TYPE.test(physical) &&\n spelling.startsWith(\"'\") &&\n spelling.endsWith(\"'\")\n ) {\n let temporal = spelling\n .slice(1, -1)\n .replace(\"T\", \" \")\n .replace(ISO_UTC_SUFFIX, \"+00:00\");\n const era = temporal.endsWith(\" BC\") ? \" BC\" : \"\";\n if (era) temporal = temporal.slice(0, -3);\n if (\n physical.includes(\"with time zone\") &&\n physical.startsWith(\"timestamp\")\n ) {\n const instant = decodeProviderTimestamp(`${temporal}${era}`);\n if (instant) return instant.toISOString();\n }\n temporal = temporal\n .replace(TEMPORAL_UTC_SUFFIX, \"\")\n .replace(MINUTE_CLOCK_SUFFIX, \"$1$2:00\")\n .replace(TRAILING_FRACTION_ZEROES, \"$1\")\n .replace(EMPTY_FRACTION, \"\");\n return `${temporal}${era}`;\n }\n return spelling;\n}\n\nexport function canonicalValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalValue(item));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (item !== undefined) result[key] = canonicalValue(item);\n }\n return result;\n }\n return value;\n}\n\nexport function freezeDeep<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n if (ArrayBuffer.isView(value)) return value;\n for (const member of Object.values(value)) freezeDeep(member);\n return Object.freeze(value);\n}\n\nfunction byName(\n left: { readonly name: string },\n right: { readonly name: string }\n): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nfunction byCanonicalValue(left: unknown, right: unknown): number {\n const a = canonicalizeJsonText(left);\n const b = canonicalizeJsonText(right);\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * How a refused PostgreSQL catalog read is reported. Apart from\n * introspection, so the shared control-table read (`control.ts`) brings no\n * PostgreSQL introspection into another dialect's bundle.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { providerRefused } from \"../../execute-dispatch\";\n\n/**\n * A catalog read the provider refused, thrown named with its SQLSTATE: a\n * server that speaks PostgreSQL but not all of its catalog SQL (PlanetScale's\n * Neki) must say which read it refused, not that the estate is wrong. The\n * server's own text stays in the cause, disclosed as the driver's diagnostics\n * allow. A transport failure is not a refusal, nor is a migration error\n * already named: the caller handles them.\n */\nexport function throwIfCatalogRefusal(query: string, error: unknown): void {\n // A migration outcome raised before the read was sent (the lock protocol's\n // own statements, such as the session's limits) is not the read's refusal.\n if (!providerRefused(error) || error instanceof MigrationError) return;\n const { providerCode, providerSqlState } = error.meta;\n throw new MigrationError(\n `PostgreSQL catalog query \"${query}\" failed with SQLSTATE ${String(providerSqlState ?? providerCode)}: ${error.message}`,\n VibORMErrorCode.MIGRATION_FAILED,\n { cause: error, meta: { providerCode, providerSqlState } }\n );\n}\n","import { normalizeType } from \"./push-fingerprint\";\n/**\n * Marker and ledger control tables: one reserved pair.\n * Read-only commands never bootstrap. Parsers in v1-parse own row truth.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { isRetryableError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport {\n boundNamespace,\n qualifiedName,\n tableExistsProbe,\n} from \"./catalog-probes\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { throwIfCatalogRefusal } from \"./drivers/postgres/catalog-refusal\";\nimport { providerFacts } from \"./execute-dispatch\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { withManagedTables } from \"./target\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodePathHash, eventIdFor, parseLedgerEvent } from \"./v1-parse\";\nimport { parseMarkerPayload } from \"./v1-parse-control\";\nimport { readFlag } from \"./v1-parse-shared\";\nimport type {\n LedgerEventV1,\n MarkerIndexPredicateV1,\n MigrationMarkerV1,\n} from \"./v1-types\";\n\n/** The reserved control pair: the marker's table and the ledger's. */\nexport const CONTROL_TABLES: { readonly state: string; readonly log: string } =\n Object.freeze({\n state: \"_viborm_migration_state\",\n log: \"_viborm_migration_log\",\n });\n\nconst CHECK_PREFIX = /^\\s*check\\s*/i;\nconst CHECK_FORMATTING = /[\\s()\"`]/g;\n\nexport type ControlPresence =\n | { readonly kind: \"missing-table\"; readonly table: \"state\" | \"log\" | \"both\" }\n | { readonly kind: \"recoverable-state-only\" }\n | { readonly kind: \"present\" };\n\nfunction placeholder(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n index: number\n): string {\n if (dialect === \"surrealql\") return `$p${index}`;\n return dialect === \"postgresql\" ? `$${index}` : \"?\";\n}\n\ntype ControlTable = keyof typeof CONTROL_TABLES;\n\n/**\n * The one declaration of a control table: its columns, primary key first,\n * with the types VibORM's DDL spells.\n */\nfunction controlColumns(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): readonly (readonly [name: string, type: string])[] {\n if (table === \"state\") {\n return [\n [\"singleton\", \"INTEGER\"],\n [\"payload\", \"TEXT\"],\n ];\n }\n const id = dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\";\n return [\n [\"event_id\", id],\n [\"attempt_id\", id],\n [\"kind\", dialect === \"mysql\" ? \"VARCHAR(32)\" : \"TEXT\"],\n [\"payload\", \"TEXT\"],\n ];\n}\n\n/** The parenthesized definition `CREATE TABLE` writes for one control table. */\nfunction controlDefinition(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n table: ControlTable\n): string {\n const check = table === \"state\" ? \" CHECK (singleton = 1)\" : \"\";\n const columns = controlColumns(dialect, table).map(([name, type], index) =>\n index === 0\n ? `${name} ${type} PRIMARY KEY${check}`\n : `${name} ${type} NOT NULL`\n );\n return `(\\n ${columns.join(\",\\n \")}\\n )`;\n}\n\n/** A control table in SurrealQL: its columns are fields, its key a unique index. */\nfunction surrealControlDefinition(\n driver: BoundMigrationDriver,\n table: ControlTable\n): string {\n const name = qualifiedName(driver, CONTROL_TABLES[table]);\n const key = table === \"state\" ? \"singleton\" : \"event_id\";\n const fields =\n table === \"state\"\n ? [\"singleton TYPE int ASSERT $value = 1\", \"payload TYPE string\"]\n : [\n \"event_id TYPE string\",\n \"attempt_id TYPE string\",\n \"kind TYPE string\",\n \"payload TYPE string\",\n ];\n return [\n `DEFINE TABLE ${name} SCHEMAFULL;`,\n ...fields.map((field) => {\n const [column, ...rest] = field.split(\" \");\n return `DEFINE FIELD ${column} ON ${name} ${rest.join(\" \")};`;\n }),\n `DEFINE INDEX ${CONTROL_TABLES[table]}_key ON ${name} FIELDS ${key} UNIQUE;`,\n ].join(\" \");\n}\n\n/** Exact writer-owned state definition; the control owner authenticates its contents separately. */\nexport function isSqliteStateControlDefinition(\n name: string,\n sql: string | null\n): boolean {\n return (\n name === CONTROL_TABLES.state &&\n sql !== null &&\n sqliteDefinitionBody(sql) ===\n sqliteDefinitionBody(controlDefinition(\"sqlite\", \"state\"))\n );\n}\n\nexport function createControlTableSQL(driver: BoundMigrationDriver): {\n state: string;\n log: string;\n} {\n const create = (table: ControlTable) =>\n driver.target.dialect === \"surrealql\"\n ? surrealControlDefinition(driver, table)\n : `CREATE TABLE IF NOT EXISTS ${qualifiedName(driver, CONTROL_TABLES[table])} ${controlDefinition(driver.target.dialect, table)}`;\n return { state: create(\"state\"), log: create(\"log\") };\n}\n\nexport function refusePartialControl(presence: ControlPresence): void {\n if (presence.kind === \"recoverable-state-only\") {\n throw new MigrationError(\n \"Migration control tables are inconsistent: log is missing after interrupted bootstrap\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (presence.kind === \"missing-table\" && presence.table !== \"both\") {\n throw new MigrationError(\n `Migration control tables are inconsistent: ${presence.table} is missing`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/** The events of attempts that never reached a state. */\nconst CLOSED_WITHOUT_STATE: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"started\",\n \"step-confirmed\",\n \"failed\",\n \"rolled-back\",\n \"resolved\",\n]);\n\n/**\n * Without a marker, history may only hold attempts closed by `failed`,\n * `rolled-back` or `resolved`, so `apply` can start again (plan S4). An\n * unfinished attempt is its caller's refusal.\n */\nexport function refuseIncompatibleHistory(\n marker: MigrationMarkerV1 | null,\n ledger: readonly LedgerEventV1[]\n): void {\n if (marker !== null) return;\n if (unfinishedAttempts(ledger).length > 0) return;\n if (ledger.every((event) => CLOSED_WITHOUT_STATE.has(event.kind))) return;\n throw new MigrationError(\n \"Migration ledger history exists without a current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/**\n * Which control tables exist. PostgreSQL answers from `catalog`, the one\n * statement that also authenticates them (plan D5), read here when not given.\n */\nexport async function inspectControlPresence(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n catalog?: PostgresControlCatalog\n): Promise<ControlPresence> {\n const read = catalog ?? (await postgresControlCatalog(producer, driver));\n const stateMissing = read\n ? !read.state\n : await isTableMissing(producer, driver, CONTROL_TABLES.state);\n const logMissing = read\n ? !read.log\n : await isTableMissing(producer, driver, CONTROL_TABLES.log);\n if (stateMissing && logMissing)\n return { kind: \"missing-table\", table: \"both\" };\n if (stateMissing) return { kind: \"missing-table\", table: \"state\" };\n if (logMissing) {\n // Bootstrap creates state before log. If the second CREATE failed, the\n // empty state table is the one recognizable partial state that can be\n // completed idempotently. A marker row means this is real history with a\n // missing ledger and must remain a hard refusal.\n await assertControlTablesAuthentic(producer, driver, \"state\", read);\n if (await isStateControlEmpty(producer, driver)) {\n return { kind: \"recoverable-state-only\" };\n }\n return { kind: \"missing-table\", table: \"log\" };\n }\n return { kind: \"present\" };\n}\n\n/**\n * Introspects with the managed-table scope narrowed to the two control tables.\n *\n * Every dialect's introspection already reads an unselected table without\n * interpreting it (no refusal of its indexes, types or defaults), so a managed\n * table's state — an INVALID index left by an interrupted `CREATE INDEX\n * CONCURRENTLY` among them — can no longer make the control plane unreadable\n * and take `status()` and `log()` down with it. The view restates `target`\n * only, the way every execution view in this layer restates one member.\n */\nfunction introspectControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<SchemaSnapshot> {\n return withManagedTables(driver, [\n CONTROL_TABLES.log,\n CONTROL_TABLES.state,\n ]).introspect((sql, params) => producer._executeRaw(sql, params));\n}\n\n/** The refusals of the pair, and of a state table left without its log. */\nconst UNAUTHENTIC = {\n pair: {\n unreadable: \"Migration control tables cannot be authenticated\",\n unexpected: \"Migration control tables have an unexpected definition\",\n attached: \"Migration control tables have executable attachments\",\n },\n state: {\n unreadable:\n \"A partial migration control state table cannot be authenticated\",\n unexpected:\n \"A partial migration control state table has an unexpected definition\",\n attached:\n \"A partial migration control state table has executable attachments\",\n },\n} as const;\n\n/**\n * Proves that both reserved control tables — or, with `scope` \"state\", the\n * state table bootstrap left without its log — still have VibORM's exact\n * shape. PostgreSQL reads `catalog` when presence already read it.\n */\nexport async function assertControlTablesAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n scope: keyof typeof UNAUTHENTIC = \"pair\",\n catalog?: PostgresControlCatalog\n): Promise<void> {\n if (driver.target.dialect === \"postgresql\") {\n assertPostgresControlAuthentic(\n catalog ?? (await readPostgresControlCatalog(producer, driver)),\n scope\n );\n return;\n }\n const refusal = UNAUTHENTIC[scope];\n if (driver.target.dialect === \"surrealql\") {\n await assertSurrealControlAuthentic(producer, driver, scope);\n return;\n }\n let snapshot: SchemaSnapshot;\n try {\n snapshot = await introspectControlTables(producer, driver);\n } catch (failure) {\n // The pair keeps introspection's own refusal; the partial state wraps it.\n if (failure instanceof MigrationError && scope === \"pair\") throw failure;\n throw unreadable(refusal.unreadable, failure);\n }\n const matches = (name: string) =>\n snapshot.tables.filter((table) => table.name === name);\n const [state, ...otherStates] = matches(CONTROL_TABLES.state);\n const [log, ...otherLogs] = matches(CONTROL_TABLES.log);\n if (\n !state ||\n otherStates.length > 0 ||\n !hasExpectedShape(state, driver, \"state\") ||\n (scope === \"pair\" &&\n !(log && otherLogs.length === 0 && hasExpectedShape(log, driver, \"log\")))\n ) {\n throw new MigrationError(\n refusal.unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasSingletonCheck: boolean;\n try {\n hasSingletonCheck = await hasExpectedSingletonCheck(producer, driver);\n } catch (failure) {\n throw unreadable(refusal.unreadable, failure);\n }\n if (!hasSingletonCheck) {\n throw new MigrationError(\n refusal.unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasAttachments: boolean;\n try {\n hasAttachments = await hasControlAttachments(producer, driver);\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw unreadable(refusal.unreadable, failure);\n }\n if (hasAttachments) {\n throw new MigrationError(\n refusal.attached,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/** Each control table's fields, unique key and no event, as SurrealDB reads them back. */\nasync function assertSurrealControlAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n scope: keyof typeof UNAUTHENTIC\n): Promise<void> {\n const refusal = UNAUTHENTIC[scope];\n for (const table of scope === \"pair\"\n ? ([\"state\", \"log\"] as const)\n : ([\"state\"] as const)) {\n const name = qualifiedName(driver, CONTROL_TABLES[table]);\n let info: {\n readonly fields: readonly { readonly name: string }[];\n readonly indexes: readonly { readonly name: string }[];\n readonly events: readonly unknown[];\n };\n try {\n const { rows } = await producer._executeRaw<typeof info>(\n `RETURN [(INFO FOR TABLE ${name} STRUCTURE).{ fields, indexes, events }]`\n );\n info = rows[0]!;\n } catch (failure) {\n throw unreadable(refusal.unreadable, failure);\n }\n const expected =\n table === \"state\"\n ? [\"payload\", \"singleton\"]\n : [\"attempt_id\", \"event_id\", \"kind\", \"payload\"];\n const fields = info.fields.map((field) => field.name).sort();\n if (\n fields.join() !== expected.join() ||\n info.indexes.length !== 1 ||\n info.indexes[0]?.name !== `${CONTROL_TABLES[table]}_key`\n )\n throw new MigrationError(\n refusal.unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (info.events.length > 0)\n throw new MigrationError(\n refusal.attached,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/**\n * The definition VibORM creates, as introspection reads it back: the declared\n * columns, NOT NULL with no default (SQLite's TEXT key aside), and the primary\n * key alone. MySQL reports\n * the singleton's INTEGER as `int`.\n */\nfunction hasExpectedShape(\n table: TableDef,\n driver: BoundMigrationDriver,\n kind: ControlTable\n): boolean {\n const mysql = driver.target.dialect === \"mysql\";\n const columns = controlColumns(driver.target.dialect, kind);\n return (\n table.columns.length === columns.length &&\n table.columns.every((column, index) => {\n const [name, type] = columns[index]!;\n return (\n column.name === name &&\n (name === \"singleton\"\n ? normalizeType(column.type) === normalizeType(mysql ? \"INT\" : type)\n : column.type.toLowerCase() === type.toLowerCase()) &&\n // SQLite lets a rowid table's key hold NULL unless it is the rowid\n // alias, and the definition writes the key without NOT NULL.\n column.nullable ===\n (driver.target.dialect === \"sqlite\" &&\n index === 0 &&\n type !== \"INTEGER\") &&\n column.default === undefined &&\n column.autoIncrement !== true &&\n column.decimal === undefined\n );\n }) &&\n table.primaryKey?.name ===\n (mysql ? \"PRIMARY\" : `${CONTROL_TABLES[kind]}_pkey`) &&\n table.primaryKey.columns.length === 1 &&\n table.primaryKey.columns[0] === columns[0]![0] &&\n table.indexes.length === 0 &&\n table.foreignKeys.length === 0 &&\n table.uniqueConstraints.length === 0 &&\n table.relationStorage === undefined\n );\n}\n\nasync function hasExpectedSingletonCheck(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n if (driver.target.dialect === \"sqlite\") {\n const result = await producer._executeRaw<{ sql: unknown }>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [CONTROL_TABLES.state]\n );\n const sql = result.rows[0]?.sql;\n return (\n result.rows.length === 1 &&\n typeof sql === \"string\" &&\n isSqliteStateControlDefinition(CONTROL_TABLES.state, sql)\n );\n }\n const result = await producer._executeRaw<{ definition: unknown }>(\n `SELECT cc.CHECK_CLAUSE AS definition\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.CHECK_CONSTRAINTS cc\n ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\nWHERE tc.CONSTRAINT_SCHEMA = ?\n AND tc.TABLE_NAME = ?\n AND tc.CONSTRAINT_TYPE = 'CHECK'\nORDER BY tc.CONSTRAINT_NAME`,\n [driver.namespace, CONTROL_TABLES.state]\n );\n return (\n result.rows.length === 1 &&\n normalizeSingletonCheck(result.rows[0]?.definition) === \"singleton=1\"\n );\n}\n\nfunction sqliteDefinitionBody(sql: string): string {\n const body = sql.slice(sql.indexOf(\"(\"));\n return body.replace(/[\\s\"`]/g, \"\").toLowerCase();\n}\n\nfunction normalizeSingletonCheck(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value\n .replace(CHECK_PREFIX, \"\")\n .replace(CHECK_FORMATTING, \"\")\n .toLowerCase();\n}\n\nasync function hasControlAttachments(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const names = [CONTROL_TABLES.state, CONTROL_TABLES.log];\n const result =\n driver.target.dialect === \"sqlite\"\n ? await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND tbl_name IN (?, ?)) AS attached\",\n names\n )\n : await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (?, ?)) AS attached\",\n [driver.namespace, ...names]\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Migration control attachment probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const attached = readFlag(Object.values(result.rows[0]!)[0]);\n if (attached !== undefined) return attached;\n throw new MigrationError(\n \"Migration control attachment probe returned an invalid flag\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\nasync function isStateControlEmpty(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<boolean> {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n try {\n const result = await producer._executeRaw(\n `SELECT payload FROM ${table} WHERE singleton = 1`\n );\n return result.rows.length === 0;\n } catch (failure) {\n throw unreadable(\n \"A partial migration control state table cannot be proven empty\",\n failure\n );\n }\n}\n\n/**\n * The refusal `message` for a control-table read that failed, or the failure\n * itself when it says nothing about the tables: the migration lock not taken\n * (the read may be the statement that reopens a command's locked transaction,\n * after a commit let the lock go), a lost connection or another retryable\n * failure, which the caller retries.\n */\nfunction unreadable(message: string, failure: unknown): unknown {\n const transient =\n isRetryableError(failure) ||\n (failure instanceof MigrationError &&\n failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED);\n return transient\n ? failure\n : new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE, {\n cause: errorCause(failure),\n meta: providerFacts(failure),\n });\n}\n\nexport async function isTableMissing(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const probe = tableExistsProbe(driver, tableName, true);\n const result = await producer._executeRaw<Record<string, unknown>>(\n probe.sql,\n probeParameters(probe.parameters)\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Control catalog probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return readFlag(Object.values(result.rows[0]!)[0]) !== true;\n}\n\nfunction probeParameters(\n parameters: ReturnType<typeof tableExistsProbe>[\"parameters\"]\n): unknown[] {\n return parameters.map((parameter) => {\n if (parameter.kind !== \"string\") {\n throw new MigrationError(\n \"Control catalog probe parameters must be strings\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return parameter.value;\n });\n}\n\nexport interface MigrationControlRead {\n readonly presence: ControlPresence;\n readonly marker: MigrationMarkerV1 | null;\n /**\n * The ledger events, in causal order (`inCausalOrder`): every event, or\n * with `{ ledger: \"open\" }` those of an unfinished attempt and the latest\n * `failed` one (plan D5, new defect 6). Without a marker the history may\n * only hold attempts that never reached a state, and all of it is read so\n * `refuseIncompatibleHistory` can say so.\n */\n readonly ledger: readonly LedgerEventV1[];\n}\n\n/** The event kinds that open an attempt, and those that close one. */\nconst OPENING_KINDS: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"started\",\n \"reset-started\",\n]);\nconst CLOSING_KINDS: ReadonlySet<LedgerEventV1[\"kind\"]> = new Set([\n \"applied\",\n \"rolled-back\",\n \"failed\",\n \"baselined\",\n \"reanchored\",\n \"resolved\",\n \"reset-applied\",\n]);\n\n/**\n * Reads the control-plane view. A present pair is authenticated once before\n * either table is trusted; callers decide whether total absence or the\n * recoverable bootstrap arm is valid for their command.\n */\nexport async function readControlState(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n { ledger: scope = \"all\" }: { readonly ledger?: \"open\" | \"all\" } = {}\n): Promise<MigrationControlRead> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind !== \"present\") {\n return { presence, marker: null, ledger: [] };\n }\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n const markerResult = await producer._executeRaw<{ payload: unknown }>(\n `SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1`\n );\n // Without a marker every event is read: `refuseIncompatibleHistory` judges\n // the whole history then.\n const all = scope === \"all\" || markerResult.rows.length === 0;\n const ledgerResult = await producer._executeRaw<{ payload: unknown }>(\n ledgerSql(driver, all)\n );\n const { marker, ledger } = decodeControlRows(\n markerResult.rows,\n ledgerResult.rows\n );\n return { presence, marker, ledger };\n}\n\n/**\n * The ledger events a command reads, selected by their columns, which the\n * one writer (`appendLedger`) fills from the event it appends: every event,\n * or those of an unfinished attempt and the latest `failed` one (plan D5,\n * new defect 6).\n */\nfunction ledgerSql(driver: BoundMigrationDriver, all: boolean): string {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n // Which attempts are open is `unfinishedAttempts`'s to read: a subquery here\n // answers rows, not the list SQL's `IN` reads.\n if (all || driver.target.dialect === \"surrealql\")\n return `SELECT payload FROM ${log}`;\n return `SELECT payload FROM ${log} WHERE ${openAttempt(log)}\n OR event_id = (SELECT event_id FROM ${log} WHERE kind = 'failed' ORDER BY ${jsonField(driver.target.dialect, \"startedAt\")} DESC, event_id DESC LIMIT 1)`;\n}\n\n/** The ledger rows of an unfinished attempt, as `unfinishedAttempts` reads them. */\nfunction openAttempt(log: string): string {\n const list = (kinds: ReadonlySet<string>) =>\n [...kinds].map((kind) => `'${kind}'`).join(\", \");\n return `(attempt_id IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(OPENING_KINDS)}))\n AND attempt_id NOT IN (SELECT attempt_id FROM ${log} WHERE kind IN (${list(CLOSING_KINDS)})))`;\n}\n\n/**\n * `assertLockedSinceDecision` as a condition one request asserts under its\n * own lock (plan D7): the marker is still `expected`, or there is none when\n * that is null, and no attempt is open.\n */\nexport function markerUnmovedCondition(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null\n): { readonly sql: string; readonly params: unknown[] } {\n const log = qualifiedName(driver, CONTROL_TABLES.log);\n const at = expected && markerAt(driver.target.dialect, 1, expected);\n const marker = `EXISTS (SELECT 1 FROM ${qualifiedName(driver, CONTROL_TABLES.state)}${at ? ` WHERE singleton = 1 AND ${at.sql}` : \"\"})`;\n return {\n sql: `(${at ? \"\" : \"NOT \"}${marker} AND NOT EXISTS (SELECT 1 FROM ${log} WHERE ${openAttempt(log)}))`,\n params: at ? at.params : [],\n };\n}\n\n/** What identifies a marker: `markerAt` matches it in SQL, `sameMarker` in JS. */\nexport type MarkerIdentity = Pick<MigrationMarkerV1, \"revision\" | \"pathHash\">;\n\n/** The marker row is `expected`, bound from `$first` on. */\nfunction markerAt(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n first: number,\n { revision, pathHash }: MarkerIdentity\n): { readonly sql: string; readonly params: unknown[] } {\n const slot = placeholder(dialect, first);\n if (dialect === \"surrealql\")\n return {\n sql: `encoding::json::decode(payload).revision = ${slot} AND encoding::json::decode(payload).pathHash = ${placeholder(dialect, first + 1)}`,\n params: [revision, pathHash],\n };\n const revisionMatch =\n dialect === \"postgresql\"\n ? `(payload::json->>'revision')::bigint = ${slot}`\n : dialect === \"mysql\"\n ? `CAST(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.revision')) AS UNSIGNED) = ${slot}`\n : `CAST(json_extract(payload, '$.revision') AS INTEGER) = ${slot}`;\n return {\n sql: `${revisionMatch} AND ${jsonField(dialect, \"pathHash\")} = ${placeholder(dialect, first + 1)}`,\n params: [revision, pathHash],\n };\n}\n\nfunction decodeControlRows(\n markerRows: readonly { readonly payload: unknown }[],\n ledgerRows: readonly { readonly payload: unknown }[]\n): {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n} {\n const markerRow = markerRows[0];\n const stored =\n markerRow && parseMarkerPayload(parsePayload(markerRow.payload));\n return {\n marker: stored ? stored.marker : null,\n predicates: stored ? stored.predicates : [],\n ledger: inCausalOrder(\n ledgerRows.map((row) => parseLedgerEvent(parsePayload(row.payload)))\n ),\n };\n}\n\n/**\n * Plan D5: what a PostgreSQL no-op decides on, in two statements: the control\n * tables' definition, then the marker, the open attempts and the catalog\n * digest, read together and so in one snapshot, provided `lockFree` (the\n * migration lock taken and released at once) holds. Without a marker there is\n * no no-op to prove, so the ledger is never read whole here. `undefined`\n * unless both control tables are present, so no statement here names a table\n * that is not there, and while another command holds the lock; a pair that is\n * not exactly VibORM's is refused. The digest hashes partial-index predicates\n * as the server deparses them, for comparison with those recorded beside the\n * marker.\n */\nexport async function readPostgresDecision(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n lockFree: string\n): Promise<\n | {\n readonly marker: MigrationMarkerV1 | null;\n readonly predicates: readonly MarkerIndexPredicateV1[];\n readonly ledger: readonly LedgerEventV1[];\n readonly digest: Sha256 | undefined;\n }\n | undefined\n> {\n const catalog = await readPostgresControlCatalog(producer, driver);\n if (!(catalog.state && catalog.log)) return;\n assertPostgresControlAuthentic(catalog, \"pair\");\n // Only PostgreSQL reads a decision in one statement: its driver owns this.\n const digest = driver.catalogDigestQuery!(CONTROL_TABLES, true);\n const { rows } = await producer._executeRaw<{\n marker: unknown;\n ledger: unknown;\n digest: unknown;\n }>(\n `SELECT (SELECT json_agg(json_build_object('payload', marker.payload)) FROM (SELECT payload FROM ${qualifiedName(driver, CONTROL_TABLES.state)} WHERE singleton = 1) marker)::text AS marker,\n (SELECT json_agg(json_build_object('payload', ledger.payload)) FROM (${ledgerSql(driver, false)}) ledger)::text AS ledger,\n (${digest.sql}) AS digest WHERE ${lockFree}`,\n digest.parameters\n );\n if (rows.length === 0) return;\n return {\n ...decodeControlRows(\n readPayloadRows(rows[0]?.marker),\n readPayloadRows(rows[0]?.ledger)\n ),\n digest: isSha256(rows[0]?.digest) ? rows[0].digest : undefined,\n };\n}\n\n/** The `{ payload }` rows a JSON aggregate carries; none for SQL NULL. */\nfunction readPayloadRows(value: unknown): { readonly payload: unknown }[] {\n const rows: unknown = readCatalogJson(value);\n return Array.isArray(rows)\n ? rows.flatMap((row: unknown) =>\n isRecord(row) ? [{ payload: row.payload }] : []\n )\n : [];\n}\n\n/**\n * The ledger in causal order (new defect 6). Without a sequence column the\n * clock is the order, and it ties: one millisecond can hold a whole\n * transactional group, or one attempt's close and the next one's start. The\n * events of one instant come attempt by attempt — the one opened earliest\n * first, then along the state chain (an attempt leaving the state another one\n * arrives at follows it), then by attempt id — and inside an attempt as it\n * ran: it opens, confirms steps, then closes. Only a cycle of attempts within\n * one millisecond (up, down, up) falls back to attempt ids.\n */\nfunction inCausalOrder(events: readonly LedgerEventV1[]): LedgerEventV1[] {\n const opened = new Map<Sha256, string>();\n for (const { attemptId, startedAt } of events) {\n const first = opened.get(attemptId);\n if (first === undefined || startedAt < first) {\n opened.set(attemptId, startedAt);\n }\n }\n const byTime = [...events].sort((left, right) =>\n compareText(left.startedAt, right.startedAt)\n );\n const ordered: LedgerEventV1[] = [];\n for (let start = 0; start < byTime.length; ) {\n const instant = byTime[start]!.startedAt;\n let end = start;\n while (byTime[end]?.startedAt === instant) end += 1;\n ordered.push(...instantInOrder(byTime.slice(start, end), opened));\n start = end;\n }\n return ordered;\n}\n\nfunction instantInOrder(\n events: readonly LedgerEventV1[],\n opened: ReadonlyMap<Sha256, string>\n): LedgerEventV1[] {\n const pending = new Map<Sha256, LedgerEventV1[]>();\n for (const event of events) {\n const attempt = pending.get(event.attemptId);\n if (attempt) attempt.push(event);\n else pending.set(event.attemptId, [event]);\n }\n const follows = ({ attemptId, fromState }: LedgerEventV1) =>\n fromState !== null &&\n [...pending.values()].some(\n ([other]) =>\n other!.attemptId !== attemptId && other!.toState === fromState\n );\n const ordered: LedgerEventV1[] = [];\n while (pending.size > 0) {\n const [next] = [...pending.values()]\n .map(([first]) => first!)\n .sort(\n (left, right) =>\n compareText(\n opened.get(left.attemptId)!,\n opened.get(right.attemptId)!\n ) ||\n Number(follows(left)) - Number(follows(right)) ||\n compareText(left.attemptId, right.attemptId)\n );\n ordered.push(\n ...pending\n .get(next!.attemptId)!\n .sort(\n (left, right) =>\n causalRank(left) - causalRank(right) ||\n compareText(left.eventId, right.eventId)\n )\n );\n pending.delete(next!.attemptId);\n }\n return ordered;\n}\n\nfunction compareText(left: string, right: string): number {\n return Number(left > right) - Number(left < right);\n}\n\nfunction causalRank(event: LedgerEventV1): number {\n if (OPENING_KINDS.has(event.kind)) return 0;\n return CLOSING_KINDS.has(event.kind) ? 2 : 1;\n}\n\n/** The text of one top-level field of a JSON payload, per dialect. */\nfunction jsonField(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n field: string\n): string {\n if (dialect === \"postgresql\") return `payload::json->>'${field}'`;\n if (dialect === \"mysql\") {\n return `JSON_UNQUOTE(JSON_EXTRACT(payload, '$.${field}'))`;\n }\n return `json_extract(payload, '$.${field}')`;\n}\n\n/** One control table as the PostgreSQL catalog read reports it. */\ninterface PostgresControlTable {\n readonly kind: unknown;\n readonly partition: unknown;\n readonly columns: unknown;\n readonly constraints: unknown;\n readonly indexes: unknown;\n readonly executable: unknown;\n}\n\ninterface PostgresControlCatalog {\n readonly state: PostgresControlTable | undefined;\n readonly log: PostgresControlTable | undefined;\n}\n\n/**\n * Both control tables' definitions in one statement (plan D5): the columns,\n * the constraints but PostgreSQL 18's catalogued NOT NULLs, how many indexes,\n * and whether a trigger, rule, policy or row security is attached. It reads\n * these two relations only, so no managed table's state — an INVALID index\n * among them (plan S7) — can make the control plane unreadable.\n */\nconst POSTGRES_CONTROL_CATALOG = `SELECT control.position, c.relkind::text AS kind, c.relispartition AS partition,\n (SELECT json_agg(json_build_array(a.attname::text, pg_catalog.format_type(a.atttypid, a.atttypmod), a.attnotnull, a.atthasdef, a.attidentity::text, a.attgenerated::text) ORDER BY a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped)::text AS columns,\n (SELECT json_agg(json_build_array(k.contype::text, k.conname::text, pg_catalog.pg_get_constraintdef(k.oid, true)) ORDER BY k.conname) FROM pg_catalog.pg_constraint k WHERE k.conrelid = c.oid AND k.contype <> 'n')::text AS constraints,\n (SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid)::text AS indexes,\n (EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g WHERE g.tgrelid = c.oid AND NOT g.tgisinternal)\n OR EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w WHERE w.ev_class = c.oid AND w.rulename <> '_RETURN')\n OR EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid)\n OR c.relrowsecurity OR c.relforcerowsecurity) AS executable\nFROM (VALUES (1, $2::text), (2, $3::text)) AS control(position, name)\nLEFT JOIN pg_catalog.pg_class c ON c.relname = control.name AND c.relkind IN ('r', 'p')\n AND c.relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1::text)\nORDER BY control.position`;\n\n/** {@link readPostgresControlCatalog} on PostgreSQL; nothing elsewhere. */\nfunction postgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog | undefined> {\n return driver.target.dialect === \"postgresql\"\n ? readPostgresControlCatalog(producer, driver)\n : Promise.resolve(undefined);\n}\n\nasync function readPostgresControlCatalog(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PostgresControlCatalog> {\n let rows: readonly Record<string, unknown>[];\n try {\n ({ rows } = await producer._executeRaw<Record<string, unknown>>(\n POSTGRES_CONTROL_CATALOG,\n [boundNamespace(driver), CONTROL_TABLES.state, CONTROL_TABLES.log]\n ));\n } catch (failure) {\n throwIfCatalogRefusal(\"control catalog\", failure);\n throw unreadable(UNAUTHENTIC.pair.unreadable, failure);\n }\n if (rows.length !== 2) {\n throw new MigrationError(\n \"Migration control catalog read must return one row per control table\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n state: presentControlTable(rows[0]),\n log: presentControlTable(rows[1]),\n };\n}\n\n/** One row of the catalog read, or `undefined` when that table is absent. */\nfunction presentControlTable(row: unknown): PostgresControlTable | undefined {\n if (!isRecord(row) || row.kind === null || row.kind === undefined) return;\n const { kind, partition, columns, constraints, indexes, executable } = row;\n return { kind, partition, columns, constraints, indexes, executable };\n}\n\nfunction assertPostgresControlAuthentic(\n { state, log }: PostgresControlCatalog,\n scope: keyof typeof UNAUTHENTIC\n): void {\n const pair = scope === \"pair\";\n if (\n !(\n state &&\n hasPostgresShape(state, \"state\") &&\n (!pair || (log && hasPostgresShape(log, \"log\")))\n )\n ) {\n throw new MigrationError(\n UNAUTHENTIC[scope].unexpected,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n readFlag(state.executable) !== false ||\n (pair && readFlag(log?.executable) !== false)\n ) {\n throw new MigrationError(\n UNAUTHENTIC[scope].attached,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\n/**\n * The exact definition VibORM creates: an ordinary table of NOT NULL columns\n * with no default, identity or generation, its primary key, the state\n * table's one `singleton = 1` CHECK, and no other constraint or index.\n */\nfunction hasPostgresShape(\n table: PostgresControlTable,\n kind: ControlTable\n): boolean {\n const columns = controlColumns(\"postgresql\", kind);\n const constraints = readCatalogRows(table.constraints);\n if (constraints === undefined) return false;\n const checks = constraints.filter((constraint) => constraint[0] === \"c\");\n const keys = constraints.filter((constraint) => constraint[0] === \"p\");\n return (\n table.kind === \"r\" &&\n readFlag(table.partition) === false &&\n String(table.indexes) === \"1\" &&\n canonicalizeJsonText(readCatalogJson(table.columns)) ===\n canonicalizeJsonText(\n columns.map(([name, type]) => [\n name,\n type.toLowerCase(),\n true,\n false,\n \"\",\n \"\",\n ])\n ) &&\n constraints.length === keys.length + checks.length &&\n keys.length === 1 &&\n keys[0]?.[1] === `${CONTROL_TABLES[kind]}_pkey` &&\n keys[0]?.[2] === `PRIMARY KEY (${columns[0]![0]})` &&\n checks.length === (kind === \"state\" ? 1 : 0) &&\n checks.every((check) => normalizeSingletonCheck(check[2]) === \"singleton=1\")\n );\n}\n\n/** A JSON column of the catalog read, or `null` when it is not JSON text. */\nfunction readCatalogJson(value: unknown): unknown {\n if (typeof value !== \"string\") return null;\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\n/** A JSON array of arrays (no rows: SQL NULL), or `undefined`. */\nfunction readCatalogRows(\n value: unknown\n): readonly (readonly unknown[])[] | undefined {\n if (value === null) return [];\n const rows: unknown = readCatalogJson(value);\n if (!Array.isArray(rows)) return undefined;\n const checked: (readonly unknown[])[] = [];\n for (const row of rows) {\n const entry: unknown = row;\n if (!Array.isArray(entry)) return undefined;\n checked.push(entry);\n }\n return checked;\n}\n\n/**\n * Creates the pair, or completes the one a failed bootstrap left, under the\n * migration lock: no other command bootstraps between the presence read and\n * the CREATE, so presence is read once.\n */\nexport async function ensureControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<void> {\n const catalog = await postgresControlCatalog(producer, driver);\n const presence = await inspectControlPresence(producer, driver, catalog);\n if (presence.kind === \"present\") {\n await assertControlTablesAuthentic(producer, driver, \"pair\", catalog);\n return;\n }\n if (presence.kind === \"missing-table\") refusePartialControl(presence);\n else {\n await producer._executeRaw(\n `${driver.target.dialect === \"surrealql\" ? \"REMOVE TABLE\" : \"DROP TABLE\"} ${qualifiedName(driver, CONTROL_TABLES.state)}`\n );\n }\n const sql = createControlTableSQL(driver);\n await producer._executeRaw(sql.state);\n await producer._executeRaw(sql.log);\n await assertControlTablesAuthentic(producer, driver);\n}\n\n/**\n * Moves the marker. `predicates`, recorded beside it, are the partial-index\n * predicates of `next`'s snapshot as PostgreSQL deparsed them; a marker\n * without them proves its no-op under the lock.\n */\nexport async function casMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): Promise<void> {\n const { sql, params } = markerWrite(driver, expected, next, predicates);\n if (expected === null) {\n try {\n const result = await producer._executeRaw(sql, params);\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker insert did not create the singleton row\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n } catch (error) {\n if (error instanceof MigrationError) throw error;\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n return;\n }\n\n const result = await producer._executeRaw(sql, params);\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n}\n\n/**\n * The statement {@link casMarker} sends: the first marker's INSERT, or the\n * UPDATE that matches only the `expected` marker. One request (plan D7)\n * sends it after asserting that marker under its lock.\n */\nexport function markerWrite(\n driver: BoundMigrationDriver,\n expected: MarkerIdentity | null,\n next: MigrationMarkerV1,\n predicates: readonly MarkerIndexPredicateV1[] = []\n): { readonly sql: string; readonly params: unknown[] } {\n const table = qualifiedName(driver, CONTROL_TABLES.state);\n const payload = canonicalizeJsonText(\n predicates.length > 0 ? { ...next, predicates } : next\n );\n const dialect = driver.target.dialect;\n const at = expected && markerAt(dialect, 2, expected);\n return at\n ? {\n sql: `UPDATE ${table} SET payload = ${placeholder(dialect, 1)} WHERE singleton = 1 AND ${at.sql}`,\n params: [payload, ...at.params],\n }\n : {\n sql: `INSERT INTO ${table} (singleton, payload) VALUES (1, ${placeholder(dialect, 1)})`,\n params: [payload],\n };\n}\n\n/** Appends events in one statement, in their order. */\nexport async function appendLedger(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n ...events: readonly LedgerEventV1[]\n): Promise<void> {\n const table = qualifiedName(driver, CONTROL_TABLES.log);\n const dialect = driver.target.dialect;\n const rows = events.map((_, index) =>\n [1, 2, 3, 4].map((column) => placeholder(dialect, index * 4 + column))\n );\n await producer._executeRaw(\n `INSERT INTO ${table} (event_id, attempt_id, kind, payload) VALUES ${rows.map((row) => `(${row.join(\", \")})`).join(\", \")}`,\n events.flatMap((event) => [\n event.eventId,\n event.attemptId,\n event.kind,\n canonicalizeJsonText(event),\n ])\n );\n}\n\nexport function markerFromPath(\n estateHash: Sha256,\n snapshotHash: Sha256,\n path: MigrationMarkerV1[\"path\"],\n revision: number\n): MigrationMarkerV1 {\n const stateId = path.length === 0 ? null : path.at(-1)!.stateId;\n return {\n format: \"1\",\n estateHash,\n stateId,\n snapshotHash,\n path,\n pathHash: encodePathHash(path),\n revision,\n updatedAt: new Date().toISOString(),\n };\n}\n\n/** Every ledger event's sealed fields: format, times, tool version and id. */\nexport function ledgerEvent({\n open = false,\n failure = null,\n ...fields\n}: Omit<\n LedgerEventV1,\n \"format\" | \"eventId\" | \"toolVersion\" | \"startedAt\" | \"finishedAt\" | \"failure\"\n> & { failure?: string | null; open?: boolean }): LedgerEventV1 {\n const startedAt = new Date().toISOString();\n const event = {\n format: \"1\" as const,\n ...fields,\n startedAt,\n finishedAt: open ? null : startedAt,\n toolVersion: \"v1\",\n failure,\n };\n return { ...event, eventId: eventIdFor(event) };\n}\n\n/** The fields every event of one attempt carries. */\ntype AttemptSeed = Pick<\n LedgerEventV1,\n | \"estateHash\"\n | \"snapshotHash\"\n | \"sqlHash\"\n | \"fromState\"\n | \"toState\"\n | \"transitionHash\"\n | \"direction\"\n>;\n\n/** An attempt's id: the id of its `started` event under the zero attempt. */\nexport function attemptIdFor(seed: AttemptSeed): Sha256 {\n return ledgerEvent({\n ...seed,\n attemptId: \"0\".repeat(64),\n kind: \"started\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n open: true,\n }).eventId;\n}\n\n/** The builder of one attempt's ledger events. */\nexport interface AttemptEvents {\n readonly attemptId: Sha256;\n event(\n kind: LedgerEventV1[\"kind\"],\n effectState: LedgerEventV1[\"effectState\"],\n step?: {\n readonly operationId: string | null;\n readonly dispatchId: Sha256 | null;\n },\n failure?: string\n ): LedgerEventV1;\n}\n\n/**\n * One attempt's events: each carries `seed` (and a reset plan, when it has\n * one) and `attemptId`, by default the id of the attempt's own `started`\n * event. An opening kind leaves its event unfinished.\n */\nexport function attemptEvents(\n seed: AttemptSeed & Pick<LedgerEventV1, \"resetPlan\">,\n attemptId: Sha256 = attemptIdFor(seed)\n): AttemptEvents {\n return {\n attemptId,\n event: (kind, effectState, step, failure) =>\n ledgerEvent({\n ...seed,\n attemptId,\n kind,\n effectState,\n operationId: step?.operationId ?? null,\n dispatchId: step?.dispatchId ?? null,\n failure,\n open: OPENING_KINDS.has(kind),\n }),\n };\n}\n\n/** Whether a read marker is the one expected; two absent markers are. */\nexport function sameMarker(\n marker: MarkerIdentity | null,\n expected: MarkerIdentity | null\n): boolean {\n return (\n marker?.revision === expected?.revision &&\n marker?.pathHash === expected?.pathHash\n );\n}\n\n/** Compare-and-swaps the marker from `current` to the one `path` ends at. */\nexport async function advanceMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n estateHash: Sha256,\n current: MigrationMarkerV1 | null,\n path: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n revisionStep = 1,\n predicates?: readonly MarkerIndexPredicateV1[]\n): Promise<MigrationMarkerV1> {\n const next = markerFromPath(\n estateHash,\n snapshotHash,\n path,\n (current?.revision ?? 0) + revisionStep\n );\n await casMarker(producer, driver, current, next, predicates);\n return next;\n}\n\nfunction parsePayload(value: unknown): unknown {\n if (typeof value === \"string\") return JSON.parse(value);\n return value;\n}\n\nexport function unfinishedAttempts(\n events: readonly LedgerEventV1[]\n): readonly LedgerEventV1[] {\n const started = new Map<string, LedgerEventV1>();\n const closed = new Set<string>();\n for (const event of events) {\n if (OPENING_KINDS.has(event.kind)) started.set(event.attemptId, event);\n if (CLOSING_KINDS.has(event.kind)) closed.add(event.attemptId);\n }\n return [...started.values()].filter((event) => !closed.has(event.attemptId));\n}\n","/**\n * Migration Estate Target\n *\n * ONE resolver derives the durable estate target from a concrete execution\n * driver, and ONE pair of readers reaches the two runtime facts installed on\n * the adapter and the driver (`adapter.namespace`,\n * `driver.migrationNamespaceAttestation`). Every migration verb, the registry\n * binding, and the live-capability admission owner reach those facts through\n * here, so no command re-decides dialect, namespace or attestation for itself.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { CONTROL_TABLES } from \"./control\";\nimport { snapshotExactArray } from \"./input-boundary\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport { normalizeDialect } from \"./utils\";\n\nexport const MANAGED_TABLES = Symbol(\"migration managed tables\");\n/** The client's resolved limits (plans S1, T5a), bound with its driver. */\nexport const MIGRATION_LIMITS = Symbol(\"migration limits\");\n\n/** Exact physical membership, authenticated as part of the estate target. */\nexport function normalizeManagedTables(\n value: unknown\n): readonly string[] | undefined {\n if (value === undefined) return;\n const entries = snapshotExactArray(value, \"managed tables\", (message) => {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n });\n const names: string[] = [];\n for (const name of entries) {\n if (typeof name !== \"string\" || name.length === 0 || name.includes(\"\\0\"))\n throw new MigrationError(\n \"Managed tables must contain non-empty physical names\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (names.includes(name))\n throw new MigrationError(\n `Managed table \"${name}\" is repeated`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n names.push(name);\n }\n return Object.freeze(names.sort());\n}\n\nexport function selectManagedSnapshot(\n snapshot: SchemaSnapshot,\n target: MigrationTarget,\n desired = false\n): SchemaSnapshot {\n const names = target.tables;\n if (names === undefined) return snapshot;\n // Control authenticity reads the same inventory, independently of user scope.\n const selected = (name: string) =>\n names.includes(name) ||\n name === CONTROL_TABLES.state ||\n name === CONTROL_TABLES.log;\n if (desired && snapshot.tables.some((table) => !names.includes(table.name)))\n throw new MigrationError(\n \"The schema declares a physical table outside the authenticated managed-table list\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n // A control-only selection (the control-table read) draws no user\n // boundary: a user table's keys must not make the control plane unreadable,\n // whatever scope the command selects.\n const userScope = names.some(\n (name) => name !== CONTROL_TABLES.state && name !== CONTROL_TABLES.log\n );\n for (const table of userScope ? snapshot.tables : [])\n for (const fk of table.foreignKeys) {\n if (selected(table.name) !== selected(fk.referencedTable))\n throw new MigrationError(\n `Foreign key \"${table.name}.${fk.name}\" crosses the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const tables = snapshot.tables.filter((table) => selected(table.name));\n const used = new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n for (const table of snapshot.tables.filter(\n (table) => !selected(table.name)\n )) {\n if (\n target.dialect === \"postgresql\" &&\n table.columns.some((column) =>\n enums?.some(\n (item) =>\n (column.type.endsWith(\"[]\")\n ? column.type.slice(0, -2)\n : column.type) === item.name\n )\n )\n )\n throw new MigrationError(\n `Table \"${table.name}\" shares a managed enum across the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return { ...snapshot, tables, ...(enums === undefined ? {} : { enums }) };\n}\n\n/**\n * The live namespace the adapter is bound to, or undefined when the adapter\n * exposes none.\n *\n * Module-private on purpose: `resolveMigrationEstate` is the ONE reader of this\n * fact in the whole migration layer, so no second caller can take a second look\n * at a value a custom adapter may answer differently each time.\n *\n * The property is read reflectively for one reason: it is an OPTIONAL runtime\n * fact whose declaration lives on the adapter contract, and reading it as\n * untyped data keeps the migration layer from claiming any adapter it is handed\n * — including a caller-supplied custom adapter — has already declared it. A\n * present-but-non-string value is the same as absent: unproven.\n *\n * So is the EMPTY STRING. §1.3 settles it for the shipped path — an empty\n * candidate \"is not passed to identifier validation\" and preserves unbound mode\n * — and `normalizeNamespace` (`src/schema/identifier.ts`) rejects `\"\"` against\n * the identifier grammar, so no stock constructor can produce one. A custom\n * adapter can, and this reader is the seam that admits it: an empty name proves\n * no schema and no database, and reading it as proven would qualify every live\n * statement with an EMPTY quoted segment (`\"\".\"users\"`).\n */\nfunction readAdapterNamespace(driver: AnyDriver): string | undefined {\n const value: unknown = Reflect.get(driver.adapter, \"namespace\");\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * The driver's immutable non-redirecting migration-namespace attestation, or\n * undefined when the driver makes no such claim.\n *\n * Only the exact string `\"non-redirecting\"` is an attestation. There is no\n * provider-name fallback and no inference from class, URL, handshake or\n * server version: a driver that does not carry this exact value is unproven,\n * which is what keeps PlanetScale (and any MySQL2 connection reaching Vitess\n * through the ordinary MySQL protocol) out of effectful migration work.\n */\nexport function readNamespaceAttestation(\n driver: AnyDriver\n): \"non-redirecting\" | undefined {\n const value: unknown = Reflect.get(driver, \"migrationNamespaceAttestation\");\n return value === \"non-redirecting\" ? value : undefined;\n}\n\n/**\n * Reads one catalog statement with its bound values.\n *\n * The same shape the dialect base class's `proveNamespaceExists` takes, spelled\n * here so the migration layer's shared owners can name a catalog read without\n * importing a dialect module for the type.\n */\nexport type CatalogRead = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * A dialect whose CONFIGURED namespace and the server's own spelling of it can\n * differ, and which therefore answers one command-local spelling (§5.2).\n *\n * MySQL is the only such dialect: `lower_case_table_names` can make a\n * differently cased configured value name the same physical database, so\n * catalog resolution accepts a single case-folded candidate — and every later\n * statement of that command has to speak the spelling the SERVER answered with,\n * not the one the configuration carried. `information_schema` rows carry the\n * server's spelling, and on a case-sensitive server so does `USE`.\n *\n * PostgreSQL has no such projection (its `pg_namespace` proof is byte-exact)\n * and SQLite has no namespace at all, so both answer nothing here and their\n * commands keep the exact bound driver they started with.\n *\n * The capability is STRUCTURAL, exactly like the pinned-session hook: a dialect\n * declares it by implementing it. This interface is what the implementation is\n * checked against; {@link readsCommandNamespace} is what a shared owner asks.\n */\nexport interface CommandNamespaceResolver {\n resolveCommandNamespace(read: CatalogRead): Promise<string>;\n}\n\n/**\n * Whether this migration driver resolves a command-local namespace spelling.\n *\n * Read as an optional runtime capability rather than declared on the dialect\n * base class, for the same reason `adapter.namespace` is read reflectively\n * above: it is a fact only one dialect has, and a base-class declaration would\n * make every dialect — including a caller-supplied one — answer for it.\n */\nexport function readsCommandNamespace<T extends object>(\n migrationDriver: T\n): migrationDriver is T & CommandNamespaceResolver {\n return (\n typeof Reflect.get(migrationDriver, \"resolveCommandNamespace\") ===\n \"function\"\n );\n}\n\n/**\n * The two estate facts a bound migration driver carries, derived together.\n *\n * `target` is the DURABLE estate generated artifacts claim;\n * `namespace` is the LIVE execution destination. They coincide for PostgreSQL\n * and deliberately differ for MySQL, whose artifacts are database-relative, so\n * both have to be published — but both come from ONE read of the adapter.\n */\nexport interface MigrationEstate {\n readonly target: MigrationTarget;\n readonly namespace: string | undefined;\n}\n\n/**\n * Derives the one frozen estate target and the one live namespace for a\n * concrete execution driver, from a SINGLE read of `adapter.namespace`.\n *\n * The single read is load-bearing, not tidiness. A custom adapter may expose\n * `namespace` as an accessor; two reads could answer two different strings, and\n * the durable target would then name one estate while live DDL rendered\n * another. Reading once and publishing both facts from that one value makes the\n * disagreement structurally impossible (plan §14).\n *\n * The dialect goes through `normalizeDialect` here and nowhere else in the\n * migration layer's target decisions, so a driver cannot resolve to two targets\n * by being read raw on one path and normalized on another.\n *\n * A PostgreSQL driver whose adapter exposes no namespace is UNPROVEN and\n * refused. It must not silently acquire the `\"public\"` default: generated\n * PostgreSQL SQL contains the schema, so a defaulted target would write a\n * durable claim nothing established.\n */\nexport function resolveMigrationEstate(driver: AnyDriver): MigrationEstate {\n const dialect = normalizeDialect(driver.dialect);\n const namespace = readAdapterNamespace(driver);\n\n if (dialect === \"postgresql\") {\n if (namespace === undefined) {\n throw new MigrationError(\n `The PostgreSQL driver \"${driver.driverName}\" exposes no adapter namespace, so its migration estate has no proven schema. ` +\n 'Generated PostgreSQL migration SQL is schema-qualified, so the estate cannot fall back to \"public\": construct the driver with an explicit `namespace`, or supply an adapter that declares one.',\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.driverName, dialect } }\n );\n }\n return { target: Object.freeze({ dialect, namespace }), namespace };\n }\n\n // MySQL and SQLite estates are namespace-free BY DESIGN. MySQL artifacts are\n // database-relative so one history deploys to several database names; SQLite\n // has no namespace concept at all. The live MySQL destination rides beside\n // the target on the bound view, never inside it.\n return { target: Object.freeze({ dialect }), namespace };\n}\n\n/**\n * Human-readable estate description for refusal messages and safe metadata.\n *\n * The live namespace is a SECOND argument because the two facts are separate\n * for MySQL: its durable target is namespace-free by design (§3.1), so the\n * database a command actually touches rides beside it on the bound view. A\n * caller that has it passes it; a caller describing a stored estate target —\n * which carries no database name and must not appear to — does not.\n *\n * Naming it matters wherever the description is what a person consents to: the\n * CLI's `--force-reset` confirmation used to read \"This will DROP ALL TABLES in\n * mysql\", which identifies nothing on the one dialect whose estate target is\n * namespace-free (DECISIONS N6: the confirmation \"must name the target\n * namespace\").\n */\nexport function formatMigrationTarget(\n target: MigrationTarget,\n namespace?: string\n): string {\n if (target.dialect === \"postgresql\") {\n return `${target.dialect} schema \"${target.namespace}\"`;\n }\n return namespace === undefined\n ? target.dialect\n : `${target.dialect} database \"${namespace}\"`;\n}\n\n/**\n * A stored estate is bound to one durable target. PostgreSQL artifacts are\n * schema-qualified, so `alpha` cannot generate or apply as `beta`. MySQL and\n * SQLite compare dialect only.\n *\n * A managed-table list may only grow: the client's list is the estate's\n * frozen list plus tables it adds (adopted or created later). A name of the\n * estate's list missing from the client's, or a list on one side only,\n * refuses.\n */\nexport function assertEstateTargetMatches(\n stored: MigrationTarget,\n live: MigrationTarget\n): void {\n if ((stored.tables === undefined) !== (live.tables === undefined)) {\n throw new MigrationError(\n stored.tables === undefined\n ? \"Estate managed-table scope does not match this client: the estate manages the whole database, and this client passes a `tables` list\"\n : \"Estate managed-table scope does not match this client: the estate manages an exact `tables` list, and this client passes none\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n const missing =\n stored.tables?.filter((name) => !live.tables?.includes(name)) ?? [];\n if (missing.length > 0) {\n throw new MigrationError(\n `Estate managed-table scope does not match this client: its \\`tables\\` list omits ${missing.map((name) => `\"${name}\"`).join(\", \")}, which the estate manages. A list may only grow.`,\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (stored.dialect !== live.dialect) {\n throw new MigrationError(\n \"Estate target dialect does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (\n stored.dialect === \"postgresql\" &&\n live.dialect === \"postgresql\" &&\n stored.namespace !== live.namespace\n ) {\n throw new MigrationError(\n \"Estate target namespace does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n}\n\n/**\n * The tables a history command manages: the estate's frozen list, every table\n * of `snapshots`, less `unmanaged` (a table adopted by a transition, on the\n * side where it is not yet managed). Undefined for an estate without a list,\n * which manages the whole database. Never the client's list: a name only the\n * client lists is a table nothing adopted yet, and it stays the user's.\n */\nexport function managedTables(\n listed: readonly string[] | undefined,\n snapshots: readonly SchemaSnapshot[],\n unmanaged: readonly string[] = []\n): readonly string[] | undefined {\n if (listed === undefined) return;\n const names = new Set(listed);\n for (const snapshot of snapshots)\n for (const table of snapshot.tables) names.add(table.name);\n for (const name of unmanaged) names.delete(name);\n return Object.freeze([...names].sort());\n}\n\n/**\n * A view of `driver` whose target selects `tables` (the whole namespace when\n * undefined): every inventory it reads — introspection, the PostgreSQL\n * catalog digest, invalid indexes, the reset inventory — selects that set.\n * Like every execution view of this layer, it restates `target` only.\n */\nexport function withManagedTables<\n D extends { readonly target: MigrationTarget },\n>(driver: D, tables: readonly string[] | undefined): D {\n const { tables: _replaced, ...target } = driver.target;\n const scoped: D = Object.create(driver);\n Object.defineProperty(scoped, \"target\", {\n value: Object.freeze(tables === undefined ? target : { ...target, tables }),\n enumerable: true,\n });\n return Object.freeze(scoped);\n}\n","/**\n * The one conversion no dialect can perform in SQL: a column BECOMING binary.\n *\n * Every generated `ALTER COLUMN` is a blind re-reading of the bytes already\n * stored. That is harmless when the two types share a reading — `varchar(40)`\n * and `text` are the same characters, `numeric(10,2)` and `numeric(12,2)` the\n * same number — and it is data loss the moment the target is a BINARY column,\n * because the only cast a dialect offers there re-encodes the source's own\n * spelling:\n *\n * · PostgreSQL's `USING col::bytea` writes the ASCII of the old text. A\n * 26-character ULID becomes 26 bytes, not the 16 its codec reads, and every\n * later read is refused as \"not in this column's declared identifier\n * domain\" (measured live on PostgreSQL 16).\n * · SQLite's table rebuild copies the value VERBATIM into the new BLOB\n * column, so `typeof()` still answers `'text'` afterwards — the migration\n * type and the engine binding disagree with no error at all.\n * · MySQL's `MODIFY COLUMN … BINARY(n)` truncates or pads to the declared\n * width without a word in a non-strict `sql_mode`.\n *\n * So the conversion is REFUSED where it is generated, with the manual route\n * named. This is the rule `docs/architecture/native-ids-plan.md` §3 states for\n * an identifier (\"a blind `USING col::bytea` would re-encode text bytes, so it\n * is never emitted\"), and it is stated here in the terms a migration driver\n * actually has: the two column TYPES. A snapshot carries no logical marker that\n * would say \"this BLOB decodes identifiers\", and it does not need one — a\n * verbatim copy into a binary column is unreadable whatever the column holds.\n *\n * PostgreSQL's `uuid` target is deliberately NOT here. `col::uuid` is a real\n * conversion PostgreSQL performs value by value: it succeeds for an estate of\n * canonical uuids and aborts the whole transaction for one that is not, leaving\n * the column as it was. That is a conversion with a wrong answer for nobody.\n *\n * Pure and connection-free, like every other module in this layer.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { Dialect } from \"./drivers/types\";\n\n/** MySQL's two width-carrying binary column spellings. */\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\(\\d+\\)$/i;\nconst MYSQL_BLOB_FAMILY = /^(?:TINYBLOB|BLOB|MEDIUMBLOB|LONGBLOB)$/i;\n\n/** Whether this dialect spells `type` as a column of raw bytes. */\nfunction isBinaryColumnType(type: string, dialect: Dialect): boolean {\n const spelling = type.trim();\n switch (dialect) {\n case \"postgresql\":\n return spelling.toLowerCase() === \"bytea\";\n case \"mysql\":\n return (\n MYSQL_SIZED_BINARY.test(spelling) || MYSQL_BLOB_FAMILY.test(spelling)\n );\n default:\n return spelling.toUpperCase() === \"BLOB\";\n }\n}\n\n/**\n * Refuse an alteration that turns a non-binary column into a binary one.\n *\n * Both sides binary is a WIDTH change and is left alone: `VARBINARY(100)` to\n * `VARBINARY(200)` re-reads the same bytes as the same bytes, which is the\n * property this refusal exists to require.\n */\nexport function refuseBinaryReencoding(\n table: string,\n column: string,\n fromType: string,\n toType: string,\n dialect: Dialect\n): void {\n if (!isBinaryColumnType(toType, dialect)) return;\n if (isBinaryColumnType(fromType, dialect)) return;\n throw new MigrationError(\n `Column \"${column}\" of \"${table}\" would change from ${fromType} to ${toType}, and no dialect can re-read the stored values as bytes: ` +\n \"the generated cast would store the old value's own spelling, which nothing can decode afterwards. \" +\n \"Convert the rows yourself — add the new column, write the decoded values into it, drop the old one and rename — \" +\n \"or, for a declared identifier format, keep the column as it is with a text-family native type, which validates the domain without changing storage.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n","/**\n * MigrationDriver Base Class\n *\n * Abstract base class for database-specific migration drivers.\n * Each driver implements DDL generation and introspection for its database.\n */\n\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { refinedStringDefault } from \"@schema/validation/rules/model\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport type {\n AnyDriver,\n SqliteMigrationCapability,\n} from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { refuseBinaryReencoding } from \"../binary-conversion\";\nimport type { Sha256 } from \"../identity\";\nimport type { ResolvedMigrationLimits } from \"../limits\";\nimport {\n applyNativeRename,\n type NativeRenameOperation,\n} from \"../native-rename\";\nimport type {\n DiffOperation,\n EnumDependentCheck,\n IndexDef,\n MigrationTarget,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { defaultGeneratedPrimaryKeyName, derivedMigrationName } from \"../utils\";\nimport type { PushTargetIdentity } from \"../v1-types\";\nimport type { BoundMigrationDriver } from \".\";\nimport type { Dialect, MigrationCapabilities } from \"./types\";\n\nconst ARRAY_TYPE = /\\[\\]$/;\n\n/** How the serializer ends an index, unique or foreign key name it derives. */\nconst DERIVED_TAIL = /_(?:idx|f?key)$/;\n\n/** A feature of a live table that its adoption would take over unseen. */\nexport interface AdoptionHazard {\n readonly table: string;\n readonly feature: string;\n}\n\n/** A name a native rename carries along, and the statement kind that does. */\nexport interface DerivedRename {\n readonly kind: \"constraint\" | \"index\" | \"type\";\n readonly to: string;\n}\n\n/** The two control tables the fingerprint leaves out. */\nexport interface ControlTableNames {\n readonly state: string;\n readonly log: string;\n}\n\n/**\n * Context passed to DDL generation methods.\n * Contains information needed for operations that require knowledge of the current schema.\n */\nexport interface DDLContext {\n /**\n * Where the rendered statement is going.\n *\n * REQUIRED, and deliberately not defaulted anywhere: an artifact is durable\n * and a live statement is not, and the two differ for MySQL (relative\n * artifacts, qualified live SQL). A dispatcher default would reintroduce\n * exactly the implicit mode this fact replaces, so every caller states it.\n * Generation and generated rollback pass `\"artifact\"`; push, live reset and\n * every immediate DDL path pass `\"live\"`. SQLite ignores the distinction.\n */\n readonly destination: \"artifact\" | \"live\";\n\n /**\n * Current database schema snapshot.\n * Required for SQLite table recreation operations.\n */\n currentSchema?: SchemaSnapshot;\n\n /**\n * The operations of this batch that run *before* the one being generated.\n *\n * `currentSchema` is introspected once, before the batch starts, so on its\n * own it describes the database as it was — not as the statements already\n * emitted have left it. A SQLite table recreation has to name the indexes the\n * table holds at the moment it runs, because `DROP TABLE` takes them with it;\n * see `SQLite3MigrationDriver.getCurrentTable`.\n */\n precedingOperations?: DiffOperation[];\n /** Remaining intent in this same compilation batch, for physical coalescing. */\n followingOperations?: readonly DiffOperation[];\n}\n\n// Extract individual operation types from the DiffOperation union\nexport type CreateTableOperation = Extract<\n DiffOperation,\n { type: \"createTable\" }\n>;\nexport type DropTableOperation = Extract<DiffOperation, { type: \"dropTable\" }>;\nexport type RenameTableOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" }\n>;\nexport type AddColumnOperation = Extract<DiffOperation, { type: \"addColumn\" }>;\nexport type DropColumnOperation = Extract<\n DiffOperation,\n { type: \"dropColumn\" }\n>;\nexport type RenameColumnOperation = Extract<\n DiffOperation,\n { type: \"renameColumn\" }\n>;\nexport type AlterColumnOperation = Extract<\n DiffOperation,\n { type: \"alterColumn\" }\n>;\nexport type CreateIndexOperation = Extract<\n DiffOperation,\n { type: \"createIndex\" }\n>;\nexport type DropIndexOperation = Extract<DiffOperation, { type: \"dropIndex\" }>;\nexport type AddForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"addForeignKey\" }\n>;\nexport type DropForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"dropForeignKey\" }\n>;\nexport type AddUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"addUniqueConstraint\" }\n>;\nexport type DropUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"dropUniqueConstraint\" }\n>;\nexport type AddPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"addPrimaryKey\" }\n>;\nexport type DropPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"dropPrimaryKey\" }\n>;\nexport type CreateEnumOperation = Extract<\n DiffOperation,\n { type: \"createEnum\" }\n>;\nexport type DropEnumOperation = Extract<DiffOperation, { type: \"dropEnum\" }>;\nexport type AlterEnumOperation = Extract<DiffOperation, { type: \"alterEnum\" }>;\n\n/**\n * What a dialect states one operation compiles to: one statement, or the\n * ordered statements it needs. {@link MigrationDriver.compileStatements}\n * filters blanks once for every operation.\n */\ntype GeneratedStatements = string | readonly string[];\n\n/**\n * Abstract base class for migration drivers.\n *\n * Each database (PostgreSQL, SQLite, LibSQL, etc.) extends this class\n * to provide database-specific DDL generation and schema introspection.\n */\nexport abstract class MigrationDriver {\n /**\n * The SQL dialect this driver targets.\n */\n abstract readonly dialect: Dialect;\n\n /**\n * The specific driver name (e.g., \"pg\", \"postgres\", \"pglite\", \"sqlite3\", \"libsql\").\n * Used for driver-specific registration and lookup.\n */\n abstract readonly driverName: string;\n\n /**\n * Capabilities supported by this driver.\n */\n abstract readonly capabilities: MigrationCapabilities;\n\n // ===========================================================================\n // ESTATE BINDING (installed by the registry, never mutated on a singleton)\n // ===========================================================================\n\n // All three are `declare`: the class DECLARES the shape a bound view has and\n // emits no field for it. Under `useDefineForClassFields` (tsconfig target\n // es2022) an ordinary optional field would install a writable, enumerable own\n // property valued `undefined` on the REGISTERED SINGLETON — module-level\n // state that `Reflect.set` could then fill in, which §3.1 forbids. With\n // `declare`, `\"namespace\" in postgresMigrationDriver` is false, and the only\n // instances carrying these facts are the frozen views the registry defines\n // them on.\n\n /**\n * The estate target this instance is bound to.\n *\n * Absent on the REGISTERED singleton, which stays stateless: binding happens\n * at lookup and produces a separate frozen view whose prototype is the\n * singleton. Renderers that need the estate must handle the unbound case\n * rather than assume one, because a singleton reached by name renders\n * artifact SQL with no estate behind it.\n */\n declare readonly target?: MigrationTarget;\n\n /**\n * The exact concrete execution driver this instance was bound to, retained\n * for live admission (its immutable attestation) and for the adapter's\n * capabilities. Absent on the unbound singleton.\n */\n declare readonly executionDriver?: AnyDriver;\n\n /**\n * The bound SQLite driver's migration capability, read once at binding.\n * Absent on the unbound singleton and on every other dialect.\n */\n declare readonly sqliteMigrationCapability?: SqliteMigrationCapability;\n\n /**\n * The live execution namespace read once from the bound adapter.\n *\n * Present for PostgreSQL (its target proved it) and for a bound MySQL\n * adapter; absent for an unbound MySQL adapter used for artifact-only work\n * and for SQLite, which has no namespace.\n */\n declare readonly namespace?: string;\n\n /**\n * The limits of the command this instance is bound for (plans S1, T5a).\n * Absent on the unbound singleton, which renders under the defaults.\n */\n declare readonly limits?: ResolvedMigrationLimits;\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Introspects the current database schema.\n *\n * @param executeRaw - Function to execute raw SQL queries\n * @returns The current schema snapshot\n */\n abstract introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<SchemaSnapshot>;\n\n /**\n * Proves external physical requirements encoded by authenticated snapshots.\n * Dialects with no such requirement keep the no-op owner here.\n *\n * `program` is the statement list the command is about to run (empty when\n * it runs none), so a dialect can refuse what that program would destroy\n * (SQLite: a recreation's dependent triggers and views). Required: a caller\n * cannot skip these refusals by leaving it out.\n *\n * Answers whether the program must commit where `catalogCommitBoundaries`\n * names (PlanetScale's Neki). A caller that `splits` commits there itself\n * and is told so; any other is refused such a program before effects.\n */\n async preflightSchemaRequirements(\n _snapshots: readonly SchemaSnapshot[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n _program: readonly string[],\n _splits?: boolean\n ): Promise<boolean> {\n // Most dialects have no external schema requirement to prove.\n return false;\n }\n\n /**\n * What each named live table carries that changes how it behaves and that\n * no snapshot describes, so the adoption proof cannot see it (a trigger, a\n * conflict clause, a collation the declaration does not state): one entry\n * per table and feature, none when there is nothing. Asked of the tables a\n * command's path adopts (`assertAdoptable`, `proof.ts`): a managed table\n * keeps whatever it has, and `verify` never asks. `introspectSchema` asks it\n * of every table it reads, whose document cannot carry these either.\n */\n async adoptionHazards(\n _tables: readonly string[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<readonly AdoptionHazard[]> {\n return [];\n }\n\n /**\n * Returns this database's own spelling of each declared partial-index\n * predicate, so the differ can compare a declaration against what the catalog\n * gave back (Decision 7.4).\n *\n * Optional, and implemented only where the two spellings can differ.\n * PostgreSQL deparses through `pg_get_expr`, so a declared `active = true`\n * reads back as `(active = true)` and every push re-creates the index;\n * SQLite stores the CREATE INDEX statement verbatim and has nothing to\n * reconcile; MySQL refuses a partial index outright.\n *\n * `executeRaw` runs on ONE pinned connection for the whole call — the\n * canonicalization may need session-local scratch objects, which a pooled\n * connection per statement would scatter. Positional result; `undefined` at\n * a position means the database did not answer, and the differ then refuses\n * to call that predicate equal to anything. `executeBatch` is given where\n * no connection can be pinned (Neon HTTP): each request may be a new\n * session, so session-local work goes out as one request.\n */\n canonicalizeIndexPredicates?(\n tableName: string,\n predicates: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n executeBatch?: <T>(\n statements: readonly string[]\n ) => Promise<ReadonlyArray<{ rows: T[] }>>\n ): Promise<ReadonlyArray<string | undefined>>;\n\n /**\n * The CHECK constraints on the columns of each named enum, read from the\n * live catalog for `push`: a schema snapshot models none, and an enum\n * recreation must drop and re-add them around its text conversion. Optional,\n * and implemented only by PostgreSQL, the one dialect that recreates a type\n * under its columns.\n */\n readEnumDependentChecks?(\n enumNames: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<ReadonlyArray<EnumDependentCheck & { readonly enumName: string }>>;\n\n /**\n * The live managed schema's fingerprint in one statement, where this\n * dialect can compute it (PostgreSQL, `postgres/catalog-digest.ts`): the\n * statement for a caller that embeds it, and the digest read, `undefined`\n * where it abstains. Absent elsewhere, and the caller introspects. The bound\n * driver owns it, so another dialect's bundle never carries it.\n */\n catalogDigestQuery?(\n this: BoundMigrationDriver,\n control: ControlTableNames,\n deparsedPredicates?: boolean\n ): { readonly sql: string; readonly parameters: unknown[] };\n catalogDigest?(\n this: BoundMigrationDriver,\n producer: AnyDriver,\n control: ControlTableNames\n ): Promise<Sha256 | undefined>;\n\n /**\n * Explains why one inverted operation cannot be rendered as an automatic\n * rollback on this dialect. Generation owns the persisted rollback policy;\n * the driver owns the physical boundary that makes an inverse unsafe.\n */\n getIrreversibleRollbackReason(_operation: DiffOperation): string | undefined {\n return undefined;\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n /**\n * Maps a VibORM scalar type to the native database column type.\n *\n * @param scalar - The scalar definition\n * @param scalarState - The scalar state with type info\n * @returns The native column type string\n */\n /**\n * `idDomain` is the identifier domain this column holds, which a foreign key\n * DERIVES from the key it references and therefore cannot be read off the\n * scalar. The physical type comes from the one storage owner\n * ({@link idStorageOf}), so the column this creates and the parameter the\n * engine binds into it are one decision.\n */\n abstract mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string;\n\n /**\n * Final pass over a serialized table before diffing/DDL generation.\n * Lets drivers apply table-aware type adjustments (e.g. MySQL rewrites\n * keyed TEXT columns to VARCHAR, since TEXT cannot be indexed without a\n * key length). Default: identity.\n */\n finalizeTable(table: TableDef): TableDef {\n return table;\n }\n\n /** A generated junction, before {@link finalizeTable}. */\n markJunction?(table: TableDef): TableDef;\n\n /** Whether these operations, after a reset or not, cannot share a transaction. */\n buildsApart?(operations: readonly DiffOperation[], reset?: boolean): boolean;\n\n /** A driver's own answer to what a push targets, where it has one. */\n pushTarget?(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<PushTargetIdentity>;\n\n /**\n * What a committed program of `statements` left running, waited for before\n * the command goes on (SurrealDB's indexes built in the background).\n */\n awaitIndexBuilds?(\n producer: AnyDriver,\n statements: readonly string[]\n ): Promise<void>;\n\n /** A driver's own hold on a command, where no pinned session can take one. */\n holdLock?<T>(\n driver: AnyDriver,\n lockWait: number,\n run: () => Promise<T>\n ): Promise<T>;\n\n /** The exact generated PK name used by this driver's DDL and its inverse. */\n generatedPrimaryKeyName(tableName: string, name?: string): string {\n return defaultGeneratedPrimaryKeyName(tableName, name);\n }\n\n /** Project exactly this driver's compiled rename before diffing or inversion. */\n projectNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n ): SchemaSnapshot {\n const projected = applyNativeRename(snapshot, operation);\n const renames = this.derivedRenames(operation, snapshot);\n if (renames.size === 0) return projected;\n const name = (from: string) => renames.get(from)?.to ?? from;\n const renamed = <T extends { readonly name: string }>(\n items: readonly T[]\n ) => items.map((item) => ({ ...item, name: name(item.name) }));\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n return {\n ...projected,\n ...(projected.enums ? { enums: renamed(projected.enums) } : {}),\n tables: projected.tables.map((table) => {\n if (table.name !== owner) return table;\n const { primaryKey } = table;\n return {\n ...table,\n columns: table.columns.map((column) => {\n const element = column.type.replace(ARRAY_TYPE, \"\");\n const type = name(element) + column.type.slice(element.length);\n return { ...column, type };\n }),\n ...(primaryKey?.name\n ? { primaryKey: { ...primaryKey, name: name(primaryKey.name) } }\n : {}),\n indexes: renamed(table.indexes),\n uniqueConstraints: renamed(table.uniqueConstraints),\n foreignKeys: renamed(table.foreignKeys),\n };\n }),\n };\n }\n\n /**\n * The statements that move `renames`, the names a native rename of `owner`\n * carries along, on a dialect whose renames carry them (PostgreSQL,\n * MySQL). `table` is the owner as the rename leaves it, still holding the\n * old names. Absent where a rename leaves every name as it is (SQLite).\n */\n protected renameDerivedNames?(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>,\n table: TableDef,\n context: DDLContext\n ): string[];\n\n /**\n * The names a native rename carries along, each derived from what it\n * renames: the default primary key's (`<table>_pkey`), a per-column enum\n * type (`<table>_<column>_enum`), and an index, unique or foreign key named\n * after its own columns (`<table>_<columns>_idx`, `_key`, `_fkey`). A table\n * rename also moves an index, unique or foreign key named `<table>_<rest>`\n * that ends as the serializer ends them (`_idx`, `_key`, `_fkey`), whatever\n * the rest is: field names, a compound key's name. Both spellings must fit\n * unbounded (63 bytes) so the inverse rename reads the rest back. Any other\n * name is custom, and stays; a self-set index name of that derived shape\n * cannot be told apart, and moves.\n */\n private derivedRenames(\n operation: NativeRenameOperation,\n snapshot: SchemaSnapshot | undefined\n ): Map<string, DerivedRename> {\n const [from, to] =\n operation.type === \"renameTable\"\n ? [operation.from, operation.to]\n : [operation.tableName, operation.tableName];\n const renamed = (column: string) =>\n operation.type === \"renameColumn\" && column === operation.from\n ? operation.to\n : column;\n const renames = new Map<string, DerivedRename>();\n const follow = (\n kind: DerivedRename[\"kind\"],\n name: string | undefined,\n derive: (table: string, column: (name: string) => string) => string,\n tailed = false\n ) => {\n if (name === undefined) return;\n const tail = name.slice(from.length);\n const next =\n name === derive(from, (column) => column)\n ? derive(to, renamed)\n : tailed &&\n name.startsWith(`${from}_`) &&\n DERIVED_TAIL.test(tail) &&\n derivedMigrationName(to + tail) === to + tail\n ? to + tail\n : name;\n if (next !== name) renames.set(name, { kind, to: next });\n };\n const named =\n (columns: readonly string[], suffix: string) =>\n (owner: string, column: (name: string) => string) =>\n derivedMigrationName(\n `${owner}_${columns.map(column).join(\"_\")}_${suffix}`\n );\n const table = snapshot?.tables.find((item) => item.name === from);\n if (!(table && this.renameDerivedNames)) return renames;\n follow(\"constraint\", table.primaryKey?.name, (owner) =>\n this.generatedPrimaryKeyName(owner)\n );\n for (const column of table.columns) {\n follow(\"type\", column.type.replace(ARRAY_TYPE, \"\"), (owner, renamedTo) =>\n this.getEnumColumnType(owner, renamedTo(column.name), [])\n );\n }\n // A raw index's name is the one its declaration gives, whatever it reads like.\n for (const index of table.indexes) {\n if (index.raw) continue;\n follow(\"index\", index.name, named(index.columns, \"idx\"), true);\n }\n // A unique constraint's index carries its name: renaming it renames both.\n for (const unique of table.uniqueConstraints) {\n follow(\"index\", unique.name, named(unique.columns, \"key\"), true);\n }\n for (const key of table.foreignKeys) {\n follow(\"constraint\", key.name, named(key.columns, \"fkey\"), true);\n }\n return renames;\n }\n\n private compileDerivedRenames(\n operation: NativeRenameOperation,\n context: DDLContext\n ): string[] {\n const snapshot = this.schemaAtOperation(context);\n const renames = this.derivedRenames(operation, snapshot);\n if (renames.size === 0) return [];\n const owner =\n operation.type === \"renameTable\" ? operation.to : operation.tableName;\n const table = applyNativeRename(snapshot!, operation).tables.find(\n (item) => item.name === owner\n )!;\n return this.renameDerivedNames!(owner, renames, table, context);\n }\n\n /**\n * The raw indexes a column rename leaves with a stale marker, as the rename\n * leaves them: the database's index follows the column, but the marker\n * beside it still names the old one, so each driver writes it again (a\n * comment, or the index re-created). One the program drops anyway is left\n * to that drop.\n */\n protected rawIndexesRenamedBy(\n op: RenameColumnOperation,\n context: DDLContext\n ): IndexDef[] {\n let indexes =\n this.schemaAtOperation(context)?.tables.find(\n ({ name }) => name === op.tableName\n )?.indexes ?? [];\n // The indexes the program already dropped or created on the table (a\n // rollback restores the old index before it renames its column back).\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"dropIndex\" &&\n operation.tableName === op.tableName\n )\n indexes = indexes.filter(({ name }) => name !== operation.indexName);\n if (\n operation.type === \"createIndex\" &&\n operation.tableName === op.tableName\n )\n indexes = [...indexes, operation.index];\n }\n const dropped = new Set(\n (context.followingOperations ?? []).flatMap((operation) =>\n operation.type === \"dropIndex\" && operation.tableName === op.tableName\n ? [operation.indexName]\n : []\n )\n );\n return indexes.flatMap((index) =>\n index.raw && index.columns.includes(op.from) && !dropped.has(index.name)\n ? [\n {\n ...index,\n columns: index.columns.map((column) =>\n column === op.from ? op.to : column\n ),\n },\n ]\n : []\n );\n }\n\n /** Native identity and PK effects needed by rename and enum DDL at this prefix. */\n protected schemaAtOperation(context: DDLContext): SchemaSnapshot | undefined {\n let snapshot = context.currentSchema;\n if (!snapshot) return undefined;\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"renameTable\" ||\n operation.type === \"renameColumn\"\n ) {\n snapshot = this.projectNativeRename(snapshot, operation);\n } else if (operation.type === \"createTable\") {\n const table = operation.table;\n snapshot = {\n ...snapshot,\n tables: [\n ...snapshot.tables,\n table.primaryKey\n ? {\n ...table,\n primaryKey: {\n ...table.primaryKey,\n name: this.generatedPrimaryKeyName(\n table.name,\n table.primaryKey.name\n ),\n },\n }\n : table,\n ],\n };\n } else if (operation.type === \"dropTable\") {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n } else if (\n operation.type === \"addPrimaryKey\" ||\n operation.type === \"dropPrimaryKey\"\n ) {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n primaryKey:\n operation.type === \"addPrimaryKey\"\n ? {\n ...operation.primaryKey,\n name: this.generatedPrimaryKeyName(\n operation.tableName,\n operation.primaryKey.name\n ),\n }\n : undefined,\n }\n : table\n ),\n };\n }\n }\n return snapshot;\n }\n\n // Note: getDefaultExpression is implemented below as a common method\n // Override it in subclasses only if database-specific behavior is needed\n\n /**\n * Gets the column type for an enum field.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param values - The enum values\n * @returns The column type (e.g., \"users_status_enum\" for PG, \"TEXT\" for SQLite)\n */\n abstract getEnumColumnType(\n tableName: string,\n columnName: string,\n values: string[]\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n abstract generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropTable(\n op: DropTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n abstract generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropColumn(\n op: DropColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n abstract generateCreateIndex(\n op: CreateIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropIndex(\n op: DropIndexOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n abstract generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n abstract generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n abstract generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n abstract generateCreateEnum(\n op: CreateEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n abstract generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): GeneratedStatements;\n\n // ===========================================================================\n // DDL COMPILATION\n // ===========================================================================\n\n protected filterStatements(\n statements: readonly (string | null | undefined)[]\n ): string[] {\n return statements.filter(\n (statement): statement is string =>\n statement !== null &&\n statement !== undefined &&\n statement.trim().length > 0\n );\n }\n abstract escapeIdentifier(name: string): string;\n abstract getDefaultExpression(\n _scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined;\n\n /** Literal defaults cross the scalar's authoritative write admission once. */\n protected literalDefaultValue(state: ScalarState): unknown {\n const value = state.default;\n if (\n value == null ||\n typeof value === \"function\" ||\n state.autoGenerate ||\n jsonNullKindOf(value) ||\n state.decimal !== undefined\n )\n return value;\n if (typeof value === \"number\" && !Number.isFinite(value))\n throw new MigrationError(\n `Invalid default value: ${value} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n const result = state.base[\"~standard\"].validate(value);\n // A string's own validator judges its default where a create takes it;\n // the column still holds one it refuses (`refinedStringDefault`).\n if (!(\"value\" in result) && refinedStringDefault(state)) return value;\n if (!(\"value\" in result))\n throw new MigrationError(\n `Invalid ${state.type} literal default; the declared scalar schema refused it before DDL.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return result.value;\n }\n\n // ===========================================================================\n // LIVE CONTROL AND NAMESPACE\n // ===========================================================================\n\n /**\n * Proves the configured namespace exists before an empty inventory or an\n * empty applied set may be published.\n *\n * A catalog-driven read cannot otherwise tell a configured-but-absent\n * namespace from an existing namespace holding zero managed objects, and\n * PostgreSQL reports a missing schema and a missing table with the same\n * SQLSTATE. Default: nothing to prove — SQLite has no namespace, and this\n * is not a SQLite namespace feature. PostgreSQL (`pg_namespace`) and MySQL\n * (`information_schema.SCHEMATA`) install their proofs in their own units.\n */\n proveNamespaceExists(\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<void> {\n return Promise.resolve();\n }\n\n // ===========================================================================\n // PUSH PROBES\n // ===========================================================================\n\n /** Whether a table holds any row, which `push` reads before adding a required field. */\n abstract tableHoldsRows(producer: AnyDriver, table: string): Promise<boolean>;\n /** A stored value of `column` that `declared` does not hold, if a row has one. */\n abstract undeclaredValue(\n producer: AnyDriver,\n table: string,\n column: string,\n declared: readonly string[]\n ): Promise<{ readonly stored: unknown } | undefined>;\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * Generates SQL for acquiring a migration lock, with a stable `acquired`\n * alias so the caller reads one known column rather than a provider-shaped\n * name derived from the expression text.\n *\n * Returns null when this dialect takes no session lock (SQLite/LibSQL, which\n * keep their own single-connection queue).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateAcquireLock(lockId: number): string | null;\n\n /**\n * Generates SQL for releasing a migration lock, with a stable `released`\n * alias. Returns null on the dialects that take no lock.\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateReleaseLock(lockId: number): string | null;\n\n /**\n * Whether the provider's answer to {@link generateAcquireLock} PROVES the\n * lock is held.\n *\n * Asked only when a lock statement was emitted, so the dialects that emit\n * none never reach it. The default is `false` because a lock nobody proved is\n * a lock nobody holds: MySQL's `GET_LOCK` returns `0` on timeout and `NULL`\n * on error, and the previous owner discarded that answer entirely and ran the\n * \"protected\" work anyway.\n */\n provesLockAcquired(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Whether the provider's answer to {@link generateReleaseLock} PROVES the\n * lock was released. A false answer condemns the session: it is holding a\n * lock nobody will release, and returning it to a pool would strand it.\n */\n provesLockReleased(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Selects the live migration target on a pinned session, or null when this\n * dialect has nothing to select.\n *\n * MySQL is the only arm: its generated artifacts are database-relative, so\n * the target has to be selected on the connection that executes them. Every\n * other dialect qualifies its statements and must never touch session state\n * (§13).\n */\n generateSelectTarget(): string | null {\n return null;\n }\n\n /**\n * Whether this server holds one command's migration lock as the session\n * lock alone, taken once before its first transaction and never mixed with\n * the transaction lock (PlanetScale's Neki). Asked once per command, on its\n * pinned session, before any lock. Default: no.\n */\n holdsSessionLock(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n /**\n * Whether this command's server refuses to plan a statement against any\n * relation in a transaction that changed the schema (PlanetScale's Neki,\n * `NK013` \"[817] … earlier DDL in this transaction is not reflected in the\n * router's schema view\"), VibORM's own ledger and marker writes included:\n * its work then runs stepwise, each statement committed alone, its control\n * writes in their own. Known once {@link holdsSessionLock} answered for the\n * command. Default: no.\n */\n commitsSchemaChangesAlone(): boolean {\n return false;\n }\n\n /**\n * The session lock PostgreSQL stepwise work keeps (plan D1), taken while\n * the session holds the transaction lock on the same key (or alone, where\n * {@link holdsSessionLock}); null elsewhere.\n */\n generateSessionLock(_lockId: number): string | null {\n return null;\n }\n\n /**\n * A condition true while no command holds the migration lock (plan D5).\n * The default never proves it: only PostgreSQL can ask.\n */\n generateLockFree(_lockId: number): string {\n return \"false\";\n }\n\n /**\n * Proves a locked session may run this command's work, once, after its\n * target is selected, and returns the driver the command renders from.\n * Default: nothing to prove.\n */\n proveSession(\n _read: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<this> {\n return Promise.resolve(this);\n }\n\n /** The statements a sequential program runs first, on its producer. */\n programPreamble(_producer: AnyDriver): Promise<readonly string[]> {\n return Promise.resolve([]);\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The live-namespace table inventory: the exact set of tables a reset may\n * drop, as a BOUND read.\n *\n * `{ sql, params }` rather than a bare string because §4.2/§5.2 require the\n * namespace to reach a catalog predicate through the parameter channel: a\n * bare-string seam has nothing to bind through, so it can only splice the\n * name into the statement as an escaped literal.\n *\n * @returns Bound SELECT returning rows with a `name` column\n */\n abstract generateInventoryTables(): { sql: string; params: unknown[] };\n\n /**\n * The live-namespace enum inventory, or null for dialects with no standalone\n * enum types.\n */\n abstract generateInventoryEnums(): {\n sql: string;\n params: unknown[];\n } | null;\n abstract generateDropTableSQL(tableName: string): string;\n abstract generateDropEnumSQL(enumName: string): string | null;\n\n // ===========================================================================\n // DISPATCH (final - not meant to be overridden)\n // ===========================================================================\n\n /**\n * The one owner of provider statement boundaries for generated DDL.\n */\n compileStatements(\n operation: DiffOperation,\n context: DDLContext\n ): readonly string[] {\n const generated = this.generateOperation(operation, context);\n const statements = typeof generated === \"string\" ? [generated] : generated;\n return this.filterStatements(\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n ? [...statements, ...this.compileDerivedRenames(operation, context)]\n : statements\n );\n }\n\n private generateOperation(\n operation: DiffOperation,\n context: DDLContext\n ): GeneratedStatements {\n switch (operation.type) {\n case \"createTable\":\n return this.generateCreateTable(operation, context);\n case \"dropTable\":\n return this.generateDropTable(operation, context);\n case \"renameTable\":\n return this.generateRenameTable(operation, context);\n case \"addColumn\":\n return this.generateAddColumn(operation, context);\n case \"dropColumn\":\n return this.generateDropColumn(operation, context);\n case \"renameColumn\":\n return this.generateRenameColumn(operation, context);\n case \"alterColumn\":\n // Asked HERE rather than in each driver's `generateAlterColumn`: the\n // question is one — \"can this dialect re-read the stored bytes as the\n // new type?\" — and three copies of it would drift the way the three\n // conversion routes already did (PostgreSQL cast, SQLite rebuild,\n // MySQL MODIFY, each silently wrong in its own way).\n refuseBinaryReencoding(\n operation.tableName,\n operation.columnName,\n operation.from.type,\n operation.to.type,\n this.dialect\n );\n return this.generateAlterColumn(operation, context);\n case \"createIndex\":\n return this.generateCreateIndex(operation, context);\n case \"dropIndex\":\n return this.generateDropIndex(operation, context);\n case \"addForeignKey\":\n return this.generateAddForeignKey(operation, context);\n case \"dropForeignKey\":\n return this.generateDropForeignKey(operation, context);\n case \"addUniqueConstraint\":\n return this.generateAddUniqueConstraint(operation, context);\n case \"dropUniqueConstraint\":\n return this.generateDropUniqueConstraint(operation, context);\n case \"addPrimaryKey\":\n return this.generateAddPrimaryKey(operation, context);\n case \"dropPrimaryKey\":\n return this.generateDropPrimaryKey(operation, context);\n case \"createEnum\":\n return this.generateCreateEnum(operation, context);\n case \"dropEnum\":\n return this.generateDropEnum(operation, context);\n case \"alterEnum\":\n return this.generateAlterEnum(operation, context);\n default:\n throw new MigrationError(\n `Unknown operation type: ${(operation as any).type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n }\n\n /**\n * Generates display DDL for a diff operation.\n */\n generateDDL(operation: DiffOperation, context: DDLContext): string {\n return this.compileStatements(operation, context).join(\";\\n\");\n }\n}\n","/**\n * Migration Driver Registry\n *\n * Central registry for migration drivers. Drivers are registered by their\n * driver name and can be looked up by driver name or dialect.\n *\n * This module registers nothing: the entry an application imports does\n * (`dialects/*.ts`), so a bundle carries only the dialects it registers.\n */\n\nimport type {\n AnyDriver,\n SqliteMigrationCapability,\n} from \"../../drivers/driver\";\nimport {\n type DiagnosticDisclosure,\n MigrationError,\n VibORMErrorCode,\n} from \"../../errors\";\nimport {\n DEFAULT_MIGRATION_LIMITS,\n type ResolvedMigrationLimits,\n} from \"../limits\";\nimport { resolveMigrationEstate, selectManagedSnapshot } from \"../target\";\nimport type { MigrationTarget } from \"../types\";\nimport type { MigrationDriver } from \"./base\";\nimport type { Dialect } from \"./types\";\n\nexport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"./base\";\n// Export base class and types\nexport { MigrationDriver } from \"./base\";\nexport type { Dialect, MigrationCapabilities } from \"./types\";\n\n// =============================================================================\n// REGISTRY\n// =============================================================================\n\n/**\n * Registry of migration drivers by driver name.\n */\nconst driverRegistry = new Map<string, MigrationDriver>();\n\n/**\n * The implementation each stock SQLite driver binds to, by name.\n *\n * SQLite is the one dialect with two implementations, so a SQLite driver never\n * binds by dialect: a driver declaring `sqliteMigrationCapability` binds to\n * `sqlite3` whatever its name (so a declaring libSQL subclass never reaches the\n * libsql implementation's unvalidated native ALTER COLUMN), an undeclared stock\n * driver binds here, and an undeclared custom one has no binding at all.\n * Binding is not admission: effectful work still needs the declaration\n * (`admission.ts`). PostgreSQL and MySQL have one implementation each,\n * registered under the dialect's name.\n */\nconst STOCK_SQLITE_BINDINGS: ReadonlyMap<string, string> = new Map([\n [\"sqlite3\", \"sqlite3\"],\n [\"bun-sqlite\", \"sqlite3\"],\n [\"libsql\", \"libsql\"],\n]);\n\n/**\n * The closed table of admitted declarations, as bound: stock SQLite, a\n * Durable Object, and D1 (read-only). They restate the drivers' own\n * declarations in `src/drivers/driver.ts`, spelled here so the migration\n * bundle does not import the driver module.\n */\nconst SQLITE_MIGRATION_CAPABILITIES: readonly SqliteMigrationCapability[] = [\n Object.freeze({\n foreignKeys: \"pragma\",\n reservedTablePrefixes: \"none\",\n exclusion: \"database-write-lock\",\n }),\n Object.freeze({\n foreignKeys: \"pragma\",\n reservedTablePrefixes: \"_cf_\",\n exclusion: \"frame\",\n }),\n Object.freeze({\n foreignKeys: \"none\",\n reservedTablePrefixes: \"_cf_\",\n exclusion: \"none\",\n }),\n];\n\n/**\n * Registers a migration driver.\n *\n * @param driver - The migration driver to register\n */\nexport function registerMigrationDriver(driver: MigrationDriver): void {\n driverRegistry.set(driver.driverName, driver);\n}\n\n/**\n * A migration driver bound to one estate.\n *\n * Binding narrows two of the base class's optional facts — the durable target\n * and the execution driver — to present ones, so an admitted live boundary\n * never has to ask whether its driver knows which estate it serves. The live\n * `namespace` stays optional: an unbound MySQL adapter binds to a real estate,\n * and refusing it for effectful work belongs to the admission owner.\n */\nexport interface BoundMigrationDriver extends MigrationDriver {\n readonly target: MigrationTarget;\n readonly executionDriver: AnyDriver;\n /** The SQLite capability read once at binding; admission decides from it. */\n readonly sqliteMigrationCapability: SqliteMigrationCapability | undefined;\n /** The command's limits: the client's own, or the defaults. */\n readonly limits: ResolvedMigrationLimits;\n /**\n * What the command's failures disclose: its client's own instrumentation\n * `diagnostics`, carried by the session its statements run on.\n */\n readonly diagnostics: DiagnosticDisclosure | undefined;\n}\n\n/**\n * Looks up the dialect implementation and returns it BOUND to this driver's\n * estate.\n *\n * The registry stays the dialect implementation registry and its entries stay\n * stateless: binding never mutates a registered singleton and never parks an\n * active namespace in module-level state. The bound value is a frozen view\n * whose prototype is the registered instance, so two clients on two schemas\n * hold two immutable targets over one implementation.\n *\n * This is the ONE place a driver becomes a migration estate. Resolving the\n * estate here is what makes an unproven PostgreSQL adapter fail at lookup\n * rather than at some later statement.\n *\n * The durable target and the live namespace are BOTH taken from one\n * `resolveMigrationEstate` call, which reads `adapter.namespace` exactly once.\n * Binding must never read that fact a second time: an accessor-backed custom\n * adapter could answer differently, and the frozen view would then name one\n * estate in its target and render another in its DDL.\n *\n * @throws MigrationError if no implementation is registered, or if the estate\n * target cannot be proven\n */\nexport function getMigrationDriver(\n driver: AnyDriver,\n tables?: readonly string[],\n limits: ResolvedMigrationLimits = DEFAULT_MIGRATION_LIMITS,\n diagnostics?: DiagnosticDisclosure\n): BoundMigrationDriver {\n const { target: baseTarget, namespace } = resolveMigrationEstate(driver);\n const target =\n tables === undefined\n ? baseTarget\n : Object.freeze({ ...baseTarget, tables });\n const capability =\n target.dialect === \"sqlite\"\n ? readSqliteMigrationCapability(driver)\n : undefined;\n const implementation = findMigrationDriver(\n driver.driverName,\n target.dialect,\n capability\n );\n\n const bound: BoundMigrationDriver = Object.create(implementation);\n Object.defineProperties(bound, {\n target: { value: target, enumerable: true },\n executionDriver: { value: driver, enumerable: true },\n namespace: { value: namespace, enumerable: true },\n sqliteMigrationCapability: { value: capability, enumerable: true },\n limits: { value: limits, enumerable: true },\n diagnostics: { value: diagnostics, enumerable: true },\n introspect: {\n async value(\n this: MigrationDriver,\n executeRaw: Parameters<MigrationDriver[\"introspect\"]>[0]\n ) {\n // `this.target`, not the bound one: a history command restates the\n // managed set on a view of this driver (`withManagedTables`).\n return selectManagedSnapshot(\n await implementation.introspect.call(this, executeRaw),\n (this as BoundMigrationDriver).target\n );\n },\n },\n });\n Object.freeze(bound);\n return bound;\n}\n\n/**\n * The driver's SQLite migration capability, read ONCE, as the table's own\n * frozen entry, or undefined when it declares none of them. Only whole exact\n * declarations count: each member is a safety claim, and a mistyped or mixed\n * claim must not read as an approximate one.\n */\nfunction readSqliteMigrationCapability(\n driver: AnyDriver\n): SqliteMigrationCapability | undefined {\n const declared: unknown = driver.sqliteMigrationCapability;\n if (typeof declared !== \"object\" || declared === null) return;\n const foreignKeys: unknown = Reflect.get(declared, \"foreignKeys\");\n const reservedTablePrefixes: unknown = Reflect.get(\n declared,\n \"reservedTablePrefixes\"\n );\n const exclusion: unknown = Reflect.get(declared, \"exclusion\");\n return SQLITE_MIGRATION_CAPABILITIES.find(\n (capability) =>\n capability.foreignKeys === foreignKeys &&\n capability.reservedTablePrefixes === reservedTablePrefixes &&\n capability.exclusion === exclusion\n );\n}\n\n/** Resolves the registered implementation this driver binds to. */\nfunction findMigrationDriver(\n driverName: string,\n dialect: Dialect,\n capability: SqliteMigrationCapability | undefined\n): MigrationDriver {\n let name: string | undefined = dialect;\n if (dialect === \"sqlite\") {\n name = capability ? \"sqlite3\" : STOCK_SQLITE_BINDINGS.get(driverName);\n }\n const driver = name === undefined ? undefined : driverRegistry.get(name);\n if (driver) return driver;\n throw new MigrationError(\n name === undefined\n ? `The SQLite driver \"${driverName}\" declares no \\`sqliteMigrationCapability\\`, so no migration implementation binds to it.`\n : `No migration driver registered for \"${driverName}\" (dialect: ${dialect}).`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { driver: driverName, dialect } }\n );\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n MAX_DATETIME_EPOCH_MILLISECONDS,\n MIN_DATETIME_EPOCH_MILLISECONDS,\n} from \"@validation/primitives/datetime-values\";\nimport { createIdentifierQuoter } from \"../../../../sql/identifiers\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n/**\n * `abs(INT64_MIN)` raises SQLite's \"integer overflow\" error: the one abort\n * every copy and rewrite expression uses to stop on a value it cannot convert.\n */\nexport const SQLITE_ABORT = \"abs(-9223372036854775808)\";\n\nconst ISO_DATE = \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\";\nconst ISO_TIME = \"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\";\nconst ISO_OFFSET = \"[+-][0-9][0-9]:[0-9][0-9]\";\n/**\n * The stored-text grammar: the client's ISO input grammar plus SQLite's own\n * zone-less spelling (`datetime('now')`, `CURRENT_TIMESTAMP`), which SQLite\n * defines as UTC.\n */\nconst ISO_TIMESTAMP_SHAPES = [\n `${ISO_DATE} ${ISO_TIME}`,\n `${ISO_DATE} ${ISO_TIME}.[0-9]`,\n `${ISO_DATE} ${ISO_TIME}.[0-9][0-9]`,\n `${ISO_DATE} ${ISO_TIME}.[0-9][0-9][0-9]`,\n `${ISO_DATE}T${ISO_TIME}Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]${ISO_OFFSET}`,\n];\n\nexport function sqliteDateTimeTargetRequiresRecreation(\n from: DateTimePhysicalForm | undefined,\n to: DateTimePhysicalForm | undefined\n): boolean {\n return to !== undefined && from !== to;\n}\n\n/** SQLite spelling of JavaScript's `Math.round`, including negative halves. */\nfunction roundToInteger(expression: string): string {\n const integer = `CAST(${expression} AS INTEGER)`;\n const fraction = `(${expression} - ${integer})`;\n return (\n `(${integer} + CASE ` +\n `WHEN ${fraction} >= 0.5 THEN 1 ` +\n `WHEN ${fraction} < -0.5 THEN -1 ELSE 0 END)`\n );\n}\n\nfunction julianToEpochMilliseconds(julianDay: string): string {\n return roundToInteger(\n `((${julianDay} - ${UNIX_EPOCH_JULIAN_DAY}) * ${MILLISECONDS_PER_DAY})`\n );\n}\n\nfunction epochMillisecondsToJulian(epochMilliseconds: string): string {\n return (\n `((${epochMilliseconds} / ${MILLISECONDS_PER_DAY}.0) + ` +\n `${UNIX_EPOCH_JULIAN_DAY})`\n );\n}\n\nfunction textFractionMilliseconds(source: string): string {\n const first = `CAST(substr(${source}, 21, 1) AS INTEGER)`;\n const second = `CAST(substr(${source}, 22, 1) AS INTEGER)`;\n const third = `CAST(substr(${source}, 23, 1) AS INTEGER)`;\n return (\n `(CASE WHEN substr(${source}, 20, 1) <> '.' THEN 0 ELSE ` +\n `${first} * 100 + ` +\n `CASE WHEN substr(${source}, 22, 1) GLOB '[0-9]' THEN ${second} * 10 + ` +\n `CASE WHEN substr(${source}, 23, 1) GLOB '[0-9]' THEN ${third} ELSE 0 END ` +\n \"ELSE 0 END END)\"\n );\n}\n\n/** SQLite's zone-less UTC spelling separates date and time with a space. */\nfunction isZoneless(source: string): string {\n return `substr(${source}, 11, 1) = ' '`;\n}\n\nfunction textOffsetMilliseconds(source: string): string {\n const magnitude =\n `((CAST(substr(${source}, -5, 2) AS INTEGER) * 60 + ` +\n `CAST(substr(${source}, -2, 2) AS INTEGER)) * 60000)`;\n return (\n `(CASE WHEN substr(${source}, -1, 1) = 'Z' OR ${isZoneless(source)} THEN 0 ` +\n `WHEN substr(${source}, -6, 1) = '+' THEN ${magnitude} ` +\n `ELSE -${magnitude} END)`\n );\n}\n\n/** Epoch milliseconds without SQLite's narrower timezone-offset parser. */\nfunction textToEpochMilliseconds(source: string): string {\n const day = julianToEpochMilliseconds(\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z')`\n );\n const local =\n `(${day} + CAST(substr(${source}, 12, 2) AS INTEGER) * 3600000 + ` +\n `CAST(substr(${source}, 15, 2) AS INTEGER) * 60000 + ` +\n `CAST(substr(${source}, 18, 2) AS INTEGER) * 1000 + ` +\n `${textFractionMilliseconds(source)})`;\n return `(${local} - ${textOffsetMilliseconds(source)})`;\n}\n\n/** Canonical ISO text for an admitted SQLite-range epoch millisecond. */\nfunction epochMillisecondsToText(epochMilliseconds: string): string {\n const wholeSeconds =\n `(CASE WHEN ${epochMilliseconds} < 0 AND ` +\n `${epochMilliseconds} % 1000 <> 0 ` +\n `THEN ${epochMilliseconds} / 1000 - 1 ` +\n `ELSE ${epochMilliseconds} / 1000 END)`;\n const milliseconds = `(((${epochMilliseconds} % 1000) + 1000) % 1000)`;\n return (\n \"(\" +\n `strftime('%Y-%m-%dT%H:%M:%S', ${wholeSeconds}, 'unixepoch') || ` +\n `printf('.%03dZ', ${milliseconds})` +\n \")\"\n );\n}\n\nfunction epochMilliseconds(source: string, form: DateTimePhysicalForm): string {\n if (form === \"epochMillis\") return source;\n if (form === \"julianDay\") return julianToEpochMilliseconds(source);\n return textToEpochMilliseconds(source);\n}\n\n/** SQL transcription of the stored-text grammar (`ISO_TIMESTAMP_SHAPES`). */\nfunction isIsoTimestamp(source: string): string {\n return `(${ISO_TIMESTAMP_SHAPES.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")})`;\n}\n\n/** Component rules used by the public ISO timestamp admission boundary. */\nfunction isAdmittedIsoTimestamp(source: string): string {\n const year = `CAST(substr(${source}, 1, 4) AS INTEGER)`;\n const month = `CAST(substr(${source}, 6, 2) AS INTEGER)`;\n const day = `CAST(substr(${source}, 9, 2) AS INTEGER)`;\n const hour = `CAST(substr(${source}, 12, 2) AS INTEGER)`;\n const minute = `CAST(substr(${source}, 15, 2) AS INTEGER)`;\n const second = `CAST(substr(${source}, 18, 2) AS INTEGER)`;\n const zulu = `substr(${source}, -1, 1) = 'Z'`;\n const offsetHour = `CAST(substr(${source}, -5, 2) AS INTEGER)`;\n const offsetMinute = `CAST(substr(${source}, -2, 2) AS INTEGER)`;\n const isLeapYear = `(${year} % 4 = 0 AND (${year} % 100 <> 0 OR ${year} % 400 = 0))`;\n const lastDay =\n `(CASE ${month} ` +\n `WHEN 2 THEN CASE WHEN ${isLeapYear} THEN 29 ELSE 28 END ` +\n \"WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 \" +\n \"ELSE 31 END)\";\n return (\n `${isIsoTimestamp(source)} AND ${month} BETWEEN 1 AND 12 AND ` +\n `${day} BETWEEN 1 AND ${lastDay} AND ${hour} BETWEEN 0 AND 23 AND ` +\n `${minute} BETWEEN 0 AND 59 AND ${second} BETWEEN 0 AND 59 AND ` +\n `(${zulu} OR ${isZoneless(source)} OR (${offsetHour} BETWEEN 0 AND 23 AND ${offsetMinute} BETWEEN 0 AND 59)) AND ` +\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z') IS NOT NULL`\n );\n}\n\nfunction sourceIsExact(\n source: string,\n form: DateTimePhysicalForm,\n epoch: string\n): string {\n if (form === \"text\") {\n return (\n `typeof(${source}) = 'text' AND ${isAdmittedIsoTimestamp(source)} AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n if (form === \"epochMillis\") {\n return (\n `typeof(${source}) = 'integer' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n return (\n `typeof(${source}) = 'real' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS} AND ` +\n `${epochMillisecondsToJulian(epoch)} = ${source}`\n );\n}\n\nfunction targetValue(epoch: string, form: DateTimePhysicalForm): string {\n if (form === \"text\") return epochMillisecondsToText(epoch);\n if (form === \"epochMillis\") return epoch;\n return epochMillisecondsToJulian(epoch);\n}\n\nfunction targetIsExact(\n epoch: string,\n form: DateTimePhysicalForm,\n value: string\n): string {\n if (form === \"text\") {\n return `${value} IS NOT NULL AND ${isIsoTimestamp(value)}`;\n }\n if (form === \"epochMillis\") return \"1\";\n return `${julianToEpochMilliseconds(value)} = ${epoch}`;\n}\n\n/**\n * Converts one copied SQLite DateTime between its declared physical forms.\n *\n * The guard is the sole integrity boundary. It accepts only a value that is an\n * exact member of the source vocabulary and whose target representation\n * decodes to the same millisecond. `abs(INT64_MIN)` is SQLite's built-in,\n * deterministic error expression; it makes malformed, out-of-range, and\n * inexact rows abort the recreation instead of being rounded or reinterpreted.\n * An authenticated snapshot proves a same-form source and can retain it\n * unchanged. A live-introspected source has no logical marker, so even a\n * same-physical-form adoption crosses this guard before it becomes DateTime.\n */\nexport function sqliteDateTimeCopyExpression(\n source: string,\n from: DateTimePhysicalForm,\n to: DateTimePhysicalForm,\n isDeclaredSource: boolean\n): string {\n if (from === to && isDeclaredSource) return source;\n const epoch = epochMilliseconds(source, from);\n const value = from === to ? source : targetValue(epoch, to);\n const exact =\n from === to\n ? sourceIsExact(source, from, epoch)\n : `${sourceIsExact(source, from, epoch)} AND ${targetIsExact(epoch, to, value)}`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL ` +\n `WHEN ${exact} THEN ${value} ` +\n `ELSE ${SQLITE_ABORT} END`\n );\n}\n\n/** A reviewed manual-migration expression; the argument is a physical column name. */\nexport function sqliteCanonicalDateTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** The Time writer, the `viborm check --db` audit and the repair share one physical grammar. */\nfunction timeSource(source: string): { valid: string; value: string } {\n const shapes = [\n ISO_TIME,\n `${ISO_TIME}.[0-9]`,\n `${ISO_TIME}.[0-9][0-9]`,\n `${ISO_TIME}.[0-9][0-9][0-9]`,\n ];\n const valid = `typeof(${source}) = 'text' AND (${shapes.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")}) AND CAST(substr(${source},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${source},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${source},7,2) AS INTEGER) BETWEEN 0 AND 59`;\n const value = `substr(${source},1,8) || '.' || substr(CASE WHEN length(${source}) = 8 THEN '000' ELSE substr(${source},10) || '000' END,1,3)`;\n return { valid, value };\n}\n\n/** Canonical millisecond Time storage; malformed source rows abort the statement. */\nexport function sqliteCanonicalTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${valid} THEN ${value} ELSE ${SQLITE_ABORT} END`;\n}\n\n/** Exact canonical carrier predicates for `viborm check --db`: NULL passes, unknown/malformed does not. */\nexport function sqliteCanonicalDateTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\nexport function sqliteCanonicalTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${valid} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\ntype TemporalType = \"datetime\" | \"time\";\n\n/**\n * One text DateTime/Time column (scalar or JSON list): which rows lie outside\n * the canonical carrier, and the canonical value a row rewrites to. NULL is\n * canonical. A list is rewritten member by member, in array order; a non-text\n * member or a non-array carrier aborts like a malformed scalar.\n */\nfunction temporalCarrier(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): { readonly noncanonical: string; readonly canonical: string } {\n const [predicate, expression] =\n type === \"time\"\n ? [sqliteCanonicalTimePredicate, sqliteCanonicalTimeExpression]\n : [sqliteCanonicalDateTimePredicate, sqliteCanonicalDateTimeExpression];\n if (!list) {\n return {\n noncanonical: `NOT ${predicate(column)}`,\n canonical: expression(column),\n };\n }\n const quote = createIdentifierQuoter('\"');\n const name = `${quote(table)}.${quote(column)}`;\n // json_each is reached only after proving an array carrier.\n const array = `json_valid(${name}) AND json_type(${name}) = 'array'`;\n return {\n noncanonical: `CASE WHEN ${name} IS NULL THEN 0 WHEN ${array} THEN EXISTS (SELECT 1 FROM json_each(${name}) WHERE type <> 'text' OR NOT ${predicate(\"value\")}) ELSE 1 END`,\n canonical: `CASE WHEN ${array} THEN (SELECT json_group_array(CASE WHEN \"type\" = 'text' THEN ${expression(\"value\")} ELSE ${SQLITE_ABORT} END) FROM (SELECT \"value\", \"type\" FROM json_each(${name}) ORDER BY \"key\")) ELSE ${SQLITE_ABORT} END`,\n };\n}\n\n/** Counts one text DateTime/Time column's rows outside the canonical carrier. */\nexport function sqliteNoncanonicalTemporalCount(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const { noncanonical } = temporalCarrier(table, column, type, list);\n return `SELECT count(*) AS noncanonical FROM ${createIdentifierQuoter('\"')(table)} WHERE ${noncanonical}`;\n}\n\n/** Rewrites one column's noncanonical rows into canonical text; a malformed value aborts the statement. */\nexport function sqliteCanonicalTemporalUpdate(\n table: string,\n column: string,\n type: TemporalType,\n list: boolean\n): string {\n const quote = createIdentifierQuoter('\"');\n const { noncanonical, canonical } = temporalCarrier(\n table,\n column,\n type,\n list\n );\n return `UPDATE ${quote(table)} SET ${quote(column)} = ${canonical} WHERE ${noncanonical}`;\n}\n","/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","import { isSqliteStateControlDefinition } from \"../../control\";\n/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport { BATCH_REFS_TABLE } from \"@adapters/shared/batch-refs\";\nimport {\n sqliteDefinitionKeywords,\n sqliteTableDefinitions,\n} from \"../../../adapters/databases/sqlite/storage/column-constraints\";\nimport { readSqliteDecimalConstraint } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n readSqliteGeoPointColumn,\n SQLITE_GEO_POINT_TYPE,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { skipSqlNonStructuralRegion } from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport type { SqliteMigrationCapability } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { RAW_INDEX_MARKER_PREFIX, readRawIndexMarker } from \"../../raw-index\";\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { mapReferentialAction } from \"../utils\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteInt,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * A pragma's integer column, as a number.\n *\n * SQLite reports integers, but the driver decides how they arrive: the LibSQL\n * driver runs with `intMode: \"bigint\"` (`src/drivers/libsql/index.ts`), so every\n * pragma integer reaches this file as BigInt. Read raw, each one is wrong in a\n * different way — `1n === 1` is false, so a unique index reads as non-unique\n * and a NOT NULL column reads as nullable; and `a.seqno - b.seqno` yields a\n * BigInt that `Array#sort` refuses outright, which crashes the introspection of\n * any index over two or more columns. Normalizing here, once, is what lets the\n * rest of this file compare plain numbers.\n */\nfunction int(value: SqliteInt): number {\n return Number(value);\n}\n\n/** The predicate half of a stored `CREATE INDEX … WHERE …`, if there is one. */\nconst TRAILING_WHERE = /^WHERE\\s+([\\s\\S]+)$/i;\n/** The defaults SQLite's column grammar takes without parentheses. */\n// Identifiers include NULL, TRUE, FALSE and CURRENT_*, and SQLite reads a\n// bare or double-quoted one in a default as a string literal.\nconst LITERAL_DEFAULT =\n /^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|0x[\\da-f]+|'(?:[^']|'')*'|x'[\\da-f]*'|\"(?:[^\"]|\"\")*\"|[a-z_][\\w$]*)$/i;\n\n/**\n * A column's default as DDL. `PRAGMA table_info` reports `DEFAULT (expr)`\n * without its parentheses, and an expression is a legal default only inside\n * them: a table recreation that wrote `strftime(...)` back verbatim (an\n * `s.dateTime().now()` column) was a `CREATE TABLE` SQLite refused.\n */\nfunction columnDefault(value: string | null): string | undefined {\n if (value === null) return;\n return LITERAL_DEFAULT.test(value) ? value : `(${value})`;\n}\nconst AUTOINCREMENT = /\\bAUTOINCREMENT\\b/i;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The CHECK the SQLite driver embeds in an enum column type.\n *\n * `PRAGMA table_info` reports only `TEXT`. The values live in\n * `sqlite_master.sql` as `CHECK(\"col\" IN ('a', 'b'))`, which is the same\n * spelling `getEnumColumnType` writes into the desired snapshot. Reconstruct\n * that suffix so fingerprint and differ see one type.\n */\nfunction sqliteEnumCheckSuffix(\n tableSql: string | null,\n columnName: string\n): string | undefined {\n if (!tableSql) return;\n const quoted = escapeIdentifier(columnName);\n const match = tableSql.match(\n new RegExp(\n `CHECK\\\\(\\\\s*${escapeRegExp(quoted)}\\\\s+IN\\\\s*\\\\((\\\\s*(?:'(?:[^']|'')*'\\\\s*,\\\\s*)*'(?:[^']|'')*'\\\\s*)\\\\)\\\\s*\\\\)`,\n \"i\"\n )\n );\n const list = match?.[1];\n if (!list) return;\n const values: string[] = [];\n const literals = /'((?:[^']|'')*)'/g;\n let literal = literals.exec(list);\n while (literal) {\n const value = literal[1];\n if (value !== undefined) values.push(value.replace(/''/g, \"'\"));\n literal = literals.exec(list);\n }\n if (values.length === 0) return;\n const escaped = values\n .map((value) => `'${value.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return ` CHECK(${quoted} IN (${escaped}))`;\n}\n\n/**\n * Reads the predicate of a partial index back out of the text SQLite stored.\n *\n * SQLite keeps `sqlite_master.sql` as the statement was written and re-spells\n * nothing (measured on 3.51: the predicate, its inner spacing and its padding\n * all come back byte-identical; only the statement terminator is dropped), so\n * the predicate the differ compares is the one the serializer emitted. This\n * reads it out and does not normalize it — `indexesEqual` is the one place the\n * two snapshot producers' spellings are reconciled.\n *\n * The predicate is whatever follows the column list, not whatever follows the\n * first `WHERE` in the text: a column may be named `a WHERE b`. So walk the\n * statement to the parenthesis that closes the column list, skipping quoted\n * identifiers and string literals, and read the tail from there.\n */\n/** The marker `generateCreateIndex` ends a raw index's text with. */\nconst RAW_INDEX_TRAILER = new RegExp(\n String.raw`/\\* ${RAW_INDEX_MARKER_PREFIX}(\\{[^\\n]*\\}) \\*/\\s*$`\n);\n\n/** The raw index an index's stored text marks, when VibORM wrote it for this index. */\nfunction sqliteRawIndex(\n sql: string | null,\n name: string\n): IndexDef | undefined {\n const marker = sql === null ? undefined : RAW_INDEX_TRAILER.exec(sql)?.[1];\n return marker === undefined ? undefined : readRawIndexMarker(marker, name);\n}\n\nfunction partialIndexPredicate(sql: string | null): string | undefined {\n if (!sql) return undefined;\n\n let depth = 0;\n let cursor = 0;\n let columnListEnd = -1;\n\n while (cursor < sql.length) {\n // Quoted tokens and comments are skipped through the ONE owner of where a\n // non-structural SQLite region ends, shared with the reserved decimal-\n // constraint reader: both read text SQLite stored verbatim, and both are\n // wrong the same way if its contents are read as syntax.\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n\n const char = sql[cursor];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) {\n columnListEnd = cursor;\n break;\n }\n }\n cursor++;\n }\n\n if (columnListEnd === -1) return undefined;\n\n const match = TRAILING_WHERE.exec(sql.slice(columnListEnd + 1).trimStart());\n return match?.[1];\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\n/** `CREATE TABLE … (…) WITHOUT ROWID`: the two words at the statement's top level. */\nfunction isWithoutRowid(sql: string): boolean {\n const words = sqliteDefinitionKeywords(sql);\n return words.some(\n (word, index) => word === \"WITHOUT\" && words[index + 1] === \"ROWID\"\n );\n}\n\n/**\n * What a stored `CREATE TABLE` declares beyond the snapshot's vocabulary and\n * that changes how the table behaves: `STRICT` typing, an `ON CONFLICT`\n * resolution on a key or NOT NULL (`REPLACE` overwrites a row a create would\n * have refused), and a column collation other than BINARY, which the\n * declaration never writes. A quoted collation name is not read, so it counts.\n * An indexed column's collation is refused by every reader already (V8001),\n * and a CHECK by introspection (V11009).\n */\nexport function sqliteTableHazards(sql: string): string[] {\n const hazards: string[] = [];\n if (sqliteDefinitionKeywords(sql).includes(\"STRICT\")) hazards.push(\"STRICT\");\n for (const { text, columnName } of sqliteTableDefinitions(sql)) {\n const words = sqliteDefinitionKeywords(text);\n const where =\n columnName === undefined\n ? \"a table constraint\"\n : `column \"${columnName}\"`;\n if (words.some((word, i) => word === \"ON\" && words[i + 1] === \"CONFLICT\"))\n hazards.push(`ON CONFLICT on ${where}`);\n if (\n words.some((word, i) => word === \"COLLATE\" && words[i + 1] !== \"BINARY\")\n )\n hazards.push(`a collation on ${where}`);\n }\n return hazards;\n}\n\n/**\n * Whether a column holds NULL. `PRAGMA table_info` reports what was declared,\n * and SQLite enforces more only in two places: a WITHOUT ROWID key, which it\n * already reports as `notnull = 1`, and the rowid alias — a rowid table's\n * one-column INTEGER key, the only key with no backing `pk` index (the\n * `INTEGER PRIMARY KEY DESC` quirk has one, and holds NULL). Any other key\n * column of a rowid table accepts NULL unless it is declared NOT NULL.\n */\nexport function sqliteColumnNullable(\n notnull: number,\n pk: number,\n keyIndexed: boolean\n): boolean {\n return notnull === 0 && (pk === 0 || keyIndexed);\n}\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n managedTables?: readonly string[],\n reservedTablePrefixes: SqliteMigrationCapability[\"reservedTablePrefixes\"] = \"none\"\n): Promise<SchemaSnapshot> {\n // Get all tables. `sql` rides along on the query that was already being made\n // — the reserved decimal constraints are read out of it, and a second live\n // read for them would be a raw-execution call site the architecture census\n // pins per file. The engine's batch reference scratch is not part of the\n // user's schema: it is TEMP where the transport admits temporary objects and\n // never appears here, but on D1 it is an ordinary table in `main`, and a\n // snapshot that carried it would have push and diff plan its drop.\n // Cloudflare (D1, Durable Objects) owns the `_cf_` tables and forbids their\n // PRAGMAs. Filter that exact prefix only where the driver's capability\n // reserves it; GLOB treats `_` literally, and an ordinary SQLite\n // application's similarly named tables stay visible.\n const tablesResult = await executeRaw<SqliteTable>(\n `\n SELECT name, sql\n FROM sqlite_master\n WHERE type = 'table'\n AND name NOT LIKE 'sqlite_%'\n AND name <> ?\n ${reservedTablePrefixes === \"_cf_\" ? \"AND name NOT GLOB '_cf_*'\" : \"\"}\n ORDER BY name\n `,\n [BATCH_REFS_TABLE]\n );\n\n const tables: TableDef[] = [];\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.name;\n\n const selected =\n managedTables === undefined || managedTables.includes(tableName);\n const definitions = sqliteTableDefinitions(tableRow.sql ?? \"\");\n if (\n selected &&\n definitions.some((definition) =>\n sqliteDefinitionKeywords(definition.text).includes(\"AS\")\n )\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"generated columns\" } }\n );\n if (\n selected &&\n sqliteDefinitionKeywords((tableRow.sql ?? \"\").split(\"(\")[0]!).includes(\n \"VIRTUAL\"\n )\n )\n throw new MigrationError(\n `SQLite virtual table \"${tableName}\" cannot be faithfully reconstructed. Synchronization refuses before effects.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"virtual table\" } }\n );\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n const tableSql = tableRow.sql;\n const hasAutoincrement = AUTOINCREMENT.test(tableSql ?? \"\");\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n const keyIndexed = indexesResult.rows.some(({ origin }) => origin === \"pk\");\n\n // The pragma reports that an index is partial but not what its predicate\n // is; only the stored statement carries that.\n const indexSqlResult = await executeRaw<{\n name: string;\n sql: string | null;\n }>(\n \"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?\",\n [tableName]\n );\n const indexSql = new Map(\n indexSqlResult.rows.map((row) => [row.name, row.sql])\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n const pk = int(col.pk);\n const type = col.type || \"TEXT\";\n const nullable = sqliteColumnNullable(int(col.notnull), pk, keyIndexed);\n const geoPointEncoding = readSqliteGeoPointColumn(\n tableSql,\n { name: col.name, type, nullable },\n escapeIdentifier\n );\n columns.push({\n name: col.name,\n geoPointEncoding,\n type: geoPointEncoding\n ? SQLITE_GEO_POINT_TYPE\n : `${type}${sqliteEnumCheckSuffix(tableSql, col.name) ?? \"\"}`,\n nullable,\n default: columnDefault(col.dflt_value),\n autoIncrement: pk === 1 && hasAutoincrement,\n // The declared domain, recovered from the reserved CHECK constraint\n // the driver wrote. Nothing else on this dialect carries it: the type\n // is `INTEGER` (or `TEXT`) at every precision and scale, and the\n // pragma reports no constraints at all — so a side that could not\n // recover it would read as a change on every push, forever.\n decimal: readSqliteDecimalConstraint(\n tableSql,\n // The descriptor proof consumes the exact declared type PRAGMA\n // reported. The generic snapshot fallback above may call an untyped\n // column TEXT, but that normalization cannot turn BLOB affinity into\n // the writer-owned TEXT decimal-list carrier.\n { name: col.name, type: col.type, nullable },\n escapeIdentifier\n ),\n });\n\n if (pk > 0) {\n pkColumns.push({ name: col.name, position: pk });\n }\n }\n\n if (selected) {\n const checks = definitions.reduce(\n (count, definition) =>\n count +\n sqliteDefinitionKeywords(definition.text).filter(\n (word) => word === \"CHECK\"\n ).length,\n 0\n );\n const represented = columns.reduce(\n (count, column) =>\n count +\n Number(column.decimal !== undefined) +\n Number(column.geoPointEncoding !== undefined) +\n Number(sqliteEnumCheckSuffix(tableSql, column.name) !== undefined),\n 0\n );\n if (\n checks !== represented &&\n !isSqliteStateControlDefinition(tableName, tableSql)\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"CHECK constraints\" } }\n );\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n // The table's options follow its definitions, outside any paren.\n ...(isWithoutRowid(tableSql ?? \"\") ? { withoutRowid: true } : {}),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // A raw index is its marker, whatever its key semantics are.\n const raw = sqliteRawIndex(indexSql.get(idx.name) ?? null, idx.name);\n if (raw) {\n indexes.push(raw);\n continue;\n }\n // xinfo exposes the physical key semantics that index_info erases.\n // Auxiliary rowid columns are not key members; user expressions, DESC\n // and collations cannot be faithfully recreated by this declaration DSL.\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_xinfo(${escapeIdentifier(idx.name)})`\n );\n const keys = indexColsResult.rows.filter(\n (column) => int(column.key) === 1\n );\n const unsupported =\n keys.length === 0 ||\n keys.some(\n (column) =>\n int(column.cid) < 0 ||\n column.name === null ||\n int(column.desc) !== 0 ||\n column.coll !== \"BINARY\"\n );\n if (unsupported) {\n if (managedTables === undefined || managedTables.includes(tableName)) {\n throw new MigrationError(\n `SQLite index \"${tableName}.${idx.name}\" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Declare it with .rawIndex() (drop this hand-made copy first: only an index VibORM created carries the marker it recognizes), or manage its table outside this synchronization scope.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName: idx.name } }\n );\n }\n continue;\n }\n // PK membership is already represented by the table's primary key.\n if (idx.origin === \"pk\") continue;\n const indexColumns = keys\n .sort((a, b) => int(a.seqno) - int(b.seqno))\n .flatMap((column) => (column.name === null ? [] : [column.name]));\n\n const unique = int(idx.unique) === 1;\n if (unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique,\n where: partialIndexPredicate(indexSql.get(idx.name) ?? null),\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const id = int(fk.id);\n const existing = fkMap.get(id) || [];\n existing.push(fk);\n fkMap.set(id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => int(a.seq) - int(b.seq));\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [] };\n}\n","import { selectManagedSnapshot } from \"./target\";\n/**\n * Model-to-SchemaSnapshot Serializer\n *\n * Converts VibORM model definitions into a database-agnostic SchemaSnapshot\n * that can be compared with the current database state.\n *\n * Database-specific logic is delegated to the MigrationDriver:\n * - Type mapping (mapScalarType)\n * - Default expressions (getDefaultExpression)\n * - Enum handling (capabilities.supportsNativeEnums, getEnumColumnType)\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport { lightModels } from \"../schema/json/light\";\nimport {\n type AnyModel,\n getModelKeyCatalog,\n getTableName as getModelTableName,\n isTotalIndex,\n type ModelState,\n} from \"../schema/model\";\nimport type { RelationSlot } from \"../schema/relation\";\nimport { automaticForeignKeyIndexName } from \"../schema/relation/helpers\";\nimport type { Scalar } from \"../schema/scalars/base\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"../schema/scalars/decimal/provider-limits\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedRelationEdge,\n type ResolvedRelationIndex,\n type ResolvedVariantJunctionEdge,\n type ResolvedVariantJunctionMember,\n type ResolvedVariantRowEdge,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { declaredRawIndex, RAW_INDEX_TEMPLATE_KEY } from \"./raw-index\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\n\n// =============================================================================\n// SERIALIZER\n// =============================================================================\n\nexport interface SerializeOptions {\n migrationDriver: MigrationDriver;\n}\n\n/** Translate the shared pure refusal into the migration boundary's error. */\nexport function assertMigrationDecimalDomainsFitProvider(\n models: Record<string, AnyModel>,\n dialect: Dialect\n): void {\n const refusal = findDecimalProviderLimitRefusal(models, dialect);\n if (refusal === undefined) return;\n throw new MigrationError(\n describeDecimalProviderLimitRefusal(refusal),\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/** One model's edges, bucketed at their anchors in declaration order. */\ninterface ModelEdges {\n readonly variants: ResolvedVariantEdgeRef[];\n readonly foreignKeys: ResolvedForeignKeyEdge[];\n}\n\ntype ResolvedVariantEdgeRef =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\ntype ResolvedForeignKeyEdge = Extract<\n ResolvedRelationEdge,\n { kind: \"foreignKey\" }\n>;\ntype ResolvedJunctionEdge = Extract<ResolvedRelationEdge, { kind: \"junction\" }>;\n\n/**\n * Stage the ONE derived edge iterator into the two emission buckets the\n * serializer already had (D4): per-model variant storage and foreign keys for\n * the model phase, and ordinary junctions for the phase that follows it.\n *\n * `resolvedEdges` yields each edge exactly once, at its canonical anchor, in\n * schema/model/field order — which is the order both phases already walked. No\n * topology is stored here and none is re-expanded (§11.5.9).\n */\nfunction stageEdges(index: ResolvedRelationIndex): {\n readonly byModel: ReadonlyMap<AnyModel, ModelEdges>;\n readonly junctions: readonly ResolvedJunctionEdge[];\n} {\n const byModel = new Map<AnyModel, ModelEdges>();\n const junctions: ResolvedJunctionEdge[] = [];\n const bucket = (model: AnyModel): ModelEdges => {\n const held = byModel.get(model);\n if (held) return held;\n const created: ModelEdges = { variants: [], foreignKeys: [] };\n byModel.set(model, created);\n return created;\n };\n for (const edge of resolvedEdges(index)) {\n if (edge.kind === \"junction\") {\n // A declared model's table is that model's: the loop over models owns it,\n // and each side's foreign key arrives as its own edge below.\n if (!edge.topology.declared) junctions.push(edge);\n continue;\n }\n if (edge.kind === \"foreignKey\") {\n bucket(edge.owner.source).foreignKeys.push(edge);\n continue;\n }\n bucket(edge.carrier.source).variants.push(edge);\n }\n return { byModel, junctions };\n}\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nfunction isSlot(one: RelationSlot, other: RelationSlot): boolean {\n return one.source === other.source && one.field === other.field;\n}\n\n/** The endpoint an ordinary edge reaches FROM the given one. */\nfunction partnerOf(\n edge: ResolvedForeignKeyEdge | ResolvedJunctionEdge,\n from: RelationSlot\n): RelationSlot {\n const [first, second] = edge.endpoints;\n return isSlot(first, from) ? second : first;\n}\n\n/**\n * Serializes a collection of VibORM models into a SchemaSnapshot\n */\nexport function serializeModels(\n models: Record<string, AnyModel>,\n options: SerializeOptions\n): SchemaSnapshot {\n hydrateSchemaNames(models);\n assertMigrationDecimalDomainsFitProvider(\n models,\n options.migrationDriver.dialect\n );\n return serializeResolvedModels(\n models,\n options.migrationDriver,\n resolveSchemaOrThrow(models)\n );\n}\n\n/** Internal composition seam for a boundary that already owns resolution. */\nexport function serializeResolvedModels(\n models: Record<string, AnyModel>,\n migrationDriver: MigrationDriver,\n index: ResolvedRelationIndex\n): SchemaSnapshot {\n const { byModel, junctions } = stageEdges(index);\n const tables: TableDef[] = [];\n const enums: EnumDef[] = [];\n const enumsSet = new Set<string>();\n const polymorphicStorage: PolymorphicSnapshotStorage[] = [];\n // One registry for EVERY junction-shaped table — polymorphic member\n // junctions (registered by the model loop below, model iteration order then\n // member declaration order) and ordinary many-to-many junctions (registered\n // by the walk that follows) — so the \"one table name, one definition\"\n // invariant covers both routes through the same map.\n const junctionTables = new Map<string, { def: TableDef; pairKey: string }>();\n\n for (const [modelName, model] of Object.entries(models)) {\n // Every migration path states its schema here, so this is the one refusal.\n if (lightModels.has(model))\n throw new MigrationError(\n `Model \"${modelName}\" comes from a light schema document, which leaves out the indexes a migration keeps: a push or a migration of it would drop them. Introspect the database without \\`light\\` to migrate.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n const modelState = model[\"~\"].state;\n const tableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n\n const columns: ColumnDef[] = [];\n const indexes: IndexDef[] = [];\n const foreignKeys: ForeignKeyDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const relationStorage: Record<\n string,\n PolymorphicToOneStorageRegistryEntry\n > = {};\n let primaryKey: PrimaryKeyDef | undefined;\n const pkColumns: string[] = [];\n\n // Process scalars\n for (const [fieldName, scalar] of Object.entries<Scalar>(\n modelState.scalars\n )) {\n const scalarState = scalar[\"~\"].state;\n // Use model's nameRegistry for column name resolution (supports field reuse)\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n\n // Handle enum types (only for databases that support native enums)\n let columnType: string;\n // The LIST representation is decided before enum identity is spelled. A\n // dialect with native arrays keeps both — `enumname[]` — while the others\n // store the list in the same container every other list uses, where an\n // element type has no expression at all: an inline `ENUM(...)` or a\n // `TEXT CHECK(col IN ...)` describes ONE member, so spelling it for a\n // list produces a column that refuses every value the field can hold.\n const spellsEnumColumn =\n scalarState.type === \"enum\" &&\n (scalarState.array !== true ||\n migrationDriver.capabilities.supportsNativeArrays);\n if (spellsEnumColumn) {\n const enumScalar = scalar as any;\n const enumValues = enumScalar.enumValues as string[] | undefined;\n\n if (migrationDriver.capabilities.supportsNativeEnums && enumValues) {\n // Use explicit enum name if provided, otherwise auto-generate\n const enumName =\n scalarState.enumName && migrationDriver.dialect === \"postgresql\"\n ? scalarState.enumName\n : migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues\n );\n\n const previousEnum = enums.find((item) => item.name === enumName);\n if (\n previousEnum &&\n JSON.stringify(previousEnum.values) !== JSON.stringify(enumValues)\n )\n throw new MigrationError(\n `Enum type \"${enumName}\" is declared with incompatible values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (!enumsSet.has(enumName)) {\n enums.push({\n name: enumName,\n values: enumValues,\n });\n enumsSet.add(enumName);\n }\n columnType = scalarState.array ? `${enumName}[]` : enumName;\n } else {\n // Fall back to driver's default enum column type\n columnType = migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues || []\n );\n }\n } else {\n // A foreign key's identifier domain is DERIVED from the key it\n // references, so it is read against the model through the same\n // resolved index this serialization is already built from.\n columnType = migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, fieldName, index)\n );\n }\n\n const columnDef: ColumnDef = {\n name: columnName,\n type: columnType,\n nullable: scalarState.nullable,\n default: migrationDriver.getDefaultExpression(scalar, scalarState),\n autoIncrement: scalarState.autoGenerate?.kind === \"increment\",\n // Carried by REFERENCE off the resolved scalar, never rebuilt: the\n // frozen descriptor is the one source of truth, and the physical type\n // above is derived from it. On SQLite that type is `INTEGER` or `TEXT`\n // whatever the domain is, so without this the differ would see no\n // change when the domain moved.\n decimal: scalarState.decimal,\n geoPointEncoding:\n migrationDriver.dialect === \"sqlite\" && scalarState.type === \"point\"\n ? \"binary64\"\n : undefined,\n dateTime:\n migrationDriver.dialect === \"sqlite\" &&\n scalarState.type === \"datetime\" &&\n scalarState.array !== true\n ? sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType)\n : undefined,\n };\n\n columns.push(columnDef);\n\n // Track primary key columns\n if (scalarState.isId) {\n pkColumns.push(columnName);\n }\n\n // Handle unique constraints on individual fields\n if (scalarState.isUnique && !scalarState.isId) {\n uniqueConstraints.push({\n name: `${tableName}_${columnName}_key`,\n columns: [columnName],\n });\n }\n }\n\n // Handle compound primary key\n if (modelState.compoundId) {\n const firstKey = Object.keys(modelState.compoundId)[0];\n const compoundIdSchema = firstKey\n ? modelState.compoundId[firstKey]\n : undefined;\n if (compoundIdSchema?.entries) {\n pkColumns.push(\n ...Object.keys(compoundIdSchema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n )\n );\n }\n }\n\n // Set primary key. `WITHOUT ROWID` is SQLite's alone, and SQLite's\n // AUTOINCREMENT is a rowid's: the pair is refused here, before any\n // migration names the table, and never on a dialect that ignores it.\n const withoutRowid =\n model[\"~\"].withoutRowid && migrationDriver.dialect === \"sqlite\";\n const incremented = columns.find((column) => column.autoIncrement);\n if (withoutRowid && incremented)\n throw new MigrationError(\n `\"${modelName}\" is declared withoutRowid, and its ID \"${incremented.name}\" uses .increment(): SQLite's AUTOINCREMENT needs a rowid`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, field: incremented.name } }\n );\n // A model without an ID (M001, refused by validation unless the caller\n // skipped it) has no key to cluster on: the option would be dropped.\n if (withoutRowid && pkColumns.length === 0)\n throw new MigrationError(\n `\"${modelName}\" is declared withoutRowid and has no ID: SQLite's WITHOUT ROWID needs a primary key`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName } }\n );\n // F006 refuses a nullable key member on the validated path; this is the\n // one for `skipValidation`, which would publish a column every dialect\n // builds NOT NULL, so every later proof of the state would refuse it.\n const nullableKey = columns.find(\n (column) => column.nullable && pkColumns.includes(column.name)\n );\n if (nullableKey)\n throw new MigrationError(\n `\"${modelName}.${nullableKey.name}\" is nullable and a member of the ID: every database builds a primary-key column NOT NULL`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, field: nullableKey.name } }\n );\n if (pkColumns.length > 0) {\n primaryKey = {\n columns: pkColumns,\n name: `${tableName}_pkey`,\n ...(withoutRowid ? { withoutRowid: true as const } : {}),\n };\n }\n\n // Handle compound unique constraints\n const compoundUniques: ModelState[\"compoundUniques\"] =\n modelState.compoundUniques;\n if (compoundUniques) {\n for (const [constraintName, schema] of Object.entries(compoundUniques)) {\n if (schema?.entries) {\n uniqueConstraints.push({\n name: `${tableName}_${constraintName}_key`,\n columns: Object.keys(schema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n ),\n });\n }\n }\n }\n\n // Process indexes from model state\n const declaredIndexColumns: string[][] = [];\n for (const indexDef of modelState.indexes) {\n const indexName =\n indexDef.options.name ||\n `${tableName}_${indexDef.fields.join(\"_\")}_idx`;\n // `.map()` renames the column, so the DDL has to name the column and not\n // the TypeScript field — the same resolution the compound uniques and the\n // FK columns already do. One resolution serves both readers: the CREATE\n // INDEX below, and the foreign-key index's coverage decision, which has\n // to compare the same names or it emits a duplicate index.\n const columns = indexDef.fields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const declared: IndexDef = {\n name: indexName,\n columns,\n unique: indexDef.options.unique ?? false,\n type: indexDef.options.type,\n where: indexDef.options.where,\n };\n indexes.push(declared);\n if (isTotalIndex(declared)) {\n declaredIndexColumns.push(columns);\n }\n }\n\n // A raw index is never a key and never covers a foreign key: its text may\n // index an expression of the columns it names, or not in their order. It is\n // listed before the foreign-key indexes so that an automatic one yields\n // its name to it. A dialect it has no text for has no such index.\n const templateKey = RAW_INDEX_TEMPLATE_KEY[migrationDriver.dialect];\n for (const rawIndex of model[\"~\"].rawIndexes) {\n const template = templateKey && rawIndex.templates[templateKey];\n if (template === undefined) continue;\n // I002 sees explicit names only; an `.index()` without one takes its\n // name here, and two indexes under one name fail the second CREATE.\n if (indexes.some(({ name }) => name === rawIndex.name))\n throw new MigrationError(\n `The raw index \"${modelName}.${rawIndex.name}\" has the name of another index of \"${modelName}\": give one of them another name.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { model: modelName, indexName: rawIndex.name } }\n );\n indexes.push(\n declaredRawIndex(\n modelName,\n rawIndex.name,\n template,\n migrationDriver.dialect,\n (field) =>\n Object.hasOwn(modelState.scalars, field)\n ? model[\"~\"].getFieldName(field).sql\n : undefined\n )\n );\n }\n\n // Variant storage is relation-owned, so it never appears in the public\n // scalar map. The RESOLVED CARRIER EDGE is the single source for the\n // row-held private columns and index, the collection member junction\n // tables, and generated-file member history.\n const modelEdges = byModel.get(model) ?? { variants: [], foreignKeys: [] };\n for (const edge of modelEdges.variants) {\n if (edge.kind === \"variantJunctionCarrier\") {\n const members: PolymorphicToManySnapshotMember[] = [];\n for (const member of edge.members) {\n const memberDef = serializeMemberJunction(\n model,\n tableName,\n member,\n migrationDriver,\n index\n );\n // pairName is always set for a member junction: the resolved topology\n // is built exclusively by the gate, which passes\n // `${model}.${relation}.${publicType}` — already distinct from every\n // ordinary pairKey spelling.\n const pairKey = member.topology.pairName!;\n const existing = junctionTables.get(memberDef.name);\n if (\n existing &&\n (existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(memberDef))\n ) {\n throw new Error(\n `Junction table \"${memberDef.name}\" is shared by multiple distinct relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n if (!existing) {\n junctionTables.set(memberDef.name, { def: memberDef, pairKey });\n }\n\n const memberTarget = member.topology.target.model;\n const targetModelName = memberTarget[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n memberTarget,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n memberJunctionTable: member.topology.table,\n inverseCardinality: member.uniqueTarget ? \"one\" : \"many\",\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toMany\",\n members,\n });\n continue;\n }\n const storage = edge.storage;\n const typeScalarState = storage.typeColumn.scalar[\"~\"].state;\n const idScalarState = storage.idColumn.scalar[\"~\"].state;\n columns.push(\n {\n name: storage.typeColumn.name,\n type: migrationDriver.mapScalarType(\n storage.typeColumn.scalar,\n typeScalarState\n ),\n nullable: storage.typeColumn.nullable,\n },\n {\n name: storage.idColumn.name,\n // The carrier's id column holds every variant's KEY, and a key's\n // domain may be DERIVED, so the column names the key it stands in for\n // and that key is resolved against the index. Every variant agrees on\n // the answer or this storage does not exist (P002).\n type: migrationDriver.mapScalarType(\n storage.idColumn.scalar,\n idScalarState,\n storage.idColumn.reference === undefined\n ? undefined\n : idDomainOf(\n storage.idColumn.reference.model,\n storage.idColumn.reference.field,\n index\n )\n ),\n nullable: storage.idColumn.nullable,\n }\n );\n indexes.push({\n name: storage.indexName,\n columns: [storage.typeColumn.name, storage.idColumn.name],\n unique: edge.uniqueTarget,\n });\n // The physical facts stay in the TableDef above where the structural\n // differ owns them; the registry annotates which of those parts are\n // relation-owned, keyed by the storage ref the metadata entry carries.\n relationStorage[storage.typeColumn.name] = {\n kind: \"polymorphicToOne\",\n typeColumn: storage.typeColumn.name,\n idColumn: storage.idColumn.name,\n index: storage.indexName,\n };\n\n const members: PolymorphicToOneSnapshotMember[] = [];\n for (const member of edge.members) {\n const targetModelName = member.targetModel[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n member.targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toOne\",\n storageRef: storage.typeColumn.name,\n members,\n });\n }\n\n // A UNIQUE foreign key gets a unique constraint at the bottom of the\n // relation loop, and that constraint is an index — so it covers the\n // foreign-key index exactly as a declared unique does. It is collected HERE,\n // before the loop, because `uniqueConstraints` grows INSIDE it: one model may\n // name the same columns from a plural and from a singular edge (legal, and\n // measured through `serializeModels`), and reading the half-built list made\n // the answer depend on which relation the schema happened to spell first —\n // `many` before `one` emitted the redundant index, `one` before `many` did\n // not. The condition mirrors the branch that pushes the constraint, so this\n // claims coverage only where the constraint follows.\n const oneToOneFkColumns: string[][] = [];\n for (const edge of modelEdges.foreignKeys) {\n if (!edge.unique) continue;\n oneToOneFkColumns.push(\n edge.reference.members.map(\n (member) => model[\"~\"].getFieldName(member.foreignField).sql\n )\n );\n }\n\n // Process foreign keys. ONE edge per stored reference, at its OWNER, in the\n // owner's declaration order — the gate decided which endpoint stores the\n // reference, so there is no family label to test and no inverse to discover.\n for (const edge of modelEdges.foreignKeys) {\n const targetSlot = partnerOf(edge, edge.owner);\n const targetModel = targetSlot.source;\n const targetModelState = targetModel[\"~\"].state;\n const targetTableName =\n targetModel[\"~\"].names.sql ||\n targetModelState.tableName ||\n edge.owner.field.toLowerCase();\n\n // Resolve TS field names to actual column names (.map() support)\n const fkFields = edge.reference.members.map(\n (member) => member.foreignField\n );\n const fkColumns = fkFields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const referencedColumns = edge.reference.members.map(\n (member) => targetModel[\"~\"].getFieldName(member.referencedField).sql\n );\n\n // Prisma parity: without an explicit .onDelete(), a stored reference whose\n // every local member is nullable defaults to SET NULL and a required one to\n // RESTRICT, so deletes behave identically across databases (MySQL checks\n // self-referencing FKs row-by-row where PG/SQLite validate at statement\n // end). The rule has one owner, `foreignKeyOnDelete`, which the engine's\n // referential requirement reads too.\n foreignKeys.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_fkey`,\n columns: fkColumns,\n referencedTable: targetTableName,\n referencedColumns,\n onDelete: foreignKeyOnDelete(edge),\n onUpdate: edge.reference.onUpdate ?? \"noAction\",\n });\n\n // The inverse of a plural stored reference is to-many: every include,\n // relation filter and nested-write locate reads this table through the FK\n // columns. MySQL/InnoDB indexes an FK constraint by itself;\n // PostgreSQL and SQLite do not, so serialize the index on every\n // dialect — one snapshot shape for the differ, and on MySQL the\n // explicit index takes the place of the implicit one. A UNIQUE FK\n // needs nothing here: the unique constraint below is its index.\n if (edge.unique) {\n // 1:1 FK must be unique at the DB level, or it degrades to N:1\n const fkKey = [...fkColumns].sort().join(\",\");\n const alreadyUnique =\n [...pkColumns].sort().join(\",\") === fkKey ||\n uniqueConstraints.some(\n (u) => [...u.columns].sort().join(\",\") === fkKey\n ) ||\n indexes.some(\n (i) =>\n i.unique &&\n isTotalIndex(i) &&\n [...i.columns].sort().join(\",\") === fkKey\n );\n if (!alreadyUnique) {\n uniqueConstraints.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_key`,\n columns: fkColumns,\n });\n }\n continue;\n }\n\n // The primary key, every unique constraint and every declared index\n // is backed by an index on all three dialects, and an index serves\n // any prefix of its columns — so a FK index over such a prefix\n // would only duplicate one the database already has.\n const coveringColumns = [\n pkColumns,\n ...uniqueConstraints.map((unique) => unique.columns),\n ...oneToOneFkColumns,\n ...declaredIndexColumns,\n ];\n const alreadyIndexed = coveringColumns.some((columns) =>\n fkColumns.every((column, position) => columns[position] === column)\n );\n if (alreadyIndexed) continue;\n // An index the schema declares over exactly these columns but\n // does not cover them — a partial index — auto-names itself the\n // way this one does, and a database keeps one index per name. So\n // the automatic index falls back on the name of the constraint it\n // serves. Only a schema that has no foreign-key index today can\n // take the fallback, so no database that already holds the index\n // is renamed into a drop and a create.\n //\n // A schema may of course have spent BOTH names on indexes of its\n // own — `.index([...], { name: \"<table>_<cols>_fkey_idx\" })` is\n // legal. Then this index has no name left to take, and pushing it\n // anyway put two entries under one name into the snapshot: the\n // differ emitted two `CREATE INDEX` and the second failed the\n // whole push (measured on better-sqlite3: `index\n // zz_fb_kid_ownerId_fkey_idx already exists`). The index is a read\n // optimization, not a correctness requirement, so it yields to the\n // names the schema declared.\n const name = automaticForeignKeyIndexName(\n tableName,\n fkColumns,\n new Set(indexes.map((index) => index.name))\n );\n if (name !== undefined) {\n indexes.push({ name, columns: fkColumns, unique: false });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n // Key omitted when empty so ordinary tables keep their exact shape.\n ...(Object.keys(relationStorage).length > 0 ? { relationStorage } : {}),\n });\n }\n\n // ==========================================================================\n // ORDINARY JUNCTION TABLES\n //\n // One edge per resolved pair, at `endpoints[0]` — the canonically first\n // endpoint, which is the very endpoint the old two-model walk registered from.\n // A member VIEW of a variant carrier never appears here: the gate resolved\n // that slot onto its carrier's edge, so the skip that used to rescan for a\n // compatible binding is now structural.\n // ==========================================================================\n for (const edge of junctions) {\n const sourceSlot = edge.endpoints[0];\n const model = sourceSlot.source;\n const modelName = model[\"~\"].names.ts;\n const sourceTableName =\n model[\"~\"].names.sql ||\n model[\"~\"].state.tableName ||\n (modelName ?? \"\").toLowerCase();\n const targetSlot = partnerOf(edge, sourceSlot);\n const targetModel = targetSlot.source;\n const targetModelName = targetModel[\"~\"].names.ts;\n if (!(modelName && targetModelName)) {\n throw new Error(\n `Target model for relation \"${sourceSlot.field}\" has no name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n const targetTableName = targetModel[\"~\"].names.sql;\n if (!targetTableName) {\n throw new Error(\n `Target model \"${targetModelName}\" has no SQL table name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n const sourcePkFields = getPrimaryKeyFieldDefs(\n model,\n migrationDriver,\n index\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n index\n );\n const topology = edge.topology;\n // Decorate the owner's members with the driver-typed key defs by index:\n // the members were zipped from these same row-key lists, so both sides\n // carry exactly one member per key def and the lookup cannot miss.\n const sourceMembers = topology.source.members.map((member, index) => ({\n column: member.junctionField,\n pk: sourcePkFields[index]!,\n }));\n const targetMembers = topology.target.members.map((member, index) => ({\n column: member.junctionField,\n pk: targetPkFields[index]!,\n }));\n\n // Canonical column order: sorted model names decide (as the generated\n // table name does), so both sides serialize the identical table. Each\n // side carries its own foreign key's actions, so the reorder below moves\n // an action with the table and columns it constrains. Prisma parity: an\n // action the owner left unstated is CASCADE, so deleting an endpoint row\n // removes its associations.\n const sourceSide = {\n members: sourceMembers,\n table: sourceTableName,\n sortKey: modelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.source),\n onUpdate: topology.source.onUpdate ?? \"cascade\",\n };\n const targetSide = {\n members: targetMembers,\n table: targetTableName,\n sortKey: targetModelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.target),\n onUpdate: topology.target.onUpdate ?? \"cascade\",\n };\n let [first, second] = [sourceSide, targetSide];\n if (!topology.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map((member) => member.column);\n const secondColumns = second.members.map((member) => member.column);\n\n const junctionDef: TableDef = {\n name: topology.table,\n columns: [\n ...first.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ...second.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers first-side lookups; reverse traversal needs one\n // index over the complete second-side stored reference.\n indexes: [\n {\n name: topology.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map((member) => member.pk.column),\n onDelete: first.onDelete,\n onUpdate: first.onUpdate,\n },\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map((member) => member.pk.column),\n onDelete: second.onDelete,\n onUpdate: second.onUpdate,\n },\n ],\n uniqueConstraints: [],\n };\n\n // Both sides of a pair serialize identically after canonicalization, so\n // a mismatch means two different relation pairs collide on one table.\n // Pair identity (models + relation name) catches collisions even when\n // the column defs happen to be byte-identical.\n const pairKey = `${[first.sortKey, second.sortKey].join(\"::\")}::${\n topology.pairName ?? \"\"\n }`;\n const existing = junctionTables.get(topology.table);\n if (existing) {\n if (\n existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(junctionDef)\n ) {\n throw new Error(\n `Junction table \"${topology.table}\" is shared by multiple distinct many-to-many relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n continue;\n }\n junctionTables.set(topology.table, { def: junctionDef, pairKey });\n }\n\n // Append junction tables to the tables array\n for (const { def } of junctionTables.values()) {\n tables.push(migrationDriver.markJunction?.(def) ?? def);\n }\n\n const snapshot: SchemaSnapshot = {\n tables: tables.map((table) => migrationDriver.finalizeTable(table)),\n enums: enums.length > 0 ? enums : undefined,\n ...(polymorphicStorage.length > 0 ? { polymorphicStorage } : {}),\n };\n return migrationDriver.target\n ? selectManagedSnapshot(snapshot, migrationDriver.target, true)\n : snapshot;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/**\n * Serialize ONE polymorphic collection member's junction table, byte-reusing\n * the ordinary junction template: canonical orientation, driver types zipped\n * BY INDEX against the stored topology's sides, PK without a name, one\n * reverse index when uniqueness does not cover it, and two FIXED-cascade foreign keys —\n * `resolveJunctionPairActions` is NEVER called on this path (member actions\n * are cascade by design; a hostile referential-action spelling never reaches\n * this DDL). Consumes ONLY the stored `ResolvedJunctionTopology`: every\n * physical name comes from the topology's own methods, never reconstructed\n * from naming conventions.\n */\nfunction serializeMemberJunction(\n ownerModel: AnyModel,\n ownerTableName: string,\n member: ResolvedVariantJunctionMember,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): TableDef {\n const junction = member.topology;\n const targetModel = junction.target.model;\n const targetModelName = targetModel[\"~\"].names.ts;\n const targetTableName = getModelTableName(\n targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n );\n const sourcePkFields = getPrimaryKeyFieldDefs(\n ownerModel,\n migrationDriver,\n relations\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n relations\n );\n // Decorate the sides with the driver-typed key defs by index: the stored\n // topology zipped its members from the same model-key-catalog row keys these\n // defs come from, so both lists carry exactly one entry per key def.\n const sourceMembers = junction.source.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: sourcePkFields[index]!,\n })\n );\n const targetMembers = junction.target.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: targetPkFields[index]!,\n })\n );\n\n const sourceSide = { members: sourceMembers, table: ownerTableName };\n const targetSide = { members: targetMembers, table: targetTableName };\n let [first, second] = [sourceSide, targetSide];\n if (!junction.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map(\n (junctionMember) => junctionMember.column\n );\n const secondColumns = second.members.map(\n (junctionMember) => junctionMember.column\n );\n\n return {\n name: junction.table,\n columns: [\n ...first.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ...second.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers the first side. A singular target on the second side has\n // its unique constraint already; otherwise reverse lookup needs an index.\n indexes:\n member.uniqueTarget && junction.sourceIsFirst\n ? []\n : [\n {\n name: junction.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n ],\n // The unique side is the complete ordered TARGET side, NOT the reverse\n // index flipped: when the target sorts canonical-first the reverse index\n // covers the OWNER side, and the PK prefix does not make target columns\n // unique. The name is asked LAST (idx → first fkey → second fkey → key)\n // so the other three refusal positions stay where they are.\n uniqueConstraints: member.uniqueTarget\n ? [\n {\n name: junction.uniqueTargetName(),\n columns: targetMembers.map(\n (junctionMember) => junctionMember.column\n ),\n },\n ]\n : [],\n };\n}\n\n/**\n * Get every primary-key member in model-key order.\n */\nfunction getPrimaryKeyFieldDefs(\n model: AnyModel,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): readonly { field: string; column: string; type: string }[] {\n const modelState = model[\"~\"].state;\n const modelName = model[\"~\"].names.ts;\n const rowKey = getModelKeyCatalog(model).rowKey?.fields;\n if (!rowKey || rowKey.length === 0) {\n throw new Error(\n `Model \"${modelName}\" has no primary key. Schema may not be hydrated.`\n );\n }\n return rowKey.map((field) => {\n const scalar = modelState.scalars[field];\n if (!scalar) {\n throw new Error(\n `Primary-key field '${field}' of model \"${modelName}\" is not a scalar.`\n );\n }\n const scalarState = scalar[\"~\"].state;\n return {\n field,\n column: model[\"~\"].getFieldName(field).sql,\n // A junction column holds the referenced primary KEY's values, and that\n // key's identifier domain may be DERIVED — the one-to-one child whose\n // primary key is its parent foreign key is the ordinary case — so it is\n // read against the model through the same resolved index every other\n // column of this serialization is typed from. Reading the scalar's own\n // declaration types the junction column as text beside the sixteen-byte\n // column it references, which PostgreSQL refuses to key at all.\n type: migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, field, relations)\n ),\n };\n });\n}\n\nexport { getColumnName } from \"../schema/model\";\n\n/**\n * Gets the SQL table name for a model\n */\nexport function getTableName(model: AnyModel, modelName: string): string {\n return getModelTableName(model, modelName.toLowerCase());\n}\n"],"mappings":"i6CAMA,SAAgB,oBACd,EACA,EACA,EACA,EACmC,CACnC,IAAI,EACA,EAA+B,EAAE,CACrC,GAAI,CACoB,OAAO,GAAU,UAAnC,GAA+C,CAAC,MAAM,QAAQ,EAAM,GACtE,EAAc,EACd,EAAO,QAAQ,QAAQ,EAAM,QAExB,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,yBAA0B,EAAW,EAAQ,CAAC,CAEvE,GAAI,CAAC,EAAa,OAAOA,EAAO,GAAG,EAAM,oBAAoB,CAC7D,IAAM,EAAoC,EAAE,CAC5C,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,OAAO,GAAQ,UAAY,CAAC,EAAQ,SAAS,EAAI,CACnD,OAAOA,EAAO,GAAG,EAAM,wBAAwB,OAAO,EAAI,GAAG,CAE/D,GAAI,CACF,EAAS,GAAO,QAAQ,IAAI,EAAa,EAAI,OACtC,EAAS,CAChB,OAAOA,EAAO,GAAG,EAAM,GAAG,EAAI,oBAAqB,EAAW,EAAQ,CAAC,EAG3E,OAAO,OAAO,OAAO,EAAS,CAGhC,SAAgB,mBACd,EACA,EACA,EACoB,CACpB,IAAI,EACJ,GAAI,CACE,MAAM,QAAQ,EAAM,GAAE,EAAU,MAAM,KAAK,EAAM,QAC9C,EAAS,CAChB,OAA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