viborm 1.4.0 → 1.4.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.
- package/dist/{adapter-namespace-BLejG8FA.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
- package/dist/{adapter-namespace-BLejG8FA.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/builder-BxCr9ANq.mjs +2 -0
- package/dist/builder-BxCr9ANq.mjs.map +1 -0
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{chain-D5J9hIw-.mjs → chain-C4EUyLzF.mjs} +2 -2
- package/dist/{chain-D5J9hIw-.mjs.map → chain-C4EUyLzF.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-BzgBm_86.d.mts → client-D-XiaClb.d.mts} +1 -1
- package/dist/client-DACEO6tS.mjs +2 -0
- package/dist/client-DACEO6tS.mjs.map +1 -0
- package/dist/{client-aU3YhZ6G.mjs → client-sAey5P-I.mjs} +2 -2
- package/dist/{client-aU3YhZ6G.mjs.map → client-sAey5P-I.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/current-C2fZL9Ln.mjs +2 -0
- package/dist/current-C2fZL9Ln.mjs.map +1 -0
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{datetime-physical-codec-lX7IJBlz.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
- package/dist/{datetime-physical-codec-lX7IJBlz.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
- package/dist/{driver-u2qJicrE.mjs → driver-BqD-3_jO.mjs} +2 -2
- package/dist/{driver-u2qJicrE.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
- package/dist/driver-DseQwbsu.mjs +2 -0
- package/dist/driver-DseQwbsu.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/every-CEQMQEdt.mjs +2 -0
- package/dist/{every-CzF00eDV.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
- package/dist/execution-context-asSCmyas.mjs +2 -0
- package/dist/execution-context-asSCmyas.mjs.map +1 -0
- package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
- package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
- package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
- package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
- package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
- package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
- package/dist/{identifier-conversion-Dc0Rf4Gi.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
- package/dist/{identifier-conversion-Dc0Rf4Gi.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
- package/dist/{index-B4IWFJfv.d.mts → index-Ci8b13Lm.d.mts} +52 -6
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
- package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
- package/dist/{libsql-CrDXsfpL.mjs → libsql-DPrXWc_J.mjs} +2 -2
- package/dist/{libsql-CrDXsfpL.mjs.map → libsql-DPrXWc_J.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/{memory-TXO4KgBy.mjs → memory-DiTWROVS.mjs} +2 -2
- package/dist/{memory-TXO4KgBy.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-adapter-C5CMIYRS.mjs → mysql-adapter-B1U35CJn.mjs} +2 -2
- package/dist/{mysql-adapter-C5CMIYRS.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
- package/dist/{mysql-C2vOPcuA.mjs → mysql-fJlFIW7m.mjs} +2 -2
- package/dist/{mysql-C2vOPcuA.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-uRqi0URP.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
- package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-SzkGh-3T.d.mts → planner-CUcPdJwD.d.mts} +1 -1
- package/dist/{postgres-BSmy1PYR.mjs → postgres-DD92WdFu.mjs} +2 -2
- package/dist/{postgres-BSmy1PYR.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
- package/dist/{postgres-adapter-BAqRfWl1.mjs → postgres-adapter-B7hzWhky.mjs} +2 -2
- package/dist/{postgres-adapter-BAqRfWl1.mjs.map → postgres-adapter-B7hzWhky.mjs.map} +1 -1
- package/dist/{postgres-adapter-B1RyJlWL.mjs → postgres-adapter-CJmoxTW7.mjs} +2 -2
- package/dist/{postgres-adapter-B1RyJlWL.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-V09frtmK.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
- package/dist/{provider-limits-V09frtmK.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
- package/dist/result-shape-ic2j3Tze.mjs +2 -0
- package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
- package/dist/{rows-BiaiswSV.mjs → rows-YyvK9MDz.mjs} +2 -2
- package/dist/{rows-BiaiswSV.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
- package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
- package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-tGtziyCJ.mjs → schema-CUm_yh6L.mjs} +2 -2
- package/dist/{schema-tGtziyCJ.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
- package/dist/{schema-introspection-C1-XrQP4.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
- package/dist/{schema-introspection-C1-XrQP4.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sqlite-adapter-CoDeF2h2.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
- package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
- package/dist/{sqlite-utils-C0TyzOys.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
- package/dist/{sqlite-utils-C0TyzOys.mjs.map → sqlite-utils-C5_KQPZn.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
- package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
- package/dist/{utils-DkAxKcDD.mjs → utils-CQ2nQwwO.mjs} +2 -2
- package/dist/{utils-DkAxKcDD.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
- package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
- package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
- package/dist/{validation-C7Z6wTJa.mjs → validation-CjWRiLWU.mjs} +2 -2
- package/dist/{validation-C7Z6wTJa.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
- package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
- package/dist/version-DLtcW9kn.mjs +2 -0
- package/dist/{version-n393hhwM.mjs.map → version-DLtcW9kn.mjs.map} +1 -1
- package/package.json +15 -15
- package/dist/builder-BS8EW4BQ.mjs +0 -2
- package/dist/builder-BS8EW4BQ.mjs.map +0 -1
- package/dist/client-Bhl2mWam.mjs +0 -2
- package/dist/client-Bhl2mWam.mjs.map +0 -1
- package/dist/current-oXcxSCBQ.mjs +0 -2
- package/dist/current-oXcxSCBQ.mjs.map +0 -1
- package/dist/driver-CQQbCQh9.mjs +0 -2
- package/dist/driver-CQQbCQh9.mjs.map +0 -1
- package/dist/every-CzF00eDV.mjs +0 -2
- package/dist/execution-context-rJXTRVrJ.mjs +0 -2
- package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
- package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
- package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
- package/dist/result-shape-Fi1-Fvri.mjs +0 -2
- package/dist/result-shape-Fi1-Fvri.mjs.map +0 -1
- package/dist/sqlite-adapter-CoDeF2h2.mjs.map +0 -1
- package/dist/version-n393hhwM.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-C2vOPcuA.mjs","names":["COLUMNS_QUERY","mode","introspectMySQL","column"],"sources":["../src/migrations/drivers/mysql/catalog.ts","../src/migrations/drivers/mysql/decimal-recovery.ts","../src/migrations/drivers/mysql/introspect.ts","../src/migrations/drivers/mysql/pinned-session.ts","../src/migrations/drivers/mysql/index.ts"],"sourcesContent":["/**\n * MySQL catalog targeting (plan §5.2).\n *\n * Every MySQL migration catalog read filters on ONE exact database, and this\n * module owns which database that is. It replaces `DATABASE()`, whose answer is\n * the connection's ambient default — a fact the ORM never configured and a\n * proxy or a pooled session can change under it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\n\n/**\n * The configured database name, on the shared safe-metadata allowlist's own\n * `namespace` key (`src/errors/diagnostics.ts`). The message states which\n * database it is; this makes it readable programmatically too.\n */\nconst namespaceMeta = (namespace: string) => ({\n dialect: \"mysql\",\n namespace,\n});\n\n/**\n * The one existence proof. `SCHEMA_NAME` comes back so the caller can speak the\n * server's own spelling in later catalog filters.\n *\n * The comparison is case-insensitive because `lower_case_table_names` can make\n * a differently cased configured value name the same physical database; the\n * candidate set it produces is then resolved by the rules below, never guessed.\n */\nconst SCHEMATA_QUERY = `\nSELECT SCHEMA_NAME\nFROM information_schema.SCHEMATA\nWHERE LOWER(SCHEMA_NAME) = LOWER(?)\nORDER BY SCHEMA_NAME\n`;\n\n/**\n * One catalog row, as UNTRUSTED transport data.\n *\n * `SCHEMA_NAME` is typed `unknown` on purpose. MySQL declares the column NOT\n * NULL, but the value reaching this module has crossed a driver: a\n * serverless/HTTP MySQL transport, or any custom `_executeRaw`, can answer with\n * `null` or a number. Declaring the server's own DDL here would be a claim this\n * module cannot make, so the narrowing below makes it instead.\n */\ninterface SchemataRow {\n SCHEMA_NAME: unknown;\n}\n\n/** Executes one catalog statement with its bound values. */\nexport type CatalogReader = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * Proves the configured database exists and returns the catalog's own spelling\n * of it (§5.2).\n *\n * Three refusals, all before any snapshot, tracking or DDL effect:\n *\n * 1. no configured database — a MySQL estate is database-relative on purpose,\n * so an unbound driver has nothing to read a catalog against. Every COMMAND\n * that reaches here has already been refused by the shared live-capability\n * admission owner (`src/migrations/admission.ts`), `introspect(client)`\n * included. This arm's unique coverage is the UNBOUND REGISTERED SINGLETON,\n * which the migration layer deliberately keeps usable by name for\n * artifact-only work: `mysqlMigrationDriver.introspect(reader)` reaches this\n * reader with no client, no context and therefore no admission owner in\n * front of it. It is also what narrows the base class's optional\n * `namespace?: string` to the `string` every filter below binds, without an\n * assertion.\n * 2. no candidate row — a missing database is not an empty database, and\n * publishing an empty inventory for one would plan a full rebuild against a\n * database that does not exist.\n * 3. more than one case-only candidate and none byte-exact — the server would\n * pick one by its own collation rules; choosing for it would silently bind\n * the estate to a database the configuration never named.\n *\n * The returned spelling is command-local: it is a projection of the configured\n * target under this server's identity rules, it is never stored, and it\n * disappears with the pinned session that resolved it. Within that command it\n * is what EVERY statement naming the database renders from — the `USE`, the\n * catalog filters, the tracking table and the live DDL alike — because refusal\n * 3 has already established that only one database answers to the configured\n * name here, and the server accepts only its own spelling of it. Runtime ORM\n * SQL is outside this: it renders from the adapter's immutable configured\n * value, which nothing in this module projects.\n */\nexport async function resolveCatalogNamespace(\n executeRaw: CatalogReader,\n namespace: string | undefined\n): Promise<string> {\n if (namespace === undefined) {\n throw new MigrationError(\n \"This MySQL client's adapter declares no database, so there is no catalog to read. \" +\n \"MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n\n const { rows } = await executeRaw<SchemataRow>(SCHEMATA_QUERY, [namespace]);\n // A present-but-non-string name is the same as absent: unproven. Keeping one\n // would publish it as \"the resolved catalog spelling\", bind it into all five\n // subsequent filters, match nothing, and report an ABSENT database as an\n // empty one — the single outcome refusal 2 exists to prevent. Dropping it\n // here leaves that refusal owning the outcome. (Same doctrine as\n // `src/migrations/target.ts`'s reader of `adapter.namespace`.)\n const candidates = rows\n .map((row) => row.SCHEMA_NAME)\n .filter((name): name is string => typeof name === \"string\");\n\n if (candidates.length === 0) {\n throw new MigrationError(\n `The MySQL database \"${namespace}\" does not exist or is not visible to this connection. ` +\n \"VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { ...namespaceMeta(namespace), type: \"missing-database\" } }\n );\n }\n\n const exact = candidates.find((candidate) => candidate === namespace);\n if (exact !== undefined) {\n return exact;\n }\n\n const [folded] = candidates;\n if (candidates.length === 1 && folded !== undefined) {\n return folded;\n }\n\n throw new MigrationError(\n `The MySQL database \"${namespace}\" matches ${candidates.length} existing databases that differ only by case (${candidates.join(\", \")}). ` +\n \"Configure the exact name this server reports so migration work cannot land in the wrong one.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n ...namespaceMeta(namespace),\n type: \"ambiguous-database\",\n candidates,\n },\n }\n );\n}\n","import type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionConstraintName,\n mysqlDecimalFitsCatalogCheck,\n mysqlDecimalListFitsCatalogCheck,\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport type { CatalogRead } from \"../../target\";\n\nconst RESERVED_PREFIX = \"viborm_decimal_\";\nconst RESERVED_NAME = /^viborm_decimal_([sl])_(\\d+)_(\\d+)$/;\nconst CATALOG_CHARACTER_SET_INTRODUCER = /^_[a-zA-Z0-9]+(?=')/;\nconst WHITESPACE = /\\s/;\n\nconst CONSTRAINTS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n tc.ENFORCED,\n cc.CHECK_CLAUSE\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.CONSTRAINT_TYPE = 'CHECK'\n AND LEFT(tc.CONSTRAINT_NAME, 15) = ?\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME\n`;\n\nconst COLUMNS_QUERY = `\nSELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = ?\nORDER BY TABLE_NAME, ORDINAL_POSITION\n`;\n\ninterface ConstraintRow {\n readonly TABLE_NAME: unknown;\n readonly CONSTRAINT_NAME: unknown;\n readonly ENFORCED: unknown;\n readonly CHECK_CLAUSE: unknown;\n}\n\ninterface ColumnRow {\n readonly TABLE_NAME: unknown;\n readonly COLUMN_NAME: unknown;\n readonly DATA_TYPE: unknown;\n readonly COLUMN_COMMENT: unknown;\n}\n\ninterface ProvenConstraint {\n readonly tableName: string;\n readonly constraintName: string;\n}\n\ninterface RecoveryColumn {\n readonly name: string;\n readonly dataType: string;\n readonly comment: string;\n}\n\nfunction refuseReservedConstraint(\n constraintName: string,\n tableName: string,\n reason: string\n): never {\n throw new MigrationError(\n `The MySQL CHECK constraint \"${constraintName}\" on table \"${tableName}\" uses VibORM's reserved decimal-conversion namespace but ${reason}. ` +\n \"Migration work is refused before any cleanup or schema effect; rename the user-owned constraint, or restore the exact interrupted VibORM conversion proof and run the command again.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n type: \"decimal-conversion-constraint-collision\",\n table: tableName,\n constraint: constraintName,\n },\n }\n );\n}\n\nfunction readString(\n value: unknown,\n constraintName: string,\n tableName: string,\n field: string\n): string {\n if (typeof value === \"string\") return value;\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its catalog ${field} is not a string`\n );\n}\n\n/**\n * MySQL stores CHECK clauses in a normalized spelling: keywords are lower-case,\n * redundant grouping parentheses are added, `CHARACTER SET` becomes `CHARSET`,\n * and string literals acquire a connection-character-set introducer. These are\n * presentation changes only. Removing precisely those tokens leaves the exact\n * generated expression comparable without accepting another predicate.\n */\nfunction normalizeCheckClause(clause: string): string {\n // CHECK_CLAUSE escapes each catalog-rendered string delimiter as `\\'` on\n // mysql2. None of VibORM's fixed proof literals contains an apostrophe, so\n // this removes only the provider's delimiter escape, never literal content.\n const rendered = clause.replaceAll(\"\\\\'\", \"'\");\n let normalized = \"\";\n let index = 0;\n while (index < rendered.length) {\n const char = rendered[index];\n if (char === \"'\") {\n const start = index;\n index++;\n while (index < rendered.length) {\n if (rendered[index] === \"\\\\\" && index + 1 < rendered.length) {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\" && rendered[index + 1] === \"'\") {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\") {\n index++;\n break;\n }\n index++;\n }\n normalized += rendered.slice(start, index);\n continue;\n }\n if (char === \"`\") {\n const end = rendered.indexOf(\"`\", index + 1);\n if (end < 0) return clause;\n normalized += rendered.slice(index, end + 1);\n index = end + 1;\n continue;\n }\n if (WHITESPACE.test(char ?? \"\")) {\n index++;\n continue;\n }\n if (char === \"_\") {\n const introducer = CATALOG_CHARACTER_SET_INTRODUCER.exec(\n rendered.slice(index)\n );\n if (introducer !== null) {\n index += introducer[0].length;\n continue;\n }\n }\n normalized += char?.toLowerCase() ?? \"\";\n index++;\n }\n return normalized;\n}\n\nfunction expectedConstraint(\n column: RecoveryColumn,\n kind: \"s\" | \"l\",\n descriptor: DecimalDescriptor\n): string {\n const quotedColumn = `\\`${column.name}\\``;\n return kind === \"s\"\n ? mysqlDecimalFitsCatalogCheck(\n quotedColumn,\n `DECIMAL(${descriptor.precision},${descriptor.scale})`\n )\n : mysqlDecimalListFitsCatalogCheck(quotedColumn, descriptor);\n}\n\nfunction readDescriptor(\n match: RegExpExecArray,\n constraintName: string,\n tableName: string\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(match[2], match[3], \"mysql\");\n if (descriptor === undefined) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name declares a decimal domain this provider does not admit\"\n );\n }\n const kind = match[1] === \"s\" ? \"scalar\" : \"list\";\n if (decimalConversionConstraintName(kind, descriptor) !== constraintName) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name is not the canonical spelling of its decimal proof\"\n );\n }\n return descriptor;\n}\n\nfunction proveConstraint(\n row: ConstraintRow,\n columnsByTable: ReadonlyMap<string, readonly RecoveryColumn[]>\n): ProvenConstraint {\n const rawName =\n typeof row.CONSTRAINT_NAME === \"string\"\n ? row.CONSTRAINT_NAME\n : \"<unreported>\";\n const rawTable =\n typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"<unreported>\";\n const constraintName = readString(\n row.CONSTRAINT_NAME,\n rawName,\n rawTable,\n \"CONSTRAINT_NAME\"\n );\n const tableName = readString(\n row.TABLE_NAME,\n constraintName,\n rawTable,\n \"TABLE_NAME\"\n );\n const clause = readString(\n row.CHECK_CLAUSE,\n constraintName,\n tableName,\n \"CHECK_CLAUSE\"\n );\n const enforced = readString(\n row.ENFORCED,\n constraintName,\n tableName,\n \"ENFORCED\"\n );\n if (enforced !== \"YES\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its CHECK is not enforced\"\n );\n }\n const nameMatch = RESERVED_NAME.exec(constraintName);\n if (nameMatch === null) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name does not match the complete reserved proof identity\"\n );\n }\n const kind = nameMatch[1] === \"s\" ? \"s\" : \"l\";\n const descriptor = readDescriptor(nameMatch, constraintName, tableName);\n\n const columns = columnsByTable.get(tableName) ?? [];\n const actualClause = normalizeCheckClause(clause);\n for (const column of columns) {\n const expected = expectedConstraint(column, kind, descriptor);\n if (normalizeCheckClause(expected) !== actualClause) continue;\n if (kind === \"s\") {\n if (\n column.dataType === \"decimal\" ||\n column.dataType === \"int\" ||\n column.dataType === \"bigint\"\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its scalar proof is attached to impossible ${column.dataType} storage`\n );\n }\n if (column.dataType !== \"json\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its list proof is attached to impossible ${column.dataType} storage`\n );\n }\n let current: DecimalDescriptor | undefined;\n try {\n current = readMysqlDecimalListMarker(column.comment);\n } catch {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column carries an invalid decimal-list marker\"\n );\n }\n if (\n current !== undefined &&\n current.scale === descriptor.scale &&\n current.precision >= descriptor.precision\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column does not carry a compatible source or target decimal-list marker\"\n );\n }\n\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its concrete CHECK predicate does not match that proof identity\"\n );\n}\n\nfunction groupColumns(\n rows: readonly ColumnRow[]\n): Map<string, RecoveryColumn[]> {\n const columnsByTable = new Map<string, RecoveryColumn[]>();\n for (const row of rows) {\n const tableName = typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"\";\n const columnName =\n typeof row.COLUMN_NAME === \"string\" ? row.COLUMN_NAME : \"\";\n const dataType = typeof row.DATA_TYPE === \"string\" ? row.DATA_TYPE : \"\";\n const comment =\n typeof row.COLUMN_COMMENT === \"string\" ? row.COLUMN_COMMENT : \"\";\n if (tableName === \"\" || columnName === \"\" || dataType === \"\") continue;\n const columns = columnsByTable.get(tableName) ?? [];\n columns.push({\n name: columnName,\n dataType: dataType.toLowerCase(),\n comment,\n });\n columnsByTable.set(tableName, columns);\n }\n return columnsByTable;\n}\n\n/**\n * Plans the removal of authenticated remnants of a MySQL decimal conversion.\n *\n * The migration lock excludes another VibORM command. Every reserved row is\n * proven before the first DROP is returned, so a user-owned collision or a\n * malformed catalog answer cannot make cleanup partially mutate the estate.\n * Execution belongs to the sequential-program owner: MySQL can commit a DROP\n * before reporting a connection failure, and only that owner can state the\n * resulting uncertain boundary honestly.\n */\nexport async function planInterruptedMySQLDecimalRecovery(\n read: CatalogRead,\n namespace: string,\n quoteIdentifier: (name: string) => string\n): Promise<readonly string[]> {\n const { rows } = await read<ConstraintRow>(CONSTRAINTS_QUERY, [\n namespace,\n RESERVED_PREFIX,\n ]);\n if (rows.length === 0) return [];\n if (rows.length > 1) {\n const first = rows[0];\n refuseReservedConstraint(\n typeof first?.CONSTRAINT_NAME === \"string\"\n ? first.CONSTRAINT_NAME\n : \"<unreported>\",\n typeof first?.TABLE_NAME === \"string\" ? first.TABLE_NAME : \"<unreported>\",\n `the catalog contains ${rows.length} reserved proofs, although one locked conversion can leave at most one`\n );\n }\n\n const columns = await read<ColumnRow>(COLUMNS_QUERY, [namespace]);\n const columnsByTable = groupColumns(columns.rows);\n const proven = rows.map((row) => proveConstraint(row, columnsByTable));\n\n return proven.map(\n (constraint) =>\n `ALTER TABLE ${quoteIdentifier(namespace)}.${quoteIdentifier(constraint.tableName)} DROP CHECK ${quoteIdentifier(constraint.constraintName)}`\n );\n}\n","/**\n * MySQL Schema Introspection\n *\n * Reads the current database schema from MySQL's information_schema,\n * returning a normalized SchemaSnapshot.\n */\n\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport { decodeUtf8 } from \"../../identity\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport {\n MYSQL_PRINTED_CHARACTERS,\n mysqlEnumType,\n mysqlStringLiteral,\n parseMySqlEnumValues,\n} from \"../type-mapping\";\nimport { groupBy, groupByNested, mapReferentialAction } from \"../utils\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport type {\n MySQLColumn,\n MySQLForeignKey,\n MySQLIndex,\n MySQLPrimaryKey,\n MySQLTable,\n} from \"./types\";\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\n// Every filter below binds the resolved database as DATA (§5.2). The name is\n// never spliced into the statement, and `DATABASE()` — the connection's ambient\n// default, which the ORM never configured — appears nowhere.\nconst TABLES_QUERY = `\nSELECT TABLE_NAME\nFROM information_schema.TABLES\nWHERE TABLE_SCHEMA = ?\n AND TABLE_TYPE = 'BASE TABLE'\nORDER BY TABLE_NAME\n`;\n\nconst COLUMNS_QUERY = `\nSELECT\n TABLE_NAME,\n COLUMN_NAME,\n DATA_TYPE,\n COLUMN_TYPE,\n IS_NULLABLE,\n COLUMN_DEFAULT,\n CHARACTER_MAXIMUM_LENGTH,\n NUMERIC_PRECISION,\n NUMERIC_SCALE,\n SRS_ID,\n EXTRA,\n COLUMN_COMMENT\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = ?\nORDER BY TABLE_NAME, ORDINAL_POSITION\n`;\n\nconst PRIMARY_KEYS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nWHERE tc.TABLE_SCHEMA = ?\n AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'\nORDER BY tc.TABLE_NAME, kcu.ORDINAL_POSITION\n`;\n\nconst INDEXES_QUERY = `\nSELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n NON_UNIQUE,\n INDEX_TYPE,\n SEQ_IN_INDEX\nFROM information_schema.STATISTICS\nWHERE TABLE_SCHEMA = ?\n AND INDEX_NAME != 'PRIMARY'\nORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n`;\n\n// Both endpoints are projected and BOTH are admitted as filter candidates\n// (§5.2): a constraint that leaves the estate in either direction has to be\n// visible here before it can be refused, and an inbound one is not reachable\n// through the referencing side's schema at all.\nconst FOREIGN_KEYS_QUERY = `\nSELECT\n tc.TABLE_SCHEMA,\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.REFERENCED_TABLE_SCHEMA,\n kcu.REFERENCED_TABLE_NAME,\n kcu.REFERENCED_COLUMN_NAME,\n rc.DELETE_RULE,\n rc.UPDATE_RULE,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nJOIN information_schema.REFERENTIAL_CONSTRAINTS rc\n ON rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n AND rc.CONSTRAINT_SCHEMA = tc.TABLE_SCHEMA\nWHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'\n AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?)\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\n`;\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/**\n * The MySQL storage whose literal default the catalog already reports the way\n * the estate spells it: a number is a number, and a `BIT` default is reported\n * as its own `b'…'` literal. Every other type's literal default is a QUOTED\n * string in DDL, and `information_schema` reports it with the quotes gone.\n */\nconst MYSQL_NUMERIC_DATA_TYPES = new Set([\n \"bigint\",\n \"bit\",\n \"decimal\",\n \"double\",\n \"float\",\n \"int\",\n \"integer\",\n \"mediumint\",\n \"numeric\",\n \"real\",\n \"smallint\",\n \"tinyint\",\n]);\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction formatColumnType(col: MySQLColumn): string {\n if (col.DATA_TYPE.toLowerCase() === \"point\") {\n const srid = readSrid(col);\n return srid === undefined ? \"POINT\" : `POINT SRID ${srid}`;\n }\n\n // An ENUM's values ARE its type. `information_schema` prints its own\n // rendering of them — `enum('a','b')`, no space after the comma — so the\n // parsed values are re-spelled through the estate's ONE enum speller and the\n // two snapshots name one type. A COLUMN_TYPE that parses to no values at all\n // is not an enum MySQL could have created; it stays exactly as read.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n return values ? mysqlEnumType(values) : col.COLUMN_TYPE;\n }\n\n // For types with modifiers (unsigned, zerofill) or size info in COLUMN_TYPE,\n // prefer COLUMN_TYPE to preserve full type specification\n // Examples: \"int unsigned\", \"bigint unsigned zerofill\", \"varbinary(255)\", \"bit(8)\", \"timestamp(6)\"\n const columnType = col.COLUMN_TYPE.toLowerCase();\n const hasModifiers =\n columnType.includes(\"unsigned\") ||\n columnType.includes(\"zerofill\") ||\n // Has parentheses with size/precision info (but not enum which is handled above)\n (columnType.includes(\"(\") && col.DATA_TYPE !== \"enum\");\n\n if (hasModifiers) {\n return col.COLUMN_TYPE;\n }\n\n // Fallback: construct from DATA_TYPE with precision info\n if (col.DATA_TYPE === \"varchar\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `VARCHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"char\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `CHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION) {\n if (col.NUMERIC_SCALE !== null && col.NUMERIC_SCALE !== undefined) {\n return `DECIMAL(${col.NUMERIC_PRECISION},${col.NUMERIC_SCALE})`;\n }\n return `DECIMAL(${col.NUMERIC_PRECISION})`;\n }\n\n return col.DATA_TYPE.toUpperCase();\n}\n\nfunction readSrid(col: MySQLColumn): number | undefined {\n if (col.SRS_ID === null || col.SRS_ID === undefined) return undefined;\n const value = Number(col.SRS_ID);\n if (Number.isSafeInteger(value) && value >= 0 && value <= 4_294_967_295) {\n return value;\n }\n throw new MigrationError(\n `MySQL reported an invalid SRID for column \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\". Migration introspection is refused rather than publishing an unprovable spatial type.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-srid\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(extra: string): boolean {\n return extra.toLowerCase().includes(\"auto_increment\");\n}\n\n/**\n * The declared decimal domain of a MySQL column, or `undefined`.\n *\n * Two carriers, because MySQL stores the two shapes differently. A scalar is\n * `DECIMAL(p,s)` and the catalog reports the pair directly. A list is `JSON`,\n * which carries nothing, so its domain lives in the deterministic column\n * comment — matched EXACTLY (§6.2): a comment that merely mentions a decimal is\n * a comment, not a descriptor, and reading one as a descriptor would attach a\n * domain to a column VibORM never declared one on.\n */\nfunction readDecimalDomain(col: MySQLColumn): DecimalDescriptor | undefined {\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION !== null) {\n const descriptor = readStoredDecimalDescriptor(\n col.NUMERIC_PRECISION,\n col.NUMERIC_SCALE ?? 0,\n \"mysql\"\n );\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `MySQL reported column \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\" as DECIMAL(${String(col.NUMERIC_PRECISION)},${String(col.NUMERIC_SCALE ?? 0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n }\n if (col.DATA_TYPE !== \"json\") return undefined;\n return readMysqlDecimalListMarker(col.COLUMN_COMMENT);\n}\n\n/**\n * MySQL deparses an expression-backed string literal as `_charset\\\\'value\\\\'`.\n * The introducer is CAPTURED because it names the encoding of the bytes that\n * follow it (see {@link decodeIntroducedLiteral}).\n */\nconst MYSQL_STRING_EXPRESSION_DEFAULT = /^_([A-Za-z0-9_]+)\\\\'([\\s\\S]*)\\\\'$/;\n\n/** One backslash escape, with the character it escapes. */\nconst MYSQL_ESCAPE_SEQUENCE = /\\\\([\\s\\S]?)/g;\n\n/** Each byte read as the codepoint of the same number. */\nfunction decodeSingleByte(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\"\");\n}\n\n/**\n * MySQL's `latin1` IS Windows-1252, not ISO-8859-1: the 32 bytes 0x80–0x9F are\n * printable characters there (0x93 is U+201C), and the five cp1252 leaves\n * undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) MySQL maps to the same-numbered\n * control. Every other byte is the codepoint of its own number.\n */\nconst CP1252_HIGH: readonly number[] = [\n 0x20_ac, 0x81, 0x20_1a, 0x01_92, 0x20_1e, 0x20_26, 0x20_20, 0x20_21, 0x02_c6,\n 0x20_30, 0x01_60, 0x20_39, 0x01_52, 0x8d, 0x01_7d, 0x8f, 0x90, 0x20_18,\n 0x20_19, 0x20_1c, 0x20_1d, 0x20_22, 0x20_13, 0x20_14, 0x02_dc, 0x21_22,\n 0x01_61, 0x20_3a, 0x01_53, 0x9d, 0x01_7e, 0x01_78,\n];\nfunction decodeLatin1(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) =>\n String.fromCharCode(\n byte >= 0x80 && byte <= 0x9f ? (CP1252_HIGH[byte - 0x80] ?? byte) : byte\n )\n ).join(\"\");\n}\n\n/**\n * How an introducer's bytes are READ — one entry per charset, because the\n * charset is what says what a byte MEANS.\n *\n * MySQL names the charset of the DDL the literal arrived in and FREEZES it in\n * the stored expression, so the writing SESSION decides what reaches this\n * inverse, whatever the reading one speaks (measured: a column created over a\n * `latin1` connection reports `_latin1` to an ordinary utf8mb4 connection,\n * `closure-repair-2/t3/receipts/probe-frozen-introducer.log`). The UTF-8 family\n * is decoded; `ascii` and `binary` map each byte to the codepoint of the same\n * number, so the catalog's text already IS the value; `latin1` is read as the\n * Windows-1252 MySQL means by it ({@link decodeLatin1}). A charset\n * outside this table — `cp1251`, say, where the same byte is a different\n * letter — is not read at all: either reading would be a guess there, and a\n * wrong guess calls two different defaults equal.\n */\nconst MYSQL_INTRODUCER_DECODERS: ReadonlyMap<\n string,\n (bytes: Uint8Array) => string\n> = new Map([\n [\"utf8\", decodeUtf8],\n [\"utf8mb3\", decodeUtf8],\n [\"utf8mb4\", decodeUtf8],\n [\"latin1\", decodeLatin1],\n [\"ascii\", decodeSingleByte],\n [\"binary\", decodeSingleByte],\n]);\n\n/**\n * The printed literal behind the catalog's text, or `undefined` when the text\n * is not the byte sequence the introducer promises.\n *\n * `information_schema.COLUMNS.COLUMN_DEFAULT` hands an EXPRESSION default's\n * text back one codepoint per BYTE: `café ☕` arrives as the nine codepoints\n * `63 61 66 c3 a9 20 e2 98 95` — the UTF-8 bytes of the value, each read as a\n * character — while the SAME column carries a LITERAL default's value decoded\n * (measured on 8.4.11: `HEX(COLUMN_DEFAULT)` shows the expansion server-side,\n * and `SHOW CREATE TABLE` prints the true text, so the loss is MySQL's own\n * rendering of a stored expression, not the connection's character set and not\n * the driver). Those bytes are the literal, in the charset the introducer\n * names, so they are read back with THAT charset\n * ({@link MYSQL_INTRODUCER_DECODERS}) rather than re-decoded by a rule of this\n * module's invention.\n *\n * An unknown charset, an out-of-byte-range codepoint, or an invalid byte\n * sequence keeps the catalog's own text. These checks do not prove provenance:\n * the measured mysql2 byte-expanded spelling of `é` and already-decoded text\n * whose literal characters are `é` both present `c3 a9`, a valid UTF-8\n * sequence. Content alone cannot distinguish them. This decoder therefore\n * describes the measured mysql2 catalog representation; other transport\n * representations are unverified, and valid UTF-8-shaped already-decoded text\n * can be transformed rather than fail closed.\n */\nfunction decodeIntroducedLiteral(\n introducer: string,\n printed: string\n): string | undefined {\n const decode = MYSQL_INTRODUCER_DECODERS.get(introducer.toLowerCase());\n if (decode === undefined) return undefined;\n const codes = [...printed].map((character) => character.codePointAt(0) ?? 0);\n if (codes.some((code) => code > 0xff)) return undefined;\n try {\n return decode(Uint8Array.from(codes));\n } catch {\n return undefined;\n }\n}\n\n/** `undefined` for a body carrying an escape MySQL's printer does not write. */\nfunction unescapeOneLayer(body: string): string | undefined {\n let owned = true;\n const unescaped = body.replace(\n MYSQL_ESCAPE_SEQUENCE,\n (_match: string, escaped: string) => {\n const character = MYSQL_PRINTED_CHARACTERS.get(escaped);\n if (character === undefined) {\n owned = false;\n return escaped;\n }\n return character;\n }\n );\n return owned ? unescaped : undefined;\n}\n\n/**\n * The VALUE behind MySQL's deparse of a string default, or `undefined` when\n * the catalog text carries an escape this inverse does not own.\n *\n * The text is escaped TWICE — once by MySQL printing the string literal inside\n * the expression, once by `information_schema` printing that expression — so a\n * declared `it's` arrives as the characters `_utf8mb4\\'it\\\\\\'s\\'` (measured on\n * MySQL 8.4.11). Each pass undoes one layer, through the table MySQL's printer\n * writes (`MYSQL_PRINTED_CHARACTERS`). An escape outside that table is not one\n * this server printed for a value the estate spelled, so inverting it would be\n * a guess, and a wrong guess calls two different defaults equal.\n *\n * The BYTES come first ({@link decodeIntroducedLiteral}), because the catalog\n * spells them one per codepoint and every escape MySQL prints is ASCII: the\n * layers are the same after the decode, and only a text that is those bytes\n * reaches them.\n */\nfunction deparsedStringValue(columnDefault: string): string | undefined {\n const deparsed = MYSQL_STRING_EXPRESSION_DEFAULT.exec(columnDefault);\n const introducer = deparsed?.[1];\n const body = deparsed?.[2];\n const printed =\n introducer === undefined || body === undefined\n ? undefined\n : decodeIntroducedLiteral(introducer, body);\n const literal = printed === undefined ? undefined : unescapeOneLayer(printed);\n return literal === undefined ? undefined : unescapeOneLayer(literal);\n}\n\n/**\n * The column's default, in the ONE spelling the estate uses.\n *\n * MySQL reports a default in two vocabularies and neither is the estate's. A\n * LITERAL default comes back as the bare VALUE — `member`, `x'y` — with the\n * quotes DDL required stripped off. An EXPRESSION default (every default on a\n * TEXT, BLOB, JSON or GEOMETRY column, since those refuse a literal) comes back\n * as MySQL's deparse of the expression, where a string literal is printed\n * `_charset\\\\'value\\\\'`. Both are translated here, at the one boundary that\n * reads the catalog, into what `finalizeMySQLColumn` spells on the desired\n * side; otherwise a default nobody touched reads as a changed column on every\n * push, and the final push attestation refuses the schema it just created.\n *\n * A deparse this inverse does not own keeps MySQL's own catalog text, which\n * stays different from the desired side: the column is re-planned and the push\n * then FAILS at the final attestation with `MIGRATION_DRIFT`. That is the\n * fail-closed direction — the same one the decimal-list container took when it\n * could not be re-encoded byte for byte — and it refuses a default nobody\n * proved equal instead of reporting a schema the database does not hold.\n */\nfunction cleanDefault(col: MySQLColumn): string | undefined {\n const columnDefault = col.COLUMN_DEFAULT;\n if (columnDefault === null) return undefined;\n if (col.EXTRA.toUpperCase().includes(\"DEFAULT_GENERATED\")) {\n const value = deparsedStringValue(columnDefault);\n return value === undefined\n ? columnDefault\n : `(${mysqlStringLiteral(value)})`;\n }\n return MYSQL_NUMERIC_DATA_TYPES.has(col.DATA_TYPE.toLowerCase())\n ? columnDefault\n : mysqlStringLiteral(columnDefault);\n}\n\n/**\n * Refuses every foreign key with one endpoint outside the selected database\n * (§5.2), before the snapshot exists.\n *\n * Both directions are refused for the same reason: the estate's own DDL cannot\n * express, drop or recreate a constraint whose other half lives in a database\n * this client does not manage, so a reset, a push, or a generated down would\n * plan work that is either impossible or destructive to a stranger's schema.\n *\n * This runs BEFORE the rows are grouped, because the grouped set is also what\n * hides MySQL's auto-created FK indexes from the snapshot: admitting a foreign\n * row here would silently change which indexes the differ sees.\n */\nfunction admitContainedForeignKeys(\n rows: readonly MySQLForeignKey[],\n namespace: string,\n tables?: readonly string[]\n): void {\n for (const row of rows) {\n if (\n tables !== undefined &&\n !(row.TABLE_SCHEMA === namespace && tables.includes(row.TABLE_NAME)) &&\n !(\n row.REFERENCED_TABLE_SCHEMA === namespace &&\n tables.includes(row.REFERENCED_TABLE_NAME)\n )\n )\n continue;\n if (\n row.TABLE_SCHEMA === namespace &&\n row.REFERENCED_TABLE_SCHEMA === namespace\n ) {\n continue;\n }\n throw new MigrationError(\n `Foreign key \"${row.CONSTRAINT_NAME}\" crosses a database boundary: \\`${row.TABLE_SCHEMA}\\`.\\`${row.TABLE_NAME}\\` references \\`${row.REFERENCED_TABLE_SCHEMA}\\`.\\`${row.REFERENCED_TABLE_NAME}\\`, and this client manages only \"${namespace}\". ` +\n \"Migration work is refused before any snapshot, plan or DDL: VibORM cannot recreate or drop a constraint whose other half lives in a database it does not own.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n // BOTH endpoints are reported (§5.2), each on its own allowlisted\n // channel: the referencing one on `table`, the referenced one on\n // `referencedTable`, beside the database this client manages.\n meta: {\n dialect: \"mysql\",\n type: \"cross-database-foreign-key\",\n constraint: row.CONSTRAINT_NAME,\n namespace,\n table: `${row.TABLE_SCHEMA}.${row.TABLE_NAME}`,\n referencedTable: `${row.REFERENCED_TABLE_SCHEMA}.${row.REFERENCED_TABLE_NAME}`,\n },\n }\n );\n }\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: CatalogReader,\n namespace: string | undefined,\n managedTables?: readonly string[]\n): Promise<SchemaSnapshot> {\n // The database is proven to exist BEFORE anything is read, so an absent one\n // can never be published as an empty inventory (§5.2). Its returned spelling\n // is what every filter below binds and what the containment comparison uses:\n // under `lower_case_table_names` the server's spelling is the identity the\n // catalog rows actually carry.\n const catalogNamespace = await resolveCatalogNamespace(executeRaw, namespace);\n\n // One after another: these run on the command's ONE pinned session, and a\n // connection runs one statement at a time. mysql2 queues overlapping\n // queries silently, but the overlap bought nothing.\n const scope = [catalogNamespace];\n const tablesResult = await executeRaw<MySQLTable>(TABLES_QUERY, scope);\n const columnsResult = await executeRaw<MySQLColumn>(COLUMNS_QUERY, scope);\n const primaryKeysResult = await executeRaw<MySQLPrimaryKey>(\n PRIMARY_KEYS_QUERY,\n scope\n );\n const indexesResult = await executeRaw<MySQLIndex>(INDEXES_QUERY, scope);\n const foreignKeysResult = await executeRaw<MySQLForeignKey>(\n FOREIGN_KEYS_QUERY,\n [catalogNamespace, catalogNamespace]\n );\n\n admitContainedForeignKeys(\n foreignKeysResult.rows,\n catalogNamespace,\n managedTables\n );\n\n // Group results\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.TABLE_NAME);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.TABLE_NAME);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.TABLE_NAME,\n (idx) => idx.INDEX_NAME\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows.filter((fk) => fk.TABLE_SCHEMA === catalogNamespace),\n (fk) => fk.TABLE_NAME,\n (fk) => fk.CONSTRAINT_NAME\n );\n // Track enum definitions found in columns\n const enumDefs: EnumDef[] = [];\n const seenEnums = new Set<string>();\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.TABLE_NAME;\n\n // Build columns\n const columns: ColumnDef[] = [];\n for (const col of columnsByTable.get(tableName) || []) {\n if (\n (managedTables === undefined || managedTables.includes(tableName)) &&\n (col.EXTRA.toUpperCase().includes(\"VIRTUAL GENERATED\") ||\n col.EXTRA.toUpperCase().includes(\"STORED GENERATED\"))\n )\n throw new MigrationError(\n `MySQL column \"${tableName}.${col.COLUMN_NAME}\" is generated. Synchronization refuses before effects because its expression cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: tableName,\n column: col.COLUMN_NAME,\n feature: \"generated column\",\n },\n }\n );\n // Extract enum values if this is an enum column\n // MySQL has no standalone enum object, so the inline type IS the\n // identity — and it is the identity the DESIRED snapshot registers too\n // (`serializer.ts` names an enum by `getEnumColumnType`). Naming it\n // anything else here, as a derived `table$column$enum` did, made every\n // enum-bearing schema carry two enum definitions that could never match.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n const enumName = values && mysqlEnumType(values);\n if (values && enumName && !seenEnums.has(enumName)) {\n enumDefs.push({ name: enumName, values });\n seenEnums.add(enumName);\n }\n }\n\n const managed =\n managedTables === undefined || managedTables.includes(tableName);\n const decimal = managed ? readDecimalDomain(col) : undefined;\n columns.push({\n name: col.COLUMN_NAME,\n type: managed ? formatColumnType(col) : col.COLUMN_TYPE,\n nullable: col.IS_NULLABLE === \"YES\",\n default: managed ? cleanDefault(col) : undefined,\n autoIncrement: isAutoIncrement(col.EXTRA),\n decimal,\n });\n }\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstPkCol = pkCols[0];\n if (firstPkCol) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.COLUMN_NAME),\n name: firstPkCol.CONSTRAINT_NAME,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n // MySQL auto-creates an index named after each FK constraint; it isn't a\n // user index and can't be dropped while the FK exists, so hide it\n const fkNames = new Set(fkByTable.get(tableName)?.keys() ?? []);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n if (fkNames.has(indexName)) {\n continue;\n }\n indexCols.sort((a, b) => a.SEQ_IN_INDEX - b.SEQ_IN_INDEX);\n const firstCol = indexCols[0];\n if (firstCol) {\n const rawIndexType = firstCol.INDEX_TYPE.toLowerCase();\n // MySQL INFORMATION_SCHEMA reports RTREE for spatial indexes, normalize to \"spatial\"\n const indexType = rawIndexType === \"rtree\" ? \"spatial\" : rawIndexType;\n indexes.push({\n name: indexName,\n columns: indexCols.map((idx) => idx.COLUMN_NAME),\n unique: firstCol.NON_UNIQUE === 0,\n // MySQL uses BTREE, HASH, FULLTEXT, SPATIAL (reported as RTREE) - preserve all supported types\n type:\n indexType === \"btree\" ||\n indexType === \"hash\" ||\n indexType === \"fulltext\" ||\n indexType === \"spatial\"\n ? (indexType as \"btree\" | \"hash\" | \"fulltext\" | \"spatial\")\n : undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.COLUMN_NAME),\n referencedTable: firstFk.REFERENCED_TABLE_NAME,\n referencedColumns: fkCols.map((fk) => fk.REFERENCED_COLUMN_NAME),\n onDelete: mapReferentialAction(firstFk.DELETE_RULE),\n onUpdate: mapReferentialAction(firstFk.UPDATE_RULE),\n });\n }\n }\n }\n\n // MySQL HAS ONE UNIQUE NAMESPACE, so a unique is reported ONCE — as an\n // index, above, from STATISTICS. TABLE_CONSTRAINTS lists the very same\n // object a second time (its `UNIQUE` constraint face), and filing that\n // second face here made every unique-bearing MySQL schema churn forever:\n // whichever bucket the desired side did not use looked like a stray object\n // and the differ planned a drop for it (measured on docker MySQL 8 — a\n // spurious `dropIndex` for a declared unique constraint, a spurious\n // `dropUniqueConstraint` for a declared unique index).\n //\n // The desired side is canonicalized to match by the driver's\n // `finalizeTable`, which rewrites every unique constraint into a unique\n // index. Both sides now speak indexes, so a unique round-trips unchanged.\n //\n // The bucket stays in the shape (every dialect's snapshot carries it) and\n // is always empty for MySQL. TABLE_CONSTRAINTS is no longer queried at all:\n // it can report nothing the STATISTICS rows above do not already carry.\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // MySQL doesn't have standalone enum types, but we track them for compatibility\n return {\n tables,\n enums: enumDefs.length > 0 ? enumDefs : undefined,\n };\n}\n","/**\n * MySQL pinned migration session: lock identity, exact lock proofs, the one\n * admitted target selection, and the session's exact-value proof.\n *\n * This module is §13's single exempted `USE` producer. Every other `USE` in the\n * shipped source is a defect, and the architecture census enforces that by\n * naming THIS path — `PINNED_ARTIFACT_SESSION_OWNERS` — and nothing else. The\n * exemption is sound only because the statement below can be reached solely\n * from a pinned migration session, where the owner, lifetime, lock, target and\n * cleanup are one physical connection that is destroyed afterwards\n * (`MySQL2Driver.pinnedSession`).\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { CatalogRead } from \"../../target\";\n\n/**\n * MySQL's `GET_LOCK` name limit. Longer names are an error on 8.0+ and were\n * silently truncated before, which would have collapsed two databases onto one\n * lock name — the exact accident the hash below prevents.\n */\nconst LOCK_NAME_LIMIT = 64;\n\nconst LOCK_NAME_PREFIX = \"viborm_migration_\";\n\n/** `_` + eight hex digits. */\nconst LOCK_HASH_LENGTH = 9;\n\nconst LOCK_NAME_BUDGET =\n LOCK_NAME_LIMIT - LOCK_NAME_PREFIX.length - LOCK_HASH_LENGTH;\n\n/** Every character MySQL identifiers admit that a lock name should not carry. */\nconst NON_LOCK_NAME_CHARACTERS = /[^a-z0-9_]/g;\n\nconst FNV_OFFSET_BASIS = 0x81_1c_9d_c5;\nconst FNV_PRIME = 0x01_00_01_93;\n\n/**\n * A deterministic 32-bit FNV-1a hash, as eight lowercase hex digits.\n *\n * The lock name has to survive truncation without two databases colliding, and\n * a cryptographic digest would be a runtime dependency for a value nothing\n * secret depends on: this is a collision-spreading suffix, not a secret.\n */\nfunction hashLockScope(value: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let index = 0; index < value.length; index += 1) {\n // FNV-1a IS an XOR followed by a multiply; any other spelling is a\n // different function.\n // biome-ignore lint/suspicious/noBitwiseOperators: FNV-1a is defined as XOR-then-multiply.\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, FNV_PRIME);\n }\n // The unsigned shift is how JavaScript reads a 32-bit result back as a\n // non-negative integer.\n // biome-ignore lint/suspicious/noBitwiseOperators: reads the 32-bit result as unsigned.\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * The lock name for one MySQL database.\n *\n * The scope is a CONSERVATIVE lowercase form of the configured database name.\n * Under `lower_case_table_names=1` two spellings of one database are the same\n * database, and letting them take different lock names would let two migration\n * commands run concurrently against it. Lowercasing may also serialize two\n * genuinely distinct case-sensitive databases that differ only in case; that is\n * the deliberate trade — a lock taken too widely is slow, a lock taken too\n * narrowly is wrong.\n *\n * The hash is computed over the WHOLE lowercased name, so two names sharing a\n * truncated prefix still get different locks.\n */\nexport function mysqlMigrationLockName(namespace: string): string {\n const scope = namespace.toLowerCase();\n const readable = scope\n .replace(NON_LOCK_NAME_CHARACTERS, \"_\")\n .slice(0, LOCK_NAME_BUDGET);\n return `${LOCK_NAME_PREFIX}${readable}_${hashLockScope(scope)}`;\n}\n\n/**\n * `GET_LOCK` with a stable `acquired` alias.\n *\n * The alias exists so the caller reads ONE known column instead of guessing at\n * a provider-shaped name built from the expression text.\n */\nexport function mysqlAcquireLockStatement(\n namespace: string,\n timeoutSeconds: number,\n quote: (value: string) => string\n): string {\n return `SELECT GET_LOCK(${quote(mysqlMigrationLockName(namespace))}, ${timeoutSeconds}) AS acquired`;\n}\n\n/** `RELEASE_LOCK` with a stable `released` alias, for the same reason. */\nexport function mysqlReleaseLockStatement(\n namespace: string,\n quote: (value: string) => string\n): string {\n return `SELECT RELEASE_LOCK(${quote(mysqlMigrationLockName(namespace))}) AS released`;\n}\n\n/**\n * The exact arms of a MySQL lock answer.\n *\n * `GET_LOCK` returns `1` when the lock was taken, `0` when the wait timed out,\n * and `NULL` on error. Treating all three as success is what made the previous\n * owner report a timeout as an acquired lock. `RELEASE_LOCK` answers the same\n * three ways about a release.\n *\n * The row itself is provider-shaped data: a value may arrive as a number, as a\n * decimal string (mysql2 returns `BIGINT`-family values as strings when\n * `supportBigNumbers` is on), or not at all. Exactly one row carrying a value\n * that parses to the number 1 is the proof; everything else — `0`, `NULL`, a\n * missing column, a missing row, more than one row, unparseable text — is not.\n */\nexport function mysqlLockAnswer(\n rows: readonly unknown[],\n column: \"acquired\" | \"released\"\n): boolean {\n if (rows.length !== 1) {\n return false;\n }\n const row = rows[0];\n if (typeof row !== \"object\" || row === null) {\n return false;\n }\n const value: unknown = Reflect.get(row, column);\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n return Number(value) === 1;\n }\n return false;\n}\n\n/**\n * Selects the migration target on the pinned session.\n *\n * Generated MySQL artifacts are database-RELATIVE by design (§13): one estate\n * deploys to `app_dev`, `app_test` and `app_prod`. Executing them verbatim on a\n * connection whose default database is something else lands the migration in\n * that other database, which is why the target is selected here — on the one\n * connection that runs the artifact, immediately before it, every time, never\n * once for the session. A manual artifact is allowed to issue its own `USE`\n * precisely because the next artifact re-selects the target anyway.\n *\n * The identifier is quoted with the migration driver's own quoter, and the name\n * itself passed the ASCII database-name grammar at driver construction.\n */\nexport function mysqlSelectTargetStatement(\n namespace: string,\n quoteIdentifier: (name: string) => string\n): string {\n return `USE ${quoteIdentifier(namespace)}`;\n}\n\nconst MYSQL_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)/;\n\n/**\n * PROVES this pinned session fails on an out-of-range value instead of\n * truncating it (plan 3.3), once per session, before any statement it\n * protects: outside a strict mode MySQL stores an overflowing `DECIMAL`\n * clamped, with a warning (measured on 8.4), and migration work runs DDL and\n * manual artifacts outside the ORM's guarded assignments. CHECK constraints\n * must be enforced too (MySQL 8.0.16+).\n */\nexport async function proveMySQLExactValueSession(\n read: CatalogRead,\n estate: string\n): Promise<void> {\n const { rows } = await read<unknown>(\n \"SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version\"\n );\n const row = rows[0];\n const mode: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"sql_mode\")\n : undefined;\n const declared = typeof mode === \"string\" ? mode : \"\";\n const serverVersion: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"server_version\")\n : undefined;\n const renderedVersion =\n typeof serverVersion === \"string\" ? serverVersion : \"<unreported>\";\n if (!supportsEnforcedMySQLChecks(renderedVersion)) {\n throw new MigrationError(\n `This MySQL migration session reports version \"${renderedVersion}\". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"unenforced-check-constraints\",\n target: estate,\n },\n }\n );\n }\n const hasStrictMode = declared.split(\",\").some((mode) => {\n const token = mode.trim();\n return token === \"STRICT_TRANS_TABLES\" || token === \"STRICT_ALL_TABLES\";\n });\n if (hasStrictMode) {\n return;\n }\n throw new MigrationError(\n `This MySQL session runs in sql_mode \"${declared}\", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. ` +\n \"Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"non-strict-sql-mode\",\n target: estate,\n },\n }\n );\n}\n\n/** MySQL began enforcing CHECK constraints in 8.0.16. */\nfunction supportsEnforcedMySQLChecks(version: string): boolean {\n if (version.toLowerCase().includes(\"mariadb\")) {\n return false;\n }\n const match = MYSQL_VERSION.exec(version);\n if (match === null) {\n return false;\n }\n const major = Number(match[1]);\n const minor = Number(match[2]);\n const patch = Number(match[3]);\n return major > 8 || (major === 8 && (minor > 0 || patch >= 16));\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\n/**\n * MySQL Migration Driver\n *\n * Implements the MigrationDriver interface for MySQL databases.\n * Supports all DDL operations natively with MySQL-specific syntax.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { renderQualifiedIdentifier } from \"../../../sql/identifiers\";\nimport {\n decimalConversionConstraintName,\n decimalConversionRequired,\n describeDecimalDomain,\n describeDecimalStorageKind,\n mysqlDecimalFitsCheck,\n mysqlDecimalListFitsCheck,\n mysqlDecimalListMarker,\n mysqlDecimalStorageKind,\n} from \"../../decimal\";\nimport type {\n ColumnDef,\n DiffOperation,\n ForeignKeyDef,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\n\n// Regex patterns for spatial type detection\nconst SPATIAL_TYPE_PATTERNS = [\n /^GEOMETRY\\b/,\n /^POINT\\b/,\n /^LINESTRING\\b/,\n /^POLYGON\\b/,\n /^MULTIPOINT\\b/,\n /^MULTILINESTRING\\b/,\n /^MULTIPOLYGON\\b/,\n /^GEOMETRYCOLLECTION\\b/,\n] as const;\n\n// Regex pattern for extracting base type from column type string\n// e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\"\nconst UNINDEXABLE_ORDINARY_TYPE =\n /^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\\b/i;\nconst BASE_TYPE_PATTERN = /[\\s(]/;\n\nfunction classifyDecimalListDescriptorChange(\n source: NonNullable<ColumnDef[\"decimal\"]>,\n target: NonNullable<ColumnDef[\"decimal\"]>\n): \"same\" | \"widening\" | \"narrowing\" | \"rescaling\" {\n if (source.scale !== target.scale) return \"rescaling\";\n if (source.precision < target.precision) return \"widening\";\n if (source.precision > target.precision) return \"narrowing\";\n return \"same\";\n}\n\nimport type { CatalogRead, CommandNamespaceResolver } from \"../../target\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DerivedRename,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport {\n getMySQLType,\n MYSQL_TYPE_DEFAULTS,\n mysqlEnumType,\n mysqlStringLiteral,\n} from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport { planInterruptedMySQLDecimalRecovery } from \"./decimal-recovery\";\nimport { introspect as introspectMySQL } from \"./introspect\";\nimport {\n mysqlAcquireLockStatement,\n mysqlLockAnswer,\n mysqlReleaseLockStatement,\n mysqlSelectTargetStatement,\n proveMySQLExactValueSession,\n} from \"./pinned-session\";\n\nconst MYSQL_POINT_ATTRIBUTE_START = MYSQL_TYPE_DEFAULTS.point.indexOf(\" \");\nconst MYSQL_POINT_BASE_TYPE = MYSQL_TYPE_DEFAULTS.point.slice(\n 0,\n MYSQL_POINT_ATTRIBUTE_START\n);\nconst MYSQL_POINT_SRID_ATTRIBUTE = MYSQL_TYPE_DEFAULTS.point.slice(\n MYSQL_POINT_ATTRIBUTE_START + 1\n);\n\n/**\n * `GET_LOCK`'s wait bound. A migration command that cannot take the lock within\n * this window reports `MIGRATION_LOCK_FAILED` instead of waiting forever;\n * PostgreSQL's `pg_advisory_lock` blocks by contrast, which is its own\n * documented behaviour.\n */\nconst MIGRATION_LOCK_TIMEOUT_SECONDS = 30;\n\n/**\n * The storage classes MySQL refuses a literal `DEFAULT` on. Its own error names\n * them: \"BLOB, TEXT, GEOMETRY or JSON column can't have a default value\"\n * (errno 1101, measured on MySQL 8.4 under `STRICT_TRANS_TABLES`). MySQL 8.0.13\n * gave exactly those four an EXPRESSION default instead — `DEFAULT ('value')` —\n * which is the spelling the JSON decimal-list container already used, so it is\n * the one spelling for all four.\n */\nfunction mysqlRefusesLiteralDefault(columnType: string): boolean {\n const upper = columnType.toUpperCase();\n return (\n upper.includes(\"TEXT\") ||\n upper.includes(\"BLOB\") ||\n upper.includes(\"JSON\") ||\n SPATIAL_TYPE_PATTERNS.some((pattern) => pattern.test(upper))\n );\n}\n\n/**\n * A MySQL temporal type, with the fractional-seconds precision it declares.\n */\nconst MYSQL_TIMESTAMP_TYPE = /^(?:DATETIME|TIMESTAMP)\\s*(?:\\((\\d+)\\))?$/i;\n\n/**\n * `CURRENT_TIMESTAMP` as the RESOLVED column type takes it, or `undefined` for\n * a type that takes no such default at all.\n *\n * MySQL requires the expression's precision to AGREE with the column's:\n * `DATETIME(3) DEFAULT CURRENT_TIMESTAMP` is errno 1067, ER_INVALID_DEFAULT\n * (measured on 8.4.11), and `DATETIME(3)` is what `.dateTime()` resolves to\n * unless a native type says otherwise — so a declared `.now()` could not be\n * pushed to MySQL at all. The precision is READ OFF the type this driver just\n * mapped instead of being restated as a constant here, which is the same\n * reason a resolved DATE or TIME carries no database default rather than an\n * expression MySQL refuses.\n */\nfunction mysqlNowExpression(columnType: string): string | undefined {\n const precision = MYSQL_TIMESTAMP_TYPE.exec(columnType.trim());\n if (precision === null) {\n return undefined;\n }\n return precision[1] === undefined\n ? \"CURRENT_TIMESTAMP\"\n : `CURRENT_TIMESTAMP(${precision[1]})`;\n}\n\n/**\n * One column, as MySQL will hold and report it.\n *\n * Both rewrites belong to the same moment — after this, the desired snapshot\n * and the live one are comparable — and both are MySQL facts, not schema\n * decisions: a keyed TEXT column has to carry a key length, and a default on a\n * storage class that refuses a literal is carried as an expression. Leaving\n * the second one to the DDL emitter is what silently DROPPED the declared\n * default: the estate asked for one, the emitter wrote none, and the final\n * push attestation reported the column it did not get.\n */\nfunction finalizeMySQLColumn(column: ColumnDef, keyed: boolean): ColumnDef {\n const type =\n column.type.toUpperCase() === \"TEXT\" && keyed\n ? \"VARCHAR(191)\"\n : column.type;\n const spelled =\n column.default !== undefined && mysqlRefusesLiteralDefault(type)\n ? `(${column.default})`\n : column.default;\n return type === column.type && spelled === column.default\n ? column\n : { ...column, type, default: spelled };\n}\n\n/** Exact integer storage that can be adopted without inventing a source scale. */\nfunction isMySQLExactIntegerType(type: string): boolean {\n const base = type.trim().toUpperCase().split(BASE_TYPE_PATTERN, 1)[0];\n return base === \"INT\" || base === \"INTEGER\" || base === \"BIGINT\";\n}\nexport class MySQLMigrationDriver\n extends MigrationDriver\n implements CommandNamespaceResolver\n{\n readonly dialect = \"mysql\" as const;\n readonly driverName = \"mysql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true, // MySQL has inline ENUM type\n supportsAddEnumValueInTransaction: false, // MODIFY COLUMN is DDL and causes implicit commit\n supportsIndexTypes: [\"btree\", \"fulltext\", \"spatial\"], // InnoDB does not support user-defined HASH indexes\n supportsNativeArrays: false, // Use JSON instead\n supportsAddForeignKeyViaAlter: true, // ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY\n // `information_schema` reports the declared `CONSTRAINT_NAME`.\n introspectionReadsConstraintNames: true,\n };\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (operation.type !== \"alterColumn\") return undefined;\n const source = operation.from.decimal;\n const target = operation.to.decimal;\n if (\n source === undefined ||\n target === undefined ||\n mysqlDecimalStorageKind(operation.from) !== \"list\" ||\n mysqlDecimalStorageKind(operation.to) !== \"list\" ||\n classifyDecimalListDescriptorChange(source, target) !== \"narrowing\"\n ) {\n return undefined;\n }\n return (\n \"MySQL cannot automatically roll back the decimal-list widening of \" +\n `\"${operation.tableName}\".\"${operation.columnName}\": the inverse narrows ` +\n `${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, and ` +\n \"its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.\"\n );\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Reads the live catalog for the database THIS driver is bound to.\n *\n * The namespace travels as an argument rather than being read from the\n * connection, so an ambient default database — a pooled session, a proxy, a\n * URL path nobody re-read — can never decide which estate is introspected.\n */\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: CatalogReader\n ): Promise<boolean> {\n const names = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n );\n if (names.size === 0) return false;\n const namespace = await resolveCatalogNamespace(executeRaw, this.namespace);\n const views = await executeRaw<{ TABLE_NAME: string }>(\n \"SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?\",\n [namespace]\n );\n const collision = views.rows.find((row) => names.has(row.TABLE_NAME));\n if (collision)\n throw new MigrationError(\n `MySQL relation \"${collision.TABLE_NAME}\" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.TABLE_NAME, feature: \"view\", namespace } }\n );\n return false;\n }\n\n introspect(executeRaw: CatalogReader): Promise<SchemaSnapshot> {\n return introspectMySQL(executeRaw, this.namespace, this.target?.tables);\n }\n\n // ===========================================================================\n // IDENTIFIER ESCAPING (MySQL uses backticks)\n // ===========================================================================\n\n /**\n * A string value, spelled the way MySQL reads it back.\n *\n * The base doubles `'` and leaves everything else alone, which is right\n * where a backslash is an ordinary character. MySQL reads it as an escape\n * introducer, so that spelling silently changed the value it carried —\n * `DEFAULT ('a\\b')` created a column holding a BACKSPACE, measured. One\n * spelling serves both snapshot producers (`mysqlStringLiteral`).\n */\n override escapeValue(value: string | null | undefined): string {\n return value == null ? \"NULL\" : mysqlStringLiteral(String(value));\n }\n\n override escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\\`${String(name).replace(/`/g, \"``\")}\\``;\n }\n\n /**\n * THE table-position renderer (§5.1).\n *\n * A `\"live\"` statement names `` `database`.`table` `` so it reaches the bound\n * database whatever the connection's own default is; an `\"artifact\"`\n * statement names the table relative so ONE generated MySQL estate deploys to\n * `app_dev`, `app_test` and `app_prod` unchanged (§13 rejects embedded\n * database names in stored artifacts).\n *\n * An unbound driver has no database to name, so both destinations render the\n * bare table and unbound MySQL output stays byte-identical (§12.21). The\n * database and the object are quoted SEPARATELY, through the one\n * qualification primitive: handing `database.table` to `escapeIdentifier`\n * would silently produce one identifier naming a table with a dot in it.\n */\n protected override tableRef(\n tableName: string,\n destination: DDLContext[\"destination\"]\n ): string {\n return renderQualifiedIdentifier(\n (name) => this.escapeIdentifier(name),\n destination === \"live\" ? this.namespace : undefined,\n tableName\n );\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // See the PostgreSQL driver: one storage owner, override included.\n const idStorage =\n idDomain === undefined || scalarState.array === true\n ? undefined\n : idStorageOf(idDomain, declaration, \"mysql\");\n if (idStorage) return idStorage.columnType;\n\n // MySQL has no native list type. A native declaration can describe one\n // scalar member only; every list keeps the JSON container below.\n const nativeType = nativeTypeFor(declaration, \"mysql\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getMySQLType({\n type: scalarState.type,\n array: scalarState.array,\n decimal: scalarState.decimal,\n });\n }\n\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n const literal =\n scalarState.type === \"datetime\" &&\n !scalarState.array &&\n scalarState.hasDefault &&\n !scalarState.autoGenerate\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n !scalarState.array &&\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n typeof literal === \"string\"\n )\n return this.escapeValue(encodeMySqlDateTime(literal));\n // information_schema.COLUMNS reports both an omitted default and an\n // explicit DEFAULT NULL as catalog NULL. They have the same behavior for a\n // nullable column, so serialize the one representation MySQL can read back\n // instead of manufacturing an alterColumn on every later push.\n if (scalarState.hasDefault && scalarState.default === null) {\n return undefined;\n }\n // `now` is the one generator MySQL spells natively, and it is spelled from\n // the RESOLVED column type, so it is answered here — where that type is —\n // rather than by the generator hook, which is handed the declaration only.\n // (`uuid` stays application-level: MySQL 8 has `UUID()`, but not as a\n // column default.)\n if (scalarState.autoGenerate?.kind === \"now\") {\n return mysqlNowExpression(this.mapScalarType(scalar, scalarState));\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n /**\n * TWO canonicalizations, both required before the differ compares anything.\n *\n * 1. MySQL cannot index TEXT columns without an explicit key length.\n * Rewrite TEXT columns that participate in the primary key, a unique\n * constraint, an index, or a foreign key to VARCHAR(191) (Prisma's\n * default: 191 * 4 bytes fits the 767-byte InnoDB key limit).\n *\n * 2. MySQL HAS ONE UNIQUE NAMESPACE. A `UNIQUE` constraint and a unique\n * index are the same object: `information_schema.TABLE_CONSTRAINTS`\n * reports it as a UNIQUE constraint and `information_schema.STATISTICS`\n * reports its backing index, so introspection sees ONE database object\n * under TWO buckets. Whichever bucket the desired schema did not use then\n * looks like a stray object and the differ plans a drop for it — measured\n * on docker MySQL 8 as a spurious `dropIndex` for every declared unique\n * CONSTRAINT and a spurious `dropUniqueConstraint` for every declared\n * unique INDEX, on every push, forever.\n *\n * So MySQL picks ONE bucket and both sides speak it: every unique becomes\n * a unique INDEX here, and introspection (`introspect.ts`) files uniques\n * only under `indexes` to match. Indexes are the right survivor because\n * they carry the strictly larger vocabulary — a unique index can express\n * a unique constraint, not the reverse.\n *\n * Existing databases need no migration: the object already exists under\n * the name the desired side now spells as an index, so the two sides\n * simply agree. `generateCreateTable` emits nothing for the (now empty)\n * unique-constraint bucket and the index bucket is created as usual.\n */\n override finalizeTable(table: TableDef): TableDef {\n const keyedColumns = new Set<string>([\n ...(table.primaryKey?.columns ?? []),\n ...table.uniqueConstraints.flatMap((uq) => uq.columns),\n ...table.indexes.flatMap((index) => index.columns),\n ...table.foreignKeys.flatMap((fk) => fk.columns),\n ]);\n\n const declaredIndexNames = new Set(\n table.indexes.map((index) => index.name)\n );\n const uniquesAsIndexes = table.uniqueConstraints\n // A name already spelled as an index is the SAME object; keeping both\n // would put two entries under one name into the snapshot.\n .filter((unique) => !declaredIndexNames.has(unique.name))\n .map((unique) => ({\n name: unique.name,\n columns: unique.columns,\n unique: true,\n }));\n\n const finalized: TableDef = {\n ...table,\n primaryKey: table.primaryKey\n ? { ...table.primaryKey, name: \"PRIMARY\" }\n : undefined,\n columns: table.columns.map((column) =>\n finalizeMySQLColumn(column, keyedColumns.has(column.name))\n ),\n indexes: [...table.indexes, ...uniquesAsIndexes],\n uniqueConstraints: [],\n };\n const ordinary = finalized.indexes.filter(\n (index) => !index.type || index.type === \"btree\"\n );\n const keys = [\n { name: \"PRIMARY\", columns: finalized.primaryKey?.columns ?? [] },\n ...ordinary.map((index) => ({\n name: index.name,\n columns: index.columns,\n })),\n ...finalized.foreignKeys.map((key) => ({\n name: key.name,\n columns: key.columns,\n })),\n ];\n for (const { name, columns } of keys) {\n for (const nameOfColumn of columns) {\n const column = finalized.columns.find(\n (column) => column.name === nameOfColumn\n );\n if (column && UNINDEXABLE_ORDINARY_TYPE.test(column.type)) {\n throw new MigrationError(\n `MySQL key \"${table.name}.${name}\" cannot directly index ${column.type} column \"${column.name}\". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: table.name, column: column.name } }\n );\n }\n }\n }\n const increments = finalized.columns.filter(\n (column) => column.autoIncrement\n );\n if (\n increments.length > 1 ||\n increments.some(\n (column) =>\n finalized.primaryKey?.columns[0] !== column.name &&\n !ordinary.some(\n (index) => index.columns[0] === column.name && !index.where\n ) &&\n !finalized.foreignKeys.some((key) => key.columns[0] === column.name)\n )\n ) {\n throw new MigrationError(\n `MySQL table \"${table.name}\" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return finalized;\n }\n\n /**\n * MySQL uses 1/0 for boolean values (TINYINT(1)).\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n /**\n * MySQL enum values are part of the column definition.\n * Returns ENUM('val1', 'val2', ...) syntax.\n */\n getEnumColumnType(\n _tableName: string,\n _columnName: string,\n values: string[]\n ): string {\n return mysqlEnumType(values);\n }\n\n // ===========================================================================\n // HELPER METHODS\n // ===========================================================================\n\n /**\n * MySQL integer types that support AUTO_INCREMENT.\n * Includes variations with UNSIGNED modifier.\n */\n private static readonly AUTO_INCREMENT_TYPES = new Set([\n \"tinyint\",\n \"smallint\",\n \"mediumint\",\n \"int\",\n \"integer\",\n \"bigint\",\n ]);\n\n /**\n * Validates that a column type is compatible with AUTO_INCREMENT.\n * Returns true if valid, throws MigrationError if invalid.\n */\n private validateAutoIncrementType(column: ColumnDef): void {\n // Extract base type (e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\")\n const baseType = column.type.toLowerCase().split(BASE_TYPE_PATTERN)[0]!;\n\n if (!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(baseType)) {\n throw new MigrationError(\n \"MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with AUTO_INCREMENT.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n }\n\n /**\n * Generates a column definition string for MySQL.\n */\n protected override generateColumnDef(\n column: ColumnDef,\n _context: DDLContext\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n const isGeoPoint = column.type.toUpperCase() === MYSQL_TYPE_DEFAULTS.point;\n\n // Handle auto-increment (MySQL uses AUTO_INCREMENT keyword)\n if (column.autoIncrement) {\n // Validate that the column type supports AUTO_INCREMENT\n this.validateAutoIncrementType(column);\n // Preserve the original type (including modifiers like UNSIGNED)\n parts.push(column.type);\n parts.push(\"AUTO_INCREMENT\");\n } else {\n parts.push(isGeoPoint ? MYSQL_POINT_BASE_TYPE : column.type);\n }\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // MySQL's grammar places the SRID attribute after nullability:\n // `POINT NOT NULL SRID 4326`, not `POINT SRID 4326 NOT NULL`.\n if (isGeoPoint) {\n parts.push(MYSQL_POINT_SRID_ATTRIBUTE);\n }\n\n // DEFAULT clause (an auto-increment column has no default to spell).\n // `finalizeMySQLColumn` already spelled a default whose storage class\n // refuses a literal as MySQL's expression default, so every default that\n // reaches here is one MySQL can take.\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n // The descriptor marker for a JSON-backed decimal LIST. A scalar needs\n // none — `DECIMAL(p,s)` spells its own domain — but JSON carries nothing,\n // so the comment is the only place a list's precision and scale survive\n // (§6.2). It is emitted from `generateColumnDef`, which is also what\n // `MODIFY COLUMN` renders, because MODIFY rewrites the WHOLE definition:\n // a comment this method did not re-emit would be dropped by the very\n // statement that changed the column.\n if (column.decimal && mysqlDecimalStorageKind(column) === \"list\") {\n parts.push(\n `COMMENT ${this.escapeValue(mysqlDecimalListMarker(column.decimal))}`\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const columnDefs = table.columns.map((col) =>\n this.generateColumnDef(col, context)\n );\n\n const increment = table.columns.find((column) => column.autoIncrement);\n const inlineIndex =\n increment && table.primaryKey?.columns[0] !== increment.name\n ? table.indexes.find(\n (index) =>\n (!index.type || index.type === \"btree\") &&\n !index.where &&\n index.columns[0] === increment.name\n )\n : undefined;\n if (inlineIndex)\n columnDefs.push(\n `${inlineIndex.unique ? \"UNIQUE \" : \"\"}KEY ${this.escapeIdentifier(inlineIndex.name)} (${inlineIndex.columns.map((column) => this.escapeIdentifier(column)).join(\", \")})`\n );\n\n // Primary key\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n columnDefs.push(`PRIMARY KEY (${pkCols})`);\n }\n\n // Unique constraints\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys (inline in CREATE TABLE for MySQL)\n for (const fk of table.foreignKeys) {\n columnDefs.push(this.foreignKeyClause(fk, context));\n }\n\n const sql = `CREATE TABLE ${this.tableRef(table.name, context.destination)} (\\n ${columnDefs.join(\",\\n \")}\\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`;\n\n const statements = [sql];\n\n // Indexes are created separately\n for (const idx of table.indexes) {\n if (idx === inlineIndex) continue;\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n generateDropTable(op: DropTableOperation, context: DDLContext): string {\n // MySQL doesn't have CASCADE for DROP TABLE in the same way\n // Foreign key checks need to be disabled or FKs dropped first\n return `DROP TABLE IF EXISTS ${this.tableRef(op.tableName, context.destination)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, context: DDLContext): string {\n // BOTH sides carry the database (§5.1): `RENAME TABLE a TO b` names two\n // independent tables, and an unqualified destination would move the table\n // into the connection's default database instead of renaming it in place.\n return `RENAME TABLE ${this.tableRef(op.from, context.destination)} TO ${this.tableRef(op.to, context.destination)}`;\n }\n\n // An index or unique (one object here) is renamed in place. A foreign key\n // cannot be: it is dropped and added under its new name in the same\n // statement, so the key is never absent.\n protected override renameDerivedNames(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>,\n table: TableDef,\n context: DDLContext\n ): string[] {\n const clauses = [...renames].map(([from, { to }]) => {\n const key = table.foreignKeys.find((item) => item.name === from);\n return key\n ? `DROP FOREIGN KEY ${this.escapeIdentifier(from)}, ADD ${this.foreignKeyClause({ ...key, name: to }, context)}`\n : `RENAME INDEX ${this.escapeIdentifier(from)} TO ${this.escapeIdentifier(to)}`;\n });\n return [\n `ALTER TABLE ${this.tableRef(owner, context.destination)} ${clauses.join(\", \")}`,\n ];\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation, context: DDLContext): string {\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, context: DDLContext): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(op: RenameColumnOperation, context: DDLContext): string {\n // MySQL 8.0+ supports RENAME COLUMN. Column names stay ONE identifier —\n // only the table position carries the database (§5.1).\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const { tableName, columnName, to } = op;\n const table = this.tableRef(tableName, context.destination);\n\n // Build the new column definition\n const colDef = this.generateColumnDef(to, context);\n\n const alter =\n // If column name changed, use CHANGE COLUMN (which handles rename + alter)\n columnName === to.name\n ? `ALTER TABLE ${table} MODIFY COLUMN ${colDef}`\n : `ALTER TABLE ${table} CHANGE COLUMN ${this.escapeIdentifier(columnName)} ${colDef}`;\n\n const bracket = this.decimalConversionBracket(op, table, context);\n return bracket === null\n ? [alter]\n : [bracket.validate, alter, bracket.release];\n }\n\n /**\n * The proof a decimal conversion runs inside, or `null` when the alteration\n * moves no stored decimal value.\n *\n * MySQL commits each DDL statement as it runs, so there is no transaction to\n * take a bad conversion back — the refusal has to happen BEFORE the column\n * moves. The CHECK constraint is that proof: adding it fails the ALTER when\n * any existing row would not survive the target domain, and it does so\n * whatever `sql_mode` is set to, which a bare `MODIFY COLUMN` does not — in a\n * non-strict mode MySQL answers an out-of-range or over-scaled conversion\n * with a warning and a truncated value, silently rewriting stored data.\n * That mode-independence is the constraint's whole reason to exist beside the\n * MODIFY that would also refuse in strict mode.\n *\n * It is DROPPED only after the alteration, not before it: while it stands, no\n * concurrent write can land a value the target domain would have to round.\n * That is how §7.4's \"while writes are excluded\" is spelled here, because the\n * obvious spelling — `LOCK TABLES` — is a transaction leader the artifact\n * classifier refuses, and growing that enumeration is forbidden.\n */\n private decimalConversionBracket(\n op: AlterColumnOperation,\n table: string,\n context: DDLContext\n ): { validate: string; release: string } | null {\n const { from, to } = op;\n const source = from.decimal;\n const target = to.decimal;\n if (target === undefined) return null;\n if (!decimalConversionRequired(from, to)) return null;\n if (op.columnName !== to.name) {\n throw new MigrationError(\n `The MySQL decimal conversion for \"${op.tableName}\".\"${op.columnName}\" also renames the column to \"${to.name}\". ` +\n \"Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: op.tableName,\n column: op.columnName,\n type: \"decimal-conversion-with-rename\",\n },\n }\n );\n }\n\n const targetKind = mysqlDecimalStorageKind(to);\n if (source === undefined) {\n // An unmarked JSON container has no proven descriptor and therefore no\n // proven member scale. A scalar INT/BIGINT is different: its exact\n // logical meaning is an integer at scale zero, and the transient CHECK\n // can prove that every one survives the target domain unchanged.\n if (targetKind !== \"scalar\" || !isMySQLExactIntegerType(from.type)) {\n this.refuseDecimalAdoption(op, context, targetKind);\n }\n return this.decimalScalarConversionBracket(op, table, to.type, target);\n }\n\n const sourceKind = mysqlDecimalStorageKind(from);\n if (targetKind === undefined || sourceKind !== targetKind) {\n this.refuseDecimalConversion(\n op,\n context,\n `moves it from ${describeDecimalStorageKind(sourceKind)} to ${describeDecimalStorageKind(targetKind)} storage, which`\n );\n }\n if (targetKind === \"list\") {\n // The coefficient spelling stays exact only while scale stands still.\n // Widening then moves no member, but it still needs a live proof that\n // malformed or out-of-source-domain storage cannot acquire a wider\n // descriptor marker. Narrowing is deliberately refused: MySQL's\n // implicit DDL commits cannot make its stricter proof, marker change,\n // and cleanup one indivisible operation.\n const change = classifyDecimalListDescriptorChange(source, target);\n if (change === \"rescaling\") {\n this.refuseDecimalConversion(\n op,\n context,\n `moves its JSON list from ${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, which rescales every member and so`\n );\n }\n if (change === \"narrowing\") {\n this.refuseDecimalConversion(\n op,\n context,\n `narrows its JSON list from ${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, which`\n );\n }\n return this.decimalListConversionBracket(op, table, source);\n }\n return this.decimalScalarConversionBracket(op, table, to.type, target);\n }\n\n private decimalListConversionBracket(\n op: AlterColumnOperation,\n table: string,\n narrower: NonNullable<ColumnDef[\"decimal\"]>\n ): { validate: string; release: string } {\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\"list\", narrower)\n );\n const col = this.escapeIdentifier(op.columnName);\n return {\n validate: `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${mysqlDecimalListFitsCheck(col, narrower)})`,\n release: `ALTER TABLE ${table} DROP CHECK ${constraint}`,\n };\n }\n\n private decimalScalarConversionBracket(\n op: AlterColumnOperation,\n table: string,\n targetType: string,\n target: NonNullable<ColumnDef[\"decimal\"]>\n ): { validate: string; release: string } {\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\"scalar\", target)\n );\n const col = this.escapeIdentifier(op.columnName);\n return {\n validate: `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${mysqlDecimalFitsCheck(col, targetType)})`,\n release: `ALTER TABLE ${table} DROP CHECK ${constraint}`,\n };\n }\n\n /** Refuse an adoption whose source has no exact, descriptor-free meaning. */\n private refuseDecimalAdoption(\n op: AlterColumnOperation,\n context: DDLContext,\n targetKind: ReturnType<typeof mysqlDecimalStorageKind>\n ): never {\n throw new MigrationError(\n `The declared change to \"${op.tableName}\".\"${op.columnName}\" would adopt unmarked ${op.from.type} storage as a fixed-decimal ${describeDecimalStorageKind(targetKind)}. ` +\n \"Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. \" +\n \"The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: op.tableName,\n column: op.columnName,\n feature: \"decimal storage adoption\",\n dialect: \"mysql\",\n target: context.destination,\n },\n }\n );\n }\n\n /**\n * Refuses a decimal conversion MySQL cannot perform without either rounding\n * stored values or leaving them half-converted.\n *\n * The unsafe case is always a REWRITE of stored bytes: a JSON list whose\n * members must be rescaled, or a column moving between the scalar and list\n * shapes. Same-scale precision widening needs only a proof and uses the\n * normalized-container CHECK above. Narrowing or changing scale cannot make\n * its stricter proof or member rewrite plus descriptor-marker DDL\n * indivisible across MySQL's implicit commits. It therefore refuses before\n * any statement runs; PostgreSQL and the SQLite family convert the same\n * change inside their atomic provider boundary.\n */\n private refuseDecimalConversion(\n op: AlterColumnOperation,\n context: DDLContext,\n reason: string\n ): never {\n throw new MigrationError(\n `The declared change to \"${op.tableName}\".\"${op.columnName}\" ${reason} would rewrite every stored value, and MySQL commits each DDL statement implicitly. ` +\n \"There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. \" +\n \"The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: op.tableName,\n column: op.columnName,\n feature: \"decimal descriptor conversion\",\n dialect: \"mysql\",\n target: context.destination,\n },\n }\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, context: DDLContext): string {\n const { tableName, index } = op;\n\n // Validate index type\n this.validateIndexType(index.type, index.name);\n\n // MySQL has no partial index. Emitting the index without its predicate\n // would build a different index from the declared one and would index rows\n // the schema excluded, so refuse the declaration instead of dropping it.\n if (index.where) {\n throw new MigrationError(\n `Index \"${index.name}\" declares a partial index predicate (where: \"${index.where}\"). ` +\n \"MySQL does not support partial indexes. \" +\n \"Either remove 'where' from the index definition, or move the predicate into a generated column and index that.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name, indexWhere: index.where } }\n );\n }\n\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n\n // MySQL index type syntax varies by type:\n // - FULLTEXT and SPATIAL are prefixes: CREATE FULLTEXT INDEX ...\n // - BTREE is default, no clause needed\n // Note: HASH indexes are not supported by InnoDB (only MEMORY engine supports them)\n let indexPrefix = \"\";\n\n if (index.type === \"fulltext\") {\n indexPrefix = \"FULLTEXT \";\n } else if (index.type === \"spatial\") {\n indexPrefix = \"SPATIAL \";\n }\n // btree is default, no prefix needed\n\n // UNIQUE cannot be combined with FULLTEXT or SPATIAL in MySQL\n if (index.unique && indexPrefix) {\n throw new MigrationError(\n `Cannot combine UNIQUE with ${index.type?.toUpperCase()} index \"${index.name}\". ` +\n `MySQL does not support UNIQUE ${index.type?.toUpperCase()} indexes. ` +\n `Either remove 'unique: true' from the index definition, or create a separate unique index.`,\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { indexName: index.name, indexType: index.type } }\n );\n }\n const unique = index.unique ? \"UNIQUE \" : \"\";\n\n // The index NAME stays one identifier; the table it is built on carries the\n // database (§5.1).\n return `CREATE ${unique}${indexPrefix}INDEX ${this.escapeIdentifier(index.name)} ON ${this.tableRef(tableName, context.destination)} (${cols})`;\n }\n\n generateDropIndex(op: DropIndexOperation, context: DDLContext): string {\n // MySQL DROP INDEX requires ON tableName syntax, and that table position is\n // the one that carries the database — the index name stays bare (§5.1).\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)} ON ${this.tableRef(op.tableName, context.destination)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} ADD ${this.foreignKeyClause(op.fk, context)}`;\n }\n\n private foreignKeyClause(fk: ForeignKeyDef, context: DDLContext): string {\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n let sql = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n sql += `FOREIGN KEY (${cols}) `;\n sql += `REFERENCES ${this.tableRef(fk.referencedTable, context.destination)} (${refCols})`;\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n sql += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n sql += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n return sql;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.tableRef(tableName, context.destination)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): string {\n // MySQL uses DROP INDEX for unique constraints\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP INDEX ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.tableRef(tableName, context.destination)} ADD PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): string {\n // MySQL doesn't name primary keys in DROP\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP PRIMARY KEY`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // MySQL doesn't have standalone enum types - they're part of column defs\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // MySQL enums are inline with column definitions\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateDropEnum(_op: DropEnumOperation, _context: DDLContext): string {\n // No standalone enum to drop\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n // To alter an enum in MySQL, we need to MODIFY COLUMN for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n\n if (!newValues || newValues.length === 0) {\n return [`-- MySQL: no new values provided for enum \"${enumName}\"`];\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return [`-- MySQL: no dependent columns found for enum \"${enumName}\"`];\n }\n\n const statements: string[] = [];\n const enumType = this.getEnumColumnType(\"\", \"\", newValues);\n\n // Migrate rows off removed values before MODIFY COLUMN — with rows still\n // holding a removed value, MODIFY errors in strict mode. Replacement\n // targets must already exist in the old enum (surviving values or NULL);\n // mapping to a value added in the same alter is not supported.\n statements.push(...this.buildEnumReplacementUpdates(op, context));\n\n for (const dep of dependentColumns) {\n const currentTable = context.currentSchema?.tables.find(\n (t) => t.name === dep.tableName\n );\n const column = currentTable?.columns.find(\n (c) => c.name === dep.columnName\n );\n\n if (!column) {\n statements.push(\n `-- MySQL: column \"${dep.columnName}\" not found in table \"${dep.tableName}\"`\n );\n continue;\n }\n\n const table = this.tableRef(dep.tableName, context.destination);\n const col = this.escapeIdentifier(dep.columnName);\n const nullable = column.nullable ? \"\" : \" NOT NULL\";\n const defaultVal =\n column.default !== undefined ? ` DEFAULT ${column.default}` : \"\";\n\n statements.push(\n `ALTER TABLE ${table} MODIFY COLUMN ${col} ${enumType}${nullable}${defaultVal}`\n );\n }\n\n return statements;\n }\n\n /**\n * Proves the configured database exists (§5.2).\n *\n * The proof IS the resolution ({@link resolveCommandNamespace}), and no\n * migration command reaches this arm: the shared owner asks a dialect that\n * answers a spelling for that spelling instead, so `status()`, `log()`\n * and a dry push all keep the answer rather than discarding it here. The\n * override remains because the base class's proof is part of the dialect\n * contract and its default answers \"nothing to prove\", which is false for a\n * dialect whose estates are database-relative — an unlocked caller that only\n * wants the fact must not get a silent yes.\n */\n override async proveNamespaceExists(\n executeRaw: CatalogReader\n ): Promise<void> {\n await this.resolveCommandNamespace(executeRaw);\n }\n\n /**\n * Proves the configured database exists and answers the SERVER's spelling of\n * it, for the length of one command (§5.2).\n *\n * ONE `information_schema.SCHEMATA` read, with the configured name BOUND as\n * data. `DATABASE()` would answer with the connection's ambient default, and\n * an inference is exactly what this proof exists to remove: it would report\n * an existing sibling database as proof that the configured one is there.\n *\n * The answer matters because the read is deliberately case-insensitive:\n * `lower_case_table_names` can make a differently cased configured value name\n * the same physical database, so one case-folded candidate is accepted (see\n * `catalog.ts`). Under that acceptance the configured spelling is NOT what\n * the server has — `USE` fails on it, `TABLE_SCHEMA = ?` matches nothing, and\n * a reset inventory that binds it reports an existing database as empty. The\n * command-driver owner therefore binds this spelling onto the command's\n * driver view — for locked and read-only commands alike — and every statement\n * below renders from it.\n */\n async resolveCommandNamespace(read: CatalogRead): Promise<string> {\n return await resolveCatalogNamespace(read, this.namespace);\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * MySQL named locks are per-SERVER, not per-database, so a single global name\n * would serialize every database on the instance and a per-connection name\n * would serialize none. The name is derived from the configured database\n * (`mysqlMigrationLockName`), which is also why an unbound driver has no lock\n * to take: there is no scope to name.\n *\n * `lockId` is deliberately unused. It was the whole identity before; keeping\n * it in the name would only add a constant, and the scope that matters is the\n * database.\n */\n generateAcquireLock(_lockId: number): string | null {\n return mysqlAcquireLockStatement(\n this.requireLockScope(),\n MIGRATION_LOCK_TIMEOUT_SECONDS,\n (value) => this.escapeValue(value)\n );\n }\n\n generateReleaseLock(_lockId: number): string | null {\n return mysqlReleaseLockStatement(this.requireLockScope(), (value) =>\n this.escapeValue(value)\n );\n }\n\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"acquired\");\n }\n\n override provesLockReleased(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"released\");\n }\n\n /**\n * The one admitted `USE`, spelled by the pinned-session owner (§13). It is\n * reachable only from a pinned migration session, which destroys its\n * connection afterwards, so the selection cannot leak into pooled traffic.\n *\n * On the command's own driver view `this.namespace` is the spelling the\n * SERVER answered with, which is the only one `USE` is guaranteed to accept:\n * on a case-sensitive server the configured `ProbeCase` is not the existing\n * `probecase`, and selecting it is a raw `Unknown database` error after a\n * proof that just admitted the database.\n */\n override generateSelectTarget(): string | null {\n if (this.namespace === undefined) {\n return null;\n }\n return mysqlSelectTargetStatement(this.namespace, (name) =>\n this.escapeIdentifier(name)\n );\n }\n\n /**\n * Proves the session's strict exact-value mode, then binds the command to\n * its ONE interrupted decimal-conversion recovery: planned by its first\n * sequential program (after apply has read its journal), empty for later\n * ones, and left untaken when the plan's own proof fails.\n */\n override async proveSession(read: CatalogRead): Promise<this> {\n await proveMySQLExactValueSession(\n read,\n `database \"${this.namespace ?? \"(unbound)\"}\"`\n );\n const namespace = this.requireLockScope();\n let taken = false;\n let planned: Promise<readonly string[]> | undefined;\n const command: this = Object.create(this);\n Object.defineProperty(command, \"programPreamble\", {\n value: async (producer: AnyDriver): Promise<readonly string[]> => {\n if (taken) return [];\n if (planned !== undefined) {\n await planned;\n return [];\n }\n planned = planInterruptedMySQLDecimalRecovery(\n (sql, params) => producer._executeRaw(sql, params),\n namespace,\n (name) => this.escapeIdentifier(name)\n );\n try {\n const statements = await planned;\n taken = true;\n return statements;\n } catch (error) {\n planned = undefined;\n throw error;\n }\n },\n });\n Object.freeze(command);\n return command;\n }\n\n /** A program no locked command bound has no recovery scope to run under. */\n override programPreamble(): Promise<readonly string[]> {\n return Promise.reject(\n new MigrationError(\n \"This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-migration-command\" } }\n )\n );\n }\n\n /**\n * The database whose migrations this lock serializes.\n *\n * An unbound driver is refused rather than falling back to a server-wide\n * name: a lock that covers every database on the instance is not this\n * estate's lock, and one that covers none protects nothing. No admitted path\n * reaches here unbound — the admission owner gates every locking command on\n * the resolved namespace first.\n */\n private requireLockScope(): string {\n if (this.namespace === undefined) {\n throw new MigrationError(\n \"This MySQL migration driver is not bound to a database, so there is no lock scope to name. \" +\n \"A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n return this.namespace;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The reset inventory, filtered on the bound database.\n *\n * `DATABASE()` had to go: with a connection whose default database is not the\n * configured one, it inventories — and therefore drops — a database this\n * client never targeted.\n *\n * The bound name is the command's own spelling (§5.2): `information_schema`\n * rows carry the server's, so binding a case-folded configured spelling here\n * matches nothing and reports an existing database as empty — an inventory\n * that decides what a reset DROPS cannot be answered by the wrong catalog.\n *\n * An unbound driver REFUSES rather than rendering a statement (plan §14,\n * 2026-08-27 — the one declared exception to §12.21's unbound byte-freeze).\n * There is no third option worth having: the baseline `DATABASE()` form is\n * the ambient target this feature exists to remove, and `= NULL` matches\n * nothing, so `reset` would inventory nothing, drop nothing, and report\n * success over a database it never looked at. No admitted command path\n * reaches here unbound — every caller is an effectful command the admission\n * owner has already gated — so this is what an unreachable arm does when it\n * is reached anyway.\n */\n generateInventoryTables(): { sql: string; params: unknown[] } {\n if (this.namespace === undefined) {\n throw new MigrationError(\n \"This MySQL migration driver is not bound to a database, so there is no table inventory to read. \" +\n \"VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n return {\n sql: \"SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME\",\n params: [this.namespace],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // MySQL doesn't have standalone enum types\n return null;\n }\n}\n\n// Export singleton instance\nexport const mysqlMigrationDriver = new MySQLMigrationDriver();\n"],"mappings":"6oBAgBA,MAAM,cAAiB,IAAuB,CAC5C,QAAS,QACT,YACD,EAsED,eAAsB,wBACpB,EACA,EACiB,CACjB,GAAI,IAAc,IAAA,GAChB,MAAM,IAAI,EACR,wPAEA,EAAgB,wBAChB,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,mBAAoB,CAAE,CACzD,CAGH,GAAM,CAAE,QAAS,MAAM,EAAwB;;;;;EAAgB,CAAC,EAAU,CAAC,CAOrE,EAAa,EAChB,IAAK,GAAQ,EAAI,YAAY,CAC7B,OAAQ,GAAyB,OAAO,GAAS,SAAS,CAE7D,GAAI,EAAW,SAAW,EACxB,MAAM,IAAI,EACR,uBAAuB,EAAU,wLAEjC,EAAgB,wBAChB,CAAE,KAAM,CAAE,GAAG,cAAc,EAAU,CAAE,KAAM,mBAAoB,CAAE,CACpE,CAGH,IAAM,EAAQ,EAAW,KAAM,GAAc,IAAc,EAAU,CACr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,IAAY,IAAA,GAEd,OADA,MAAM,EACC,EAAE,CAEX,EAAU,qCACP,EAAK,IAAW,EAAS,YAAY,EAAK,EAAO,CAClD,EACC,GAAS,KAAK,iBAAiB,EAAK,CACtC,CACD,GAAI,CACF,IAAM,EAAa,MAAM,EAEzB,MADA,GAAQ,GACD,QACA,EAAO,CAEd,KADA,GAAU,IAAA,GACJ,IAGX,CAAC,CACF,OAAO,OAAO,EAAQ,CACf,EAIT,iBAAuD,CACrD,OAAO,QAAQ,OACb,IAAI,EACF,uGACA,EAAgB,wBAChB,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,4BAA6B,CAAE,CAClE,CACF,CAYH,kBAAmC,CACjC,GAAI,KAAK,YAAc,IAAA,GACrB,MAAM,IAAI,EACR,iTAEA,EAAgB,wBAChB,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,mBAAoB,CAAE,CACzD,CAEH,OAAO,KAAK,UA6Bd,yBAA8D,CAC5D,GAAI,KAAK,YAAc,IAAA,GACrB,MAAM,IAAI,EACR,oUAEA,EAAgB,wBAChB,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,mBAAoB,CAAE,CACzD,CAEH,MAAO,CACL,IAAK,oIACL,OAAQ,CAAC,KAAK,UAAU,CACzB,CAGH,wBAAoE,CAElE,OAAO"}
|
|
1
|
+
{"version":3,"file":"mysql-fJlFIW7m.mjs","names":["COLUMNS_QUERY","mode","introspectMySQL","column"],"sources":["../src/migrations/drivers/mysql/catalog.ts","../src/migrations/drivers/mysql/decimal-recovery.ts","../src/migrations/drivers/mysql/introspect.ts","../src/migrations/drivers/mysql/pinned-session.ts","../src/migrations/drivers/mysql/index.ts"],"sourcesContent":["/**\n * MySQL catalog targeting (plan §5.2).\n *\n * Every MySQL migration catalog read filters on ONE exact database, and this\n * module owns which database that is. It replaces `DATABASE()`, whose answer is\n * the connection's ambient default — a fact the ORM never configured and a\n * proxy or a pooled session can change under it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\n\n/**\n * The configured database name, on the shared safe-metadata allowlist's own\n * `namespace` key (`src/errors/diagnostics.ts`). The message states which\n * database it is; this makes it readable programmatically too.\n */\nconst namespaceMeta = (namespace: string) => ({\n dialect: \"mysql\",\n namespace,\n});\n\n/**\n * The one existence proof. `SCHEMA_NAME` comes back so the caller can speak the\n * server's own spelling in later catalog filters.\n *\n * The comparison is case-insensitive because `lower_case_table_names` can make\n * a differently cased configured value name the same physical database; the\n * candidate set it produces is then resolved by the rules below, never guessed.\n */\nconst SCHEMATA_QUERY = `\nSELECT SCHEMA_NAME\nFROM information_schema.SCHEMATA\nWHERE LOWER(SCHEMA_NAME) = LOWER(?)\nORDER BY SCHEMA_NAME\n`;\n\n/**\n * One catalog row, as UNTRUSTED transport data.\n *\n * `SCHEMA_NAME` is typed `unknown` on purpose. MySQL declares the column NOT\n * NULL, but the value reaching this module has crossed a driver: a\n * serverless/HTTP MySQL transport, or any custom `_executeRaw`, can answer with\n * `null` or a number. Declaring the server's own DDL here would be a claim this\n * module cannot make, so the narrowing below makes it instead.\n */\ninterface SchemataRow {\n SCHEMA_NAME: unknown;\n}\n\n/** Executes one catalog statement with its bound values. */\nexport type CatalogReader = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * Proves the configured database exists and returns the catalog's own spelling\n * of it (§5.2).\n *\n * Three refusals, all before any snapshot, tracking or DDL effect:\n *\n * 1. no configured database — a MySQL estate is database-relative on purpose,\n * so an unbound driver has nothing to read a catalog against. Every COMMAND\n * that reaches here has already been refused by the shared live-capability\n * admission owner (`src/migrations/admission.ts`), `introspect(client)`\n * included. This arm's unique coverage is the UNBOUND REGISTERED SINGLETON,\n * which the migration layer deliberately keeps usable by name for\n * artifact-only work: `mysqlMigrationDriver.introspect(reader)` reaches this\n * reader with no client, no context and therefore no admission owner in\n * front of it. It is also what narrows the base class's optional\n * `namespace?: string` to the `string` every filter below binds, without an\n * assertion.\n * 2. no candidate row — a missing database is not an empty database, and\n * publishing an empty inventory for one would plan a full rebuild against a\n * database that does not exist.\n * 3. more than one case-only candidate and none byte-exact — the server would\n * pick one by its own collation rules; choosing for it would silently bind\n * the estate to a database the configuration never named.\n *\n * The returned spelling is command-local: it is a projection of the configured\n * target under this server's identity rules, it is never stored, and it\n * disappears with the pinned session that resolved it. Within that command it\n * is what EVERY statement naming the database renders from — the `USE`, the\n * catalog filters, the tracking table and the live DDL alike — because refusal\n * 3 has already established that only one database answers to the configured\n * name here, and the server accepts only its own spelling of it. Runtime ORM\n * SQL is outside this: it renders from the adapter's immutable configured\n * value, which nothing in this module projects.\n */\nexport async function resolveCatalogNamespace(\n executeRaw: CatalogReader,\n namespace: string | undefined\n): Promise<string> {\n if (namespace === undefined) {\n throw new MigrationError(\n \"This MySQL client's adapter declares no database, so there is no catalog to read. \" +\n \"MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n\n const { rows } = await executeRaw<SchemataRow>(SCHEMATA_QUERY, [namespace]);\n // A present-but-non-string name is the same as absent: unproven. Keeping one\n // would publish it as \"the resolved catalog spelling\", bind it into all five\n // subsequent filters, match nothing, and report an ABSENT database as an\n // empty one — the single outcome refusal 2 exists to prevent. Dropping it\n // here leaves that refusal owning the outcome. (Same doctrine as\n // `src/migrations/target.ts`'s reader of `adapter.namespace`.)\n const candidates = rows\n .map((row) => row.SCHEMA_NAME)\n .filter((name): name is string => typeof name === \"string\");\n\n if (candidates.length === 0) {\n throw new MigrationError(\n `The MySQL database \"${namespace}\" does not exist or is not visible to this connection. ` +\n \"VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { ...namespaceMeta(namespace), type: \"missing-database\" } }\n );\n }\n\n const exact = candidates.find((candidate) => candidate === namespace);\n if (exact !== undefined) {\n return exact;\n }\n\n const [folded] = candidates;\n if (candidates.length === 1 && folded !== undefined) {\n return folded;\n }\n\n throw new MigrationError(\n `The MySQL database \"${namespace}\" matches ${candidates.length} existing databases that differ only by case (${candidates.join(\", \")}). ` +\n \"Configure the exact name this server reports so migration work cannot land in the wrong one.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n ...namespaceMeta(namespace),\n type: \"ambiguous-database\",\n candidates,\n },\n }\n );\n}\n","import type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionConstraintName,\n mysqlDecimalFitsCatalogCheck,\n mysqlDecimalListFitsCatalogCheck,\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport type { CatalogRead } from \"../../target\";\n\nconst RESERVED_PREFIX = \"viborm_decimal_\";\nconst RESERVED_NAME = /^viborm_decimal_([sl])_(\\d+)_(\\d+)$/;\nconst CATALOG_CHARACTER_SET_INTRODUCER = /^_[a-zA-Z0-9]+(?=')/;\nconst WHITESPACE = /\\s/;\n\nconst CONSTRAINTS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n tc.ENFORCED,\n cc.CHECK_CLAUSE\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.CONSTRAINT_TYPE = 'CHECK'\n AND LEFT(tc.CONSTRAINT_NAME, 15) = ?\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME\n`;\n\nconst COLUMNS_QUERY = `\nSELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = ?\nORDER BY TABLE_NAME, ORDINAL_POSITION\n`;\n\ninterface ConstraintRow {\n readonly TABLE_NAME: unknown;\n readonly CONSTRAINT_NAME: unknown;\n readonly ENFORCED: unknown;\n readonly CHECK_CLAUSE: unknown;\n}\n\ninterface ColumnRow {\n readonly TABLE_NAME: unknown;\n readonly COLUMN_NAME: unknown;\n readonly DATA_TYPE: unknown;\n readonly COLUMN_COMMENT: unknown;\n}\n\ninterface ProvenConstraint {\n readonly tableName: string;\n readonly constraintName: string;\n}\n\ninterface RecoveryColumn {\n readonly name: string;\n readonly dataType: string;\n readonly comment: string;\n}\n\nfunction refuseReservedConstraint(\n constraintName: string,\n tableName: string,\n reason: string\n): never {\n throw new MigrationError(\n `The MySQL CHECK constraint \"${constraintName}\" on table \"${tableName}\" uses VibORM's reserved decimal-conversion namespace but ${reason}. ` +\n \"Migration work is refused before any cleanup or schema effect; rename the user-owned constraint, or restore the exact interrupted VibORM conversion proof and run the command again.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n type: \"decimal-conversion-constraint-collision\",\n table: tableName,\n constraint: constraintName,\n },\n }\n );\n}\n\nfunction readString(\n value: unknown,\n constraintName: string,\n tableName: string,\n field: string\n): string {\n if (typeof value === \"string\") return value;\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its catalog ${field} is not a string`\n );\n}\n\n/**\n * MySQL stores CHECK clauses in a normalized spelling: keywords are lower-case,\n * redundant grouping parentheses are added, `CHARACTER SET` becomes `CHARSET`,\n * and string literals acquire a connection-character-set introducer. These are\n * presentation changes only. Removing precisely those tokens leaves the exact\n * generated expression comparable without accepting another predicate.\n */\nfunction normalizeCheckClause(clause: string): string {\n // CHECK_CLAUSE escapes each catalog-rendered string delimiter as `\\'` on\n // mysql2. None of VibORM's fixed proof literals contains an apostrophe, so\n // this removes only the provider's delimiter escape, never literal content.\n const rendered = clause.replaceAll(\"\\\\'\", \"'\");\n let normalized = \"\";\n let index = 0;\n while (index < rendered.length) {\n const char = rendered[index];\n if (char === \"'\") {\n const start = index;\n index++;\n while (index < rendered.length) {\n if (rendered[index] === \"\\\\\" && index + 1 < rendered.length) {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\" && rendered[index + 1] === \"'\") {\n index += 2;\n continue;\n }\n if (rendered[index] === \"'\") {\n index++;\n break;\n }\n index++;\n }\n normalized += rendered.slice(start, index);\n continue;\n }\n if (char === \"`\") {\n const end = rendered.indexOf(\"`\", index + 1);\n if (end < 0) return clause;\n normalized += rendered.slice(index, end + 1);\n index = end + 1;\n continue;\n }\n if (WHITESPACE.test(char ?? \"\")) {\n index++;\n continue;\n }\n if (char === \"_\") {\n const introducer = CATALOG_CHARACTER_SET_INTRODUCER.exec(\n rendered.slice(index)\n );\n if (introducer !== null) {\n index += introducer[0].length;\n continue;\n }\n }\n normalized += char?.toLowerCase() ?? \"\";\n index++;\n }\n return normalized;\n}\n\nfunction expectedConstraint(\n column: RecoveryColumn,\n kind: \"s\" | \"l\",\n descriptor: DecimalDescriptor\n): string {\n const quotedColumn = `\\`${column.name}\\``;\n return kind === \"s\"\n ? mysqlDecimalFitsCatalogCheck(\n quotedColumn,\n `DECIMAL(${descriptor.precision},${descriptor.scale})`\n )\n : mysqlDecimalListFitsCatalogCheck(quotedColumn, descriptor);\n}\n\nfunction readDescriptor(\n match: RegExpExecArray,\n constraintName: string,\n tableName: string\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(match[2], match[3], \"mysql\");\n if (descriptor === undefined) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name declares a decimal domain this provider does not admit\"\n );\n }\n const kind = match[1] === \"s\" ? \"scalar\" : \"list\";\n if (decimalConversionConstraintName(kind, descriptor) !== constraintName) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name is not the canonical spelling of its decimal proof\"\n );\n }\n return descriptor;\n}\n\nfunction proveConstraint(\n row: ConstraintRow,\n columnsByTable: ReadonlyMap<string, readonly RecoveryColumn[]>\n): ProvenConstraint {\n const rawName =\n typeof row.CONSTRAINT_NAME === \"string\"\n ? row.CONSTRAINT_NAME\n : \"<unreported>\";\n const rawTable =\n typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"<unreported>\";\n const constraintName = readString(\n row.CONSTRAINT_NAME,\n rawName,\n rawTable,\n \"CONSTRAINT_NAME\"\n );\n const tableName = readString(\n row.TABLE_NAME,\n constraintName,\n rawTable,\n \"TABLE_NAME\"\n );\n const clause = readString(\n row.CHECK_CLAUSE,\n constraintName,\n tableName,\n \"CHECK_CLAUSE\"\n );\n const enforced = readString(\n row.ENFORCED,\n constraintName,\n tableName,\n \"ENFORCED\"\n );\n if (enforced !== \"YES\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its CHECK is not enforced\"\n );\n }\n const nameMatch = RESERVED_NAME.exec(constraintName);\n if (nameMatch === null) {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its name does not match the complete reserved proof identity\"\n );\n }\n const kind = nameMatch[1] === \"s\" ? \"s\" : \"l\";\n const descriptor = readDescriptor(nameMatch, constraintName, tableName);\n\n const columns = columnsByTable.get(tableName) ?? [];\n const actualClause = normalizeCheckClause(clause);\n for (const column of columns) {\n const expected = expectedConstraint(column, kind, descriptor);\n if (normalizeCheckClause(expected) !== actualClause) continue;\n if (kind === \"s\") {\n if (\n column.dataType === \"decimal\" ||\n column.dataType === \"int\" ||\n column.dataType === \"bigint\"\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its scalar proof is attached to impossible ${column.dataType} storage`\n );\n }\n if (column.dataType !== \"json\") {\n refuseReservedConstraint(\n constraintName,\n tableName,\n `its list proof is attached to impossible ${column.dataType} storage`\n );\n }\n let current: DecimalDescriptor | undefined;\n try {\n current = readMysqlDecimalListMarker(column.comment);\n } catch {\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column carries an invalid decimal-list marker\"\n );\n }\n if (\n current !== undefined &&\n current.scale === descriptor.scale &&\n current.precision >= descriptor.precision\n ) {\n return { tableName, constraintName };\n }\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its JSON column does not carry a compatible source or target decimal-list marker\"\n );\n }\n\n refuseReservedConstraint(\n constraintName,\n tableName,\n \"its concrete CHECK predicate does not match that proof identity\"\n );\n}\n\nfunction groupColumns(\n rows: readonly ColumnRow[]\n): Map<string, RecoveryColumn[]> {\n const columnsByTable = new Map<string, RecoveryColumn[]>();\n for (const row of rows) {\n const tableName = typeof row.TABLE_NAME === \"string\" ? row.TABLE_NAME : \"\";\n const columnName =\n typeof row.COLUMN_NAME === \"string\" ? row.COLUMN_NAME : \"\";\n const dataType = typeof row.DATA_TYPE === \"string\" ? row.DATA_TYPE : \"\";\n const comment =\n typeof row.COLUMN_COMMENT === \"string\" ? row.COLUMN_COMMENT : \"\";\n if (tableName === \"\" || columnName === \"\" || dataType === \"\") continue;\n const columns = columnsByTable.get(tableName) ?? [];\n columns.push({\n name: columnName,\n dataType: dataType.toLowerCase(),\n comment,\n });\n columnsByTable.set(tableName, columns);\n }\n return columnsByTable;\n}\n\n/**\n * Plans the removal of authenticated remnants of a MySQL decimal conversion.\n *\n * The migration lock excludes another VibORM command. Every reserved row is\n * proven before the first DROP is returned, so a user-owned collision or a\n * malformed catalog answer cannot make cleanup partially mutate the estate.\n * Execution belongs to the sequential-program owner: MySQL can commit a DROP\n * before reporting a connection failure, and only that owner can state the\n * resulting uncertain boundary honestly.\n */\nexport async function planInterruptedMySQLDecimalRecovery(\n read: CatalogRead,\n namespace: string,\n quoteIdentifier: (name: string) => string\n): Promise<readonly string[]> {\n const { rows } = await read<ConstraintRow>(CONSTRAINTS_QUERY, [\n namespace,\n RESERVED_PREFIX,\n ]);\n if (rows.length === 0) return [];\n if (rows.length > 1) {\n const first = rows[0];\n refuseReservedConstraint(\n typeof first?.CONSTRAINT_NAME === \"string\"\n ? first.CONSTRAINT_NAME\n : \"<unreported>\",\n typeof first?.TABLE_NAME === \"string\" ? first.TABLE_NAME : \"<unreported>\",\n `the catalog contains ${rows.length} reserved proofs, although one locked conversion can leave at most one`\n );\n }\n\n const columns = await read<ColumnRow>(COLUMNS_QUERY, [namespace]);\n const columnsByTable = groupColumns(columns.rows);\n const proven = rows.map((row) => proveConstraint(row, columnsByTable));\n\n return proven.map(\n (constraint) =>\n `ALTER TABLE ${quoteIdentifier(namespace)}.${quoteIdentifier(constraint.tableName)} DROP CHECK ${quoteIdentifier(constraint.constraintName)}`\n );\n}\n","/**\n * MySQL Schema Introspection\n *\n * Reads the current database schema from MySQL's information_schema,\n * returning a normalized SchemaSnapshot.\n */\n\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n readMysqlDecimalListMarker,\n readStoredDecimalDescriptor,\n} from \"../../decimal\";\nimport { decodeUtf8 } from \"../../identity\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport {\n MYSQL_PRINTED_CHARACTERS,\n mysqlEnumType,\n mysqlStringLiteral,\n parseMySqlEnumValues,\n} from \"../type-mapping\";\nimport { groupBy, groupByNested, mapReferentialAction } from \"../utils\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport type {\n MySQLColumn,\n MySQLForeignKey,\n MySQLIndex,\n MySQLPrimaryKey,\n MySQLTable,\n} from \"./types\";\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\n// Every filter below binds the resolved database as DATA (§5.2). The name is\n// never spliced into the statement, and `DATABASE()` — the connection's ambient\n// default, which the ORM never configured — appears nowhere.\nconst TABLES_QUERY = `\nSELECT TABLE_NAME\nFROM information_schema.TABLES\nWHERE TABLE_SCHEMA = ?\n AND TABLE_TYPE = 'BASE TABLE'\nORDER BY TABLE_NAME\n`;\n\nconst COLUMNS_QUERY = `\nSELECT\n TABLE_NAME,\n COLUMN_NAME,\n DATA_TYPE,\n COLUMN_TYPE,\n IS_NULLABLE,\n COLUMN_DEFAULT,\n CHARACTER_MAXIMUM_LENGTH,\n NUMERIC_PRECISION,\n NUMERIC_SCALE,\n SRS_ID,\n EXTRA,\n COLUMN_COMMENT\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = ?\nORDER BY TABLE_NAME, ORDINAL_POSITION\n`;\n\nconst PRIMARY_KEYS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nWHERE tc.TABLE_SCHEMA = ?\n AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'\nORDER BY tc.TABLE_NAME, kcu.ORDINAL_POSITION\n`;\n\nconst INDEXES_QUERY = `\nSELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n NON_UNIQUE,\n INDEX_TYPE,\n SEQ_IN_INDEX\nFROM information_schema.STATISTICS\nWHERE TABLE_SCHEMA = ?\n AND INDEX_NAME != 'PRIMARY'\nORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n`;\n\n// Both endpoints are projected and BOTH are admitted as filter candidates\n// (§5.2): a constraint that leaves the estate in either direction has to be\n// visible here before it can be refused, and an inbound one is not reachable\n// through the referencing side's schema at all.\nconst FOREIGN_KEYS_QUERY = `\nSELECT\n tc.TABLE_SCHEMA,\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.REFERENCED_TABLE_SCHEMA,\n kcu.REFERENCED_TABLE_NAME,\n kcu.REFERENCED_COLUMN_NAME,\n rc.DELETE_RULE,\n rc.UPDATE_RULE,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nJOIN information_schema.REFERENTIAL_CONSTRAINTS rc\n ON rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n AND rc.CONSTRAINT_SCHEMA = tc.TABLE_SCHEMA\nWHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'\n AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?)\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\n`;\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/**\n * The MySQL storage whose literal default the catalog already reports the way\n * the estate spells it: a number is a number, and a `BIT` default is reported\n * as its own `b'…'` literal. Every other type's literal default is a QUOTED\n * string in DDL, and `information_schema` reports it with the quotes gone.\n */\nconst MYSQL_NUMERIC_DATA_TYPES = new Set([\n \"bigint\",\n \"bit\",\n \"decimal\",\n \"double\",\n \"float\",\n \"int\",\n \"integer\",\n \"mediumint\",\n \"numeric\",\n \"real\",\n \"smallint\",\n \"tinyint\",\n]);\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction formatColumnType(col: MySQLColumn): string {\n if (col.DATA_TYPE.toLowerCase() === \"point\") {\n const srid = readSrid(col);\n return srid === undefined ? \"POINT\" : `POINT SRID ${srid}`;\n }\n\n // An ENUM's values ARE its type. `information_schema` prints its own\n // rendering of them — `enum('a','b')`, no space after the comma — so the\n // parsed values are re-spelled through the estate's ONE enum speller and the\n // two snapshots name one type. A COLUMN_TYPE that parses to no values at all\n // is not an enum MySQL could have created; it stays exactly as read.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n return values ? mysqlEnumType(values) : col.COLUMN_TYPE;\n }\n\n // For types with modifiers (unsigned, zerofill) or size info in COLUMN_TYPE,\n // prefer COLUMN_TYPE to preserve full type specification\n // Examples: \"int unsigned\", \"bigint unsigned zerofill\", \"varbinary(255)\", \"bit(8)\", \"timestamp(6)\"\n const columnType = col.COLUMN_TYPE.toLowerCase();\n const hasModifiers =\n columnType.includes(\"unsigned\") ||\n columnType.includes(\"zerofill\") ||\n // Has parentheses with size/precision info (but not enum which is handled above)\n (columnType.includes(\"(\") && col.DATA_TYPE !== \"enum\");\n\n if (hasModifiers) {\n return col.COLUMN_TYPE;\n }\n\n // Fallback: construct from DATA_TYPE with precision info\n if (col.DATA_TYPE === \"varchar\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `VARCHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"char\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `CHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION) {\n if (col.NUMERIC_SCALE !== null && col.NUMERIC_SCALE !== undefined) {\n return `DECIMAL(${col.NUMERIC_PRECISION},${col.NUMERIC_SCALE})`;\n }\n return `DECIMAL(${col.NUMERIC_PRECISION})`;\n }\n\n return col.DATA_TYPE.toUpperCase();\n}\n\nfunction readSrid(col: MySQLColumn): number | undefined {\n if (col.SRS_ID === null || col.SRS_ID === undefined) return undefined;\n const value = Number(col.SRS_ID);\n if (Number.isSafeInteger(value) && value >= 0 && value <= 4_294_967_295) {\n return value;\n }\n throw new MigrationError(\n `MySQL reported an invalid SRID for column \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\". Migration introspection is refused rather than publishing an unprovable spatial type.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-srid\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(extra: string): boolean {\n return extra.toLowerCase().includes(\"auto_increment\");\n}\n\n/**\n * The declared decimal domain of a MySQL column, or `undefined`.\n *\n * Two carriers, because MySQL stores the two shapes differently. A scalar is\n * `DECIMAL(p,s)` and the catalog reports the pair directly. A list is `JSON`,\n * which carries nothing, so its domain lives in the deterministic column\n * comment — matched EXACTLY (§6.2): a comment that merely mentions a decimal is\n * a comment, not a descriptor, and reading one as a descriptor would attach a\n * domain to a column VibORM never declared one on.\n */\nfunction readDecimalDomain(col: MySQLColumn): DecimalDescriptor | undefined {\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION !== null) {\n const descriptor = readStoredDecimalDescriptor(\n col.NUMERIC_PRECISION,\n col.NUMERIC_SCALE ?? 0,\n \"mysql\"\n );\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `MySQL reported column \"${col.TABLE_NAME}\".\"${col.COLUMN_NAME}\" as DECIMAL(${String(col.NUMERIC_PRECISION)},${String(col.NUMERIC_SCALE ?? 0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: col.TABLE_NAME,\n column: col.COLUMN_NAME,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n }\n if (col.DATA_TYPE !== \"json\") return undefined;\n return readMysqlDecimalListMarker(col.COLUMN_COMMENT);\n}\n\n/**\n * MySQL deparses an expression-backed string literal as `_charset\\\\'value\\\\'`.\n * The introducer is CAPTURED because it names the encoding of the bytes that\n * follow it (see {@link decodeIntroducedLiteral}).\n */\nconst MYSQL_STRING_EXPRESSION_DEFAULT = /^_([A-Za-z0-9_]+)\\\\'([\\s\\S]*)\\\\'$/;\n\n/** One backslash escape, with the character it escapes. */\nconst MYSQL_ESCAPE_SEQUENCE = /\\\\([\\s\\S]?)/g;\n\n/** Each byte read as the codepoint of the same number. */\nfunction decodeSingleByte(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\"\");\n}\n\n/**\n * MySQL's `latin1` IS Windows-1252, not ISO-8859-1: the 32 bytes 0x80–0x9F are\n * printable characters there (0x93 is U+201C), and the five cp1252 leaves\n * undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) MySQL maps to the same-numbered\n * control. Every other byte is the codepoint of its own number.\n */\nconst CP1252_HIGH: readonly number[] = [\n 0x20_ac, 0x81, 0x20_1a, 0x01_92, 0x20_1e, 0x20_26, 0x20_20, 0x20_21, 0x02_c6,\n 0x20_30, 0x01_60, 0x20_39, 0x01_52, 0x8d, 0x01_7d, 0x8f, 0x90, 0x20_18,\n 0x20_19, 0x20_1c, 0x20_1d, 0x20_22, 0x20_13, 0x20_14, 0x02_dc, 0x21_22,\n 0x01_61, 0x20_3a, 0x01_53, 0x9d, 0x01_7e, 0x01_78,\n];\nfunction decodeLatin1(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) =>\n String.fromCharCode(\n byte >= 0x80 && byte <= 0x9f ? (CP1252_HIGH[byte - 0x80] ?? byte) : byte\n )\n ).join(\"\");\n}\n\n/**\n * How an introducer's bytes are READ — one entry per charset, because the\n * charset is what says what a byte MEANS.\n *\n * MySQL names the charset of the DDL the literal arrived in and FREEZES it in\n * the stored expression, so the writing SESSION decides what reaches this\n * inverse, whatever the reading one speaks (measured: a column created over a\n * `latin1` connection reports `_latin1` to an ordinary utf8mb4 connection,\n * `closure-repair-2/t3/receipts/probe-frozen-introducer.log`). The UTF-8 family\n * is decoded; `ascii` and `binary` map each byte to the codepoint of the same\n * number, so the catalog's text already IS the value; `latin1` is read as the\n * Windows-1252 MySQL means by it ({@link decodeLatin1}). A charset\n * outside this table — `cp1251`, say, where the same byte is a different\n * letter — is not read at all: either reading would be a guess there, and a\n * wrong guess calls two different defaults equal.\n */\nconst MYSQL_INTRODUCER_DECODERS: ReadonlyMap<\n string,\n (bytes: Uint8Array) => string\n> = new Map([\n [\"utf8\", decodeUtf8],\n [\"utf8mb3\", decodeUtf8],\n [\"utf8mb4\", decodeUtf8],\n [\"latin1\", decodeLatin1],\n [\"ascii\", decodeSingleByte],\n [\"binary\", decodeSingleByte],\n]);\n\n/**\n * The printed literal behind the catalog's text, or `undefined` when the text\n * is not the byte sequence the introducer promises.\n *\n * `information_schema.COLUMNS.COLUMN_DEFAULT` hands an EXPRESSION default's\n * text back one codepoint per BYTE: `café ☕` arrives as the nine codepoints\n * `63 61 66 c3 a9 20 e2 98 95` — the UTF-8 bytes of the value, each read as a\n * character — while the SAME column carries a LITERAL default's value decoded\n * (measured on 8.4.11: `HEX(COLUMN_DEFAULT)` shows the expansion server-side,\n * and `SHOW CREATE TABLE` prints the true text, so the loss is MySQL's own\n * rendering of a stored expression, not the connection's character set and not\n * the driver). Those bytes are the literal, in the charset the introducer\n * names, so they are read back with THAT charset\n * ({@link MYSQL_INTRODUCER_DECODERS}) rather than re-decoded by a rule of this\n * module's invention.\n *\n * An unknown charset, an out-of-byte-range codepoint, or an invalid byte\n * sequence keeps the catalog's own text. These checks do not prove provenance:\n * the measured mysql2 byte-expanded spelling of `é` and already-decoded text\n * whose literal characters are `é` both present `c3 a9`, a valid UTF-8\n * sequence. Content alone cannot distinguish them. This decoder therefore\n * describes the measured mysql2 catalog representation; other transport\n * representations are unverified, and valid UTF-8-shaped already-decoded text\n * can be transformed rather than fail closed.\n */\nfunction decodeIntroducedLiteral(\n introducer: string,\n printed: string\n): string | undefined {\n const decode = MYSQL_INTRODUCER_DECODERS.get(introducer.toLowerCase());\n if (decode === undefined) return undefined;\n const codes = [...printed].map((character) => character.codePointAt(0) ?? 0);\n if (codes.some((code) => code > 0xff)) return undefined;\n try {\n return decode(Uint8Array.from(codes));\n } catch {\n return undefined;\n }\n}\n\n/** `undefined` for a body carrying an escape MySQL's printer does not write. */\nfunction unescapeOneLayer(body: string): string | undefined {\n let owned = true;\n const unescaped = body.replace(\n MYSQL_ESCAPE_SEQUENCE,\n (_match: string, escaped: string) => {\n const character = MYSQL_PRINTED_CHARACTERS.get(escaped);\n if (character === undefined) {\n owned = false;\n return escaped;\n }\n return character;\n }\n );\n return owned ? unescaped : undefined;\n}\n\n/**\n * The VALUE behind MySQL's deparse of a string default, or `undefined` when\n * the catalog text carries an escape this inverse does not own.\n *\n * The text is escaped TWICE — once by MySQL printing the string literal inside\n * the expression, once by `information_schema` printing that expression — so a\n * declared `it's` arrives as the characters `_utf8mb4\\'it\\\\\\'s\\'` (measured on\n * MySQL 8.4.11). Each pass undoes one layer, through the table MySQL's printer\n * writes (`MYSQL_PRINTED_CHARACTERS`). An escape outside that table is not one\n * this server printed for a value the estate spelled, so inverting it would be\n * a guess, and a wrong guess calls two different defaults equal.\n *\n * The BYTES come first ({@link decodeIntroducedLiteral}), because the catalog\n * spells them one per codepoint and every escape MySQL prints is ASCII: the\n * layers are the same after the decode, and only a text that is those bytes\n * reaches them.\n */\nfunction deparsedStringValue(columnDefault: string): string | undefined {\n const deparsed = MYSQL_STRING_EXPRESSION_DEFAULT.exec(columnDefault);\n const introducer = deparsed?.[1];\n const body = deparsed?.[2];\n const printed =\n introducer === undefined || body === undefined\n ? undefined\n : decodeIntroducedLiteral(introducer, body);\n const literal = printed === undefined ? undefined : unescapeOneLayer(printed);\n return literal === undefined ? undefined : unescapeOneLayer(literal);\n}\n\n/**\n * The column's default, in the ONE spelling the estate uses.\n *\n * MySQL reports a default in two vocabularies and neither is the estate's. A\n * LITERAL default comes back as the bare VALUE — `member`, `x'y` — with the\n * quotes DDL required stripped off. An EXPRESSION default (every default on a\n * TEXT, BLOB, JSON or GEOMETRY column, since those refuse a literal) comes back\n * as MySQL's deparse of the expression, where a string literal is printed\n * `_charset\\\\'value\\\\'`. Both are translated here, at the one boundary that\n * reads the catalog, into what `finalizeMySQLColumn` spells on the desired\n * side; otherwise a default nobody touched reads as a changed column on every\n * push, and the final push attestation refuses the schema it just created.\n *\n * A deparse this inverse does not own keeps MySQL's own catalog text, which\n * stays different from the desired side: the column is re-planned and the push\n * then FAILS at the final attestation with `MIGRATION_DRIFT`. That is the\n * fail-closed direction — the same one the decimal-list container took when it\n * could not be re-encoded byte for byte — and it refuses a default nobody\n * proved equal instead of reporting a schema the database does not hold.\n */\nfunction cleanDefault(col: MySQLColumn): string | undefined {\n const columnDefault = col.COLUMN_DEFAULT;\n if (columnDefault === null) return undefined;\n if (col.EXTRA.toUpperCase().includes(\"DEFAULT_GENERATED\")) {\n const value = deparsedStringValue(columnDefault);\n return value === undefined\n ? columnDefault\n : `(${mysqlStringLiteral(value)})`;\n }\n return MYSQL_NUMERIC_DATA_TYPES.has(col.DATA_TYPE.toLowerCase())\n ? columnDefault\n : mysqlStringLiteral(columnDefault);\n}\n\n/**\n * Refuses every foreign key with one endpoint outside the selected database\n * (§5.2), before the snapshot exists.\n *\n * Both directions are refused for the same reason: the estate's own DDL cannot\n * express, drop or recreate a constraint whose other half lives in a database\n * this client does not manage, so a reset, a push, or a generated down would\n * plan work that is either impossible or destructive to a stranger's schema.\n *\n * This runs BEFORE the rows are grouped, because the grouped set is also what\n * hides MySQL's auto-created FK indexes from the snapshot: admitting a foreign\n * row here would silently change which indexes the differ sees.\n */\nfunction admitContainedForeignKeys(\n rows: readonly MySQLForeignKey[],\n namespace: string,\n tables?: readonly string[]\n): void {\n for (const row of rows) {\n if (\n tables !== undefined &&\n !(row.TABLE_SCHEMA === namespace && tables.includes(row.TABLE_NAME)) &&\n !(\n row.REFERENCED_TABLE_SCHEMA === namespace &&\n tables.includes(row.REFERENCED_TABLE_NAME)\n )\n )\n continue;\n if (\n row.TABLE_SCHEMA === namespace &&\n row.REFERENCED_TABLE_SCHEMA === namespace\n ) {\n continue;\n }\n throw new MigrationError(\n `Foreign key \"${row.CONSTRAINT_NAME}\" crosses a database boundary: \\`${row.TABLE_SCHEMA}\\`.\\`${row.TABLE_NAME}\\` references \\`${row.REFERENCED_TABLE_SCHEMA}\\`.\\`${row.REFERENCED_TABLE_NAME}\\`, and this client manages only \"${namespace}\". ` +\n \"Migration work is refused before any snapshot, plan or DDL: VibORM cannot recreate or drop a constraint whose other half lives in a database it does not own.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n // BOTH endpoints are reported (§5.2), each on its own allowlisted\n // channel: the referencing one on `table`, the referenced one on\n // `referencedTable`, beside the database this client manages.\n meta: {\n dialect: \"mysql\",\n type: \"cross-database-foreign-key\",\n constraint: row.CONSTRAINT_NAME,\n namespace,\n table: `${row.TABLE_SCHEMA}.${row.TABLE_NAME}`,\n referencedTable: `${row.REFERENCED_TABLE_SCHEMA}.${row.REFERENCED_TABLE_NAME}`,\n },\n }\n );\n }\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: CatalogReader,\n namespace: string | undefined,\n managedTables?: readonly string[]\n): Promise<SchemaSnapshot> {\n // The database is proven to exist BEFORE anything is read, so an absent one\n // can never be published as an empty inventory (§5.2). Its returned spelling\n // is what every filter below binds and what the containment comparison uses:\n // under `lower_case_table_names` the server's spelling is the identity the\n // catalog rows actually carry.\n const catalogNamespace = await resolveCatalogNamespace(executeRaw, namespace);\n\n // One after another: these run on the command's ONE pinned session, and a\n // connection runs one statement at a time. mysql2 queues overlapping\n // queries silently, but the overlap bought nothing.\n const scope = [catalogNamespace];\n const tablesResult = await executeRaw<MySQLTable>(TABLES_QUERY, scope);\n const columnsResult = await executeRaw<MySQLColumn>(COLUMNS_QUERY, scope);\n const primaryKeysResult = await executeRaw<MySQLPrimaryKey>(\n PRIMARY_KEYS_QUERY,\n scope\n );\n const indexesResult = await executeRaw<MySQLIndex>(INDEXES_QUERY, scope);\n const foreignKeysResult = await executeRaw<MySQLForeignKey>(\n FOREIGN_KEYS_QUERY,\n [catalogNamespace, catalogNamespace]\n );\n\n admitContainedForeignKeys(\n foreignKeysResult.rows,\n catalogNamespace,\n managedTables\n );\n\n // Group results\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.TABLE_NAME);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.TABLE_NAME);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.TABLE_NAME,\n (idx) => idx.INDEX_NAME\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows.filter((fk) => fk.TABLE_SCHEMA === catalogNamespace),\n (fk) => fk.TABLE_NAME,\n (fk) => fk.CONSTRAINT_NAME\n );\n // Track enum definitions found in columns\n const enumDefs: EnumDef[] = [];\n const seenEnums = new Set<string>();\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.TABLE_NAME;\n\n // Build columns\n const columns: ColumnDef[] = [];\n for (const col of columnsByTable.get(tableName) || []) {\n if (\n (managedTables === undefined || managedTables.includes(tableName)) &&\n (col.EXTRA.toUpperCase().includes(\"VIRTUAL GENERATED\") ||\n col.EXTRA.toUpperCase().includes(\"STORED GENERATED\"))\n )\n throw new MigrationError(\n `MySQL column \"${tableName}.${col.COLUMN_NAME}\" is generated. Synchronization refuses before effects because its expression cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: tableName,\n column: col.COLUMN_NAME,\n feature: \"generated column\",\n },\n }\n );\n // Extract enum values if this is an enum column\n // MySQL has no standalone enum object, so the inline type IS the\n // identity — and it is the identity the DESIRED snapshot registers too\n // (`serializer.ts` names an enum by `getEnumColumnType`). Naming it\n // anything else here, as a derived `table$column$enum` did, made every\n // enum-bearing schema carry two enum definitions that could never match.\n if (col.DATA_TYPE === \"enum\") {\n const values = parseMySqlEnumValues(col.COLUMN_TYPE);\n const enumName = values && mysqlEnumType(values);\n if (values && enumName && !seenEnums.has(enumName)) {\n enumDefs.push({ name: enumName, values });\n seenEnums.add(enumName);\n }\n }\n\n const managed =\n managedTables === undefined || managedTables.includes(tableName);\n const decimal = managed ? readDecimalDomain(col) : undefined;\n columns.push({\n name: col.COLUMN_NAME,\n type: managed ? formatColumnType(col) : col.COLUMN_TYPE,\n nullable: col.IS_NULLABLE === \"YES\",\n default: managed ? cleanDefault(col) : undefined,\n autoIncrement: isAutoIncrement(col.EXTRA),\n decimal,\n });\n }\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstPkCol = pkCols[0];\n if (firstPkCol) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.COLUMN_NAME),\n name: firstPkCol.CONSTRAINT_NAME,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n // MySQL auto-creates an index named after each FK constraint; it isn't a\n // user index and can't be dropped while the FK exists, so hide it\n const fkNames = new Set(fkByTable.get(tableName)?.keys() ?? []);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n if (fkNames.has(indexName)) {\n continue;\n }\n indexCols.sort((a, b) => a.SEQ_IN_INDEX - b.SEQ_IN_INDEX);\n const firstCol = indexCols[0];\n if (firstCol) {\n const rawIndexType = firstCol.INDEX_TYPE.toLowerCase();\n // MySQL INFORMATION_SCHEMA reports RTREE for spatial indexes, normalize to \"spatial\"\n const indexType = rawIndexType === \"rtree\" ? \"spatial\" : rawIndexType;\n indexes.push({\n name: indexName,\n columns: indexCols.map((idx) => idx.COLUMN_NAME),\n unique: firstCol.NON_UNIQUE === 0,\n // MySQL uses BTREE, HASH, FULLTEXT, SPATIAL (reported as RTREE) - preserve all supported types\n type:\n indexType === \"btree\" ||\n indexType === \"hash\" ||\n indexType === \"fulltext\" ||\n indexType === \"spatial\"\n ? (indexType as \"btree\" | \"hash\" | \"fulltext\" | \"spatial\")\n : undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.COLUMN_NAME),\n referencedTable: firstFk.REFERENCED_TABLE_NAME,\n referencedColumns: fkCols.map((fk) => fk.REFERENCED_COLUMN_NAME),\n onDelete: mapReferentialAction(firstFk.DELETE_RULE),\n onUpdate: mapReferentialAction(firstFk.UPDATE_RULE),\n });\n }\n }\n }\n\n // MySQL HAS ONE UNIQUE NAMESPACE, so a unique is reported ONCE — as an\n // index, above, from STATISTICS. TABLE_CONSTRAINTS lists the very same\n // object a second time (its `UNIQUE` constraint face), and filing that\n // second face here made every unique-bearing MySQL schema churn forever:\n // whichever bucket the desired side did not use looked like a stray object\n // and the differ planned a drop for it (measured on docker MySQL 8 — a\n // spurious `dropIndex` for a declared unique constraint, a spurious\n // `dropUniqueConstraint` for a declared unique index).\n //\n // The desired side is canonicalized to match by the driver's\n // `finalizeTable`, which rewrites every unique constraint into a unique\n // index. Both sides now speak indexes, so a unique round-trips unchanged.\n //\n // The bucket stays in the shape (every dialect's snapshot carries it) and\n // is always empty for MySQL. TABLE_CONSTRAINTS is no longer queried at all:\n // it can report nothing the STATISTICS rows above do not already carry.\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // MySQL doesn't have standalone enum types, but we track them for compatibility\n return {\n tables,\n enums: enumDefs.length > 0 ? enumDefs : undefined,\n };\n}\n","/**\n * MySQL pinned migration session: lock identity, exact lock proofs, the one\n * admitted target selection, and the session's exact-value proof.\n *\n * This module is §13's single exempted `USE` producer. Every other `USE` in the\n * shipped source is a defect, and the architecture census enforces that by\n * naming THIS path — `PINNED_ARTIFACT_SESSION_OWNERS` — and nothing else. The\n * exemption is sound only because the statement below can be reached solely\n * from a pinned migration session, where the owner, lifetime, lock, target and\n * cleanup are one physical connection that is destroyed afterwards\n * (`MySQL2Driver.pinnedSession`).\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { CatalogRead } from \"../../target\";\n\n/**\n * MySQL's `GET_LOCK` name limit. Longer names are an error on 8.0+ and were\n * silently truncated before, which would have collapsed two databases onto one\n * lock name — the exact accident the hash below prevents.\n */\nconst LOCK_NAME_LIMIT = 64;\n\nconst LOCK_NAME_PREFIX = \"viborm_migration_\";\n\n/** `_` + eight hex digits. */\nconst LOCK_HASH_LENGTH = 9;\n\nconst LOCK_NAME_BUDGET =\n LOCK_NAME_LIMIT - LOCK_NAME_PREFIX.length - LOCK_HASH_LENGTH;\n\n/** Every character MySQL identifiers admit that a lock name should not carry. */\nconst NON_LOCK_NAME_CHARACTERS = /[^a-z0-9_]/g;\n\nconst FNV_OFFSET_BASIS = 0x81_1c_9d_c5;\nconst FNV_PRIME = 0x01_00_01_93;\n\n/**\n * A deterministic 32-bit FNV-1a hash, as eight lowercase hex digits.\n *\n * The lock name has to survive truncation without two databases colliding, and\n * a cryptographic digest would be a runtime dependency for a value nothing\n * secret depends on: this is a collision-spreading suffix, not a secret.\n */\nfunction hashLockScope(value: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let index = 0; index < value.length; index += 1) {\n // FNV-1a IS an XOR followed by a multiply; any other spelling is a\n // different function.\n // biome-ignore lint/suspicious/noBitwiseOperators: FNV-1a is defined as XOR-then-multiply.\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, FNV_PRIME);\n }\n // The unsigned shift is how JavaScript reads a 32-bit result back as a\n // non-negative integer.\n // biome-ignore lint/suspicious/noBitwiseOperators: reads the 32-bit result as unsigned.\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * The lock name for one MySQL database.\n *\n * The scope is a CONSERVATIVE lowercase form of the configured database name.\n * Under `lower_case_table_names=1` two spellings of one database are the same\n * database, and letting them take different lock names would let two migration\n * commands run concurrently against it. Lowercasing may also serialize two\n * genuinely distinct case-sensitive databases that differ only in case; that is\n * the deliberate trade — a lock taken too widely is slow, a lock taken too\n * narrowly is wrong.\n *\n * The hash is computed over the WHOLE lowercased name, so two names sharing a\n * truncated prefix still get different locks.\n */\nexport function mysqlMigrationLockName(namespace: string): string {\n const scope = namespace.toLowerCase();\n const readable = scope\n .replace(NON_LOCK_NAME_CHARACTERS, \"_\")\n .slice(0, LOCK_NAME_BUDGET);\n return `${LOCK_NAME_PREFIX}${readable}_${hashLockScope(scope)}`;\n}\n\n/**\n * `GET_LOCK` with a stable `acquired` alias.\n *\n * The alias exists so the caller reads ONE known column instead of guessing at\n * a provider-shaped name built from the expression text.\n */\nexport function mysqlAcquireLockStatement(\n namespace: string,\n timeoutSeconds: number,\n quote: (value: string) => string\n): string {\n return `SELECT GET_LOCK(${quote(mysqlMigrationLockName(namespace))}, ${timeoutSeconds}) AS acquired`;\n}\n\n/** `RELEASE_LOCK` with a stable `released` alias, for the same reason. */\nexport function mysqlReleaseLockStatement(\n namespace: string,\n quote: (value: string) => string\n): string {\n return `SELECT RELEASE_LOCK(${quote(mysqlMigrationLockName(namespace))}) AS released`;\n}\n\n/**\n * The exact arms of a MySQL lock answer.\n *\n * `GET_LOCK` returns `1` when the lock was taken, `0` when the wait timed out,\n * and `NULL` on error. Treating all three as success is what made the previous\n * owner report a timeout as an acquired lock. `RELEASE_LOCK` answers the same\n * three ways about a release.\n *\n * The row itself is provider-shaped data: a value may arrive as a number, as a\n * decimal string (mysql2 returns `BIGINT`-family values as strings when\n * `supportBigNumbers` is on), or not at all. Exactly one row carrying a value\n * that parses to the number 1 is the proof; everything else — `0`, `NULL`, a\n * missing column, a missing row, more than one row, unparseable text — is not.\n */\nexport function mysqlLockAnswer(\n rows: readonly unknown[],\n column: \"acquired\" | \"released\"\n): boolean {\n if (rows.length !== 1) {\n return false;\n }\n const row = rows[0];\n if (typeof row !== \"object\" || row === null) {\n return false;\n }\n const value: unknown = Reflect.get(row, column);\n if (typeof value === \"number\") {\n return value === 1;\n }\n if (typeof value === \"string\") {\n return Number(value) === 1;\n }\n return false;\n}\n\n/**\n * Selects the migration target on the pinned session.\n *\n * Generated MySQL artifacts are database-RELATIVE by design (§13): one estate\n * deploys to `app_dev`, `app_test` and `app_prod`. Executing them verbatim on a\n * connection whose default database is something else lands the migration in\n * that other database, which is why the target is selected here — on the one\n * connection that runs the artifact, immediately before it, every time, never\n * once for the session. A manual artifact is allowed to issue its own `USE`\n * precisely because the next artifact re-selects the target anyway.\n *\n * The identifier is quoted with the migration driver's own quoter, and the name\n * itself passed the ASCII database-name grammar at driver construction.\n */\nexport function mysqlSelectTargetStatement(\n namespace: string,\n quoteIdentifier: (name: string) => string\n): string {\n return `USE ${quoteIdentifier(namespace)}`;\n}\n\nconst MYSQL_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)/;\n\n/**\n * PROVES this pinned session fails on an out-of-range value instead of\n * truncating it (plan 3.3), once per session, before any statement it\n * protects: outside a strict mode MySQL stores an overflowing `DECIMAL`\n * clamped, with a warning (measured on 8.4), and migration work runs DDL and\n * manual artifacts outside the ORM's guarded assignments. CHECK constraints\n * must be enforced too (MySQL 8.0.16+).\n */\nexport async function proveMySQLExactValueSession(\n read: CatalogRead,\n estate: string\n): Promise<void> {\n const { rows } = await read<unknown>(\n \"SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version\"\n );\n const row = rows[0];\n const mode: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"sql_mode\")\n : undefined;\n const declared = typeof mode === \"string\" ? mode : \"\";\n const serverVersion: unknown =\n typeof row === \"object\" && row !== null\n ? Reflect.get(row, \"server_version\")\n : undefined;\n const renderedVersion =\n typeof serverVersion === \"string\" ? serverVersion : \"<unreported>\";\n if (!supportsEnforcedMySQLChecks(renderedVersion)) {\n throw new MigrationError(\n `This MySQL migration session reports version \"${renderedVersion}\". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"unenforced-check-constraints\",\n target: estate,\n },\n }\n );\n }\n const hasStrictMode = declared.split(\",\").some((mode) => {\n const token = mode.trim();\n return token === \"STRICT_TRANS_TABLES\" || token === \"STRICT_ALL_TABLES\";\n });\n if (hasStrictMode) {\n return;\n }\n throw new MigrationError(\n `This MySQL session runs in sql_mode \"${declared}\", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. ` +\n \"Effectful migration work is refused: without a strict mode MySQL answers an out-of-range DECIMAL with a warning and stores the clamped value, so an exact fixed-decimal column would silently stop holding what it was given. Enable a strict mode on the server or on this connection and run the command again.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"mysql\",\n type: \"non-strict-sql-mode\",\n target: estate,\n },\n }\n );\n}\n\n/** MySQL began enforcing CHECK constraints in 8.0.16. */\nfunction supportsEnforcedMySQLChecks(version: string): boolean {\n if (version.toLowerCase().includes(\"mariadb\")) {\n return false;\n }\n const match = MYSQL_VERSION.exec(version);\n if (match === null) {\n return false;\n }\n const major = Number(match[1]);\n const minor = Number(match[2]);\n const patch = Number(match[3]);\n return major > 8 || (major === 8 && (minor > 0 || patch >= 16));\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\n/**\n * MySQL Migration Driver\n *\n * Implements the MigrationDriver interface for MySQL databases.\n * Supports all DDL operations natively with MySQL-specific syntax.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport type { AnyDriver } from \"../../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { renderQualifiedIdentifier } from \"../../../sql/identifiers\";\nimport {\n decimalConversionConstraintName,\n decimalConversionRequired,\n describeDecimalDomain,\n describeDecimalStorageKind,\n mysqlDecimalFitsCheck,\n mysqlDecimalListFitsCheck,\n mysqlDecimalListMarker,\n mysqlDecimalStorageKind,\n} from \"../../decimal\";\nimport type {\n ColumnDef,\n DiffOperation,\n ForeignKeyDef,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\n\n// Regex patterns for spatial type detection\nconst SPATIAL_TYPE_PATTERNS = [\n /^GEOMETRY\\b/,\n /^POINT\\b/,\n /^LINESTRING\\b/,\n /^POLYGON\\b/,\n /^MULTIPOINT\\b/,\n /^MULTILINESTRING\\b/,\n /^MULTIPOLYGON\\b/,\n /^GEOMETRYCOLLECTION\\b/,\n] as const;\n\n// Regex pattern for extracting base type from column type string\n// e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\"\nconst UNINDEXABLE_ORDINARY_TYPE =\n /^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\\b/i;\nconst BASE_TYPE_PATTERN = /[\\s(]/;\n\nfunction classifyDecimalListDescriptorChange(\n source: NonNullable<ColumnDef[\"decimal\"]>,\n target: NonNullable<ColumnDef[\"decimal\"]>\n): \"same\" | \"widening\" | \"narrowing\" | \"rescaling\" {\n if (source.scale !== target.scale) return \"rescaling\";\n if (source.precision < target.precision) return \"widening\";\n if (source.precision > target.precision) return \"narrowing\";\n return \"same\";\n}\n\nimport type { CatalogRead, CommandNamespaceResolver } from \"../../target\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DerivedRename,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport {\n getMySQLType,\n MYSQL_TYPE_DEFAULTS,\n mysqlEnumType,\n mysqlStringLiteral,\n} from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { type CatalogReader, resolveCatalogNamespace } from \"./catalog\";\nimport { planInterruptedMySQLDecimalRecovery } from \"./decimal-recovery\";\nimport { introspect as introspectMySQL } from \"./introspect\";\nimport {\n mysqlAcquireLockStatement,\n mysqlLockAnswer,\n mysqlReleaseLockStatement,\n mysqlSelectTargetStatement,\n proveMySQLExactValueSession,\n} from \"./pinned-session\";\n\nconst MYSQL_POINT_ATTRIBUTE_START = MYSQL_TYPE_DEFAULTS.point.indexOf(\" \");\nconst MYSQL_POINT_BASE_TYPE = MYSQL_TYPE_DEFAULTS.point.slice(\n 0,\n MYSQL_POINT_ATTRIBUTE_START\n);\nconst MYSQL_POINT_SRID_ATTRIBUTE = MYSQL_TYPE_DEFAULTS.point.slice(\n MYSQL_POINT_ATTRIBUTE_START + 1\n);\n\n/**\n * `GET_LOCK`'s wait bound. A migration command that cannot take the lock within\n * this window reports `MIGRATION_LOCK_FAILED` instead of waiting forever;\n * PostgreSQL's `pg_advisory_lock` blocks by contrast, which is its own\n * documented behaviour.\n */\nconst MIGRATION_LOCK_TIMEOUT_SECONDS = 30;\n\n/**\n * The storage classes MySQL refuses a literal `DEFAULT` on. Its own error names\n * them: \"BLOB, TEXT, GEOMETRY or JSON column can't have a default value\"\n * (errno 1101, measured on MySQL 8.4 under `STRICT_TRANS_TABLES`). MySQL 8.0.13\n * gave exactly those four an EXPRESSION default instead — `DEFAULT ('value')` —\n * which is the spelling the JSON decimal-list container already used, so it is\n * the one spelling for all four.\n */\nfunction mysqlRefusesLiteralDefault(columnType: string): boolean {\n const upper = columnType.toUpperCase();\n return (\n upper.includes(\"TEXT\") ||\n upper.includes(\"BLOB\") ||\n upper.includes(\"JSON\") ||\n SPATIAL_TYPE_PATTERNS.some((pattern) => pattern.test(upper))\n );\n}\n\n/**\n * A MySQL temporal type, with the fractional-seconds precision it declares.\n */\nconst MYSQL_TIMESTAMP_TYPE = /^(?:DATETIME|TIMESTAMP)\\s*(?:\\((\\d+)\\))?$/i;\n\n/**\n * `CURRENT_TIMESTAMP` as the RESOLVED column type takes it, or `undefined` for\n * a type that takes no such default at all.\n *\n * MySQL requires the expression's precision to AGREE with the column's:\n * `DATETIME(3) DEFAULT CURRENT_TIMESTAMP` is errno 1067, ER_INVALID_DEFAULT\n * (measured on 8.4.11), and `DATETIME(3)` is what `.dateTime()` resolves to\n * unless a native type says otherwise — so a declared `.now()` could not be\n * pushed to MySQL at all. The precision is READ OFF the type this driver just\n * mapped instead of being restated as a constant here, which is the same\n * reason a resolved DATE or TIME carries no database default rather than an\n * expression MySQL refuses.\n */\nfunction mysqlNowExpression(columnType: string): string | undefined {\n const precision = MYSQL_TIMESTAMP_TYPE.exec(columnType.trim());\n if (precision === null) {\n return undefined;\n }\n return precision[1] === undefined\n ? \"CURRENT_TIMESTAMP\"\n : `CURRENT_TIMESTAMP(${precision[1]})`;\n}\n\n/**\n * One column, as MySQL will hold and report it.\n *\n * Both rewrites belong to the same moment — after this, the desired snapshot\n * and the live one are comparable — and both are MySQL facts, not schema\n * decisions: a keyed TEXT column has to carry a key length, and a default on a\n * storage class that refuses a literal is carried as an expression. Leaving\n * the second one to the DDL emitter is what silently DROPPED the declared\n * default: the estate asked for one, the emitter wrote none, and the final\n * push attestation reported the column it did not get.\n */\nfunction finalizeMySQLColumn(column: ColumnDef, keyed: boolean): ColumnDef {\n const type =\n column.type.toUpperCase() === \"TEXT\" && keyed\n ? \"VARCHAR(191)\"\n : column.type;\n const spelled =\n column.default !== undefined && mysqlRefusesLiteralDefault(type)\n ? `(${column.default})`\n : column.default;\n return type === column.type && spelled === column.default\n ? column\n : { ...column, type, default: spelled };\n}\n\n/** Exact integer storage that can be adopted without inventing a source scale. */\nfunction isMySQLExactIntegerType(type: string): boolean {\n const base = type.trim().toUpperCase().split(BASE_TYPE_PATTERN, 1)[0];\n return base === \"INT\" || base === \"INTEGER\" || base === \"BIGINT\";\n}\nexport class MySQLMigrationDriver\n extends MigrationDriver\n implements CommandNamespaceResolver\n{\n readonly dialect = \"mysql\" as const;\n readonly driverName = \"mysql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true, // MySQL has inline ENUM type\n supportsAddEnumValueInTransaction: false, // MODIFY COLUMN is DDL and causes implicit commit\n supportsIndexTypes: [\"btree\", \"fulltext\", \"spatial\"], // InnoDB does not support user-defined HASH indexes\n supportsNativeArrays: false, // Use JSON instead\n supportsAddForeignKeyViaAlter: true, // ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY\n // `information_schema` reports the declared `CONSTRAINT_NAME`.\n introspectionReadsConstraintNames: true,\n };\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (operation.type !== \"alterColumn\") return undefined;\n const source = operation.from.decimal;\n const target = operation.to.decimal;\n if (\n source === undefined ||\n target === undefined ||\n mysqlDecimalStorageKind(operation.from) !== \"list\" ||\n mysqlDecimalStorageKind(operation.to) !== \"list\" ||\n classifyDecimalListDescriptorChange(source, target) !== \"narrowing\"\n ) {\n return undefined;\n }\n return (\n \"MySQL cannot automatically roll back the decimal-list widening of \" +\n `\"${operation.tableName}\".\"${operation.columnName}\": the inverse narrows ` +\n `${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, and ` +\n \"its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.\"\n );\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Reads the live catalog for the database THIS driver is bound to.\n *\n * The namespace travels as an argument rather than being read from the\n * connection, so an ambient default database — a pooled session, a proxy, a\n * URL path nobody re-read — can never decide which estate is introspected.\n */\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: CatalogReader\n ): Promise<boolean> {\n const names = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n );\n if (names.size === 0) return false;\n const namespace = await resolveCatalogNamespace(executeRaw, this.namespace);\n const views = await executeRaw<{ TABLE_NAME: string }>(\n \"SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?\",\n [namespace]\n );\n const collision = views.rows.find((row) => names.has(row.TABLE_NAME));\n if (collision)\n throw new MigrationError(\n `MySQL relation \"${collision.TABLE_NAME}\" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.TABLE_NAME, feature: \"view\", namespace } }\n );\n return false;\n }\n\n introspect(executeRaw: CatalogReader): Promise<SchemaSnapshot> {\n return introspectMySQL(executeRaw, this.namespace, this.target?.tables);\n }\n\n // ===========================================================================\n // IDENTIFIER ESCAPING (MySQL uses backticks)\n // ===========================================================================\n\n /**\n * A string value, spelled the way MySQL reads it back.\n *\n * The base doubles `'` and leaves everything else alone, which is right\n * where a backslash is an ordinary character. MySQL reads it as an escape\n * introducer, so that spelling silently changed the value it carried —\n * `DEFAULT ('a\\b')` created a column holding a BACKSPACE, measured. One\n * spelling serves both snapshot producers (`mysqlStringLiteral`).\n */\n override escapeValue(value: string | null | undefined): string {\n return value == null ? \"NULL\" : mysqlStringLiteral(String(value));\n }\n\n override escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\\`${String(name).replace(/`/g, \"``\")}\\``;\n }\n\n /**\n * THE table-position renderer (§5.1).\n *\n * A `\"live\"` statement names `` `database`.`table` `` so it reaches the bound\n * database whatever the connection's own default is; an `\"artifact\"`\n * statement names the table relative so ONE generated MySQL estate deploys to\n * `app_dev`, `app_test` and `app_prod` unchanged (§13 rejects embedded\n * database names in stored artifacts).\n *\n * An unbound driver has no database to name, so both destinations render the\n * bare table and unbound MySQL output stays byte-identical (§12.21). The\n * database and the object are quoted SEPARATELY, through the one\n * qualification primitive: handing `database.table` to `escapeIdentifier`\n * would silently produce one identifier naming a table with a dot in it.\n */\n protected override tableRef(\n tableName: string,\n destination: DDLContext[\"destination\"]\n ): string {\n return renderQualifiedIdentifier(\n (name) => this.escapeIdentifier(name),\n destination === \"live\" ? this.namespace : undefined,\n tableName\n );\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string {\n const declaration = scalar[\"~\"].nativeType;\n\n // See the PostgreSQL driver: one storage owner, override included.\n const idStorage =\n idDomain === undefined || scalarState.array === true\n ? undefined\n : idStorageOf(idDomain, declaration, \"mysql\");\n if (idStorage) return idStorage.columnType;\n\n // MySQL has no native list type. A native declaration can describe one\n // scalar member only; every list keeps the JSON container below.\n const nativeType = nativeTypeFor(declaration, \"mysql\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getMySQLType({\n type: scalarState.type,\n array: scalarState.array,\n decimal: scalarState.decimal,\n });\n }\n\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n const literal =\n scalarState.type === \"datetime\" &&\n !scalarState.array &&\n scalarState.hasDefault &&\n !scalarState.autoGenerate\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n !scalarState.array &&\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n typeof literal === \"string\"\n )\n return this.escapeValue(encodeMySqlDateTime(literal));\n // information_schema.COLUMNS reports both an omitted default and an\n // explicit DEFAULT NULL as catalog NULL. They have the same behavior for a\n // nullable column, so serialize the one representation MySQL can read back\n // instead of manufacturing an alterColumn on every later push.\n if (scalarState.hasDefault && scalarState.default === null) {\n return undefined;\n }\n // `now` is the one generator MySQL spells natively, and it is spelled from\n // the RESOLVED column type, so it is answered here — where that type is —\n // rather than by the generator hook, which is handed the declaration only.\n // (`uuid` stays application-level: MySQL 8 has `UUID()`, but not as a\n // column default.)\n if (scalarState.autoGenerate?.kind === \"now\") {\n return mysqlNowExpression(this.mapScalarType(scalar, scalarState));\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n /**\n * TWO canonicalizations, both required before the differ compares anything.\n *\n * 1. MySQL cannot index TEXT columns without an explicit key length.\n * Rewrite TEXT columns that participate in the primary key, a unique\n * constraint, an index, or a foreign key to VARCHAR(191) (Prisma's\n * default: 191 * 4 bytes fits the 767-byte InnoDB key limit).\n *\n * 2. MySQL HAS ONE UNIQUE NAMESPACE. A `UNIQUE` constraint and a unique\n * index are the same object: `information_schema.TABLE_CONSTRAINTS`\n * reports it as a UNIQUE constraint and `information_schema.STATISTICS`\n * reports its backing index, so introspection sees ONE database object\n * under TWO buckets. Whichever bucket the desired schema did not use then\n * looks like a stray object and the differ plans a drop for it — measured\n * on docker MySQL 8 as a spurious `dropIndex` for every declared unique\n * CONSTRAINT and a spurious `dropUniqueConstraint` for every declared\n * unique INDEX, on every push, forever.\n *\n * So MySQL picks ONE bucket and both sides speak it: every unique becomes\n * a unique INDEX here, and introspection (`introspect.ts`) files uniques\n * only under `indexes` to match. Indexes are the right survivor because\n * they carry the strictly larger vocabulary — a unique index can express\n * a unique constraint, not the reverse.\n *\n * Existing databases need no migration: the object already exists under\n * the name the desired side now spells as an index, so the two sides\n * simply agree. `generateCreateTable` emits nothing for the (now empty)\n * unique-constraint bucket and the index bucket is created as usual.\n */\n override finalizeTable(table: TableDef): TableDef {\n const keyedColumns = new Set<string>([\n ...(table.primaryKey?.columns ?? []),\n ...table.uniqueConstraints.flatMap((uq) => uq.columns),\n ...table.indexes.flatMap((index) => index.columns),\n ...table.foreignKeys.flatMap((fk) => fk.columns),\n ]);\n\n const declaredIndexNames = new Set(\n table.indexes.map((index) => index.name)\n );\n const uniquesAsIndexes = table.uniqueConstraints\n // A name already spelled as an index is the SAME object; keeping both\n // would put two entries under one name into the snapshot.\n .filter((unique) => !declaredIndexNames.has(unique.name))\n .map((unique) => ({\n name: unique.name,\n columns: unique.columns,\n unique: true,\n }));\n\n const finalized: TableDef = {\n ...table,\n primaryKey: table.primaryKey\n ? { ...table.primaryKey, name: \"PRIMARY\" }\n : undefined,\n columns: table.columns.map((column) =>\n finalizeMySQLColumn(column, keyedColumns.has(column.name))\n ),\n indexes: [...table.indexes, ...uniquesAsIndexes],\n uniqueConstraints: [],\n };\n const ordinary = finalized.indexes.filter(\n (index) => !index.type || index.type === \"btree\"\n );\n const keys = [\n { name: \"PRIMARY\", columns: finalized.primaryKey?.columns ?? [] },\n ...ordinary.map((index) => ({\n name: index.name,\n columns: index.columns,\n })),\n ...finalized.foreignKeys.map((key) => ({\n name: key.name,\n columns: key.columns,\n })),\n ];\n for (const { name, columns } of keys) {\n for (const nameOfColumn of columns) {\n const column = finalized.columns.find(\n (column) => column.name === nameOfColumn\n );\n if (column && UNINDEXABLE_ORDINARY_TYPE.test(column.type)) {\n throw new MigrationError(\n `MySQL key \"${table.name}.${name}\" cannot directly index ${column.type} column \"${column.name}\". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: table.name, column: column.name } }\n );\n }\n }\n }\n const increments = finalized.columns.filter(\n (column) => column.autoIncrement\n );\n if (\n increments.length > 1 ||\n increments.some(\n (column) =>\n finalized.primaryKey?.columns[0] !== column.name &&\n !ordinary.some(\n (index) => index.columns[0] === column.name && !index.where\n ) &&\n !finalized.foreignKeys.some((key) => key.columns[0] === column.name)\n )\n ) {\n throw new MigrationError(\n `MySQL table \"${table.name}\" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return finalized;\n }\n\n /**\n * MySQL uses 1/0 for boolean values (TINYINT(1)).\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n /**\n * MySQL enum values are part of the column definition.\n * Returns ENUM('val1', 'val2', ...) syntax.\n */\n getEnumColumnType(\n _tableName: string,\n _columnName: string,\n values: string[]\n ): string {\n return mysqlEnumType(values);\n }\n\n // ===========================================================================\n // HELPER METHODS\n // ===========================================================================\n\n /**\n * MySQL integer types that support AUTO_INCREMENT.\n * Includes variations with UNSIGNED modifier.\n */\n private static readonly AUTO_INCREMENT_TYPES = new Set([\n \"tinyint\",\n \"smallint\",\n \"mediumint\",\n \"int\",\n \"integer\",\n \"bigint\",\n ]);\n\n /**\n * Validates that a column type is compatible with AUTO_INCREMENT.\n * Returns true if valid, throws MigrationError if invalid.\n */\n private validateAutoIncrementType(column: ColumnDef): void {\n // Extract base type (e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\")\n const baseType = column.type.toLowerCase().split(BASE_TYPE_PATTERN)[0]!;\n\n if (!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(baseType)) {\n throw new MigrationError(\n \"MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with AUTO_INCREMENT.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n }\n\n /**\n * Generates a column definition string for MySQL.\n */\n protected override generateColumnDef(\n column: ColumnDef,\n _context: DDLContext\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n const isGeoPoint = column.type.toUpperCase() === MYSQL_TYPE_DEFAULTS.point;\n\n // Handle auto-increment (MySQL uses AUTO_INCREMENT keyword)\n if (column.autoIncrement) {\n // Validate that the column type supports AUTO_INCREMENT\n this.validateAutoIncrementType(column);\n // Preserve the original type (including modifiers like UNSIGNED)\n parts.push(column.type);\n parts.push(\"AUTO_INCREMENT\");\n } else {\n parts.push(isGeoPoint ? MYSQL_POINT_BASE_TYPE : column.type);\n }\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // MySQL's grammar places the SRID attribute after nullability:\n // `POINT NOT NULL SRID 4326`, not `POINT SRID 4326 NOT NULL`.\n if (isGeoPoint) {\n parts.push(MYSQL_POINT_SRID_ATTRIBUTE);\n }\n\n // DEFAULT clause (an auto-increment column has no default to spell).\n // `finalizeMySQLColumn` already spelled a default whose storage class\n // refuses a literal as MySQL's expression default, so every default that\n // reaches here is one MySQL can take.\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n // The descriptor marker for a JSON-backed decimal LIST. A scalar needs\n // none — `DECIMAL(p,s)` spells its own domain — but JSON carries nothing,\n // so the comment is the only place a list's precision and scale survive\n // (§6.2). It is emitted from `generateColumnDef`, which is also what\n // `MODIFY COLUMN` renders, because MODIFY rewrites the WHOLE definition:\n // a comment this method did not re-emit would be dropped by the very\n // statement that changed the column.\n if (column.decimal && mysqlDecimalStorageKind(column) === \"list\") {\n parts.push(\n `COMMENT ${this.escapeValue(mysqlDecimalListMarker(column.decimal))}`\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const columnDefs = table.columns.map((col) =>\n this.generateColumnDef(col, context)\n );\n\n const increment = table.columns.find((column) => column.autoIncrement);\n const inlineIndex =\n increment && table.primaryKey?.columns[0] !== increment.name\n ? table.indexes.find(\n (index) =>\n (!index.type || index.type === \"btree\") &&\n !index.where &&\n index.columns[0] === increment.name\n )\n : undefined;\n if (inlineIndex)\n columnDefs.push(\n `${inlineIndex.unique ? \"UNIQUE \" : \"\"}KEY ${this.escapeIdentifier(inlineIndex.name)} (${inlineIndex.columns.map((column) => this.escapeIdentifier(column)).join(\", \")})`\n );\n\n // Primary key\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n columnDefs.push(`PRIMARY KEY (${pkCols})`);\n }\n\n // Unique constraints\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys (inline in CREATE TABLE for MySQL)\n for (const fk of table.foreignKeys) {\n columnDefs.push(this.foreignKeyClause(fk, context));\n }\n\n const sql = `CREATE TABLE ${this.tableRef(table.name, context.destination)} (\\n ${columnDefs.join(\",\\n \")}\\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`;\n\n const statements = [sql];\n\n // Indexes are created separately\n for (const idx of table.indexes) {\n if (idx === inlineIndex) continue;\n statements.push(\n this.generateCreateIndex(\n {\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n },\n context\n )\n );\n }\n\n return statements;\n }\n\n generateDropTable(op: DropTableOperation, context: DDLContext): string {\n // MySQL doesn't have CASCADE for DROP TABLE in the same way\n // Foreign key checks need to be disabled or FKs dropped first\n return `DROP TABLE IF EXISTS ${this.tableRef(op.tableName, context.destination)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, context: DDLContext): string {\n // BOTH sides carry the database (§5.1): `RENAME TABLE a TO b` names two\n // independent tables, and an unqualified destination would move the table\n // into the connection's default database instead of renaming it in place.\n return `RENAME TABLE ${this.tableRef(op.from, context.destination)} TO ${this.tableRef(op.to, context.destination)}`;\n }\n\n // An index or unique (one object here) is renamed in place. A foreign key\n // cannot be: it is dropped and added under its new name in the same\n // statement, so the key is never absent.\n protected override renameDerivedNames(\n owner: string,\n renames: ReadonlyMap<string, DerivedRename>,\n table: TableDef,\n context: DDLContext\n ): string[] {\n const clauses = [...renames].map(([from, { to }]) => {\n const key = table.foreignKeys.find((item) => item.name === from);\n return key\n ? `DROP FOREIGN KEY ${this.escapeIdentifier(from)}, ADD ${this.foreignKeyClause({ ...key, name: to }, context)}`\n : `RENAME INDEX ${this.escapeIdentifier(from)} TO ${this.escapeIdentifier(to)}`;\n });\n return [\n `ALTER TABLE ${this.tableRef(owner, context.destination)} ${clauses.join(\", \")}`,\n ];\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation, context: DDLContext): string {\n const colDef = this.generateColumnDef(op.column, context);\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, context: DDLContext): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(op: RenameColumnOperation, context: DDLContext): string {\n // MySQL 8.0+ supports RENAME COLUMN. Column names stay ONE identifier —\n // only the table position carries the database (§5.1).\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const { tableName, columnName, to } = op;\n const table = this.tableRef(tableName, context.destination);\n\n // Build the new column definition\n const colDef = this.generateColumnDef(to, context);\n\n const alter =\n // If column name changed, use CHANGE COLUMN (which handles rename + alter)\n columnName === to.name\n ? `ALTER TABLE ${table} MODIFY COLUMN ${colDef}`\n : `ALTER TABLE ${table} CHANGE COLUMN ${this.escapeIdentifier(columnName)} ${colDef}`;\n\n const bracket = this.decimalConversionBracket(op, table, context);\n return bracket === null\n ? [alter]\n : [bracket.validate, alter, bracket.release];\n }\n\n /**\n * The proof a decimal conversion runs inside, or `null` when the alteration\n * moves no stored decimal value.\n *\n * MySQL commits each DDL statement as it runs, so there is no transaction to\n * take a bad conversion back — the refusal has to happen BEFORE the column\n * moves. The CHECK constraint is that proof: adding it fails the ALTER when\n * any existing row would not survive the target domain, and it does so\n * whatever `sql_mode` is set to, which a bare `MODIFY COLUMN` does not — in a\n * non-strict mode MySQL answers an out-of-range or over-scaled conversion\n * with a warning and a truncated value, silently rewriting stored data.\n * That mode-independence is the constraint's whole reason to exist beside the\n * MODIFY that would also refuse in strict mode.\n *\n * It is DROPPED only after the alteration, not before it: while it stands, no\n * concurrent write can land a value the target domain would have to round.\n * That is how §7.4's \"while writes are excluded\" is spelled here, because the\n * obvious spelling — `LOCK TABLES` — is a transaction leader the artifact\n * classifier refuses, and growing that enumeration is forbidden.\n */\n private decimalConversionBracket(\n op: AlterColumnOperation,\n table: string,\n context: DDLContext\n ): { validate: string; release: string } | null {\n const { from, to } = op;\n const source = from.decimal;\n const target = to.decimal;\n if (target === undefined) return null;\n if (!decimalConversionRequired(from, to)) return null;\n if (op.columnName !== to.name) {\n throw new MigrationError(\n `The MySQL decimal conversion for \"${op.tableName}\".\"${op.columnName}\" also renames the column to \"${to.name}\". ` +\n \"Run the rename as a separate migration step before changing the decimal descriptor; an interrupted CHECK proof must keep one stable column identity across MySQL's implicit DDL commits.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"mysql\",\n table: op.tableName,\n column: op.columnName,\n type: \"decimal-conversion-with-rename\",\n },\n }\n );\n }\n\n const targetKind = mysqlDecimalStorageKind(to);\n if (source === undefined) {\n // An unmarked JSON container has no proven descriptor and therefore no\n // proven member scale. A scalar INT/BIGINT is different: its exact\n // logical meaning is an integer at scale zero, and the transient CHECK\n // can prove that every one survives the target domain unchanged.\n if (targetKind !== \"scalar\" || !isMySQLExactIntegerType(from.type)) {\n this.refuseDecimalAdoption(op, context, targetKind);\n }\n return this.decimalScalarConversionBracket(op, table, to.type, target);\n }\n\n const sourceKind = mysqlDecimalStorageKind(from);\n if (targetKind === undefined || sourceKind !== targetKind) {\n this.refuseDecimalConversion(\n op,\n context,\n `moves it from ${describeDecimalStorageKind(sourceKind)} to ${describeDecimalStorageKind(targetKind)} storage, which`\n );\n }\n if (targetKind === \"list\") {\n // The coefficient spelling stays exact only while scale stands still.\n // Widening then moves no member, but it still needs a live proof that\n // malformed or out-of-source-domain storage cannot acquire a wider\n // descriptor marker. Narrowing is deliberately refused: MySQL's\n // implicit DDL commits cannot make its stricter proof, marker change,\n // and cleanup one indivisible operation.\n const change = classifyDecimalListDescriptorChange(source, target);\n if (change === \"rescaling\") {\n this.refuseDecimalConversion(\n op,\n context,\n `moves its JSON list from ${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, which rescales every member and so`\n );\n }\n if (change === \"narrowing\") {\n this.refuseDecimalConversion(\n op,\n context,\n `narrows its JSON list from ${describeDecimalDomain(source)} to ${describeDecimalDomain(target)}, which`\n );\n }\n return this.decimalListConversionBracket(op, table, source);\n }\n return this.decimalScalarConversionBracket(op, table, to.type, target);\n }\n\n private decimalListConversionBracket(\n op: AlterColumnOperation,\n table: string,\n narrower: NonNullable<ColumnDef[\"decimal\"]>\n ): { validate: string; release: string } {\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\"list\", narrower)\n );\n const col = this.escapeIdentifier(op.columnName);\n return {\n validate: `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${mysqlDecimalListFitsCheck(col, narrower)})`,\n release: `ALTER TABLE ${table} DROP CHECK ${constraint}`,\n };\n }\n\n private decimalScalarConversionBracket(\n op: AlterColumnOperation,\n table: string,\n targetType: string,\n target: NonNullable<ColumnDef[\"decimal\"]>\n ): { validate: string; release: string } {\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\"scalar\", target)\n );\n const col = this.escapeIdentifier(op.columnName);\n return {\n validate: `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${mysqlDecimalFitsCheck(col, targetType)})`,\n release: `ALTER TABLE ${table} DROP CHECK ${constraint}`,\n };\n }\n\n /** Refuse an adoption whose source has no exact, descriptor-free meaning. */\n private refuseDecimalAdoption(\n op: AlterColumnOperation,\n context: DDLContext,\n targetKind: ReturnType<typeof mysqlDecimalStorageKind>\n ): never {\n throw new MigrationError(\n `The declared change to \"${op.tableName}\".\"${op.columnName}\" would adopt unmarked ${op.from.type} storage as a fixed-decimal ${describeDecimalStorageKind(targetKind)}. ` +\n \"Only INT and BIGINT have one exact descriptor-free meaning that a transient target-domain CHECK can prove. Approximate, text, native-decimal-without-descriptor, and unmarked JSON storage could already contain rounded values or members at an unknown scale. \" +\n \"The change is refused before any statement runs, so MySQL cannot implicitly round or reinterpret the stored data. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: op.tableName,\n column: op.columnName,\n feature: \"decimal storage adoption\",\n dialect: \"mysql\",\n target: context.destination,\n },\n }\n );\n }\n\n /**\n * Refuses a decimal conversion MySQL cannot perform without either rounding\n * stored values or leaving them half-converted.\n *\n * The unsafe case is always a REWRITE of stored bytes: a JSON list whose\n * members must be rescaled, or a column moving between the scalar and list\n * shapes. Same-scale precision widening needs only a proof and uses the\n * normalized-container CHECK above. Narrowing or changing scale cannot make\n * its stricter proof or member rewrite plus descriptor-marker DDL\n * indivisible across MySQL's implicit commits. It therefore refuses before\n * any statement runs; PostgreSQL and the SQLite family convert the same\n * change inside their atomic provider boundary.\n */\n private refuseDecimalConversion(\n op: AlterColumnOperation,\n context: DDLContext,\n reason: string\n ): never {\n throw new MigrationError(\n `The declared change to \"${op.tableName}\".\"${op.columnName}\" ${reason} would rewrite every stored value, and MySQL commits each DDL statement implicitly. ` +\n \"There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. \" +\n \"The change is refused before any statement runs, so the schema and its data are unchanged. Only same-scale precision widening is applied automatically; narrowing or a scale change needs an explicit migration that validates and moves the values itself.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: op.tableName,\n column: op.columnName,\n feature: \"decimal descriptor conversion\",\n dialect: \"mysql\",\n target: context.destination,\n },\n }\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, context: DDLContext): string {\n const { tableName, index } = op;\n\n // Validate index type\n this.validateIndexType(index.type, index.name);\n\n // MySQL has no partial index. Emitting the index without its predicate\n // would build a different index from the declared one and would index rows\n // the schema excluded, so refuse the declaration instead of dropping it.\n if (index.where) {\n throw new MigrationError(\n `Index \"${index.name}\" declares a partial index predicate (where: \"${index.where}\"). ` +\n \"MySQL does not support partial indexes. \" +\n \"Either remove 'where' from the index definition, or move the predicate into a generated column and index that.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { indexName: index.name, indexWhere: index.where } }\n );\n }\n\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n\n // MySQL index type syntax varies by type:\n // - FULLTEXT and SPATIAL are prefixes: CREATE FULLTEXT INDEX ...\n // - BTREE is default, no clause needed\n // Note: HASH indexes are not supported by InnoDB (only MEMORY engine supports them)\n let indexPrefix = \"\";\n\n if (index.type === \"fulltext\") {\n indexPrefix = \"FULLTEXT \";\n } else if (index.type === \"spatial\") {\n indexPrefix = \"SPATIAL \";\n }\n // btree is default, no prefix needed\n\n // UNIQUE cannot be combined with FULLTEXT or SPATIAL in MySQL\n if (index.unique && indexPrefix) {\n throw new MigrationError(\n `Cannot combine UNIQUE with ${index.type?.toUpperCase()} index \"${index.name}\". ` +\n `MySQL does not support UNIQUE ${index.type?.toUpperCase()} indexes. ` +\n `Either remove 'unique: true' from the index definition, or create a separate unique index.`,\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { indexName: index.name, indexType: index.type } }\n );\n }\n const unique = index.unique ? \"UNIQUE \" : \"\";\n\n // The index NAME stays one identifier; the table it is built on carries the\n // database (§5.1).\n return `CREATE ${unique}${indexPrefix}INDEX ${this.escapeIdentifier(index.name)} ON ${this.tableRef(tableName, context.destination)} (${cols})`;\n }\n\n generateDropIndex(op: DropIndexOperation, context: DDLContext): string {\n // MySQL DROP INDEX requires ON tableName syntax, and that table position is\n // the one that carries the database — the index name stays bare (§5.1).\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)} ON ${this.tableRef(op.tableName, context.destination)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} ADD ${this.foreignKeyClause(op.fk, context)}`;\n }\n\n private foreignKeyClause(fk: ForeignKeyDef, context: DDLContext): string {\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n let sql = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n sql += `FOREIGN KEY (${cols}) `;\n sql += `REFERENCES ${this.tableRef(fk.referencedTable, context.destination)} (${refCols})`;\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n sql += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n sql += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n return sql;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string {\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.tableRef(tableName, context.destination)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): string {\n // MySQL uses DROP INDEX for unique constraints\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP INDEX ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.tableRef(tableName, context.destination)} ADD PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): string {\n // MySQL doesn't name primary keys in DROP\n return `ALTER TABLE ${this.tableRef(op.tableName, context.destination)} DROP PRIMARY KEY`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // MySQL doesn't have standalone enum types - they're part of column defs\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // MySQL enums are inline with column definitions\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateDropEnum(_op: DropEnumOperation, _context: DDLContext): string {\n // No standalone enum to drop\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n // To alter an enum in MySQL, we need to MODIFY COLUMN for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n\n if (!newValues || newValues.length === 0) {\n return [`-- MySQL: no new values provided for enum \"${enumName}\"`];\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return [`-- MySQL: no dependent columns found for enum \"${enumName}\"`];\n }\n\n const statements: string[] = [];\n const enumType = this.getEnumColumnType(\"\", \"\", newValues);\n\n // Migrate rows off removed values before MODIFY COLUMN — with rows still\n // holding a removed value, MODIFY errors in strict mode. Replacement\n // targets must already exist in the old enum (surviving values or NULL);\n // mapping to a value added in the same alter is not supported.\n statements.push(...this.buildEnumReplacementUpdates(op, context));\n\n for (const dep of dependentColumns) {\n const currentTable = context.currentSchema?.tables.find(\n (t) => t.name === dep.tableName\n );\n const column = currentTable?.columns.find(\n (c) => c.name === dep.columnName\n );\n\n if (!column) {\n statements.push(\n `-- MySQL: column \"${dep.columnName}\" not found in table \"${dep.tableName}\"`\n );\n continue;\n }\n\n const table = this.tableRef(dep.tableName, context.destination);\n const col = this.escapeIdentifier(dep.columnName);\n const nullable = column.nullable ? \"\" : \" NOT NULL\";\n const defaultVal =\n column.default !== undefined ? ` DEFAULT ${column.default}` : \"\";\n\n statements.push(\n `ALTER TABLE ${table} MODIFY COLUMN ${col} ${enumType}${nullable}${defaultVal}`\n );\n }\n\n return statements;\n }\n\n /**\n * Proves the configured database exists (§5.2).\n *\n * The proof IS the resolution ({@link resolveCommandNamespace}), and no\n * migration command reaches this arm: the shared owner asks a dialect that\n * answers a spelling for that spelling instead, so `status()`, `log()`\n * and a dry push all keep the answer rather than discarding it here. The\n * override remains because the base class's proof is part of the dialect\n * contract and its default answers \"nothing to prove\", which is false for a\n * dialect whose estates are database-relative — an unlocked caller that only\n * wants the fact must not get a silent yes.\n */\n override async proveNamespaceExists(\n executeRaw: CatalogReader\n ): Promise<void> {\n await this.resolveCommandNamespace(executeRaw);\n }\n\n /**\n * Proves the configured database exists and answers the SERVER's spelling of\n * it, for the length of one command (§5.2).\n *\n * ONE `information_schema.SCHEMATA` read, with the configured name BOUND as\n * data. `DATABASE()` would answer with the connection's ambient default, and\n * an inference is exactly what this proof exists to remove: it would report\n * an existing sibling database as proof that the configured one is there.\n *\n * The answer matters because the read is deliberately case-insensitive:\n * `lower_case_table_names` can make a differently cased configured value name\n * the same physical database, so one case-folded candidate is accepted (see\n * `catalog.ts`). Under that acceptance the configured spelling is NOT what\n * the server has — `USE` fails on it, `TABLE_SCHEMA = ?` matches nothing, and\n * a reset inventory that binds it reports an existing database as empty. The\n * command-driver owner therefore binds this spelling onto the command's\n * driver view — for locked and read-only commands alike — and every statement\n * below renders from it.\n */\n async resolveCommandNamespace(read: CatalogRead): Promise<string> {\n return await resolveCatalogNamespace(read, this.namespace);\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * MySQL named locks are per-SERVER, not per-database, so a single global name\n * would serialize every database on the instance and a per-connection name\n * would serialize none. The name is derived from the configured database\n * (`mysqlMigrationLockName`), which is also why an unbound driver has no lock\n * to take: there is no scope to name.\n *\n * `lockId` is deliberately unused. It was the whole identity before; keeping\n * it in the name would only add a constant, and the scope that matters is the\n * database.\n */\n generateAcquireLock(_lockId: number): string | null {\n return mysqlAcquireLockStatement(\n this.requireLockScope(),\n MIGRATION_LOCK_TIMEOUT_SECONDS,\n (value) => this.escapeValue(value)\n );\n }\n\n generateReleaseLock(_lockId: number): string | null {\n return mysqlReleaseLockStatement(this.requireLockScope(), (value) =>\n this.escapeValue(value)\n );\n }\n\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"acquired\");\n }\n\n override provesLockReleased(rows: readonly unknown[]): boolean {\n return mysqlLockAnswer(rows, \"released\");\n }\n\n /**\n * The one admitted `USE`, spelled by the pinned-session owner (§13). It is\n * reachable only from a pinned migration session, which destroys its\n * connection afterwards, so the selection cannot leak into pooled traffic.\n *\n * On the command's own driver view `this.namespace` is the spelling the\n * SERVER answered with, which is the only one `USE` is guaranteed to accept:\n * on a case-sensitive server the configured `ProbeCase` is not the existing\n * `probecase`, and selecting it is a raw `Unknown database` error after a\n * proof that just admitted the database.\n */\n override generateSelectTarget(): string | null {\n if (this.namespace === undefined) {\n return null;\n }\n return mysqlSelectTargetStatement(this.namespace, (name) =>\n this.escapeIdentifier(name)\n );\n }\n\n /**\n * Proves the session's strict exact-value mode, then binds the command to\n * its ONE interrupted decimal-conversion recovery: planned by its first\n * sequential program (after apply has read its journal), empty for later\n * ones, and left untaken when the plan's own proof fails.\n */\n override async proveSession(read: CatalogRead): Promise<this> {\n await proveMySQLExactValueSession(\n read,\n `database \"${this.namespace ?? \"(unbound)\"}\"`\n );\n const namespace = this.requireLockScope();\n let taken = false;\n let planned: Promise<readonly string[]> | undefined;\n const command: this = Object.create(this);\n Object.defineProperty(command, \"programPreamble\", {\n value: async (producer: AnyDriver): Promise<readonly string[]> => {\n if (taken) return [];\n if (planned !== undefined) {\n await planned;\n return [];\n }\n planned = planInterruptedMySQLDecimalRecovery(\n (sql, params) => producer._executeRaw(sql, params),\n namespace,\n (name) => this.escapeIdentifier(name)\n );\n try {\n const statements = await planned;\n taken = true;\n return statements;\n } catch (error) {\n planned = undefined;\n throw error;\n }\n },\n });\n Object.freeze(command);\n return command;\n }\n\n /** A program no locked command bound has no recovery scope to run under. */\n override programPreamble(): Promise<readonly string[]> {\n return Promise.reject(\n new MigrationError(\n \"This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-migration-command\" } }\n )\n );\n }\n\n /**\n * The database whose migrations this lock serializes.\n *\n * An unbound driver is refused rather than falling back to a server-wide\n * name: a lock that covers every database on the instance is not this\n * estate's lock, and one that covers none protects nothing. No admitted path\n * reaches here unbound — the admission owner gates every locking command on\n * the resolved namespace first.\n */\n private requireLockScope(): string {\n if (this.namespace === undefined) {\n throw new MigrationError(\n \"This MySQL migration driver is not bound to a database, so there is no lock scope to name. \" +\n \"A MySQL named lock is server-wide, and VibORM will not take one that covers every database on the instance. Supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n return this.namespace;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The reset inventory, filtered on the bound database.\n *\n * `DATABASE()` had to go: with a connection whose default database is not the\n * configured one, it inventories — and therefore drops — a database this\n * client never targeted.\n *\n * The bound name is the command's own spelling (§5.2): `information_schema`\n * rows carry the server's, so binding a case-folded configured spelling here\n * matches nothing and reports an existing database as empty — an inventory\n * that decides what a reset DROPS cannot be answered by the wrong catalog.\n *\n * An unbound driver REFUSES rather than rendering a statement (plan §14,\n * 2026-08-27 — the one declared exception to §12.21's unbound byte-freeze).\n * There is no third option worth having: the baseline `DATABASE()` form is\n * the ambient target this feature exists to remove, and `= NULL` matches\n * nothing, so `reset` would inventory nothing, drop nothing, and report\n * success over a database it never looked at. No admitted command path\n * reaches here unbound — every caller is an effectful command the admission\n * owner has already gated — so this is what an unreachable arm does when it\n * is reached anyway.\n */\n generateInventoryTables(): { sql: string; params: unknown[] } {\n if (this.namespace === undefined) {\n throw new MigrationError(\n \"This MySQL migration driver is not bound to a database, so there is no table inventory to read. \" +\n \"VibORM will not fall back to the connection's ambient default database here: a reset inventory decides what gets DROPPED. Supply the live destination explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n return {\n sql: \"SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME\",\n params: [this.namespace],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // MySQL doesn't have standalone enum types\n return null;\n }\n}\n\n// Export singleton instance\nexport const mysqlMigrationDriver = new MySQLMigrationDriver();\n"],"mappings":"6oBAgBA,MAAM,cAAiB,IAAuB,CAC5C,QAAS,QACT,YACD,EAsED,eAAsB,wBACpB,EACA,EACiB,CACjB,GAAI,IAAc,IAAA,GAChB,MAAM,IAAI,EACR,wPAEA,EAAgB,wBAChB,CAAE,KAAM,CAAE,QAAS,QAAS,KAAM,mBAAoB,CAAE,CACzD,CAGH,GAAM,CAAE,QAAS,MAAM,EAAwB;;;;;EAAgB,CAAC,EAAU,CAAC,CAOrE,EAAa,EAChB,IAAK,GAAQ,EAAI,YAAY,CAC7B,OAAQ,GAAyB,OAAO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