viborm 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
- package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs → array-literal-BsbbSLw3.mjs} +1 -1
- package/dist/{array-literal-DcEm5tt_.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
- package/dist/base-AdXAoy6l.mjs +2 -0
- package/dist/base-AdXAoy6l.mjs.map +1 -0
- package/dist/batch-refs-4L8ECdPU.mjs +2 -0
- package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
- package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
- package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
- package/dist/builder-Ycvq3ETg.mjs +2 -0
- package/dist/builder-Ycvq3ETg.mjs.map +1 -0
- package/dist/bun-sql.d.mts +19 -2
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sql.mjs.map +1 -1
- package/dist/bun-sqlite.d.mts +9 -8
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/bun-sqlite.mjs.map +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/memory.mjs.map +1 -1
- package/dist/cache-BO57X0TT.mjs +2 -0
- package/dist/cache-BO57X0TT.mjs.map +1 -0
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/canonical-json-rfC2Dg0X.mjs +2 -0
- package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
- package/dist/chain-Dh0FV72b.mjs +2 -0
- package/dist/chain-Dh0FV72b.mjs.map +1 -0
- package/dist/cli.mjs +5 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-BLiBmykn.mjs +2 -0
- package/dist/client-BLiBmykn.mjs.map +1 -0
- package/dist/client-CCgfcp5A.mjs +52 -0
- package/dist/client-CCgfcp5A.mjs.map +1 -0
- package/dist/client-CRBo95D0.d.mts +610 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
- package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/controls-DXgIn4zh.mjs +2 -0
- package/dist/controls-DXgIn4zh.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-oIhiYZEP.mjs +2 -0
- package/dist/{datetime-physical-codec-BK93pJGW.mjs.map → datetime-physical-codec-oIhiYZEP.mjs.map} +1 -1
- package/dist/driver-B19QlFqn.mjs +2 -0
- package/dist/{driver-ZIbkciaz.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
- package/dist/driver-BlnKXPFF.mjs +2 -0
- package/dist/driver-BlnKXPFF.mjs.map +1 -0
- package/dist/driver.d.mts +2 -2
- package/dist/driver.mjs +1 -1
- package/dist/error-mapping-CnPCv1dm.mjs +2 -0
- package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
- package/dist/every-4KE0p2Gw.mjs +2 -0
- package/dist/every-4KE0p2Gw.mjs.map +1 -0
- package/dist/{execution-context-Bm_qTp1i.mjs → execution-context-BKR3bgES.mjs} +1 -1
- package/dist/{execution-context-Bm_qTp1i.mjs.map → execution-context-BKR3bgES.mjs.map} +1 -1
- package/dist/fs-estate-CAhDg7nY.mjs +2 -0
- package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
- package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
- package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
- package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
- package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
- package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
- package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
- package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
- package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
- package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
- package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
- package/dist/identity-CLFhCTZx.mjs +2 -0
- package/dist/identity-CLFhCTZx.mjs.map +1 -0
- package/dist/{index-BbcE-gyl.d.mts → index-C_XLSTy2.d.mts} +624 -351
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/instrumentation.mjs.map +1 -1
- package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
- package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs → json-number-CGXpPu4D.mjs} +1 -1
- package/dist/{json-number-TpD-pfqt.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
- package/dist/key-BeoOwGr3.mjs +2 -0
- package/dist/key-BeoOwGr3.mjs.map +1 -0
- package/dist/libsql-Bu_IdFU1.mjs +11 -0
- package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/memory-D4yxtCPK.mjs +2 -0
- package/dist/memory-D4yxtCPK.mjs.map +1 -0
- package/dist/migrations/mysql.d.mts +6 -0
- package/dist/migrations/mysql.mjs +2 -0
- package/dist/migrations/mysql.mjs.map +1 -0
- package/dist/migrations/postgres.d.mts +6 -0
- package/dist/migrations/postgres.mjs +2 -0
- package/dist/migrations/postgres.mjs.map +1 -0
- package/dist/migrations/sqlite.d.mts +6 -0
- package/dist/migrations/sqlite.mjs +2 -0
- package/dist/migrations/sqlite.mjs.map +1 -0
- package/dist/migrations/storage/durable-object.d.mts +17 -0
- package/dist/migrations/storage/durable-object.mjs +2 -0
- package/dist/migrations/storage/durable-object.mjs.map +1 -0
- package/dist/migrations/storage/fs.d.mts +6 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.d.mts +14 -0
- package/dist/migrations/storage/r2.mjs +2 -0
- package/dist/migrations/storage/r2.mjs.map +1 -0
- package/dist/migrations/tenant.d.mts +92 -0
- package/dist/migrations/tenant.mjs +2 -0
- package/dist/migrations/tenant.mjs.map +1 -0
- package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
- package/dist/migrations-DTObIjAm.mjs.map +1 -0
- package/dist/migrations.d.mts +6 -561
- package/dist/migrations.mjs +1 -1
- package/dist/migrations.mjs.map +1 -1
- package/dist/mysql-CibPaHSp.mjs +99 -0
- package/dist/mysql-CibPaHSp.mjs.map +1 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
- package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
- package/dist/mysql2.d.mts +1 -3
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/object-store-DQR6bTBY.mjs +2 -0
- package/dist/object-store-DQR6bTBY.mjs.map +1 -0
- package/dist/object-store-DyYOCtmX.d.mts +156 -0
- package/dist/observation-DUSm7oXK.mjs +2 -0
- package/dist/observation-DUSm7oXK.mjs.map +1 -0
- package/dist/pg.d.mts +37 -12
- package/dist/pg.mjs +1 -1
- package/dist/pg.mjs.map +1 -1
- package/dist/pglite.d.mts +2 -1
- package/dist/pglite.mjs +1 -1
- package/dist/pglite.mjs.map +1 -1
- package/dist/physical-6V_LNU3L.mjs +2 -0
- package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
- package/dist/pinned-session-CLxj5M5e.mjs +2 -0
- package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-Bbw8W81b.d.mts → planner-C6Lfsasx.d.mts} +57 -3
- package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
- package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
- package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
- package/dist/postgres-oqNW9xqo.mjs +415 -0
- package/dist/postgres-oqNW9xqo.mjs.map +1 -0
- package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
- package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
- package/dist/postgres.d.mts +11 -1
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/{provider-limits-DXj_pOT0.mjs → provider-limits-BHATED_m.mjs} +2 -2
- package/dist/{provider-limits-DXj_pOT0.mjs.map → provider-limits-BHATED_m.mjs.map} +1 -1
- package/dist/registration-preflight-DEjv050M.mjs +4 -0
- package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
- package/dist/result-shape-CTNdNSW3.mjs +2 -0
- package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
- package/dist/scalar-U0wD5bKy.mjs +2 -0
- package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema/json.mjs.map +1 -1
- package/dist/schema-Cjem1-0f.mjs +2 -0
- package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
- package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
- package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
- package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
- package/dist/settle-B9Vg1FnP.mjs +2 -0
- package/dist/settle-B9Vg1FnP.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
- package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
- package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
- package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
- package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
- package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -8
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
- package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
- package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
- package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
- package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
- package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
- package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
- package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
- package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
- package/dist/{transaction-operation-BC7aua5V.mjs.map → transaction-operation-CKK3l_9x.mjs.map} +1 -1
- package/dist/{utils-CRFUUfNn.mjs → utils-CZNaOZR7.mjs} +4 -3
- package/dist/utils-CZNaOZR7.mjs.map +1 -0
- package/dist/v-D5Z06FKN.mjs +2 -0
- package/dist/v-D5Z06FKN.mjs.map +1 -0
- package/dist/validation-Dk9Q_-C7.mjs +2 -0
- package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
- package/dist/validation-PF9-_nKd.mjs +2 -0
- package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-X9-bwtRo.mjs +2 -0
- package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
- package/dist/value-guards-CK9guf2Z.mjs +2 -0
- package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
- package/dist/version-JDaZht4U.mjs +2 -0
- package/dist/{version-De1l_ZMF.mjs.map → version-JDaZht4U.mjs.map} +1 -1
- package/package.json +75 -33
- package/dist/base-vfur-DaU.mjs +0 -2
- package/dist/base-vfur-DaU.mjs.map +0 -1
- package/dist/batch-refs-Op1fx9Bo.mjs +0 -6
- package/dist/batch-refs-Op1fx9Bo.mjs.map +0 -1
- package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs +0 -2
- package/dist/builder-DkWfNHEV.mjs.map +0 -1
- package/dist/chain-uIFlkkXS.mjs +0 -2
- package/dist/chain-uIFlkkXS.mjs.map +0 -1
- package/dist/client-C8gXvWIA.mjs +0 -2
- package/dist/client-C8gXvWIA.mjs.map +0 -1
- package/dist/client-z9mcpRtA.mjs +0 -435
- package/dist/client-z9mcpRtA.mjs.map +0 -1
- package/dist/controls-BhxRnPYS.mjs +0 -2
- package/dist/controls-BhxRnPYS.mjs.map +0 -1
- package/dist/datetime-physical-codec-BK93pJGW.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs +0 -2
- package/dist/driver-CHclfK3q.mjs.map +0 -1
- package/dist/driver-ZIbkciaz.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs +0 -2
- package/dist/driver-options-DVxWlZ0s.mjs.map +0 -1
- package/dist/error-mapping-LKqxnw-b.mjs +0 -2
- package/dist/error-mapping-LKqxnw-b.mjs.map +0 -1
- package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
- package/dist/fs-estate-BLqNdigQ.mjs +0 -2
- package/dist/fs-estate-BLqNdigQ.mjs.map +0 -1
- package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
- package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
- package/dist/key-DKaqPb8w.mjs +0 -2
- package/dist/key-DKaqPb8w.mjs.map +0 -1
- package/dist/migrations-BWZSBMZh.mjs.map +0 -1
- package/dist/mysql-adapter-DtZdwqzc.mjs +0 -2
- package/dist/mysql-adapter-DtZdwqzc.mjs.map +0 -1
- package/dist/observation-CLp8ylmL.mjs +0 -2
- package/dist/observation-CLp8ylmL.mjs.map +0 -1
- package/dist/physical-BkelResN.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs +0 -2
- package/dist/pinned-session-CNANv7bv.mjs.map +0 -1
- package/dist/postgres-adapter-ButxrmEa.mjs +0 -2
- package/dist/postgres-adapter-ButxrmEa.mjs.map +0 -1
- package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
- package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
- package/dist/result-shape-CKLOBSKl.mjs +0 -2
- package/dist/result-shape-CKLOBSKl.mjs.map +0 -1
- package/dist/scalar-BTktMqvO.mjs +0 -2
- package/dist/schema-BFNcMdO6.mjs +0 -2
- package/dist/schema-introspection-C7P7lwIs.mjs +0 -6
- package/dist/schema-introspection-C7P7lwIs.mjs.map +0 -1
- package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
- package/dist/sqlite-adapter-1krz0OXw.mjs +0 -2
- package/dist/sqlite-adapter-1krz0OXw.mjs.map +0 -1
- package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
- package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
- package/dist/transaction-oskVwmsf.mjs.map +0 -1
- package/dist/transactions-gjmrWN5W.mjs +0 -2
- package/dist/transactions-gjmrWN5W.mjs.map +0 -1
- package/dist/utils-CRFUUfNn.mjs.map +0 -1
- package/dist/v-B2WwtcRz.mjs +0 -2
- package/dist/v-B2WwtcRz.mjs.map +0 -1
- package/dist/validation-Du6j0Q38.mjs +0 -2
- package/dist/validation-Du6j0Q38.mjs.map +0 -1
- package/dist/validation-tgjL_9n8.mjs +0 -2
- package/dist/validator-DMlEScV3.mjs +0 -2
- package/dist/version-De1l_ZMF.mjs +0 -2
- /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
- /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-z9mcpRtA.mjs","names":["epochMilliseconds","WHITESPACE","escapeIdentifier","factor","COLUMNS_QUERY","namespace","quoteIdentifier","escapeIdentifier","refuse","literal","value","refuse","result","refuse","table","namespace","mode","namespace","requireDecimalDomain","IDENTIFIER_PART","ambiguousToResolveChange","actual","currentPk","desiredPk","control","placeholder","matches","int","literal","mapReferentialAction","introspect","introspect","namespace","COLUMNS_QUERY","PRIMARY_KEYS_QUERY","INDEXES_QUERY","FOREIGN_KEYS_QUERY","mapReferentialAction","formatColumnType","isAutoIncrement","readDecimalDomain","literal","cleanDefault","namespace","namespace","quoteIdentifier","namespace","introspectMySQL","literal","column","sql","namespace","mapReferentialAction","namespace","literal","namespace","namespace","columns","members","getModelTableName","index","table","column","refuse","steps"],"sources":["../src/adapters/databases/sqlite/storage/datetime.ts","../src/adapters/databases/sqlite/storage/sql-lexing.ts","../src/adapters/databases/sqlite/storage/column-constraints.ts","../src/adapters/databases/sqlite/storage/decimal.ts","../src/migrations/decimal.ts","../src/migrations/drivers/mysql/decimal-recovery.ts","../src/adapters/databases/sqlite/storage/geo-point.ts","../src/migrations/canonical-json.ts","../src/migrations/v1-parse-shared.ts","../src/migrations/v1-parse-snapshot.ts","../src/migrations/push-fingerprint.ts","../src/migrations/catalog-probes.ts","../src/migrations/base64.ts","../src/migrations/v1-parse-dispatch.ts","../src/migrations/v1-parse-control.ts","../src/migrations/v1-parse.ts","../src/migrations/control.ts","../src/migrations/input-boundary.ts","../src/migrations/drop-order.ts","../src/migrations/utils.ts","../src/migrations/target.ts","../src/migrations/pinned-session.ts","../src/migrations/admission.ts","../src/migrations/drivers/type-mapping.ts","../src/migrations/native-rename.ts","../src/migrations/types.ts","../src/migrations/resolver.ts","../src/migrations/push/enum-removals.ts","../src/migrations/differ.ts","../src/migrations/invert.ts","../src/migrations/sql-blob.ts","../src/migrations/statement-safety.ts","../src/migrations/compile.ts","../src/migrations/empty-snapshot.ts","../src/migrations/execute-dispatch.ts","../src/migrations/foreign-keys.ts","../src/migrations/graph.ts","../src/migrations/binary-conversion.ts","../src/migrations/drivers/base.ts","../src/migrations/drivers/sqlite/introspect.ts","../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts","../src/migrations/drivers/mysql/catalog.ts","../src/migrations/drivers/utils.ts","../src/migrations/drivers/mysql/introspect.ts","../src/migrations/drivers/mysql/pinned-session.ts","../src/migrations/drivers/mysql/index.ts","../src/migrations/identifier-conversion.ts","../src/migrations/drivers/postgres/canonicalize-index-predicate.ts","../src/migrations/drivers/postgres/introspect.ts","../src/migrations/drivers/postgres/index.ts","../src/migrations/drivers/index.ts","../src/migrations/serializer.ts","../src/migrations/push/format.ts","../src/migrations/push/planner.ts","../src/migrations/live-reset.ts","../src/migrations/sql-assembly.ts","../src/migrations/push-plan.ts","../src/migrations/apply-v1.ts","../src/migrations/check.ts","../src/migrations/generate-input.ts","../src/migrations/public-view.ts","../src/migrations/storage/contract.ts","../src/migrations/generate-v1.ts","../src/migrations/down-input.ts","../src/migrations/reset-v1.ts","../src/migrations/operators.ts","../src/migrations/push-consent.ts","../src/migrations/push-v1.ts","../src/migrations/client.ts"],"sourcesContent":["import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n MAX_DATETIME_EPOCH_MILLISECONDS,\n MIN_DATETIME_EPOCH_MILLISECONDS,\n} from \"@validation/primitives/datetime-values\";\nimport { createIdentifierQuoter } from \"../../../../sql/identifiers\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n/** SQL literals mirroring the public four-digit UTC DateTime domain. */\nconst SQLITE_MIN_INTEGER = \"-9223372036854775808\";\n\nconst ISO_DATE = \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\";\nconst ISO_TIME = \"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\";\nconst ISO_OFFSET = \"[+-][0-9][0-9]:[0-9][0-9]\";\nconst ISO_TIMESTAMP_SHAPES = [\n `${ISO_DATE}T${ISO_TIME}Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]${ISO_OFFSET}`,\n];\n\nexport function sqliteDateTimeTargetRequiresRecreation(\n from: DateTimePhysicalForm | undefined,\n to: DateTimePhysicalForm | undefined\n): boolean {\n return to !== undefined && from !== to;\n}\n\n/** SQLite spelling of JavaScript's `Math.round`, including negative halves. */\nfunction roundToInteger(expression: string): string {\n const integer = `CAST(${expression} AS INTEGER)`;\n const fraction = `(${expression} - ${integer})`;\n return (\n `(${integer} + CASE ` +\n `WHEN ${fraction} >= 0.5 THEN 1 ` +\n `WHEN ${fraction} < -0.5 THEN -1 ELSE 0 END)`\n );\n}\n\nfunction julianToEpochMilliseconds(julianDay: string): string {\n return roundToInteger(\n `((${julianDay} - ${UNIX_EPOCH_JULIAN_DAY}) * ${MILLISECONDS_PER_DAY})`\n );\n}\n\nfunction epochMillisecondsToJulian(epochMilliseconds: string): string {\n return (\n `((${epochMilliseconds} / ${MILLISECONDS_PER_DAY}.0) + ` +\n `${UNIX_EPOCH_JULIAN_DAY})`\n );\n}\n\nfunction textFractionMilliseconds(source: string): string {\n const first = `CAST(substr(${source}, 21, 1) AS INTEGER)`;\n const second = `CAST(substr(${source}, 22, 1) AS INTEGER)`;\n const third = `CAST(substr(${source}, 23, 1) AS INTEGER)`;\n return (\n `(CASE WHEN substr(${source}, 20, 1) <> '.' THEN 0 ELSE ` +\n `${first} * 100 + ` +\n `CASE WHEN substr(${source}, 22, 1) GLOB '[0-9]' THEN ${second} * 10 + ` +\n `CASE WHEN substr(${source}, 23, 1) GLOB '[0-9]' THEN ${third} ELSE 0 END ` +\n \"ELSE 0 END END)\"\n );\n}\n\nfunction textOffsetMilliseconds(source: string): string {\n const magnitude =\n `((CAST(substr(${source}, -5, 2) AS INTEGER) * 60 + ` +\n `CAST(substr(${source}, -2, 2) AS INTEGER)) * 60000)`;\n return (\n `(CASE WHEN substr(${source}, -1, 1) = 'Z' THEN 0 ` +\n `WHEN substr(${source}, -6, 1) = '+' THEN ${magnitude} ` +\n `ELSE -${magnitude} END)`\n );\n}\n\n/** Epoch milliseconds without SQLite's narrower timezone-offset parser. */\nfunction textToEpochMilliseconds(source: string): string {\n const day = julianToEpochMilliseconds(\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z')`\n );\n const local =\n `(${day} + CAST(substr(${source}, 12, 2) AS INTEGER) * 3600000 + ` +\n `CAST(substr(${source}, 15, 2) AS INTEGER) * 60000 + ` +\n `CAST(substr(${source}, 18, 2) AS INTEGER) * 1000 + ` +\n `${textFractionMilliseconds(source)})`;\n return `(${local} - ${textOffsetMilliseconds(source)})`;\n}\n\n/** Canonical ISO text for an admitted SQLite-range epoch millisecond. */\nfunction epochMillisecondsToText(epochMilliseconds: string): string {\n const wholeSeconds =\n `(CASE WHEN ${epochMilliseconds} < 0 AND ` +\n `${epochMilliseconds} % 1000 <> 0 ` +\n `THEN ${epochMilliseconds} / 1000 - 1 ` +\n `ELSE ${epochMilliseconds} / 1000 END)`;\n const milliseconds = `(((${epochMilliseconds} % 1000) + 1000) % 1000)`;\n return (\n \"(\" +\n `strftime('%Y-%m-%dT%H:%M:%S', ${wholeSeconds}, 'unixepoch') || ` +\n `printf('.%03dZ', ${milliseconds})` +\n \")\"\n );\n}\n\nfunction epochMilliseconds(source: string, form: DateTimePhysicalForm): string {\n if (form === \"epochMillis\") return source;\n if (form === \"julianDay\") return julianToEpochMilliseconds(source);\n return textToEpochMilliseconds(source);\n}\n\n/** SQL transcription of `validateIsoTimestamp`'s accepted string grammar. */\nfunction isIsoTimestamp(source: string): string {\n return `(${ISO_TIMESTAMP_SHAPES.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")})`;\n}\n\n/** Component rules used by the public ISO timestamp admission boundary. */\nfunction isAdmittedIsoTimestamp(source: string): string {\n const year = `CAST(substr(${source}, 1, 4) AS INTEGER)`;\n const month = `CAST(substr(${source}, 6, 2) AS INTEGER)`;\n const day = `CAST(substr(${source}, 9, 2) AS INTEGER)`;\n const hour = `CAST(substr(${source}, 12, 2) AS INTEGER)`;\n const minute = `CAST(substr(${source}, 15, 2) AS INTEGER)`;\n const second = `CAST(substr(${source}, 18, 2) AS INTEGER)`;\n const zulu = `substr(${source}, -1, 1) = 'Z'`;\n const offsetHour = `CAST(substr(${source}, -5, 2) AS INTEGER)`;\n const offsetMinute = `CAST(substr(${source}, -2, 2) AS INTEGER)`;\n const isLeapYear = `(${year} % 4 = 0 AND (${year} % 100 <> 0 OR ${year} % 400 = 0))`;\n const lastDay =\n `(CASE ${month} ` +\n `WHEN 2 THEN CASE WHEN ${isLeapYear} THEN 29 ELSE 28 END ` +\n \"WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 \" +\n \"ELSE 31 END)\";\n return (\n `${isIsoTimestamp(source)} AND ${month} BETWEEN 1 AND 12 AND ` +\n `${day} BETWEEN 1 AND ${lastDay} AND ${hour} BETWEEN 0 AND 23 AND ` +\n `${minute} BETWEEN 0 AND 59 AND ${second} BETWEEN 0 AND 59 AND ` +\n `(${zulu} OR (${offsetHour} BETWEEN 0 AND 23 AND ${offsetMinute} BETWEEN 0 AND 59)) AND ` +\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z') IS NOT NULL`\n );\n}\n\nfunction sourceIsExact(\n source: string,\n form: DateTimePhysicalForm,\n epoch: string\n): string {\n if (form === \"text\") {\n return (\n `typeof(${source}) = 'text' AND ${isAdmittedIsoTimestamp(source)} AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n if (form === \"epochMillis\") {\n return (\n `typeof(${source}) = 'integer' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n return (\n `typeof(${source}) = 'real' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS} AND ` +\n `${epochMillisecondsToJulian(epoch)} = ${source}`\n );\n}\n\nfunction targetValue(epoch: string, form: DateTimePhysicalForm): string {\n if (form === \"text\") return epochMillisecondsToText(epoch);\n if (form === \"epochMillis\") return epoch;\n return epochMillisecondsToJulian(epoch);\n}\n\nfunction targetIsExact(\n epoch: string,\n form: DateTimePhysicalForm,\n value: string\n): string {\n if (form === \"text\") {\n return `${value} IS NOT NULL AND ${isIsoTimestamp(value)}`;\n }\n if (form === \"epochMillis\") return \"1\";\n return `${julianToEpochMilliseconds(value)} = ${epoch}`;\n}\n\n/**\n * Converts one copied SQLite DateTime between its declared physical forms.\n *\n * The guard is the sole integrity boundary. It accepts only a value that is an\n * exact member of the source vocabulary and whose target representation\n * decodes to the same millisecond. `abs(INT64_MIN)` is SQLite's built-in,\n * deterministic error expression; it makes malformed, out-of-range, and\n * inexact rows abort the recreation instead of being rounded or reinterpreted.\n * An authenticated snapshot proves a same-form source and can retain it\n * unchanged. A live-introspected source has no logical marker, so even a\n * same-physical-form adoption crosses this guard before it becomes DateTime.\n */\nexport function sqliteDateTimeCopyExpression(\n source: string,\n from: DateTimePhysicalForm,\n to: DateTimePhysicalForm,\n isDeclaredSource: boolean\n): string {\n if (from === to && isDeclaredSource) return source;\n const epoch = epochMilliseconds(source, from);\n const value = from === to ? source : targetValue(epoch, to);\n const exact =\n from === to\n ? sourceIsExact(source, from, epoch)\n : `${sourceIsExact(source, from, epoch)} AND ${targetIsExact(epoch, to, value)}`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL ` +\n `WHEN ${exact} THEN ${value} ` +\n `ELSE abs(${SQLITE_MIN_INTEGER}) END`\n );\n}\n\n/** A reviewed manual-migration expression; the argument is a physical column name. */\nexport function sqliteCanonicalDateTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} THEN ${value} ELSE abs(${SQLITE_MIN_INTEGER}) END`;\n}\n\n/** The Time writer, the `viborm check --db` audit and the repair share one physical grammar. */\nfunction timeSource(source: string): { valid: string; value: string } {\n const shapes = [\n ISO_TIME,\n `${ISO_TIME}.[0-9]`,\n `${ISO_TIME}.[0-9][0-9]`,\n `${ISO_TIME}.[0-9][0-9][0-9]`,\n ];\n const valid = `typeof(${source}) = 'text' AND (${shapes.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")}) AND CAST(substr(${source},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${source},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${source},7,2) AS INTEGER) BETWEEN 0 AND 59`;\n const value = `substr(${source},1,8) || '.' || substr(CASE WHEN length(${source}) = 8 THEN '000' ELSE substr(${source},10) || '000' END,1,3)`;\n return { valid, value };\n}\n\n/** Canonical millisecond Time storage; malformed source rows abort the statement. */\nexport function sqliteCanonicalTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${valid} THEN ${value} ELSE abs(${SQLITE_MIN_INTEGER}) END`;\n}\n\n/** Exact canonical carrier predicates for `viborm check --db`: NULL passes, unknown/malformed does not. */\nexport function sqliteCanonicalDateTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\nexport function sqliteCanonicalTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${valid} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\n/** Counts one text DateTime/Time column's rows (scalar or JSON list) outside the canonical carrier. */\nexport function sqliteNoncanonicalTemporalCount(\n table: string,\n column: string,\n type: \"datetime\" | \"time\",\n list: boolean\n): string {\n const quote = createIdentifierQuoter('\"');\n const canonical =\n type === \"time\"\n ? sqliteCanonicalTimePredicate\n : sqliteCanonicalDateTimePredicate;\n const name = quote(column);\n // json_each is reached only after proving an array carrier. Each member\n // uses the same temporal domain as a scalar column.\n const noncanonical = list\n ? `CASE WHEN ${name} IS NULL THEN 0 WHEN json_valid(${name}) AND json_type(${name}) = 'array' THEN EXISTS (SELECT 1 FROM json_each(${name}) WHERE type <> 'text' OR NOT ${canonical(\"value\")}) ELSE 1 END`\n : `NOT ${canonical(column)}`;\n return `SELECT count(*) AS noncanonical FROM ${quote(table)} WHERE ${noncanonical}`;\n}\n","/** SQLite token boundaries shared by stored-DDL readers. */\n\n/** An identifier token and where it ends. */\nexport interface SqliteIdentifierToken {\n readonly value: string;\n readonly quoted: boolean;\n readonly end: number;\n}\n\nconst IDENTIFIER_CLOSERS: Readonly<Record<string, string>> = {\n '\"': '\"',\n \"`\": \"`\",\n \"[\": \"]\",\n};\n\nconst BARE_IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\nconst WHITESPACE = /\\s/;\n\n/** Whether one character can occur in SQLite's bare identifier spelling. */\nexport function isSqliteBareIdentifierCharacter(character: string): boolean {\n return BARE_IDENTIFIER_CHARACTER.test(character);\n}\n\n/**\n * Read the identifier at or after `index`, in any of SQLite's four spellings.\n *\n * A doubled quote inside a `\"…\"` or a `` `…` `` token is an escaped one.\n */\nexport function readSqliteIdentifier(\n text: string,\n index: number\n): SqliteIdentifierToken | undefined {\n let cursor = index;\n while (cursor < text.length) {\n while (cursor < text.length && WHITESPACE.test(text.charAt(cursor))) {\n cursor++;\n }\n const isComment =\n (text[cursor] === \"-\" && text[cursor + 1] === \"-\") ||\n (text[cursor] === \"/\" && text[cursor + 1] === \"*\");\n if (!isComment) break;\n cursor = skipSqlNonStructuralRegion(text, cursor);\n }\n const opener = text[cursor];\n if (opener === undefined) return undefined;\n\n const closer = IDENTIFIER_CLOSERS[opener];\n if (closer !== undefined) {\n let value = \"\";\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n if (text[cursor + 1] === closer && closer !== \"]\") {\n value += closer;\n cursor += 2;\n continue;\n }\n return { value, quoted: true, end: cursor + 1 };\n }\n value += text[cursor];\n cursor++;\n }\n return undefined;\n }\n\n const start = cursor;\n while (\n cursor < text.length &&\n isSqliteBareIdentifierCharacter(text.charAt(cursor))\n ) {\n cursor++;\n }\n if (cursor === start) return undefined;\n return { value: text.slice(start, cursor), quoted: false, end: cursor };\n}\n\n/**\n * The offset just past the quoted token or SQL comment starting at `index`, or\n * `index` itself when structural SQL starts there.\n */\nexport function skipSqlNonStructuralRegion(\n text: string,\n index: number\n): number {\n const opener = text[index];\n if (opener === undefined) return index;\n if (opener === \"-\" && text[index + 1] === \"-\") {\n const end = text.indexOf(\"\\n\", index + 2);\n return end === -1 ? text.length : end;\n }\n if (opener === \"/\" && text[index + 1] === \"*\") {\n const end = text.indexOf(\"*/\", index + 2);\n return end === -1 ? text.length : end + 2;\n }\n const closer = opener === \"'\" ? \"'\" : IDENTIFIER_CLOSERS[opener];\n if (closer === undefined) return index;\n\n let cursor = index + 1;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n // A doubled quote is an escaped one, not the end of the token. `]` has\n // no escape in SQLite's bracket spelling.\n if (text[cursor + 1] === closer && closer !== \"]\") {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n cursor++;\n }\n return text.length;\n}\n","import {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"./sql-lexing\";\n\n/** One top-level entry of a `CREATE TABLE` definition list. */\nexport interface SqliteTableDefinition {\n readonly text: string;\n /** The column this entry defines, or `undefined` for a table constraint. */\n readonly columnName: string | undefined;\n}\n\n/** A `CONSTRAINT <name>` at the top level of one definition. */\nexport interface SqliteConstraintClause {\n readonly name: string;\n /** Where the `CONSTRAINT` keyword starts inside the definition text. */\n readonly offset: number;\n}\n\n/** Keywords that open a table constraint rather than a column definition. */\nconst TABLE_CONSTRAINT_KEYWORDS = new Set([\n \"CONSTRAINT\",\n \"PRIMARY\",\n \"UNIQUE\",\n \"CHECK\",\n \"FOREIGN\",\n]);\n\n/**\n * Every top-level entry of the definition list, with the column each one\n * defines. Quoted tokens and comments are skipped before structural commas and\n * parentheses are interpreted.\n */\nexport function sqliteTableDefinitions(sql: string): SqliteTableDefinition[] {\n let open = -1;\n let scan = 0;\n while (scan < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, scan);\n if (skipped !== scan) {\n scan = skipped;\n continue;\n }\n if (sql[scan] === \"(\") {\n open = scan;\n break;\n }\n scan++;\n }\n if (open === -1) return [];\n\n const definitions: SqliteTableDefinition[] = [];\n let depth = 1;\n let start = open + 1;\n let cursor = start;\n while (cursor < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = sql[cursor];\n if (char === \"(\") depth++;\n else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n } else if (char === \",\" && depth === 1) {\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n start = cursor + 1;\n }\n cursor++;\n }\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n return definitions;\n}\n\nfunction describeDefinition(raw: string): SqliteTableDefinition {\n const text = raw.trim();\n const first = readSqliteIdentifier(text, 0);\n if (first === undefined) return { text, columnName: undefined };\n if (first.quoted) return { text, columnName: first.value };\n return {\n text,\n columnName: TABLE_CONSTRAINT_KEYWORDS.has(first.value.toUpperCase())\n ? undefined\n : first.value,\n };\n}\n\n/** Every structural `CONSTRAINT <name>` at depth zero of one definition. */\nexport function sqliteConstraintClauses(\n definition: string\n): SqliteConstraintClause[] {\n const clauses: SqliteConstraintClause[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = definition.charAt(cursor);\n const word = isSqliteBareIdentifierCharacter(char)\n ? readSqliteIdentifier(definition, cursor)\n : undefined;\n if (word !== undefined) {\n if (depth === 0 && word.value.toUpperCase() === \"CONSTRAINT\") {\n const name = readSqliteIdentifier(definition, word.end);\n if (name) {\n clauses.push({ name: name.value, offset: cursor });\n cursor = name.end;\n continue;\n }\n }\n cursor = word.end;\n continue;\n }\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n cursor++;\n }\n return clauses;\n}\n\n/** Structural keywords outside expression bodies, quoted tokens and comments. */\nexport function sqliteDefinitionKeywords(definition: string): string[] {\n const words: string[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const word = readSqliteIdentifier(definition, cursor);\n if (word && !word.quoted) {\n if (depth === 0) words.push(word.value.toUpperCase());\n cursor = word.end;\n continue;\n }\n if (definition[cursor] === \"(\") depth++;\n else if (definition[cursor] === \")\") depth--;\n cursor++;\n }\n return words;\n}\n","/**\n * SQLite fixed-decimal migration storage.\n *\n * SQLite cannot carry a decimal descriptor in its declared storage type, so\n * this module owns the reserved CHECK carrier, its structural reader, and the\n * exact table-rebuild expressions that rescale scalar and list coefficients.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"../../../../validation/primitives/decimal-codec\";\nexport type DecimalStorageKind = \"scalar\" | \"list\";\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n readonly decimal?: DecimalDescriptor | undefined;\n}\nexport function sqliteDecimalStorageKind(\n column: Pick<PhysicalColumn, \"type\" | \"decimal\">\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase();\n if (type === decimalColumnType(\"sqlite\", column.decimal)) return \"scalar\";\n return type === \"TEXT\" ? \"list\" : undefined;\n}\n\nimport {\n type SqliteConstraintClause,\n type SqliteTableDefinition,\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/**\n * The reserved SQLite constraint name for one decimal column.\n *\n * SQLite's declared type is the wrong carrier twice over: it stores `INTEGER`\n * (or `TEXT` for a list) whatever the domain is, and a CHECK written INTO the\n * type string never reads back — `PRAGMA table_info.type` reports only the\n * `type-name` production, so the desired `TEXT CHECK(...)` can never equal the\n * introspected `TEXT` and a full table recreation is planned on every push,\n * forever. (That is measured behaviour of the enum column type, not a\n * hypothetical.) So the descriptor rides in a NAMED constraint, and\n * introspection recovers it from the name.\n */\nexport function sqliteDecimalConstraintName(\n columnName: string,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${columnName}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/** The namespace VibORM reserves for the constraints it writes itself. */\nconst RESERVED_CONSTRAINT_PREFIX = \"viborm_decimal_\";\n\n/** `<precision>_<scale>`: what follows the column name in a reserved name. */\nconst RESERVED_CONSTRAINT_TAIL = /^(\\d+)_(\\d+)$/;\n\n/**\n * The declared domain of one column, read back out of the `CREATE TABLE` text\n * SQLite stored — or `undefined` when this column carries no reserved\n * constraint. The matching PRAGMA type and nullability travel with the column:\n * the stored clause is owned only when it is the exact writer rendering for\n * those physical facts.\n *\n * This PARSES, it does not search. The name alone is not evidence: SQLite\n * stores the statement verbatim, so any string literal a user can write — an\n * enum value, a string default, an index predicate — appears in the same text\n * and can spell VibORM's reserved prefix. A first-hit substring scan therefore\n * reads a user's data as a descriptor, and with an earlier offset it OVERRIDES\n * the real constraint: the next push plans a conversion between two domains\n * neither side declared and rewrites every stored coefficient. So the reader\n * walks the column-definition list the same quote-aware way\n * `partialIndexPredicate` walks a `CREATE INDEX` (`introspect.ts`), finds real\n * `CONSTRAINT <name> CHECK (…)` clauses, and binds each to the column definition\n * it actually sits in.\n *\n * A reserved name the module could not have written is REFUSED, not ignored.\n * Ignoring it is not the safe reading: the name is in a namespace only this\n * module writes, so its presence means either a corrupted carrier or a\n * collision, and both make every later push either wrong (a conversion between\n * invented domains) or non-convergent (a descriptor the desired side can never\n * match). The refusal names the constraint so the estate can be repaired.\n *\n * Ownership is proved by RE-RENDERING: the clause must be, byte for byte, what\n * {@link sqliteDecimalCheck} would emit for this column at the descriptor the\n * name declares. That is the only test that cannot be forged by a name alone,\n * and it is exact because SQLite re-spells nothing it stores.\n */\nexport function readSqliteDecimalConstraint(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n if (!tableSql) return undefined;\n // The reserved namespace has to appear at all before the statement is worth\n // parsing: introspection reads every column of every table, and the\n // overwhelming majority carry no decimal.\n if (!tableSql.includes(RESERVED_CONSTRAINT_PREFIX)) return undefined;\n\n let found: DecimalDescriptor | undefined;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(RESERVED_CONSTRAINT_PREFIX)) continue;\n // This reader is invoked once for every PRAGMA column. A reserved\n // column constraint is adjudicated when its own physical column is in\n // hand, because only that invocation knows the type and nullability the\n // database actually reported. TABLE constraints have no such invocation\n // and are always namespace squatters.\n if (\n definition.columnName !== undefined &&\n definition.columnName !== column.name\n ) {\n continue;\n }\n const descriptor = ownedDescriptor(\n definition,\n clause,\n column,\n escapeIdentifier\n );\n if (descriptor === undefined) {\n throw new MigrationError(\n `The stored definition carries a constraint named \"${clause.name}\", which is inside the namespace VibORM reserves for the fixed-decimal descriptor it writes itself, but it is not a constraint VibORM wrote. ` +\n \"A reserved constraint is the ONLY place a SQLite column's declared precision and scale survive — the storage class is INTEGER or TEXT at every domain — so reading this one as a descriptor would plan conversions between domains the schema never declared, and ignoring it would re-plan the same alteration on every push. \" +\n \"Rename or drop the constraint, or restore the definition VibORM wrote for this column.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n constraint: clause.name,\n // Absent for a TABLE constraint, which belongs to no column.\n ...(definition.columnName === undefined\n ? {}\n : { column: definition.columnName }),\n },\n }\n );\n }\n if (found !== undefined) {\n throw new MigrationError(\n `The stored definition carries more than one fixed-decimal descriptor for column \"${column.name}\": ${describeDecimalDomain(found)} and ${describeDecimalDomain(descriptor)}. ` +\n \"One physical column can have only one logical decimal domain, so introspection refuses the ambiguous reserved carriers instead of choosing one by order.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { column: column.name } }\n );\n }\n found = descriptor;\n }\n }\n return found;\n}\n\n/**\n * Whether one catalog column is the checked scaled-integer storage VibORM\n * writes for `descriptor`: INTEGER (TEXT for a list) carrying exactly that\n * descriptor's reserved CHECK. Typed queries never ask; `viborm check --db`\n * does, for a table VibORM did not create.\n */\nexport function isSqliteDecimalStorage(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): boolean {\n const stored = readSqliteDecimalConstraint(\n tableSql,\n column,\n escapeIdentifier\n );\n return (\n sameDecimalDescriptor(stored, descriptor) &&\n sqliteDecimalStorageKind({ type: column.type, decimal: stored }) === kind\n );\n}\n\n/** One top-level entry of a `CREATE TABLE`'s parenthesized definition list. */\n/**\n * The reserved constraint this clause carries, or `undefined` when the clause\n * is one this module could not have written.\n *\n * Three things must hold together, and each is a way the namespace gets\n * squatted: the clause sits in a COLUMN definition (never a table constraint,\n * which VibORM never writes); its name is this column's name followed by the\n * two numbers; and the whole clause re-renders byte for byte.\n */\nfunction ownedDescriptor(\n definition: SqliteTableDefinition,\n clause: SqliteConstraintClause,\n physicalColumn: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n const column = definition.columnName;\n if (column === undefined) return undefined;\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${column}_`;\n if (!clause.name.startsWith(prefix)) return undefined;\n const match = RESERVED_CONSTRAINT_TAIL.exec(clause.name.slice(prefix.length));\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"sqlite\");\n if (descriptor === undefined) return undefined;\n // PRAGMA owns the physical type and nullability. Re-render ONLY the shape\n // those facts permit; trying all four writer spellings lets an impossible\n // INTEGER/list or nullable/non-null carrier masquerade as a valid domain.\n const kind = sqliteDecimalStorageKind({\n ...physicalColumn,\n decimal: descriptor,\n });\n if (kind === undefined) return undefined;\n const rendered = sqliteDecimalCheck(\n physicalColumn,\n descriptor,\n kind,\n escapeIdentifier\n );\n if (definition.text.startsWith(rendered, clause.offset)) {\n return descriptor;\n }\n return undefined;\n}\n\n/**\n * Whether one generated table definition carries this column's reserved\n * decimal descriptor name in the structural column clause that owns it.\n *\n * Apply uses this only after it has proved the surrounding statement sequence\n * is VibORM's exact generated table-recreation program. It distinguishes the\n * decimal-column rename variant, whose copy expression needs no conversion\n * sentinel, from an unrelated recreation of a table that merely contains some\n * other decimal column.\n */\nexport function sqliteColumnDefinitionCarriesDecimalDescriptor(\n tableSql: string,\n columnName: string\n): boolean {\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${columnName}_`;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n if (definition.columnName !== columnName) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(prefix)) continue;\n const match = RESERVED_CONSTRAINT_TAIL.exec(\n clause.name.slice(prefix.length)\n );\n if (\n match &&\n readStoredDecimalDescriptor(match[1], match[2], \"sqlite\") !== undefined\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** `10^precision - 1`: the widest coefficient the domain can hold. */\nfunction maxCoefficient(precision: number): bigint {\n return 10n ** BigInt(precision) - 1n;\n}\n\n/**\n * The reserved CHECK a SQLite decimal column carries, as a complete column\n * constraint (`CONSTRAINT <name> CHECK (<body>)`).\n *\n * A scalar is the signed integer coefficient. A list is TEXT holding a JSON\n * array of coefficient strings. NULL passes only for a nullable column.\n */\nexport function sqliteDecimalCheck(\n column: { readonly name: string; readonly nullable: boolean },\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): string {\n const col = escapeIdentifier(column.name);\n const name = escapeIdentifier(\n sqliteDecimalConstraintName(column.name, descriptor)\n );\n const bound = maxCoefficient(descriptor.precision).toString();\n const body =\n kind === \"list\"\n ? `typeof(${col}) = 'text' AND json_valid(${col}) AND json_type(${col}) = 'array'`\n : `typeof(${col}) = 'integer' AND ${col} BETWEEN -${bound} AND ${bound}`;\n const guarded = column.nullable ? `${col} IS NULL OR (${body})` : body;\n return `CONSTRAINT ${name} CHECK (${guarded})`;\n}\n\n/**\n * The value a row lands in the rebuilt table when it does not fit the target\n * domain. It fails the target column's own reserved CHECK and aborts the whole\n * recreation atomically.\n */\nconst SCALAR_SENTINEL = \"'viborm:decimal-out-of-domain'\";\nconst LIST_SENTINEL = \"'viborm:decimal-list-out-of-domain'\";\n\ninterface Rescale {\n /** `10^|scale delta|`, as an integer literal. */\n readonly factor: string;\n readonly direction: \"up\" | \"down\" | \"none\";\n /** The inclusive absolute bound the SOURCE coefficient must satisfy. */\n readonly bound: string;\n}\n\n/** The one arithmetic decision behind every SQLite conversion expression. */\nfunction rescale(\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor\n): Rescale {\n const targetMax = maxCoefficient(to.precision);\n const sourceMax = from ? maxCoefficient(from.precision) : targetMax;\n const delta = to.scale - (from?.scale ?? 0);\n if (delta === 0) {\n return {\n factor: \"1\",\n direction: \"none\",\n bound: min(sourceMax, targetMax).toString(),\n };\n }\n if (delta > 0) {\n const factor = 10n ** BigInt(delta);\n return {\n factor: factor.toString(),\n direction: \"up\",\n bound: min(sourceMax, targetMax / factor).toString(),\n };\n }\n const factor = 10n ** BigInt(-delta);\n return {\n factor: factor.toString(),\n direction: \"down\",\n bound: min(sourceMax, targetMax * factor).toString(),\n };\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n}\n\n/**\n * The per-column source expression used by SQLite table recreation. It\n * converts stored values from `from`'s physical spelling to `to`'s without a\n * REAL intermediate and routes every malformed or out-of-domain value to the\n * target CHECK's sentinel.\n */\nexport function sqliteDecimalCopyExpression(\n source: string,\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor,\n kind: DecimalStorageKind\n): string {\n const { factor, direction, bound } = rescale(from, to);\n const exact = direction === \"down\" ? ` AND ${source} % ${factor} = 0` : \"\";\n if (kind === \"scalar\") {\n const converted = convertedCoefficient(source, direction, factor);\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' ` +\n `AND ${source} BETWEEN -${bound} AND ${bound}${exact} THEN ${converted} ` +\n `ELSE ${SCALAR_SENTINEL} END`\n );\n }\n return listCopyExpression(source, direction, factor, bound);\n}\n\nfunction convertedCoefficient(\n operand: string,\n direction: Rescale[\"direction\"],\n factor: string\n): string {\n if (direction === \"up\") return `${operand} * ${factor}`;\n if (direction === \"down\") return `${operand} / ${factor}`;\n return operand;\n}\n\n/** Convert a SQLite JSON coefficient-string list without losing order. */\nfunction listCopyExpression(\n source: string,\n direction: Rescale[\"direction\"],\n factor: string,\n bound: string\n): string {\n const member = `\"m\".\"value\"`;\n const asInteger = `CAST(${member} AS INTEGER)`;\n const exact = direction === \"down\" ? ` AND ${asInteger} % ${factor} = 0` : \"\";\n const admissible =\n `\"m\".\"type\" = 'text' AND CAST(${asInteger} AS TEXT) = ${member} ` +\n `AND ${asInteger} BETWEEN -${bound} AND ${bound}${exact}`;\n const converted = `CAST(${convertedCoefficient(`CAST(\"value\" AS INTEGER)`, direction, factor)} AS TEXT)`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'text' AND json_valid(${source}) = 1 THEN ` +\n `CASE WHEN json_type(${source}) = 'array' THEN CASE WHEN ` +\n `(SELECT count(*) FROM json_each(${source}) AS \"m\" WHERE NOT (${admissible})) = 0 THEN ` +\n `(SELECT json_group_array(${converted}) FROM (SELECT \"value\" FROM json_each(${source}) AS \"m\" ORDER BY \"m\".\"key\")) ` +\n `ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END`\n );\n}\n","/**\n * The migration layer's decimal renders.\n *\n * `@validation/primitives/decimal-codec` owns everything VALUE-shaped: the\n * grammar, canonical text, the logical <-> coefficient conversion, and the two\n * DDL renderings (`decimalColumnType`, `decimalDefaultText`). This module owns\n * what only a MIGRATION asks — the questions whose subject is a pair of\n * descriptors or a stored column rather than a value:\n *\n * - whether two snapshots describe the same domain, whether a change narrows\n * it, and which scalar/list storage shape a decimal column carries;\n * - the MySQL column-comment marker for a JSON-backed list; and\n * - the shared validation predicates used by native-decimal migration drivers.\n *\n * Everything here is PURE and connection-free: migration DDL is generated into\n * durable artifacts, so none of it may consult a database.\n *\n * Nothing here re-derives a precision or a scale. Every entry takes the frozen\n * descriptor its caller already holds (plan §1.1: no migration component stores\n * an independent precision or scale decision).\n */\n\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n readStoredDecimalDescriptor,\n sameDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ColumnDef } from \"./types\";\n\n/**\n * Whether moving from `from` to `to` SHRINKS the set of representable values —\n * the destructive half of a descriptor change.\n *\n * Two independent limits move: the fractional digits (`scale`) and the integer\n * digits (`precision - scale`). A change that lowers either one can find a\n * stored value it cannot hold, and the conversion then refuses; a change that\n * raises both is exact for every existing row. Widening the scale while keeping\n * the precision therefore counts as narrowing, because it takes an integer\n * digit away — `NUMERIC(10,2)` holds 99999999.99 and `NUMERIC(10,5)` does not.\n */\nexport function decimalDomainNarrows(\n from: DecimalDescriptor,\n to: DecimalDescriptor\n): boolean {\n const integerDigitsLost =\n to.precision - to.scale < from.precision - from.scale;\n return integerDigitsLost || to.scale < from.scale;\n}\n\n/**\n * Whether this alteration moves stored values INTO a declared decimal domain —\n * the ONE signal every provider's conversion route reads.\n *\n * Only the TARGET has to declare a domain. An absent source descriptor does not\n * make the change descriptor-free: it means the stored values were written\n * under some other reading, and adopting them under this one is exactly the\n * transition §7.3 governs. Skipping the conversion there is what silently\n * reinterprets a PostgreSQL `numeric` by rounding it through the `USING` cast,\n * and what copies a SQLite integer into a coefficient column at a scale it was\n * never written at. Each provider answers the absent source in its own terms —\n * PostgreSQL's target-domain CHECK is a complete proof on its own, and the\n * SQLite copy reads an untyped `INTEGER` as the logical integer it is — but the\n * QUESTION is one, so this is one predicate.\n *\n * The physical type is part of it beside the descriptor, because a scalar that\n * becomes a list keeps its precision and scale while changing storage class\n * completely. It is compared case-insensitively, the same reading the differ\n * takes: one snapshot side is the serializer's spelling and the other is\n * whatever the catalog answered.\n */\nexport function decimalConversionRequired(\n from: ColumnDef,\n to: ColumnDef\n): boolean {\n if (to.decimal === undefined) return false;\n return (\n !sameDecimalDescriptor(from.decimal, to.decimal) ||\n from.type.toUpperCase() !== to.type.toUpperCase()\n );\n}\n\n/**\n * Whether this alteration can lose data because the target domain is smaller.\n * The migration differ's destructive classifier is the sole consumer-facing\n * decision owner; this function owns only the decimal-domain question it asks.\n */\nexport function decimalChangeNarrows(from: ColumnDef, to: ColumnDef): boolean {\n if (from.decimal === undefined || to.decimal === undefined) return false;\n return decimalDomainNarrows(from.decimal, to.decimal);\n}\n\n/**\n * A storage shape, spelled for a refusal MESSAGE.\n *\n * `undefined` is a real answer here and it has to say so: it means the column's\n * declared type is neither of the two spellings this layer writes, which is a\n * different fact from \"the domain moved\" and must not be reported as one.\n */\nexport function describeDecimalStorageKind(\n kind: DecimalStorageKind | undefined\n): string {\n return kind ?? \"unrecognized\";\n}\n\n// =============================================================================\n// THE MYSQL DESCRIPTOR CARRIER\n// =============================================================================\n\n/**\n * The deterministic VibORM-owned column-comment marker for a JSON-backed MySQL\n * decimal list.\n *\n * A `DECIMAL(p,s)` column spells its own domain, but a decimal LIST is stored\n * as `JSON` (MySQL has no array type), and JSON carries nothing. The marker is\n * that column's descriptor, and it is the whole comment: introspection\n * recognizes only the exact marker (§6.2), so a hand-written comment that\n * merely mentions a decimal is not a descriptor.\n */\nexport function mysqlDecimalListMarker(descriptor: DecimalDescriptor): string {\n return `viborm:decimal(${descriptor.precision},${descriptor.scale})`;\n}\n\nconst MYSQL_LIST_MARKER = /^viborm:decimal\\((\\d+),(\\d+)\\)$/;\n\n/**\n * The domain a MySQL column comment declares, or `undefined` when it is not the\n * reserved marker. A marker-shaped comment with an invalid domain refuses.\n */\nexport function readMysqlDecimalListMarker(\n comment: string | null | undefined\n): DecimalDescriptor | undefined {\n if (!comment) return undefined;\n const match = MYSQL_LIST_MARKER.exec(comment);\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"mysql\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n \"The stored MySQL column comment uses VibORM's reserved decimal-list marker but carries an invalid fixed-decimal descriptor. \" +\n \"A reserved marker must contain finite safe integers inside the complete MySQL decimal domain; repair or remove the comment before running migrations.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n\n// =============================================================================\n// THE DIALECT STORAGE SHAPES\n// =============================================================================\n\n/**\n * How one dialect physically holds a decimal: one value, or a container of\n * them. The migration layer reads it off the column rather than the model,\n * because a snapshot side may have come from introspection.\n */\nexport type { DecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\nimport {\n type DecimalStorageKind,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\n\nexport {\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"@validation/primitives/decimal-codec\";\nexport { sqliteDecimalStorageKind } from \"../adapters/databases/sqlite/storage/decimal\";\n\n/**\n * The storage shape of a MySQL decimal column, or `undefined` when the column\n * holds no decimal.\n *\n * A scalar spells its own domain in `DECIMAL(p,s)` — introspection reads it\n * back lowercased, so the comparison is case-insensitive — and a list is the\n * `JSON` container every MySQL list gets, carrying its domain in the\n * column-comment marker instead.\n *\n * A MODIFIER after the domain does not change the storage shape.\n * `decimal(10,2) unsigned` and `decimal(10,2) zerofill` are the same physical\n * decimal, introspected verbatim through `formatColumnType`'s modifier arm, and\n * a shape of `undefined` for them would refuse the very ALTER that normalizes\n * them — an estate that could never converge. The domain token itself still has\n * to match the descriptor EXACTLY, so `DECIMAL(10,20)` is not `DECIMAL(10,2)`\n * with a modifier.\n */\nexport function mysqlDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \" \").trim();\n const scalar = decimalColumnType(\"mysql\", column.decimal);\n if (type === scalar || type.startsWith(`${scalar} `)) return \"scalar\";\n return type === MYSQL_DECIMAL_LIST_TYPE ? \"list\" : undefined;\n}\n\n/** PostgreSQL's native scalar and native-array decimal storage shapes. */\nexport function postgresDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase().replace(/\\s+/g, \"\").trim();\n const scalar = decimalColumnType(\"pg\", column.decimal);\n if (type === scalar) return \"scalar\";\n return type === `${scalar}[]` ? \"list\" : undefined;\n}\n\n/**\n * The provider-independent scalar/list identity of a migration decimal.\n *\n * Rename detection needs the shape, not typmod equality: changing a decimal\n * descriptor necessarily changes PostgreSQL/MySQL's physical type spelling,\n * while it keeps the same value/container identity and can still be a native\n * column rename followed by one exact conversion.\n */\nexport function migrationDecimalStorageKind(\n column: ColumnDef\n): DecimalStorageKind | undefined {\n return (\n postgresDecimalStorageKind(column) ??\n mysqlDecimalStorageKind(column) ??\n sqliteDecimalStorageKind(column)\n );\n}\n\n/** MySQL has no array type; every list is JSON, decimal lists included. */\nexport const MYSQL_DECIMAL_LIST_TYPE = \"JSON\";\n\n/**\n * TEXT, not the blanket `JSON` every other SQLite list gets: the list's\n * reserved CHECK asserts `typeof = 'text'`, and `JSON` has NUMERIC affinity\n * under SQLite's rules (it contains none of INT/CHAR/CLOB/TEXT/BLOB/REAL/FLOA/\n * DOUB), which would try to convert a numeric-looking container on the way in.\n */\nexport const SQLITE_DECIMAL_LIST_TYPE = \"TEXT\";\n\n// =============================================================================\n// THE PostgreSQL / MySQL VALIDATION PREDICATE\n// =============================================================================\n\n/**\n * The transient constraint a native-decimal conversion validates through.\n *\n * It is added, kept live ACROSS the type change, and dropped after. That\n * ordering is the whole design: the constraint proves every EXISTING row\n * already fits the target domain, and — because it stays — no concurrent write\n * can land a value the target would have to round while the conversion runs.\n * It is how \"while writes are excluded\" is spelled on MySQL, whose `LOCK\n * TABLES` the artifact classifier refuses as a transaction leader.\n */\n/**\n * The compact identity of one transient conversion proof.\n *\n * The table and column deliberately stay out of this identity: MySQL can\n * publish a different table-name spelling through `lower_case_table_names`,\n * while an interrupted proof must authenticate before the original spelling\n * is available again. The exact catalog CHECK authenticates its table and\n * column instead. Kind, precision and scale are already a small, bounded,\n * collision-free identity, so spelling them directly is both shorter and\n * stronger than hashing them: recovery can authenticate the declared proof\n * without searching or trusting a lossy digest.\n */\nexport function decimalConversionConstraintName(\n kind: DecimalStorageKind,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${kind === \"scalar\" ? \"s\" : \"l\"}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/**\n * \"The target domain admits this value UNCHANGED\", as a CHECK body.\n *\n * One idea, spelled in each dialect's cast syntax: a cast to the target type\n * rounds a value with too many fractional digits and refuses one with too many\n * integer digits, so a value that survives the cast intact is exactly a value\n * the conversion does not have to change. That is §7.3's rule — \"convert only\n * when every value fits\", and \"no descriptor change rounds existing data\" —\n * without a per-digit predicate. PostgreSQL's `numeric` also admits special\n * non-finite values, and `NaN` compares equal to itself, so finiteness is an\n * independent part of the proof. Arrays prove it for every member beside the\n * existing NULL-member refusal, while the outer `column IS NULL` continues to\n * admit a nullable whole list.\n *\n * The type token is the one `decimalColumnType` produced for the target column,\n * array suffix included; nothing here re-spells it.\n */\nexport function postgresDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n const unchanged = `${column} = ${column}::${targetType}`;\n if (targetType.endsWith(\"[]\")) {\n const hasNoNonFiniteMember = [\"NaN\", \"Infinity\", \"-Infinity\"]\n .map((value) => `array_position(${column}, '${value}'::numeric) IS NULL`)\n .join(\" AND \");\n return `${column} IS NULL OR (array_position(${column}, NULL) IS NULL AND ${hasNoNonFiniteMember} AND ${unchanged})`;\n }\n const hasFiniteValue = `${column} NOT IN ('NaN'::numeric, 'Infinity'::numeric, '-Infinity'::numeric)`;\n return `${column} IS NULL OR (${hasFiniteValue} AND ${unchanged})`;\n}\n\n/** {@link postgresDecimalFitsCheck}'s MySQL spelling. */\nexport function mysqlDecimalFitsCheck(\n column: string,\n targetType: string\n): string {\n return `${column} IS NULL OR ${column} = CAST(${column} AS ${targetType})`;\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalFitsCheck}. */\nexport function mysqlDecimalFitsCatalogCheck(\n column: string,\n targetType: string\n): string {\n return `((${column} is null) or (${column} = cast(${column} as ${targetType})))`;\n}\n\nfunction mysqlDecimalListCheckParts(\n column: string,\n descriptor: DecimalDescriptor\n): { readonly rendered: string; readonly normalizedContainer: string } {\n const coefficient = `(\"0\"|\"-?[1-9][0-9]{0,${descriptor.precision - 1}}\")`;\n return {\n rendered: `CAST(${column} AS CHAR CHARACTER SET utf8mb4)`,\n normalizedContainer: `^.(${coefficient}(, ${coefficient})*)?.$`,\n };\n}\n\n/**\n * A MySQL JSON decimal list is already in the target domain without changing\n * one stored byte.\n *\n * MySQL CHECK expressions cannot contain a subquery, so this validates the\n * provider's own normalized JSON rendering as one anchored language. Every\n * member must be a JSON string carrying the canonical coefficient grammar,\n * and the digit bound comes from the narrower descriptor that must remain true\n * across the marker change. `LEFT` and `RIGHT` prove the two brackets while\n * the anchored regular expression uses one character for each. That avoids a\n * backslash whose SQL meaning would depend on `NO_BACKSLASH_ESCAPES`.\n */\nexport function mysqlDecimalListFitsCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n return (\n `${column} IS NULL OR (` +\n `LEFT(${rendered}, 1) = '[' AND RIGHT(${rendered}, 1) = ']' AND ` +\n `REGEXP_LIKE(${rendered}, '${normalizedContainer}', 'c'))`\n );\n}\n\n/** MySQL's catalog-normalized shape for {@link mysqlDecimalListFitsCheck}. */\nexport function mysqlDecimalListFitsCatalogCheck(\n column: string,\n descriptor: DecimalDescriptor\n): string {\n const { rendered, normalizedContainer } = mysqlDecimalListCheckParts(\n column,\n descriptor\n );\n const catalogRendered = rendered.replace(\n \"CHAR CHARACTER SET\",\n \"char charset\"\n );\n return (\n `((${column} is null) or (` +\n `(${`LEFT(${catalogRendered}, 1)`} = '[') and ` +\n `(${`RIGHT(${catalogRendered}, 1)`} = ']') and ` +\n `${`REGEXP_LIKE(${catalogRendered}, '${normalizedContainer}', 'c')`}))`\n );\n}\n","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","import { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n} from \"../../../../validation/primitives/geo-values\";\nimport { sqliteBinary64JsonNumber } from \"./json-number\";\n\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nimport {\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/** TEXT-affinity spelling reserved for VibORM's canonical GeoPoint carrier. */\nexport const SQLITE_GEO_POINT_TYPE = \"VIBORM_GEO_TEXT\";\n\n/** Fixed so a native column rename cannot stale the constraint identity. */\nconst SQLITE_GEO_POINT_CONSTRAINT = \"viborm_geo\";\n\n/** The complete writer-owned column constraint for one GeoPoint carrier. */\nexport function sqliteGeoPointCheck(\n column: Pick<PhysicalColumn, \"name\" | \"nullable\">,\n escapeIdentifier: (name: string) => string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const col = escapeIdentifier(column.name);\n const longitude = `json_extract(${col}, '$.longitude')`;\n const latitude = `json_extract(${col}, '$.latitude')`;\n const valid =\n `CASE WHEN typeof(${col}) = 'text' AND json_valid(${col}) THEN (` +\n `json_type(${col}) = 'object' AND ` +\n `json_type(${col}, '$.longitude') IN ('integer', 'real') AND ` +\n `json_type(${col}, '$.latitude') IN ('integer', 'real') AND ` +\n `${longitude} > ${GEO_LONGITUDE_MIN} AND ${longitude} <= ${GEO_LONGITUDE_MAX} AND ` +\n `${latitude} >= ${GEO_LATITUDE_MIN} AND ${latitude} <= ${GEO_LATITUDE_MAX} AND ` +\n `${col} = ${sqliteGeoPointCarrier(col, encoding)}` +\n \") ELSE 0 END\";\n const body = column.nullable ? `${col} IS NULL OR (${valid})` : valid;\n return `CONSTRAINT ${escapeIdentifier(SQLITE_GEO_POINT_CONSTRAINT)} CHECK (${body})`;\n}\n\n/**\n * Proves that SQLite's reserved declared type is paired with the exact\n * writer-owned constraint. A reserved type without its proof is refused rather\n * than published as a GeoPoint or silently normalized into one.\n */\nexport function readSqliteGeoPointColumn(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): \"legacy\" | \"binary64\" | undefined {\n if (column.type.toUpperCase() !== SQLITE_GEO_POINT_TYPE) return undefined;\n const expected = sqliteGeoPointCheck(column, escapeIdentifier);\n const legacy = sqliteGeoPointCheck(column, escapeIdentifier, \"legacy\");\n let encoding: \"legacy\" | \"binary64\" = \"binary64\";\n let matching = 0;\n for (const definition of sqliteTableDefinitions(tableSql ?? \"\")) {\n if (definition.columnName !== column.name) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (clause.name !== SQLITE_GEO_POINT_CONSTRAINT) continue;\n if (definition.text.startsWith(expected, clause.offset))\n encoding = \"binary64\";\n else if (definition.text.startsWith(legacy, clause.offset))\n encoding = \"legacy\";\n else refuseUnprovenGeoPoint(column);\n matching++;\n }\n }\n if (matching !== 1) refuseUnprovenGeoPoint(column);\n return encoding;\n}\n\nfunction refuseUnprovenGeoPoint(\n column: Pick<PhysicalColumn, \"name\" | \"type\">\n): never {\n throw new MigrationError(\n `SQLite column \"${column.name}\" uses VibORM's reserved GeoPoint type \"${column.type}\" without the exact canonical GeoPoint CHECK constraint. ` +\n \"Migration introspection is refused rather than treating an unproven JSON carrier as a GeoPoint.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"sqlite\",\n column: column.name,\n type: column.type,\n },\n }\n );\n}\n\n/** Copying legacy storage preserves the double still present, not earlier lost digits. */\nexport function sqliteGeoPointCarrier(\n source: string,\n encoding: \"legacy\" | \"binary64\" = \"binary64\"\n): string {\n const longitude = `json_extract(${source}, '$.longitude')`;\n const latitude = `json_extract(${source}, '$.latitude')`;\n return `json_object('longitude', ${encoding === \"legacy\" ? longitude : sqliteBinary64JsonNumber(longitude)}, 'latitude', ${encoding === \"legacy\" ? latitude : sqliteBinary64JsonNumber(latitude)})`;\n}\n\n/** Format-1 snapshots predating the precision annotation describe the legacy CHECK. */\nexport function sqliteGeoPointEncoding(column: {\n readonly type: string;\n readonly geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}): \"legacy\" | \"binary64\" | undefined {\n return column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE\n ? (column.geoPointEncoding ?? \"legacy\")\n : undefined;\n}\n","/**\n * RFC 8785 JSON Canonicalization Scheme (JCS).\n *\n * Hash identity is these exact UTF-8 bytes. No locale, insertion order,\n * platform line ending, or display formatter participates.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\n\nconst UTF8 = new TextEncoder();\n\nexport function canonicalizeJson(value: unknown): Uint8Array {\n return UTF8.encode(serializeJcs(value));\n}\n\nexport function canonicalizeJsonText(value: unknown): string {\n return serializeJcs(value);\n}\n\nfunction serializeJcs(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\") return serializeNumber(value);\n if (Array.isArray(value)) {\n const parts = new Array<string>(value.length);\n for (let i = 0; i < value.length; i++) {\n parts[i] = serializeJcs(value[i]);\n }\n return `[${parts.join(\",\")}]`;\n }\n if (isRecord(value)) {\n const keys = Object.keys(value).sort(compareUtf16);\n const parts = new Array<string>(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n parts[i] = `${JSON.stringify(key)}:${serializeJcs(value[key])}`;\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new MigrationError(\n \"Canonical JSON refuses undefined, bigint, function, symbol, and boxed values\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nfunction serializeNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"Canonical JSON refuses NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (Object.is(value, -0)) return \"0\";\n return JSON.stringify(value);\n}\n\nfunction compareUtf16(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nexport function assertCanonicalBytes(\n bytes: Uint8Array,\n reconstructed: unknown,\n label: string\n): void {\n const expected = canonicalizeJson(reconstructed);\n if (bytes.length !== expected.length) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n for (let i = 0; i < bytes.length; i++) {\n if (bytes[i] !== expected[i]) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n `${label} must be UTF-8 without a BOM`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch (cause) {\n throw new MigrationError(\n `${label} is not valid UTF-8 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE,\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) return false;\n }\n return true;\n}\n","/**\n * Shared hostile-parse primitives for Migration V1.\n *\n * Exact-key admission and primitive field readers. Artifact parsers own\n * their shapes; this file owns only the reusable refuse/key helpers.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isNumber, isRecord, isString } from \"../validation/value-guards\";\n\nexport function refuse(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE);\n}\n\nexport function exactObject(\n value: unknown,\n allowed: readonly string[],\n required: readonly string[],\n label: string\n): Record<string, unknown> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) refuse(`${label} has unknown key ${key}`);\n }\n for (const key of required) {\n if (!(key in value)) refuse(`${label} is missing ${key}`);\n }\n return value;\n}\n\nexport function parseFormat(value: unknown, label: string): \"1\" {\n if (value !== \"1\") refuse(`${label} format must be \"1\"`);\n return \"1\";\n}\n\nexport function parseFiniteInteger(value: unknown, label: string): number {\n if (\n !(isNumber(value) && Number.isInteger(value) && Number.isSafeInteger(value))\n ) {\n refuse(`${label} must be a safe integer`);\n }\n return value;\n}\n\nexport function parseRequiredString(value: unknown, label: string): string {\n if (!isString(value) || value.length === 0)\n refuse(`${label} must be a non-empty string`);\n return value;\n}\n\nexport function parseStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) => {\n if (!isString(entry)) refuse(`${label}[${index}] must be a string`);\n return entry;\n });\n}\n\nexport function parseIdentifierArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) refuse(`${label} must be an array`);\n return value.map((entry, index) =>\n parseRequiredString(entry, `${label}[${index}]`)\n );\n}\n","/**\n * Hostile parser and hash owner for Migration V1 schema snapshots.\n *\n * Snapshot bytes are admitted only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport {\n exactObject,\n parseIdentifierArray,\n parseRequiredString,\n parseStringArray,\n refuse,\n} from \"./v1-parse-shared\";\n\nconst SNAPSHOT_KEYS = [\"enums\", \"polymorphicStorage\", \"tables\"] as const;\nconst TABLE_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"name\",\n \"primaryKey\",\n \"relationStorage\",\n \"uniqueConstraints\",\n] as const;\nconst TABLE_REQUIRED_KEYS = [\n \"columns\",\n \"foreignKeys\",\n \"indexes\",\n \"name\",\n \"uniqueConstraints\",\n] as const;\nconst COLUMN_KEYS = [\n \"autoIncrement\",\n \"dateTime\",\n \"geoPointEncoding\",\n \"decimal\",\n \"default\",\n \"name\",\n \"nullable\",\n \"type\",\n] as const;\nconst DECIMAL_KEYS = [\"precision\", \"scale\"] as const;\nconst PRIMARY_KEY_KEYS = [\"columns\", \"name\"] as const;\nconst INDEX_KEYS = [\"columns\", \"name\", \"type\", \"unique\", \"where\"] as const;\nconst FOREIGN_KEY_KEYS = [\n \"columns\",\n \"name\",\n \"onDelete\",\n \"onUpdate\",\n \"referencedColumns\",\n \"referencedTable\",\n] as const;\nconst UNIQUE_CONSTRAINT_KEYS = [\"columns\", \"name\"] as const;\nconst ENUM_KEYS = [\"name\", \"values\"] as const;\nconst RELATION_STORAGE_KEYS = [\n \"idColumn\",\n \"index\",\n \"kind\",\n \"typeColumn\",\n] as const;\nconst POLYMORPHIC_TO_ONE_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n \"storageRef\",\n] as const;\nconst POLYMORPHIC_TO_MANY_KEYS = [\n \"kind\",\n \"members\",\n \"ownerTable\",\n \"relation\",\n] as const;\nconst POLYMORPHIC_TO_ONE_MEMBER_KEYS = [\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\nconst POLYMORPHIC_TO_MANY_MEMBER_KEYS = [\n \"inverseCardinality\",\n \"memberJunctionTable\",\n \"publicType\",\n \"storedType\",\n \"targetTable\",\n] as const;\n\nfunction parseColumn(value: unknown, label: string): ColumnDef {\n const record = exactObject(\n value,\n COLUMN_KEYS,\n [\"name\", \"nullable\", \"type\"],\n label\n );\n if (!isBoolean(record.nullable)) refuse(`${label}.nullable must be boolean`);\n const column: ColumnDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n type: parseRequiredString(record.type, `${label}.type`),\n nullable: record.nullable,\n };\n if (\"default\" in record) {\n if (!isString(record.default)) refuse(`${label}.default must be a string`);\n column.default = record.default;\n }\n if (\"autoIncrement\" in record) {\n if (!isBoolean(record.autoIncrement)) {\n refuse(`${label}.autoIncrement must be boolean`);\n }\n column.autoIncrement = record.autoIncrement;\n }\n if (\"decimal\" in record) {\n column.decimal = parseDecimalDescriptor(record.decimal, `${label}.decimal`);\n }\n if (\"geoPointEncoding\" in record) {\n if (\n (record.geoPointEncoding !== \"legacy\" &&\n record.geoPointEncoding !== \"binary64\") ||\n column.type.toUpperCase() !== \"VIBORM_GEO_TEXT\" ||\n column.decimal !== undefined ||\n \"dateTime\" in record\n )\n refuse(`${label}.geoPointEncoding contradicts its physical type`);\n column.geoPointEncoding = record.geoPointEncoding;\n }\n if (\"dateTime\" in record) {\n if (\n !isString(record.dateTime) ||\n (record.dateTime !== \"text\" &&\n record.dateTime !== \"epochMillis\" &&\n record.dateTime !== \"julianDay\")\n ) {\n refuse(`${label}.dateTime must name a DateTime physical form`);\n }\n const physicalType =\n record.dateTime === \"text\"\n ? \"TEXT\"\n : record.dateTime === \"epochMillis\"\n ? \"INTEGER\"\n : \"REAL\";\n if (column.type.toUpperCase() !== physicalType) {\n refuse(`${label}.dateTime contradicts its physical type`);\n }\n if (column.decimal !== undefined) {\n refuse(`${label} cannot be both DateTime and fixed-decimal storage`);\n }\n column.dateTime = record.dateTime;\n }\n return column;\n}\n\nfunction parseDecimalDescriptor(\n value: unknown,\n label: string\n): DecimalDescriptor {\n const record = exactObject(value, DECIMAL_KEYS, DECIMAL_KEYS, label);\n if (\n !(isNumber(record.precision) && Number.isSafeInteger(record.precision)) ||\n record.precision < 1\n ) {\n refuse(`${label}.precision must be a positive safe integer`);\n }\n if (\n !(isNumber(record.scale) && Number.isSafeInteger(record.scale)) ||\n Object.is(record.scale, -0) ||\n record.scale < 0 ||\n record.scale > record.precision\n ) {\n refuse(`${label}.scale must be a safe integer between 0 and precision`);\n }\n return { precision: record.precision, scale: record.scale };\n}\n\nfunction parsePrimaryKey(value: unknown, label: string): PrimaryKeyDef {\n const record = exactObject(value, PRIMARY_KEY_KEYS, [\"columns\"], label);\n const primaryKey: PrimaryKeyDef = {\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n if (\"name\" in record) {\n primaryKey.name = parseRequiredString(record.name, `${label}.name`);\n }\n return primaryKey;\n}\n\nfunction parseIndex(value: unknown, label: string): IndexDef {\n const record = exactObject(\n value,\n INDEX_KEYS,\n [\"columns\", \"name\", \"unique\"],\n label\n );\n if (!isBoolean(record.unique)) refuse(`${label}.unique must be boolean`);\n const index: IndexDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n unique: record.unique,\n };\n if (\"type\" in record) {\n if (\n record.type !== \"btree\" &&\n record.type !== \"hash\" &&\n record.type !== \"gin\" &&\n record.type !== \"gist\" &&\n record.type !== \"fulltext\" &&\n record.type !== \"spatial\"\n ) {\n refuse(`${label}.type is invalid`);\n }\n index.type = record.type;\n }\n if (\"where\" in record) {\n if (!isString(record.where)) refuse(`${label}.where must be a string`);\n index.where = record.where;\n }\n return index;\n}\n\nfunction parseReferentialAction(\n value: unknown,\n label: string\n): ReferentialAction {\n if (\n value === \"cascade\" ||\n value === \"setNull\" ||\n value === \"restrict\" ||\n value === \"noAction\" ||\n value === \"setDefault\"\n ) {\n return value;\n }\n refuse(`${label} is not a referential action`);\n}\n\nfunction parseForeignKey(value: unknown, label: string): ForeignKeyDef {\n const record = exactObject(\n value,\n FOREIGN_KEY_KEYS,\n [\"columns\", \"name\", \"referencedColumns\", \"referencedTable\"],\n label\n );\n const foreignKey: ForeignKeyDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n referencedTable: parseRequiredString(\n record.referencedTable,\n `${label}.referencedTable`\n ),\n referencedColumns: parseIdentifierArray(\n record.referencedColumns,\n `${label}.referencedColumns`\n ),\n };\n if (\"onDelete\" in record) {\n foreignKey.onDelete = parseReferentialAction(\n record.onDelete,\n `${label}.onDelete`\n );\n }\n if (\"onUpdate\" in record) {\n foreignKey.onUpdate = parseReferentialAction(\n record.onUpdate,\n `${label}.onUpdate`\n );\n }\n return foreignKey;\n}\n\nfunction parseUniqueConstraint(\n value: unknown,\n label: string\n): UniqueConstraintDef {\n const record = exactObject(\n value,\n UNIQUE_CONSTRAINT_KEYS,\n UNIQUE_CONSTRAINT_KEYS,\n label\n );\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: parseIdentifierArray(record.columns, `${label}.columns`),\n };\n}\n\nfunction parseRelationStorage(\n value: unknown,\n label: string\n): Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>> {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const entries: Record<string, PolymorphicToOneStorageRegistryEntry> = {};\n for (const [storageRef, rawEntry] of Object.entries(value)) {\n const entryLabel = `${label}.${storageRef}`;\n const record = exactObject(\n rawEntry,\n RELATION_STORAGE_KEYS,\n RELATION_STORAGE_KEYS,\n entryLabel\n );\n if (record.kind !== \"polymorphicToOne\") {\n refuse(`${entryLabel}.kind must be polymorphicToOne`);\n }\n Object.defineProperty(entries, storageRef, {\n configurable: true,\n enumerable: true,\n value: {\n kind: \"polymorphicToOne\",\n typeColumn: parseRequiredString(\n record.typeColumn,\n `${entryLabel}.typeColumn`\n ),\n idColumn: parseRequiredString(\n record.idColumn,\n `${entryLabel}.idColumn`\n ),\n index: parseRequiredString(record.index, `${entryLabel}.index`),\n },\n writable: true,\n });\n }\n return entries;\n}\n\nfunction parseTable(value: unknown, label: string): TableDef {\n const record = exactObject(value, TABLE_KEYS, TABLE_REQUIRED_KEYS, label);\n if (!Array.isArray(record.columns))\n refuse(`${label}.columns must be an array`);\n if (!Array.isArray(record.indexes))\n refuse(`${label}.indexes must be an array`);\n if (!Array.isArray(record.foreignKeys)) {\n refuse(`${label}.foreignKeys must be an array`);\n }\n if (!Array.isArray(record.uniqueConstraints)) {\n refuse(`${label}.uniqueConstraints must be an array`);\n }\n const table: TableDef = {\n name: parseRequiredString(record.name, `${label}.name`),\n columns: record.columns.map((column, index) =>\n parseColumn(column, `${label}.columns[${index}]`)\n ),\n indexes: record.indexes.map((index, position) =>\n parseIndex(index, `${label}.indexes[${position}]`)\n ),\n foreignKeys: record.foreignKeys.map((foreignKey, index) =>\n parseForeignKey(foreignKey, `${label}.foreignKeys[${index}]`)\n ),\n uniqueConstraints: record.uniqueConstraints.map((constraint, index) =>\n parseUniqueConstraint(constraint, `${label}.uniqueConstraints[${index}]`)\n ),\n };\n if (\"primaryKey\" in record) {\n table.primaryKey = parsePrimaryKey(\n record.primaryKey,\n `${label}.primaryKey`\n );\n }\n if (\"relationStorage\" in record) {\n table.relationStorage = parseRelationStorage(\n record.relationStorage,\n `${label}.relationStorage`\n );\n }\n return table;\n}\n\nfunction parseEnum(value: unknown, label: string): EnumDef {\n const record = exactObject(value, ENUM_KEYS, ENUM_KEYS, label);\n return {\n name: parseRequiredString(record.name, `${label}.name`),\n values: parseStringArray(record.values, `${label}.values`),\n };\n}\n\nfunction parseToOneMember(\n value: unknown,\n label: string\n): PolymorphicToOneSnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n POLYMORPHIC_TO_ONE_MEMBER_KEYS,\n label\n );\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n };\n}\n\nfunction parseToManyMember(\n value: unknown,\n label: string\n): PolymorphicToManySnapshotMember {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n POLYMORPHIC_TO_MANY_MEMBER_KEYS,\n label\n );\n if (\n record.inverseCardinality !== \"one\" &&\n record.inverseCardinality !== \"many\"\n ) {\n refuse(`${label}.inverseCardinality must be one or many`);\n }\n return {\n publicType: parseRequiredString(record.publicType, `${label}.publicType`),\n storedType: parseRequiredString(record.storedType, `${label}.storedType`),\n targetTable: parseRequiredString(\n record.targetTable,\n `${label}.targetTable`\n ),\n memberJunctionTable: parseRequiredString(\n record.memberJunctionTable,\n `${label}.memberJunctionTable`\n ),\n inverseCardinality: record.inverseCardinality,\n };\n}\n\nfunction parsePolymorphicStorage(\n value: unknown,\n label: string\n): PolymorphicSnapshotStorage {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n if (value.kind === \"toOne\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_ONE_KEYS,\n POLYMORPHIC_TO_ONE_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toOne\",\n storageRef: parseRequiredString(record.storageRef, `${label}.storageRef`),\n members: record.members.map((member, index) =>\n parseToOneMember(member, `${label}.members[${index}]`)\n ),\n };\n }\n if (value.kind === \"toMany\") {\n const record = exactObject(\n value,\n POLYMORPHIC_TO_MANY_KEYS,\n POLYMORPHIC_TO_MANY_KEYS,\n label\n );\n if (!Array.isArray(record.members)) {\n refuse(`${label}.members must be an array`);\n }\n return {\n ownerTable: parseRequiredString(record.ownerTable, `${label}.ownerTable`),\n relation: parseRequiredString(record.relation, `${label}.relation`),\n kind: \"toMany\",\n members: record.members.map((member, index) =>\n parseToManyMember(member, `${label}.members[${index}]`)\n ),\n };\n }\n refuse(`${label}.kind must be toOne or toMany`);\n}\n\nexport function parseSnapshotDocument(\n bytes: Uint8Array,\n expectedHash: Sha256\n): SchemaSnapshot {\n const parsed = parseJsonBytes(bytes, `snapshots/${expectedHash}.json`);\n const record = exactObject(parsed, SNAPSHOT_KEYS, [\"tables\"], \"snapshot\");\n if (!Array.isArray(record.tables)) refuse(\"snapshot.tables must be an array\");\n const snapshot: SchemaSnapshot = {\n tables: record.tables.map((table, index) =>\n parseTable(table, `snapshot.tables[${index}]`)\n ),\n };\n if (\"enums\" in record) {\n if (!Array.isArray(record.enums)) refuse(\"snapshot.enums must be an array\");\n snapshot.enums = record.enums.map((enumDef, index) =>\n parseEnum(enumDef, `snapshot.enums[${index}]`)\n );\n }\n if (\"polymorphicStorage\" in record) {\n if (!Array.isArray(record.polymorphicStorage)) {\n refuse(\"snapshot.polymorphicStorage must be an array\");\n }\n snapshot.polymorphicStorage = record.polymorphicStorage.map(\n (storage, index) =>\n parsePolymorphicStorage(\n storage,\n `snapshot.polymorphicStorage[${index}]`\n )\n );\n }\n assertCanonicalBytes(bytes, snapshot, `snapshots/${expectedHash}.json`);\n const actual = domainHash(HASH_DOMAIN.snapshot, bytes);\n if (actual !== expectedHash) {\n throw new MigrationError(\n \"snapshot filename does not match its canonical bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\nexport function encodeSnapshot(snapshot: SchemaSnapshot): {\n bytes: Uint8Array;\n snapshotHash: Sha256;\n} {\n const bytes = canonicalizeJson(omitUndefinedKeys(snapshot));\n return { bytes, snapshotHash: domainHash(HASH_DOMAIN.snapshot, bytes) };\n}\n\nfunction omitUndefinedKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => omitUndefinedKeys(item));\n }\n if (!isRecord(value)) return value;\n const admitted: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n const item = value[key];\n if (item === undefined) continue;\n admitted[key] = omitUndefinedKeys(item);\n }\n return admitted;\n}\n","import { readArrayLiteralText } from \"../adapters/databases/postgres/array-literal\";\nimport { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\nimport { decodeProviderTimestamp } from \"../validation/primitives/datetime-physical-codec\";\n/**\n * Live schema fingerprint and push target identity.\n *\n * `bindingId` is minted from the original client driver, never a pinned\n * producer. This module hashes the snapshot it is given; callers strip\n * control tables before fingerprinting.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport type { IndexPredicateCanonicalizer } from \"./differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport type { MigrationClient } from \"./push/planner\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodeSnapshot } from \"./v1-parse-snapshot\";\nimport type { PushTargetIdentity } from \"./v1-types\";\n\nconst BINDINGS = new WeakMap<object, string>();\n\nexport function bindingId(client: MigrationClient): string {\n const existing = BINDINGS.get(client.$driver);\n if (existing) return existing;\n const id = randomUUID();\n BINDINGS.set(client.$driver, id);\n return id;\n}\n\nexport async function pushTargetIdentity(\n client: MigrationClient,\n producer: AnyDriver,\n driver: BoundMigrationDriver\n): Promise<PushTargetIdentity> {\n const id = bindingId(client);\n if (driver.target.dialect === \"postgresql\") {\n const result = await producer._executeRaw<{ database: unknown }>(\n \"SELECT current_database() AS database\"\n );\n const database = result.rows[0]?.database;\n if (typeof database !== \"string\" || database.length === 0) {\n throw new MigrationError(\n \"PostgreSQL did not return its current database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"postgresql\",\n database,\n namespace: driver.namespace ?? driver.target.namespace,\n bindingId: id,\n };\n }\n if (driver.target.dialect === \"mysql\") {\n if (!driver.namespace) {\n throw new MigrationError(\n \"MySQL push has no resolved database identity\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return {\n dialect: \"mysql\",\n database: driver.namespace,\n bindingId: id,\n };\n }\n return { dialect: \"sqlite\", location: null, bindingId: id };\n}\n\nexport function hashSnapshot(snapshot: SchemaSnapshot): Sha256 {\n return encodeSnapshot(snapshot).snapshotHash;\n}\n\nexport function bindIndexPredicateCanonicalizer(\n producer: AnyDriver,\n driver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = driver.canonicalizeIndexPredicates;\n if (!canonicalize) return;\n return async (tableName, predicates) => {\n try {\n return await canonicalize.call(\n driver,\n tableName,\n predicates,\n (sql, params) => producer._executeRaw(sql, params)\n );\n } catch {\n return predicates.map(() => undefined);\n }\n };\n}\n\nexport async function canonicalizeSnapshotPredicates(\n snapshot: SchemaSnapshot,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<SchemaSnapshot> {\n if (!canonicalize) return snapshot;\n const tables: TableDef[] = [];\n for (const table of snapshot.tables) {\n const pending = table.indexes.filter((index) => index.where);\n if (pending.length === 0) {\n tables.push(table);\n continue;\n }\n const predicates = pending.map((index) => index.where!);\n const spellings = await canonicalize(table.name, predicates);\n let next = 0;\n tables.push({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.where) return index;\n const spelling = spellings[next++];\n return spelling === undefined ? index : { ...index, where: spelling };\n }),\n });\n }\n return { ...snapshot, tables };\n}\n\nexport async function fingerprintLive(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver,\n producer: AnyDriver\n): Promise<Sha256> {\n return fingerprintSnapshot(\n await canonicalizeSnapshotPredicates(\n snapshot,\n bindIndexPredicateCanonicalizer(producer, driver)\n ),\n driver\n );\n}\n\nexport function fingerprintSnapshot(\n snapshot: SchemaSnapshot,\n driver: MigrationDriver\n): Sha256 {\n const tables = canonicalUniqueEntities(snapshot)\n .tables.map((table) => ({\n name: table.name,\n columns: table.columns\n .map((column) => ({\n name: column.name,\n type: normalizeType(column.type),\n nullable: column.nullable,\n default: normalizeDefault(column.default, column.type) ?? null,\n autoIncrement: column.autoIncrement ?? false,\n ...(sqliteGeoPointEncoding(column)\n ? { geoPointEncoding: sqliteGeoPointEncoding(column) }\n : {}),\n }))\n .sort(byName),\n primaryKey: table.primaryKey\n ? {\n columns: table.primaryKey.columns,\n ...(driver.dialect === \"postgresql\"\n ? { name: table.primaryKey.name || `${table.name}_pkey` }\n : {}),\n }\n : null,\n indexes: table.indexes\n .map((index) => ({\n name: index.name,\n columns: index.columns,\n unique: index.unique ?? false,\n type: index.type ?? \"btree\",\n where: index.where?.trim() || null,\n }))\n .sort(byName),\n foreignKeys: table.foreignKeys\n .map((foreignKey) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? foreignKey.name\n : null,\n columns: foreignKey.columns,\n referencedTable: foreignKey.referencedTable,\n referencedColumns: foreignKey.referencedColumns,\n onDelete: foreignKey.onDelete ?? \"noAction\",\n onUpdate: foreignKey.onUpdate ?? \"noAction\",\n }))\n .sort(byCanonicalValue),\n uniqueConstraints: table.uniqueConstraints\n .map((constraint) => ({\n name: driver.capabilities.introspectionReadsConstraintNames\n ? constraint.name\n : null,\n columns: constraint.columns,\n }))\n .sort(byCanonicalValue),\n }))\n .sort(byName);\n const enums = [...(snapshot.enums ?? [])]\n .map((item) => ({ name: item.name, values: item.values }))\n .sort(byName);\n return domainHash(HASH_DOMAIN.snapshot, canonicalizeJson({ tables, enums }));\n}\n\n/** A total btree unique index and a unique constraint enforce the same key. */\nexport function canonicalUniqueEntities(\n snapshot: SchemaSnapshot\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) => ({\n ...table,\n uniqueConstraints: [\n ...table.uniqueConstraints,\n ...table.indexes\n .filter(\n (index) =>\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n .map((index) => ({ name: index.name, columns: index.columns })),\n ],\n indexes: table.indexes.filter(\n (index) =>\n !(\n index.unique &&\n !index.where &&\n (!index.type || index.type === \"btree\")\n )\n ),\n })),\n };\n}\n\nexport function normalizeType(type: string): string {\n const tokens =\n type.trim().match(/'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|[^'\"]+/g) ?? [];\n return tokens\n .map((token) => {\n if (token.startsWith(\"'\") || token.startsWith('\"')) return token;\n return token\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \",\")\n .replace(/\\s+\\[\\]/g, \"[]\")\n .replace(/\\bcharacter varying\\b/g, \"varchar\")\n .replace(/\\bcharacter\\b/g, \"char\")\n .replace(/\\bbit varying\\b/g, \"varbit\")\n .replace(/\\btimestamptz(\\(\\d+\\))?/g, \"timestamp$1 with time zone\")\n .replace(/\\btimetz(\\(\\d+\\))?/g, \"time$1 with time zone\")\n .replace(/\\b(timestamp|time)(\\(\\d+\\))? without time zone/g, \"$1$2\")\n .replace(/\\bint4\\b/g, \"integer\")\n .replace(/\\bint8\\b/g, \"bigint\")\n .replace(/\\bint2\\b/g, \"smallint\")\n .replace(/\\bfloat4\\b/g, \"real\")\n .replace(/\\bfloat8\\b/g, \"double precision\")\n .replace(/\\bbool\\b/g, \"boolean\");\n })\n .join(\"\");\n}\n\nconst UTC_NOW_DEFAULT =\n /^(?:now\\(\\) at time zone 'utc'|timezone\\(\\s*'utc'\\s*,\\s*now\\(\\)\\s*\\))$/;\nconst MILLISECOND_NOW_DEFAULT =\n /^date_trunc\\(\\s*'milliseconds'\\s*,([\\s\\S]+)\\)$/;\nconst UTC_CURRENT_TIME_DEFAULT =\n /^timezone\\(\\s*'utc'\\s*,\\s*current_time(?:\\(3\\))?\\s*\\)$/;\nconst NUMERIC_PHYSICAL_TYPE =\n /^(integer|bigint|smallint|real|double precision|float|int|tinyint)/;\nconst INTEGER_LITERAL = /^[-+]?\\d+$/;\nconst TEMPORAL_PHYSICAL_TYPE = /^(timestamp|time|date)/;\nconst ISO_UTC_SUFFIX = /Z$/;\nconst TEMPORAL_UTC_SUFFIX = /(?:Z|[+]00(?::00)?)$/;\nconst MINUTE_CLOCK_SUFFIX = /(^| )(\\d{2}:\\d{2})(?=$|[+-])/;\nconst TRAILING_FRACTION_ZEROES = /(\\.\\d*?)0+(?=$|[+-])/;\nconst EMPTY_FRACTION = /\\.(?=$|[+-])/;\nconst BARE_FUNCTION_DEFAULT = /^[a-z_][a-z0-9_]*\\(\\)$/;\nconst NUMBER_LITERAL = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\nfunction stripDefaultParentheses(value: string): string {\n let text = value.trim();\n while (text.startsWith(\"(\") && text.endsWith(\")\")) {\n const structural = text.replace(\n /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"/g,\n (literal) => \" \".repeat(literal.length)\n );\n let depth = 0;\n let whole = true;\n for (let index = 0; index < structural.length; index++) {\n if (structural[index] === \"(\") depth++;\n else if (structural[index] === \")\") depth--;\n if (depth === 0 && index < structural.length - 1) {\n whole = false;\n break;\n }\n }\n if (!whole || depth !== 0) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n}\n\nexport function normalizeDefault(\n value: string | undefined,\n type?: string\n): string | undefined {\n if (value === undefined) return;\n const spelling = stripDefaultParentheses(value);\n const normalized = spelling.toLowerCase();\n if (normalized === \"null\") return;\n const utcNow = normalized\n .replaceAll(\"::text\", \"\")\n .replaceAll(\"current_timestamp\", \"now()\");\n if (UTC_NOW_DEFAULT.test(utcNow)) return \"now() at time zone 'utc'\";\n const truncated = MILLISECOND_NOW_DEFAULT.exec(utcNow);\n if (truncated?.[1]) {\n const clock = normalizeDefault(truncated[1], type);\n if (clock === \"now()\" || clock === \"now() at time zone 'utc'\")\n return `date_trunc('milliseconds',${clock})`;\n }\n if (UTC_CURRENT_TIME_DEFAULT.test(utcNow))\n return utcNow.includes(\"current_time(3)\")\n ? \"timezone('utc',current_time(3))\"\n : \"timezone('utc',current_time)\";\n if (normalized === \"current_timestamp\" || normalized === \"now()\")\n return \"now()\";\n const boolean = type === undefined || normalizeType(type) === \"boolean\";\n if (\n boolean &&\n (normalized === \"true\" || normalized === \"'t'\" || normalized === \"1\")\n )\n return \"true\";\n if (\n boolean &&\n (normalized === \"false\" || normalized === \"'f'\" || normalized === \"0\")\n )\n return \"false\";\n if (BARE_FUNCTION_DEFAULT.test(normalized)) return normalized;\n const unquoted =\n normalized.startsWith(\"'\") && normalized.endsWith(\"'\")\n ? normalized.slice(1, -1)\n : normalized;\n const physical = type === undefined ? \"\" : normalizeType(type);\n if (spelling.startsWith(\"'\") && spelling.endsWith(\"'\")) {\n const literal = spelling.slice(1, -1).replaceAll(\"''\", \"'\");\n if (physical.endsWith(\"[]\")) {\n const values = readArrayLiteralText(literal);\n if (values)\n return canonicalizeJsonText(\n values.map((value) =>\n value === null\n ? null\n : normalizeDefault(\n `'${(physical.slice(0, -2) === \"boolean\" && (value === \"t\" || value === \"f\") ? (value === \"t\" ? \"true\" : \"false\") : value).replaceAll(\"'\", \"''\")}'`,\n physical.slice(0, -2)\n )\n )\n );\n }\n if (physical === \"json\" || physical === \"jsonb\") {\n try {\n return canonicalizeJsonText(JSON.parse(literal));\n } catch {\n /* A SQL expression is not a JSON document literal. */\n }\n }\n }\n if (NUMERIC_PHYSICAL_TYPE.test(physical) && NUMBER_LITERAL.test(unquoted)) {\n return INTEGER_LITERAL.test(unquoted)\n ? BigInt(unquoted).toString()\n : String(Number(unquoted));\n }\n if (\n TEMPORAL_PHYSICAL_TYPE.test(physical) &&\n spelling.startsWith(\"'\") &&\n spelling.endsWith(\"'\")\n ) {\n let temporal = spelling\n .slice(1, -1)\n .replace(\"T\", \" \")\n .replace(ISO_UTC_SUFFIX, \"+00:00\");\n const era = temporal.endsWith(\" BC\") ? \" BC\" : \"\";\n if (era) temporal = temporal.slice(0, -3);\n if (\n physical.includes(\"with time zone\") &&\n physical.startsWith(\"timestamp\")\n ) {\n const instant = decodeProviderTimestamp(`${temporal}${era}`);\n if (instant) return instant.toISOString();\n }\n temporal = temporal\n .replace(TEMPORAL_UTC_SUFFIX, \"\")\n .replace(MINUTE_CLOCK_SUFFIX, \"$1$2:00\")\n .replace(TRAILING_FRACTION_ZEROES, \"$1\")\n .replace(EMPTY_FRACTION, \"\");\n return `${temporal}${era}`;\n }\n return spelling;\n}\n\nexport function canonicalValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalValue(item));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (item !== undefined) result[key] = canonicalValue(item);\n }\n return result;\n }\n return value;\n}\n\nexport function freezeDeep<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) return value;\n if (ArrayBuffer.isView(value)) return value;\n for (const member of Object.values(value)) freezeDeep(member);\n return Object.freeze(value);\n}\n\nfunction byName(\n left: { readonly name: string },\n right: { readonly name: string }\n): number {\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;\n}\n\nfunction byCanonicalValue(left: unknown, right: unknown): number {\n const a = canonicalizeJsonText(left);\n const b = canonicalizeJsonText(right);\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import { renderQualifiedIdentifier } from \"../sql/identifiers\";\n/**\n * Driver catalog probes. These are the only checks the ORM proves read-only.\n * Manual trusted-read checks are a different arm.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"./drivers\";\nimport type { DiffOperation } from \"./types\";\nimport type { MigrationParameterV1 } from \"./v1-types\";\n\nexport interface CatalogProbe {\n readonly id: string;\n readonly sql: string;\n readonly parameters: readonly MigrationParameterV1[];\n readonly equals: boolean;\n}\n\ntype CatalogProbeLifetime = \"live-command\" | \"stored-artifact\";\n\nfunction namespace(driver: MigrationDriver): string | undefined {\n return (\n driver.namespace ??\n (driver.target?.dialect === \"postgresql\"\n ? driver.target.namespace\n : undefined)\n );\n}\n\nfunction boundCatalogNamespace(driver: MigrationDriver): string {\n const value = namespace(driver);\n if (value) return value;\n throw new MigrationError(\n \"A catalog probe needs the bound migration namespace and this driver has none\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.dialect } }\n );\n}\n\nfunction stringParam(value: string): MigrationParameterV1 {\n return { kind: \"string\", value };\n}\n\nfunction mysqlNamespaceParam(\n driver: MigrationDriver,\n lifetime: CatalogProbeLifetime\n): MigrationParameterV1 {\n return lifetime === \"stored-artifact\"\n ? { kind: \"target-namespace\" }\n : stringParam(boundCatalogNamespace(driver));\n}\n\nexport function tableExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'p'))`,\n parameters: [stringParam(schema), stringParam(tableName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n ],\n equals: exists,\n };\n }\n return {\n id: `table:${exists ? \"exists\" : \"absent\"}:${tableName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)`,\n parameters: [stringParam(tableName)],\n equals: exists,\n };\n}\n\nexport function columnExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n columnName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND a.attnum > 0 AND NOT a.attisdropped)\",\n parameters: [\n stringParam(schema),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(columnName),\n ],\n equals: exists,\n };\n }\n return {\n id: `column:${exists ? \"exists\" : \"absent\"}:${tableName}.${columnName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM pragma_table_info(?) WHERE name = ?)\",\n parameters: [stringParam(tableName), stringParam(columnName)],\n equals: exists,\n };\n}\n\nexport function indexExistsProbe(\n driver: MigrationDriver,\n tableName: string,\n indexName: string,\n exists: boolean,\n lifetime: CatalogProbeLifetime = \"live-command\"\n): CatalogProbe {\n const dialect = driver.dialect;\n if (dialect === \"postgresql\") {\n const schema = boundCatalogNamespace(driver);\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'i')`,\n parameters: [stringParam(schema), stringParam(indexName)],\n equals: exists,\n };\n }\n if (dialect === \"mysql\") {\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: \"SELECT EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND index_name = ?)\",\n parameters: [\n mysqlNamespaceParam(driver, lifetime),\n stringParam(tableName),\n stringParam(indexName),\n ],\n equals: exists,\n };\n }\n return {\n id: `index:${exists ? \"exists\" : \"absent\"}:${indexName}`,\n sql: `SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?)`,\n parameters: [stringParam(indexName)],\n equals: exists,\n };\n}\n\nexport function probeForGeneratedStatement(\n driver: MigrationDriver,\n operation: DiffOperation,\n statement: string\n): { pre: CatalogProbe; post: CatalogProbe } | null {\n if (\n (driver.dialect === \"postgresql\" || driver.dialect === \"mysql\") &&\n namespace(driver) === undefined\n ) {\n return null;\n }\n const text = statement.trim().toUpperCase();\n if (\n text.startsWith(\"PRAGMA\") ||\n text.startsWith(\"INSERT \") ||\n text.startsWith(\"--\")\n ) {\n return null;\n }\n switch (operation.type) {\n case \"createTable\":\n if (text.startsWith(\"CREATE TABLE\")) {\n return {\n pre: tableExistsProbe(\n driver,\n operation.table.name,\n false,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.table.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n if (text.startsWith(\"CREATE \") && text.includes(\"INDEX\")) {\n const index = operation.table.indexes.find((item) =>\n statement.includes(item.name)\n );\n if (!index) return null;\n return {\n pre: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.table.name,\n index.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n return null;\n case \"dropTable\":\n return {\n pre: tableExistsProbe(\n driver,\n operation.tableName,\n true,\n \"stored-artifact\"\n ),\n post: tableExistsProbe(\n driver,\n operation.tableName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"addColumn\": {\n const pre = columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n false,\n \"stored-artifact\"\n );\n const required =\n !operation.column.nullable &&\n operation.column.default === undefined &&\n !operation.column.autoIncrement;\n const table = renderQualifiedIdentifier(\n (name) => driver.escapeIdentifier(name),\n driver.dialect === \"postgresql\" ? namespace(driver) : undefined,\n operation.tableName\n );\n return {\n pre: required\n ? {\n ...pre,\n id: `column:absent-and-empty-table:${operation.tableName}.${operation.column.name}`,\n sql: `SELECT (${pre.sql.slice(\"SELECT \".length)}) OR EXISTS (SELECT 1 FROM ${table} LIMIT 1)`,\n }\n : pre,\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.column.name,\n true,\n \"stored-artifact\"\n ),\n };\n }\n case \"dropColumn\":\n return {\n pre: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n true,\n \"stored-artifact\"\n ),\n post: columnExistsProbe(\n driver,\n operation.tableName,\n operation.columnName,\n false,\n \"stored-artifact\"\n ),\n };\n case \"createIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n false,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.index.name,\n true,\n \"stored-artifact\"\n ),\n };\n case \"dropIndex\":\n return {\n pre: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n true,\n \"stored-artifact\"\n ),\n post: indexExistsProbe(\n driver,\n operation.tableName,\n operation.indexName,\n false,\n \"stored-artifact\"\n ),\n };\n default:\n return null;\n }\n}\n\nexport function boundNamespace(\n driver: BoundMigrationDriver\n): string | undefined {\n return namespace(driver);\n}\n","/** Runtime-neutral canonical Base64 for persisted migration parameters. */\n\nconst ALPHABET =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst CANONICAL_SHAPE =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n\nexport function encodeBase64(bytes: Uint8Array): string {\n let encoded = \"\";\n for (let index = 0; index < bytes.length; index += 3) {\n const first = bytes[index]!;\n const hasSecond = index + 1 < bytes.length;\n const hasThird = index + 2 < bytes.length;\n const second = hasSecond ? bytes[index + 1]! : 0;\n const third = hasThird ? bytes[index + 2]! : 0;\n encoded += ALPHABET[Math.floor(first / 4)];\n encoded += ALPHABET[(first % 4) * 16 + Math.floor(second / 16)];\n encoded += hasSecond\n ? ALPHABET[(second % 16) * 4 + Math.floor(third / 64)]\n : \"=\";\n encoded += hasThird ? ALPHABET[third % 64] : \"=\";\n }\n return encoded;\n}\n\nexport function decodeCanonicalBase64(text: string): Uint8Array | undefined {\n if (!CANONICAL_SHAPE.test(text)) return;\n const padding = text.endsWith(\"==\") ? 2 : text.endsWith(\"=\") ? 1 : 0;\n const decoded = new Uint8Array((text.length / 4) * 3 - padding);\n let offset = 0;\n for (let index = 0; index < text.length; index += 4) {\n const first = ALPHABET.indexOf(text.charAt(index));\n const second = ALPHABET.indexOf(text.charAt(index + 1));\n const thirdCharacter = text.charAt(index + 2);\n const fourthCharacter = text.charAt(index + 3);\n const third = thirdCharacter === \"=\" ? 0 : ALPHABET.indexOf(thirdCharacter);\n const fourth =\n fourthCharacter === \"=\" ? 0 : ALPHABET.indexOf(fourthCharacter);\n decoded[offset] = first * 4 + Math.floor(second / 16);\n offset += 1;\n if (thirdCharacter !== \"=\") {\n decoded[offset] = (second % 16) * 16 + Math.floor(third / 4);\n offset += 1;\n }\n if (fourthCharacter !== \"=\") {\n decoded[offset] = (third % 4) * 64 + fourth;\n offset += 1;\n }\n }\n return encodeBase64(decoded) === text ? decoded : undefined;\n}\n","/**\n * Dispatch identity and hostile parameter admission.\n * Reset-plan and state parsers share this owner; they do not import each other.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeDecimal } from \"../validation/primitives/decimal-codec\";\nimport {\n isBoolean,\n isNumber,\n isRecord,\n isString,\n} from \"../validation/value-guards\";\nimport { decodeCanonicalBase64 } from \"./base64\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { exactObject, parseFiniteInteger, refuse } from \"./v1-parse-shared\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\nconst DISPATCH_KEYS = [\n \"dispatchId\",\n \"length\",\n \"offset\",\n \"parameters\",\n \"sqlHash\",\n] as const;\n\nconst CANONICAL_BIGINT = /^(?:0|-?[1-9]\\d*)$/;\n\nexport function encodeDispatchIdentity(\n sqlHash: Sha256,\n offset: number,\n length: number,\n parameters: readonly MigrationParameterV1[]\n): Sha256 {\n return domainHash(\n HASH_DOMAIN.dispatch,\n canonicalizeJson({ sqlHash, offset, length, parameters })\n );\n}\n\nexport function parseDispatch(\n value: unknown,\n label: string\n): MigrationDispatchV1 {\n const record = exactObject(value, DISPATCH_KEYS, DISPATCH_KEYS, label);\n const offset = parseFiniteInteger(record.offset, `${label}.offset`);\n const length = parseFiniteInteger(record.length, `${label}.length`);\n if (offset < 0 || length < 0) refuse(`${label} range must be non-negative`);\n if (!Array.isArray(record.parameters))\n refuse(`${label}.parameters must be an array`);\n const parameters = record.parameters.map((parameter, index) =>\n parseParameter(parameter, `${label}.parameters[${index}]`)\n );\n const sqlHash = parseSha256(record.sqlHash, `${label}.sqlHash`);\n const dispatchId = parseSha256(record.dispatchId, `${label}.dispatchId`);\n const expected = encodeDispatchIdentity(sqlHash, offset, length, parameters);\n if (dispatchId !== expected) {\n throw new MigrationError(\n `${label}.dispatchId does not match its SQL range and parameters`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { dispatchId, sqlHash, offset, length, parameters };\n}\n\nfunction parseParameter(value: unknown, label: string): MigrationParameterV1 {\n if (!(isRecord(value) && isString(value.kind))) {\n refuse(`${label} must be a tagged parameter`);\n }\n switch (value.kind) {\n case \"null\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"null\" };\n case \"target-namespace\":\n exactObject(value, [\"kind\"], [\"kind\"], label);\n return { kind: \"target-namespace\" };\n case \"boolean\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isBoolean(record.value)) refuse(`${label}.value must be boolean`);\n return { kind: \"boolean\", value: record.value };\n }\n case \"string\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value)) refuse(`${label}.value must be a string`);\n return { kind: \"string\", value: record.value };\n }\n case \"number\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!(isNumber(record.value) && Number.isFinite(record.value))) {\n refuse(`${label}.value must be a finite number`);\n }\n return { kind: \"number\", value: record.value };\n }\n case \"bigint\":\n case \"bytes\":\n case \"date-time\":\n case \"decimal\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n if (!isString(record.value))\n refuse(`${label}.value must be canonical text`);\n assertCanonicalParameterText(value.kind, record.value, label);\n return { kind: value.kind, value: record.value };\n }\n case \"json\": {\n const record = exactObject(\n value,\n [\"kind\", \"value\"],\n [\"kind\", \"value\"],\n label\n );\n return { kind: \"json\", value: record.value };\n }\n default:\n refuse(`${label}.kind is not a V1 parameter tag`);\n }\n}\n\nfunction assertCanonicalParameterText(\n kind: \"bigint\" | \"bytes\" | \"date-time\" | \"decimal\",\n value: string,\n label: string\n): void {\n if (kind === \"bigint\" && !CANONICAL_BIGINT.test(value)) {\n refuse(`${label}.value must be canonical bigint text`);\n }\n if (kind === \"bytes\" && decodeCanonicalBase64(value) === undefined) {\n refuse(`${label}.value must be canonical base64 text`);\n }\n if (kind === \"date-time\") {\n try {\n if (new Date(value).toISOString() !== value) {\n refuse(`${label}.value must be canonical date-time text`);\n }\n } catch {\n refuse(`${label}.value must be canonical date-time text`);\n }\n }\n if (kind === \"decimal\" && canonicalizeDecimal(value) !== value) {\n refuse(`${label}.value must be canonical decimal text`);\n }\n}\n","/**\n * Hostile parsers and hash owner for Migration V1 marker and ledger rows.\n *\n * Path identity lives next to the marker it authenticates. Reset-plan\n * admission lives next to the ledger event that carries it.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport {\n exactObject,\n parseFiniteInteger,\n parseFormat,\n parseRequiredString,\n refuse,\n} from \"./v1-parse-shared\";\nimport type {\n LedgerEffectStateV1,\n LedgerEventKindV1,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ResetPlanV1,\n} from \"./v1-types\";\n\nexport function encodePathHash(path: readonly MarkerPathEdgeV1[]): Sha256 {\n return domainHash(HASH_DOMAIN.path, canonicalizeJson(path));\n}\n\nexport function eventIdFor(event: Omit<LedgerEventV1, \"eventId\">): Sha256 {\n return domainHash(HASH_DOMAIN.event, canonicalizeJson(event));\n}\n\nconst MARKER_KEYS = [\n \"estateHash\",\n \"format\",\n \"path\",\n \"pathHash\",\n \"revision\",\n \"snapshotHash\",\n \"stateId\",\n \"updatedAt\",\n] as const;\nconst PATH_EDGE_KEYS = [\n \"baselineBoundary\",\n \"stateId\",\n \"transitionHash\",\n] as const;\n\nexport function parseMarkerRow(value: unknown): MigrationMarkerV1 {\n const record = exactObject(\n value,\n MARKER_KEYS,\n MARKER_KEYS,\n \"migration marker\"\n );\n if (!Array.isArray(record.path)) refuse(\"marker.path must be an array\");\n const path = record.path.map((edge, index) => {\n const item = exactObject(\n edge,\n PATH_EDGE_KEYS,\n PATH_EDGE_KEYS,\n `marker.path[${index}]`\n );\n if (!isBoolean(item.baselineBoundary)) {\n refuse(`marker.path[${index}].baselineBoundary must be boolean`);\n }\n return {\n stateId: parseSha256(item.stateId, `marker.path[${index}].stateId`),\n transitionHash: parseSha256(\n item.transitionHash,\n `marker.path[${index}].transitionHash`\n ),\n baselineBoundary: item.baselineBoundary,\n };\n });\n const pathHash = parseSha256(record.pathHash, \"marker.pathHash\");\n if (pathHash !== encodePathHash(path)) {\n throw new MigrationError(\n \"marker.pathHash does not match the stored path\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (!isString(record.updatedAt) || record.updatedAt.length === 0) {\n refuse(\"marker.updatedAt must be an ISO timestamp\");\n }\n return {\n format: parseFormat(record.format, \"marker\"),\n estateHash: parseSha256(record.estateHash, \"marker.estateHash\"),\n stateId:\n record.stateId === null\n ? null\n : parseSha256(record.stateId, \"marker.stateId\"),\n snapshotHash: parseSha256(record.snapshotHash, \"marker.snapshotHash\"),\n path,\n pathHash,\n revision: parseFiniteInteger(record.revision, \"marker.revision\"),\n updatedAt: record.updatedAt,\n };\n}\n\nconst LEDGER_KINDS: readonly LedgerEventKindV1[] = [\n \"started\",\n \"step-confirmed\",\n \"applied\",\n \"failed\",\n \"rolled-back\",\n \"baselined\",\n \"resolved\",\n \"reset-started\",\n \"reset-step-confirmed\",\n \"reset-applied\",\n];\nconst EFFECT_STATES: readonly LedgerEffectStateV1[] = [\n \"none\",\n \"committed\",\n \"partial\",\n \"may-have-committed\",\n];\nconst LEDGER_KEYS = [\n \"attemptId\",\n \"direction\",\n \"dispatchId\",\n \"effectState\",\n \"estateHash\",\n \"eventId\",\n \"failure\",\n \"finishedAt\",\n \"format\",\n \"fromState\",\n \"kind\",\n \"operationId\",\n \"snapshotHash\",\n \"sqlHash\",\n \"startedAt\",\n \"toState\",\n \"toolVersion\",\n \"transitionHash\",\n] as const;\nconst RESET_LEDGER_KEYS = [...LEDGER_KEYS, \"resetPlan\"] as const;\nconst RESET_PLAN_KEYS = [\n \"clearDispatches\",\n \"estateHash\",\n \"referencedStates\",\n \"replayPath\",\n \"resetPlanHash\",\n \"sourceFingerprint\",\n \"sourceRevision\",\n \"targetIdentity\",\n] as const;\n\nexport function parseLedgerEvent(value: unknown): LedgerEventV1 {\n if (!isRecord(value)) refuse(\"ledger event must be an object\");\n const kind = parseLedgerKind(value.kind);\n const record = exactObject(\n value,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n kind === \"reset-started\" ? RESET_LEDGER_KEYS : LEDGER_KEYS,\n \"ledger event\"\n );\n const event = {\n format: parseFormat(record.format, \"ledger event\"),\n eventId: parseSha256(record.eventId, \"ledger.eventId\"),\n attemptId: parseSha256(record.attemptId, \"ledger.attemptId\"),\n kind,\n estateHash: parseSha256(record.estateHash, \"ledger.estateHash\"),\n snapshotHash: parseSha256(record.snapshotHash, \"ledger.snapshotHash\"),\n sqlHash:\n record.sqlHash === null\n ? null\n : parseSha256(record.sqlHash, \"ledger.sqlHash\"),\n fromState:\n record.fromState === null\n ? null\n : parseSha256(record.fromState, \"ledger.fromState\"),\n toState:\n record.toState === null\n ? null\n : parseSha256(record.toState, \"ledger.toState\"),\n transitionHash:\n record.transitionHash === null\n ? null\n : parseSha256(record.transitionHash, \"ledger.transitionHash\"),\n direction: parseDirection(record.direction),\n operationId:\n record.operationId === null\n ? null\n : parseRequiredString(record.operationId, \"ledger.operationId\"),\n dispatchId:\n record.dispatchId === null\n ? null\n : parseSha256(record.dispatchId, \"ledger.dispatchId\"),\n effectState: parseEffectState(record.effectState),\n startedAt: parseRequiredString(record.startedAt, \"ledger.startedAt\"),\n finishedAt:\n record.finishedAt === null\n ? null\n : parseRequiredString(record.finishedAt, \"ledger.finishedAt\"),\n toolVersion: parseRequiredString(record.toolVersion, \"ledger.toolVersion\"),\n failure:\n record.failure === null\n ? null\n : parseRequiredString(record.failure, \"ledger.failure\"),\n };\n const admitted =\n kind === \"reset-started\"\n ? { ...event, resetPlan: parseResetPlan(record.resetPlan) }\n : event;\n const { eventId, ...body } = admitted;\n if (eventId !== eventIdFor(body)) {\n throw new MigrationError(\n \"ledger eventId does not match the canonical event\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return admitted;\n}\n\nfunction parseLedgerKind(value: unknown): LedgerEventKindV1 {\n if (isString(value)) {\n for (const kind of LEDGER_KINDS) {\n if (value === kind) return kind;\n }\n }\n refuse(\"ledger event.kind is not a V1 kind\");\n}\n\nfunction parseEffectState(value: unknown): LedgerEffectStateV1 {\n if (isString(value)) {\n for (const effectState of EFFECT_STATES) {\n if (value === effectState) return effectState;\n }\n }\n refuse(\"ledger event.effectState is invalid\");\n}\n\nfunction parseDirection(value: unknown): LedgerEventV1[\"direction\"] {\n if (\n value === \"forward\" ||\n value === \"rollback\" ||\n value === \"reset\" ||\n value === \"baseline\" ||\n value === \"resolve\"\n ) {\n return value;\n }\n refuse(\"ledger event.direction is invalid\");\n}\n\nfunction parseResetPlan(value: unknown): ResetPlanV1 {\n const record = exactObject(\n value,\n RESET_PLAN_KEYS,\n RESET_PLAN_KEYS,\n \"reset plan\"\n );\n if (\n !(\n Array.isArray(record.replayPath) &&\n Array.isArray(record.clearDispatches) &&\n Array.isArray(record.referencedStates)\n )\n ) {\n refuse(\"reset plan arrays are malformed\");\n }\n const plan: ResetPlanV1 = {\n estateHash: parseSha256(record.estateHash, \"resetPlan.estateHash\"),\n targetIdentity: parseRequiredString(\n record.targetIdentity,\n \"resetPlan.targetIdentity\"\n ),\n sourceRevision: parseFiniteInteger(\n record.sourceRevision,\n \"resetPlan.sourceRevision\"\n ),\n sourceFingerprint: parseSha256(\n record.sourceFingerprint,\n \"resetPlan.sourceFingerprint\"\n ),\n replayPath: record.replayPath.map((id, index) =>\n parseSha256(id, `resetPlan.replayPath[${index}]`)\n ),\n clearDispatches: record.clearDispatches.map((dispatch, index) =>\n parseDispatch(dispatch, `resetPlan.clearDispatches[${index}]`)\n ),\n referencedStates: record.referencedStates.map((id, index) =>\n parseSha256(id, `resetPlan.referencedStates[${index}]`)\n ),\n resetPlanHash: parseSha256(record.resetPlanHash, \"resetPlan.resetPlanHash\"),\n };\n const { resetPlanHash, ...body } = plan;\n if (\n resetPlanHash !== domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(body))\n ) {\n throw new MigrationError(\n \"resetPlanHash does not match the canonical reset plan\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return plan;\n}\n","import { normalizeManagedTables } from \"./target\";\n/**\n * Hostile parsers and hash owners for Migration V1 estate, dispatch,\n * state, and transition artifacts.\n *\n * Snapshot and control admission live in sibling modules. This file\n * re-exports them so existing `./v1-parse` imports keep working.\n * Every JSON boundary admits a value only after exact-key validation,\n * re-canonicalization against the original bytes, and hash recomputation.\n * No `JSON.parse(...) as SchemaSnapshot` remains.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isBoolean, isRecord, isString } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport {\n domainHash,\n HASH_ALGORITHM,\n HASH_DOMAIN,\n parseSha256,\n type Sha256,\n} from \"./identity\";\nimport type { MigrationTarget } from \"./types\";\nimport { parseDispatch } from \"./v1-parse-dispatch\";\nimport { exactObject, parseFormat, refuse } from \"./v1-parse-shared\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStateManifestV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport {\n encodePathHash,\n eventIdFor,\n parseLedgerEvent,\n parseMarkerRow,\n} from \"./v1-parse-control\";\nexport { encodeDispatchIdentity, parseDispatch } from \"./v1-parse-dispatch\";\nexport {\n encodeSnapshot,\n parseSnapshotDocument,\n} from \"./v1-parse-snapshot\";\n\nconst ESTATE_KEYS = [\"format\", \"hash\", \"target\"] as const;\nconst PG_TARGET_KEYS = [\"dialect\", \"namespace\", \"tables\"] as const;\nconst DIALECT_ONLY_TARGET_KEYS = [\"dialect\", \"tables\"] as const;\nconst CHECK_KEYS = [\"equals\", \"id\", \"kind\", \"query\"] as const;\nconst PROVEN_STEP_KEYS = [\"execute\", \"postcheck\", \"precheck\", \"retry\"] as const;\nconst OPAQUE_STEP_KEYS = [\"execute\", \"retry\"] as const;\nconst OPERATION_KEYS = [\"id\", \"label\", \"origin\", \"risk\", \"steps\"] as const;\nconst SCHEMA_ROLLBACK_KEYS = [\"kind\", \"operations\"] as const;\nconst MANUAL_ROLLBACK_KEYS = [\n \"kind\",\n \"operations\",\n \"requestedBoundary\",\n] as const;\nconst IRREVERSIBLE_KEYS = [\"kind\", \"reason\"] as const;\nconst PARENT_KEYS = [\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n \"transitionHash\",\n] as const;\nconst STATE_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n \"stateId\",\n] as const;\nconst STATE_HASH_KEYS = [\n \"destinationChecks\",\n \"estateHash\",\n \"format\",\n \"name\",\n \"parents\",\n \"snapshotHash\",\n \"sqlHash\",\n] as const;\nconst TRANSITION_HASH_KEYS = [\n \"fromState\",\n \"operations\",\n \"originChecks\",\n \"requestedForwardBoundary\",\n \"rollback\",\n] as const;\n\nfunction parseManagedTables(value: unknown, label: string): readonly string[] {\n try {\n const tables = normalizeManagedTables(value);\n if (tables !== undefined) return tables;\n } catch {\n refuse(\n `${label}.tables must be a sorted, unique array of physical table names`\n );\n }\n return refuse(`${label}.tables must be an array`);\n}\n\nexport function parseMigrationTarget(\n value: unknown,\n label: string\n): MigrationTarget {\n if (!isRecord(value)) refuse(`${label} must be an object`);\n const dialect = value.dialect;\n if (dialect === \"postgresql\") {\n const record = exactObject(\n value,\n PG_TARGET_KEYS,\n [\"dialect\", \"namespace\"],\n label\n );\n if (!isString(record.namespace) || record.namespace.length === 0) {\n refuse(`${label}.namespace must be a non-empty string`);\n }\n return {\n dialect: \"postgresql\",\n namespace: record.namespace,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n if (dialect === \"mysql\" || dialect === \"sqlite\") {\n exactObject(value, DIALECT_ONLY_TARGET_KEYS, [\"dialect\"], label);\n return {\n dialect,\n ...(value.tables === undefined\n ? {}\n : { tables: parseManagedTables(value.tables, label) }),\n };\n }\n refuse(`${label}.dialect is not a V1 migration target`);\n}\n\nexport function parseEstateDescriptor(bytes: Uint8Array): {\n descriptor: MigrationEstateDescriptorV1;\n estateHash: Sha256;\n} {\n const parsed = parseJsonBytes(bytes, \"estate.json\");\n const record = exactObject(parsed, ESTATE_KEYS, ESTATE_KEYS, \"estate.json\");\n if (record.hash !== HASH_ALGORITHM) {\n refuse('estate.json hash algorithm must be \"sha256\"');\n }\n const descriptor: MigrationEstateDescriptorV1 = {\n format: parseFormat(record.format, \"estate.json\"),\n target: parseMigrationTarget(record.target, \"estate.json.target\"),\n hash: \"sha256\",\n };\n assertCanonicalBytes(bytes, descriptor, \"estate.json\");\n return { descriptor, estateHash: domainHash(HASH_DOMAIN.estate, bytes) };\n}\n\nexport function encodeEstateDescriptor(target: MigrationTarget): {\n bytes: Uint8Array;\n estateHash: Sha256;\n descriptor: MigrationEstateDescriptorV1;\n} {\n const descriptor: MigrationEstateDescriptorV1 = {\n format: \"1\",\n target,\n hash: \"sha256\",\n };\n const bytes = canonicalizeJson(descriptor);\n return {\n bytes,\n estateHash: domainHash(HASH_DOMAIN.estate, bytes),\n descriptor,\n };\n}\n\nfunction parseCheck(value: unknown, label: string): MigrationBooleanCheckV1 {\n const record = exactObject(value, CHECK_KEYS, CHECK_KEYS, label);\n if (record.kind !== \"driver\" && record.kind !== \"trusted-read\") {\n refuse(`${label}.kind must be driver or trusted-read`);\n }\n if (!isString(record.id) || record.id.length === 0) {\n refuse(`${label}.id must be a non-empty string`);\n }\n if (!isBoolean(record.equals)) refuse(`${label}.equals must be boolean`);\n return {\n kind: record.kind,\n id: record.id,\n query: parseDispatch(record.query, `${label}.query`),\n equals: record.equals,\n };\n}\n\nfunction parseStep(value: unknown, label: string): MigrationStepV1 {\n if (\n !isRecord(value) ||\n (value.retry !== \"proven\" && value.retry !== \"opaque\")\n ) {\n refuse(`${label}.retry must be proven or opaque`);\n }\n if (value.retry === \"proven\") {\n const record = exactObject(\n value,\n PROVEN_STEP_KEYS,\n PROVEN_STEP_KEYS,\n label\n );\n return {\n retry: \"proven\",\n precheck: parseCheck(record.precheck, `${label}.precheck`),\n execute: parseDispatch(record.execute, `${label}.execute`),\n postcheck: parseCheck(record.postcheck, `${label}.postcheck`),\n };\n }\n const record = exactObject(value, OPAQUE_STEP_KEYS, OPAQUE_STEP_KEYS, label);\n return {\n retry: \"opaque\",\n execute: parseDispatch(record.execute, `${label}.execute`),\n };\n}\n\nfunction parseOperation(value: unknown, label: string): MigrationOperationV1 {\n const record = exactObject(value, OPERATION_KEYS, OPERATION_KEYS, label);\n if (!isString(record.id) || record.id.length === 0)\n refuse(`${label}.id is required`);\n if (!isString(record.label) || record.label.length === 0) {\n refuse(`${label}.label is required`);\n }\n if (record.origin !== \"generated\" && record.origin !== \"manual\") {\n refuse(`${label}.origin must be generated or manual`);\n }\n if (\n record.risk !== \"safe\" &&\n record.risk !== \"destructive\" &&\n record.risk !== \"opaque\"\n ) {\n refuse(`${label}.risk is not a V1 risk class`);\n }\n if (!Array.isArray(record.steps) || record.steps.length === 0) {\n refuse(`${label}.steps must be a non-empty array`);\n }\n return {\n id: record.id,\n label: record.label,\n origin: record.origin,\n risk: record.risk,\n steps: record.steps.map((step, index) =>\n parseStep(step, `${label}.steps[${index}]`)\n ),\n };\n}\n\nfunction parseRollback(value: unknown, label: string): MigrationRollbackV1 {\n if (!(isRecord(value) && isString(value.kind)))\n refuse(`${label} must be a tagged rollback`);\n if (value.kind === \"schema\") {\n const record = exactObject(\n value,\n SCHEMA_ROLLBACK_KEYS,\n SCHEMA_ROLLBACK_KEYS,\n label\n );\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"schema\",\n operations: record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n ),\n };\n }\n if (value.kind === \"manual\") {\n const record = exactObject(\n value,\n MANUAL_ROLLBACK_KEYS,\n MANUAL_ROLLBACK_KEYS,\n label\n );\n if (\n record.requestedBoundary !== \"transactional\" &&\n record.requestedBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedBoundary must be transactional or stepwise`);\n }\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n return {\n kind: \"manual\",\n requestedBoundary: record.requestedBoundary,\n operations: record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n ),\n };\n }\n if (value.kind === \"irreversible\") {\n const record = exactObject(\n value,\n IRREVERSIBLE_KEYS,\n IRREVERSIBLE_KEYS,\n label\n );\n if (!isString(record.reason) || record.reason.trim().length === 0) {\n refuse(`${label}.reason must be a non-empty string`);\n }\n return { kind: \"irreversible\", reason: record.reason };\n }\n refuse(`${label}.kind is not a V1 rollback`);\n}\n\nexport function encodeTransitionHash(\n transition: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of TRANSITION_HASH_KEYS) {\n body[key] = transition[key];\n }\n return domainHash(HASH_DOMAIN.transition, canonicalizeJson(body));\n}\n\nfunction parseParent(\n value: unknown,\n label: string\n): MigrationParentTransitionV1 {\n const record = exactObject(value, PARENT_KEYS, PARENT_KEYS, label);\n const fromState =\n record.fromState === null\n ? null\n : parseSha256(record.fromState, `${label}.fromState`);\n if (\n record.requestedForwardBoundary !== null &&\n record.requestedForwardBoundary !== \"transactional\" &&\n record.requestedForwardBoundary !== \"stepwise\"\n ) {\n refuse(`${label}.requestedForwardBoundary is invalid`);\n }\n if (!Array.isArray(record.originChecks))\n refuse(`${label}.originChecks must be an array`);\n if (!Array.isArray(record.operations))\n refuse(`${label}.operations must be an array`);\n const operations = record.operations.map((operation, index) =>\n parseOperation(operation, `${label}.operations[${index}]`)\n );\n const rollback = parseRollback(record.rollback, `${label}.rollback`);\n const origins = new Set(operations.map((operation) => operation.origin));\n if (origins.size > 1) {\n refuse(`${label} mixes generated and manual operations`);\n }\n if (record.requestedForwardBoundary !== null && origins.has(\"generated\")) {\n refuse(\n `${label}.requestedForwardBoundary is only valid on a manual transition`\n );\n }\n if (rollback.kind === \"manual\" && origins.has(\"generated\")) {\n refuse(`${label}.rollback cannot be manual on a generated transition`);\n }\n const parsed: Omit<MigrationParentTransitionV1, \"transitionHash\"> = {\n fromState,\n originChecks: record.originChecks.map((check, index) =>\n parseCheck(check, `${label}.originChecks[${index}]`)\n ),\n requestedForwardBoundary: record.requestedForwardBoundary,\n operations,\n rollback,\n };\n const transitionHash = parseSha256(\n record.transitionHash,\n `${label}.transitionHash`\n );\n const expected = encodeTransitionHash(parsed);\n if (transitionHash !== expected) {\n throw new MigrationError(\n `${label}.transitionHash does not match its transition`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...parsed, transitionHash };\n}\n\nexport function compareFromState(\n left: Sha256 | null,\n right: Sha256 | null\n): number {\n if (left === right) return 0;\n if (left === null) return -1;\n if (right === null) return 1;\n return left < right ? -1 : 1;\n}\n\nexport function sortParents(\n parents: readonly MigrationParentTransitionV1[]\n): MigrationParentTransitionV1[] {\n return [...parents].sort((left, right) =>\n compareFromState(left.fromState, right.fromState)\n );\n}\n\nexport function encodeStateId(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): Sha256 {\n const body: Record<string, unknown> = {};\n for (const key of STATE_HASH_KEYS) {\n body[key] = manifest[key];\n }\n return domainHash(HASH_DOMAIN.state, canonicalizeJson(body));\n}\n\nexport function parseStateManifest(\n bytes: Uint8Array,\n expectedId: Sha256\n): MigrationStateManifestV1 {\n const parsed = parseJsonBytes(bytes, `states/${expectedId}.json`);\n const record = exactObject(parsed, STATE_KEYS, STATE_KEYS, \"state manifest\");\n if (!Array.isArray(record.parents) || record.parents.length === 0) {\n refuse(\"state manifest must have at least one parent transition\");\n }\n if (!Array.isArray(record.destinationChecks)) {\n refuse(\"state manifest.destinationChecks must be an array\");\n }\n if (!isString(record.name) || record.name.length === 0) {\n refuse(\"state manifest.name must be a non-empty string\");\n }\n const parents = record.parents.map((parent, index) =>\n parseParent(parent, `state.parents[${index}]`)\n );\n for (let i = 1; i < parents.length; i++) {\n if (\n compareFromState(parents[i - 1]!.fromState, parents[i]!.fromState) >= 0\n ) {\n refuse(\n \"state manifest parents must be sorted by fromState with null first\"\n );\n }\n }\n const seen = new Set<string>();\n for (const parent of parents) {\n const key = parent.fromState ?? \"null\";\n if (seen.has(key)) refuse(\"state manifest has a duplicate parent\");\n seen.add(key);\n }\n const withoutId: Omit<MigrationStateManifestV1, \"stateId\"> = {\n format: parseFormat(record.format, \"state manifest\"),\n estateHash: parseSha256(record.estateHash, \"state.estateHash\"),\n name: record.name,\n snapshotHash: parseSha256(record.snapshotHash, \"state.snapshotHash\"),\n sqlHash: parseSha256(record.sqlHash, \"state.sqlHash\"),\n destinationChecks: record.destinationChecks.map((check, index) =>\n parseCheck(check, `state.destinationChecks[${index}]`)\n ),\n parents,\n };\n assertCanonicalBytes(\n bytes,\n { ...withoutId, stateId: expectedId },\n `states/${expectedId}.json`\n );\n const stateId = parseSha256(record.stateId, \"state.stateId\");\n const expected = encodeStateId(withoutId);\n if (stateId !== expected || stateId !== expectedId) {\n throw new MigrationError(\n \"stateId does not match the canonical manifest or filename\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { ...withoutId, stateId };\n}\n\nexport function encodeStateManifest(\n manifest: Omit<MigrationStateManifestV1, \"stateId\">\n): { bytes: Uint8Array; stateId: Sha256; manifest: MigrationStateManifestV1 } {\n const parents = sortParents(manifest.parents);\n const sorted = { ...manifest, parents };\n const stateId = encodeStateId(sorted);\n const complete = { ...sorted, stateId };\n return { bytes: canonicalizeJson(complete), stateId, manifest: complete };\n}\n\nexport function encodeSqlBlob(bytes: Uint8Array): Sha256 {\n return domainHash(HASH_DOMAIN.sql, bytes);\n}\n","import { normalizeType } from \"./push-fingerprint\";\n/**\n * Marker and ledger control tables. Two tables, one validated base name.\n * Read-only commands never bootstrap. Parsers in v1-parse own row truth.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { errorCause } from \"../drivers/shared/driver-options\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport { tableExistsProbe } from \"./catalog-probes\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport type { Sha256 } from \"./identity\";\nimport type { SchemaSnapshot, TableDef } from \"./types\";\nimport { encodePathHash, parseLedgerEvent, parseMarkerRow } from \"./v1-parse\";\nimport type { LedgerEventV1, MigrationMarkerV1 } from \"./v1-types\";\n\nexport const DEFAULT_CONTROL_BASE = \"_viborm_migration\";\n\nconst CONTROL_BASE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst CHECK_PREFIX = /^\\s*check\\s*/i;\nconst CHECK_FORMATTING = /[\\s()\"`]/g;\n\nexport type ControlPresence =\n | { readonly kind: \"missing-table\"; readonly table: \"state\" | \"log\" | \"both\" }\n | { readonly kind: \"recoverable-state-only\" }\n | { readonly kind: \"present\" };\n\nexport function controlTableNames(base: string): {\n state: string;\n log: string;\n} {\n if (!CONTROL_BASE_NAME.test(base)) {\n throw new MigrationError(\n \"Control table base name is not a safe identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return { state: `${base}_state`, log: `${base}_log` };\n}\n\nexport function qualifyControl(\n driver: BoundMigrationDriver,\n name: string\n): string {\n if (driver.target.dialect === \"postgresql\") {\n return `${quotePg(driver.namespace ?? driver.target.namespace)}.${quotePg(name)}`;\n }\n if (driver.target.dialect === \"mysql\" && driver.namespace) {\n return `${quoteMy(driver.namespace)}.${quoteMy(name)}`;\n }\n return quoteIdent(driver.target.dialect, name);\n}\n\nfunction quotePg(value: string): string {\n return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction quoteMy(value: string): string {\n return `\\`${value.replaceAll(\"`\", \"``\")}\\``;\n}\n\nfunction quoteIdent(\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n value: string\n): string {\n return dialect === \"mysql\" ? quoteMy(value) : quotePg(value);\n}\n\nfunction placeholder(\n dialect: BoundMigrationDriver[\"target\"][\"dialect\"],\n index: number\n): string {\n return dialect === \"postgresql\" ? `$${index}` : \"?\";\n}\n\nconst STATE_CONTROL_DEFINITION = `(\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n payload TEXT NOT NULL\n )`;\n\n/** Exact writer-owned state definition; the control owner authenticates its contents separately. */\nexport function isSqliteStateControlDefinition(\n name: string,\n sql: string | null\n): boolean {\n return (\n name === controlTableNames(DEFAULT_CONTROL_BASE).state &&\n sql !== null &&\n sqliteDefinitionBody(sql) === sqliteDefinitionBody(STATE_CONTROL_DEFINITION)\n );\n}\n\nexport function createControlTableSQL(\n driver: BoundMigrationDriver,\n base: string\n): { state: string; log: string } {\n const names = controlTableNames(base);\n const state = qualifyControl(driver, names.state);\n const log = qualifyControl(driver, names.log);\n return {\n state: `CREATE TABLE IF NOT EXISTS ${state} ${STATE_CONTROL_DEFINITION}`,\n log:\n driver.target.dialect === \"mysql\"\n ? `CREATE TABLE IF NOT EXISTS ${log} (\n event_id VARCHAR(64) PRIMARY KEY,\n attempt_id VARCHAR(64) NOT NULL,\n kind VARCHAR(32) NOT NULL,\n payload TEXT NOT NULL\n )`\n : `CREATE TABLE IF NOT EXISTS ${log} (\n event_id TEXT PRIMARY KEY,\n attempt_id TEXT NOT NULL,\n kind TEXT NOT NULL,\n payload TEXT NOT NULL\n )`,\n };\n}\n\nexport function refusePartialControl(presence: ControlPresence): void {\n if (presence.kind === \"recoverable-state-only\") {\n throw new MigrationError(\n \"Migration control tables are inconsistent: log is missing after interrupted bootstrap\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (presence.kind === \"missing-table\" && presence.table !== \"both\") {\n throw new MigrationError(\n `Migration control tables are inconsistent: ${presence.table} is missing`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\nexport function refuseIncompatibleHistory(\n marker: MigrationMarkerV1 | null,\n ledger: readonly LedgerEventV1[]\n): void {\n if (marker !== null || ledger.length === 0) return;\n if (unfinishedAttempts(ledger).length > 0) return;\n throw new MigrationError(\n \"Migration ledger history exists without a current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\nexport async function inspectControlPresence(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string\n): Promise<ControlPresence> {\n const names = controlTableNames(base);\n const stateMissing = await isTableMissing(producer, driver, names.state);\n const logMissing = await isTableMissing(producer, driver, names.log);\n if (stateMissing && logMissing)\n return { kind: \"missing-table\", table: \"both\" };\n if (stateMissing) return { kind: \"missing-table\", table: \"state\" };\n if (logMissing) {\n // Bootstrap creates state before log. If the second CREATE failed, the\n // empty state table is the one recognizable partial state that can be\n // completed idempotently. A marker row means this is real history with a\n // missing ledger and must remain a hard refusal.\n await assertExpectedStateControlTable(producer, driver, names);\n if (await isStateControlEmpty(producer, driver, names.state)) {\n return { kind: \"recoverable-state-only\" };\n }\n return { kind: \"missing-table\", table: \"log\" };\n }\n return { kind: \"present\" };\n}\n\n/** Proves that both reserved control tables still have VibORM's exact shape. */\nexport async function assertControlTablesAuthentic(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string\n): Promise<void> {\n const names = controlTableNames(base);\n let snapshot: SchemaSnapshot;\n try {\n snapshot = await driver.introspect((sql, params) =>\n producer._executeRaw(sql, params)\n );\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"Migration control tables cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n const stateMatches = snapshot.tables.filter(\n (table) => table.name === names.state\n );\n const logMatches = snapshot.tables.filter(\n (table) => table.name === names.log\n );\n if (\n stateMatches.length !== 1 ||\n logMatches.length !== 1 ||\n !hasExpectedStateTableShape(stateMatches[0]!, driver, names.state) ||\n !hasExpectedLogTableShape(logMatches[0]!, driver, names.log)\n ) {\n throw new MigrationError(\n \"Migration control tables have an unexpected definition\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasSingletonCheck: boolean;\n try {\n hasSingletonCheck = await hasExpectedSingletonCheck(\n producer,\n driver,\n names.state\n );\n } catch (failure) {\n throw new MigrationError(\n \"Migration control tables cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n if (!hasSingletonCheck) {\n throw new MigrationError(\n \"Migration control tables have an unexpected definition\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasAttachments: boolean;\n try {\n hasAttachments = await hasControlAttachments(producer, driver, names);\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"Migration control tables cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n if (hasAttachments) {\n throw new MigrationError(\n \"Migration control tables have executable attachments\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\nasync function assertExpectedStateControlTable(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n names: { readonly state: string; readonly log: string }\n): Promise<void> {\n const tableName = names.state;\n let snapshot: SchemaSnapshot;\n try {\n snapshot = await driver.introspect((sql, params) =>\n producer._executeRaw(sql, params)\n );\n } catch (failure) {\n throw new MigrationError(\n \"A partial migration control state table cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n const matches = snapshot.tables.filter((table) => table.name === tableName);\n const stateTable = matches[0];\n if (\n matches.length !== 1 ||\n !stateTable ||\n !hasExpectedStateTableShape(stateTable, driver, tableName)\n ) {\n throw new MigrationError(\n \"A partial migration control state table has an unexpected definition\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasSingletonCheck: boolean;\n try {\n hasSingletonCheck = await hasExpectedSingletonCheck(\n producer,\n driver,\n tableName\n );\n } catch (failure) {\n throw new MigrationError(\n \"A partial migration control state table cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n if (!hasSingletonCheck) {\n throw new MigrationError(\n \"A partial migration control state table has an unexpected definition\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n let hasAttachments: boolean;\n try {\n hasAttachments = await hasControlAttachments(producer, driver, names);\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"A partial migration control state table cannot be authenticated\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n if (hasAttachments) {\n throw new MigrationError(\n \"A partial migration control state table has executable attachments\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\nfunction hasExpectedStateTableShape(\n table: TableDef,\n driver: BoundMigrationDriver,\n tableName: string\n): boolean {\n const singleton = table.columns[0];\n const payload = table.columns[1];\n const singletonType =\n driver.target.dialect === \"postgresql\"\n ? \"int4\"\n : driver.target.dialect === \"mysql\"\n ? \"INT\"\n : \"INTEGER\";\n const payloadType = driver.target.dialect === \"mysql\" ? \"TEXT\" : \"text\";\n const primaryKeyName =\n driver.target.dialect === \"mysql\" ? \"PRIMARY\" : `${tableName}_pkey`;\n return (\n table.columns.length === 2 &&\n singleton?.name === \"singleton\" &&\n normalizeType(singleton.type) === normalizeType(singletonType) &&\n singleton.nullable === false &&\n singleton.default === undefined &&\n singleton.autoIncrement !== true &&\n singleton.decimal === undefined &&\n payload?.name === \"payload\" &&\n payload.type.toLowerCase() === payloadType.toLowerCase() &&\n payload.nullable === false &&\n payload.default === undefined &&\n payload.autoIncrement !== true &&\n payload.decimal === undefined &&\n table.primaryKey?.name === primaryKeyName &&\n table.primaryKey.columns.length === 1 &&\n table.primaryKey.columns[0] === \"singleton\" &&\n table.indexes.length === 0 &&\n table.foreignKeys.length === 0 &&\n table.uniqueConstraints.length === 0 &&\n table.relationStorage === undefined\n );\n}\n\nfunction hasExpectedLogTableShape(\n table: TableDef,\n driver: BoundMigrationDriver,\n tableName: string\n): boolean {\n const expected =\n driver.target.dialect === \"mysql\"\n ? [\n [\"event_id\", \"varchar(64)\"],\n [\"attempt_id\", \"varchar(64)\"],\n [\"kind\", \"varchar(32)\"],\n [\"payload\", \"text\"],\n ]\n : [\n [\"event_id\", \"text\"],\n [\"attempt_id\", \"text\"],\n [\"kind\", \"text\"],\n [\"payload\", \"text\"],\n ];\n const primaryKeyName =\n driver.target.dialect === \"mysql\" ? \"PRIMARY\" : `${tableName}_pkey`;\n return (\n table.columns.length === expected.length &&\n table.columns.every((column, index) => {\n const shape = expected[index];\n return (\n shape !== undefined &&\n column.name === shape[0] &&\n column.type.toLowerCase() === shape[1] &&\n column.nullable === false &&\n column.default === undefined &&\n column.autoIncrement !== true &&\n column.decimal === undefined\n );\n }) &&\n table.primaryKey?.name === primaryKeyName &&\n table.primaryKey.columns.length === 1 &&\n table.primaryKey.columns[0] === \"event_id\" &&\n table.indexes.length === 0 &&\n table.foreignKeys.length === 0 &&\n table.uniqueConstraints.length === 0 &&\n table.relationStorage === undefined\n );\n}\n\nasync function hasExpectedSingletonCheck(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n if (driver.target.dialect === \"sqlite\") {\n const result = await producer._executeRaw<{ sql: unknown }>(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [tableName]\n );\n if (result.rows.length !== 1 || typeof result.rows[0]?.sql !== \"string\") {\n return false;\n }\n const expected = createControlTableSQL(driver, DEFAULT_CONTROL_BASE).state;\n return (\n sqliteDefinitionBody(result.rows[0].sql) ===\n sqliteDefinitionBody(expected)\n );\n }\n const result =\n driver.target.dialect === \"postgresql\"\n ? await producer._executeRaw<{ definition: unknown }>(\n `SELECT pg_get_constraintdef(c.oid, true) AS definition\nFROM pg_catalog.pg_constraint c\nJOIN pg_catalog.pg_class t ON t.oid = c.conrelid\nJOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace\nWHERE n.nspname = $1 AND t.relname = $2 AND c.contype = 'c'\nORDER BY c.conname`,\n [driver.namespace ?? driver.target.namespace, tableName]\n )\n : await producer._executeRaw<{ definition: unknown }>(\n `SELECT cc.CHECK_CLAUSE AS definition\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.CHECK_CONSTRAINTS cc\n ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\nWHERE tc.CONSTRAINT_SCHEMA = ?\n AND tc.TABLE_NAME = ?\n AND tc.CONSTRAINT_TYPE = 'CHECK'\nORDER BY tc.CONSTRAINT_NAME`,\n [driver.namespace, tableName]\n );\n return (\n result.rows.length === 1 &&\n normalizeSingletonCheck(result.rows[0]?.definition) === \"singleton=1\"\n );\n}\n\nfunction sqliteDefinitionBody(sql: string): string {\n const body = sql.slice(sql.indexOf(\"(\"));\n return body.replace(/[\\s\"`]/g, \"\").toLowerCase();\n}\n\nfunction normalizeSingletonCheck(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value\n .replace(CHECK_PREFIX, \"\")\n .replace(CHECK_FORMATTING, \"\")\n .toLowerCase();\n}\n\nasync function hasControlAttachments(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n names: { readonly state: string; readonly log: string }\n): Promise<boolean> {\n const result =\n driver.target.dialect === \"sqlite\"\n ? await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND tbl_name IN (?, ?)) AS attached\",\n [names.state, names.log]\n )\n : driver.target.dialect === \"mysql\"\n ? await producer._executeRaw<Record<string, unknown>>(\n \"SELECT EXISTS (SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = ? AND EVENT_OBJECT_TABLE IN (?, ?)) AS attached\",\n [driver.namespace, names.state, names.log]\n )\n : await producer._executeRaw<Record<string, unknown>>(\n `SELECT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_trigger trigger\n JOIN pg_catalog.pg_class table_class ON table_class.oid = trigger.tgrelid\n JOIN pg_catalog.pg_namespace namespace ON namespace.oid = table_class.relnamespace\n WHERE namespace.nspname = $1\n AND table_class.relname IN ($2, $3)\n AND NOT trigger.tgisinternal\n UNION ALL\n SELECT 1\n FROM pg_catalog.pg_rewrite rule\n JOIN pg_catalog.pg_class table_class ON table_class.oid = rule.ev_class\n JOIN pg_catalog.pg_namespace namespace ON namespace.oid = table_class.relnamespace\n WHERE namespace.nspname = $1\n AND table_class.relname IN ($2, $3)\n AND rule.rulename <> '_RETURN'\n UNION ALL\n SELECT 1\n FROM pg_catalog.pg_policy policy\n JOIN pg_catalog.pg_class table_class ON table_class.oid = policy.polrelid\n JOIN pg_catalog.pg_namespace namespace ON namespace.oid = table_class.relnamespace\n WHERE namespace.nspname = $1\n AND table_class.relname IN ($2, $3)\n UNION ALL\n SELECT 1\n FROM pg_catalog.pg_class table_class\n JOIN pg_catalog.pg_namespace namespace ON namespace.oid = table_class.relnamespace\n WHERE namespace.nspname = $1\n AND table_class.relname IN ($2, $3)\n AND (table_class.relrowsecurity OR table_class.relforcerowsecurity)\n) AS attached`,\n [\n driver.namespace ?? driver.target.namespace,\n names.state,\n names.log,\n ]\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Migration control attachment probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const value = Object.values(result.rows[0]!)[0];\n if (isPresentCatalogFlag(value)) return true;\n if (isAbsentCatalogFlag(value)) return false;\n throw new MigrationError(\n \"Migration control attachment probe returned an invalid flag\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\nasync function isStateControlEmpty(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const table = qualifyControl(driver, tableName);\n try {\n const result = await producer._executeRaw(\n `SELECT payload FROM ${table} WHERE singleton = 1`\n );\n return result.rows.length === 0;\n } catch (failure) {\n throw new MigrationError(\n \"A partial migration control state table cannot be proven empty\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { cause: errorCause(failure) }\n );\n }\n}\n\nasync function isTableMissing(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n tableName: string\n): Promise<boolean> {\n const probe = tableExistsProbe(driver, tableName, true);\n const result = await producer._executeRaw<Record<string, unknown>>(\n probe.sql,\n probeParameters(probe.parameters)\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n \"Control catalog probe must return exactly one row\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return !isPresentCatalogFlag(Object.values(result.rows[0]!)[0]);\n}\n\nfunction probeParameters(\n parameters: ReturnType<typeof tableExistsProbe>[\"parameters\"]\n): unknown[] {\n return parameters.map((parameter) => {\n if (parameter.kind !== \"string\") {\n throw new MigrationError(\n \"Control catalog probe parameters must be strings\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return parameter.value;\n });\n}\n\nfunction isPresentCatalogFlag(value: unknown): boolean {\n return (\n value === true ||\n value === 1 ||\n value === 1n ||\n value === \"1\" ||\n value === \"t\" ||\n value === \"true\"\n );\n}\n\nfunction isAbsentCatalogFlag(value: unknown): boolean {\n return (\n value === false ||\n value === 0 ||\n value === 0n ||\n value === \"0\" ||\n value === \"f\" ||\n value === \"false\"\n );\n}\n\nexport interface MigrationControlRead {\n readonly presence: ControlPresence;\n readonly marker: MigrationMarkerV1 | null;\n readonly ledger: readonly LedgerEventV1[];\n}\n\n/**\n * Reads the complete control-plane view. A present pair is authenticated once\n * before either table is trusted; callers decide whether total absence or the\n * recoverable bootstrap arm is valid for their command.\n */\nexport async function readControlState(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string\n): Promise<MigrationControlRead> {\n const presence = await inspectControlPresence(producer, driver, base);\n if (presence.kind !== \"present\") {\n return { presence, marker: null, ledger: [] };\n }\n await assertControlTablesAuthentic(producer, driver, base);\n const names = controlTableNames(base);\n const markerResult = await producer._executeRaw<{ payload: unknown }>(\n `SELECT payload FROM ${qualifyControl(driver, names.state)} WHERE singleton = 1`\n );\n const markerRow = markerResult.rows[0];\n const marker = markerRow\n ? parseMarkerRow(parsePayload(markerRow.payload))\n : null;\n const ledgerResult = await producer._executeRaw<{ payload: unknown }>(\n `SELECT payload FROM ${qualifyControl(driver, names.log)}`\n );\n const ledger = ledgerResult.rows\n .map((row) => parseLedgerEvent(parsePayload(row.payload)))\n .sort((left, right) => {\n if (left.startedAt !== right.startedAt) {\n return left.startedAt < right.startedAt ? -1 : 1;\n }\n return left.eventId < right.eventId ? -1 : 1;\n });\n return { presence, marker, ledger };\n}\n\nexport async function ensureControlTables(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string\n): Promise<void> {\n const presence = await inspectControlPresence(producer, driver, base);\n if (presence.kind === \"present\") {\n await assertControlTablesAuthentic(producer, driver, base);\n return;\n }\n if (presence.kind === \"missing-table\") {\n refusePartialControl(presence);\n }\n const names = controlTableNames(base);\n const stateMissing = await isTableMissing(producer, driver, names.state);\n const logMissing = await isTableMissing(producer, driver, names.log);\n if (!stateMissing && logMissing) {\n if (presence.kind !== \"recoverable-state-only\") {\n throw new MigrationError(\n \"Migration control tables changed during bootstrap\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await assertExpectedStateControlTable(producer, driver, names);\n if (!(await isStateControlEmpty(producer, driver, names.state))) {\n throw new MigrationError(\n \"Migration control tables are inconsistent: log is missing\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await producer._executeRaw(\n `DROP TABLE ${qualifyControl(driver, names.state)}`\n );\n } else if (!(stateMissing && logMissing)) {\n throw new MigrationError(\n \"Migration control tables changed during bootstrap\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const sql = createControlTableSQL(driver, base);\n await producer._executeRaw(sql.state);\n await producer._executeRaw(sql.log);\n await assertControlTablesAuthentic(producer, driver, base);\n}\n\nexport async function casMarker(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string,\n expected: { revision: number; pathHash: Sha256 } | null,\n next: MigrationMarkerV1\n): Promise<void> {\n const table = qualifyControl(driver, controlTableNames(base).state);\n const payload = canonicalizeJsonText(next);\n const dialect = driver.target.dialect;\n if (expected === null) {\n try {\n const result = await producer._executeRaw(\n `INSERT INTO ${table} (singleton, payload) VALUES (1, ${placeholder(dialect, 1)})`,\n [payload]\n );\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker insert did not create the singleton row\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n } catch (error) {\n if (error instanceof MigrationError) throw error;\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n return;\n }\n\n const revisionMatch =\n dialect === \"postgresql\"\n ? `(payload::json->>'revision')::bigint = ${placeholder(dialect, 2)}`\n : dialect === \"mysql\"\n ? `CAST(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.revision')) AS UNSIGNED) = ${placeholder(dialect, 2)}`\n : `CAST(json_extract(payload, '$.revision') AS INTEGER) = ${placeholder(dialect, 2)}`;\n const pathMatch =\n dialect === \"postgresql\"\n ? `payload::json->>'pathHash' = ${placeholder(dialect, 3)}`\n : dialect === \"mysql\"\n ? `JSON_UNQUOTE(JSON_EXTRACT(payload, '$.pathHash')) = ${placeholder(dialect, 3)}`\n : `json_extract(payload, '$.pathHash') = ${placeholder(dialect, 3)}`;\n const result = await producer._executeRaw(\n `UPDATE ${table} SET payload = ${placeholder(dialect, 1)} WHERE singleton = 1 AND ${revisionMatch} AND ${pathMatch}`,\n [payload, expected.revision, expected.pathHash]\n );\n if (result.rowCount !== 1) {\n throw new MigrationError(\n \"Migration marker compare-and-swap failed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n}\n\nexport async function appendLedger(\n producer: AnyDriver,\n driver: BoundMigrationDriver,\n base: string,\n event: LedgerEventV1\n): Promise<void> {\n const table = qualifyControl(driver, controlTableNames(base).log);\n const dialect = driver.target.dialect;\n await producer._executeRaw(\n `INSERT INTO ${table} (event_id, attempt_id, kind, payload) VALUES (${placeholder(dialect, 1)}, ${placeholder(dialect, 2)}, ${placeholder(dialect, 3)}, ${placeholder(dialect, 4)})`,\n [event.eventId, event.attemptId, event.kind, canonicalizeJsonText(event)]\n );\n}\n\nexport function markerFromPath(\n estateHash: Sha256,\n snapshotHash: Sha256,\n path: MigrationMarkerV1[\"path\"],\n revision: number\n): MigrationMarkerV1 {\n const stateId = path.length === 0 ? null : path.at(-1)!.stateId;\n return {\n format: \"1\",\n estateHash,\n stateId,\n snapshotHash,\n path,\n pathHash: encodePathHash(path),\n revision,\n updatedAt: new Date().toISOString(),\n };\n}\n\nfunction parsePayload(value: unknown): unknown {\n if (typeof value === \"string\") return JSON.parse(value);\n return value;\n}\n\nexport function unfinishedAttempts(\n events: readonly LedgerEventV1[]\n): readonly LedgerEventV1[] {\n const started = new Map<string, LedgerEventV1>();\n const closed = new Set<string>();\n for (const event of events) {\n if (event.kind === \"started\" || event.kind === \"reset-started\") {\n started.set(event.attemptId, event);\n }\n if (\n event.kind === \"applied\" ||\n event.kind === \"rolled-back\" ||\n event.kind === \"failed\" ||\n event.kind === \"baselined\" ||\n event.kind === \"resolved\" ||\n event.kind === \"reset-applied\"\n ) {\n closed.add(event.attemptId);\n }\n }\n return [...started.values()].filter((event) => !closed.has(event.attemptId));\n}\n","/** Settles one hostile record into an exact immutable property snapshot. */\n\nimport { errorCause } from \"../drivers/shared/driver-options\";\n\ntype RefuseInput = (message: string, cause?: Error) => never;\n\nexport function snapshotExactRecord(\n value: unknown,\n allowed: readonly string[],\n label: string,\n refuse: RefuseInput\n): Readonly<Record<string, unknown>> {\n let objectValue: object | undefined;\n let keys: readonly PropertyKey[] = [];\n try {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n objectValue = value;\n keys = Reflect.ownKeys(value);\n }\n } catch (failure) {\n return refuse(`${label} could not be inspected`, errorCause(failure));\n }\n if (!objectValue) return refuse(`${label} must be an object`);\n const snapshot: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\" || !allowed.includes(key)) {\n return refuse(`${label} contains unknown key ${String(key)}`);\n }\n try {\n snapshot[key] = Reflect.get(objectValue, key);\n } catch (failure) {\n return refuse(`${label}.${key} could not be read`, errorCause(failure));\n }\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotExactArray(\n value: unknown,\n label: string,\n refuse: RefuseInput\n): readonly unknown[] {\n let entries: unknown[] | undefined;\n try {\n if (Array.isArray(value)) entries = Array.from(value);\n } catch (failure) {\n return refuse(`${label} could not be read`, errorCause(failure));\n }\n if (!entries) return refuse(`${label} must be an array`);\n return Object.freeze(entries);\n}\n","/**\n * The order in which tables are dropped: children before parents.\n *\n * Two callers need it, with different premises. A generated program\n * (`orderTableDrops`, reached through `prepareSchemaProgram`) still has live\n * foreign keys when it drops a table, so an order that violates one fails,\n * and a cycle is broken only where a key's delete action allows it. A\n * namespace reset (`live-reset.ts`) has already dropped every key it can see,\n * so its order is defence and a cycle falls back to inventory order.\n * `childrenBeforeParents` is the one rule they share; what a cycle means stays\n * with each caller.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { DiffOperation, ReferentialAction, SchemaSnapshot } from \"./types\";\n\n/** `from` holds a foreign key that references `to`. */\nexport interface TableReference {\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * Orders `items` so that no item comes after a table it is referenced by.\n *\n * Each round takes every item no remaining item references, in input order, so\n * independent tables keep their given order. What a cycle leaves unordered is\n * returned as `blocked`, in input order; a reference from an item to itself\n * blocks that item.\n */\nexport function childrenBeforeParents<T>(\n items: readonly T[],\n nameOf: (item: T) => string,\n references: readonly TableReference[]\n): { ordered: T[]; blocked: T[] } {\n const referencedBy = new Map<string, string[]>();\n for (const { from, to } of references) {\n const children = referencedBy.get(to);\n if (children) {\n children.push(from);\n } else {\n referencedBy.set(to, [from]);\n }\n }\n\n let remaining = [...items];\n const ordered: T[] = [];\n for (;;) {\n const names = new Set(remaining.map(nameOf));\n const isFree = (item: T) =>\n !referencedBy.get(nameOf(item))?.some((child) => names.has(child));\n const free = remaining.filter(isFree);\n if (free.length === 0) {\n return { ordered, blocked: remaining };\n }\n ordered.push(...free);\n remaining = remaining.filter((item) => !isFree(item));\n }\n}\n\ntype DropTable = Extract<DiffOperation, { type: \"dropTable\" }>;\n\nconst tableOf = (drop: DropTable) => drop.tableName;\n\n/** A key still active when its tables are dropped. */\ninterface ActiveKey extends TableReference {\n readonly columns: readonly string[];\n readonly onDelete: ReferentialAction | undefined;\n}\n\n/**\n * Orders a prepared program's `dropTable` operations from the foreign keys\n * the CURRENT snapshot says exist, children first wherever the keys allow.\n *\n * A key matters while it is still active when its tables are dropped: both of\n * its tables are dropped, and the program does not remove it with an explicit\n * `dropForeignKey`. PostgreSQL and MySQL remove every such key first\n * (`materializeDroppedTableForeignKeys`), so their drops keep the order they\n * were given. A retained table never references a dropped one: the desired\n * schema cannot, so the differ removes that key, and `sortOperations` runs\n * every `dropForeignKey` before every `dropTable`.\n *\n * SQLite holds keys inline and drops with enforcement on. `DROP TABLE` first\n * deletes every row, applying each key's delete action (`refusalOf`), so a\n * cycle is broken at a table whose drop no key can refuse, and refused before\n * any statement exists when no such table remains. The drops replace the band\n * of drops `sortOperations` emitted, where that band begins.\n */\nexport function orderTableDrops(\n operations: DiffOperation[],\n current: SchemaSnapshot\n): DiffOperation[] {\n const drops = operations.filter(\n (operation): operation is DropTable => operation.type === \"dropTable\"\n );\n if (drops.length === 0) {\n return operations;\n }\n\n const dropped = new Set(drops.map(tableOf));\n const removedKeys = new Set<string>();\n for (const operation of operations) {\n if (operation.type === \"dropForeignKey\") {\n removedKeys.add(`${operation.tableName} ${operation.fkName}`);\n }\n }\n const keys: ActiveKey[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const active =\n dropped.has(table.name) &&\n dropped.has(fk.referencedTable) &&\n !removedKeys.has(`${table.name} ${fk.name}`);\n if (active) {\n keys.push({\n from: table.name,\n to: fk.referencedTable,\n columns: fk.columns,\n onDelete: fk.onDelete,\n });\n }\n }\n }\n // Children first: every key between two tables, and a self-reference that\n // refuses even its own table's delete.\n const childFirst = keys.filter(\n (key) => key.from !== key.to || key.onDelete === \"restrict\"\n );\n\n const ordered: DropTable[] = [];\n let remaining = drops;\n for (;;) {\n const step = childrenBeforeParents(remaining, tableOf, childFirst);\n ordered.push(...step.ordered);\n if (step.blocked.length === 0) {\n break;\n }\n const left = new Set(step.blocked.map(tableOf));\n const next = step.blocked.find(\n (drop) => !refusalOf(drop.tableName, keys, left)\n );\n if (!next) {\n throw cyclicDropRefusal(step.blocked.map(tableOf), keys);\n }\n ordered.push(next);\n remaining = step.blocked.filter((drop) => drop !== next);\n }\n\n const first = operations.findIndex(\n (operation) => operation.type === \"dropTable\"\n );\n const rest = operations.filter((operation) => operation.type !== \"dropTable\");\n return [...rest.slice(0, first), ...ordered, ...rest.slice(first)];\n}\n\n/**\n * The key that may refuse dropping `table` while the `existing` tables,\n * `table` among them, remain, if any.\n *\n * The implicit delete removes every row of `table`, and CASCADE extends it to\n * the rows of each remaining table that cascades from a deleted one. A\n * remaining key into a deleted table then decides: CASCADE deleted its rows\n * too and SET NULL clears them; RESTRICT refuses at once; NO ACTION and SET\n * DEFAULT are settled when the statement ends, by when a key held by `table`\n * has lost every row, while one held by another table may still point at\n * nothing. Measured on better-sqlite3 over random populated rows, for every\n * pair of actions on a two-table cycle in both orders and for each action on\n * a self-reference.\n */\nfunction refusalOf(\n table: string,\n keys: readonly ActiveKey[],\n existing: ReadonlySet<string>\n): ActiveKey | undefined {\n const deleted = new Set([table]);\n for (const name of deleted) {\n for (const key of keys) {\n if (\n key.to === name &&\n key.onDelete === \"cascade\" &&\n existing.has(key.from)\n ) {\n deleted.add(key.from);\n }\n }\n }\n return keys.find(\n (key) =>\n deleted.has(key.to) &&\n existing.has(key.from) &&\n key.onDelete !== \"cascade\" &&\n key.onDelete !== \"setNull\" &&\n (key.onDelete === \"restrict\" || key.from !== table)\n );\n}\n\nconst ACTION_SQL: Record<ReferentialAction, string> = {\n cascade: \"CASCADE\",\n setNull: \"SET NULL\",\n restrict: \"RESTRICT\",\n noAction: \"NO ACTION\",\n setDefault: \"SET DEFAULT\",\n};\n\n/**\n * Names every blocked table and a key that refuses its drop, by columns:\n * SQLite introspection cannot read a key's name back.\n */\nfunction cyclicDropRefusal(\n blocked: readonly string[],\n keys: readonly ActiveKey[]\n): MigrationError {\n const left = new Set(blocked);\n const reasons = blocked.flatMap((table) => {\n const key = refusalOf(table, keys, left);\n return key\n ? [\n `dropping \"${table}\" is refused by ${key.from}(${key.columns.join(\", \")}) -> ${key.to} ON DELETE ${ACTION_SQL[key.onDelete ?? \"noAction\"]}`,\n ]\n : [];\n });\n return new MigrationError(\n `Tables ${blocked.map((name) => `\"${name}\"`).join(\", \")} cannot be dropped in an order that satisfies their foreign keys: ${reasons.join(\"; \")}. This database enforces those keys while it drops a table and cannot drop a key without rebuilding its table, so the whole plan is refused before any statement runs. ` +\n \"Remove one of these relations, or change its delete action to SET NULL, in a separate change first; then drop the tables.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"cyclic-table-drop\" } }\n );\n}\n","import { createHash } from \"node:crypto\";\n/**\n * Shared migration helpers that do not own a V1 command.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationDriver } from \"./drivers\";\nimport { orderTableDrops } from \"./drop-order\";\nimport type { Dialect, DiffOperation, SchemaSnapshot } from \"./types\";\n\n/** PostgreSQL/MySQL derived identifiers keep their uniqueness under byte caps. */\nexport function derivedMigrationName(name: string): string {\n if (Buffer.byteLength(name) <= 63) return name;\n let prefix = \"\";\n for (const character of name) {\n if (Buffer.byteLength(prefix + character) > 54) break;\n prefix += character;\n }\n return `${prefix}_${createHash(\"sha256\").update(name).digest(\"hex\").slice(0, 8)}`;\n}\n\n/** Default generated-key spelling; dialects may supply their physical rule. */\nexport function defaultGeneratedPrimaryKeyName(\n tableName: string,\n name?: string\n): string {\n return name || `${tableName}_pkey`;\n}\n\n// DIALECT UTILITIES\n// =============================================================================\n\n/**\n * Validates and normalizes the database dialect for migrations.\n * Throws if the dialect is not supported.\n */\nexport function normalizeDialect(dialect: string): Dialect {\n if (dialect === \"postgresql\" || dialect === \"postgres\") {\n return \"postgresql\";\n }\n if (dialect === \"sqlite\") {\n return \"sqlite\";\n }\n if (dialect === \"mysql\") {\n return \"mysql\";\n }\n throw new MigrationError(\n `Unsupported dialect for migrations: \"${dialect}\". ` +\n \"Supported dialects: postgresql, sqlite, mysql.\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH,\n { meta: { dialect } }\n );\n}\n\n// QUERY EXECUTOR\n// =============================================================================\n\n/**\n * Type for executing SQL queries and returning rows.\n */\nexport type QueryExecutor = (\n sql: string,\n params?: unknown[]\n) => Promise<unknown[]>;\n\n/**\n * Creates a query executor from a driver.\n * Extracts rows from the QueryResult.\n */\nexport function createQueryExecutor(driver: AnyDriver): QueryExecutor {\n return async (sql: string, params?: unknown[]) => {\n const result = await driver._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n return result.rows;\n };\n}\n\n// =============================================================================\n// OPERATION UTILITIES\n// =============================================================================\n\n/**\n * Operation execution order priorities.\n * Lower numbers execute first.\n */\nconst OPERATION_PRIORITY: Record<DiffOperation[\"type\"], number> = {\n createEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n renameTable: 9,\n addColumn: 10,\n renameColumn: 11,\n alterColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n alterEnum: 1.5,\n dropEnum: 18,\n};\n\n/**\n * Slot for the index drops that have to run *after* the batch's index creates.\n * Between `createIndex` and `addForeignKey`, so a superseded index is gone\n * before a new constraint is bound to whatever is left.\n */\nconst SUPERSEDED_INDEX_DROP_PRIORITY =\n (OPERATION_PRIORITY.createIndex + OPERATION_PRIORITY.addForeignKey) / 2;\n\n/**\n * Picks out the `dropIndex` operations whose replacement has to exist first.\n *\n * MySQL binds a foreign key to whichever index covers its columns and refuses\n * to drop that index while it is the last one covering them (errno 1553). A\n * schema edit that supersedes such an index — widening it, or covering the same\n * columns with a unique constraint — plans the drop and its replacement in the\n * same batch, so the replacement has to be in place before the drop runs.\n *\n * Two arrangements keep a drop in its early slot instead:\n * - The batch creates an index of the *same name*, which the drop has to free\n * first. The name is matched on its own, not per table: PostgreSQL and SQLite\n * scope an index name to the schema/database, so a batch that frees a name on\n * one table and takes it on another collides too (Postgres 42P07). Matching\n * on the name alone can only keep a drop early, never defer one, so it cannot\n * reopen the 1553 case — there the created index has a different name.\n * - A table that also drops a column loses that column's indexes along with it,\n * so a drop deferred past the column drop would address an index already\n * gone. (A dropped *table* cannot collide: index diffs are only produced for\n * tables present in both snapshots.)\n */\nfunction supersededIndexDrops(operations: DiffOperation[]): Set<DiffOperation> {\n const createdIndexNames = new Set<string>();\n const tablesLosingColumns = new Set<string>();\n for (const op of operations) {\n if (op.type === \"createIndex\") {\n createdIndexNames.add(op.index.name);\n } else if (op.type === \"addUniqueConstraint\") {\n createdIndexNames.add(op.constraint.name);\n } else if (op.type === \"addPrimaryKey\" && op.primaryKey.name) {\n createdIndexNames.add(op.primaryKey.name);\n } else if (op.type === \"dropColumn\") {\n tablesLosingColumns.add(op.tableName);\n }\n }\n\n const superseded = new Set<DiffOperation>();\n for (const op of operations) {\n if (\n op.type === \"dropIndex\" &&\n !createdIndexNames.has(op.indexName) &&\n !tablesLosingColumns.has(op.tableName)\n ) {\n superseded.add(op);\n }\n }\n return superseded;\n}\n\n/**\n * Sorts operations for proper execution order:\n * 1. Create enums (before tables that use them)\n * 2. Drop foreign keys (before dropping tables/columns)\n * 3. Drop indexes, constraints, columns\n * 4. Drop tables\n * 5. Create tables\n * 6. Establish table and column renames before operations using the new names\n * 7. Add or alter columns and constraints\n * 8. Create indexes\n * 9. Drop the indexes those creates supersede (see `supersededIndexDrops`)\n * 10. Add foreign keys (after tables/columns exist)\n */\nexport function sortOperations(operations: DiffOperation[]): DiffOperation[] {\n const superseded = supersededIndexDrops(operations);\n const priorityOf = (op: DiffOperation) =>\n superseded.has(op)\n ? SUPERSEDED_INDEX_DROP_PRIORITY\n : OPERATION_PRIORITY[op.type];\n const baseline = operations\n .map((operation, index) => ({ operation, index }))\n .sort((a, b) => priorityOf(a.operation) - priorityOf(b.operation));\n const renames = baseline.filter(\n ({ operation }) =>\n operation.type === \"renameTable\" || operation.type === \"renameColumn\"\n );\n if (renames.length === 0) return baseline.map(({ operation }) => operation);\n const ordered: DiffOperation[] = [];\n const visited = new Set<number>();\n const active = new Set<number>();\n const visit = (entry: (typeof baseline)[number]): void => {\n if (visited.has(entry.index)) return;\n if (active.has(entry.index)) {\n throw new MigrationError(\n \"Migration operations contain a cyclic native rename dependency\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n active.add(entry.index);\n for (const prerequisite of renames) {\n if (prerequisite.index === entry.index) continue;\n const rename = prerequisite.operation;\n const operation = entry.operation;\n if (rename.type === \"renameTable\") {\n // A later producer can reuse an earlier table name. A column rename\n // before that name was consumed addresses the earlier identity.\n if (\n operation.type === \"renameColumn\" &&\n prerequisite.index > entry.index &&\n renames.some(\n (earlier) =>\n earlier.index > entry.index &&\n earlier.index < prerequisite.index &&\n earlier.operation.type === \"renameTable\" &&\n earlier.operation.from === operation.tableName\n )\n )\n continue;\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index && rename.to === operation.from\n : operationTargetsTable(operation, rename.to);\n if (needed) visit(prerequisite);\n } else if (rename.type === \"renameColumn\") {\n const needed =\n operation.type === \"renameTable\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.from\n : operation.type === \"renameColumn\"\n ? prerequisite.index < entry.index &&\n rename.tableName === operation.tableName &&\n rename.to === operation.from\n : operationTargetsColumn(operation, rename.tableName, rename.to);\n if (needed) visit(prerequisite);\n }\n }\n active.delete(entry.index);\n visited.add(entry.index);\n ordered.push(entry.operation);\n };\n for (const entry of baseline) visit(entry);\n return ordered;\n}\n\n/** A table operation that must address the post-rename identity. */\nfunction operationTargetsTable(\n operation: DiffOperation,\n tableName: string\n): boolean {\n if (operation.type === \"createTable\") {\n return operation.table.name === tableName;\n }\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) => column.tableName === tableName\n ) ?? false\n );\n }\n return \"tableName\" in operation && operation.tableName === tableName;\n}\n\nfunction operationTargetsColumn(\n operation: DiffOperation,\n tableName: string,\n columnName: string\n): boolean {\n if (operation.type === \"alterEnum\" || operation.type === \"dropEnum\") {\n return (\n operation.dependentColumns?.some(\n (column) =>\n column.tableName === tableName && column.columnName === columnName\n ) ?? false\n );\n }\n return (\n \"tableName\" in operation &&\n operation.tableName === tableName &&\n \"columnName\" in operation &&\n operation.columnName === columnName\n );\n}\n\n/**\n * Lifts *forward-reference* foreign keys out of `createTable` operations into\n * separate `addForeignKey` operations, so a table whose FK points at a table\n * created later in the same batch does not emit the constraint before its\n * referenced table exists.\n *\n * This is the DDL-ordering fix for `push()` / generated migrations: a schema\n * that declares a child model (the endpoint holding the FK) *before* its parent\n * would otherwise emit `ALTER TABLE child ADD ... FOREIGN KEY REFERENCES parent`\n * (Postgres) or an inline FK (MySQL) immediately after `CREATE TABLE child`,\n * before `CREATE TABLE parent` runs — Postgres `42P01`, MySQL analogous — and\n * the whole transactional push aborts with zero tables created.\n *\n * The transform is capability-gated and deliberately *surgical*:\n * - Drivers that cannot `ALTER TABLE ADD FOREIGN KEY` (SQLite/LibSQL) keep FKs\n * inline and are returned untouched — they resolve forward references lazily\n * and rewriting an FK into an `addForeignKey` op would trigger a table\n * recreation against an introspected-empty current schema.\n * - Only FKs that reference a table created *later* in this batch are lifted.\n * Backward references (referenced-first schemas, self-references, FKs to\n * pre-existing tables) already work and are left byte-identical, preserving\n * the DDL of schemas that were never broken.\n *\n * Lifted `addForeignKey` operations are appended after every other operation so\n * they run once all `CREATE TABLE`s have executed. Non-lifted operations retain\n * their exact input order.\n */\nexport function extractForwardReferenceForeignKeys(\n operations: DiffOperation[],\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n // Position of each table within the sequence of createTable operations.\n const createdTablePosition = new Map<string, number>();\n let position = 0;\n for (const op of operations) {\n if (op.type === \"createTable\") {\n createdTablePosition.set(op.table.name, position);\n position += 1;\n }\n }\n\n const result: DiffOperation[] = [];\n const liftedForeignKeys: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type !== \"createTable\") {\n result.push(op);\n continue;\n }\n\n const selfPosition = createdTablePosition.get(op.table.name);\n // Partition this table's FKs into those that must stay inline and those\n // that point forward to a table created later in the batch.\n const retained = op.table.foreignKeys.filter((fk) => {\n const targetPosition = createdTablePosition.get(fk.referencedTable);\n const isForwardReference =\n targetPosition !== undefined &&\n selfPosition !== undefined &&\n targetPosition > selfPosition;\n return !isForwardReference;\n });\n\n if (retained.length === op.table.foreignKeys.length) {\n // No forward references — leave the operation byte-identical.\n result.push(op);\n continue;\n }\n\n const forwardForeignKeys = op.table.foreignKeys.filter(\n (fk) => !retained.includes(fk)\n );\n\n result.push({\n ...op,\n table: { ...op.table, foreignKeys: retained },\n });\n for (const fk of forwardForeignKeys) {\n liftedForeignKeys.push({\n type: \"addForeignKey\",\n tableName: op.table.name,\n fk,\n });\n }\n }\n\n return [...result, ...liftedForeignKeys];\n}\n\n/**\n * Materializes the foreign-key drops a dropped-table graph needs, ONCE, for\n * every consumer: push, generated up SQL, and inverted generated down SQL.\n *\n * The differ omits a foreign-key drop when both endpoint tables disappear —\n * there is no surviving table to alter, so nothing produces the operation — and\n * §6.1 removes the `CASCADE` that used to paper over it. Without this stage a\n * `RESTRICT` drop of two mutually-referencing tables fails no matter which\n * order they are emitted in, and a cycle fails in every order.\n *\n * Every implicated key is included regardless of the table order the batch\n * happens to have, including keys whose owning AND referenced tables are both\n * being dropped, and including cycles. `sortOperations` then puts every\n * `dropForeignKey` (priority 2) ahead of every `dropTable` (priority 7).\n *\n * Drivers that cannot `ALTER TABLE ... DROP CONSTRAINT` keep their operations\n * byte-identical: SQLite and LibSQL hold foreign keys inline and rebuild tables\n * instead, so an explicit drop is not a statement they can emit.\n */\nexport function materializeDroppedTableForeignKeys(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return operations;\n }\n\n const droppedTables = new Set<string>();\n const plannedDrops = new Set<string>();\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n droppedTables.add(op.tableName);\n } else if (op.type === \"dropForeignKey\") {\n plannedDrops.add(`${op.tableName} ${op.fkName}`);\n }\n }\n if (droppedTables.size === 0) {\n return operations;\n }\n\n const materialized: DiffOperation[] = [];\n for (const table of current.tables) {\n for (const fk of table.foreignKeys) {\n const implicated =\n droppedTables.has(table.name) || droppedTables.has(fk.referencedTable);\n if (implicated && !plannedDrops.has(`${table.name} ${fk.name}`)) {\n materialized.push({\n type: \"dropForeignKey\",\n tableName: table.name,\n fkName: fk.name,\n });\n }\n }\n }\n\n return materialized.length === 0\n ? operations\n : [...materialized, ...operations];\n}\n\n/**\n * One compile-order owner for generated schema programs. Generate and push\n * both hand this result to the compiler, and nothing sorts it afterwards. Do\n * not lift, materialize or order drops at a second call site. Drops are\n * ordered last, once every foreign-key removal the program makes is known.\n */\nexport function prepareSchemaProgram(\n operations: DiffOperation[],\n current: SchemaSnapshot,\n migrationDriver: MigrationDriver\n): DiffOperation[] {\n return orderTableDrops(\n materializeDroppedTableForeignKeys(\n extractForwardReferenceForeignKeys(operations, migrationDriver),\n current,\n migrationDriver\n ),\n current\n );\n}\n\n// =============================================================================\n// MIGRATION FILE UTILITIES\n// =============================================================================\n\n/**\n * Generate a migration name based on the operations.\n */\nexport function generateMigrationName(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"empty\";\n }\n\n const primaryOp = operations[0];\n if (!primaryOp) {\n return \"migration\";\n }\n\n switch (primaryOp.type) {\n case \"createTable\":\n return operations.length === 1\n ? `create-${primaryOp.table.name}`\n : \"initial\";\n case \"dropTable\":\n return `drop-${primaryOp.tableName}`;\n case \"addColumn\":\n return `add-${primaryOp.column.name}-to-${primaryOp.tableName}`;\n case \"dropColumn\":\n return `drop-${primaryOp.columnName}-from-${primaryOp.tableName}`;\n case \"renameTable\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"renameColumn\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"createIndex\":\n return `add-index-${primaryOp.index.name}`;\n case \"dropIndex\":\n return `drop-index-${primaryOp.indexName}`;\n case \"addForeignKey\":\n return `add-fk-${primaryOp.fk.name}`;\n case \"dropForeignKey\":\n return `drop-fk-${primaryOp.fkName}`;\n case \"createEnum\":\n return `create-enum-${primaryOp.enumDef.name}`;\n case \"dropEnum\":\n return `drop-enum-${primaryOp.enumName}`;\n case \"alterEnum\":\n return `alter-enum-${primaryOp.enumName}`;\n default:\n return \"migration\";\n }\n}\n","/**\n * Migration Estate Target\n *\n * ONE resolver derives the durable estate target from a concrete execution\n * driver, and ONE pair of readers reaches the two runtime facts installed on\n * the adapter and the driver (`adapter.namespace`,\n * `driver.migrationNamespaceAttestation`). Every migration verb, the registry\n * binding, and the live-capability admission owner reach those facts through\n * here, so no command re-decides dialect, namespace or attestation for itself.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { controlTableNames, DEFAULT_CONTROL_BASE } from \"./control\";\nimport { snapshotExactArray } from \"./input-boundary\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport { normalizeDialect } from \"./utils\";\n\nexport const MANAGED_TABLES = Symbol(\"migration managed tables\");\n\n/** Exact physical membership, authenticated as part of the estate target. */\nexport function normalizeManagedTables(\n value: unknown\n): readonly string[] | undefined {\n if (value === undefined) return;\n const entries = snapshotExactArray(value, \"managed tables\", (message) => {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n });\n const names: string[] = [];\n for (const name of entries) {\n if (typeof name !== \"string\" || name.length === 0 || name.includes(\"\\0\"))\n throw new MigrationError(\n \"Managed tables must contain non-empty physical names\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (names.includes(name))\n throw new MigrationError(\n `Managed table \"${name}\" is repeated`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n names.push(name);\n }\n return Object.freeze(names.sort());\n}\n\nexport function selectManagedSnapshot(\n snapshot: SchemaSnapshot,\n target: MigrationTarget,\n desired = false\n): SchemaSnapshot {\n const names = target.tables;\n if (names === undefined) return snapshot;\n const control = controlTableNames(DEFAULT_CONTROL_BASE);\n // Control authenticity reads the same inventory, independently of user scope.\n const selected = (name: string) =>\n names.includes(name) || name === control.state || name === control.log;\n if (desired && snapshot.tables.some((table) => !names.includes(table.name)))\n throw new MigrationError(\n \"The schema declares a physical table outside the authenticated managed-table list\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n for (const table of snapshot.tables)\n for (const fk of table.foreignKeys) {\n if (selected(table.name) !== selected(fk.referencedTable))\n throw new MigrationError(\n `Foreign key \"${table.name}.${fk.name}\" crosses the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const tables = snapshot.tables.filter((table) => selected(table.name));\n const used = new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const enums = snapshot.enums?.filter((item) => used.has(item.name));\n for (const table of snapshot.tables.filter(\n (table) => !selected(table.name)\n )) {\n if (\n target.dialect === \"postgresql\" &&\n table.columns.some((column) =>\n enums?.some(\n (item) =>\n (column.type.endsWith(\"[]\")\n ? column.type.slice(0, -2)\n : column.type) === item.name\n )\n )\n )\n throw new MigrationError(\n `Table \"${table.name}\" shares a managed enum across the managed-table boundary`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return { ...snapshot, tables, ...(enums === undefined ? {} : { enums }) };\n}\n\n/**\n * The live namespace the adapter is bound to, or undefined when the adapter\n * exposes none.\n *\n * Module-private on purpose: `resolveMigrationEstate` is the ONE reader of this\n * fact in the whole migration layer, so no second caller can take a second look\n * at a value a custom adapter may answer differently each time.\n *\n * The property is read reflectively for one reason: it is an OPTIONAL runtime\n * fact whose declaration lives on the adapter contract, and reading it as\n * untyped data keeps the migration layer from claiming any adapter it is handed\n * — including a caller-supplied custom adapter — has already declared it. A\n * present-but-non-string value is the same as absent: unproven.\n *\n * So is the EMPTY STRING. §1.3 settles it for the shipped path — an empty\n * candidate \"is not passed to identifier validation\" and preserves unbound mode\n * — and `normalizeNamespace` (`src/schema/identifier.ts`) rejects `\"\"` against\n * the identifier grammar, so no stock constructor can produce one. A custom\n * adapter can, and this reader is the seam that admits it: an empty name proves\n * no schema and no database, and reading it as proven would qualify every live\n * statement with an EMPTY quoted segment (`\"\".\"users\"`).\n */\nfunction readAdapterNamespace(driver: AnyDriver): string | undefined {\n const value: unknown = Reflect.get(driver.adapter, \"namespace\");\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * The driver's immutable non-redirecting migration-namespace attestation, or\n * undefined when the driver makes no such claim.\n *\n * Only the exact string `\"non-redirecting\"` is an attestation. There is no\n * provider-name fallback and no inference from class, URL, handshake or\n * server version: a driver that does not carry this exact value is unproven,\n * which is what keeps PlanetScale (and any MySQL2 connection reaching Vitess\n * through the ordinary MySQL protocol) out of effectful migration work.\n */\nexport function readNamespaceAttestation(\n driver: AnyDriver\n): \"non-redirecting\" | undefined {\n const value: unknown = Reflect.get(driver, \"migrationNamespaceAttestation\");\n return value === \"non-redirecting\" ? value : undefined;\n}\n\n/**\n * Reads one catalog statement with its bound values.\n *\n * The same shape the dialect base class's `proveNamespaceExists` takes, spelled\n * here so the migration layer's shared owners can name a catalog read without\n * importing a dialect module for the type.\n */\nexport type CatalogRead = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * A dialect whose CONFIGURED namespace and the server's own spelling of it can\n * differ, and which therefore answers one command-local spelling (§5.2).\n *\n * MySQL is the only such dialect: `lower_case_table_names` can make a\n * differently cased configured value name the same physical database, so\n * catalog resolution accepts a single case-folded candidate — and every later\n * statement of that command has to speak the spelling the SERVER answered with,\n * not the one the configuration carried. `information_schema` rows carry the\n * server's spelling, and on a case-sensitive server so does `USE`.\n *\n * PostgreSQL has no such projection (its `pg_namespace` proof is byte-exact)\n * and SQLite has no namespace at all, so both answer nothing here and their\n * commands keep the exact bound driver they started with.\n *\n * The capability is STRUCTURAL, exactly like the pinned-session hook: a dialect\n * declares it by implementing it. This interface is what the implementation is\n * checked against; {@link readsCommandNamespace} is what a shared owner asks.\n */\nexport interface CommandNamespaceResolver {\n resolveCommandNamespace(read: CatalogRead): Promise<string>;\n}\n\n/**\n * Whether this migration driver resolves a command-local namespace spelling.\n *\n * Read as an optional runtime capability rather than declared on the dialect\n * base class, for the same reason `adapter.namespace` is read reflectively\n * above: it is a fact only one dialect has, and a base-class declaration would\n * make every dialect — including a caller-supplied one — answer for it.\n */\nexport function readsCommandNamespace<T extends object>(\n migrationDriver: T\n): migrationDriver is T & CommandNamespaceResolver {\n return (\n typeof Reflect.get(migrationDriver, \"resolveCommandNamespace\") ===\n \"function\"\n );\n}\n\n/**\n * The two estate facts a bound migration driver carries, derived together.\n *\n * `target` is the DURABLE estate generated artifacts claim;\n * `namespace` is the LIVE execution destination. They coincide for PostgreSQL\n * and deliberately differ for MySQL, whose artifacts are database-relative, so\n * both have to be published — but both come from ONE read of the adapter.\n */\nexport interface MigrationEstate {\n readonly target: MigrationTarget;\n readonly namespace: string | undefined;\n}\n\n/**\n * Derives the one frozen estate target and the one live namespace for a\n * concrete execution driver, from a SINGLE read of `adapter.namespace`.\n *\n * The single read is load-bearing, not tidiness. A custom adapter may expose\n * `namespace` as an accessor; two reads could answer two different strings, and\n * the durable target would then name one estate while live DDL rendered\n * another. Reading once and publishing both facts from that one value makes the\n * disagreement structurally impossible (plan §14).\n *\n * The dialect goes through `normalizeDialect` here and nowhere else in the\n * migration layer's target decisions, so a driver cannot resolve to two targets\n * by being read raw on one path and normalized on another.\n *\n * A PostgreSQL driver whose adapter exposes no namespace is UNPROVEN and\n * refused. It must not silently acquire the `\"public\"` default: generated\n * PostgreSQL SQL contains the schema, so a defaulted target would write a\n * durable claim nothing established.\n */\nexport function resolveMigrationEstate(driver: AnyDriver): MigrationEstate {\n const dialect = normalizeDialect(driver.dialect);\n const namespace = readAdapterNamespace(driver);\n\n if (dialect === \"postgresql\") {\n if (namespace === undefined) {\n throw new MigrationError(\n `The PostgreSQL driver \"${driver.driverName}\" exposes no adapter namespace, so its migration estate has no proven schema. ` +\n 'Generated PostgreSQL migration SQL is schema-qualified, so the estate cannot fall back to \"public\": construct the driver with an explicit `namespace`, or supply an adapter that declares one.',\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { driver: driver.driverName, dialect } }\n );\n }\n return { target: Object.freeze({ dialect, namespace }), namespace };\n }\n\n // MySQL and SQLite estates are namespace-free BY DESIGN. MySQL artifacts are\n // database-relative so one history deploys to several database names; SQLite\n // has no namespace concept at all. The live MySQL destination rides beside\n // the target on the bound view, never inside it.\n return { target: Object.freeze({ dialect }), namespace };\n}\n\n/**\n * Human-readable estate description for refusal messages and safe metadata.\n *\n * The live namespace is a SECOND argument because the two facts are separate\n * for MySQL: its durable target is namespace-free by design (§3.1), so the\n * database a command actually touches rides beside it on the bound view. A\n * caller that has it passes it; a caller describing a stored estate target —\n * which carries no database name and must not appear to — does not.\n *\n * Naming it matters wherever the description is what a person consents to: the\n * CLI's `--force-reset` confirmation used to read \"This will DROP ALL TABLES in\n * mysql\", which identifies nothing on the one dialect whose estate target is\n * namespace-free (DECISIONS N6: the confirmation \"must name the target\n * namespace\").\n */\nexport function formatMigrationTarget(\n target: MigrationTarget,\n namespace?: string\n): string {\n if (target.dialect === \"postgresql\") {\n return `${target.dialect} schema \"${target.namespace}\"`;\n }\n return namespace === undefined\n ? target.dialect\n : `${target.dialect} database \"${namespace}\"`;\n}\n\n/**\n * A stored estate is bound to one durable target. PostgreSQL artifacts are\n * schema-qualified, so `alpha` cannot generate or apply as `beta`. MySQL and\n * SQLite compare dialect only.\n */\nexport function assertEstateTargetMatches(\n stored: MigrationTarget,\n live: MigrationTarget\n): void {\n if (JSON.stringify(stored.tables) !== JSON.stringify(live.tables)) {\n throw new MigrationError(\n \"Estate managed-table scope does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (stored.dialect !== live.dialect) {\n throw new MigrationError(\n \"Estate target dialect does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n if (\n stored.dialect === \"postgresql\" &&\n live.dialect === \"postgresql\" &&\n stored.namespace !== live.namespace\n ) {\n throw new MigrationError(\n \"Estate target namespace does not match this client\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH\n );\n }\n}\n","/**\n * The ONE pinned migration session.\n *\n * PostgreSQL advisory locks and MySQL named locks are SESSION-scoped. The\n * previous owner acquired through one pooled connection, ran the protected work\n * through others, and released through another: that protects nothing, and a\n * release issued on a connection that never held the lock strands it on the one\n * that did. §3.5's requirement is one physical producer across every decision\n * and commit boundary, so this module reserves that producer, proves the lock,\n * hands the callback that exact producer, and proves the unlock — condemning\n * the producer whenever either proof fails.\n *\n * The lock statement and the namespace proof are the only provider operations\n * allowed before the authoritative under-lock marker and ledger read, and both\n * are non-durable: a target mismatch after acquisition unlocks and leaves zero\n * tracking, DDL, artifact or snapshot effects behind.\n *\n * Two facts about that producer live here with it, because both are answers no\n * command may source twice: the driver a command RENDERS from\n * ({@link resolveCommandDriver}, which read-only commands reach without a\n * lock), and the commit boundary a program reached when the dialect commits\n * each statement as it runs ({@link runSequentialProgram}).\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport {\n leasePinnedCommand,\n type PinnedSessionControl,\n} from \"../drivers/shared/pinned-session\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport type { TransactionOptionSupport } from \"../drivers/shared/transaction-options\";\nimport { runTransactionLifecycle } from \"../drivers/shared/transactions\";\nimport type { QueryExecutionContext } from \"../drivers/types\";\nimport {\n FeatureNotSupportedError,\n MigrationError,\n VibORMErrorCode,\n} from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { planInterruptedMySQLDecimalRecovery } from \"./drivers/mysql/decimal-recovery\";\nimport { type CatalogRead, readsCommandNamespace } from \"./target\";\nimport { createQueryExecutor } from \"./utils\";\n\n/**\n * Lock ID for PostgreSQL advisory locks.\n * Hash of \"viborm_migrations\" to avoid collisions.\n *\n * PostgreSQL keeps its DATABASE-wide key: an advisory lock is already scoped to\n * the database the session connected to, and independent schema estates in one\n * database deliberately serialize with each other — they share a catalog.\n * MySQL derives a database-specific name instead, because its named locks are\n * server-wide (`drivers/mysql/pinned-session.ts`).\n */\nconst MIGRATION_LOCK_ID = 0x76_69_62_6f_72_6d; // \"viborm\" in hex, truncated\nconst MYSQL_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)/;\n\nconst MYSQL_DECIMAL_RECOVERY = Symbol(\"mysqlDecimalRecovery\");\n\ninterface MySQLDecimalRecoveryScope {\n take(producer: AnyDriver): Promise<readonly string[]>;\n}\n\nfunction isMySQLDecimalRecoveryScope(\n value: unknown\n): value is MySQLDecimalRecoveryScope {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"take\") === \"function\"\n );\n}\n\n/**\n * Whether this driver can pin a session, answered without reserving one.\n *\n * The provider's `pinnedSession()` hook is the capability: its PRESENCE is the\n * whole answer. Migration admission asks this BEFORE any provider work, so an\n * effectful command on a transport with no interactive session refuses before\n * it connects.\n *\n * This and {@link withPinnedSession} live here, beside their only callers,\n * rather than on the `Driver` class, so an application bundle that never\n * migrates does not carry them. They reach the driver's protected members by\n * element access, exactly as `TransactionBoundDriver` reaches its base's.\n */\nexport function canPinSession(driver: AnyDriver): boolean {\n return driver[\"pinnedSession\"] !== undefined;\n}\n\n/**\n * Runs `body` against ONE reserved producer.\n *\n * The view handed to the body is this exact driver with its client pinned to\n * the reservation, so every statement — the lock, the authoritative reads,\n * the DDL, the tracking writes, and the unlock — runs on the same physical\n * session, and a transaction opened inside the body runs on it too instead of\n * acquiring a second pooled connection.\n *\n * The producer is discarded rather than released when the body throws or\n * condemns it: a session whose lock state is unknown must not go back into a\n * pool.\n *\n * On a driver whose one connection IS the session, the whole call is one job\n * of the queue that already owns that connection — see the lease below.\n */\nexport async function withPinnedSession<D extends AnyDriver, T>(\n driver: D,\n body: (pinned: D, control: PinnedSessionControl) => Promise<T>\n): Promise<T> {\n const reserve = driver[\"pinnedSession\"];\n if (reserve === undefined) {\n // Two reachable shapes, one refusal. The shipped migration paths ask\n // `canPinSession()` at their admission boundary and refuse\n // `DRIVER_NOT_SUPPORTED` before any provider work, so this arm covers\n // what admission cannot see: a caller reaching the primitive directly\n // with a custom driver that implements no hook, and a caller reaching it\n // on a view that IS an already-reserved session (`createPinnedSessionView`\n // withdraws the hook).\n throw new FeatureNotSupportedError(\n driver.driverName,\n \"pinnedSession\",\n \"No session can be reserved through this driver: either the transport has no interactive session at all, or this view is itself one reserved session and reserving again would take a SECOND connection. A migration lock is session-scoped, so either way it could be released by a different connection — or never released at all.\"\n );\n }\n\n const runSession = async (): Promise<T> => {\n const reservation = await reserve.call(driver);\n let discarded = false;\n const control: PinnedSessionControl = {\n discard: () => {\n discarded = true;\n },\n };\n\n let value: T;\n try {\n value = await body(\n createPinnedSessionView(driver, reservation.session),\n control\n );\n } catch (bodyFailure) {\n // The body's failure is what the caller asked for and what the command\n // has to report. Awaiting the release in a `finally` made a release\n // rejection REPLACE it — the caller of a reset that dropped half an\n // estate on a dying socket was told only that the producer would not go\n // back. The release still runs, and still condemns the producer; its\n // own failure is recorded beside the body's (§3.5).\n discarded = true;\n try {\n await reservation.release(true);\n } catch (releaseFailure) {\n throw withSuppressedFailure(bodyFailure, releaseFailure);\n }\n throw bodyFailure;\n }\n // Nothing else failed, so a release failure IS the failure.\n await reservation.release(discarded);\n return value;\n };\n\n // A provider that reserves a DEDICATED connection — `pg`, postgres.js, Bun\n // SQL, MySQL2 — hands back a producer that is already physically apart from\n // everything else its pool is serving, and there is nothing here to lease:\n // two migration commands on a pool are arbitrated by the real session lock,\n // and serializing them on this driver would be a regression.\n //\n // A single-connection driver reserves the connection every other caller\n // shares (plan §3.5: \"PGlite — its single client UNDER THE EXISTING DRIVER\n // QUEUE\"), so the whole session — the reservation, the acquisition, the\n // decisions, the DDL, the unlock and the release — is ONE job of that queue.\n // Leasing anything narrower lets a second command in between two of this\n // one's statements, and a PostgreSQL session advisory lock is REENTRANT: on\n // one session the second command re-acquires the lock the first is holding\n // instead of waiting for it.\n if (!driver[\"serializeTransactions\"]) {\n return runSession();\n }\n // Reaching for the originating driver while its one connection is\n // transaction-bound is the refusal this driver already owns for every other\n // operation; here it is what stands between that caller and a wait on its\n // own holder. It is answered BEFORE the lease, not inside it: a driver that\n // waited for a lease another driver holds — on a client whose provider\n // serializes a transaction against every other statement — would wait for a\n // command that cannot finish until this transaction does.\n driver[\"assertBaseOperationAllowedDuringTransaction\"](\n driver[\"resolveExecutionContext\"](undefined, \"pinnedSession\")\n );\n const queue = driver[\"connectionQueue\"];\n const identify = driver[\"physicalPinnedSession\"];\n if (identify === undefined) {\n return queue.enqueue(runSession);\n }\n // The queue lease stays: it is what keeps this driver's own statements out\n // of the session. The physical lease is what keeps ANOTHER driver's command\n // out of it — and what refuses one outright when that session's\n // advisory-lock state was condemned, through this driver or any other.\n const session = await identify.call(driver);\n return leasePinnedCommand(driver.driverName, session, () =>\n queue.enqueue(runSession)\n );\n}\n\n/**\n * This driver, viewed with its client pinned to one reserved session.\n *\n * Defined rather than constructed: the view IS the concrete driver for every\n * other purpose — same adapter, same result parser, same capabilities — and\n * only the producer, the queue answer, the transaction owner and the\n * reservation hook differ. The facts it restates are `readonly`, hence\n * `defineProperties`. The transport assertion is forwarded EXACTLY: a pinned\n * session never derives, upgrades, or drops it, exactly as a\n * transaction-bound view does not.\n */\nfunction createPinnedSessionView<D extends AnyDriver>(\n driver: D,\n session: unknown\n): D {\n const view: D = Object.create(driver);\n const support = driver[\"transactionOptionSupport\"]();\n Object.defineProperties(view, {\n client: { value: session, writable: true },\n // `getClient()` returns a present client without consulting `initPromise`,\n // but a pinned view must never be able to start a second connection.\n initPromise: { value: null, writable: true },\n // The lease holds this driver's connection queue for the WHOLE session,\n // so a statement issued THROUGH this view must not wait on that queue: it\n // would be waiting for its own holder. The view is not opting out of\n // serialization — it IS the serialized job, and exclusivity for the whole\n // session is stronger than exclusivity per statement. On a driver that\n // took a dedicated connection there was no queueing here to begin with.\n serializeTransactions: { value: false },\n // §3.5's \"one physical producer\" made structural: the view IS the\n // reservation, so it has no reservation to give. Without this it\n // inherited the hook and answered `canPinSession() === true`, and a\n // nested `withLockedMigrationProducer` would have taken a SECOND\n // connection — one that then waits forever on PostgreSQL for the advisory\n // lock the first one holds, or times out on MySQL — instead of refusing.\n pinnedSession: { value: undefined },\n // The provider's own `transaction()` acquires a connection, which is what\n // pinning exists to prevent. A descriptor is how a `protected abstract`\n // member is replaced per-instance; it is also where the transaction\n // handle widens to the session, which is the honest shape here.\n transaction: { value: runPinnedTransaction },\n // A driver whose `maxWait` bounds its connection-queue wait (\"queue\")\n // has nothing left to bound on this view: the lease already holds the\n // queue for the whole session, so accepting the option here would\n // accept a bound it cannot apply. Dedicated-connection drivers keep\n // their own answer.\n transactionOptionSupport: {\n value: (): TransactionOptionSupport =>\n support.maxWait === \"queue\"\n ? {\n ...support,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"the pinned session holds the connection queue's lease for its whole duration, so there is no queue wait to bound\",\n }\n : support,\n },\n migrationNamespaceAttestation: {\n value: driver.migrationNamespaceAttestation,\n },\n });\n return view;\n}\n\n/**\n * One transaction on the already-reserved session, installed as the pinned\n * view's `transaction` member (so `this` is that view).\n *\n * Every provider's own `transaction()` acquires a connection — that is the\n * behaviour a pinned session exists to prevent — and most of them refuse\n * outright when handed a connection instead of a pool. `BEGIN`/`COMMIT`/\n * `ROLLBACK` on the reserved producer is the one form that means the same\n * thing on every transport admitted to pinning, and it keeps the lock and the\n * transaction on one session.\n */\nfunction runPinnedTransaction<T>(\n this: AnyDriver,\n session: unknown,\n fn: (tx: unknown) => Promise<T>,\n context?: QueryExecutionContext\n): Promise<T> {\n const statement = async (sql: string) => {\n await this[\"executeRaw\"](session, sql, undefined, context);\n };\n return runTransactionLifecycle({\n begin: () => statement(\"BEGIN\"),\n // The session IS the transaction here: there is no second handle to hand\n // out, and a nested `$transaction` on it runs as a SAVEPOINT.\n callback: () => fn(session),\n commit: () => statement(\"COMMIT\"),\n rollback: () => statement(\"ROLLBACK\"),\n });\n}\n\n/**\n * Runs `body` on ONE reserved producer holding this estate's migration lock.\n *\n * The body receives that producer and the migration driver THIS COMMAND must\n * render from: the same bound driver on every dialect but MySQL, and on MySQL\n * one carrying the spelling of the database the server itself answered with\n * (§5.2). Handing it over is what keeps the resolved spelling command-local —\n * it disappears with the session that resolved it, and nothing stores it.\n *\n * SQLite and LibSQL reserve nothing and take no lock: they own a single\n * connection with its own queue already, and §3.5 keeps that ownership rather\n * than making the new seam a regression for them. The callback then receives\n * the caller's own driver, which is exactly what it received before.\n *\n * This is the primitive both entry points share — estate commands through\n * {@link withLockedMigrationProducer}, and `push()`, which owns no migration\n * storage.\n */\nexport function withLockedMigrationProducer<T>(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (pinned: AnyDriver, command: BoundMigrationDriver) => Promise<T>\n): Promise<T> {\n if (migrationDriver.target.dialect === \"sqlite\") {\n return body(driver, migrationDriver);\n }\n\n return withPinnedSession(driver, async (pinned, control) => {\n // Acquisition stays OUTSIDE the release scope: a lock that was never proven\n // is not this session's to release, and issuing one anyway would fail its\n // own release proof and report that instead of the acquisition failure.\n // Everything after it is inside, because everything after it happens with\n // the lock HELD — §3.5's \"unlocks through the same producer in `finally`\"\n // covers the post-acquisition proof and target selection too.\n await acquireLock(pinned, migrationDriver);\n\n let result: T;\n try {\n const command = await validateAndSelectMigrationTarget(\n pinned,\n migrationDriver\n );\n result = await body(pinned, scopeMySQLDecimalRecovery(command));\n } catch (error) {\n await releaseAfterFailure(pinned, migrationDriver, control, error);\n throw error;\n }\n await releaseLock(pinned, migrationDriver, control);\n return result;\n });\n}\n\n/**\n * Selects the live migration target on a pinned producer, if this dialect has\n * one to select.\n *\n * The ONE consumer of the dialect's target-selection statement. It runs when\n * the lock is taken and again immediately before every relative artifact —\n * never only once for the session, because a manual artifact is allowed to\n * issue its own `USE` and the next artifact must still land on the configured\n * target (§10).\n */\nexport async function selectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n const statement = migrationDriver.generateSelectTarget();\n if (statement === null) {\n return;\n }\n await pinned._executeRaw(statement);\n}\n\n/**\n * §5.3's step 2: VALIDATED target selection, once per session.\n *\n * Selecting a database the server does not have is a raw provider failure, and\n * §3.3 requires a configured-but-absent namespace to fail on its own read-only\n * catalog proof instead — before session state changes and before any DDL. The\n * proof therefore runs on this exact producer, immediately after the lock and\n * before the first selection; every later reassertion re-selects a target this\n * session has already validated.\n *\n * It runs on every dialect, not only the one with a target to select. A\n * PostgreSQL command's proof used to be deferred to whichever of its two\n * tracking owners ran first, which meant each of them had to ask again — and\n * meant the fact was re-established once per applied-state read instead of once\n * per command. Proving it HERE is what lets everything below this line render\n * from a driver that has already been proven.\n */\nasync function validateAndSelectMigrationTarget(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const command = await resolveCommandDriver(pinned, migrationDriver);\n await selectMigrationTarget(pinned, command);\n await proveExactValueSessionMode(pinned, command);\n return command;\n}\n\n/**\n * MySQL only: PROVES this session fails on an out-of-range value instead of\n * truncating it (plan 3.3: \"Strict exact-value behavior is required; a mode\n * that converts overflow or truncation to warnings is refused for effectful\n * decimal operations\").\n *\n * The requirement is not decorative on a fixed-decimal estate. Outside strict\n * mode MySQL answers an overflowing `DECIMAL` assignment with a WARNING and\n * writes the clamped value: measured on 8.4, `UPDATE t SET amount = amount *\n * 100000` on a `DECIMAL(6,2)` column holding `10.00` stores `9999.99` and\n * returns success. Migration work may execute provider-authored DDL and manual\n * artifacts outside the ORM adapter's guarded decimal assignments, so its one\n * pinned producer must prove that an out-of-range exact value is an error.\n * Ordinary ORM increment, decrement, multiply, and divide carry their own\n * same-statement non-strict refusal; this proof owns the migration boundary.\n *\n * ONE proof, HERE: once per pinned migration session, on the producer that runs\n * the DDL, before any statement it protects. Not per operation — a hot-path\n * check would ask the same server the same question on every write, and the\n * session it would be asking about is the one this owner already reserved.\n * PostgreSQL and SQLite have no equivalent mode to prove: neither has a setting\n * that turns an out-of-range numeric into a truncation.\n */\nasync function proveExactValueSessionMode(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n if (migrationDriver.target.dialect !== \"mysql\") {\n return;\n }\n const rows = await createQueryExecutor(pinned)(\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: describeEstate(migrationDriver),\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: describeEstate(migrationDriver),\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\n/**\n * The ONE owner of the migration driver a command renders from, after its\n * namespace proof.\n *\n * A dialect that resolves a command-local spelling gets a view carrying it;\n * every other dialect proves and keeps the driver it was given. The view is\n * built the way every other execution view in this layer is — a frozen\n * `Object.create` over the bound driver, restating one readonly fact — so the\n * resolved name is not a second stored namespace: it lives exactly as long as\n * the command that resolved it (§5.2).\n *\n * The proof ANSWERS on the one dialect where the answer can differ from the\n * question: `resolveCommandNamespace` returns the server's own spelling of the\n * configured database. Throwing that spelling away is what made a case-folded\n * MySQL match pass its proof and then die on a raw `Unknown database` from the\n * very `USE` the proof had just admitted — while the reset inventory read a\n * database the server does not have.\n *\n * READ-ONLY commands take no lock — `status()`, `log()` and a dry `push()`\n * are point-in-time reports, not concurrency-stable decisions — and they reach\n * this same owner on their own producer. That is deliberate: the spelling is a\n * fact about the SERVER, not about the lock, so a command that proves it and\n * then renders the configured one is wrong whether or not it locked. There is\n * no second namespace source anywhere; every command's catalog reads and every\n * statement it renders come from the view returned here.\n */\nexport async function resolveCommandDriver(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<BoundMigrationDriver> {\n const read: CatalogRead = (sql, params) => producer._executeRaw(sql, params);\n if (!readsCommandNamespace(migrationDriver)) {\n await migrationDriver.proveNamespaceExists(read);\n return migrationDriver;\n }\n\n const spelling = await migrationDriver.resolveCommandNamespace(read);\n const command: BoundMigrationDriver = Object.create(migrationDriver);\n Object.defineProperty(command, \"namespace\", {\n value: spelling,\n enumerable: true,\n });\n Object.freeze(command);\n return command;\n}\n\n/**\n * Runs a MySQL sequential program on `producer` and reports the boundary it\n * reached (§6.2, §6.3).\n *\n * MySQL commits DDL as each statement runs. Two things follow, and this is the\n * ONE owner of both. There is no transaction — the caller has already branched\n * away from its transaction owner, because `BEGIN` → `CREATE TABLE` (which\n * commits, and the `BEGIN` with it) → a tracking write now in autocommit →\n * `COMMIT` with nothing left to commit is the APPEARANCE of atomicity. And a\n * failure part-way through cannot be undone, so it is reported as the partial\n * commit it is.\n *\n * The boundary is recorded by the producer the body runs on, not by the body:\n * apply's artifact and its tracking insert, push's DDL, force-reset's clear and\n * rebuild, down's group, resolve's completion, and reset's replay are six\n * different programs. Each would otherwise have to carry its own bookkeeping\n * and its own error. The view is built the way every other execution view in\n * this layer is — an `Object.create` over the producer restating one member —\n * so the body runs on the SAME physical session, the same reserved client, and\n * the same attestation it was handed.\n *\n * The scope is the whole program the command commits to, deliberately: a report\n * covering only the clear would tell a `reset()` nothing about the replay that\n * followed it.\n */\nexport function mayWrapTransaction(\n producer: Pick<AnyDriver, \"supportsTransactions\">,\n dialect: string,\n transactional: boolean\n): boolean {\n return transactional && dialect !== \"mysql\" && producer.supportsTransactions;\n}\n\nexport async function runSequentialProgram<T>(\n producer: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n body: (recording: AnyDriver) => Promise<T>\n): Promise<T> {\n let recoveryStatements: readonly string[] = [];\n if (migrationDriver.target.dialect === \"mysql\") {\n const recovery: unknown = Reflect.get(\n migrationDriver,\n MYSQL_DECIMAL_RECOVERY\n );\n if (!isMySQLDecimalRecoveryScope(recovery)) {\n throw 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 recoveryStatements = await recovery.take(producer);\n }\n\n /**\n * The last statement that RAN TO COMPLETION.\n *\n * Where nothing rolls back, \"completed\" IS \"committed\", and it is the only\n * honest thing an error can say about a database it did not restore.\n */\n let committed: string | undefined;\n const recording: AnyDriver = Object.create(producer);\n Object.defineProperty(recording, \"_executeRaw\", {\n value: async (sql: string, params?: unknown[]) => {\n const result = await producer._executeRaw(sql, params);\n committed = sql;\n return result;\n },\n });\n\n try {\n for (const statement of recoveryStatements) {\n await recording._executeRaw(statement);\n }\n return await body(recording);\n } catch (cause) {\n throw partialProgramFailure(cause, committed);\n }\n}\n\n/**\n * Gives one locked command one recoverable MySQL decimal-cleanup decision.\n *\n * The decision is lazy because apply must read and validate its authoritative\n * journal before recovery may touch the estate. The first sequential program\n * takes it after that preflight; later artifact/program segments in the same\n * command get an empty plan. Proof failures leave the decision untaken and\n * retain their exact migration-state diagnostics.\n */\nfunction scopeMySQLDecimalRecovery(\n migrationDriver: BoundMigrationDriver\n): BoundMigrationDriver {\n if (migrationDriver.target.dialect !== \"mysql\") {\n return migrationDriver;\n }\n if (migrationDriver.namespace === undefined) {\n throw new MigrationError(\n \"This MySQL migration command has no resolved database for interrupted decimal-conversion recovery.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: \"mysql\", type: \"unbound-database\" } }\n );\n }\n const namespace = migrationDriver.namespace;\n\n let taken = false;\n let planned: Promise<readonly string[]> | undefined;\n const scope: MySQLDecimalRecoveryScope = {\n async take(producer) {\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) => migrationDriver.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 const command: BoundMigrationDriver = Object.create(migrationDriver);\n Object.defineProperty(command, MYSQL_DECIMAL_RECOVERY, { value: scope });\n Object.freeze(command);\n return command;\n}\n\n/**\n * The honest report for a program that cannot be undone (§6.2, §6.3).\n *\n * It states the boundary and refuses to characterize anything past it: the\n * statement that FAILED may have taken effect before it errored, so the last\n * statement known to have completed is the strongest true claim available.\n * Nothing here says or implies \"rolled back\" — the whole reason this error\n * exists is that no rollback happened — and nothing here claims the database\n * was CHANGED either, because a program can fail on the catalog read it opens\n * with.\n *\n * The provider's own failure survives underneath as the cause rather than being\n * replaced by this report.\n */\nfunction partialProgramFailure(\n cause: unknown,\n committed: string | undefined\n): MigrationError {\n const boundary =\n committed ?? \"(none — the failure came before any statement completed)\";\n return new MigrationError(\n \"This migration program failed partway through. MySQL commits DDL as each statement runs, so NOTHING was rolled back: every statement that completed stands, and VibORM makes no claim about whether the statement that failed took effect. \" +\n `The last statement that completed was: ${boundary}. ` +\n \"Estate artifacts and the control plane were not rewritten as a successful apply — fix the cause and re-run.\",\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n { cause: cause instanceof Error ? cause : undefined }\n );\n}\n\n/**\n * Acquires the lock and PROVES it.\n *\n * The order is §5.3's: lock first, target selection second, and everything the\n * command decides from live state after both. Selecting the target before the\n * lock would let two commands agree on a database and then race inside it —\n * which is why the selection is the caller's next step rather than this one's\n * tail: it belongs to the scope that releases.\n */\nasync function acquireLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<void> {\n const statement = migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID);\n if (statement === null) {\n return;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await executor(statement);\n } catch (error) {\n throw new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the lock statement itself failed.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n\n if (!migrationDriver.provesLockAcquired(rows)) {\n throw new MigrationError(\n `Failed to acquire the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the lock. ` +\n \"A wait that timed out, an error, or a malformed answer all mean the lock is NOT held; VibORM will not run migration work on that assumption.\",\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n }\n}\n\n/**\n * Releases the lock after the protected work FAILED, without replacing its\n * error.\n *\n * A `finally` that throws destroys the exception the caller needs: a MySQL\n * reset that cleared tracking and dropped half an estate on a dying connection\n * would report only \"the lock could not be released\", losing both the statement\n * that failed and the partial-commit reality §3.5 and §6.2 require it to state.\n * So the release still runs — the lock must not outlive the command, and the\n * producer is still condemned — and its own failure is RECORDED on the way out\n * instead of replacing the cause.\n *\n * The recording is {@link withSuppressedFailure}, the one rule both cleanup owners\n * share. Appending the detail to `cause.message` was the same intent written as\n * a WRITE to an error VibORM does not own: it throws outright for a frozen\n * Error or an accessor-backed `message`, and the caller was then told about a\n * `TypeError` from the cleanup rather than about the estate.\n */\nasync function releaseAfterFailure(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: { discard(): void },\n cause: unknown\n): Promise<void> {\n try {\n await releaseLock(pinned, migrationDriver, control);\n } catch (releaseFailure) {\n // For everything a caller can throw and hold, this IS `cause` — carrying\n // the release failure, unchanged in every other respect. Only a primary\n // that can carry nothing at all (a thrown string, a thrown number) changes\n // shape, into the one carrier that keeps both.\n throw withSuppressedFailure(cause, releaseFailure);\n }\n}\n\n/**\n * Releases the lock and PROVES the release.\n *\n * An unproven release condemns the producer: it is a session holding a lock\n * nobody will free, and handing it back to a pool would strand that lock for\n * the life of the connection. The refusal surfaces — cleanup failure is a\n * failure — except when the body itself already threw, in which case the throw\n * propagates and replacing it would hide the cause\n * ({@link releaseAfterFailure}).\n *\n * The lock is released through the driver the command was GIVEN, never through\n * the command-local view a MySQL session resolved: a release has to name the\n * lock this session acquired, and only the acquiring driver can name it.\n */\nasync function releaseLock(\n pinned: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n control: { discard(): void }\n): Promise<void> {\n const statement = migrationDriver.generateReleaseLock(MIGRATION_LOCK_ID);\n if (statement === null) {\n return;\n }\n\n const executor = createQueryExecutor(pinned);\n let rows: unknown[];\n try {\n rows = await executor(statement);\n } catch (error) {\n control.discard();\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}. The pinned session was discarded rather than returned to the pool.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n\n if (!migrationDriver.provesLockReleased(rows)) {\n control.discard();\n throw new MigrationError(\n `Failed to release the migration lock for ${describeEstate(migrationDriver)}: the provider did not confirm the release. The pinned session was discarded rather than returned to the pool, so the lock cannot outlive the connection.`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED\n );\n }\n}\n\n/** The estate a lock failure is about. */\nfunction describeEstate(migrationDriver: BoundMigrationDriver): string {\n const { target } = migrationDriver;\n return target.dialect === \"postgresql\"\n ? `schema \"${target.namespace}\"`\n : `database \"${migrationDriver.namespace ?? \"(unbound)\"}\"`;\n}\n","/**\n * Live-capability admission\n *\n * ONE decision admits a migration command to live database state. Direct\n * `push()` and every high-level migration command reach it here; no command\n * reinterprets either fact for itself.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { canPinSession } from \"./pinned-session\";\nimport { formatMigrationTarget, readNamespaceAttestation } from \"./target\";\n\n/**\n * What a command asks of live state.\n *\n * - `effectful` — the command can write, or promises a concurrency-stable\n * decision read from live state (apply/down/reset/verify/push, and the live\n * dry down/reset decisions the CLI confirms against).\n * - `read-only` — a point-in-time read that changes nothing (status, log,\n * push dry-run introspection).\n *\n * Offline and storage-only work — generate, check, apply dry-run — never\n * reaches this owner at all.\n */\nexport type MigrationLiveRequirement = \"effectful\" | \"read-only\";\n\n/**\n * Admits (or refuses) live migration work for one command.\n *\n * The failure precedence for MySQL is exact and is the whole point of the\n * owner: an absent attestation is `DRIVER_NOT_SUPPORTED`, and only AFTER the\n * capability is admitted does an absent namespace become\n * `MIGRATION_INVALID_STATE`. Reversing them would report a missing database\n * name for a driver whose routing was never provable in the first place.\n *\n * PostgreSQL namespaces are proven earlier, when the estate target is resolved\n * — a PostgreSQL driver with no adapter namespace never reaches a live\n * boundary. SQLite has no namespace to prove.\n */\nexport function admitLiveMigrationCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const { target } = migrationDriver;\n\n if (target.dialect === \"postgresql\") {\n admitPinnedSessionCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect === \"sqlite\") {\n admitSqliteFamilyCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect !== \"mysql\") {\n return;\n }\n\n if (requirement === \"effectful\") {\n const attestation = readNamespaceAttestation(\n migrationDriver.executionDriver\n );\n if (attestation === undefined) {\n throw new MigrationError(\n `${command} needs proof that this MySQL driver does not redirect qualified table references, and the driver \"${migrationDriver.executionDriver.driverName}\" carries no non-redirecting migration-namespace attestation. ` +\n \"Effectful and concurrency-stable live migration work is refused: a successful handshake, a driver class, a URL shape or a server version is not proof that a proxy leaves qualified names in the requested database.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target, migrationDriver.namespace),\n },\n }\n );\n }\n }\n\n if (migrationDriver.namespace === undefined) {\n throw new MigrationError(\n `${command} needs a live MySQL database and this client's adapter is unbound. ` +\n \"MySQL migration artifacts are database-relative on purpose, so the live destination comes from the driver's `namespace` — supply it explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target),\n },\n }\n );\n }\n}\n\n/**\n * Refuses an effectful PostgreSQL command on a transport with no interactive\n * session.\n *\n * Neon's HTTP driver is the shipped case: it speaks a stateless request/reply\n * API, so a `pg_advisory_lock` it issued would be acquired by one request and\n * could never be released by another — the lock would be neither held for the\n * work nor released after it. Every path that mutates, or that makes a\n * concurrency-stable decision from live state, is therefore refused HERE:\n * before the connection, before storage writes, and before any other provider\n * work. Its qualified runtime, read-only introspection, status/log, push\n * dry-run, and every offline path stay available.\n *\n * The answer is `canPinSession(driver)` — the presence of the driver's own\n * pinned-session hook — so nothing declares a capability it does not implement,\n * and a custom PostgreSQL driver is judged by the same fact as a stock one.\n */\nfunction admitSqliteFamilyCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n if (requirement !== \"effectful\") {\n return;\n }\n const driverName = migrationDriver.executionDriver.driverName;\n if (driverName === \"d1\" || driverName === \"d1-http\") {\n throw new MigrationError(\n `${command} cannot claim effectful V1 migration support on \"${driverName}\": table recreation, foreign-key handling, native-batch atomicity, and marker CAS are not proven together. ` +\n \"Generation, check, and read-only status remain available.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n }\n if (driverName === \"libsql\") {\n throw new MigrationError(\n `${command} cannot claim V1 constraint alteration on libsql: existing rows are not prevalidated and table reconstruction is not proven. ` +\n \"Generation, check, and read-only status remain available.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n }\n}\n\nfunction admitPinnedSessionCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n if (requirement !== \"effectful\") {\n return;\n }\n if (canPinSession(migrationDriver.executionDriver)) {\n return;\n }\n throw new MigrationError(\n `${command} needs one physical database session it can hold a migration lock on, and the driver \"${migrationDriver.executionDriver.driverName}\" has no interactive session to reserve. ` +\n \"Effectful and concurrency-stable live migration work is refused: a session-scoped lock taken over a stateless transport would be acquired by one request and released by another, so it would protect nothing. Runtime queries, introspection, status, log, push dry-run and every offline command remain available.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n}\n","/**\n * Centralized Type Mapping for Migration Drivers\n *\n * Maps VibORM scalar types to native database column types.\n * Uses constants from native-types.ts to ensure consistency.\n */\n\nimport { PG, SQLITE } from \"@schema/scalars/native-types\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n} from \"@validation/primitives/decimal-codec\";\nimport { SQLITE_GEO_POINT_TYPE } from \"../../adapters/databases/sqlite/storage/geo-point\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { SQLITE_DECIMAL_LIST_TYPE } from \"../decimal\";\n\n// =============================================================================\n// TYPE MAPPING CONSTANTS\n// =============================================================================\n\n/**\n * Default PostgreSQL type mappings for each VibORM scalar type.\n * Uses the same type names as defined in native-types.ts.\n */\nexport const PG_TYPE_DEFAULTS = {\n string: PG.STRING.TEXT.type,\n int: PG.INT.INTEGER.type,\n number: PG.FLOAT.DOUBLE_PRECISION.type,\n boolean: PG.BOOLEAN.BOOLEAN.type,\n datetime: PG.DATETIME.TIMESTAMP(3).type,\n datetimetz: PG.DATETIME.TIMESTAMPTZ(3).type,\n date: PG.DATETIME.DATE.type,\n time: PG.DATETIME.TIME(3).type,\n timetz: PG.DATETIME.TIMETZ(3).type,\n bigint: PG.BIGINT.BIGINT.type,\n json: PG.JSON.JSONB.type,\n blob: PG.BLOB.BYTEA.type,\n vector: \"vector\",\n point: \"geography(Point,4326)\",\n enum: PG.STRING.TEXT.type,\n} as const;\n\n/**\n * Default SQLite type mappings for each VibORM scalar type.\n * SQLite has limited type affinity - most types map to TEXT, INTEGER, REAL, or BLOB.\n */\nexport const SQLITE_TYPE_DEFAULTS = {\n string: SQLITE.STRING.TEXT.type,\n int: SQLITE.INT.INTEGER.type,\n number: SQLITE.FLOAT.REAL.type,\n boolean: SQLITE.BOOLEAN.INTEGER.type,\n datetime: SQLITE.DATETIME.TEXT.type,\n date: SQLITE.DATETIME.TEXT.type,\n time: SQLITE.DATETIME.TEXT.type,\n bigint: SQLITE.BIGINT.INTEGER.type,\n json: \"JSON\", // SQLite JSON functions work with TEXT but JSON is more semantic\n blob: SQLITE.BLOB.BLOB.type,\n vector: \"JSON\", // Store as JSON array in SQLite\n point: SQLITE_GEO_POINT_TYPE,\n enum: SQLITE.STRING.TEXT.type,\n} as const;\n\n/**\n * Default MySQL type mappings for each VibORM scalar type.\n * MySQL has full type support but uses TINYINT(1) for booleans\n * and doesn't support native arrays (use JSON instead).\n */\nexport const MYSQL_TYPE_DEFAULTS = {\n string: \"TEXT\",\n int: \"INT\",\n number: \"DOUBLE\",\n boolean: \"TINYINT(1)\", // MySQL uses TINYINT(1) for boolean\n datetime: \"DATETIME(3)\", // Use DATETIME(3) to preserve JavaScript Date millisecond precision\n datetimetz: \"DATETIME(3)\", // MySQL DATETIME can store with timezone via application\n date: \"DATE\",\n time: \"TIME(3)\", // Use TIME(3) to preserve millisecond precision\n timetz: \"TIME(3)\", // MySQL TIME doesn't have timezone variant\n bigint: \"BIGINT\",\n json: \"JSON\",\n blob: \"BLOB\",\n vector: \"JSON\", // No native vector support, use JSON\n point: \"POINT SRID 4326\",\n enum: \"TEXT\", // Default for unspecified enums; usually use inline ENUM()\n} as const;\n\n/**\n * THE MySQL inline enum type — one spelling, both snapshot producers.\n *\n * MySQL has no standalone enum object: the values ARE the column type, so this\n * text is also the enum's identity in a snapshot. The desired side spells it\n * (`MySQLMigrationDriver.getEnumColumnType`) and the live side re-spells the\n * catalog's `COLUMN_TYPE` through the very same function\n * (`mysql/introspect.ts`), because `information_schema` prints its own\n * canonical rendering — `enum('a','b')`, no space after the comma, and an\n * identity of its own invention — and two spellings of ONE type read as a\n * changed column on every push and as the mismatch the final push attestation\n * refuses.\n *\n * A member IS a MySQL string literal, so it is spelled by the one function that\n * spells those (`mysqlStringLiteral` below) rather than by a second rule of its\n * own. Doubling `'` alone was that second rule: `ENUM('a\\b')` declared a member\n * holding a BACKSPACE, `ENUM('end\\')` did not parse at all, and once the\n * default beside such a member went through the shared spelling the two\n * disagreed and MySQL refused the CREATE/MODIFY with errno 1067 (all measured).\n */\nexport function mysqlEnumType(values: readonly string[]): string {\n return `ENUM(${values.map((value) => mysqlStringLiteral(value)).join(\", \")})`;\n}\n\n/**\n * THE characters MySQL's string literals carry as an escape — the one table\n * both directions read.\n *\n * MySQL reads `\\` inside a string literal as an escape introducer (only\n * `NO_BACKSLASH_ESCAPES` stops it, a mode this estate never sets and the\n * pinned session does not promise), so doubling `'` alone spells a DIFFERENT\n * value: `DEFAULT ('a\\b')` stored a BACKSPACE and `DEFAULT ('end\\')` did not\n * even parse. The four control characters are escaped for the same reason\n * they cannot be written raw: a generated statement is also the review blob,\n * which is UTF-8/LF with no carriage returns (`sql-blob.ts`).\n *\n * `information_schema` prints an expression default with exactly these escapes\n * plus `\\'` (measured on 8.4.11 — every other character, tab and backspace\n * included, is printed raw), so `mysql/introspect.ts` undoes this same table\n * before re-spelling the value through `mysqlStringLiteral` below.\n */\nexport const MYSQL_LITERAL_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"\\\\\", \"\\\\\\\\\"],\n [\"\\n\", \"\\\\n\"],\n [\"\\r\", \"\\\\r\"],\n [\"\\0\", \"\\\\0\"],\n [\"\\u001a\", \"\\\\Z\"],\n]);\n\n/**\n * THE MySQL string literal — one spelling, both snapshot producers.\n *\n * The desired side writes it (`MySQLMigrationDriver.escapeValue`) and the live\n * side re-spells the value it read out of the catalog through the very same\n * function (`mysql/introspect.ts`), because two spellings of ONE value read as\n * a changed column on every push and as the mismatch the final push\n * attestation refuses.\n */\nexport function mysqlStringLiteral(value: string): string {\n let escaped = \"\";\n for (const character of value) {\n escaped += MYSQL_LITERAL_ESCAPES.get(character) ?? character;\n }\n return `'${escaped.replace(/'/g, \"''\")}'`;\n}\n\nconst ENUM_VALUES_REGEX = /enum\\((.+)\\)/i;\n\n/**\n * What MySQL's printer writes, read backwards: the WRITE table\n * (`mysqlStringLiteral`) inverted, plus the apostrophe, which MySQL prints as\n * `\\'` although the DDL spelling doubles it instead. Every other character —\n * tab, backspace, `\"` — is printed raw (measured on 8.4.11), so an escape\n * outside this table is one this inverse does not own.\n *\n * ONE table, both catalog vocabularies, because both are MySQL printing a\n * string literal it parsed: the expression default below, and an ENUM's members\n * inside `COLUMN_TYPE`. The enum printer writes a strict SUBSET of it (`\\\\`,\n * `\\n`, `\\r`, `\\0`; it doubles `'` and prints ctrl-Z raw, measured), so reading\n * one table backwards covers both and leaves the same remainder unowned.\n */\nexport const MYSQL_PRINTED_CHARACTERS: ReadonlyMap<string, string> = new Map([\n [\"'\", \"'\"],\n ...[...MYSQL_LITERAL_ESCAPES].map(\n ([character, sequence]) =>\n [sequence.slice(1), character] as [string, string]\n ),\n]);\n\n/**\n * Parse enum values from MySQL COLUMN_TYPE string, or `null` when the catalog\n * spelled one this inverse does not own.\n *\n * Handles values containing commas, doubled single quotes (''), and the\n * backslash escapes MySQL's printer writes (`MYSQL_PRINTED_CHARACTERS`).\n * Example: \"enum('a,b','it''s','c')\" -> ['a,b', \"it's\", 'c']\n * Example: String.raw`enum('a\\\\b','line1\\nline2')` -> [\"a\\\\b\", \"line1\\nline2\"]\n *\n * Reading `\\x` as a bare `x` — which is what \"skip the backslash\" does — turned\n * the printed `\\n` of a declared NEWLINE into the letter `n`, a value the\n * declaration never held. An escape outside the table is not one this server\n * printed for a member the estate spelled, so inverting it would be a guess:\n * the column keeps MySQL's own `COLUMN_TYPE` instead and the push fails at the\n * final attestation, the same fail-closed direction the string inverse takes.\n */\nexport function parseMySqlEnumValues(columnType: string): string[] | null {\n const match = columnType.match(ENUM_VALUES_REGEX);\n if (!match?.[1]) return null;\n\n const content = match[1];\n const values: string[] = [];\n let i = 0;\n\n while (i < content.length) {\n // Skip whitespace and commas\n while (i < content.length && (content[i] === \" \" || content[i] === \",\")) {\n i++;\n }\n if (i >= content.length) break;\n\n // Expect opening quote\n if (content[i] !== \"'\") {\n i++;\n continue;\n }\n i++; // Skip opening quote\n\n // Collect value until closing quote (handle escaped quotes '' and \\')\n let value = \"\";\n while (i < content.length) {\n if (content[i] === \"\\\\\" && i + 1 < content.length) {\n // Backslash escape - the character MySQL's printer wrote it for\n const printed = MYSQL_PRINTED_CHARACTERS.get(content[i + 1] ?? \"\");\n if (printed === undefined) return null;\n value += printed;\n i += 2;\n } else if (content[i] === \"'\" && content[i + 1] === \"'\") {\n // Doubled quote escape - add single quote and skip both\n value += \"'\";\n i += 2;\n } else if (content[i] === \"'\") {\n // Closing quote\n i++;\n break;\n } else {\n value += content[i];\n i++;\n }\n }\n values.push(value);\n }\n\n return values.length > 0 ? values : null;\n}\n\n// =============================================================================\n// TYPE MAPPING FUNCTIONS\n// =============================================================================\n\nexport interface ScalarTypeContext {\n type: string;\n array?: boolean;\n withTimezone?: boolean;\n dimension?: number | undefined;\n /**\n * The declared fixed-decimal domain, for a `decimal` scalar. Every decimal\n * type on every dialect is DERIVED from it — there is no unconstrained\n * `numeric`, no `DECIMAL(65,30)`, and no TEXT decimal to fall back to.\n */\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * The declared domain of a decimal context.\n *\n * A decimal column with no descriptor has no physical type at all: the numbers\n * cannot be inferred from storage, a value, a driver, or an operation (plan\n * §1.1), so the alternative to refusing is inventing a second precision — which\n * is exactly the `DECIMAL(65,30)` this program deletes. The public decimal\n * factory cannot produce such a state; a hand-built or externally-deserialized\n * scalar state can, and this is where it stops.\n */\nfunction requireDecimalDomain(context: ScalarTypeContext): DecimalDescriptor {\n if (context.decimal) return context.decimal;\n throw new MigrationError(\n \"A decimal column has no declared precision and scale. \" +\n \"The fixed-decimal domain is declared once, on the scalar, and every physical type is derived from it.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { scalarType: \"decimal\" } }\n );\n}\n\n/**\n * Gets the PostgreSQL column type for a VibORM scalar type.\n */\nexport function getPostgresType(context: ScalarTypeContext): string {\n let baseType: string;\n\n switch (context.type) {\n case \"string\":\n baseType = PG_TYPE_DEFAULTS.string;\n break;\n case \"int\":\n baseType = PG_TYPE_DEFAULTS.int;\n break;\n case \"number\":\n baseType = PG_TYPE_DEFAULTS.number;\n break;\n case \"decimal\":\n // `NUMERIC(p,s)`, and `NUMERIC(p,s)[]` through the array suffix below:\n // PostgreSQL carries the domain in the element typmod, which is the one\n // place introspection can read it back from.\n baseType = decimalColumnType(\"pg\", requireDecimalDomain(context));\n break;\n case \"boolean\":\n baseType = PG_TYPE_DEFAULTS.boolean;\n break;\n case \"datetime\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.datetimetz\n : PG_TYPE_DEFAULTS.datetime;\n break;\n case \"date\":\n baseType = PG_TYPE_DEFAULTS.date;\n break;\n case \"time\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.timetz\n : PG_TYPE_DEFAULTS.time;\n break;\n case \"bigint\":\n baseType = PG_TYPE_DEFAULTS.bigint;\n break;\n case \"json\":\n baseType = PG_TYPE_DEFAULTS.json;\n break;\n case \"blob\":\n baseType = PG_TYPE_DEFAULTS.blob;\n break;\n case \"vector\":\n baseType =\n context.dimension === undefined\n ? PG_TYPE_DEFAULTS.vector\n : `${PG_TYPE_DEFAULTS.vector}(${context.dimension})`;\n break;\n case \"point\":\n baseType = PG_TYPE_DEFAULTS.point;\n break;\n case \"enum\":\n baseType = PG_TYPE_DEFAULTS.enum;\n break;\n default:\n baseType = PG_TYPE_DEFAULTS.string;\n }\n\n return context.array ? `${baseType}[]` : baseType;\n}\n\n/**\n * Gets the SQLite column type for a VibORM scalar type.\n * SQLite doesn't support native arrays - they are stored as JSON.\n */\nexport function getSQLiteType(context: ScalarTypeContext): string {\n // SQLite doesn't support native arrays - use JSON.\n //\n // A decimal list is the one exception, and it is TEXT rather than JSON for a\n // physical reason: its reserved CHECK asserts `typeof = 'text'`, and the\n // literal type `JSON` has NUMERIC affinity under SQLite's rules, which would\n // convert a numeric-looking container on the way in.\n if (context.array) {\n return context.type === \"decimal\" ? SQLITE_DECIMAL_LIST_TYPE : \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n case \"enum\":\n return SQLITE_TYPE_DEFAULTS.string;\n case \"json\":\n case \"vector\":\n return \"JSON\";\n case \"point\":\n return SQLITE_TYPE_DEFAULTS.point;\n case \"int\":\n case \"bigint\":\n case \"boolean\":\n return SQLITE_TYPE_DEFAULTS.int;\n case \"number\":\n return SQLITE_TYPE_DEFAULTS.number;\n // The signed INTEGER coefficient scaled by 10^scale. SQLite has no exact\n // decimal type at all — `DECIMAL(10,5)` is a NUMERIC-affinity spelling\n // whose numbers it ignores, and REAL rounds a fractional value into a\n // double as it is stored — so the exact value lives in an integer and the\n // declared precision is made real by the reserved CHECK the driver adds.\n case \"decimal\":\n return decimalColumnType(\"sqlite\", requireDecimalDomain(context));\n case \"datetime\":\n case \"date\":\n case \"time\":\n return SQLITE_TYPE_DEFAULTS.datetime;\n case \"blob\":\n return SQLITE_TYPE_DEFAULTS.blob;\n default:\n return SQLITE_TYPE_DEFAULTS.string;\n }\n}\n\n/**\n * Gets the MySQL column type for a VibORM scalar type.\n * MySQL doesn't support native arrays - they are stored as JSON.\n */\nexport function getMySQLType(context: ScalarTypeContext): string {\n // MySQL doesn't support native arrays - use JSON\n if (context.array) {\n return \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n return MYSQL_TYPE_DEFAULTS.string;\n case \"int\":\n return MYSQL_TYPE_DEFAULTS.int;\n case \"number\":\n return MYSQL_TYPE_DEFAULTS.number;\n // Never bare `DECIMAL`: MySQL reads that as `DECIMAL(10,0)` and silently\n // truncates every fraction. A decimal LIST is caught by the array arm\n // above, where it is JSON like every other MySQL list and carries its\n // domain in the column-comment marker instead.\n case \"decimal\":\n return decimalColumnType(\"mysql\", requireDecimalDomain(context));\n case \"boolean\":\n return MYSQL_TYPE_DEFAULTS.boolean;\n case \"datetime\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.datetimetz\n : MYSQL_TYPE_DEFAULTS.datetime;\n case \"date\":\n return MYSQL_TYPE_DEFAULTS.date;\n case \"time\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.timetz\n : MYSQL_TYPE_DEFAULTS.time;\n case \"bigint\":\n return MYSQL_TYPE_DEFAULTS.bigint;\n case \"json\":\n return MYSQL_TYPE_DEFAULTS.json;\n case \"blob\":\n return MYSQL_TYPE_DEFAULTS.blob;\n case \"vector\":\n return MYSQL_TYPE_DEFAULTS.vector;\n case \"point\":\n return MYSQL_TYPE_DEFAULTS.point;\n case \"enum\":\n return MYSQL_TYPE_DEFAULTS.enum;\n default:\n return MYSQL_TYPE_DEFAULTS.string;\n }\n}\n","import type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\n\nconst DOLLAR_QUOTE = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/;\nconst IDENTIFIER_START = /[A-Za-z_]/;\nconst IDENTIFIER_PART = /[A-Za-z0-9_$]/;\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\nconst SQL_WHITESPACE = /\\s/;\n\nexport type NativeRenameOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" | \"renameColumn\" }\n>;\n\n/**\n * Applies the schema-wide effect a database native rename has already made.\n *\n * The resolver uses this as its next differ input, generated down migrations\n * use it to address definitions before the inverse rename runs, and SQLite's\n * batch replay uses it before a later table reconstruction. It never mutates\n * the snapshot supplied by the caller.\n */\nexport function applyNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n): SchemaSnapshot {\n return {\n ...snapshot,\n tables:\n operation.type === \"renameTable\"\n ? renameTable(snapshot.tables, operation.from, operation.to)\n : renameColumn(\n snapshot.tables,\n operation.tableName,\n operation.from,\n operation.to\n ),\n };\n}\n\nfunction renameTable(\n tables: readonly TableDef[],\n from: string,\n to: string\n): TableDef[] {\n return tables.map((table) => ({\n ...table,\n name: table.name === from ? to : table.name,\n foreignKeys: table.foreignKeys.map((foreignKey) =>\n foreignKey.referencedTable === from\n ? { ...foreignKey, referencedTable: to }\n : foreignKey\n ),\n }));\n}\n\nfunction renameColumn(\n tables: readonly TableDef[],\n tableName: string,\n from: string,\n to: string\n): TableDef[] {\n const renamed = (name: string) => (name === from ? to : name);\n\n return tables.map((table) => {\n const ownsColumn = table.name === tableName;\n return {\n ...table,\n columns: ownsColumn\n ? table.columns.map((column) =>\n column.name === from ? { ...column, name: to } : column\n )\n : table.columns,\n ...(ownsColumn && table.primaryKey\n ? {\n primaryKey: {\n ...table.primaryKey,\n columns: table.primaryKey.columns.map(renamed),\n },\n }\n : {}),\n indexes: ownsColumn\n ? table.indexes.map((index) => ({\n ...index,\n columns: index.columns.map(renamed),\n ...(index.where === undefined\n ? {}\n : { where: renameSqlIdentifier(index.where, from, to) }),\n }))\n : table.indexes,\n foreignKeys: table.foreignKeys.map((foreignKey) => ({\n ...foreignKey,\n columns: ownsColumn\n ? foreignKey.columns.map(renamed)\n : foreignKey.columns,\n referencedColumns:\n foreignKey.referencedTable === tableName\n ? foreignKey.referencedColumns.map(renamed)\n : foreignKey.referencedColumns,\n })),\n uniqueConstraints: ownsColumn\n ? table.uniqueConstraints.map((constraint) => ({\n ...constraint,\n columns: constraint.columns.map(renamed),\n }))\n : table.uniqueConstraints,\n };\n });\n}\n\n/**\n * Rewrites one identifier in an opaque SQL expression without touching values.\n *\n * PostgreSQL and SQLite persist partial-index predicates as SQL text, but a\n * native column rename changes the parsed column references in those\n * predicates. Snapshot replay must model the same effect before a later table\n * recreation. Quoted identifiers retain their delimiter; ordinary identifiers\n * retain their spelling style when the target can be written bare. Strings,\n * dollar-quoted bodies, and comments are copied byte-for-byte.\n */\nfunction renameSqlIdentifier(sql: string, from: string, to: string): string {\n let rewritten = \"\";\n let cursor = 0;\n\n while (cursor < sql.length) {\n const quote = sql[cursor];\n\n if (quote === \"'\") {\n const end = quotedRegionEnd(sql, cursor, \"'\", \"'\");\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === '\"' || quote === \"`\") {\n const end = quotedRegionEnd(sql, cursor, quote, quote);\n if (sql[end - 1] !== quote) {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(`${quote}${quote}`, quote);\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `${quote}${to.replaceAll(quote, `${quote}${quote}`)}${quote}`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"[\") {\n const end = quotedRegionEnd(sql, cursor, \"]\", \"]\");\n if (sql[end - 1] !== \"]\") {\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n const body = sql.slice(cursor + 1, end - 1);\n const identifier = body.replaceAll(\"]]\", \"]\");\n rewritten +=\n identifier === from && !isNonColumnIdentifier(sql, cursor, end)\n ? `[${escapeBracketIdentifier(to)}]`\n : sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"-\" && sql[cursor + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", cursor + 2);\n const end = newline < 0 ? sql.length : newline;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"/\" && sql[cursor + 1] === \"*\") {\n const end = blockCommentEnd(sql, cursor);\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n if (quote === \"$\") {\n const delimiter = dollarQuoteDelimiter(sql, cursor);\n if (delimiter !== undefined) {\n const closing = sql.indexOf(delimiter, cursor + delimiter.length);\n const end = closing < 0 ? sql.length : closing + delimiter.length;\n rewritten += sql.slice(cursor, end);\n cursor = end;\n continue;\n }\n }\n if (isIdentifierStart(quote)) {\n let end = cursor + 1;\n while (end < sql.length && isIdentifierPart(sql[end]!)) end += 1;\n const identifier = sql.slice(cursor, end);\n const lowercaseIdentifier = identifier.toLowerCase();\n const escapeStringQuote =\n lowercaseIdentifier === \"e\" && sql[end] === \"'\"\n ? end\n : lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\"\n ? end + 1\n : undefined;\n if (escapeStringQuote !== undefined) {\n const literalEnd = quotedRegionEnd(\n sql,\n escapeStringQuote,\n \"'\",\n \"'\",\n true\n );\n rewritten += sql.slice(cursor, literalEnd);\n cursor = literalEnd;\n continue;\n }\n const isStringPrefix =\n sql[end] === \"'\" ||\n (lowercaseIdentifier === \"u\" &&\n sql[end] === \"&\" &&\n sql[end + 1] === \"'\");\n rewritten +=\n !(isStringPrefix || isNonColumnIdentifier(sql, cursor, end)) &&\n unquotedIdentifierMatches(identifier, from)\n ? bareIdentifierOrQuoted(to)\n : identifier;\n cursor = end;\n continue;\n }\n\n rewritten += quote;\n cursor += 1;\n }\n\n return rewritten;\n}\n\nfunction quotedRegionEnd(\n sql: string,\n start: number,\n closingQuote: string,\n escapedQuote: string,\n backslashEscapes = false\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== closingQuote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === escapedQuote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\nfunction blockCommentEnd(sql: string, start: number): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length && depth > 0) {\n if (sql[cursor] === \"/\" && sql[cursor + 1] === \"*\") {\n depth += 1;\n cursor += 2;\n } else if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n } else {\n cursor += 1;\n }\n }\n return cursor;\n}\n\nfunction dollarQuoteDelimiter(sql: string, start: number): string | undefined {\n const rest = sql.slice(start);\n const match = DOLLAR_QUOTE.exec(rest);\n return match?.[0];\n}\n\nfunction isIdentifierStart(character: string | undefined): boolean {\n return character !== undefined && IDENTIFIER_START.test(character);\n}\n\nfunction isIdentifierPart(character: string): boolean {\n return IDENTIFIER_PART.test(character);\n}\n\nfunction unquotedIdentifierMatches(identifier: string, from: string): boolean {\n return from === from.toLowerCase() && identifier.toLowerCase() === from;\n}\n\nfunction isNonColumnIdentifier(\n sql: string,\n start: number,\n end: number\n): boolean {\n let next = end;\n while (next < sql.length && SQL_WHITESPACE.test(sql[next]!)) next += 1;\n if (sql[next] === \"(\" || (sql[next] === \"=\" && sql[next + 1] === \">\")) {\n return true;\n }\n\n let previous = start - 1;\n while (previous >= 0 && SQL_WHITESPACE.test(sql[previous]!)) previous -= 1;\n if (sql[previous] === \".\") return true;\n if (sql[previous] === \":\" && sql[previous - 1] === \":\") return true;\n\n const previousEnd = previous + 1;\n while (previous >= 0 && isIdentifierPart(sql[previous]!)) previous -= 1;\n const previousWord = sql.slice(previous + 1, previousEnd).toLowerCase();\n return previousWord === \"as\" || previousWord === \"collate\";\n}\n\nfunction bareIdentifierOrQuoted(identifier: string): string {\n return BARE_IDENTIFIER.test(identifier)\n ? identifier\n : `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction escapeBracketIdentifier(identifier: string): string {\n return identifier.split(\"]\").join(\"]]\");\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n// =============================================================================\n// SCHEMA SNAPSHOT (database-agnostic representation)\n// =============================================================================\n\nexport interface SchemaSnapshot {\n tables: TableDef[];\n enums?: EnumDef[] | undefined;\n /**\n * Generated-file history for polymorphic discriminator members.\n * This is descriptive metadata only; the structural differ ignores it.\n */\n polymorphicStorage?: readonly PolymorphicSnapshotStorage[] | undefined;\n}\n\nexport interface PolymorphicToOneSnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n}\n\n/**\n * Logical-only history for a to-one polymorphic relation. The physical\n * facts (columns, index) live in the owner's {@link TableDef} where the\n * structural differ owns them; `storageRef` is the join key into the owner\n * table's `relationStorage` registry — the physical type-column name at\n * serialization time, opaque to every reader and normalized through accepted\n * rename operations before history joins.\n */\nexport interface PolymorphicToOneSnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toOne\";\n readonly storageRef: string;\n readonly members: readonly PolymorphicToOneSnapshotMember[];\n}\n\nexport interface PolymorphicToManySnapshotMember {\n readonly publicType: string;\n readonly storedType: string;\n readonly targetTable: string;\n readonly memberJunctionTable: string;\n readonly inverseCardinality: \"one\" | \"many\";\n}\n\n/**\n * Logical-only history for a collection polymorphic relation: nothing\n * physical (no side columns, constraint names, or referential actions) — each\n * member names its junction table and the structural differ owns that table's\n * shape entirely.\n */\nexport interface PolymorphicToManySnapshot {\n readonly ownerTable: string;\n readonly relation: string;\n readonly kind: \"toMany\";\n readonly members: readonly PolymorphicToManySnapshotMember[];\n}\n\nexport type PolymorphicSnapshotStorage =\n | PolymorphicToOneSnapshot\n | PolymorphicToManySnapshot;\n\n/**\n * One relation-owned physical storage annotation on the table that carries it,\n * keyed in {@link TableDef.relationStorage} by the storage ref (the physical\n * type-column name at serialization time).\n */\nexport interface PolymorphicToOneStorageRegistryEntry {\n readonly kind: \"polymorphicToOne\";\n readonly typeColumn: string;\n readonly idColumn: string;\n readonly index: string;\n}\n\nexport interface TableDef {\n name: string;\n columns: ColumnDef[];\n primaryKey?: PrimaryKeyDef | undefined;\n indexes: IndexDef[];\n foreignKeys: ForeignKeyDef[];\n uniqueConstraints: UniqueConstraintDef[];\n /**\n * Relation-owned storage registry, annotation ONLY: the structural differ\n * ignores it, drivers pass it through `finalizeTable` untouched, no DDL\n * reads it, and introspected snapshots never carry it. Its sole reader is\n * polymorphic member history, which joins\n * {@link PolymorphicToOneSnapshot.storageRef} into it.\n */\n relationStorage?:\n | Readonly<Record<string, PolymorphicToOneStorageRegistryEntry>>\n | undefined;\n}\n\nexport interface ColumnDef {\n name: string;\n type: string; // Normalized type (e.g., \"varchar(255)\", \"integer\", \"boolean\")\n nullable: boolean;\n default?: string | undefined; // SQL expression for default value\n autoIncrement?: boolean | undefined;\n /**\n * The declared fixed-decimal domain this column stores, when it stores one.\n *\n * `type` is the ACTIVE PHYSICAL representation and this is the ONE logical\n * descriptor beside it — the pair every consumer reads (serializer, snapshot,\n * differ, DDL, introspection, defaults, table reconstruction). They are not\n * redundant: on PostgreSQL and MySQL the physical type spells the domain, but\n * on SQLite the class is `INTEGER` (scalar) or `TEXT` (list) whatever the\n * precision and scale are, so a descriptor change is invisible in `type`\n * alone and the differ would plan nothing for it.\n *\n * Every snapshot producer carries it — the serializer from\n * `ScalarState[\"decimal\"]`, and each introspection from the fact its dialect\n * can prove (a PostgreSQL typmod, a MySQL `DECIMAL(p,s)` or column-comment\n * marker, a SQLite reserved CHECK constraint name) — because a side that\n * cannot recover it would read as a change on every push, forever.\n *\n * There is no parallel decimal metadata map on `Model`, adapter, or\n * migration driver (plan §7.2): this field is the migration layer's only\n * copy, and it is a copy of the frozen descriptor the resolved scalar owns.\n */\n decimal?: DecimalDescriptor | undefined;\n /**\n * The declared SQLite storage vocabulary for one scalar DateTime column.\n *\n * SQLite's three physical types do not identify the logical domain: TEXT,\n * INTEGER, and REAL also store unrelated scalar families. The serializer\n * therefore carries the declaration beside the physical type so an explicit\n * migration can translate an existing DateTime instead of reinterpreting its\n * bytes. Live introspection cannot recover this logical fact and omits it.\n */\n dateTime?: DateTimePhysicalForm | undefined;\n /** SQLite writer CHECK version; physical metadata, never a public point language. */\n geoPointEncoding?: \"legacy\" | \"binary64\" | undefined;\n}\n\nexport interface PrimaryKeyDef {\n columns: string[];\n name?: string | undefined;\n}\n\nexport interface IndexDef {\n name: string;\n columns: string[];\n unique: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"fulltext\" | \"spatial\" | undefined;\n where?: string | undefined; // For partial indexes\n}\n\nexport interface ForeignKeyDef {\n name: string;\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n onDelete?: ReferentialAction | undefined;\n onUpdate?: ReferentialAction | undefined;\n}\n\nexport type ReferentialAction =\n | \"cascade\"\n | \"setNull\"\n | \"restrict\"\n | \"noAction\"\n | \"setDefault\";\n\nexport interface UniqueConstraintDef {\n name: string;\n columns: string[];\n}\n\nexport interface EnumDef {\n name: string;\n values: string[];\n}\n\n// =============================================================================\n// DIFF OPERATIONS (resolved, ready to execute)\n// =============================================================================\n\nexport type DiffOperation =\n | { type: \"createTable\"; table: TableDef }\n | { type: \"dropTable\"; tableName: string }\n | { type: \"renameTable\"; from: string; to: string }\n | { type: \"addColumn\"; tableName: string; column: ColumnDef }\n | { type: \"dropColumn\"; tableName: string; columnName: string }\n | { type: \"renameColumn\"; tableName: string; from: string; to: string }\n | {\n type: \"alterColumn\";\n tableName: string;\n columnName: string;\n from: ColumnDef;\n to: ColumnDef;\n }\n | { type: \"createIndex\"; tableName: string; index: IndexDef }\n | { type: \"dropIndex\"; tableName: string; indexName: string }\n | { type: \"addForeignKey\"; tableName: string; fk: ForeignKeyDef }\n | { type: \"dropForeignKey\"; tableName: string; fkName: string }\n | {\n type: \"addUniqueConstraint\";\n tableName: string;\n constraint: UniqueConstraintDef;\n }\n | { type: \"dropUniqueConstraint\"; tableName: string; constraintName: string }\n | { type: \"addPrimaryKey\"; tableName: string; primaryKey: PrimaryKeyDef }\n | { type: \"dropPrimaryKey\"; tableName: string; constraintName: string }\n | { type: \"createEnum\"; enumDef: EnumDef }\n | {\n type: \"dropEnum\";\n enumName: string;\n /**\n * Columns that depend on this enum.\n * Required for SQLite to know which columns need CHECK constraint removal.\n */\n dependentColumns?: Array<{ tableName: string; columnName: string }>;\n }\n | {\n type: \"alterEnum\";\n enumName: string;\n addValues?: string[] | undefined;\n removeValues?: string[] | undefined;\n /**\n * Full list of desired enum values (required when removing values)\n * Used to recreate the enum type in PostgreSQL\n */\n newValues?: string[] | undefined;\n /**\n * Columns that depend on this enum (required when removing values)\n * Each entry is { tableName, columnName }\n */\n dependentColumns?:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n /**\n * Global replacement values for removed enum values.\n * Used as fallback when no column-specific mapping exists.\n * Maps old value -> new value for data migration.\n *\n * Example: { \"pending\": \"inactive\" } - rows with \"pending\" become \"inactive\"\n * Use null to set rows to NULL: { \"pending\": null }\n */\n valueReplacements?: Record<string, string | null> | undefined;\n /**\n * Per-column replacement values for removed enum values.\n * Allows different columns to have different mappings.\n * Key is \"tableName.columnName\", value is the replacement map.\n *\n * Example: { \"users.status\": { \"pending\": \"inactive\" }, \"orders.status\": { \"pending\": \"cancelled\" } }\n */\n columnValueReplacements?:\n | Record<string, Record<string, string | null>>\n | undefined;\n /**\n * Default replacement for any removed values without explicit mapping.\n * Useful when the enum field has a default value - use that here.\n * Use null to set rows to NULL.\n *\n * Example: If your field has `.default(\"active\")`, set defaultReplacement: \"active\"\n */\n defaultReplacement?: string | null | undefined;\n };\n\n// =============================================================================\n// AMBIGUOUS CHANGES (require user input to resolve)\n// =============================================================================\n\n/** Detected when columns are added AND dropped in the same table */\nexport type AmbiguousColumnChange = {\n type: \"ambiguousColumn\";\n tableName: string;\n droppedColumn: ColumnDef;\n addedColumn: ColumnDef;\n};\n\n/** Detected when tables are added AND dropped */\nexport type AmbiguousTableChange = {\n type: \"ambiguousTable\";\n droppedTable: string;\n addedTable: string;\n droppedTableDef: TableDef;\n addedTableDef: TableDef;\n};\n\nexport type AmbiguousChange = AmbiguousColumnChange | AmbiguousTableChange;\n\n/** User's resolution for an ambiguous change */\nexport type ChangeResolution =\n | { type: \"rename\" } // Treat as rename (preserve data)\n | { type: \"addAndDrop\" }; // Treat as separate add + drop (data loss)\n\n// =============================================================================\n// DIFF RESULT (output of differ, before resolution)\n// =============================================================================\n\nexport interface DiffResult {\n /** Operations that are unambiguous and ready to execute */\n operations: DiffOperation[];\n /** Changes that need user input to resolve */\n ambiguousChanges: AmbiguousChange[];\n}\n\n// =============================================================================\n// RESOLVER (handles ambiguous changes)\n// =============================================================================\n\n/** Callback to resolve ambiguous changes (used by CLI or programmatic API) */\nexport type Resolver = (\n changes: AmbiguousChange[]\n) => Promise<Map<AmbiguousChange, ChangeResolution>>;\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACK\n// =============================================================================\n\n/**\n * Valid resolution results.\n * - \"proceed\": Accept the change (for destructive)\n * - \"reject\": Reject the change and abort\n * - \"rename\": Treat as a rename (for ambiguous)\n * - \"addAndDrop\": Treat as separate add + drop (for ambiguous)\n * - \"enumMapped\": Enum values have been mapped (for enumValueRemoval)\n */\nexport type ResolveResult =\n | \"proceed\"\n | \"reject\"\n | \"rename\"\n | \"addAndDrop\"\n | \"enumMapped\";\n\n/**\n * Base properties shared by destructive and ambiguous changes.\n */\ninterface BaseResolveChange {\n /** The specific operation type */\n operation:\n | \"dropTable\"\n | \"dropColumn\"\n | \"addColumn\"\n | \"alterColumn\"\n | \"renameTable\"\n | \"renameColumn\";\n\n /** The table involved */\n table: string;\n\n /** The column involved (if applicable) */\n column?: string;\n\n /** Human-readable description of the change */\n description: string;\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A destructive change that will cause data loss.\n * Available methods: `proceed()`, `reject()`\n */\nexport interface DestructiveResolveChange extends BaseResolveChange {\n type: \"destructive\";\n\n /** Accept the destructive change (causes data loss) */\n proceed(): \"proceed\";\n}\n\n/**\n * An ambiguous change that could be a rename or add+drop.\n * Available methods: `rename()`, `addAndDrop()`, `reject()`\n */\nexport interface AmbiguousResolveChange extends BaseResolveChange {\n type: \"ambiguous\";\n\n /** The old name (for renames) */\n oldName?: string;\n\n /** The new name (for renames) */\n newName?: string;\n\n /** The old type (for alterColumn) */\n oldType?: string;\n\n /** The new type (for alterColumn) */\n newType?: string;\n\n /** Treat as a rename (preserves data) */\n rename(): \"rename\";\n\n /** Treat as separate add + drop (causes data loss) */\n addAndDrop(): \"addAndDrop\";\n}\n\n/**\n * An enum value removal that needs replacement mappings for a specific column.\n * Called once per column that uses the enum, allowing different mappings per column.\n * Available methods: `mapValues()`, `useNull()`, `reject()`\n */\nexport interface EnumValueRemovalChange {\n type: \"enumValueRemoval\";\n\n /** The enum name */\n enumName: string;\n\n /** The table containing the column */\n tableName: string;\n\n /** The column using this enum */\n columnName: string;\n\n /** Whether this column is nullable (if true, useNull() is safe) */\n isNullable: boolean;\n\n /** Values being removed */\n removedValues: string[];\n\n /** Available values to map to */\n availableValues: string[];\n\n /** Human-readable description */\n description: string;\n\n /**\n * Map removed values to replacement values.\n * @param replacements - Map of old value → new value (or null for NULL)\n */\n mapValues(replacements: Record<string, string | null>): \"enumMapped\";\n\n /**\n * Set all removed values to NULL.\n * This is a shorthand for mapValues where all values map to null.\n * Note: Only safe if the column is nullable.\n */\n useNull(): \"enumMapped\";\n\n /** Reject this change and abort the operation */\n reject(): \"reject\";\n}\n\n/**\n * A change that requires user resolution.\n * Use the type discriminant to determine which methods are available:\n * - `destructive`: `proceed()`, `reject()`\n * - `ambiguous`: `rename()`, `addAndDrop()`, `reject()`\n * - `enumValueRemoval`: `mapValues()`, `reject()`\n */\nexport type ResolveChange =\n | DestructiveResolveChange\n | AmbiguousResolveChange\n | EnumValueRemovalChange;\n\nexport type EnumResolutionDecision =\n | {\n readonly kind: \"mapValues\";\n readonly mappings: Record<string, string | null>;\n }\n | { readonly kind: \"useNull\" }\n | { readonly kind: \"mixed\" };\n\nconst enumResolutionDecisions = new WeakMap<\n ResolveChange,\n EnumResolutionDecision\n>();\n\n/** Internal authoritative decision made through an enum change's own methods. */\nexport function readEnumResolutionDecision(\n change: ResolveChange\n): EnumResolutionDecision | undefined {\n return enumResolutionDecisions.get(change);\n}\n\nfunction recordEnumResolutionDecision(\n change: EnumValueRemovalChange,\n decision: Exclude<EnumResolutionDecision, { readonly kind: \"mixed\" }>\n): void {\n const previous = enumResolutionDecisions.get(change);\n enumResolutionDecisions.set(\n change,\n previous !== undefined && previous.kind !== decision.kind\n ? { kind: \"mixed\" }\n : decision\n );\n}\n\n/**\n * Unified callback for resolving changes that need user input.\n * Called once per change, allowing granular control over each decision.\n *\n * @param change - The change requiring resolution\n * @returns The resolution decision (call a method on change to get this)\n *\n * @example\n * ```ts\n * resolve: async (change) => {\n * console.log(change.description);\n *\n * if (change.type === \"destructive\") {\n * return confirm(\"Accept data loss?\") ? change.proceed() : change.reject();\n * }\n *\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n *\n * if (change.type === \"enumValueRemoval\") {\n * // Map removed enum values to new values\n * return change.mapValues({\n * 'PENDING': 'INACTIVE',\n * 'OLD_VALUE': null, // Set to NULL\n * });\n * }\n * }\n * ```\n */\nexport type ResolveCallback = (\n change: ResolveChange\n) =>\n | Promise<ResolveResult | undefined | void>\n | ResolveResult\n | undefined\n | void;\n\n/**\n * Create a destructive change object with resolution methods.\n */\nexport function createDestructiveChange(props: {\n operation: \"dropTable\" | \"dropColumn\" | \"addColumn\" | \"alterColumn\";\n table: string;\n column?: string;\n description: string;\n}): DestructiveResolveChange {\n return {\n type: \"destructive\",\n ...props,\n proceed: () => \"proceed\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an ambiguous change object with resolution methods.\n */\nexport function createAmbiguousChange(props: {\n operation: \"renameTable\" | \"renameColumn\";\n table: string;\n column?: string;\n oldName?: string;\n newName?: string;\n oldType?: string;\n newType?: string;\n description: string;\n}): AmbiguousResolveChange {\n return {\n type: \"ambiguous\",\n ...props,\n rename: () => \"rename\",\n addAndDrop: () => \"addAndDrop\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an enum value removal change object with resolution methods.\n */\nexport function createEnumValueRemovalChange(props: {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n description: string;\n}): EnumValueRemovalChange {\n const change: EnumValueRemovalChange = {\n type: \"enumValueRemoval\",\n ...props,\n mapValues: (replacements: Record<string, string | null>) => {\n const mappings: Record<string, string | null> = {};\n for (const [value, replacement] of Object.entries(replacements)) {\n mappings[value] = replacement;\n }\n Object.freeze(mappings);\n recordEnumResolutionDecision(change, { kind: \"mapValues\", mappings });\n return \"enumMapped\";\n },\n useNull: () => {\n recordEnumResolutionDecision(change, { kind: \"useNull\" });\n return \"enumMapped\";\n },\n reject: () => \"reject\",\n };\n return change;\n}\n\nexport type Dialect = \"postgresql\" | \"sqlite\" | \"mysql\";\n\n/**\n * The durable estate target a migration history is generated for.\n *\n * PostgreSQL carries its schema because generated artifacts are\n * schema-qualified: a history generated for `billing` cannot be replayed as a\n * `public` estate. MySQL and SQLite arms carry ONLY their dialect — MySQL\n * artifacts are database-relative on purpose, so one estate deploys to\n * `app_dev`, `app_test` and `app_prod`, and SQLite has no namespace concept.\n *\n * This is the DURABLE compatibility claim, not the live execution destination.\n * The live destination is the adapter's namespace, which MySQL reads at its\n * live boundary and never persists here.\n */\nexport type MigrationTarget = (\n | { readonly dialect: \"postgresql\"; readonly namespace: string }\n | { readonly dialect: \"mysql\" }\n | { readonly dialect: \"sqlite\" }\n) & { readonly tables?: readonly string[] };\n","/**\n * Resolver System\n *\n * Handles ambiguous changes that require user input to resolve.\n * Provides utilities for converting user resolutions into concrete operations.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { type DiffOptions, diff } from \"./differ\";\nimport { applyNativeRename } from \"./native-rename\";\nimport type {\n AmbiguousChange,\n AmbiguousResolveChange,\n ChangeResolution,\n DestructiveResolveChange,\n DiffOperation,\n DiffResult,\n EnumValueRemovalChange,\n ResolveCallback,\n ResolveChange,\n ResolveResult,\n Resolver,\n SchemaSnapshot,\n} from \"./types\";\nimport { createAmbiguousChange, readEnumResolutionDecision } from \"./types\";\nimport { sortOperations } from \"./utils\";\n\nexport function validateResolveResult(\n expected: \"ambiguous\",\n change: AmbiguousResolveChange,\n result: unknown\n): \"rename\" | \"addAndDrop\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"destructive\",\n change: DestructiveResolveChange,\n result: unknown\n): \"proceed\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: \"enumValueRemoval\",\n change: EnumValueRemovalChange,\n result: unknown\n): \"enumMapped\" | \"reject\" | undefined;\nexport function validateResolveResult(\n expected: ResolveChange[\"type\"],\n change: ResolveChange,\n result: unknown\n): ResolveResult | undefined {\n if (result === undefined) return undefined;\n\n if (result === \"reject\") return result;\n if (\n expected === \"ambiguous\" &&\n (result === \"rename\" || result === \"addAndDrop\")\n ) {\n return result;\n }\n if (expected === \"destructive\" && result === \"proceed\") {\n return result;\n }\n if (expected === \"enumValueRemoval\" && result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision !== undefined && decision.kind !== \"mixed\") return result;\n }\n\n const received =\n typeof result === \"string\"\n ? `\"${result}\"`\n : result === null\n ? \"null\"\n : typeof result;\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result ${received} for a ${expected} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n type: \"invalid-resolution-result\",\n },\n }\n );\n}\n\n// =============================================================================\n// RESOLUTION APPLICATION\n// =============================================================================\n\n/**\n * Converts resolved ambiguous changes into concrete diff operations\n */\nexport function applyResolutions(\n changes: AmbiguousChange[],\n resolutions: Map<AmbiguousChange, ChangeResolution>\n): DiffOperation[] {\n const operations: DiffOperation[] = [];\n\n for (const change of changes) {\n const resolution = resolutions.get(change);\n if (!resolution) {\n throw new MigrationError(\n `Missing resolution for ${formatAmbiguousChange(change)}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n if (change.type === \"ambiguousColumn\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n });\n } else {\n // addAndDrop\n operations.push(\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n }\n );\n }\n } else if (change.type === \"ambiguousTable\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n });\n } else {\n // addAndDrop\n operations.push(\n { type: \"dropTable\", tableName: change.droppedTable },\n { type: \"createTable\", table: change.addedTableDef }\n );\n }\n }\n }\n\n return operations;\n}\n\n/**\n * Resolves every ambiguity exposed by accepted changes.\n *\n * Each decision is applied to a working source snapshot, then the ordinary\n * differ runs again with the original options. Native renames therefore expose\n * nested ambiguities and descriptor alterations through the same owner that\n * found the outer change; no local table differ or pre-rename operation list is\n * retained.\n */\nexport async function resolveAmbiguousChanges(\n initialDiffResult: DiffResult,\n currentSnapshot: SchemaSnapshot,\n desiredSnapshot: SchemaSnapshot,\n resolver: Resolver,\n options: DiffOptions = {}\n): Promise<DiffOperation[]> {\n let workingSnapshot = currentSnapshot;\n let diffResult = initialDiffResult;\n const resolutionOperations: DiffOperation[] = [];\n const resolvedAmbiguities = new Set<string>();\n const liveTableNames = new Map(\n currentSnapshot.tables.map((table) => [table.name, table.name])\n );\n\n while (diffResult.ambiguousChanges.length > 0) {\n const resolutions = await resolver(diffResult.ambiguousChanges);\n\n for (const change of diffResult.ambiguousChanges) {\n const key = ambiguityKey(change);\n if (resolvedAmbiguities.has(key)) {\n throw new MigrationError(\n `Ambiguous migration change did not converge after resolution: ${key}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n resolvedAmbiguities.add(key);\n\n const resolution = resolutions.get(change);\n if (!resolution)\n throw new MigrationError(\n `Missing resolution for ${formatAmbiguousChange(change)}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n const operations = applyResolutions(\n [change],\n new Map([[change, resolution]])\n );\n resolutionOperations.push(...operations);\n\n for (const operation of operations) {\n workingSnapshot = applyResolutionEffect(\n workingSnapshot,\n operation,\n options.projectRename\n );\n if (operation.type === \"renameTable\") {\n const liveName = liveTableNames.get(operation.from) ?? operation.from;\n liveTableNames.delete(operation.from);\n liveTableNames.set(operation.to, liveName);\n } else if (operation.type === \"dropTable\") {\n liveTableNames.delete(operation.tableName);\n }\n }\n }\n\n diffResult = await diff(\n workingSnapshot,\n desiredSnapshot,\n optionsForWorkingSnapshot(options, liveTableNames)\n );\n }\n\n return sortOperations([...resolutionOperations, ...diffResult.operations]);\n}\n\nfunction ambiguityKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table:${change.droppedTable}\\u0000${change.addedTable}`\n : `column:${change.tableName}\\u0000${change.droppedColumn.name}\\u0000${change.addedColumn.name}`;\n}\n\nfunction optionsForWorkingSnapshot(\n options: DiffOptions,\n liveTableNames: ReadonlyMap<string, string>\n): DiffOptions {\n const canonicalize = options.canonicalizeIndexPredicate;\n if (!canonicalize) return options;\n return {\n ...options,\n canonicalizeIndexPredicate: (tableName, predicates) =>\n canonicalize(liveTableNames.get(tableName) ?? tableName, predicates),\n };\n}\n\nfunction applyResolutionEffect(\n snapshot: SchemaSnapshot,\n operation: DiffOperation,\n projectRename: typeof applyNativeRename = applyNativeRename\n): SchemaSnapshot {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n return projectRename(snapshot, operation);\n }\n if (operation.type === \"dropTable\") {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n }\n if (operation.type === \"createTable\") {\n return { ...snapshot, tables: [...snapshot.tables, operation.table] };\n }\n if (operation.type === \"dropColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== operation.columnName\n ),\n }\n : table\n ),\n };\n }\n if (operation.type === \"addColumn\") {\n return {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? { ...table, columns: [...table.columns, operation.column] }\n : table\n ),\n };\n }\n return snapshot;\n}\n\nexport function ambiguousToResolveChange(\n change: AmbiguousChange\n): ResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n\nexport function callbackAsResolver(callback: ResolveCallback): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = await callback(resolveChange);\n if (result === \"rename\") {\n resolutions.set(change, { type: \"rename\" });\n continue;\n }\n if (result === \"addAndDrop\") {\n resolutions.set(change, { type: \"addAndDrop\" });\n continue;\n }\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n` +\n \"Generate requires change.rename() or change.addAndDrop() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return resolutions;\n };\n}\n\n// =============================================================================\n// DEFAULT RESOLVERS\n// =============================================================================\n\n/**\n * Resolver that always chooses \"rename\" for all ambiguous changes.\n * Useful for preserving data when the intent is clear.\n */\nexport const alwaysRenameResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"rename\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that always chooses \"addAndDrop\" for all ambiguous changes.\n * Useful for clean slate scenarios where data loss is acceptable.\n */\nexport const alwaysAddDropResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"addAndDrop\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that throws an error if any ambiguous changes are detected.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const strictResolver: Resolver = async (changes) => {\n if (changes.length > 0) {\n const descriptions = changes.map((change) => {\n if (change.type === \"ambiguousColumn\") {\n return `Column \"${change.droppedColumn.name}\" was removed and \"${change.addedColumn.name}\" was added in table \"${change.tableName}\"`;\n }\n return `Table \"${change.droppedTable}\" was removed and \"${change.addedTable}\" was added`;\n });\n\n throw new MigrationError(\n `Ambiguous changes detected that require resolution:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Supply a resolve callback choosing rename() or addAndDrop() for each change.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return new Map();\n};\n\n// =============================================================================\n// RESOLVER HELPERS\n// =============================================================================\n\n/**\n * Creates a resolver from a simple decision function\n */\nexport function createResolver(\n decide: (\n change: AmbiguousChange\n ) => \"rename\" | \"addAndDrop\" | Promise<\"rename\" | \"addAndDrop\">\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const decision = await decide(change);\n resolutions.set(change, { type: decision });\n }\n return resolutions;\n };\n}\n\n/**\n * Creates a resolver that uses predefined resolutions\n */\nexport function createPredefinedResolver(\n predefined: Array<{\n type: \"column\" | \"table\";\n from: string;\n to: string;\n tableName?: string;\n resolution: \"rename\" | \"addAndDrop\";\n }>\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n\n for (const change of changes) {\n const match = predefined.find((p) => {\n if (change.type === \"ambiguousColumn\" && p.type === \"column\") {\n return (\n p.from === change.droppedColumn.name &&\n p.to === change.addedColumn.name &&\n (!p.tableName || p.tableName === change.tableName)\n );\n }\n if (change.type === \"ambiguousTable\" && p.type === \"table\") {\n return p.from === change.droppedTable && p.to === change.addedTable;\n }\n return false;\n });\n\n if (match) {\n resolutions.set(change, { type: match.resolution });\n }\n // If no match found, the change will be handled by the default (add+drop)\n }\n\n return resolutions;\n };\n}\n\n/**\n * Formats ambiguous changes for display\n */\nexport function formatAmbiguousChange(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return (\n `Column rename detected in table \"${change.tableName}\":\\n` +\n ` \"${change.droppedColumn.name}\" (${change.droppedColumn.type}) → \"${change.addedColumn.name}\" (${change.addedColumn.type})`\n );\n }\n return (\n \"Table rename detected:\\n\" +\n ` \"${change.droppedTable}\" → \"${change.addedTable}\"`\n );\n}\n\n/**\n * Formats all ambiguous changes for display\n */\nexport function formatAmbiguousChanges(changes: AmbiguousChange[]): string {\n if (changes.length === 0) {\n return \"No ambiguous changes detected.\";\n }\n\n return changes.map(formatAmbiguousChange).join(\"\\n\\n\");\n}\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACKS\n// =============================================================================\n\n/**\n * Rejects all changes requiring resolution.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const rejectAllResolver: ResolveCallback = async (change) =>\n change.reject();\n\n/**\n * Accepts destructive changes, treats ambiguous column changes as renames,\n * and maps enum value removals to NULL.\n * A table pair stays undecided, so the plan refuses: the dropped side may be\n * another application's table, and only a callback naming the pair may\n * rename it.\n */\nexport const lenientResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.operation === \"renameColumn\" ? change.rename() : undefined;\n }\n\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Accepts destructive changes, treats ambiguous changes as add+drop,\n * and maps enum value removals to NULL.\n * Useful when you don't care about preserving data in ambiguous scenarios.\n */\nexport const addDropResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.addAndDrop();\n }\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Creates a unified resolver from a decision function.\n *\n * @example\n * ```ts\n * const resolver = createUnifiedResolver(async (change) => {\n * if (change.type === \"destructive\") {\n * return confirm(`Accept: ${change.description}?`) ? change.proceed() : change.reject();\n * }\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n * if (change.type === \"enumValueRemoval\") {\n * return change.mapValues({ 'OLD': 'NEW' });\n * }\n * return change.reject();\n * });\n * ```\n */\nexport function createUnifiedResolver(\n decide: (\n change: ResolveChange\n ) => Promise<\"proceed\" | \"reject\" | \"rename\" | \"addAndDrop\" | \"enumMapped\">\n): ResolveCallback {\n return decide;\n}\n","import { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { parseMySqlEnumValues } from \"../drivers/type-mapping\";\nimport { validateResolveResult } from \"../resolver\";\nimport {\n createEnumValueRemovalChange,\n type DiffOperation,\n type ResolveCallback,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"../types\";\n\nconst INLINE_ENUM_TOKEN =\n /^(?:enum\\(|text check\\(\"(?:[^\"]|\"\")*\"\\s+in\\s+\\()(\\s*'(?:[^']|'')*'(?:\\s*,\\s*'(?:[^']|'')*')*\\s*)\\)\\)?$/i;\n\n/** The closed inline enum carriers emitted by MySQL and SQLite drivers. */\nexport function inlineEnumValues(type: string): string[] | undefined {\n const match = INLINE_ENUM_TOKEN.exec(type.trim());\n if (!match?.[1]) return;\n if (type.trim().toLowerCase().startsWith(\"enum(\"))\n return parseMySqlEnumValues(type) ?? undefined;\n return Array.from(match[1].matchAll(/'((?:[^']|'')*)'/g), (item) =>\n item[1]!.replaceAll(\"''\", \"'\")\n );\n}\n\nexport interface EnumRemoval {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n}\n\ntype ColumnMappings = Record<string, string | null>;\n\nexport type EnumColumnMappings = Map<string, Map<string, ColumnMappings>>;\n\n/**\n * Detects enum value removals that need resolution.\n * Returns one removal per column that uses the enum.\n * Nullability never supplies a data-mapping decision.\n */\nexport function detectEnumValueRemovals(\n operations: DiffOperation[],\n currentSchema: SchemaSnapshot\n): EnumRemoval[] {\n const removals: EnumRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n const unresolvedValues = op.removeValues.filter((value) => {\n const hasExplicit =\n op.valueReplacements !== undefined && value in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n const dependentColumns = op.dependentColumns || [];\n\n for (const dependentColumn of dependentColumns) {\n const table = currentSchema.tables.find(\n (tableDef) => tableDef.name === dependentColumn.tableName\n );\n if (!table) {\n throw new MigrationError(\n `Table \"${dependentColumn.tableName}\" not found in current schema for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n const column = table.columns.find(\n (columnDef) => columnDef.name === dependentColumn.columnName\n );\n if (!column) {\n throw new MigrationError(\n `Column \"${dependentColumn.columnName}\" not found in table \"${dependentColumn.tableName}\" for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n removals.push({\n enumName: op.enumName,\n tableName: dependentColumn.tableName,\n columnName: dependentColumn.columnName,\n isNullable: column.nullable,\n removedValues: unresolvedValues,\n availableValues: op.newValues || [],\n });\n }\n }\n }\n }\n\n return removals;\n}\n\n/**\n * Applies force mode resolutions for enum value removals.\n * Sets all removed values to NULL for each column.\n */\nexport function applyForceEnumResolutions(\n operations: DiffOperation[],\n enumRemovals: EnumRemoval[]\n): DiffOperation[] {\n if (enumRemovals.length === 0) {\n return operations;\n }\n\n const removalsByEnum = new Map<string, EnumRemoval[]>();\n for (const removal of enumRemovals) {\n const existing = removalsByEnum.get(removal.enumName) || [];\n existing.push(removal);\n removalsByEnum.set(removal.enumName, existing);\n }\n\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const removals = removalsByEnum.get(op.enumName);\n if (!removals || removals.length === 0) {\n return op;\n }\n\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const removal of removals) {\n const columnKey = getColumnKey(removal);\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...createNullMappings(removal.removedValues),\n };\n }\n\n return {\n ...op,\n columnValueReplacements,\n };\n });\n}\n\nexport async function resolveEnumValueRemovalMappings(\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force: boolean\n): Promise<EnumColumnMappings> {\n const columnMappings: EnumColumnMappings = new Map();\n\n for (const removal of enumRemovals) {\n const change = createEnumValueRemovalChange({\n enumName: removal.enumName,\n tableName: removal.tableName,\n columnName: removal.columnName,\n isNullable: removal.isNullable,\n removedValues: removal.removedValues,\n availableValues: removal.availableValues,\n description:\n `Column \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - ` +\n `removing values: ${removal.removedValues.join(\", \")}. ` +\n `Map to: ${removal.availableValues.join(\", \")} or NULL`,\n });\n\n const result = validateResolveResult(\n \"enumValueRemoval\",\n change,\n await resolve(change)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n const columnKey = getColumnKey(removal);\n\n if (result === undefined) {\n if (force) {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n } else {\n throw new MigrationError(\n `Unresolved enum value removal: ${change.description}\\n` +\n \"Return change.mapValues() or change.useNull() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"enumMapped\") {\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n decision.mappings\n );\n } else if (decision?.kind === \"useNull\") {\n setColumnMappings(\n columnMappings,\n removal.enumName,\n columnKey,\n createNullMappings(removal.removedValues)\n );\n }\n }\n }\n\n return columnMappings;\n}\n\nexport function applyResolvedEnumMappings(\n operations: DiffOperation[],\n columnMappings: EnumColumnMappings\n): DiffOperation[] {\n const enumOperations: DiffOperation[] = [];\n\n for (const op of operations) {\n if (op.type === \"alterEnum\") {\n const enumColumnMappings = columnMappings.get(op.enumName);\n if (enumColumnMappings && enumColumnMappings.size > 0) {\n const columnValueReplacements: Record<string, ColumnMappings> = {\n ...op.columnValueReplacements,\n };\n\n for (const [columnKey, mappings] of enumColumnMappings) {\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...mappings,\n };\n }\n\n enumOperations.push({\n ...op,\n columnValueReplacements,\n });\n } else {\n enumOperations.push(op);\n }\n }\n }\n\n return enumOperations;\n}\n\nfunction setColumnMappings(\n columnMappings: EnumColumnMappings,\n enumName: string,\n columnKey: string,\n mappings: ColumnMappings\n): void {\n let enumMappings = columnMappings.get(enumName);\n if (!enumMappings) {\n enumMappings = new Map();\n columnMappings.set(enumName, enumMappings);\n }\n enumMappings.set(columnKey, mappings);\n}\n\nfunction createNullMappings(values: string[]): Record<string, null> {\n const nullMappings: Record<string, null> = {};\n for (const value of values) {\n nullMappings[value] = null;\n }\n return nullMappings;\n}\n\nfunction getColumnKey(removal: EnumRemoval): string {\n return `${removal.tableName}.${removal.columnName}`;\n}\n","import { sqliteGeoPointEncoding } from \"../adapters/databases/sqlite/storage/geo-point\";\n\n/**\n * Schema Differ\n *\n * Compares two SchemaSnapshots and produces a list of DiffOperations,\n * detecting ambiguous changes that require user input.\n */\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n decimalChangeNarrows,\n describeDecimalDomain,\n migrationDecimalStorageKind,\n} from \"./decimal\";\nimport type { applyNativeRename } from \"./native-rename\";\nimport { inlineEnumValues } from \"./push/enum-removals\";\nimport {\n canonicalUniqueEntities,\n normalizeDefault,\n normalizeType,\n} from \"./push-fingerprint\";\nimport type {\n AmbiguousChange,\n ColumnDef,\n DiffOperation,\n DiffResult,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\n\n// =============================================================================\n// PARTIAL-INDEX PREDICATE CANONICALIZATION (Decision 7.4)\n// =============================================================================\n\n/**\n * Asks the database for its own spelling of each declared index predicate.\n *\n * The differ has no connection of its own; the push path owns one and hands\n * this in (`planPush`). One call carries every predicate of one table, so the\n * round trip is paid once per table that has a partial index whose two\n * spellings differ — usually never, at most once per push.\n *\n * The result is positional. `undefined` at a position means the database did\n * not answer for that predicate, and the differ then treats it as\n * uncomparable — never as equal.\n */\nexport type IndexPredicateCanonicalizer = (\n tableName: string,\n predicates: readonly string[]\n) => Promise<ReadonlyArray<string | undefined>>;\n\nexport interface DiffOptions {\n /**\n * Compares the declared SQLite DateTime storage vocabulary carried by V1\n * snapshots. Enable only when both sides preserve that declaration. Live\n * SQLite introspection cannot recover it from TEXT, INTEGER, or REAL and\n * therefore leaves this off so an unchanged push does not drift forever.\n */\n compareDateTimeDeclarations?: boolean;\n\n /**\n * Canonicalizes partial-index predicates through the live database. Omitted\n * by callers with no connection (`generate`, which diffs two snapshots) and\n * by dialects whose catalog stores the declared statement verbatim; the\n * differ then compares the two texts raw, which is the fail-closed reading.\n */\n canonicalizeIndexPredicate?: IndexPredicateCanonicalizer;\n\n /**\n * Recognizes a foreign key and a unique constraint by its SHAPE instead of by\n * its name — see `foreignKeyShape` below for why, and for what breaks without\n * it. Set by `planPush` from the migration driver's\n * `introspectionReadsConstraintNames` capability; left off by `generate`,\n * which diffs two snapshots the serializer wrote and where every name is\n * therefore the declared one.\n */\n matchConstraintsByShape?: boolean;\n\n /** Effectful planning admission; diagnostic diffs must retain drift evidence. */\n refuseConstraintNameChurn?: boolean;\n\n /** The exact producer's additional physical effects of an accepted rename. */\n projectRename?: typeof applyNativeRename;\n}\n\n/** Canonical spellings, keyed by table and by the predicate as declared. */\ntype CanonicalPredicates = ReadonlyMap<string, string>;\n\nconst EMPTY_CANONICAL_PREDICATES: CanonicalPredicates = new Map();\n\n/** NUL joins the halves: no table name and no SQL text can contain one. */\nfunction predicateKey(tableName: string, predicate: string): string {\n return `${tableName}\\u0000${predicate}`;\n}\n\n/**\n * Asks the database for its spelling of every predicate that a partial index\n * present in both snapshots spells two ways.\n *\n * Scoped on purpose. A predicate only one side carries, or that both sides\n * spell identically, is settled without a round trip — so a schema with no\n * partial index, or one that already converged, costs nothing.\n */\nasync function canonicalizeChangedPredicates(\n currentTables: ReadonlyMap<string, TableDef>,\n desiredTables: ReadonlyMap<string, TableDef>,\n canonicalize: IndexPredicateCanonicalizer | undefined\n): Promise<CanonicalPredicates> {\n if (!canonicalize) return EMPTY_CANONICAL_PREDICATES;\n\n const canonical = new Map<string, string>();\n\n for (const [tableName, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(tableName);\n if (!currentTable) continue;\n\n const currentIndexes = new Map(\n currentTable.indexes.map((i) => [i.name, i])\n );\n const pending = new Set<string>();\n\n for (const desiredIndex of desiredTable.indexes) {\n const currentIndex = currentIndexes.get(desiredIndex.name);\n if (!currentIndex) continue;\n const left = normalizeIndexWhere(currentIndex.where);\n const right = normalizeIndexWhere(desiredIndex.where);\n if (left === undefined || right === undefined || left === right) continue;\n pending.add(left);\n pending.add(right);\n }\n\n if (pending.size === 0) continue;\n\n const predicates = [...pending];\n const spellings = await canonicalize(tableName, predicates);\n for (const [position, predicate] of predicates.entries()) {\n const spelling = spellings[position];\n if (spelling !== undefined) {\n canonical.set(predicateKey(tableName, predicate), spelling);\n }\n }\n }\n\n return canonical;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction columnPropertiesEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n normalizeType(a.type) === normalizeType(b.type) &&\n a.nullable === b.nullable &&\n normalizeDefault(a.default, a.type) ===\n normalizeDefault(b.default, b.type) &&\n // The declared domain is compared beside the physical type, not instead of\n // it, because the two carry different amounts of the fact per dialect: a\n // PostgreSQL `numeric(10,5)` spells its whole domain in the type, while a\n // SQLite decimal is `INTEGER` (or `TEXT` for a list) at every precision and\n // scale there is. Left out, a SQLite descriptor change plans NOTHING —\n // the type is byte-identical on both sides — and the column silently keeps\n // storing coefficients at the old scale.\n sqliteGeoPointEncoding(a) === sqliteGeoPointEncoding(b) &&\n sameDecimalDescriptor(a.decimal, b.decimal) &&\n (!compareDateTimeDeclarations || a.dateTime === b.dateTime)\n );\n}\n\nfunction columnsEqual(\n a: ColumnDef,\n b: ColumnDef,\n compareDateTimeDeclarations: boolean\n): boolean {\n return (\n a.name === b.name &&\n columnPropertiesEqual(a, b, compareDateTimeDeclarations)\n );\n}\n\nfunction columnsCanBeRenamed(a: ColumnDef, b: ColumnDef): boolean {\n if (normalizeType(a.type) === normalizeType(b.type)) return true;\n const aDecimalKind = migrationDecimalStorageKind(a);\n return (\n aDecimalKind !== undefined &&\n aDecimalKind === migrationDecimalStorageKind(b)\n );\n}\n\nfunction normalizeIndexType(type: IndexDef[\"type\"]): string {\n // An index with no declared type is a B-tree on every dialect. The two\n // snapshot producers spell that differently — introspection reads \"btree\"\n // back from the Postgres/MySQL catalog, SQLite reports no type at all, and\n // the serializer leaves an undeclared type undefined — so the same index\n // must not read as a change.\n return type ?? \"btree\";\n}\n\nfunction normalizeIndexUnique(unique: IndexDef[\"unique\"]): boolean {\n // `type`'s twin (above): the serializer leaves a plain `.index()`'s `unique`\n // undefined while every introspection reads a boolean back from the catalog,\n // so the same index must not read as a change. Left raw, every push re-plans\n // drop+create forever — and on MySQL the drop is a hard 1553 abort when the\n // declared index is the one InnoDB bound the FK to.\n return unique ?? false;\n}\n\nfunction normalizeIndexWhere(where: IndexDef[\"where\"]): string | undefined {\n // `type`'s and `unique`'s third twin, and the one place the partial index's\n // two spellings are reconciled. The serializer passes the declared predicate\n // through untouched; the emitter writes ` WHERE ${where}`, and SQLite stores\n // that statement verbatim, padding and all. Reading it back consumes the\n // whitespace run that separates `WHERE` from the predicate, so a declaration\n // written with padding comes back without its leading part — the same index\n // in two spellings. Left raw, every push re-plans drop+create forever.\n const trimmed = where?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * The one place the two snapshots' predicates are compared, and the reader of\n * the canonical spellings the database supplied (Decision 7.4).\n *\n * `normalizeIndexWhere` above reconciles the *padding* of one text; it cannot\n * reconcile two texts. PostgreSQL's catalog does not store the declared\n * statement — `pg_get_expr(indpred, indrelid)` deparses it, so a declared\n * `published = true` reads back as `(published = true)`, and every push drops\n * and re-creates every partial index. No client-side normalization closes that\n * while staying fail-closed: flatten whitespace and parentheses and\n * `a AND (b OR c)` starts comparing equal to `(a AND b) OR c`, so a real change\n * would stop being seen. So the database is asked, and `canonical` holds what\n * it answered. Two predicates are the same predicate only when BOTH were\n * canonicalized and the two canonical spellings are identical.\n */\nfunction indexWhereEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n const left = normalizeIndexWhere(a.where);\n const right = normalizeIndexWhere(b.where);\n if (left === right) return true;\n // A predicate that appears or disappears is a real change on every dialect,\n // and no round trip can make a partial index equal to a total one.\n if (left === undefined || right === undefined) return false;\n\n const leftCanonical = canonical.get(predicateKey(tableName, left));\n const rightCanonical = canonical.get(predicateKey(tableName, right));\n // Fail closed. Without both spellings — no canonicalizer, a dialect that has\n // none, a connection that refused, a predicate the database could not parse —\n // two texts that do not read alike stay a change.\n return leftCanonical !== undefined && leftCanonical === rightCanonical;\n}\n\nfunction indexesEqual(\n tableName: string,\n a: IndexDef,\n b: IndexDef,\n canonical: CanonicalPredicates\n): boolean {\n return (\n a.name === b.name &&\n normalizeIndexUnique(a.unique) === normalizeIndexUnique(b.unique) &&\n arraysEqual(a.columns, b.columns) &&\n normalizeIndexType(a.type) === normalizeIndexType(b.type) &&\n indexWhereEqual(tableName, a, b, canonical)\n );\n}\n\nfunction arraysEqual<T>(a: T[], b: T[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n}\n\n// =============================================================================\n// CONSTRAINT IDENTITY\n// =============================================================================\n\nfunction normalizeReferentialAction(\n action: ReferentialAction | undefined\n): ReferentialAction {\n // `normalizeIndexUnique`'s twin on the foreign-key side. Every introspection\n // reads a concrete action back from the catalog — \"NO ACTION\" when the DDL\n // declared none — while a snapshot may leave it undefined, and both spell the\n // same constraint: SQLite and MySQL omit the clause for `noAction`,\n // PostgreSQL writes `ON DELETE NO ACTION`, which is what omitting it means.\n // Left raw, the same key reads as a change and is dropped and re-added on\n // every push.\n return action ?? \"noAction\";\n}\n\n/**\n * What a foreign key IS, with the name left out: the columns it binds, what\n * they point at, and what happens on delete and on update. NUL joins the\n * columns and SOH the parts — no SQL identifier and no action name holds\n * either, so two shapes read alike only when every part does.\n *\n * The name is left out because on some dialects it is not readable. On\n * PostgreSQL and MySQL the catalog carries the name the DDL gave the\n * constraint, so a name IS an identity there and the differ matches on it.\n * SQLite carries no name for either constraint this file matches:\n * `PRAGMA foreign_key_list` has no name column at all, so introspection\n * synthesises `<table>_fk_<n>`, and an inline `CONSTRAINT x UNIQUE (...)` is\n * reported only under SQLite's own `sqlite_autoindex_<table>_<n>`. Matched by\n * name, the declared constraint is therefore missing and the read one extra on\n * every push of an unchanged schema, forever — and the two repairs the differ\n * plans are both wrong:\n *\n * - the foreign key is dropped and re-added, and SQLite has no\n * `ALTER TABLE ADD FOREIGN KEY`, so each of those rebuilds the whole table\n * — copy included — twice per push, for a schema nobody edited;\n * - the unique constraint's drop is `DROP INDEX \"sqlite_autoindex_...\"`,\n * which SQLite refuses (\"index associated with UNIQUE or PRIMARY KEY\n * constraint cannot be dropped\"), so the SECOND push of any SQLite schema\n * carrying a compound unique fails outright.\n *\n * So where the name cannot be read, the shape is the identity: two constraints\n * of one shape are one constraint, whatever the reader called them.\n */\nfunction foreignKeyShape(fk: ForeignKeyDef): string {\n return [\n fk.columns.join(\"\\u0000\"),\n fk.referencedTable,\n fk.referencedColumns.join(\"\\u0000\"),\n normalizeReferentialAction(fk.onDelete),\n normalizeReferentialAction(fk.onUpdate),\n ].join(\"\\u0001\");\n}\n\n/** `foreignKeyShape`'s twin: a unique constraint is its column list. */\nfunction uniqueConstraintShape(constraint: UniqueConstraintDef): string {\n return constraint.columns.join(\"\\u0000\");\n}\n\n/**\n * Pairs each `current` constraint with the `desired` one it is, under whichever\n * identity the dialect supports, and reports what `desired` had left over.\n *\n * Multisets, not maps, on purpose. A database written before\n * `SQLite3MigrationDriver.getCurrentTable` learned to replay the batch can hold\n * several byte-identical foreign keys on one table — they accumulated, one per\n * push, without bound. Keying by identity alone would collapse those into one\n * entry and leave the extras attached forever; pairing k of n leaves n-k\n * unmatched, and unmatched is what gets dropped.\n */\nfunction matchByIdentity<T>(\n current: readonly T[],\n desired: readonly T[],\n identityOf: (item: T) => string\n): { matches: Array<T | undefined>; unmatchedDesired: T[] } {\n const availableByIdentity = new Map<string, number[]>();\n for (const [position, item] of desired.entries()) {\n const identity = identityOf(item);\n const positions = availableByIdentity.get(identity);\n if (positions) {\n positions.push(position);\n } else {\n availableByIdentity.set(identity, [position]);\n }\n }\n\n const consumed = new Set<number>();\n const matches = current.map((item) => {\n const position = availableByIdentity.get(identityOf(item))?.shift();\n if (position === undefined) return undefined;\n consumed.add(position);\n return desired[position];\n });\n\n return {\n matches,\n unmatchedDesired: desired.filter(\n (_, position) => !consumed.has(position)\n ) as T[],\n };\n}\n\nfunction enumsEqual(a: EnumDef, b: EnumDef): boolean {\n return a.name === b.name && arraysEqual(a.values, b.values);\n}\n\n// =============================================================================\n// TABLE DIFFER\n// =============================================================================\n\ninterface TableDiffResult {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n}\n\nfunction refuseConstraintNameMismatch(\n table: string,\n actual: string,\n desired: string\n): never {\n throw new MigrationError(\n `Constraint \"${table}.${actual}\" already enforces the desired definition under a different physical name (\"${desired}\"). This declaration cannot faithfully adopt that name. Synchronization refuses before effects instead of dropping and recreating an equivalent constraint. Public key names select fields; they do not declare physical constraint names.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table, constraint: actual } }\n );\n}\n\nfunction diffTable(\n tableName: string,\n current: TableDef,\n desired: TableDef,\n canonical: CanonicalPredicates,\n matchConstraintsByShape: boolean,\n compareDateTimeDeclarations: boolean,\n refuseConstraintNameChurn: boolean\n): TableDiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n if (!matchConstraintsByShape && refuseConstraintNameChurn) {\n for (const constraint of desired.foreignKeys) {\n if (current.foreignKeys.some((actual) => actual.name === constraint.name))\n continue;\n const actual = current.foreignKeys.find(\n (actual) => foreignKeyShape(actual) === foreignKeyShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n for (const constraint of desired.uniqueConstraints) {\n if (\n current.uniqueConstraints.some(\n (actual) => actual.name === constraint.name\n )\n )\n continue;\n const actual = current.uniqueConstraints.find(\n (actual) =>\n uniqueConstraintShape(actual) === uniqueConstraintShape(constraint)\n );\n if (actual)\n refuseConstraintNameMismatch(tableName, actual.name, constraint.name);\n }\n const currentPk = current.primaryKey,\n desiredPk = desired.primaryKey;\n if (\n currentPk &&\n desiredPk &&\n arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n const actual = currentPk.name ?? `${tableName}_pkey`,\n wanted = desiredPk.name ?? `${tableName}_pkey`;\n if (actual !== wanted)\n refuseConstraintNameMismatch(tableName, actual, wanted);\n }\n }\n\n // Build column maps\n const currentColumns = new Map(current.columns.map((c) => [c.name, c]));\n const desiredColumns = new Map(desired.columns.map((c) => [c.name, c]));\n\n // Find dropped and added columns\n const droppedColumns: ColumnDef[] = [];\n const addedColumns: ColumnDef[] = [];\n\n for (const [name, col] of currentColumns) {\n if (!desiredColumns.has(name)) {\n droppedColumns.push(col);\n }\n }\n\n for (const [name, col] of desiredColumns) {\n if (!currentColumns.has(name)) {\n addedColumns.push(col);\n }\n }\n\n // Detect potential column renames (ambiguous changes)\n // A rename is suspected when a column is dropped and another is added\n // with compatible types\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n for (const dropped of droppedColumns) {\n for (const added of addedColumns) {\n if (usedDropped.has(dropped.name) || usedAdded.has(added.name)) continue;\n\n if (columnsCanBeRenamed(dropped, added)) {\n // This could be a rename - mark as ambiguous\n ambiguousChanges.push({\n type: \"ambiguousColumn\",\n tableName,\n droppedColumn: dropped,\n addedColumn: added,\n });\n usedDropped.add(dropped.name);\n usedAdded.add(added.name);\n }\n }\n }\n\n // Add operations for non-ambiguous drops and adds\n for (const dropped of droppedColumns) {\n if (!usedDropped.has(dropped.name)) {\n operations.push({\n type: \"dropColumn\",\n tableName,\n columnName: dropped.name,\n });\n }\n }\n\n for (const added of addedColumns) {\n if (!usedAdded.has(added.name)) {\n operations.push({\n type: \"addColumn\",\n tableName,\n column: added,\n });\n }\n }\n\n // Check for column modifications (same name, different properties)\n for (const [name, desiredCol] of desiredColumns) {\n const currentCol = currentColumns.get(name);\n if (\n currentCol &&\n !columnsEqual(currentCol, desiredCol, compareDateTimeDeclarations)\n ) {\n const previousValues = inlineEnumValues(currentCol.type);\n const nextValues = inlineEnumValues(desiredCol.type);\n if (\n previousValues &&\n nextValues &&\n normalizeType(currentCol.type) !== normalizeType(desiredCol.type)\n ) {\n operations.push({\n type: \"alterEnum\",\n enumName: desiredCol.type,\n newValues: nextValues,\n addValues: nextValues.filter(\n (value) => !previousValues.includes(value)\n ),\n removeValues: previousValues.filter(\n (value) => !nextValues.includes(value)\n ),\n dependentColumns: [{ tableName, columnName: name }],\n });\n const converted = { ...currentCol, type: desiredCol.type };\n if (\n !columnPropertiesEqual(\n converted,\n desiredCol,\n compareDateTimeDeclarations\n )\n )\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: converted,\n to: desiredCol,\n });\n } else {\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: currentCol,\n to: desiredCol,\n });\n }\n }\n }\n\n // Diff indexes\n const currentIndexes = new Map(current.indexes.map((i) => [i.name, i]));\n const desiredIndexes = new Map(desired.indexes.map((i) => [i.name, i]));\n\n for (const [name, idx] of currentIndexes) {\n const desiredIdx = desiredIndexes.get(name);\n if (!desiredIdx) {\n operations.push({ type: \"dropIndex\", tableName, indexName: name });\n } else if (!indexesEqual(tableName, idx, desiredIdx, canonical)) {\n // Index changed - drop and recreate\n operations.push({ type: \"dropIndex\", tableName, indexName: name });\n operations.push({ type: \"createIndex\", tableName, index: desiredIdx });\n }\n }\n\n for (const [name, idx] of desiredIndexes) {\n if (!currentIndexes.has(name)) {\n operations.push({ type: \"createIndex\", tableName, index: idx });\n }\n }\n\n // Diff foreign keys, under whichever identity this dialect's introspection\n // supports (see `foreignKeyShape`).\n const fkMatch = matchByIdentity(\n current.foreignKeys,\n desired.foreignKeys,\n matchConstraintsByShape ? foreignKeyShape : (fk) => fk.name\n );\n\n for (const [position, fk] of current.foreignKeys.entries()) {\n const desiredFk = fkMatch.matches[position];\n if (!desiredFk) {\n operations.push({ type: \"dropForeignKey\", tableName, fkName: fk.name });\n } else if (foreignKeyShape(fk) !== foreignKeyShape(desiredFk)) {\n // The pair is the same constraint under a name; its definition changed,\n // so drop and recreate. Under shape identity a pair IS one shape, so this\n // is the name-identity dialects' branch — it is where a changed\n // referential action or referenced column is caught on Postgres and\n // MySQL, and where SQLite's own drop-and-add falls out of the definition\n // having actually changed rather than out of an unreadable name.\n operations.push({ type: \"dropForeignKey\", tableName, fkName: fk.name });\n operations.push({ type: \"addForeignKey\", tableName, fk: desiredFk });\n }\n }\n\n for (const fk of fkMatch.unmatchedDesired) {\n operations.push({ type: \"addForeignKey\", tableName, fk });\n }\n\n // Diff unique constraints — same identity question, same answer.\n const uniqueMatch = matchByIdentity(\n current.uniqueConstraints,\n desired.uniqueConstraints,\n matchConstraintsByShape ? uniqueConstraintShape : (uq) => uq.name\n );\n\n for (const [position, uq] of current.uniqueConstraints.entries()) {\n const desiredUq = uniqueMatch.matches[position];\n if (!desiredUq) {\n operations.push({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: uq.name,\n });\n } else if (uniqueConstraintShape(uq) !== uniqueConstraintShape(desiredUq)) {\n operations.push({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: uq.name,\n });\n operations.push({\n type: \"addUniqueConstraint\",\n tableName,\n constraint: desiredUq,\n });\n }\n }\n\n for (const constraint of uniqueMatch.unmatchedDesired) {\n operations.push({\n type: \"addUniqueConstraint\",\n tableName,\n constraint,\n });\n }\n\n // Diff primary key\n const currentPk = current.primaryKey;\n const desiredPk = desired.primaryKey;\n\n if (currentPk && !desiredPk) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n } else if (!currentPk && desiredPk) {\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n } else if (\n currentPk &&\n desiredPk &&\n !arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n }\n\n return { operations, ambiguousChanges };\n}\n\n// =============================================================================\n// MAIN DIFFER\n// =============================================================================\n\n/**\n * Compares two schema snapshots and returns the operations needed to\n * transform the current schema into the desired schema.\n */\nexport async function diff(\n physicalCurrent: SchemaSnapshot,\n physicalDesired: SchemaSnapshot,\n options: DiffOptions = {}\n): Promise<DiffResult> {\n const current = canonicalUniqueEntities(physicalCurrent);\n const desired = canonicalUniqueEntities(physicalDesired);\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Logical polymorphic vocabulary is persisted only in authored snapshots.\n // Never publish an empty transition which changes the meaning of stored ids.\n for (const previous of current.polymorphicStorage ?? []) {\n const next = desired.polymorphicStorage?.find(\n (item) =>\n item.ownerTable === previous.ownerTable &&\n item.relation === previous.relation &&\n item.kind === previous.kind\n );\n if (!next) continue;\n for (const member of previous.members) {\n const destination = next.members.find(\n (item) => item.publicType === member.publicType\n );\n if (\n destination &&\n (destination.storedType !== member.storedType ||\n destination.targetTable !== member.targetTable)\n ) {\n throw new MigrationError(\n `Polymorphic storage \"${previous.ownerTable}.${previous.relation}\" changes stored meaning for \"${member.publicType}\"; author an explicit manual data transition`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n }\n }\n\n // Build table maps\n const currentTables = new Map(current.tables.map((t) => [t.name, t]));\n const desiredTables = new Map(desired.tables.map((t) => [t.name, t]));\n\n const canonicalPredicates = await canonicalizeChangedPredicates(\n currentTables,\n desiredTables,\n options.canonicalizeIndexPredicate\n );\n\n // Find dropped and added tables\n const droppedTables: string[] = [];\n const addedTables: string[] = [];\n\n for (const [name] of currentTables) {\n if (!desiredTables.has(name)) {\n droppedTables.push(name);\n }\n }\n\n for (const [name] of desiredTables) {\n if (!currentTables.has(name)) {\n addedTables.push(name);\n }\n }\n\n // Detect potential table renames (ambiguous changes)\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // Similarity orders questions, never answers them: even a zero-overlap\n // drop/create pair still requires an explicit author decision. Present the\n // strongest matches first so an unrelated drop cannot consume a clear rename.\n const candidates = droppedTables\n .flatMap((droppedName) => {\n const droppedTable = currentTables.get(droppedName)!;\n return addedTables.map((addedName) => {\n const addedTable = desiredTables.get(addedName)!;\n const matchingColumns = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => columnsEqual(column, other, true))\n ).length;\n const matchingNames = droppedTable.columns.filter((column) =>\n addedTable.columns.some((other) => column.name === other.name)\n ).length;\n return {\n droppedName,\n addedName,\n droppedTable,\n addedTable,\n matchingColumns,\n matchingNames,\n };\n });\n })\n .sort(\n (a, b) =>\n b.matchingNames - a.matchingNames ||\n b.matchingColumns - a.matchingColumns\n );\n for (const candidate of candidates) {\n const { droppedName, addedName, droppedTable, addedTable } = candidate;\n if (usedDropped.has(droppedName) || usedAdded.has(addedName)) continue;\n ambiguousChanges.push({\n type: \"ambiguousTable\",\n droppedTable: droppedName,\n addedTable: addedName,\n droppedTableDef: droppedTable,\n addedTableDef: addedTable,\n });\n usedDropped.add(droppedName);\n usedAdded.add(addedName);\n }\n\n // Add operations for non-ambiguous table drops and creates\n for (const name of droppedTables) {\n if (!usedDropped.has(name)) {\n operations.push({ type: \"dropTable\", tableName: name });\n }\n }\n\n for (const name of addedTables) {\n if (!usedAdded.has(name)) {\n const table = desiredTables.get(name)!;\n operations.push({ type: \"createTable\", table });\n }\n }\n\n // Diff existing tables\n for (const [name, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(name);\n if (currentTable) {\n const tableDiff = diffTable(\n name,\n currentTable,\n desiredTable,\n canonicalPredicates,\n options.matchConstraintsByShape ?? false,\n options.compareDateTimeDeclarations ?? false,\n options.refuseConstraintNameChurn ?? false\n );\n operations.push(...tableDiff.operations);\n ambiguousChanges.push(...tableDiff.ambiguousChanges);\n }\n }\n\n // Diff enums (PostgreSQL specific)\n if (current.enums || desired.enums) {\n const currentEnums = new Map((current.enums || []).map((e) => [e.name, e]));\n const desiredEnums = new Map((desired.enums || []).map((e) => [e.name, e]));\n\n // Dropped enums\n for (const [name] of currentEnums) {\n if (!desiredEnums.has(name)) {\n // Find all columns that depend on this enum\n const dependentColumns: Array<{\n tableName: string;\n columnName: string;\n }> = [];\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n operations.push({\n type: \"dropEnum\",\n enumName: name,\n dependentColumns:\n dependentColumns.length > 0 ? dependentColumns : undefined,\n });\n }\n }\n\n // Added enums\n for (const [name, enumDef] of desiredEnums) {\n if (!currentEnums.has(name)) {\n operations.push({ type: \"createEnum\", enumDef });\n }\n }\n\n // Modified enums\n for (const [name, desiredEnum] of desiredEnums) {\n const currentEnum = currentEnums.get(name);\n if (currentEnum && !enumsEqual(currentEnum, desiredEnum)) {\n const addValues = desiredEnum.values.filter(\n (v) => !currentEnum.values.includes(v)\n );\n const removeValues = currentEnum.values.filter(\n (v) => !desiredEnum.values.includes(v)\n );\n\n if (\n addValues.length > 0 ||\n removeValues.length > 0 ||\n !arraysEqual(currentEnum.values, desiredEnum.values)\n ) {\n // When removing values, we need to find all columns that use this enum\n // so we can temporarily convert them to text during the recreation\n let dependentColumns:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n dependentColumns = [];\n // Search through all tables (current schema) for columns using this enum\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name || column.type === `${name}[]`) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n\n operations.push({\n type: \"alterEnum\",\n enumName: name,\n addValues: addValues.length > 0 ? addValues : undefined,\n removeValues: removeValues.length > 0 ? removeValues : undefined,\n newValues: desiredEnum.values,\n dependentColumns:\n dependentColumns && dependentColumns.length > 0\n ? dependentColumns\n : undefined,\n });\n }\n }\n }\n }\n\n // Sort operations for proper execution order\n return {\n operations: sortOperations(\n operations.map((operation): DiffOperation => {\n if (operation.type === \"createTable\")\n return {\n ...operation,\n table:\n physicalDesired.tables.find(\n (table) => table.name === operation.table.name\n ) ?? operation.table,\n };\n if (operation.type === \"addUniqueConstraint\") {\n const index = physicalDesired.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraint.name);\n if (index)\n return {\n type: \"createIndex\",\n tableName: operation.tableName,\n index,\n };\n }\n if (operation.type === \"dropUniqueConstraint\") {\n const index = physicalCurrent.tables\n .find((table) => table.name === operation.tableName)\n ?.indexes.find((item) => item.name === operation.constraintName);\n if (index)\n return {\n type: \"dropIndex\",\n tableName: operation.tableName,\n indexName: index.name,\n };\n }\n return operation;\n })\n ),\n ambiguousChanges,\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE OPERATION CHECKS\n// =============================================================================\n\n/** The one destructive-operation classification used by every consumer. */\nexport function isDestructiveOperation(operation: DiffOperation): boolean {\n if (operation.type === \"alterEnum\")\n return (operation.removeValues?.length ?? 0) > 0;\n if (operation.type === \"addColumn\")\n return !operation.column.nullable && operation.column.default === undefined;\n if (operation.type === \"dropTable\" || operation.type === \"dropColumn\") {\n return true;\n }\n return (\n operation.type === \"alterColumn\" &&\n (normalizeType(operation.from.type) !== normalizeType(operation.to.type) ||\n (operation.from.nullable && !operation.to.nullable) ||\n decimalChangeNarrows(operation.from, operation.to))\n );\n}\n\n/** Checks if any operation can cause data loss or refuse existing rows. */\nexport function hasDestructiveOperations(operations: DiffOperation[]): boolean {\n return operations.some(isDestructiveOperation);\n}\n\n/**\n * Gets a human-readable description of destructive operations\n */\nexport function getDestructiveOperationDescriptions(\n operations: DiffOperation[]\n): string[] {\n const descriptions: string[] = [];\n\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n descriptions.push(`Drop table \"${op.tableName}\" (all data will be lost)`);\n } else if (op.type === \"dropColumn\") {\n descriptions.push(\n `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`\n );\n } else if (op.type === \"alterColumn\") {\n if (normalizeType(op.from.type) !== normalizeType(op.to.type)) {\n descriptions.push(\n `Change type of \"${op.tableName}\".\"${op.columnName}\" from ${op.from.type} to ${op.to.type} (may cause data loss)`\n );\n }\n if (op.from.nullable && !op.to.nullable) {\n descriptions.push(\n `Make \"${op.tableName}\".\"${op.columnName}\" NOT NULL (may fail if column contains NULL values)`\n );\n }\n if (\n op.from.decimal &&\n op.to.decimal &&\n decimalChangeNarrows(op.from, op.to)\n ) {\n // The numbers go in the SENTENCE: `precision` and `scale` are not\n // error-metadata keys, so a refusal that put them in `meta` would drop\n // them silently.\n descriptions.push(\n `Narrow the decimal domain of \"${op.tableName}\".\"${op.columnName}\" from ${describeDecimalDomain(op.from.decimal)} to ${describeDecimalDomain(op.to.decimal)} (the conversion refuses every value that no longer fits, rather than rounding it)`\n );\n }\n }\n }\n\n return descriptions;\n}\n","/**\n * Inverse owner for generated DiffOperation programs.\n * Empty programs invert to an empty schema rollback. Missing inverses are\n * irreversible. This is the only place that answers that question.\n */\n\nimport { applyNativeRename } from \"./native-rename\";\nimport type { DiffOperation, SchemaSnapshot, TableDef } from \"./types\";\nimport { defaultGeneratedPrimaryKeyName } from \"./utils\";\n\nexport interface InvertedOperations {\n operations: DiffOperation[];\n warnings: string[];\n}\n\nexport function invertOperations(\n operations: DiffOperation[],\n previousSnapshot: SchemaSnapshot,\n projectRename: typeof applyNativeRename = applyNativeRename,\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName = defaultGeneratedPrimaryKeyName\n): InvertedOperations {\n const warnings: string[] = [];\n const inverted: DiffOperation[] = [];\n // At the inverse of operation i, every rename that preceded i in the up\n // program is still active and every rename that followed it has already been\n // inverted. Keep the previous definitions at each exact prefix so a restored\n // FK targets the identity that exists at that point — neither always-old nor\n // always-new is correct.\n let previousAtOperationIdentity = previousSnapshot;\n const previousIdentityBefore: SchemaSnapshot[] = [];\n // A key the up program drops by itself (PostgreSQL/MySQL drop every key of\n // a dropped table first) comes back through that drop's own inverse, which\n // runs after every recreated table exists. The recreated table leaves it\n // out: restored inline it would name a table not yet recreated, and then be\n // added a second time.\n const keysRestoredByTheirOwnInverse = new Set<string>();\n for (const op of operations) {\n previousIdentityBefore.push(previousAtOperationIdentity);\n if (op.type === \"dropForeignKey\") {\n keysRestoredByTheirOwnInverse.add(\n foreignKeyIdentity(op.tableName, op.fkName)\n );\n }\n if (op.type === \"renameTable\" || op.type === \"renameColumn\") {\n previousAtOperationIdentity = projectRename(\n previousAtOperationIdentity,\n op\n );\n }\n }\n\n for (let i = operations.length - 1; i >= 0; i--) {\n const op = operations[i]!;\n const previousAtIdentity = previousIdentityBefore[i] ?? previousSnapshot;\n const findPrevTable = (name: string): TableDef | undefined =>\n previousAtIdentity.tables.find((table) => table.name === name);\n const inverse = invertOperation(\n op,\n previousSnapshot,\n findPrevTable,\n keysRestoredByTheirOwnInverse,\n warnings,\n primaryKeyName\n );\n if (inverse) inverted.push(...inverse);\n }\n\n return { operations: inverted, warnings };\n}\n\nconst foreignKeyIdentity = (tableName: string, fkName: string) =>\n `${tableName}\\u0000${fkName}`;\n\nfunction invertOperation(\n op: DiffOperation,\n previousSnapshot: SchemaSnapshot,\n findPrevTable: (name: string) => TableDef | undefined,\n keysRestoredByTheirOwnInverse: ReadonlySet<string>,\n warnings: string[],\n primaryKeyName: typeof defaultGeneratedPrimaryKeyName\n): DiffOperation[] | null {\n switch (op.type) {\n case \"createTable\":\n warnings.push(\n `createTable \"${op.table.name}\" inverts to dropTable: rolling back drops the table and every row created after this migration. No data is preserved.`\n );\n return [{ type: \"dropTable\", tableName: op.table.name }];\n\n case \"dropTable\": {\n const table = findPrevTable(op.tableName);\n if (!table) {\n warnings.push(\n `Cannot invert dropTable \"${op.tableName}\": table not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropTable \"${op.tableName}\" was lossy: rolling back recreates the table structure but not its data.`\n );\n const foreignKeys = table.foreignKeys.filter(\n (fk) =>\n !keysRestoredByTheirOwnInverse.has(\n foreignKeyIdentity(table.name, fk.name)\n )\n );\n return [{ type: \"createTable\", table: { ...table, foreignKeys } }];\n }\n\n case \"renameTable\":\n return [{ type: \"renameTable\", from: op.to, to: op.from }];\n\n case \"addColumn\":\n return [\n {\n type: \"dropColumn\",\n tableName: op.tableName,\n columnName: op.column.name,\n },\n ];\n\n case \"dropColumn\": {\n const table = findPrevTable(op.tableName);\n const column = table?.columns.find((c) => c.name === op.columnName);\n if (!column) {\n warnings.push(\n `Cannot invert dropColumn \"${op.tableName}.${op.columnName}\": column not found in previous snapshot.`\n );\n return null;\n }\n warnings.push(\n `dropColumn \"${op.tableName}.${op.columnName}\" was lossy: rolling back restores the column but not its data.`\n );\n return [{ type: \"addColumn\", tableName: op.tableName, column }];\n }\n\n case \"renameColumn\":\n return [\n {\n type: \"renameColumn\",\n tableName: op.tableName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"alterColumn\":\n return [\n {\n type: \"alterColumn\",\n tableName: op.tableName,\n columnName: op.columnName,\n from: op.to,\n to: op.from,\n },\n ];\n\n case \"createIndex\":\n return [\n {\n type: \"dropIndex\",\n tableName: op.tableName,\n indexName: op.index.name,\n },\n ];\n\n case \"dropIndex\": {\n const table = findPrevTable(op.tableName);\n const index = table?.indexes.find((i) => i.name === op.indexName);\n if (!index) {\n warnings.push(\n `Cannot invert dropIndex \"${op.indexName}\" on \"${op.tableName}\": index not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createIndex\", tableName: op.tableName, index }];\n }\n\n case \"addForeignKey\":\n return [\n { type: \"dropForeignKey\", tableName: op.tableName, fkName: op.fk.name },\n ];\n\n case \"dropForeignKey\": {\n const table = findPrevTable(op.tableName);\n const fk = table?.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n warnings.push(\n `Cannot invert dropForeignKey \"${op.fkName}\" on \"${op.tableName}\": foreign key not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"addForeignKey\", tableName: op.tableName, fk }];\n }\n\n case \"addUniqueConstraint\":\n return [\n {\n type: \"dropUniqueConstraint\",\n tableName: op.tableName,\n constraintName: op.constraint.name,\n },\n ];\n\n case \"dropUniqueConstraint\": {\n const table = findPrevTable(op.tableName);\n const constraint = table?.uniqueConstraints.find(\n (u) => u.name === op.constraintName\n );\n if (!constraint) {\n warnings.push(\n `Cannot invert dropUniqueConstraint \"${op.constraintName}\" on \"${op.tableName}\": constraint not found in previous snapshot.`\n );\n return null;\n }\n return [\n { type: \"addUniqueConstraint\", tableName: op.tableName, constraint },\n ];\n }\n\n case \"addPrimaryKey\":\n return [\n {\n type: \"dropPrimaryKey\",\n tableName: op.tableName,\n constraintName: primaryKeyName(op.tableName, op.primaryKey.name),\n },\n ];\n\n case \"dropPrimaryKey\": {\n const table = findPrevTable(op.tableName);\n if (!table?.primaryKey) {\n warnings.push(\n `Cannot invert dropPrimaryKey on \"${op.tableName}\": primary key not found in previous snapshot.`\n );\n return null;\n }\n return [\n {\n type: \"addPrimaryKey\",\n tableName: op.tableName,\n primaryKey: table.primaryKey,\n },\n ];\n }\n\n case \"createEnum\":\n return [{ type: \"dropEnum\", enumName: op.enumDef.name }];\n\n case \"dropEnum\": {\n const enumDef = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!enumDef) {\n warnings.push(\n `Cannot invert dropEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n return [{ type: \"createEnum\", enumDef }];\n }\n\n case \"alterEnum\": {\n const prevEnum = previousSnapshot.enums?.find(\n (e) => e.name === op.enumName\n );\n if (!prevEnum) {\n warnings.push(\n `Cannot invert alterEnum \"${op.enumName}\": enum not found in previous snapshot.`\n );\n return null;\n }\n if (op.removeValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" removed values [${op.removeValues.join(\", \")}]: rolling back restores the values but not replaced row data.`\n );\n }\n if (op.addValues?.length) {\n warnings.push(\n `alterEnum \"${op.enumName}\" rollback removes values [${op.addValues.join(\", \")}]: rows using them will fail unless remapped manually.`\n );\n }\n return [\n {\n type: \"alterEnum\",\n enumName: op.enumName,\n addValues: op.removeValues,\n removeValues: op.addValues,\n newValues: prevEnum.values,\n dependentColumns: op.dependentColumns,\n },\n ];\n }\n\n default:\n warnings.push(\"Cannot invert an unknown generated operation.\");\n return null;\n }\n}\n","/**\n * Exact SQL framing for Migration V1.\n *\n * The blob is the human review artifact. Execution slices UTF-8 byte ranges.\n * There is no delimiter parser, breakpoint marker, or comment search.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { decodeUtf8, type Sha256 } from \"./identity\";\nimport { encodeSqlBlob } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationSqlRangeV1 } from \"./v1-types\";\n\nconst DISPLAY_SEPARATOR = new TextEncoder().encode(\"\\n\\n\");\n\nexport function encodeSqlText(text: string): Uint8Array {\n if (text.includes(\"\\r\")) {\n throw new MigrationError(\n \"Manual SQL fragments containing carriage returns are refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (text.startsWith(\"\\uFEFF\")) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return new TextEncoder().encode(text);\n}\n\nexport function composeSqlBlob(fragments: readonly string[]): {\n bytes: Uint8Array;\n ranges: MigrationSqlRangeV1[];\n sqlHash: Sha256;\n} {\n const encoded = fragments.map(encodeSqlText);\n let total = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) total += DISPLAY_SEPARATOR.length;\n total += encoded[i]!.length;\n }\n const bytes = new Uint8Array(total);\n const ranges: MigrationSqlRangeV1[] = [];\n let offset = 0;\n for (let i = 0; i < encoded.length; i++) {\n if (i > 0) {\n bytes.set(DISPLAY_SEPARATOR, offset);\n offset += DISPLAY_SEPARATOR.length;\n }\n const fragment = encoded[i]!;\n bytes.set(fragment, offset);\n ranges.push({\n dispatchId: \"\",\n offset,\n length: fragment.length,\n });\n offset += fragment.length;\n }\n return {\n bytes,\n sqlHash: encodeSqlBlob(bytes),\n ranges,\n };\n}\n\nexport function validateSqlRanges(\n bytes: Uint8Array,\n dispatches: readonly MigrationDispatchV1[]\n): void {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8 without a BOM\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes.includes(0x0d)) {\n throw new MigrationError(\n \"SQL blobs must be UTF-8/LF without carriage returns\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n decodeUtf8(bytes);\n } catch {\n throw new MigrationError(\n \"SQL blobs must be valid UTF-8\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const sqlHash = encodeSqlBlob(bytes);\n const unique: MigrationDispatchV1[] = [];\n const seen = new Set<string>();\n for (const dispatch of dispatches) {\n if (seen.has(dispatch.dispatchId)) continue;\n seen.add(dispatch.dispatchId);\n unique.push(dispatch);\n }\n const ordered = unique.sort(\n (left, right) => left.offset - right.offset || left.length - right.length\n );\n let previousEnd = 0;\n for (let index = 0; index < ordered.length; index++) {\n const dispatch = ordered[index]!;\n if (dispatch.sqlHash !== sqlHash) {\n throw new MigrationError(\n \"Dispatch sqlHash does not match the SQL blob\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (\n !(\n Number.isSafeInteger(dispatch.offset) &&\n Number.isSafeInteger(dispatch.length)\n ) ||\n dispatch.offset < 0 ||\n dispatch.length < 0\n ) {\n throw new MigrationError(\n \"SQL ranges must use non-negative safe integers\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (dispatch.offset + dispatch.length > bytes.length) {\n throw new MigrationError(\n \"SQL range exceeds the blob\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (index === 0) {\n if (dispatch.offset !== 0) {\n throw new MigrationError(\n \"SQL ranges must begin at byte zero\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else {\n const expectedOffset = previousEnd + DISPLAY_SEPARATOR.length;\n if (dispatch.offset !== expectedOffset) {\n throw new MigrationError(\n dispatch.offset < expectedOffset\n ? \"SQL ranges overlap or omit their separator\"\n : \"SQL ranges contain an unclaimed gap\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (bytes[previousEnd] !== 0x0a || bytes[previousEnd + 1] !== 0x0a) {\n throw new MigrationError(\n \"SQL range separators must be exactly two newline bytes\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n previousEnd = dispatch.offset + dispatch.length;\n }\n if (ordered.length === 0) {\n if (bytes.length === 0) return;\n throw new MigrationError(\n \"A SQL blob without dispatches must be empty\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (previousEnd === bytes.length) return;\n if (previousEnd + 1 === bytes.length && bytes[previousEnd] === 0x0a) {\n return;\n }\n throw new MigrationError(\n \"SQL blobs contain bytes after the final range\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nexport function sliceDispatch(\n bytes: Uint8Array,\n dispatch: MigrationDispatchV1\n): string {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n bytes.subarray(dispatch.offset, dispatch.offset + dispatch.length)\n );\n}\n\nconst MYSQL_DELIMITER = /(^|\\s)DELIMITER\\s/i;\n\nexport function refuseMysqlDelimiter(text: string): void {\n if (MYSQL_DELIMITER.test(text)) {\n throw new MigrationError(\n \"MySQL DELIMITER is a client command, not server SQL\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n","/**\n * The ONE lexical classifier for migration-artifact execution safety.\n *\n * VibORM opens an enclosing boundary around every artifact it executes: an\n * apply/down/reset transaction on PostgreSQL, and a session lock on both\n * PostgreSQL and MySQL. This module refuses the DIRECT statements that would\n * end or reframe it — a `COMMIT` inside an artifact ends the rollback scope\n * VibORM promised, and a `RELEASE_LOCK`/`pg_advisory_unlock` inside one frees\n * the lock that is excluding every other migration command (§3.5).\n *\n * It refuses direct lexical controls and is NOT a sandbox for procedural or\n * dynamic SQL. That distinction is the module's contract, not a caveat on it.\n * Manual migration SQL is trusted last-mile authority: its author owns what it\n * does, this included. A dollar-quoted body is DATA to this scan — it has to\n * be, or every ordinary `CREATE FUNCTION` is refused — and the same bytes are a\n * statement to the server, so `DO $$ BEGIN PERFORM pg_advisory_unlock_all();\n * END $$` frees the migration lock while the command holds it. A pre-existing\n * safe-named function, a function the artifact creates, and `EXECUTE` over a\n * built string are the same escape by another route. It is executed rather than\n * asserted: `tests/unit/migrations/pinned-migration-session.core.test.ts` runs\n * that exact artifact through `apply()` on a real PostgreSQL and pins the lock\n * gone. Do not answer a procedural escape with another spelling here — the\n * enumeration does not close, and every addition costs valid author SQL.\n *\n * What the refusals do buy is the ACCIDENT and the audit: an author who typed a\n * `COMMIT` or a `pg_advisory_unlock(...)` straight into an artifact learns\n * before any of it runs, and a deliberate escape has to be WRITTEN as one, in\n * the artifact, where a reviewer sees it. The deliberate case is answered\n * afterwards instead, by the release proof in `pinned-session.ts`: a lock the\n * command acquired and no longer holds fails that command loudly and discards\n * the session, rather than letting it report a migration that ran outside the\n * boundary it published.\n *\n * The scanner is comment- and string-safe, which is the whole reason this is a\n * classifier rather than a regular expression: `-- COMMIT`, `'COMMIT'`, a\n * column named `\"commit\"`, and a dollar-quoted body that merely mentions\n * `pg_advisory_unlock` are all valid SQL and must stay valid. Only executable\n * tokens are classified.\n *\n * Executable is not enough on its own, because a spelling is not a role. A\n * table named `pg_advisory_notes`, a column named `release_lock`, and MySQL's\n * `@autocommit` user variable are executable tokens that call nothing and set\n * nothing, and refusing them refused valid author SQL over a resemblance. So\n * every scanned word carries the role its POSITION gives it, and the lock\n * refusals key on a call — one owner deciding it for bare and quoted\n * identifiers alike.\n *\n * Comment- and string-safety is DIALECT-SPECIFIC, so the scan takes the dialect\n * rather than reading one lexical grammar into both servers. Every arm below\n * that branches exists because the two servers disagree about what is data:\n * MySQL's `#` line comments and its `--` whitespace rule, its executable\n * `/*!…` comments whose contents the server RUNS, its backslash escapes inside\n * string literals, PostgreSQL's `E'…'` escape strings, and PostgreSQL's nested\n * block comments. Reading one server's grammar on the other either blinds the\n * scanner to a real statement or refuses an artifact that is entirely a\n * comment.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationTarget } from \"./types\";\n\n/**\n * Statement-leading PHRASES that open, close, or reframe a transaction.\n *\n * The test is on the LEADING word because that is what makes the word a\n * statement rather than a name: `END` opens nothing in `CREATE TABLE end_state`,\n * and `RELEASE` is only `RELEASE SAVEPOINT` at the start of a statement.\n *\n * `PREPARE TRANSACTION` is the entry that needs a second word, and it needs it\n * in both directions. It DETACHES the running transaction from this session for\n * a later `COMMIT PREPARED`, so where the server allows it at all\n * (`max_prepared_transactions > 0`) the entry's DDL is left unresolved while\n * the tracking write that records it lands in the autocommit that follows. And\n * `PREPARE plan AS SELECT …` begins with the same word while controlling\n * nothing, so refusing the leader alone would ban ordinary author SQL. The\n * phrase is the unit of the test; `PREPARE` alone is not an entry. Its two\n * siblings need no entry of their own — `COMMIT PREPARED` and\n * `ROLLBACK PREPARED` already lead with a refused word.\n */\nconst POSTGRES_TRANSACTION_LEADERS = new Set([\n \"ABORT\",\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"PREPARE TRANSACTION\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n]);\n\nconst MYSQL_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"LOCK\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"START\",\n \"UNLOCK\",\n \"XA\",\n]);\n\n/** SQLite controls over the transaction boundary owned by the migration run. */\nconst SQLITE_TRANSACTION_LEADERS = new Set([\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n]);\n\n/**\n * PostgreSQL's advisory-lock family, by prefix.\n *\n * A prefix rather than a list because the family is closed by naming\n * convention and open by variant: session and transaction scope, shared and\n * exclusive, blocking and `try_`. Enumerating them invites the one that is\n * missed.\n *\n * Being this wide is only safe because the prefix is read at a CALL and nowhere\n * else. `pg_advisory_notes` is a table an author may have kept for years, and\n * `pg_advisory_note` a column in it; the family's spelling makes neither of them\n * a function, and refusing them refused valid SQL over a resemblance.\n */\nconst POSTGRES_ADVISORY_PREFIXES = [\"PG_ADVISORY\", \"PG_TRY_ADVISORY\"];\n\n/**\n * Words after which an identifier is the NAME of the object a statement\n * defines, never a function it calls — even with a `(` right behind it.\n *\n * `CREATE TABLE pg_advisory_notes (id INT)` opens a COLUMN list, and\n * `CREATE FUNCTION \"pg_advisory_unlock_all\"()` an argument declaration; neither\n * calls anything. These are the only words a `(`-followed identifier can sit\n * behind without being a call, and the two servers agree on them: neither has\n * an expression in which a called function's name follows the bare word TABLE,\n * VIEW, FUNCTION, PROCEDURE, AGGREGATE, or the EXISTS of `IF NOT EXISTS`.\n *\n * MySQL's inline index names — `UNIQUE KEY get_lock (id)` — are the one\n * definition this set does not reach, and `KEY`/`INDEX` stay out of it on\n * purpose: unlike the six above, each is also an ordinary column name, so the\n * set would start being reached from expressions and exempt what follows one.\n * A refused index name costs its author a rename; that exemption costs the\n * boundary.\n */\nconst OBJECT_NAME_KEYWORDS = new Set([\n \"AGGREGATE\",\n \"EXISTS\",\n \"FUNCTION\",\n \"PROCEDURE\",\n \"TABLE\",\n \"VIEW\",\n]);\n\n/** MySQL's named-lock family: acquisition, release, and both probes. */\nconst MYSQL_LOCK_FUNCTIONS = new Set([\n \"GET_LOCK\",\n \"IS_FREE_LOCK\",\n \"IS_USED_LOCK\",\n \"RELEASE_ALL_LOCKS\",\n \"RELEASE_LOCK\",\n]);\n\n/** The tag body of a PostgreSQL dollar quote: `$tag$`. */\nconst DOLLAR_TAG_PART = /[A-Za-z0-9_]/;\n/** The optional server-version prefix of a MySQL executable comment. */\nconst VERSION_DIGIT = /[0-9]/;\n\n/**\n * MySQL's SYSTEM-variable sigil, which the bare spelling of the same name also\n * reaches: `SET @@autocommit = 0` and `SET autocommit = 0` change one setting,\n * so the sigil folds away and both meet the same refusal.\n *\n * ONE `@` does not fold. `@autocommit` is a user variable — a slot with a name\n * that happens to read like the setting, which no server behavior consults —\n * and folding it refused `SET @autocommit = 0`, valid MySQL, as a commit-\n * boundary change. `SELECT @release_lock` was refused as a lock call the same\n * way.\n */\nconst SYSTEM_VARIABLE_SIGIL = /^@@/;\n\n/**\n * The dialects this classifier reads.\n */\nexport type ClassifiedDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\n/**\n * The characters that make a bare word, per dialect.\n *\n * `@` is the whole difference and it is not cosmetic. In MySQL the sigil is\n * part of the identifier — `@name` and `@@name` are two different names, and\n * neither is the bare one. PostgreSQL has no variable sigil at all: `@` is an\n * operator character there, so joining it to the word behind it would read\n * `SELECT @pg_advisory_unlock(1)` as one name the advisory prefix no longer\n * matches, hiding a call the server still makes.\n */\nconst WORD_CHARACTERS: Record<\n ClassifiedDialect,\n { readonly start: RegExp; readonly part: RegExp }\n> = {\n mysql: { start: /[A-Za-z_@]/, part: /[A-Za-z0-9_$@]/ },\n postgresql: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n sqlite: { start: /[A-Za-z_]/, part: /[A-Za-z0-9_$]/ },\n};\n\n/**\n * One executable word and the syntactic role its POSITION gives it.\n *\n * The role is the point. A lock-function refusal that reads spelling alone\n * refuses `CREATE TABLE get_lock (id INT)` and `CREATE TABLE t (release_lock\n * INT)`, which call nothing and are the author's to keep. `calls` is decided\n * once, by {@link callsArguments}, for bare and quoted identifiers alike.\n */\ntype ScannedWord = {\n /**\n * The folded spelling. A bare word arrives uppercased, minus MySQL's system\n * sigil; a called quoted identifier arrives in its own lowercase spelling,\n * which is the only one that names a PostgreSQL built-in.\n */\n readonly text: string;\n /** Whether an argument list opens behind it, in a position that may call. */\n readonly calls: boolean;\n};\n\n/**\n * What sits immediately in front of the cursor, whitespace and comments apart.\n *\n * `qualifier` is the `.` of a qualified name, and it is why the role of\n * `alpha.pg_advisory_notes` is decided by the word in front of `alpha`:\n * `CREATE TABLE` defines that name and `SELECT` calls it, and the qualifier\n * between them changes neither.\n */\ntype PrecedingToken = \"word\" | \"qualifier\" | \"other\";\n\n/**\n * The EXECUTABLE bare words of an artifact chunk, grouped per statement.\n *\n * Grouping on the top-level `;` is load-bearing, not cosmetic: VibORM's\n * artifact parser splits on its own breakpoint marker, so ONE parsed chunk\n * routinely holds several SQL statements. A classifier that only looked at the\n * first word of the chunk would read `CREATE TABLE t; COMMIT;` as a `CREATE`\n * and let the `COMMIT` through — which is precisely the statement that ends the\n * transaction VibORM promised.\n *\n * Quoted identifiers are excluded rather than included WHEN THEY ARE NAMED: a\n * table or column the author quoted is a name, never a keyword, so\n * `CREATE TABLE \"commit\"` and a column named `` `get_lock` `` stay valid. Text\n * inside comments, single-quoted literals and PostgreSQL dollar-quoted bodies\n * is skipped for the same reason — it is data, not a statement.\n *\n * A quoted identifier the statement CALLS is the exception: quoting a\n * function's name does not stop PostgreSQL calling it, so\n * `pg_catalog.\"pg_advisory_unlock_all\"()` frees the lock excluding every other\n * migration command while every word the scan retained says\n * `SELECT pg_catalog`. Which of the two a quoted run is comes from\n * {@link callsArguments}, the same owner that decides it for bare words.\n *\n * The dialect decides which runs are data. A MySQL executable comment is the\n * clearest case: its contents are not data at all, and the server runs them.\n */\nexport function readExecutableStatements(\n sql: string,\n dialect: ClassifiedDialect\n): string[][] {\n return scanStatements(sql, dialect).map((words) =>\n words.map((word) => word.text)\n );\n}\n\n/**\n * The scan itself: executable words with the role their position gives them,\n * grouped per statement.\n *\n * {@link readExecutableStatements} is this without the roles, which is all the\n * enum-boundary question needs; {@link classifyOne} needs them, because a\n * spelling in a name position is not the call it refuses.\n */\nfunction scanStatements(\n sql: string,\n dialect: ClassifiedDialect\n): ScannedWord[][] {\n const characters = WORD_CHARACTERS[dialect];\n const statements: ScannedWord[][] = [];\n let words: ScannedWord[] = [];\n let index = 0;\n let preceding: PrecedingToken = \"other\";\n /** The previous identifier RUN, whether or not the scan retained it. */\n let previousWord: string | undefined;\n /** The word governing the identifier position the cursor stands in. */\n let governing: string | undefined;\n\n while (index < sql.length) {\n const char = sql[index] ?? \"\";\n const next = sql[index + 1] ?? \"\";\n\n if (char === \"-\" && next === \"-\" && opensLineComment(sql, index, dialect)) {\n index = skipLine(sql, index);\n continue;\n }\n // MySQL's second line-comment spelling. PostgreSQL has none: `#` is an\n // operator character there, and skipping to end of line on it would blind\n // the scan to whatever followed on that line.\n if (dialect === \"mysql\" && char === \"#\") {\n index = skipLine(sql, index);\n continue;\n }\n if (char === \"/\" && next === \"*\") {\n if (dialect === \"mysql\" && sql[index + 2] === \"!\") {\n index = openExecutableComment(sql, index);\n continue;\n }\n index = skipBlockComment(sql, index, dialect);\n continue;\n }\n if (char === \"'\" || char === '\"' || char === \"`\") {\n const quoteEnd = skipQuoted(\n sql,\n index,\n char,\n escapesWithBackslash(dialect, char)\n );\n governing = governingWord(preceding, previousWord, governing);\n const name = readQuotedIdentifier(sql, index, quoteEnd, char, dialect);\n if (name !== null && callsArguments(sql, quoteEnd, governing, dialect)) {\n words.push({ text: name, calls: true });\n }\n // A quoted run ends the reach of whatever governed it: nothing that\n // follows a closing quote directly is the name of a defined object.\n preceding = \"other\";\n index = quoteEnd;\n continue;\n }\n if (dialect === \"sqlite\" && char === \"[\") {\n index = skipBracketQuoted(sql, index);\n preceding = \"other\";\n continue;\n }\n if (dialect === \"postgresql\" && char === \"$\") {\n const dollarEnd = skipDollarQuoted(sql, index);\n if (dollarEnd !== null) {\n index = dollarEnd;\n preceding = \"other\";\n continue;\n }\n }\n if (char === \";\") {\n if (words.length > 0) {\n statements.push(words);\n words = [];\n }\n index += 1;\n preceding = \"other\";\n continue;\n }\n if (characters.start.test(char)) {\n const start = index;\n index += 1;\n while (index < sql.length && characters.part.test(sql[index] ?? \"\")) {\n index += 1;\n }\n const text = sql\n .slice(start, index)\n .toUpperCase()\n .replace(SYSTEM_VARIABLE_SIGIL, \"\");\n // PostgreSQL's `E'…'` escape string. The `E` is the literal's prefix, not\n // a bare word, and it is the ONE PostgreSQL string form where a backslash\n // escapes the closing quote — reading it as a standard literal closes it\n // early at `\\'` and hides every statement up to the next quote.\n if (dialect === \"postgresql\" && text === \"E\" && sql[index] === \"'\") {\n index = skipQuoted(sql, index, \"'\", true);\n preceding = \"other\";\n continue;\n }\n governing = governingWord(preceding, previousWord, governing);\n words.push({\n text,\n calls: callsArguments(sql, index, governing, dialect),\n });\n previousWord = text;\n preceding = \"word\";\n continue;\n }\n if (char.trim() !== \"\") {\n preceding = char === \".\" ? \"qualifier\" : \"other\";\n }\n index += 1;\n }\n\n if (words.length > 0) {\n statements.push(words);\n }\n return statements;\n}\n\n/**\n * The word that governs the identifier position at the cursor, or undefined\n * when no word reaches it.\n *\n * Directly in front of an identifier, a word governs it: the `TABLE` of\n * `CREATE TABLE get_lock (…)` says that name is being defined. Across a `.`\n * the governor is inherited rather than replaced, so a qualified name is\n * decided by whatever opened the chain — `CREATE TABLE alpha.pg_advisory_notes\n * (…)` defines, `SELECT pg_catalog.\"pg_advisory_unlock_all\"()` calls.\n *\n * Any other punctuation ends the reach, and that is the half that keeps the\n * exemption honest: a comma away from a column named `view`,\n * `SELECT view, \"pg_advisory_unlock\"(1)` is a call, and reading the previous\n * WORD alone admitted it as a definition.\n */\nfunction governingWord(\n preceding: PrecedingToken,\n previousWord: string | undefined,\n chainGovernor: string | undefined\n): string | undefined {\n if (preceding === \"word\") {\n return previousWord;\n }\n if (preceding === \"qualifier\") {\n return chainGovernor;\n }\n return undefined;\n}\n\n/**\n * The unquoted-equivalent spelling of a quoted identifier, or null when the\n * quoted run is a literal or a spelling no built-in answers to.\n *\n * PostgreSQL is the only dialect that reaches a decision here. MySQL's `\"` is a\n * STRING quote, so the same bytes are data there, and its backtick-quoted names\n * resolve to stored functions rather than to the built-in named-lock family —\n * `` SELECT `release_lock`('k') `` does not run MySQL's `RELEASE_LOCK`.\n *\n * A quoted identifier is CASE-SENSITIVE, so only the folded spelling names the\n * built-in: `\"PG_ADVISORY_UNLOCK_ALL\"` is a function PostgreSQL does not have,\n * and refusing it would ban a name over a call that cannot happen. The name is\n * returned in that folded (lowercase) spelling, which is also what keeps it out\n * of every keyword test in this module — bare words arrive uppercased.\n */\nfunction readQuotedIdentifier(\n sql: string,\n start: number,\n end: number,\n quote: string,\n dialect: ClassifiedDialect\n): string | null {\n if (dialect !== \"postgresql\" || quote !== '\"') {\n return null;\n }\n // An UNTERMINATED quote ran to the end of the input; nothing follows it, so\n // nothing calls it.\n if (end - start < 2 || sql[end - 1] !== '\"') {\n return null;\n }\n const name = sql.slice(start + 1, end - 1).replaceAll('\"\"', '\"');\n return name === name.toLowerCase() ? name : null;\n}\n\n/**\n * The ONE call-position owner: whether the identifier ending at `end` is CALLED\n * where it stands.\n *\n * Two halves, and both are needed. A governing keyword makes the identifier the\n * name of an object being defined, `(` behind it or not — that is what keeps\n * `CREATE TABLE pg_advisory_notes (id INT)` and\n * `CREATE TABLE \"pg_advisory_unlock_all\" (id INT)` valid, since both open a\n * column list. Otherwise an argument list has to actually open, modulo what\n * sits between a function's name and its `(`: whitespace is the obvious case\n * and comments are the one that matters, because\n * `pg_catalog.\"pg_advisory_unlock_all\"/**\\/()` is one call to the server and a\n * lookahead that stopped at the first non-space would read it as a name.\n *\n * A qualifier is not read: `myschema.\"pg_advisory_unlock\"()` is a call too,\n * because a `search_path` this classifier cannot see decides what that name\n * resolves to. Whitespace before the `(` is admitted on MySQL as well, where\n * only `IGNORE_SPACE` makes the server accept it — refusing a call the server\n * might make is the direction this classifier can afford to be wrong in.\n */\nfunction callsArguments(\n sql: string,\n end: number,\n governing: string | undefined,\n dialect: ClassifiedDialect\n): boolean {\n if (governing !== undefined && OBJECT_NAME_KEYWORDS.has(governing)) {\n return false;\n }\n let cursor = end;\n while (cursor < sql.length) {\n const char = sql[cursor] ?? \"\";\n if (\n char === \"-\" &&\n sql[cursor + 1] === \"-\" &&\n opensLineComment(sql, cursor, dialect)\n ) {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (dialect === \"mysql\" && char === \"#\") {\n cursor = skipLine(sql, cursor);\n continue;\n }\n if (char === \"/\" && sql[cursor + 1] === \"*\") {\n cursor = skipBlockComment(sql, cursor, dialect);\n continue;\n }\n if (char.trim() !== \"\") {\n return char === \"(\";\n }\n cursor += 1;\n }\n return false;\n}\n\n/**\n * Whether the `--` at `start` opens a line comment.\n *\n * PostgreSQL's always does. MySQL's requires whitespace (or a control\n * character, or end of input) after the second dash, so\n * `SELECT 1--RELEASE_LOCK('viborm_migration_…')` is arithmetic over a REAL\n * function call there rather than a comment. Reading it as a comment hides\n * exactly the statement this classifier exists to refuse.\n */\nfunction opensLineComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): boolean {\n if (dialect !== \"mysql\") {\n return true;\n }\n const after = sql[start + 2];\n if (after === undefined) {\n return true;\n }\n return after.trim() === \"\" || after.charCodeAt(0) < 0x20;\n}\n\n/** Past SQLite's square-bracket identifier quote. */\nfunction skipBracketQuoted(sql: string, start: number): number {\n const end = sql.indexOf(\"]\", start + 1);\n return end < 0 ? sql.length : end + 1;\n}\n\n/** Past a line comment, including its newline. */\nfunction skipLine(sql: string, start: number): number {\n const lineEnd = sql.indexOf(\"\\n\", start);\n return lineEnd < 0 ? sql.length : lineEnd + 1;\n}\n\n/**\n * Past the OPENING of a MySQL executable comment (`/*!`, optionally followed by\n * a server-version prefix), leaving its contents to be scanned as statements.\n *\n * MySQL RUNS what is inside these — that is what they are for — so skipping\n * them the way an ordinary comment is skipped admits\n * `/*!50000 DO RELEASE_LOCK('viborm_migration_…')`, which frees the lock the\n * running command holds, and `/*!40101 SET AUTOCOMMIT=0`, which reframes the\n * commit boundary of everything after it. The closing delimiter needs no arm of\n * its own: neither of its characters starts a word.\n */\nfunction openExecutableComment(sql: string, start: number): number {\n let cursor = start + 3;\n while (cursor < sql.length && VERSION_DIGIT.test(sql[cursor] ?? \"\")) {\n cursor += 1;\n }\n return cursor;\n}\n\n/**\n * Past a block comment.\n *\n * PostgreSQL NESTS them, so an outer comment holding a complete inner one is\n * entirely a comment there; stopping at the first close would leave the outer\n * comment's tail scanned as SQL and refuse a valid artifact over a `COMMIT` no\n * server ever sees. MySQL does not nest, so its depth never rises and it stops\n * at the first close — which is also where the server stops.\n */\nfunction skipBlockComment(\n sql: string,\n start: number,\n dialect: ClassifiedDialect\n): number {\n let cursor = start + 2;\n let depth = 1;\n while (cursor < sql.length) {\n if (sql[cursor] === \"*\" && sql[cursor + 1] === \"/\") {\n depth -= 1;\n cursor += 2;\n if (depth === 0) {\n return cursor;\n }\n continue;\n }\n if (\n dialect === \"postgresql\" &&\n sql[cursor] === \"/\" &&\n sql[cursor + 1] === \"*\"\n ) {\n depth += 1;\n cursor += 2;\n continue;\n }\n cursor += 1;\n }\n return sql.length;\n}\n\n/**\n * Whether a backslash escapes the next character inside this quote.\n *\n * MySQL's default mode treats `\\` as an escape inside both string quotes, so\n * `'a\\'b'` is ONE literal there; its backtick identifiers take no escapes.\n * PostgreSQL's strings are standard-conforming, so a backslash is an ordinary\n * character in `'…'` and `\"…\"` — its one escape-bearing form, `E'…'`, is\n * recognised at the `E` in the scan above.\n */\nfunction escapesWithBackslash(\n dialect: ClassifiedDialect,\n quote: string\n): boolean {\n return dialect === \"mysql\" && quote !== \"`\";\n}\n\n/**\n * Past a quoted run, honoring the doubling escape every admitted dialect uses\n * (`''`, `\"\"`, ` `` `) and, where the dialect has them, backslash escapes. An\n * unterminated quote consumes the rest of the statement, which is what a\n * database would also do with it.\n */\nfunction skipQuoted(\n sql: string,\n start: number,\n quote: string,\n backslashEscapes: boolean\n): number {\n let cursor = start + 1;\n while (cursor < sql.length) {\n if (backslashEscapes && sql[cursor] === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (sql[cursor] !== quote) {\n cursor += 1;\n continue;\n }\n if (sql[cursor + 1] === quote) {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n return sql.length;\n}\n\n/**\n * Past a PostgreSQL dollar-quoted body (`$$…$$`, `$tag$…$tag$`), or null when\n * this `$` does not open one.\n *\n * Function bodies are the common shape of a hand-written PostgreSQL artifact,\n * and their contents are a string, not statements. Reading them as statements\n * would refuse a perfectly ordinary `CREATE FUNCTION` whose body happens to\n * contain `COMMIT` or `BEGIN`.\n */\nfunction skipDollarQuoted(sql: string, start: number): number | null {\n let cursor = start + 1;\n while (cursor < sql.length && DOLLAR_TAG_PART.test(sql[cursor] ?? \"\")) {\n cursor += 1;\n }\n if (sql[cursor] !== \"$\") {\n return null;\n }\n const tag = sql.slice(start, cursor + 1);\n const bodyEnd = sql.indexOf(tag, cursor + 1);\n return bodyEnd < 0 ? sql.length : bodyEnd + tag.length;\n}\n\n/** The refusal a classified statement raises, naming its artifact and cause. */\nfunction refuse(\n artifact: string,\n statement: string,\n reason: string\n): MigrationError {\n return new MigrationError(\n `Migration \"${artifact}\" contains a statement VibORM cannot execute inside the boundary it publishes: ${reason}. ` +\n `The offending statement begins \"${statement.trim().slice(0, 80)}\". ` +\n \"Manual migration SQL owns its object effects; VibORM refuses only the direct controls over its rollback scope, its migration lock, and its tracking boundary, so write the migration without them.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n}\n\n/**\n * Refuses an artifact that DIRECTLY reframes the execution boundary.\n *\n * Runs BEFORE any of the artifact's effects, so a refusal leaves the estate\n * exactly as it was. SQLite has no advisory lock, but the migration runner\n * still owns its transaction and savepoint boundary.\n */\nexport function assertArtifactExecutionSafe(\n statements: readonly string[],\n dialect: MigrationTarget[\"dialect\"],\n artifact: string\n): void {\n for (const chunk of statements) {\n const scanned = scanStatements(chunk, dialect);\n if (dialect === \"sqlite\" && isSqliteTrigger(scanned[0])) {\n continue;\n }\n for (const words of scanned) {\n classifyOne(words, chunk, dialect, artifact);\n }\n }\n}\n\n/**\n * A SQLite trigger body uses `BEGIN … END` as grammar, not transaction control.\n * Stock SQLite execution accepts one prepared statement per dispatch, so the\n * whole trigger is the provider statement and its body controls stay inside it.\n */\nfunction isSqliteTrigger(first: readonly ScannedWord[] | undefined): boolean {\n if (first?.[0]?.text !== \"CREATE\") {\n return false;\n }\n const second = first[1]?.text;\n return (\n second === \"TRIGGER\" ||\n ((second === \"TEMP\" || second === \"TEMPORARY\") &&\n first[2]?.text === \"TRIGGER\")\n );\n}\n\n/**\n * The refusable leading phrase of one statement, or undefined.\n *\n * Two lookups, because an entry is one word or two and the longer one decides:\n * `COMMIT PREPARED 'g'` is refused for its `COMMIT`, `PREPARE TRANSACTION 'g'`\n * for the pair, and `PREPARE plan AS …` for neither. These are the statement's\n * EXECUTABLE words, so the pair is already case-folded and already free of\n * whatever whitespace or comment the author wrote between the two.\n */\nfunction leadingTransactionCommand(\n words: readonly ScannedWord[],\n leaders: ReadonlySet<string>\n): string | undefined {\n const first = words[0]?.text;\n const second = words[1]?.text;\n const pair = second === undefined ? undefined : `${first} ${second}`;\n if (pair !== undefined && leaders.has(pair)) {\n return pair;\n }\n return first !== undefined && leaders.has(first) ? first : undefined;\n}\n\n/** Classifies ONE statement's executable words. */\nfunction classifyOne(\n words: readonly ScannedWord[],\n statement: string,\n dialect: ClassifiedDialect,\n artifact: string\n): void {\n const leader = words[0]?.text;\n if (leader === undefined) {\n return;\n }\n\n if (dialect === \"postgresql\") {\n const control = leadingTransactionCommand(\n words,\n POSTGRES_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would end the transaction this migration runs inside`\n );\n }\n // One fold reaches both forms the scan retains: a bare word arrives\n // uppercased, and a called quoted identifier arrives in its own folded\n // spelling, which is the only spelling that names the built-in.\n const advisory = words.find(\n (word) =>\n word.calls &&\n POSTGRES_ADVISORY_PREFIXES.some((prefix) =>\n word.text.toUpperCase().startsWith(prefix)\n )\n );\n if (advisory !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${advisory.text.toLowerCase()}\", which would change the advisory-lock state this migration command holds`\n );\n }\n return;\n }\n\n if (dialect === \"sqlite\") {\n const control = leadingTransactionCommand(\n words,\n SQLITE_TRANSACTION_LEADERS\n );\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction-control statement \"${control}\", which would change the transaction boundary this migration runs inside`\n );\n }\n return;\n }\n\n const control = leadingTransactionCommand(words, MYSQL_TRANSACTION_LEADERS);\n if (control !== undefined) {\n throw refuse(\n artifact,\n statement,\n `the transaction- or table-lock statement \"${control}\", which would change the boundary this migration runs inside`\n );\n }\n // `SET autocommit` reframes every following statement's commit boundary, and\n // it is a SET, not a leader of its own — hence the word test. The scan folds\n // `@@autocommit` to that same word and leaves `@autocommit` under its own\n // name, so the setting is reached under both its spellings and the user\n // variable under neither.\n if (leader === \"SET\" && words.some((word) => word.text === \"AUTOCOMMIT\")) {\n throw refuse(\n artifact,\n statement,\n \"a change to `autocommit`, which would change the commit boundary of every statement that follows\"\n );\n }\n const named = words.find(\n (word) => word.calls && MYSQL_LOCK_FUNCTIONS.has(word.text)\n );\n if (named !== undefined) {\n throw refuse(\n artifact,\n statement,\n `a call to \"${named.text.toLowerCase()}\", which would change the named-lock state this migration command holds`\n );\n }\n}\n\n/**\n * Whether a PostgreSQL migration edge must commit before the next one runs.\n *\n * `ALTER TYPE ... ADD VALUE` cannot be used by a later statement of the\n * transaction that added it (55P04), so apply, rollback and reset end their\n * shared transaction after such an edge. Reset creates the type in its own\n * transaction, but only PostgreSQL 17 and later exempt such a type's values.\n *\n * The question is PostgreSQL's alone — no other dialect has the statement — so\n * the scan reads PostgreSQL's lexical grammar rather than taking a dialect its\n * callers would each have to answer for.\n */\nexport function needsEnumAdditionCommitBoundary(\n statements: readonly string[]\n): boolean {\n for (const chunk of statements) {\n for (const words of readExecutableStatements(chunk, \"postgresql\")) {\n if (\n words[0] === \"ALTER\" &&\n words[1] === \"TYPE\" &&\n words.includes(\"ADD\") &&\n words.includes(\"VALUE\")\n ) {\n return true;\n }\n }\n }\n return false;\n}\n","import { isDestructiveOperation } from \"./differ\";\n/**\n * One compiler: DiffOperation and manual Sql become structured operations\n * that share one SQL blob. No delimiter split.\n */\n\nimport type { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalDecimalText } from \"../validation/primitives/decimal-value\";\nimport { decodeCanonicalBase64, encodeBase64 } from \"./base64\";\nimport {\n type CatalogProbe,\n probeForGeneratedStatement,\n} from \"./catalog-probes\";\nimport type { DDLContext, MigrationDriver } from \"./drivers\";\nimport { invertOperations } from \"./invert\";\nimport type { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { needsEnumAdditionCommitBoundary } from \"./statement-safety\";\nimport type { DiffOperation, SchemaSnapshot } from \"./types\";\nimport { encodeTransitionHash } from \"./v1-parse\";\nimport type {\n AtomicityClass,\n MigrationBooleanCheckV1,\n MigrationCheckInput,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParameterV1,\n MigrationParentTransitionV1,\n MigrationRollbackV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport interface CompiledTransition {\n readonly operations: readonly MigrationOperationV1[];\n readonly rollback: MigrationRollbackV1;\n readonly originChecks: readonly MigrationBooleanCheckV1[];\n readonly requestedForwardBoundary: \"transactional\" | \"stepwise\" | null;\n readonly atomicity: AtomicityClass;\n readonly warnings?: readonly string[];\n}\n\n/** The SQL each step of `operations` executes, in order. */\nexport function stepStatements(\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[]\n): string[] {\n return operations.flatMap((operation) =>\n operation.steps.map((step) => sliceDispatch(blob, step.execute))\n );\n}\n\n/**\n * Contiguous edges of one boundary share a commit, except that an edge adding\n * a PostgreSQL enum value ends its group: a later edge may use that value,\n * which PostgreSQL refuses until the addition commits (55P04).\n */\nexport function groupContiguousAtomicity<\n T extends { readonly boundary: string },\n>(\n items: readonly T[],\n statementsOf: (item: T) => readonly string[]\n): readonly {\n readonly boundary: T[\"boundary\"];\n readonly items: readonly T[];\n}[] {\n const groups: {\n boundary: T[\"boundary\"];\n items: T[];\n }[] = [];\n let mustCommit = false;\n for (const item of items) {\n const current = groups.at(-1);\n if (current?.boundary === item.boundary && !mustCommit) {\n current.items.push(item);\n } else {\n groups.push({ boundary: item.boundary, items: [item] });\n }\n mustCommit = needsEnumAdditionCommitBoundary(statementsOf(item));\n }\n return groups;\n}\n\nexport function compileGeneratedTransition(\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n desiredSchema: SchemaSnapshot,\n assembly: SqlAssembly\n): CompiledTransition {\n const compiled = operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n currentSchema,\n operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0);\n const inverse = invertOperations(\n [...operations],\n currentSchema,\n driver.projectNativeRename.bind(driver),\n driver.generatedPrimaryKeyName.bind(driver)\n );\n const missingBackfill = inverse.operations.find(\n (operation) =>\n operation.type === \"addColumn\" &&\n !operation.column.nullable &&\n operation.column.default === undefined\n );\n const irreversibleReason =\n missingBackfill && missingBackfill.type === \"addColumn\"\n ? `Rollback cannot restore required column \"${missingBackfill.tableName}.${missingBackfill.column.name}\" without its lost data or an explicit backfill. Author a manual rollback.`\n : inverse.operations\n .map((operation) => driver.getIrreversibleRollbackReason(operation))\n .find((reason) => reason !== undefined);\n const rollback: MigrationRollbackV1 =\n inverse.operations.length === 0 && operations.length === 0\n ? { kind: \"schema\", operations: [] }\n : irreversibleReason !== undefined\n ? { kind: \"irreversible\", reason: irreversibleReason }\n : inverse.operations.length === 0\n ? {\n kind: \"irreversible\",\n reason:\n inverse.warnings[0] ??\n \"Generated operations have no automatic inverse\",\n }\n : {\n kind: \"schema\",\n operations: inverse.operations\n .map((operation, index) =>\n compileGeneratedOperation(\n operation,\n driver,\n destination,\n desiredSchema,\n inverse.operations,\n index,\n assembly\n )\n )\n .filter((operation) => operation.steps.length > 0),\n };\n return {\n operations: compiled,\n rollback,\n warnings: inverse.warnings,\n originChecks: [],\n requestedForwardBoundary: null,\n atomicity: classifyGeneratedAtomicity(driver, operations),\n };\n}\n\nfunction compileGeneratedOperation(\n operation: DiffOperation,\n driver: MigrationDriver,\n destination: DDLContext[\"destination\"],\n currentSchema: SchemaSnapshot,\n batch: readonly DiffOperation[],\n index: number,\n assembly: SqlAssembly\n): MigrationOperationV1 {\n const context: DDLContext = {\n destination,\n currentSchema,\n precedingOperations: batch.slice(0, index),\n followingOperations: batch.slice(index + 1),\n };\n const statements = driver.compileStatements(operation, context);\n const steps: MigrationStepV1[] = statements.map((statement) => {\n const probes = probeForGeneratedStatement(driver, operation, statement);\n const execute = addDispatch(assembly, statement, []);\n if (!probes) {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: checkFromProbe(assembly, probes.pre),\n execute,\n postcheck: checkFromProbe(assembly, probes.post),\n };\n });\n return {\n id: `${operation.type}:${index}`,\n label:\n \"tableName\" in operation\n ? `${operation.type} ${operation.tableName}${\"columnName\" in operation ? `.${operation.columnName}` : \"column\" in operation ? `.${operation.column.name}` : \"\"}`\n : operation.type,\n origin: \"generated\",\n risk: isDestructiveOperation(operation) ? \"destructive\" : \"safe\",\n steps,\n };\n}\n\nexport function compileManualTransition(\n up: readonly Sql[],\n rollback:\n | {\n readonly kind: \"manual\";\n readonly execution: AtomicityClass;\n readonly sql: readonly Sql[];\n }\n | { readonly kind: \"irreversible\"; readonly reason: string },\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n requested: AtomicityClass,\n originChecks: readonly MigrationCheckInput[] | undefined,\n assembly: SqlAssembly\n): CompiledTransition {\n const operations = compileManualOperations(up, dialect, assembly, \"forward\");\n if (rollback.kind === \"irreversible\" && rollback.reason.trim().length === 0) {\n throw new MigrationError(\n \"Irreversible rollback requires a non-empty reason\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const compiledRollback: MigrationRollbackV1 =\n rollback.kind === \"irreversible\"\n ? rollback\n : {\n kind: \"manual\",\n requestedBoundary: rollback.execution,\n operations: compileManualOperations(\n rollback.sql,\n dialect,\n assembly,\n \"rollback\"\n ),\n };\n return {\n operations,\n rollback: compiledRollback,\n originChecks: (originChecks ?? []).map((check, index) =>\n compileTrustedCheck(check, dialect, assembly, `origin:${index}`)\n ),\n requestedForwardBoundary: requested,\n atomicity: requested,\n };\n}\n\nexport function assertManualStepwiseProof(\n compiled: CompiledTransition,\n destinationChecks: readonly MigrationBooleanCheckV1[]\n): void {\n const forwardStepwise = compiled.requestedForwardBoundary === \"stepwise\";\n const rollbackStepwise =\n compiled.rollback.kind === \"manual\" &&\n compiled.rollback.requestedBoundary === \"stepwise\";\n if (!(forwardStepwise || rollbackStepwise)) return;\n if (compiled.originChecks.length === 0 || destinationChecks.length === 0) {\n throw new MigrationError(\n \"Stepwise data-only manual work without complete origin and destination checks is refused before dispatch\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n}\n\nfunction compileManualOperations(\n fragments: readonly Sql[],\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n prefix: string\n): MigrationOperationV1[] {\n if (fragments.length === 0) {\n throw new MigrationError(\n `Manual ${prefix} program must contain at least one SQL dispatch`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return fragments.map((fragment, index) => {\n const text = fragment.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n if (text.trim().length === 0) {\n throw new MigrationError(\n `Manual ${prefix} SQL dispatch ${index} must contain non-whitespace text`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const parameters = fragment.values.map((value) => encodeParameter(value));\n return {\n id: `manual:${prefix}:${index}`,\n label: \"manual\",\n origin: \"manual\" as const,\n risk: \"opaque\" as const,\n steps: [\n {\n retry: \"opaque\" as const,\n execute: addDispatch(assembly, text, parameters),\n },\n ],\n };\n });\n}\n\nexport function compileTrustedCheck(\n input: MigrationCheckInput,\n dialect: \"postgresql\" | \"mysql\" | \"sqlite\",\n assembly: SqlAssembly,\n id: string\n): MigrationBooleanCheckV1 & { readonly kind: \"trusted-read\" } {\n const text = input.query.toStatement(dialect === \"postgresql\" ? \"$n\" : \"?\");\n const parameters = input.query.values.map((value) => encodeParameter(value));\n return {\n kind: \"trusted-read\" as const,\n id,\n query: addDispatch(assembly, text, parameters),\n equals: input.equals,\n };\n}\n\nexport function sealParent(\n fromState: string | null,\n compiled: CompiledTransition\n): Omit<MigrationParentTransitionV1, \"transitionHash\"> {\n return {\n fromState,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n operations: compiled.operations,\n rollback: compiled.rollback,\n };\n}\n\nexport function hashParent(\n parent: Omit<MigrationParentTransitionV1, \"transitionHash\">\n): MigrationParentTransitionV1 {\n return { ...parent, transitionHash: encodeTransitionHash(parent) };\n}\n\nfunction addDispatch(\n assembly: SqlAssembly,\n text: string,\n parameters: readonly MigrationParameterV1[]\n): MigrationDispatchV1 {\n const index = assembly.add(text, parameters);\n return {\n dispatchId: \"0\".repeat(64),\n sqlHash: \"0\".repeat(64),\n offset: index,\n length: 0,\n parameters,\n };\n}\n\nfunction checkFromProbe(\n assembly: SqlAssembly,\n probe: CatalogProbe\n): MigrationBooleanCheckV1 {\n return {\n kind: \"driver\",\n id: probe.id,\n query: addDispatch(assembly, probe.sql, probe.parameters),\n equals: probe.equals,\n };\n}\n\nexport function rebindDispatches(\n operations: readonly MigrationOperationV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationOperationV1[] {\n return operations.map((operation) => ({\n ...operation,\n steps: operation.steps.map((step) => rebindStep(step, dispatches)),\n }));\n}\n\nfunction rebindStep(\n step: MigrationStepV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationStepV1 {\n const execute = takeDispatch(step.execute, dispatches);\n if (step.retry === \"opaque\") {\n return { retry: \"opaque\", execute };\n }\n return {\n retry: \"proven\",\n precheck: {\n ...step.precheck,\n query: takeDispatch(step.precheck.query, dispatches),\n },\n execute,\n postcheck: {\n ...step.postcheck,\n query: takeDispatch(step.postcheck.query, dispatches),\n },\n };\n}\n\nfunction takeDispatch(\n placeholder: MigrationDispatchV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationDispatchV1 {\n const found = dispatches[placeholder.offset];\n if (!found) {\n throw new MigrationError(\n \"Compiled dispatch is missing from the SQL assembly\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nexport function rebindChecks(\n checks: readonly MigrationBooleanCheckV1[],\n dispatches: readonly MigrationDispatchV1[]\n): MigrationBooleanCheckV1[] {\n return checks.map((check) => ({\n ...check,\n query: takeDispatch(check.query, dispatches),\n }));\n}\n\nexport function rebindRollback(\n rollback: MigrationRollbackV1,\n dispatches: readonly MigrationDispatchV1[]\n): MigrationRollbackV1 {\n if (rollback.kind === \"irreversible\") return rollback;\n return {\n ...rollback,\n operations: rebindDispatches(rollback.operations, dispatches),\n };\n}\n\nconst CREATE_INDEX_CONCURRENTLY = /CREATE\\s+INDEX\\s+CONCURRENTLY/i;\nconst ALTER_TYPE_ADD_VALUE = /ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE/i;\n\nfunction isNonTransactionalSql(driver: MigrationDriver, sql: string): boolean {\n if (CREATE_INDEX_CONCURRENTLY.test(sql)) return true;\n return (\n ALTER_TYPE_ADD_VALUE.test(sql) &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n );\n}\n\nexport function classifyGeneratedAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[]\n): AtomicityClass {\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n operations.some(\n (operation) =>\n operation.type === \"alterEnum\" &&\n (operation.addValues?.length ?? 0) > 0 &&\n !driver.capabilities.supportsAddEnumValueInTransaction\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function assertTransactionalBoundaryHonored(\n supportsTransactions: boolean,\n requested: \"transactional\" | \"stepwise\" | null\n): void {\n if (requested === \"transactional\" && !supportsTransactions) {\n throw new MigrationError(\n \"This producer cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n}\n\nexport function classifyStoredAtomicity(\n driver: MigrationDriver,\n requested: \"transactional\" | \"stepwise\" | null,\n operations: readonly MigrationOperationV1[],\n blob?: Uint8Array\n): AtomicityClass {\n if (requested === \"transactional\") {\n if (driver.dialect === \"mysql\") {\n throw new MigrationError(\n \"This provider cannot honor a transactional manual boundary\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n return \"transactional\";\n }\n if (requested === \"stepwise\") return \"stepwise\";\n if (driver.dialect === \"mysql\") return \"stepwise\";\n if (\n blob &&\n stepStatements(blob, operations).some((text) =>\n isNonTransactionalSql(driver, text)\n )\n ) {\n return \"stepwise\";\n }\n return \"transactional\";\n}\n\nexport function encodeParameter(value: unknown): MigrationParameterV1 {\n if (value === null || value === undefined) return { kind: \"null\" };\n if (typeof value === \"boolean\") return { kind: \"boolean\", value };\n if (typeof value === \"string\") return { kind: \"string\", value };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"SQL parameters refuse NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"number\", value };\n }\n if (typeof value === \"bigint\")\n return { kind: \"bigint\", value: value.toString() };\n if (value instanceof Date)\n return { kind: \"date-time\", value: value.toISOString() };\n if (value instanceof Uint8Array) {\n return { kind: \"bytes\", value: encodeBase64(value) };\n }\n const decimal = canonicalDecimalText(value);\n if (decimal !== undefined) return { kind: \"decimal\", value: decimal };\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n throw new MigrationError(\n \"SQL parameters refuse functions and symbols\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return { kind: \"json\", value };\n}\n\nexport function decodeParameter(\n parameter: MigrationParameterV1,\n targetNamespace?: string\n): unknown {\n switch (parameter.kind) {\n case \"null\":\n return null;\n case \"target-namespace\":\n if (targetNamespace === undefined) {\n throw new MigrationError(\n \"A stored target-namespace parameter requires a resolved migration namespace\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return targetNamespace;\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"json\":\n return parameter.value;\n case \"bigint\":\n return BigInt(parameter.value);\n case \"bytes\": {\n const bytes = decodeCanonicalBase64(parameter.value);\n if (bytes === undefined) {\n throw new MigrationError(\n \"Stored bytes parameter is not canonical Base64\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return bytes;\n }\n case \"date-time\":\n return new Date(parameter.value);\n case \"decimal\":\n return parameter.value;\n default: {\n const kind: never = parameter;\n throw new MigrationError(\n `Unknown SQL parameter kind: ${JSON.stringify(kind)}`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","/**\n * The one virtual-root snapshot. Not a stored second root.\n */\n\nimport type { SchemaSnapshot } from \"./types\";\n\nexport function emptyManagedSnapshot(): SchemaSnapshot {\n return { tables: [], enums: [] };\n}\n","/**\n * One execution owner for authenticated SQL slices and typed parameters.\n * Apply, down, reset, and push consume this. There is no second executor.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { decodeParameter } from \"./compile\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type {\n LedgerEffectStateV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\nexport async function executeExactSql(\n producer: AnyDriver,\n sql: string,\n parameters: readonly unknown[] = []\n): Promise<void> {\n await producer._executeRaw(sql, [...parameters]);\n}\n\nexport async function executeDispatch(\n producer: AnyDriver,\n blob: Uint8Array,\n dispatch: MigrationDispatchV1,\n targetNamespace?: string\n): Promise<void> {\n await executeExactSql(\n producer,\n sliceDispatch(blob, dispatch),\n dispatch.parameters.map((parameter) =>\n decodeParameter(parameter, targetNamespace)\n )\n );\n}\n\nexport async function evaluateCheck(\n producer: AnyDriver,\n blob: Uint8Array,\n check: MigrationBooleanCheckV1,\n targetNamespace?: string\n): Promise<boolean> {\n const sql = sliceDispatch(blob, check.query);\n const params = check.query.parameters.map((parameter) =>\n decodeParameter(parameter, targetNamespace)\n );\n const result = await producer._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n if (result.rows.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one row`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const values = Object.values(result.rows[0]!);\n if (values.length !== 1) {\n throw new MigrationError(\n `Check ${check.id} must return exactly one column`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return coerceBoolean(values[0], check.id) === check.equals;\n}\n\nfunction coerceBoolean(value: unknown, id: string): boolean {\n if (\n value === true ||\n value === 1 ||\n value === 1n ||\n value === \"1\" ||\n value === \"t\" ||\n value === \"true\"\n ) {\n return true;\n }\n if (\n value === false ||\n value === 0 ||\n value === 0n ||\n value === \"0\" ||\n value === \"f\" ||\n value === \"false\"\n ) {\n return false;\n }\n throw new MigrationError(\n `Check ${id} did not return a boolean`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\nexport interface StepProgress {\n readonly operationId: string;\n readonly dispatchId: string;\n readonly skipped: boolean;\n}\n\nexport async function executeOperations(\n producer: AnyDriver,\n blob: Uint8Array,\n operations: readonly MigrationOperationV1[],\n boundary: \"transactional\" | \"stepwise\",\n onProgress?: (\n progress: StepProgress,\n effect: LedgerEffectStateV1\n ) => Promise<void>,\n targetNamespace?: string\n): Promise<void> {\n for (const operation of operations) {\n for (const step of operation.steps) {\n await executeStep(\n producer,\n blob,\n operation.id,\n step,\n boundary,\n onProgress,\n targetNamespace\n );\n }\n }\n}\n\nasync function executeStep(\n producer: AnyDriver,\n blob: Uint8Array,\n operationId: string,\n step: MigrationStepV1,\n boundary: \"transactional\" | \"stepwise\",\n onProgress?: (\n progress: StepProgress,\n effect: LedgerEffectStateV1\n ) => Promise<void>,\n targetNamespace?: string\n): Promise<void> {\n if (step.retry === \"proven\") {\n if (await evaluateCheck(producer, blob, step.postcheck, targetNamespace)) {\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: true },\n \"none\"\n );\n return;\n }\n if (\n !(await evaluateCheck(producer, blob, step.precheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} is neither at origin nor destination`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { lastConfirmedStep: step.execute.dispatchId } }\n );\n }\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n if (\n !(await evaluateCheck(producer, blob, step.postcheck, targetNamespace))\n ) {\n throw new MigrationError(\n `Proven step ${operationId} failed its postcheck`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT,\n {\n meta: {\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"partial\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n\n if (boundary === \"stepwise\") {\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"none\"\n );\n try {\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n } catch (error) {\n throw new MigrationError(\n `Opaque stepwise dispatch ${step.execute.dispatchId} failed with an ambiguous outcome`,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: error instanceof Error ? error : undefined,\n meta: {\n lastConfirmedStep: step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n return;\n }\n\n await executeDispatch(producer, blob, step.execute, targetNamespace);\n await onProgress?.(\n { operationId, dispatchId: step.execute.dispatchId, skipped: false },\n \"committed\"\n );\n}\n\nexport async function evaluateAllChecks(\n producer: AnyDriver,\n blob: Uint8Array,\n checks: readonly MigrationBooleanCheckV1[],\n targetNamespace?: string\n): Promise<boolean> {\n for (const check of checks) {\n if (!(await evaluateCheck(producer, blob, check, targetNamespace))) {\n return false;\n }\n }\n return true;\n}\n","/**\n * The one DDL statement a transaction silently swallows.\n *\n * SQLite cannot alter a table in place, so `alterColumn`, `addForeignKey` and\n * both halves of a unique-constraint change go through\n * `SQLite3MigrationDriver.generateTableRecreation`: create `__new_<t>`, copy\n * the rows, `DROP TABLE <t>`, rename. `DROP TABLE` is the step that needs\n * foreign keys really disabled — with enforcement on, SQLite performs an\n * implicit `DELETE FROM` before removing the table, which either raises the\n * constraint or fires the referential action on every child row.\n *\n * `PRAGMA foreign_keys` is documented by SQLite as a NO-OP inside a\n * transaction, and all three places that execute generated DDL run the batch\n * inside one — `execute-dispatch.ts` and the SQLite recreation path.\n * MEASURED on better-sqlite3 at `5e5bc60`, recreating a populated table a\n * single child row pointed at:\n *\n * - `onDelete: noAction` -> `DROP TABLE` threw `FOREIGN KEY constraint\n * failed` and the push applied nothing;\n * - `onDelete: cascade` -> no error, and every child row was gone;\n * - `onDelete: setNull` -> no error, and every child's key was NULL.\n *\n * `PRAGMA defer_foreign_keys=ON` — the spelling SQLite does honor inside a\n * transaction — does not close it: it defers the violation counter the\n * implicit delete already incremented, so `noAction` merely moves its failure\n * from `DROP TABLE` to `COMMIT`, and the two silent halves stay silent.\n *\n * So the pragma is lifted out to bracket the transaction, which is SQLite's own\n * documented procedure — its step 1 (`PRAGMA foreign_keys=OFF`) precedes its\n * step 2 (`BEGIN`). Lifting it is what makes the disable real for the first\n * time, and a real disable is fail-open for the rest of the batch: a\n * `dropTable` sharing the batch would now orphan its children instead of\n * refusing. `assertForeignKeysIntact` is that hole closed — step 10 of the same\n * procedure — and it runs inside the transaction so a violation rolls the whole\n * batch back.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\n\n/**\n * `PRAGMA foreign_keys = OFF` / `= ON`, the only statement any migration driver\n * emits whose effect a transaction discards. Written by\n * `generateTableRecreation`; no other dialect emits it.\n */\nconst MATCH_FOREIGN_KEYS_PRAGMA =\n /^PRAGMA\\s+foreign_keys\\s*=\\s*(ON|OFF)\\s*;?$/i;\n\nexport interface ForeignKeyBracket {\n /** Runs before the transaction opens. */\n readonly disable: string;\n /** Runs after it closes, however it closes. */\n readonly enable: string;\n}\n\nexport interface LiftedStatements {\n /** `null` when nothing was lifted; the statements are then untouched. */\n readonly bracket: ForeignKeyBracket | null;\n readonly statements: string[];\n}\n\n/**\n * Takes the foreign-key pragmas out of a DDL batch so the caller can run them\n * around its transaction instead of inside it.\n *\n * Returns `bracket: null` — and the statements unchanged — when there is\n * nothing to lift or nothing to lift them out of, so every caller can run the\n * result unconditionally.\n */\n/**\n * Whether this driver has no OUTSIDE to lift the pragmas to.\n *\n * A native batch is one round trip, so the pragma would have to travel inside\n * it — the very thing that does not work. Lifting it would mean a separate\n * statement on a connection the batch does not share, which is not something\n * this repo can measure: D1 is the only batch-only SQLite driver and nothing in\n * the estate exercises it. So that batch goes through untouched, exactly as it\n * did before, and the hole stays open there and named.\n *\n * Exported because the hole is also a REFUSAL condition, not only a lifting\n * one: a table recreation that has to preserve foreign keys cannot be admitted\n * on a substrate where the disable is a no-op, so the SQLite driver asks this\n * same question before it plans one (plan §7.4's D1 prerequisite).\n */\nexport function foreignKeyPragmasCannotBeLifted(driver: AnyDriver): boolean {\n return driver.supportsBatch;\n}\n\nexport function liftForeignKeyPragmas(\n driver: AnyDriver,\n statements: string[]\n): LiftedStatements {\n if (foreignKeyPragmasCannotBeLifted(driver)) {\n return { bracket: null, statements };\n }\n\n let disable: string | null = null;\n let enable: string | null = null;\n const rest: string[] = [];\n\n for (const statement of statements) {\n const match = statement.trim().match(MATCH_FOREIGN_KEYS_PRAGMA);\n if (!match) {\n rest.push(statement);\n continue;\n }\n if (match[1]?.toUpperCase() === \"OFF\") {\n disable ??= statement.trim();\n } else {\n enable ??= statement.trim();\n }\n }\n\n // Half a bracket would leave enforcement off past the batch. Leave the batch\n // exactly as it came instead, so it fails the way it failed before rather\n // than succeeding with the database unguarded.\n if (!(disable && enable)) {\n return { bracket: null, statements };\n }\n\n return { bracket: { disable, enable }, statements: rest };\n}\n\ninterface ForeignKeyCheckRow {\n table?: unknown;\n parent?: unknown;\n}\n\n/**\n * Runs `work` with enforcement really off, restoring it however `work` ends.\n * Call it OUTSIDE the transaction `work` opens — that placement is the whole\n * point. A no-op when there is no bracket.\n */\nexport async function withForeignKeysLifted<T>(\n driver: AnyDriver,\n bracket: ForeignKeyBracket | null,\n work: () => Promise<T>\n): Promise<T> {\n if (!bracket) {\n return await work();\n }\n\n await driver._executeRaw(terminate(bracket.disable));\n try {\n return await work();\n } finally {\n await driver._executeRaw(terminate(bracket.enable));\n }\n}\n\nfunction terminate(statement: string): string {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n}\n\n/**\n * Refuses a lifted batch that would commit against a broken reference. Call it\n * from INSIDE the transaction, last, so the throw takes the batch back.\n *\n * This is why the lift is not a fail-open trade. Lifting the pragma disables\n * enforcement for the whole batch, not just the recreation, so a `dropTable`\n * or a rebuild that sheds a referenced column could commit orphans the\n * un-lifted — and therefore never actually disabled — batch would have refused.\n * `PRAGMA foreign_key_check` is step 10 of SQLite's own recreation procedure.\n *\n * It cannot tell a reference the batch broke from one it merely found, and\n * refuses either way: SQLite's procedure says a reported violation means the\n * schema change is to be abandoned.\n */\nexport async function assertForeignKeysIntact(\n driver: AnyDriver,\n bracket: ForeignKeyBracket | null\n): Promise<void> {\n if (!bracket) {\n return;\n }\n\n const result = await driver._executeRaw<ForeignKeyCheckRow>(\n \"PRAGMA foreign_key_check;\"\n );\n if (result.rows.length === 0) {\n return;\n }\n\n const offenders = [\n ...new Set(\n result.rows.map(\n (row) => `${String(row.table)} -> ${String(row.parent ?? \"?\")}`\n )\n ),\n ];\n throw new MigrationError(\n `Migration left ${result.rows.length} row(s) violating a foreign key (${offenders.join(\", \")}). ` +\n \"A SQLite table recreation runs with foreign keys disabled, so the batch was rolled back rather than committed against a broken reference.\",\n VibORMErrorCode.MIGRATION_FAILED\n );\n}\n","/**\n * One immutable estate graph. Commands consume this instance; they do not\n * rescan storage or invent apply order from names.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport type { Sha256 } from \"./identity\";\nimport { sliceDispatch, validateSqlRanges } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport {\n encodeSnapshot,\n encodeSqlBlob,\n parseEstateDescriptor,\n parseSnapshotDocument,\n parseStateManifest,\n} from \"./v1-parse\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n PathWitness,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationGraph {\n readonly estateHash: Sha256;\n readonly descriptor: MigrationEstateDescriptorV1;\n readonly states: ReadonlyMap<Sha256, MigrationStateManifestV1>;\n readonly snapshots: ReadonlyMap<Sha256, SchemaSnapshot>;\n readonly sql: ReadonlyMap<Sha256, Uint8Array>;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly emptySnapshotHash: Sha256;\n}\n\n/** Resolve one authenticated graph state to its already-parsed snapshot. */\nexport function requireStateSnapshot(\n graph: MigrationGraph,\n stateId: Sha256 | null\n): SchemaSnapshot {\n const snapshotHash =\n stateId === null\n ? graph.emptySnapshotHash\n : graph.states.get(stateId)?.snapshotHash;\n const snapshot = snapshotHash ? graph.snapshots.get(snapshotHash) : undefined;\n if (!snapshot) {\n throw new MigrationError(\n \"A selected state is missing its authenticated snapshot\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\nexport async function loadMigrationGraph(\n storage: MigrationStorageReader\n): Promise<MigrationGraph> {\n const estateBytes = await storage.readEstate();\n if (!estateBytes) {\n throw new MigrationError(\n \"Estate descriptor is missing\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const { descriptor, estateHash } = parseEstateDescriptor(estateBytes);\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n const stateIds = await storage.listStates();\n const states = new Map<Sha256, MigrationStateManifestV1>();\n const neededSnapshots = new Set<Sha256>([emptySnapshotHash]);\n const neededSql = new Set<Sha256>();\n\n for (const id of stateIds) {\n const bytes = await storage.readState(id);\n if (!bytes) {\n throw new MigrationError(\n `State ${id} is listed but unreadable`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (states.has(id)) {\n throw new MigrationError(\n `State ${id} is listed more than once`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const manifest = parseStateManifest(bytes, id);\n if (manifest.estateHash !== estateHash) {\n throw new MigrationError(\n `State ${id} belongs to a different estate`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n states.set(id, manifest);\n neededSnapshots.add(manifest.snapshotHash);\n neededSql.add(manifest.sqlHash);\n }\n\n const snapshots = new Map<Sha256, SchemaSnapshot>();\n snapshots.set(emptySnapshotHash, emptyManagedSnapshot());\n for (const hash of neededSnapshots) {\n if (hash === emptySnapshotHash) continue;\n const bytes = await storage.readSnapshot(hash);\n if (!bytes) {\n throw new MigrationError(\n `Snapshot ${hash} is referenced but missing`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n snapshots.set(hash, parseSnapshotDocument(bytes, hash));\n }\n\n const sql = new Map<Sha256, Uint8Array>();\n for (const hash of neededSql) {\n const bytes = await storage.readSql(hash);\n if (!bytes) {\n throw new MigrationError(\n `SQL blob ${hash} is referenced but missing`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (encodeSqlBlob(bytes) !== hash) {\n throw new MigrationError(\n `SQL blob ${hash} does not match its bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n sql.set(hash, bytes);\n }\n\n for (const manifest of states.values()) {\n const blob = sql.get(manifest.sqlHash);\n if (!blob) continue;\n const dispatches: MigrationDispatchV1[] = [];\n for (const parent of manifest.parents) {\n collectDispatches(parent, dispatches);\n }\n collectChecks(manifest.destinationChecks, dispatches);\n validateSqlRanges(blob, dispatches);\n assertStoredParameterDialect(\n dispatches,\n descriptor.target.dialect,\n manifest.name\n );\n assertArtifactExecutionSafe(\n dispatches.map((dispatch) => sliceDispatch(blob, dispatch)),\n descriptor.target.dialect,\n manifest.name\n );\n }\n\n const outgoing = new Map<Sha256, Sha256[]>();\n for (const id of states.keys()) {\n outgoing.set(id, []);\n }\n\n for (const [id, manifest] of states) {\n for (const parent of manifest.parents) {\n if (parent.fromState === null) continue;\n if (!states.has(parent.fromState)) {\n throw new MigrationError(\n `State ${id} has a dangling parent`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n outgoing.get(parent.fromState)!.push(id);\n }\n }\n\n const roots = [...states.keys()].filter((id) =>\n states.get(id)!.parents.some((parent) => parent.fromState === null)\n );\n const leaves = [...states.keys()].filter(\n (id) => (outgoing.get(id) ?? []).length === 0\n );\n assertNoCycle(states, outgoing);\n\n if (states.size > 0 && roots.length === 0) {\n throw new MigrationError(\n \"Estate has states but no virtual-root transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n assertReachableFromEmpty(states, outgoing, roots);\n\n return {\n estateHash,\n descriptor,\n states,\n snapshots,\n sql,\n roots,\n leaves,\n emptySnapshotHash,\n };\n}\n\n/**\n * The symbolic namespace is one portable MySQL artifact value. PostgreSQL\n * stores its schema in the estate target and SQLite has no namespace, so the\n * tag in either estate is corruption rather than an executable parameter.\n */\nfunction assertStoredParameterDialect(\n dispatches: readonly MigrationDispatchV1[],\n dialect: MigrationEstateDescriptorV1[\"target\"][\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"mysql\") {\n return;\n }\n for (const dispatch of dispatches) {\n if (\n dispatch.parameters.some(\n (parameter) => parameter.kind === \"target-namespace\"\n )\n ) {\n throw new MigrationError(\n `Migration \"${artifact}\" contains a target-namespace parameter outside a MySQL estate`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n }\n }\n}\n\nfunction collectDispatches(\n parent: MigrationParentTransitionV1,\n into: MigrationDispatchV1[]\n): void {\n collectChecks(parent.originChecks, into);\n collectOperations(parent.operations, into);\n if (parent.rollback.kind !== \"irreversible\") {\n collectOperations(parent.rollback.operations, into);\n }\n}\n\nfunction collectOperations(\n operations: readonly MigrationOperationV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const operation of operations) {\n for (const step of operation.steps) {\n if (step.retry === \"proven\") {\n into.push(step.precheck.query);\n }\n into.push(step.execute);\n if (step.retry === \"proven\") {\n into.push(step.postcheck.query);\n }\n }\n }\n}\n\nfunction collectChecks(\n checks: readonly MigrationBooleanCheckV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const check of checks) {\n into.push(check.query);\n }\n}\n\nfunction assertNoCycle(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>\n): void {\n const color = new Map<Sha256, 0 | 1 | 2>();\n for (const id of states.keys()) color.set(id, 0);\n for (const start of states.keys()) {\n if (color.get(start) !== 0) continue;\n const stack: Array<{ id: Sha256; next: number }> = [{ id: start, next: 0 }];\n color.set(start, 1);\n while (stack.length > 0) {\n const frame = stack.at(-1)!;\n const edges = outgoing.get(frame.id) ?? [];\n if (frame.next < edges.length) {\n const next = edges[frame.next++]!;\n const seen = color.get(next) ?? 0;\n if (seen === 1) {\n throw new MigrationError(\n \"Estate graph contains a cycle\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (seen === 0) {\n color.set(next, 1);\n stack.push({ id: next, next: 0 });\n }\n continue;\n }\n color.set(frame.id, 2);\n stack.pop();\n }\n }\n}\n\nfunction assertReachableFromEmpty(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>,\n roots: readonly Sha256[]\n): void {\n const reachable = new Set<Sha256>();\n const pending = [...roots];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (reachable.has(id)) continue;\n reachable.add(id);\n for (const child of outgoing.get(id) ?? []) {\n pending.push(child);\n }\n }\n for (const id of states.keys()) {\n if (!reachable.has(id)) {\n throw new MigrationError(\n `State ${id} is not reachable from the empty state`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function resolveStateSelector(\n graph: MigrationGraph,\n selector: StateSelector | undefined\n): Sha256 {\n if (!selector) {\n if (graph.leaves.length === 1) return graph.leaves[0]!;\n if (graph.leaves.length === 0) {\n throw new MigrationError(\n \"Estate has no states to target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(graph.leaves.map((leaf) => [leaf]));\n }\n if (\"id\" in selector) {\n if (!graph.states.has(selector.id)) {\n throw new MigrationError(\n `Unknown state ${selector.id}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return selector.id;\n }\n if (\"prefix\" in selector) {\n const matches = [...graph.states.keys()].filter((id) =>\n id.startsWith(selector.prefix)\n );\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state has prefix ${selector.prefix}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(matches.map((id) => [id]));\n }\n const matches = [...graph.states.values()]\n .filter((state) => state.name === selector.name)\n .map((state) => state.stateId);\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state is named ${selector.name}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(matches.map((id) => [id]));\n}\n\nexport function selectRoute(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n via?: readonly Sha256[]\n): readonly Sha256[] {\n if (via && via.length > 0) {\n if (via.at(-1) !== target) {\n throw new MigrationError(\n \"via must end at the resolved target\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n const seen = new Set<string>();\n let previous = origin;\n for (const step of via) {\n if (seen.has(step)) {\n throw new MigrationError(\n \"via repeats a state\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n seen.add(step);\n if (!hasEdge(graph, previous, step)) {\n throw new MigrationError(\n \"via is not a real estate edge\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n previous = step;\n }\n return via;\n }\n\n const routes = enumerateRoutes(graph, origin, target, 2);\n if (routes.length === 1) return routes[0]!;\n if (routes.length === 0) {\n throw new MigrationError(\n \"No path exists from the current marker to the target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(routes);\n}\n\nfunction hasEdge(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): boolean {\n const state = graph.states.get(to);\n if (!state) return false;\n return state.parents.some((parent) => parent.fromState === from);\n}\n\nfunction childrenIndex(graph: MigrationGraph): Map<string, Sha256[]> {\n const index = new Map<string, Sha256[]>();\n index.set(\"null\", []);\n for (const id of graph.states.keys()) {\n index.set(id, []);\n }\n for (const [id, state] of graph.states) {\n for (const parent of state.parents) {\n const key = parent.fromState ?? \"null\";\n const list = index.get(key) ?? [];\n list.push(id);\n index.set(key, list);\n }\n }\n return index;\n}\n\nfunction enumerateRoutes(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n limit: number\n): Sha256[][] {\n const children = childrenIndex(graph);\n const found: Sha256[][] = [];\n const stack: Array<{ from: Sha256 | null; path: Sha256[] }> = [\n { from: origin, path: [] },\n ];\n while (stack.length > 0 && found.length < limit) {\n const frame = stack.pop()!;\n for (const child of children.get(frame.from ?? \"null\") ?? []) {\n if (frame.path.includes(child)) continue;\n const next = [...frame.path, child];\n if (child === target) {\n found.push(next);\n if (found.length >= limit) break;\n continue;\n }\n stack.push({ from: child, path: next });\n }\n }\n return found;\n}\n\nfunction pathRequired(routes: readonly (readonly Sha256[])[]): never {\n const witness: PathWitness = {\n routes: routes.slice(0, 2),\n frontier: firstFrontier(routes),\n more: routes.length > 2,\n };\n throw new MigrationError(\n `Multiple migration paths exist; pass via. Candidates: ${witness.routes\n .map((route) => route.join(\" -> \"))\n .join(\" | \")}`,\n VibORMErrorCode.MIGRATION_PATH_REQUIRED,\n { meta: { pathWitness: witness } }\n );\n}\n\nfunction firstFrontier(routes: readonly (readonly Sha256[])[]): Sha256[] {\n if (routes.length < 2) return [];\n const first = routes[0]!;\n const second = routes[1]!;\n const frontier: Sha256[] = [];\n const max = Math.min(first.length, second.length);\n for (let i = 0; i < max; i++) {\n if (first[i] !== second[i]) {\n frontier.push(first[i]!, second[i]!);\n return frontier;\n }\n }\n return frontier;\n}\n\nexport function parentTransition(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): MigrationParentTransitionV1 {\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n `Unknown state ${to}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const found = state.parents.find((parent) => parent.fromState === from);\n if (!found) {\n throw new MigrationError(\n \"Selected edge has no parent transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return found;\n}\n","/**\n * The one conversion no dialect can perform in SQL: a column BECOMING binary.\n *\n * Every generated `ALTER COLUMN` is a blind re-reading of the bytes already\n * stored. That is harmless when the two types share a reading — `varchar(40)`\n * and `text` are the same characters, `numeric(10,2)` and `numeric(12,2)` the\n * same number — and it is data loss the moment the target is a BINARY column,\n * because the only cast a dialect offers there re-encodes the source's own\n * spelling:\n *\n * · PostgreSQL's `USING col::bytea` writes the ASCII of the old text. A\n * 26-character ULID becomes 26 bytes, not the 16 its codec reads, and every\n * later read is refused as \"not in this column's declared identifier\n * domain\" (measured live on PostgreSQL 16).\n * · SQLite's table rebuild copies the value VERBATIM into the new BLOB\n * column, so `typeof()` still answers `'text'` afterwards — the migration\n * type and the engine binding disagree with no error at all.\n * · MySQL's `MODIFY COLUMN … BINARY(n)` truncates or pads to the declared\n * width without a word in a non-strict `sql_mode`.\n *\n * So the conversion is REFUSED where it is generated, with the manual route\n * named. This is the rule `docs/architecture/native-ids-plan.md` §3 states for\n * an identifier (\"a blind `USING col::bytea` would re-encode text bytes, so it\n * is never emitted\"), and it is stated here in the terms a migration driver\n * actually has: the two column TYPES. A snapshot carries no logical marker that\n * would say \"this BLOB decodes identifiers\", and it does not need one — a\n * verbatim copy into a binary column is unreadable whatever the column holds.\n *\n * PostgreSQL's `uuid` target is deliberately NOT here. `col::uuid` is a real\n * conversion PostgreSQL performs value by value: it succeeds for an estate of\n * canonical uuids and aborts the whole transaction for one that is not, leaving\n * the column as it was. That is a conversion with a wrong answer for nobody.\n *\n * Pure and connection-free, like every other module in this layer.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { Dialect } from \"./drivers/types\";\n\n/** MySQL's two width-carrying binary column spellings. */\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\(\\d+\\)$/i;\nconst MYSQL_BLOB_FAMILY = /^(?:TINYBLOB|BLOB|MEDIUMBLOB|LONGBLOB)$/i;\n\n/** Whether this dialect spells `type` as a column of raw bytes. */\nfunction isBinaryColumnType(type: string, dialect: Dialect): boolean {\n const spelling = type.trim();\n switch (dialect) {\n case \"postgresql\":\n return spelling.toLowerCase() === \"bytea\";\n case \"mysql\":\n return (\n MYSQL_SIZED_BINARY.test(spelling) || MYSQL_BLOB_FAMILY.test(spelling)\n );\n default:\n return spelling.toUpperCase() === \"BLOB\";\n }\n}\n\n/**\n * Refuse an alteration that turns a non-binary column into a binary one.\n *\n * Both sides binary is a WIDTH change and is left alone: `VARBINARY(100)` to\n * `VARBINARY(200)` re-reads the same bytes as the same bytes, which is the\n * property this refusal exists to require.\n */\nexport function refuseBinaryReencoding(\n table: string,\n column: string,\n fromType: string,\n toType: string,\n dialect: Dialect\n): void {\n if (!isBinaryColumnType(toType, dialect)) return;\n if (isBinaryColumnType(fromType, dialect)) return;\n throw new MigrationError(\n `Column \"${column}\" of \"${table}\" would change from ${fromType} to ${toType}, and no dialect can re-read the stored values as bytes: ` +\n \"the generated cast would store the old value's own spelling, which nothing can decode afterwards. \" +\n \"Convert the rows yourself — add the new column, write the decoded values into it, drop the old one and rename — \" +\n \"or, for a declared identifier format, keep the column as it is with a text-family native type, which validates the domain without changing storage.\",\n VibORMErrorCode.INVALID_INPUT\n );\n}\n","import { stringifyJson } from \"../../adapters/shared/standard-sql\";\n/**\n * MigrationDriver Base Class\n *\n * Abstract base class for database-specific migration drivers.\n * Each driver implements DDL generation and introspection for its database.\n */\n\nimport { jsonNullKindOf } from \"@schema/json-null\";\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport {\n type DecimalDialect,\n decimalDefaultText,\n decimalListDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { refuseBinaryReencoding } from \"../binary-conversion\";\nimport {\n applyNativeRename,\n type NativeRenameOperation,\n} from \"../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n MigrationTarget,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n} from \"../types\";\nimport { defaultGeneratedPrimaryKeyName } from \"../utils\";\nimport type { Dialect, MigrationCapabilities } from \"./types\";\n\n/**\n * Context passed to DDL generation methods.\n * Contains information needed for operations that require knowledge of the current schema.\n */\nexport interface DDLContext {\n /**\n * Where the rendered statement is going.\n *\n * REQUIRED, and deliberately not defaulted anywhere: an artifact is durable\n * and a live statement is not, and the two differ for MySQL (relative\n * artifacts, qualified live SQL). A dispatcher default would reintroduce\n * exactly the implicit mode this fact replaces, so every caller states it.\n * Generation and generated rollback pass `\"artifact\"`; push, live reset and\n * every immediate DDL path pass `\"live\"`. SQLite ignores the distinction.\n */\n readonly destination: \"artifact\" | \"live\";\n\n /**\n * Current database schema snapshot.\n * Required for SQLite table recreation operations.\n */\n currentSchema?: SchemaSnapshot;\n\n /**\n * The operations of this batch that run *before* the one being generated.\n *\n * `currentSchema` is introspected once, before the batch starts, so on its\n * own it describes the database as it was — not as the statements already\n * emitted have left it. A SQLite table recreation has to name the indexes the\n * table holds at the moment it runs, because `DROP TABLE` takes them with it;\n * see `SQLite3MigrationDriver.getCurrentTable`.\n */\n precedingOperations?: DiffOperation[];\n /** Remaining intent in this same compilation batch, for physical coalescing. */\n followingOperations?: readonly DiffOperation[];\n}\n\n// Extract individual operation types from the DiffOperation union\nexport type CreateTableOperation = Extract<\n DiffOperation,\n { type: \"createTable\" }\n>;\nexport type DropTableOperation = Extract<DiffOperation, { type: \"dropTable\" }>;\nexport type RenameTableOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" }\n>;\nexport type AddColumnOperation = Extract<DiffOperation, { type: \"addColumn\" }>;\nexport type DropColumnOperation = Extract<\n DiffOperation,\n { type: \"dropColumn\" }\n>;\nexport type RenameColumnOperation = Extract<\n DiffOperation,\n { type: \"renameColumn\" }\n>;\nexport type AlterColumnOperation = Extract<\n DiffOperation,\n { type: \"alterColumn\" }\n>;\nexport type CreateIndexOperation = Extract<\n DiffOperation,\n { type: \"createIndex\" }\n>;\nexport type DropIndexOperation = Extract<DiffOperation, { type: \"dropIndex\" }>;\nexport type AddForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"addForeignKey\" }\n>;\nexport type DropForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"dropForeignKey\" }\n>;\nexport type AddUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"addUniqueConstraint\" }\n>;\nexport type DropUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"dropUniqueConstraint\" }\n>;\nexport type AddPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"addPrimaryKey\" }\n>;\nexport type DropPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"dropPrimaryKey\" }\n>;\nexport type CreateEnumOperation = Extract<\n DiffOperation,\n { type: \"createEnum\" }\n>;\nexport type DropEnumOperation = Extract<DiffOperation, { type: \"dropEnum\" }>;\nexport type AlterEnumOperation = Extract<DiffOperation, { type: \"alterEnum\" }>;\n\n/**\n * Abstract base class for migration drivers.\n *\n * Each database (PostgreSQL, SQLite, LibSQL, etc.) extends this class\n * to provide database-specific DDL generation and schema introspection.\n */\nexport abstract class MigrationDriver {\n /**\n * The SQL dialect this driver targets.\n */\n abstract readonly dialect: Dialect;\n\n /**\n * The specific driver name (e.g., \"pg\", \"postgres\", \"pglite\", \"sqlite3\", \"libsql\").\n * Used for driver-specific registration and lookup.\n */\n abstract readonly driverName: string;\n\n /**\n * Capabilities supported by this driver.\n */\n abstract readonly capabilities: MigrationCapabilities;\n\n // ===========================================================================\n // ESTATE BINDING (installed by the registry, never mutated on a singleton)\n // ===========================================================================\n\n // All three are `declare`: the class DECLARES the shape a bound view has and\n // emits no field for it. Under `useDefineForClassFields` (tsconfig target\n // es2022) an ordinary optional field would install a writable, enumerable own\n // property valued `undefined` on the REGISTERED SINGLETON — module-level\n // state that `Reflect.set` could then fill in, which §3.1 forbids. With\n // `declare`, `\"namespace\" in postgresMigrationDriver` is false, and the only\n // instances carrying these facts are the frozen views the registry defines\n // them on.\n\n /**\n * The estate target this instance is bound to.\n *\n * Absent on the REGISTERED singleton, which stays stateless: binding happens\n * at lookup and produces a separate frozen view whose prototype is the\n * singleton. Renderers that need the estate must handle the unbound case\n * rather than assume one, because a singleton reached by name renders\n * artifact SQL with no estate behind it.\n */\n declare readonly target?: MigrationTarget;\n\n /**\n * The exact concrete execution driver this instance was bound to, retained\n * for live admission (its immutable attestation) and for the adapter's\n * capabilities. Absent on the unbound singleton.\n */\n declare readonly executionDriver?: AnyDriver;\n\n /**\n * The live execution namespace read once from the bound adapter.\n *\n * Present for PostgreSQL (its target proved it) and for a bound MySQL\n * adapter; absent for an unbound MySQL adapter used for artifact-only work\n * and for SQLite, which has no namespace.\n */\n declare readonly namespace?: string;\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Introspects the current database schema.\n *\n * @param executeRaw - Function to execute raw SQL queries\n * @returns The current schema snapshot\n */\n abstract introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<SchemaSnapshot>;\n\n /**\n * Proves external physical requirements encoded by authenticated snapshots.\n * Dialects with no such requirement keep the no-op owner here.\n */\n async preflightSchemaRequirements(\n _snapshots: readonly SchemaSnapshot[],\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<void> {\n // Most dialects have no external schema requirement to prove.\n }\n\n /**\n * Returns this database's own spelling of each declared partial-index\n * predicate, so the differ can compare a declaration against what the catalog\n * gave back (Decision 7.4).\n *\n * Optional, and implemented only where the two spellings can differ.\n * PostgreSQL deparses through `pg_get_expr`, so a declared `active = true`\n * reads back as `(active = true)` and every push re-creates the index;\n * SQLite stores the CREATE INDEX statement verbatim and has nothing to\n * reconcile; MySQL refuses a partial index outright.\n *\n * `executeRaw` runs on ONE pinned connection for the whole call — the\n * canonicalization may need session-local scratch objects, which a pooled\n * connection per statement would scatter. Positional result; `undefined` at\n * a position means the database did not answer, and the differ then refuses\n * to call that predicate equal to anything.\n */\n canonicalizeIndexPredicates?(\n tableName: string,\n predicates: readonly string[],\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<ReadonlyArray<string | undefined>>;\n\n /**\n * Explains why one inverted operation cannot be rendered as an automatic\n * rollback on this dialect. Generation owns the persisted rollback policy;\n * the driver owns the physical boundary that makes an inverse unsafe.\n */\n getIrreversibleRollbackReason(_operation: DiffOperation): string | undefined {\n return undefined;\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n /**\n * Maps a VibORM scalar type to the native database column type.\n *\n * @param scalar - The scalar definition\n * @param scalarState - The scalar state with type info\n * @returns The native column type string\n */\n /**\n * `idDomain` is the identifier domain this column holds, which a foreign key\n * DERIVES from the key it references and therefore cannot be read off the\n * scalar. The physical type comes from the one storage owner\n * ({@link idStorageOf}), so the column this creates and the parameter the\n * engine binds into it are one decision.\n */\n abstract mapScalarType(\n scalar: Scalar,\n scalarState: ScalarState,\n idDomain?: IdDomain\n ): string;\n\n /**\n * Final pass over a serialized table before diffing/DDL generation.\n * Lets drivers apply table-aware type adjustments (e.g. MySQL rewrites\n * keyed TEXT columns to VARCHAR, since TEXT cannot be indexed without a\n * key length). Default: identity.\n */\n finalizeTable(table: TableDef): TableDef {\n return table;\n }\n\n /** The exact generated PK name used by this driver's DDL and its inverse. */\n generatedPrimaryKeyName(tableName: string, name?: string): string {\n return defaultGeneratedPrimaryKeyName(tableName, name);\n }\n\n /** Project exactly this driver's compiled rename before diffing or inversion. */\n projectNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n ): SchemaSnapshot {\n return applyNativeRename(snapshot, operation);\n }\n\n // Note: getDefaultExpression is implemented below as a common method\n // Override it in subclasses only if database-specific behavior is needed\n\n /**\n * Gets the column type for an enum field.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param values - The enum values\n * @returns The column type (e.g., \"users_status_enum\" for PG, \"TEXT\" for SQLite)\n */\n abstract getEnumColumnType(\n tableName: string,\n columnName: string,\n values: string[]\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n abstract generateCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): string;\n abstract generateDropTable(\n op: DropTableOperation,\n context: DDLContext\n ): string;\n abstract generateRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n abstract generateAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): string;\n abstract generateDropColumn(\n op: DropColumnOperation,\n context: DDLContext\n ): string;\n abstract generateRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): string;\n abstract generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n abstract generateCreateIndex(\n op: CreateIndexOperation,\n context: DDLContext\n ): string;\n abstract generateDropIndex(\n op: DropIndexOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n abstract generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string;\n abstract generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n abstract generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): string;\n abstract generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n abstract generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): string;\n abstract generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n abstract generateCreateEnum(\n op: CreateEnumOperation,\n context: DDLContext\n ): string;\n abstract generateDropEnum(op: DropEnumOperation, context: DDLContext): string;\n abstract generateAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL COMPILATION\n // ===========================================================================\n\n protected filterStatements(\n statements: readonly (string | null | undefined)[]\n ): string[] {\n return statements.filter(\n (statement): statement is string =>\n statement !== null &&\n statement !== undefined &&\n statement.trim().length > 0\n );\n }\n\n compileCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateCreateTable(op, context)]);\n }\n\n compileDropTable(\n op: DropTableOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropTable(op, context)]);\n }\n\n compileRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateRenameTable(op, context)]);\n }\n\n compileAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateAddColumn(op, context)]);\n }\n\n compileDropColumn(\n op: DropColumnOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropColumn(op, context)]);\n }\n\n compileRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateRenameColumn(op, context)]);\n }\n\n compileAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateAlterColumn(op, context)]);\n }\n\n compileCreateIndex(\n op: CreateIndexOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateCreateIndex(op, context)]);\n }\n\n compileDropIndex(\n op: DropIndexOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropIndex(op, context)]);\n }\n\n compileAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateAddForeignKey(op, context)]);\n }\n\n compileDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropForeignKey(op, context)]);\n }\n\n compileAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([\n this.generateAddUniqueConstraint(op, context),\n ]);\n }\n\n compileDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([\n this.generateDropUniqueConstraint(op, context),\n ]);\n }\n\n compileAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateAddPrimaryKey(op, context)]);\n }\n\n compileDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropPrimaryKey(op, context)]);\n }\n\n compileCreateEnum(\n op: CreateEnumOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateCreateEnum(op, context)]);\n }\n\n compileDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateDropEnum(op, context)]);\n }\n\n compileAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements([this.generateAlterEnum(op, context)]);\n }\n\n /**\n * Resolves the replacement for a removed enum value on a specific column.\n * Precedence: per-column mapping (columnValueReplacements, keyed\n * \"tableName.columnName\") → flat valueReplacements → defaultReplacement.\n * Returns undefined when no replacement is configured.\n */\n protected getEnumValueReplacement(\n op: AlterEnumOperation,\n tableName: string,\n columnName: string,\n removedValue: string\n ): string | null | undefined {\n const perColumn =\n op.columnValueReplacements?.[`${tableName}.${columnName}`];\n if (perColumn && removedValue in perColumn) {\n return perColumn[removedValue];\n }\n if (op.valueReplacements && removedValue in op.valueReplacements) {\n return op.valueReplacements[removedValue];\n }\n return op.defaultReplacement;\n }\n\n /**\n * Builds the UPDATE statements that migrate rows off removed enum values,\n * honoring per-column mappings. Dialects run these before the type change\n * (Postgres: while columns are text; MySQL: before MODIFY COLUMN; SQLite:\n * before table recreation).\n */\n protected buildEnumReplacementUpdates(op: AlterEnumOperation): string[] {\n const { removeValues, dependentColumns } = op;\n if (!(removeValues?.length && dependentColumns?.length)) {\n return [];\n }\n\n const statements: string[] = [];\n for (const { tableName, columnName } of dependentColumns) {\n for (const removedValue of removeValues) {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n removedValue\n );\n if (replacement === undefined) {\n continue;\n }\n const newValue =\n replacement === null ? \"NULL\" : this.escapeValue(replacement);\n statements.push(\n `UPDATE ${this.escapeIdentifier(tableName)} SET ${this.escapeIdentifier(columnName)} = ${newValue} WHERE ${this.escapeIdentifier(columnName)} = ${this.escapeValue(removedValue)}`\n );\n }\n }\n return statements;\n }\n\n // ===========================================================================\n // HELPER METHODS (can be overridden)\n // ===========================================================================\n\n /**\n * Escapes an identifier (table name, column name, etc.).\n * Default uses double quotes with proper escaping.\n */\n 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 * Escapes a string value for SQL.\n * Default uses single quotes with proper escaping.\n * Returns \"NULL\" for null/undefined values.\n */\n escapeValue(value: string | null | undefined): string {\n if (value == null) {\n return \"NULL\";\n }\n return `'${String(value).replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Formats a referential action for foreign keys.\n */\n formatReferentialAction(action: ReferentialAction): string {\n switch (action) {\n case \"cascade\":\n return \"CASCADE\";\n case \"setNull\":\n return \"SET NULL\";\n case \"restrict\":\n return \"RESTRICT\";\n case \"setDefault\":\n return \"SET DEFAULT\";\n default:\n return \"NO ACTION\";\n }\n }\n\n // ===========================================================================\n // COMMON IMPLEMENTATIONS (can be overridden for database-specific behavior)\n // ===========================================================================\n\n /**\n * Gets the SQL default expression for a field.\n * Common implementation that handles most cases.\n * Override for database-specific behavior (e.g., UUID generation, boolean representation).\n *\n * @param scalar - The scalar declaration, including its native type\n * @param scalarState - The scalar state\n * @returns SQL default expression or undefined if no default\n */\n getDefaultExpression(\n _scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n // Auto-generated values - check for database-level support first\n if (scalarState.autoGenerate) {\n return this.getAutoGenerateExpression(scalarState.autoGenerate);\n }\n\n // Check for explicit default value\n if (!scalarState.hasDefault || scalarState.default === undefined) {\n return undefined;\n }\n\n const defaultVal = this.literalDefaultValue(scalarState);\n\n // Function defaults are generated at runtime\n if (typeof defaultVal === \"function\") {\n return undefined;\n }\n\n // A JSON null document and absent SQL value are distinct physical defaults.\n // Scalar admission already resolves bare-null ambiguity and authenticates\n // sentinels; JSON primitives must also be quoted as documents, not SQL data.\n if (scalarState.type === \"json\" && !scalarState.array) {\n const kind = jsonNullKindOf(defaultVal);\n if (kind === \"DbNull\")\n return this.dialect === \"sqlite\" ? \"NULL\" : undefined;\n if (kind === \"JsonNull\") return this.escapeValue(\"null\");\n // A schema's null output is a document; only the original nullable\n // bare-null default declares an absent SQL value.\n if (defaultVal === null && scalarState.default !== null)\n return this.escapeValue(\"null\");\n if (\n defaultVal !== null &&\n [\"string\", \"number\", \"boolean\"].includes(typeof defaultVal)\n )\n return this.escapeValue(stringifyJson(defaultVal));\n }\n\n // Null default\n if (defaultVal === null) {\n return \"NULL\";\n }\n\n // A literal decimal-list default is already a trusted list of canonical\n // logical strings: the field codec normalized it at `.default()`. Render\n // its provider value through that same codec, then let the migration driver\n // own quoting and MySQL's required expression parentheses. No generic\n // array/object default enters this arm.\n if (scalarState.decimal && scalarState.array && Array.isArray(defaultVal)) {\n return this.escapeValue(\n decimalListDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n )\n );\n }\n\n if (scalarState.array && Array.isArray(defaultVal))\n return this.escapeValue(stringifyJson(defaultVal));\n if (scalarState.type === \"json\" && typeof defaultVal === \"object\")\n return this.escapeValue(stringifyJson(defaultVal));\n if (typeof defaultVal === \"bigint\") return defaultVal.toString();\n\n // Primitive defaults\n if (typeof defaultVal === \"string\") {\n // A decimal default is canonical text by the time it reaches here\n // (`.default()` normalizes at definition time), and canonical text is the\n // WRONG DDL spelling: it strips trailing zeros, while MySQL reads a\n // `DECIMAL(p,s)` default back from `information_schema` padded to the\n // scale. Two renderings, one owner — this is the DDL one, and emitting\n // the identity one instead would make the differ see a changed default\n // on every push. It is also unquoted, because a decimal default is a\n // numeric literal and not a string on any of the three dialects.\n if (scalarState.decimal) {\n return decimalDefaultText(\n this.decimalDialect(),\n defaultVal,\n scalarState.decimal\n );\n }\n return this.escapeValue(defaultVal);\n }\n if (typeof defaultVal === \"number\") {\n if (!Number.isFinite(defaultVal)) {\n throw new MigrationError(\n `Invalid default value: ${defaultVal} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return String(defaultVal);\n }\n if (typeof defaultVal === \"boolean\") {\n return this.formatBooleanDefault(defaultVal);\n }\n\n // Arrays and objects are handled at application level, not as SQL defaults\n if (typeof defaultVal === \"object\") {\n return undefined;\n }\n\n return undefined;\n }\n\n /** Literal defaults cross the scalar's authoritative write admission once. */\n protected literalDefaultValue(state: ScalarState): unknown {\n const value = state.default;\n if (\n value == null ||\n typeof value === \"function\" ||\n state.autoGenerate ||\n jsonNullKindOf(value) ||\n state.decimal !== undefined\n )\n return value;\n if (typeof value === \"number\" && !Number.isFinite(value))\n throw new MigrationError(\n `Invalid default value: ${value} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n const result = state.base[\"~standard\"].validate(value);\n if (!(\"value\" in result))\n throw new MigrationError(\n `Invalid ${state.type} literal default; the declared scalar schema refused it before DDL.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return result.value;\n }\n\n /**\n * Formats a boolean default value.\n * Override for databases that use different representations (e.g., SQLite uses 1/0).\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? \"true\" : \"false\";\n }\n\n /**\n * This driver's dialect in the codec's vocabulary.\n *\n * Two vocabularies exist because they name different things: `Dialect` is the\n * migration ESTATE's dialect, and `DecimalDialect` is the set of dialects\n * that spell a fixed decimal differently. They are not extended together, so\n * the translation is stated once here rather than at each of the codec's\n * call sites.\n */\n protected decimalDialect(): DecimalDialect {\n if (this.dialect === \"postgresql\") return \"pg\";\n if (this.dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n }\n\n /**\n * Gets the SQL expression for an auto-generated value.\n * Override for databases that support specific generation functions.\n *\n * By default, returns undefined for all types (handled at application level).\n * PostgreSQL overrides this to use gen_random_uuid() for UUID.\n *\n * @param autoGenerate - The auto-generate type\n * @returns SQL expression or undefined if handled at application level\n */\n protected getAutoGenerateExpression(\n _autoGenerate: ScalarState[\"autoGenerate\"]\n ): string | undefined {\n // By default, all auto-generate types are handled at application level\n // Databases can override to provide native support (e.g., gen_random_uuid())\n return undefined;\n }\n\n /**\n * Validates an index type against supported capabilities.\n * Throws MigrationError if the index type is not supported.\n *\n * @param indexType - The index type to validate (e.g., \"btree\", \"hash\", \"gin\")\n * @param indexName - The index name (for error messages)\n */\n protected validateIndexType(\n indexType: string | undefined,\n indexName: string\n ): void {\n if (!indexType) return; // Default index type is always supported\n\n const supported = this.capabilities.supportsIndexTypes;\n if (!supported.includes(indexType)) {\n throw new MigrationError(\n `Index \"${indexName}\" uses unsupported index type \"${indexType}\". ` +\n `Supported types for ${this.dialect}: ${supported.join(\", \")}`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Generates a column definition string.\n * Common implementation that can be overridden for database-specific syntax.\n *\n * @param column - The column definition\n * @returns SQL column definition string\n */\n protected generateColumnDef(column: ColumnDef, context: DDLContext): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n\n // Handle type (may be overridden for auto-increment handling)\n const columnType = this.formatColumnType(column, context);\n parts.push(columnType);\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // DEFAULT clause (skip for auto-increment columns)\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Formats the column type, handling auto-increment and other special cases.\n * Override for database-specific type handling (e.g., PostgreSQL SERIAL).\n *\n * Takes the DDL context because a column type can name a managed enum type,\n * and a managed enum type is qualified exactly like any other persistent\n * object — which is a destination-dependent decision.\n */\n protected formatColumnType(column: ColumnDef, _context: DDLContext): string {\n return column.type;\n }\n\n // ===========================================================================\n // LIVE CONTROL AND NAMESPACE\n // ===========================================================================\n\n /**\n * Proves the configured namespace exists before an empty inventory or an\n * empty applied set may be published.\n *\n * A catalog-driven read cannot otherwise tell a configured-but-absent\n * namespace from an existing namespace holding zero managed objects, and\n * PostgreSQL reports a missing schema and a missing table with the same\n * SQLSTATE. Default: nothing to prove — SQLite has no namespace, and this\n * is not a SQLite namespace feature. PostgreSQL (`pg_namespace`) and MySQL\n * (`information_schema.SCHEMATA`) install their proofs in their own units.\n */\n proveNamespaceExists(\n _executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Clears every row in a preserved control table during live reset.\n *\n * @param tableName - The control table name\n * @returns SQL DELETE statement\n */\n generateClearMigrations(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `DELETE FROM ${table}`;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * Generates SQL for acquiring a migration lock, with a stable `acquired`\n * alias so the caller reads one known column rather than a provider-shaped\n * name derived from the expression text.\n *\n * Returns null when this dialect takes no session lock (SQLite/LibSQL, which\n * keep their own single-connection queue).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateAcquireLock(lockId: number): string | null;\n\n /**\n * Generates SQL for releasing a migration lock, with a stable `released`\n * alias. Returns null on the dialects that take no lock.\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateReleaseLock(lockId: number): string | null;\n\n /**\n * Whether the provider's answer to {@link generateAcquireLock} PROVES the\n * lock is held.\n *\n * Asked only when a lock statement was emitted, so the dialects that emit\n * none never reach it. The default is `false` because a lock nobody proved is\n * a lock nobody holds: MySQL's `GET_LOCK` returns `0` on timeout and `NULL`\n * on error, and the previous owner discarded that answer entirely and ran the\n * \"protected\" work anyway.\n */\n provesLockAcquired(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Whether the provider's answer to {@link generateReleaseLock} PROVES the\n * lock was released. A false answer condemns the session: it is holding a\n * lock nobody will release, and returning it to a pool would strand it.\n */\n provesLockReleased(_rows: readonly unknown[]): boolean {\n return false;\n }\n\n /**\n * Selects the live migration target on a pinned session, or null when this\n * dialect has nothing to select.\n *\n * MySQL is the only arm: its generated artifacts are database-relative, so\n * the target has to be selected on the connection that executes them. Every\n * other dialect qualifies its statements and must never touch session state\n * (§13).\n */\n generateSelectTarget(): string | null {\n return null;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * The live-namespace table inventory: the exact set of tables a reset may\n * drop, as a BOUND read.\n *\n * `{ sql, params }` rather than a bare string because §4.2/§5.2 require the\n * namespace to reach a catalog predicate through the parameter channel: a\n * bare-string seam has nothing to bind through, so it can only splice the\n * name into the statement as an escaped literal.\n *\n * @returns Bound SELECT returning rows with a `name` column\n */\n abstract generateInventoryTables(): { sql: string; params: unknown[] };\n\n /**\n * The live-namespace enum inventory, or null for dialects with no standalone\n * enum types.\n */\n abstract generateInventoryEnums(): {\n sql: string;\n params: unknown[];\n } | null;\n\n /**\n * Generates SQL for dropping a table.\n *\n * There is no `CASCADE` arm. §6.1: a namespace is a containment boundary, and\n * `DROP TABLE ... CASCADE` drops dependants in OTHER namespaces even when the\n * enumeration that produced this name only ever selected one. The dependency\n * graph is materialized as explicit foreign-key drops before the table drops\n * instead, and an unknown external dependency then aborts the operation\n * through PostgreSQL's default `RESTRICT` rather than deleting collaterally.\n *\n * @param tableName - The table name\n * @returns SQL DROP TABLE statement\n */\n generateDropTableSQL(tableName: string): string {\n return `DROP TABLE IF EXISTS ${this.escapeIdentifier(tableName)}`;\n }\n\n /**\n * Generates SQL for dropping an enum type.\n * Returns null for databases that don't support enums.\n *\n * @param enumName - The enum name\n * @returns SQL DROP TYPE statement or null\n */\n generateDropEnumSQL(_enumName: string): string | null {\n return null; // Override in PostgreSQL driver\n }\n\n // ===========================================================================\n // DISPATCH (final - not meant to be overridden)\n // ===========================================================================\n\n /**\n * The one owner of provider statement boundaries for generated DDL.\n */\n compileStatements(\n operation: DiffOperation,\n context: DDLContext\n ): readonly string[] {\n switch (operation.type) {\n case \"createTable\":\n return this.compileCreateTable(operation, context);\n case \"dropTable\":\n return this.compileDropTable(operation, context);\n case \"renameTable\":\n return this.compileRenameTable(operation, context);\n case \"addColumn\":\n return this.compileAddColumn(operation, context);\n case \"dropColumn\":\n return this.compileDropColumn(operation, context);\n case \"renameColumn\":\n return this.compileRenameColumn(operation, context);\n case \"alterColumn\":\n // Asked HERE rather than in each driver's `compileAlterColumn`: the\n // question is one — \"can this dialect re-read the stored bytes as the\n // new type?\" — and three copies of it would drift the way the three\n // conversion routes already did (PostgreSQL cast, SQLite rebuild,\n // MySQL MODIFY, each silently wrong in its own way).\n refuseBinaryReencoding(\n operation.tableName,\n operation.columnName,\n operation.from.type,\n operation.to.type,\n this.dialect\n );\n return this.compileAlterColumn(operation, context);\n case \"createIndex\":\n return this.compileCreateIndex(operation, context);\n case \"dropIndex\":\n return this.compileDropIndex(operation, context);\n case \"addForeignKey\":\n return this.compileAddForeignKey(operation, context);\n case \"dropForeignKey\":\n return this.compileDropForeignKey(operation, context);\n case \"addUniqueConstraint\":\n return this.compileAddUniqueConstraint(operation, context);\n case \"dropUniqueConstraint\":\n return this.compileDropUniqueConstraint(operation, context);\n case \"addPrimaryKey\":\n return this.compileAddPrimaryKey(operation, context);\n case \"dropPrimaryKey\":\n return this.compileDropPrimaryKey(operation, context);\n case \"createEnum\":\n return this.compileCreateEnum(operation, context);\n case \"dropEnum\":\n return this.compileDropEnum(operation, context);\n case \"alterEnum\":\n return this.compileAlterEnum(operation, context);\n default:\n throw new MigrationError(\n `Unknown operation type: ${(operation as any).type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n }\n\n /**\n * Generates display DDL for a diff operation.\n */\n generateDDL(operation: DiffOperation, context: DDLContext): string {\n return this.compileStatements(operation, context).join(\";\\n\");\n }\n}\n","import { isSqliteStateControlDefinition } from \"../../control\";\n/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport { BATCH_REFS_TABLE } from \"@adapters/shared/batch-refs\";\nimport {\n sqliteDefinitionKeywords,\n sqliteTableDefinitions,\n} from \"../../../adapters/databases/sqlite/storage/column-constraints\";\nimport { readSqliteDecimalConstraint } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n readSqliteGeoPointColumn,\n SQLITE_GEO_POINT_TYPE,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { skipSqlNonStructuralRegion } from \"../../../adapters/databases/sqlite/storage/sql-lexing\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteInt,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * A pragma's integer column, as a number.\n *\n * SQLite reports integers, but the driver decides how they arrive: the LibSQL\n * driver runs with `intMode: \"bigint\"` (`src/drivers/libsql/index.ts`), so every\n * pragma integer reaches this file as BigInt. Read raw, each one is wrong in a\n * different way — `1n === 1` is false, so a unique index reads as non-unique\n * and a NOT NULL column reads as nullable; and `a.seqno - b.seqno` yields a\n * BigInt that `Array#sort` refuses outright, which crashes the introspection of\n * any index over two or more columns. Normalizing here, once, is what lets the\n * rest of this file compare plain numbers.\n */\nfunction int(value: SqliteInt): number {\n return Number(value);\n}\n\n/** The predicate half of a stored `CREATE INDEX … WHERE …`, if there is one. */\nconst TRAILING_WHERE = /^WHERE\\s+([\\s\\S]+)$/i;\nconst AUTOINCREMENT = /\\bAUTOINCREMENT\\b/i;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The CHECK the SQLite driver embeds in an enum column type.\n *\n * `PRAGMA table_info` reports only `TEXT`. The values live in\n * `sqlite_master.sql` as `CHECK(\"col\" IN ('a', 'b'))`, which is the same\n * spelling `getEnumColumnType` writes into the desired snapshot. Reconstruct\n * that suffix so fingerprint and differ see one type.\n */\nfunction sqliteEnumCheckSuffix(\n tableSql: string | null,\n columnName: string\n): string | undefined {\n if (!tableSql) return;\n const quoted = escapeIdentifier(columnName);\n const match = tableSql.match(\n new RegExp(\n `CHECK\\\\(\\\\s*${escapeRegExp(quoted)}\\\\s+IN\\\\s*\\\\((\\\\s*(?:'(?:[^']|'')*'\\\\s*,\\\\s*)*'(?:[^']|'')*'\\\\s*)\\\\)\\\\s*\\\\)`,\n \"i\"\n )\n );\n const list = match?.[1];\n if (!list) return;\n const values: string[] = [];\n const literals = /'((?:[^']|'')*)'/g;\n let literal = literals.exec(list);\n while (literal) {\n const value = literal[1];\n if (value !== undefined) values.push(value.replace(/''/g, \"'\"));\n literal = literals.exec(list);\n }\n if (values.length === 0) return;\n const escaped = values\n .map((value) => `'${value.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return ` CHECK(${quoted} IN (${escaped}))`;\n}\n\n/**\n * Reads the predicate of a partial index back out of the text SQLite stored.\n *\n * SQLite keeps `sqlite_master.sql` as the statement was written and re-spells\n * nothing (measured on 3.51: the predicate, its inner spacing and its padding\n * all come back byte-identical; only the statement terminator is dropped), so\n * the predicate the differ compares is the one the serializer emitted. This\n * reads it out and does not normalize it — `indexesEqual` is the one place the\n * two snapshot producers' spellings are reconciled.\n *\n * The predicate is whatever follows the column list, not whatever follows the\n * first `WHERE` in the text: a column may be named `a WHERE b`. So walk the\n * statement to the parenthesis that closes the column list, skipping quoted\n * identifiers and string literals, and read the tail from there.\n */\nfunction partialIndexPredicate(sql: string | null): string | undefined {\n if (!sql) return undefined;\n\n let depth = 0;\n let cursor = 0;\n let columnListEnd = -1;\n\n while (cursor < sql.length) {\n // Quoted tokens and comments are skipped through the ONE owner of where a\n // non-structural SQLite region ends, shared with the reserved decimal-\n // constraint reader: both read text SQLite stored verbatim, and both are\n // wrong the same way if its contents are read as syntax.\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n\n const char = sql[cursor];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) {\n columnListEnd = cursor;\n break;\n }\n }\n cursor++;\n }\n\n if (columnListEnd === -1) return undefined;\n\n const match = TRAILING_WHERE.exec(sql.slice(columnListEnd + 1).trimStart());\n return match?.[1];\n}\n\nfunction mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>,\n managedTables?: readonly string[],\n excludeD1SystemTables = false\n): Promise<SchemaSnapshot> {\n // Get all tables. `sql` rides along on the query that was already being made\n // — the reserved decimal constraints are read out of it, and a second live\n // read for them would be a raw-execution call site the architecture census\n // pins per file. The engine's batch reference scratch is not part of the\n // user's schema: it is TEMP where the transport admits temporary objects and\n // never appears here, but on D1 it is an ordinary table in `main`, and a\n // snapshot that carried it would have push and diff plan its drop.\n // D1 also exposes provider-owned `_cf_` tables but forbids their PRAGMAs.\n // Filter that exact reserved prefix only for D1; GLOB treats `_` literally,\n // and an ordinary SQLite application's similarly named tables stay visible.\n const tablesResult = await executeRaw<SqliteTable>(\n `\n SELECT name, sql\n FROM sqlite_master\n WHERE type = 'table'\n AND name NOT LIKE 'sqlite_%'\n AND name <> ?\n ${excludeD1SystemTables ? \"AND name NOT GLOB '_cf_*'\" : \"\"}\n ORDER BY name\n `,\n [BATCH_REFS_TABLE]\n );\n\n const tables: TableDef[] = [];\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.name;\n\n const selected =\n managedTables === undefined || managedTables.includes(tableName);\n const definitions = sqliteTableDefinitions(tableRow.sql ?? \"\");\n if (\n selected &&\n definitions.some((definition) =>\n sqliteDefinitionKeywords(definition.text).includes(\"AS\")\n )\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has generated columns that this schema cannot represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"generated columns\" } }\n );\n if (\n selected &&\n sqliteDefinitionKeywords(\n (tableRow.sql ?? \"\").split(\"(\")[0] ?? \"\"\n ).includes(\"VIRTUAL\")\n )\n throw new MigrationError(\n `SQLite virtual table \"${tableName}\" cannot be faithfully reconstructed. Synchronization refuses before effects.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"virtual table\" } }\n );\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n const tableSql = tableRow.sql;\n const hasAutoincrement = AUTOINCREMENT.test(tableSql ?? \"\");\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n\n // The pragma reports that an index is partial but not what its predicate\n // is; only the stored statement carries that.\n const indexSqlResult = await executeRaw<{\n name: string;\n sql: string | null;\n }>(\n \"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?\",\n [tableName]\n );\n const indexSql = new Map(\n indexSqlResult.rows.map((row) => [row.name, row.sql])\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n const pk = int(col.pk);\n const type = col.type || \"TEXT\";\n const nullable = int(col.notnull) === 0 && pk === 0;\n const geoPointEncoding = readSqliteGeoPointColumn(\n tableSql,\n { name: col.name, type, nullable },\n escapeIdentifier\n );\n columns.push({\n name: col.name,\n geoPointEncoding,\n type: geoPointEncoding\n ? SQLITE_GEO_POINT_TYPE\n : `${type}${sqliteEnumCheckSuffix(tableSql, col.name) ?? \"\"}`,\n nullable,\n default: col.dflt_value ?? undefined,\n autoIncrement: pk === 1 && hasAutoincrement,\n // The declared domain, recovered from the reserved CHECK constraint\n // the driver wrote. Nothing else on this dialect carries it: the type\n // is `INTEGER` (or `TEXT`) at every precision and scale, and the\n // pragma reports no constraints at all — so a side that could not\n // recover it would read as a change on every push, forever.\n decimal: readSqliteDecimalConstraint(\n tableSql,\n // The descriptor proof consumes the exact declared type PRAGMA\n // reported. The generic snapshot fallback above may call an untyped\n // column TEXT, but that normalization cannot turn BLOB affinity into\n // the writer-owned TEXT decimal-list carrier.\n { name: col.name, type: col.type, nullable },\n escapeIdentifier\n ),\n });\n\n if (pk > 0) {\n pkColumns.push({ name: col.name, position: pk });\n }\n }\n\n if (selected) {\n const checks = definitions.reduce(\n (count, definition) =>\n count +\n sqliteDefinitionKeywords(definition.text).filter(\n (word) => word === \"CHECK\"\n ).length,\n 0\n );\n const represented = columns.reduce(\n (count, column) =>\n count +\n Number(column.decimal !== undefined) +\n Number(column.geoPointEncoding !== undefined) +\n Number(sqliteEnumCheckSuffix(tableSql, column.name) !== undefined),\n 0\n );\n if (\n checks !== represented &&\n !isSqliteStateControlDefinition(tableName, tableSql)\n )\n throw new MigrationError(\n `SQLite table \"${tableName}\" has CHECK constraints that this schema cannot faithfully represent. Synchronization refuses before effects and preserves them.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"CHECK constraints\" } }\n );\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // xinfo exposes the physical key semantics that index_info erases.\n // Auxiliary rowid columns are not key members; user expressions, DESC\n // and collations cannot be faithfully recreated by this declaration DSL.\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_xinfo(${escapeIdentifier(idx.name)})`\n );\n const keys = indexColsResult.rows.filter(\n (column) => int(column.key) === 1\n );\n const unsupported =\n keys.length === 0 ||\n keys.some(\n (column) =>\n int(column.cid) < 0 ||\n column.name === null ||\n int(column.desc) !== 0 ||\n column.coll !== \"BINARY\"\n );\n if (unsupported) {\n if (managedTables === undefined || managedTables.includes(tableName)) {\n throw new MigrationError(\n `SQLite index \"${tableName}.${idx.name}\" has expression/order/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves it. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName: idx.name } }\n );\n }\n continue;\n }\n // PK membership is already represented by the table's primary key.\n if (idx.origin === \"pk\") continue;\n const indexColumns = keys\n .sort((a, b) => int(a.seqno) - int(b.seqno))\n .flatMap((column) => (column.name === null ? [] : [column.name]));\n\n const unique = int(idx.unique) === 1;\n if (unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique,\n where: partialIndexPredicate(indexSql.get(idx.name) ?? null),\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const id = int(fk.id);\n const existing = fkMap.get(id) || [];\n existing.push(fk);\n fkMap.set(id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => int(a.seq) - int(b.seq));\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [] };\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport { isDestructiveOperation } from \"../../differ\";\n/**\n * SQLite Migration Driver\n *\n * Implements the MigrationDriver interface for SQLite databases.\n * Uses table recreation for operations SQLite doesn't support natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { sqliteDateTimePhysicalForm } from \"@schema/scalars/datetime/physical\";\nimport { encodePhysicalDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { validateIsoTime } from \"@validation/primitives/iso\";\nimport {\n sqliteDateTimeCopyExpression,\n sqliteDateTimeTargetRequiresRecreation,\n} from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport {\n sqliteDecimalCheck,\n sqliteDecimalCopyExpression,\n} from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCarrier,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport {\n decimalConversionRequired,\n describeDecimalDomain,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport { foreignKeyPragmasCannotBeLifted } from \"../../foreign-keys\";\nimport { applyNativeRename } from \"../../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\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 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 { getSQLiteType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\nconst COMPUTED_DEFAULT_PREFIX = /^(?:CURRENT_(?:TIME|DATE|TIMESTAMP)|\\()/i;\n\n/**\n * One preceding operation of the batch, applied to the table definition a later\n * recreation will rebuild. `SQLite3MigrationDriver.getCurrentTable` explains\n * why the introspected definition alone is not enough, and what each list costs\n * when it is left behind.\n */\nfunction applyToTable(table: TableDef, op: DiffOperation): TableDef {\n if (!(\"tableName\" in op) || op.tableName !== table.name) {\n return table;\n }\n switch (op.type) {\n case \"addColumn\":\n return { ...table, columns: [...table.columns, op.column] };\n case \"dropColumn\":\n return {\n ...table,\n columns: table.columns.filter(\n (column) => column.name !== op.columnName\n ),\n };\n case \"alterColumn\":\n return {\n ...table,\n columns: table.columns.map((column) =>\n column.name === op.columnName ? op.to : column\n ),\n };\n case \"createIndex\":\n return { ...table, indexes: [...table.indexes, op.index] };\n case \"dropIndex\":\n return {\n ...table,\n indexes: table.indexes.filter((index) => index.name !== op.indexName),\n };\n case \"addForeignKey\":\n return { ...table, foreignKeys: [...table.foreignKeys, op.fk] };\n case \"dropForeignKey\":\n return {\n ...table,\n foreignKeys: table.foreignKeys.filter((fk) => fk.name !== op.fkName),\n };\n case \"addUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: [...table.uniqueConstraints, op.constraint],\n };\n case \"dropUniqueConstraint\":\n return {\n ...table,\n uniqueConstraints: table.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n };\n case \"addPrimaryKey\":\n return { ...table, primaryKey: op.primaryKey };\n case \"dropPrimaryKey\":\n return { ...table, primaryKey: undefined };\n default:\n // `dropTable` is the only remaining operation that names this table, and\n // nothing rebuilds a table the same batch dropped.\n return table;\n }\n}\n\n/**\n * The schema-level table set after every preceding operation in the batch.\n *\n * Per-table replay cannot see a table created earlier in the same batch, and\n * retaining a dropped table invents relations the database no longer has.\n * This owner first evolves membership, then applies each operation's local and\n * inbound effects to every table that exists at that point.\n */\nfunction replaySchemaTables(\n tables: readonly TableDef[],\n operations: readonly DiffOperation[]\n): TableDef[] {\n let replayed = [...tables];\n for (const operation of operations) {\n if (operation.type === \"createTable\") {\n replayed = [...replayed, operation.table];\n continue;\n }\n if (operation.type === \"dropTable\") {\n replayed = replayed.filter((table) => table.name !== operation.tableName);\n continue;\n }\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n replayed = applyNativeRename({ tables: replayed }, operation).tables;\n continue;\n }\n replayed = replayed.map((table) => applyToTable(table, operation));\n }\n return replayed;\n}\n\n/** Whether a table carries an outbound FK or is the target of an inbound FK. */\nexport function sqliteTableBearsRelations(\n tableName: string,\n tables: readonly TableDef[],\n rebuiltTable?: TableDef,\n precedingOperations: readonly DiffOperation[] = []\n): boolean {\n if (rebuiltTable && rebuiltTable.foreignKeys.length > 0) return true;\n const replayed = replaySchemaTables(tables, precedingOperations);\n for (const table of replayed) {\n if (table.name === tableName && table.foreignKeys.length > 0) return true;\n if (\n table.foreignKeys.some(\n (foreignKey) => foreignKey.referencedTable === tableName\n )\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * SQLite3 Migration Driver\n *\n * Handles migrations for better-sqlite3 and similar synchronous SQLite drivers.\n * Uses table recreation for operations SQLite doesn't support natively:\n * - ALTER COLUMN (type, default, NOT NULL changes)\n * - ADD/DROP FOREIGN KEY\n * - ADD/DROP PRIMARY KEY\n *\n * LibSQL extends this class and overrides methods for operations it supports.\n */\nexport class SQLite3MigrationDriver extends MigrationDriver {\n readonly dialect = \"sqlite\" as const;\n readonly driverName: string = \"sqlite3\";\n\n override finalizeTable(table: TableDef): TableDef {\n const increments = table.columns.filter((column) => column.autoIncrement);\n if (\n increments.length > 0 &&\n (increments.length !== 1 ||\n table.primaryKey?.columns.length !== 1 ||\n table.primaryKey.columns[0] !== increments[0]!.name ||\n increments[0]!.type.toUpperCase() !== \"INTEGER\" ||\n increments[0]!.nullable)\n ) {\n throw new MigrationError(\n `SQLite table \"${table.name}\" requires its AUTOINCREMENT column to be the sole non-null INTEGER primary key. Declare .id().autoIncrement() on that column.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: table.name } }\n );\n }\n return table;\n }\n\n override getIrreversibleRollbackReason(\n operation: DiffOperation\n ): string | undefined {\n if (\n operation.type === \"alterColumn\" &&\n sqliteGeoPointEncoding(operation.from) === \"binary64\" &&\n sqliteGeoPointEncoding(operation.to) === \"legacy\"\n ) {\n return `Rollback cannot downgrade GeoPoint column \"${operation.tableName}.${operation.columnName}\" to its legacy CHECK without rounding coordinates. Author an explicit manual data transition.`;\n }\n return super.getIrreversibleRollbackReason(operation);\n }\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true, // N/A but doesn't matter\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // No `ALTER TABLE ADD FOREIGN KEY`: FKs stay inline in CREATE TABLE and\n // rely on SQLite's lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // `PRAGMA foreign_key_list` has no name column, and an inline\n // `CONSTRAINT x UNIQUE (...)` is only ever reported as\n // `sqlite_autoindex_<table>_<n>`. Neither name survives a round trip.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<void> {\n const names = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (names.length === 0) return;\n const views = await executeRaw<{ name: string }>(\n \"SELECT name FROM sqlite_master WHERE type = 'view'\"\n );\n const collision = views.rows.find((row) => names.includes(row.name));\n if (collision)\n throw new MigrationError(\n `SQLite relation \"${collision.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.name, feature: \"view\" } }\n );\n }\n\n introspect(\n executeRaw: Parameters<typeof introspect>[0]\n ): Promise<SchemaSnapshot> {\n const provider = this.executionDriver?.driverName;\n return introspect(executeRaw, this.target?.tables, provider === \"d1\");\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, \"sqlite\");\n if (idStorage) return idStorage.columnType;\n\n // SQLite has no native list type. A native declaration can describe one\n // scalar member only; every list keeps its container below.\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType && !scalarState.array) {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getSQLiteType({\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 if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n if (form === \"julianDay\") return \"(julianday('now'))\";\n if (form === \"epochMillis\")\n return \"(CAST(strftime('%s','now') AS INTEGER) * 1000 + CAST(substr(strftime('%f','now'),4,3) AS INTEGER))\";\n return \"(strftime('%Y-%m-%dT%H:%M:%fZ','now'))\";\n }\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\") return \"(strftime('%Y-%m-%d','now'))\";\n if (scalarState.type === \"time\") return \"(strftime('%H:%M:%f','now'))\";\n }\n const defaultValue =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.array &&\n (scalarState.type === \"datetime\" || scalarState.type === \"time\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.array !== true &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const form = sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType);\n const physical = encodePhysicalDateTime(defaultValue, form);\n return typeof physical === \"string\"\n ? this.escapeValue(physical)\n : String(physical);\n }\n if (\n scalarState.type === \"time\" &&\n !scalarState.array &&\n !scalarState.autoGenerate &&\n scalarState.hasDefault &&\n typeof defaultValue === \"string\"\n ) {\n const canonical = validateIsoTime(defaultValue);\n if (!(\"value\" in canonical))\n throw new MigrationError(\n \"Invalid Time literal default\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.escapeValue(canonical.value);\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n // Override formatBooleanDefault for SQLite's 1/0 representation\n\n /**\n * SQLite uses 1/0 for boolean values instead of true/false.\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n getEnumColumnType(\n _tableName: string,\n columnName: string,\n values: string[]\n ): string {\n // SQLite uses TEXT with CHECK constraint for enum validation\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `TEXT CHECK(${this.escapeIdentifier(columnName)} IN (${escapedValues}))`;\n }\n\n // ===========================================================================\n // HELPER: Column Definition\n // ===========================================================================\n\n protected generateColumnDef(column: ColumnDef, _context: DDLContext): string {\n // SQLite auto-increment only works with INTEGER PRIMARY KEY\n // Validate that autoIncrement columns use INTEGER type\n if (column.autoIncrement && column.type.toUpperCase() !== \"INTEGER\") {\n throw new MigrationError(\n \"SQLite auto-increment requires INTEGER type. \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment. ` +\n \"Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n\n if (column.autoIncrement) {\n return `${this.escapeIdentifier(column.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;\n }\n\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK is a DERIVED render of the column's own\n // descriptor, emitted as a column CONSTRAINT beside the type — never\n // folded INTO `column.type`. `getEnumColumnType` above does fold its CHECK\n // into the type, and the measured cost is a full table recreation on every\n // push forever: `PRAGMA table_info.type` reports only the `type-name`\n // production, so the desired `TEXT CHECK(...)` never equals the\n // introspected `TEXT`. A named constraint reads back out of\n // `sqlite_master.sql` instead, which is where introspection recovers the\n // descriptor from.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // TABLE RECREATION\n // ===========================================================================\n\n /**\n * Generates SQL for table recreation.\n * This is the Drizzle-style pattern for operations SQLite doesn't support.\n *\n * Steps:\n * 1. PRAGMA foreign_keys=OFF\n * 2. Create new table with desired schema\n * 3. Copy data from old table (using explicit column mapping by name)\n * 4. Drop old table\n * 5. Rename new table\n * 6. Recreate indexes\n * 7. PRAGMA foreign_keys=ON\n *\n * @param tableName - The table to recreate\n * @param newTable - The new table definition\n * @param currentTable - The current table definition (required for safe column mapping)\n * @param columnRenames - Optional map of old column name to new column name\n */\n protected compileTableRecreation(\n tableName: string,\n newTable: TableDef,\n currentTable: TableDef,\n context: DDLContext,\n columnRenames?: Map<string, string>,\n valueExpressions?: ReadonlyMap<string, string>\n ): string[] {\n const statements: string[] = [];\n const tempName = `__new_${tableName}`;\n const currentColumns = new Map(\n currentTable.columns.map((column) => [column.name, column])\n );\n const sourceNames = new Map<string, string>();\n for (const [oldName, newName] of columnRenames ?? []) {\n sourceNames.set(newName, oldName);\n }\n const usesCorrelatedListCopy = newTable.columns.some((column) => {\n const sourceName = sourceNames.get(column.name) ?? column.name;\n return (\n this.decimalConversionKind(currentColumns.get(sourceName), column) ===\n \"list\"\n );\n });\n // A list conversion opens correlated `json_each` tables whose ten virtual\n // column names are ordinary legal user column names. Every outer read is\n // qualified through this one statement-local alias so `\"value\"`, `\"key\"`,\n // and their siblings cannot be captured by the inner table. Ordinary and\n // scalar-only recreations retain their original unaliased SQL.\n const sourceAlias = \"__viborm_source\";\n\n // 1. Disable foreign keys\n statements.push(\"PRAGMA foreign_keys=OFF\");\n\n // 2. Create new table\n statements.push(\n this.generateCreateTableDef({ ...newTable, name: tempName }, context)\n );\n\n // 3. Copy data - EXPLICIT column mapping by NAME, not position\n // Build a set of current column names for quick lookup\n // For each column in the new table, find the corresponding source column.\n // `source` is an EXPRESSION, not an identifier: a decimal column whose\n // declared domain moved is converted here, inside the database, on the way\n // across.\n const copyColumns: Array<{ source: string; target: string }> = [];\n\n for (const col of newTable.columns) {\n const sourceName = sourceNames.get(col.name) ?? col.name;\n\n // Only copy if source column exists in current table\n const currentColumn = currentColumns.get(sourceName);\n if (currentColumn !== undefined) {\n const source = usesCorrelatedListCopy\n ? `${this.escapeIdentifier(sourceAlias)}.${this.escapeIdentifier(sourceName)}`\n : this.escapeIdentifier(sourceName);\n copyColumns.push({\n source:\n valueExpressions?.get(col.name) ??\n this.copySourceExpression(\n tableName,\n sourceName,\n currentColumn,\n col,\n source\n ),\n target: col.name,\n });\n } else if (!col.nullable && col.default === undefined) {\n // New NOT NULL column without default - INSERT will fail\n throw new MigrationError(\n `Cannot add NOT NULL column \"${col.name}\" without a default value during table recreation. ` +\n \"SQLite requires a default value or nullable column for table recreation.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n // New columns with defaults or nullable will get their default/NULL values\n }\n\n if (copyColumns.length > 0) {\n const selectCols = copyColumns.map((c) => c.source).join(\", \");\n const insertCols = copyColumns\n .map((c) => this.escapeIdentifier(c.target))\n .join(\", \");\n\n statements.push(\n `INSERT INTO ${this.escapeIdentifier(tempName)} (${insertCols}) ` +\n `SELECT ${selectCols} FROM ${this.escapeIdentifier(tableName)}` +\n (usesCorrelatedListCopy\n ? ` AS ${this.escapeIdentifier(sourceAlias)}`\n : \"\")\n );\n }\n\n // 4. Drop old table\n statements.push(`DROP TABLE ${this.escapeIdentifier(tableName)}`);\n\n // 5. Rename new table\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tempName)} RENAME TO ${this.escapeIdentifier(tableName)}`\n );\n\n // 6. Recreate indexes (they were dropped with the old table)\n for (const idx of newTable.indexes) {\n statements.push(\n this.generateCreateIndex(\n { type: \"createIndex\", tableName, index: idx },\n context\n )\n );\n }\n\n // 7. Re-enable foreign keys\n statements.push(\"PRAGMA foreign_keys=ON\");\n\n return this.filterStatements(statements);\n }\n\n /**\n * What the recreation SELECTs for one column of the rebuilt table.\n *\n * Ordinarily the column itself. When the column's declared decimal domain\n * moved, it is the conversion expression instead: SQLite stores the unscaled\n * coefficient, so a scale change makes every stored integer mean a different\n * number until it is rescaled, and the whole conversion runs inside the\n * database because the rebuild is one `INSERT ... SELECT` this process never\n * reads a row of.\n *\n * A change that moves the STORAGE SHAPE — a scalar becoming a list, or the\n * other way — gets no conversion and no second guard: the value is copied as\n * it stands and the target column's own reserved CHECK refuses it, which\n * aborts the rebuild inside its transaction and leaves the old table exactly\n * as it was.\n *\n * A source column that declares NO domain is the third case, and it is a\n * conversion too. An `INTEGER` holding logical integers, adopted as\n * `decimal(p,s)`, has to become a coefficient: copied as it stands, `123`\n * would silently start reading as 1.23. Only that one adoption is converted.\n * A TEXT source or a list target has no proven logical scale, and SQLite can\n * coerce numeric text after the copy, so every other unmarked source refuses\n * here before the recreation exists.\n */\n private copySourceExpression(\n tableName: string,\n sourceName: string,\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef,\n source: string\n ): string {\n if (\n targetColumn.geoPointEncoding === \"binary64\" &&\n currentColumn !== undefined &&\n sqliteGeoPointEncoding(currentColumn) === \"legacy\"\n ) {\n return `CASE WHEN ${source} IS NULL THEN NULL ELSE ${sqliteGeoPointCarrier(source)} END`;\n }\n const dateTime = targetColumn.dateTime;\n if (dateTime !== undefined) {\n const sourceForm = this.sqliteDateTimeSourceForm(currentColumn);\n if (sourceForm === undefined) {\n const sourceDomain =\n currentColumn?.decimal === undefined\n ? `${currentColumn?.type ?? \"unknown\"} storage`\n : `a fixed-decimal domain at ${describeDecimalDomain(currentColumn.decimal)}`;\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt ${sourceDomain} as a SQLite DateTime. ` +\n \"Only a declared DateTime or unmarked TEXT, INTEGER epoch-millisecond, or REAL Julian-day candidate can be converted exactly. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"SQLite DateTime storage conversion\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDateTimeCopyExpression(\n source,\n sourceForm,\n dateTime,\n currentColumn?.dateTime !== undefined\n );\n }\n\n const to = targetColumn.decimal;\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n if (to === undefined || targetKind === undefined) return source;\n\n const from = currentColumn?.decimal;\n if (from === undefined) {\n const adopting =\n targetKind === \"scalar\" &&\n currentColumn?.type.toUpperCase() === \"INTEGER\";\n if (!adopting) {\n throw new MigrationError(\n `The declared change to \"${tableName}\".\"${sourceName}\" would adopt unmarked ${currentColumn?.type ?? \"unknown\"} storage as a fixed-decimal ${targetKind}. ` +\n \"Only a scalar INTEGER has one exact descriptor-free meaning that can be rescaled into the target domain. TEXT and every list container carry no proven member scale, while other SQLite affinities can already have changed the stored value. \" +\n \"The change is refused before any statement runs, so the schema and data stay unchanged. Use an explicit migration that validates and rewrites the source values.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: tableName,\n column: sourceName,\n feature: \"decimal storage adoption\",\n dialect: \"sqlite\",\n },\n }\n );\n }\n return sqliteDecimalCopyExpression(source, undefined, to, \"scalar\");\n }\n if (sameDecimalDescriptor(from, to)) return source;\n const conversionKind = this.decimalConversionKind(\n currentColumn,\n targetColumn\n );\n if (conversionKind === undefined) return source;\n return sqliteDecimalCopyExpression(source, from, to, conversionKind);\n }\n\n /** Physical source vocabulary for a target known to be a DateTime. */\n private sqliteDateTimeSourceForm(\n column: ColumnDef | undefined\n ): \"text\" | \"epochMillis\" | \"julianDay\" | undefined {\n if (column?.dateTime !== undefined) return column.dateTime;\n if (column?.decimal !== undefined) return undefined;\n switch (column?.type.toUpperCase()) {\n case \"TEXT\":\n return \"text\";\n case \"INTEGER\":\n return \"epochMillis\";\n case \"REAL\":\n return \"julianDay\";\n default:\n return undefined;\n }\n }\n\n /** The shared-storage decimal conversion one copied column requires. */\n private decimalConversionKind(\n currentColumn: ColumnDef | undefined,\n targetColumn: ColumnDef\n ): \"scalar\" | \"list\" | undefined {\n const from = currentColumn?.decimal;\n const to = targetColumn.decimal;\n if (\n currentColumn === undefined ||\n from === undefined ||\n to === undefined ||\n sameDecimalDescriptor(from, to)\n ) {\n return undefined;\n }\n const targetKind = sqliteDecimalStorageKind(targetColumn);\n if (\n targetKind === undefined ||\n sqliteDecimalStorageKind(currentColumn) !== targetKind\n ) {\n return undefined;\n }\n return targetKind;\n }\n\n /**\n * Refuses a domain conversion the substrate cannot rebuild safely, BEFORE\n * any statement runs.\n *\n * Every SQLite descriptor change is a table recreation, and a recreation\n * drops and rebuilds the table with foreign-key enforcement disabled. That\n * disable is only real when `PRAGMA foreign_keys=OFF` runs OUTSIDE the\n * transaction — SQLite documents it as a no-op inside one — and a batch-only\n * driver has no outside to run it in. On such a driver the pragma travels\n * inside the batch and does nothing, so `DROP TABLE` either raises the\n * constraint or silently fires the referential action on every child row.\n *\n * D1 is the shipped case, and plan §7.4 states the prerequisite exactly: a\n * relation-bearing rebuild is admitted only after the foreign-key-safe\n * rebuild is proven across the ten relation shapes. Until then this refuses\n * with the substrate reason rather than shipping an unsafe drop/recreate or\n * a manual shadow-column instruction.\n *\n * Only relation-bearing tables are refused: a table with no reference in\n * either direction has nothing the disabled enforcement could damage, so\n * fresh decimal schemas and ordinary descriptor changes stay available.\n *\n * The question remains conversion-owned: decimal descriptor changes and\n * adoption, decimal carrier renames, and DateTime form/adoption transitions\n * ask this owner. A recreation requested by another column, constraint, key,\n * or enum does not become a domain conversion merely because the same table\n * also contains one of these scalars. General D1 reconstruction safety is an\n * existing migration concern outside this boundary.\n */\n private assertDomainReconstructionAdmitted(\n tableName: string,\n column: ColumnDef,\n table: TableDef,\n context: DDLContext,\n domain: \"decimal\" | \"dateTime\"\n ): void {\n let description: string;\n let feature: string;\n if (domain === \"decimal\") {\n if (column.decimal === undefined) return;\n description = `a fixed-decimal column at ${describeDecimalDomain(column.decimal)}`;\n feature = \"decimal descriptor conversion\";\n } else {\n if (column.dateTime === undefined) return;\n description = `a SQLite DateTime column in ${column.dateTime} storage`;\n feature = \"SQLite DateTime storage conversion\";\n }\n const driver = this.executionDriver;\n if (!(driver && foreignKeyPragmasCannotBeLifted(driver))) return;\n if (\n !sqliteTableBearsRelations(\n tableName,\n context.currentSchema?.tables ?? [],\n table,\n context.precedingOperations\n )\n ) {\n return;\n }\n throw new MigrationError(\n `Rebuilding \"${tableName}\".\"${column.name}\", ${description}, recreates the whole table, and the driver \"${driver.driverName}\" executes migrations as one native batch. ` +\n \"SQLite treats `PRAGMA foreign_keys=OFF` as a no-op inside a transaction, and a batch has no outside to run it in, so the rebuild would drop a table that still has enforced references — raising on one referential action and silently deleting or nulling child rows on another. \" +\n \"The change is refused before any statement runs, so the schema and its data are exactly as they were. Recreate the table without its references, or run the change on a driver that executes statements individually.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n driver: driver.driverName,\n table: tableName,\n column: column.name,\n feature,\n },\n }\n );\n }\n\n /**\n * Helper to generate CREATE TABLE DDL without indexes\n */\n protected generateCreateTableDef(\n table: TableDef,\n context: DDLContext\n ): string {\n const parts: string[] = [];\n\n // Columns\n for (const col of table.columns) {\n parts.push(this.generateColumnDef(col, context));\n }\n\n // Primary key (if composite or not INTEGER autoincrement)\n if (table.primaryKey) {\n const isSingleIntegerPK =\n table.primaryKey.columns.length === 1 &&\n table.columns.find(\n (c) =>\n c.name === table.primaryKey!.columns[0] &&\n c.type.toUpperCase() === \"INTEGER\" &&\n c.autoIncrement\n );\n\n if (!isSingleIntegerPK) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n parts.push(`PRIMARY KEY (${pkCols})`);\n }\n }\n\n // Unique constraints\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n parts.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n parts.push(fkDef);\n }\n\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)`;\n }\n\n /**\n * The table definition a recreation has to rebuild — the introspected one,\n * moved on by every preceding operation of the same batch.\n *\n * `currentSchema` is read once, before the first statement runs, so on its own\n * it describes the table as it was. A recreation drops the table and rebuilds\n * whatever this definition names, so read raw it destroys everything the same\n * batch created earlier and resurrects everything the same batch dropped. Each\n * list is a measured hazard, not a hypothetical:\n *\n * - INDEXES. `createIndex` runs at priority 15 and `addForeignKey` at 16, and\n * SQLite recreates the table for every foreign-key change — so on a database\n * that predates the FK index each foreign-key push created the index and\n * then threw it away, forever.\n *\n * - FOREIGN KEYS. `dropForeignKey` runs at 2 and `addForeignKey` at 16, and\n * the differ plans that pair for every changed key. With the pre-batch list\n * the add rebuilt the table around the constraint the drop had just removed\n * AND its replacement: measured on better-sqlite3, `zz_posts` held 1, then\n * 2, then 3 identical foreign keys after three idempotent pushes.\n *\n * - COLUMNS. `addColumn` runs at 10 and `alterColumn` at 12, and `alterColumn`\n * is a recreation on SQLite. Measured: pushing a model that both widens one\n * column's type and adds another emitted the `ALTER TABLE ... ADD COLUMN`,\n * then rebuilt the table from the pre-batch column list — and the new column\n * was gone. The push reported success, and the next one added and lost it\n * again. Two `alterColumn`s in one batch reverted each other the same way.\n *\n * - UNIQUE CONSTRAINTS. `dropUniqueConstraint` runs at 4 and\n * `addUniqueConstraint` at 14, and both ARE recreations here — the\n * constraint is inline in `CREATE TABLE` (see\n * `generateAddUniqueConstraint`). So the pair a changed constraint plans\n * reads its own predecessor, and a later recreation at 16 has to rebuild\n * around the constraint the add put there rather than the one the drop\n * removed.\n *\n * - PRIMARY KEY. `dropPrimaryKey` runs at 5 and `addPrimaryKey` at 13, both\n * ahead of `addForeignKey`, so a later recreation would rebuild around the\n * key that was just replaced.\n *\n * - INBOUND FOREIGN KEYS. Native SQLite table and column renames rewrite\n * references stored in OTHER tables. If one of those tables is recreated\n * later in the batch, its pre-batch definition would restore the old table\n * or column name unless the same replay carries the rename's remote effect.\n *\n * These are all the operations that move any of those five out of `TableDef`,\n * plus the two native renames whose effects cross table boundaries. Replaying\n * them gives what the database actually holds when the recreation runs.\n */\n protected getCurrentTable(\n tableName: string,\n context: DDLContext\n ): TableDef | undefined {\n return replaySchemaTables(\n context.currentSchema?.tables ?? [],\n context.precedingOperations ?? []\n ).find((table) => table.name === tableName);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(op: CreateTableOperation, context: DDLContext): string {\n return this.compileCreateTable(op, context).join(\";\\n\");\n }\n\n override compileCreateTable(\n op: CreateTableOperation,\n context: DDLContext\n ): readonly string[] {\n const { table } = op;\n const statements: string[] = [this.generateCreateTableDef(table, context)];\n\n // Create indexes separately\n for (const idx of table.indexes) {\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 this.filterStatements(statements);\n }\n\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\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.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n override compileAddColumn(\n op: AddColumnOperation,\n context: DDLContext\n ): readonly string[] {\n if (\n op.column.default !== undefined &&\n COMPUTED_DEFAULT_PREFIX.test(op.column.default)\n ) {\n const current = this.getCurrentTable(op.tableName, context);\n if (!current)\n throw new MigrationError(\n `Cannot add computed default: table \"${op.tableName}\" is absent`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n return this.compileTableRecreation(\n op.tableName,\n { ...current, columns: [...current.columns, op.column] },\n current,\n context\n );\n }\n return super.compileAddColumn(op, context);\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n // SQLite 3.35.0+ supports DROP COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n /**\n * Renames a column — natively first, then through a table recreation when\n * that column is a decimal.\n *\n * The descriptor rides in a CHECK constraint whose NAME contains the column\n * name, and `ALTER TABLE … RENAME COLUMN` rewrites column REFERENCES inside a\n * CHECK body but never a constraint NAME. So the native rename leaves the\n * carrier behind, pointing at a column that no longer exists: introspection\n * reads the renamed column as carrying no domain, the next push plans an\n * alteration between a domain and nothing, and the stored coefficient is\n * copied unchanged under whatever scale the schema now declares — 12345\n * meaning 123.45 silently becomes 1.2345. It is not even destructive by the\n * differ's reading, because no domain narrowed, so no prompt fires.\n *\n * The native statement has a second job a recreation cannot perform: SQLite\n * rewrites inbound foreign keys stored in OTHER tables. Only after that\n * schema-wide propagation does the ordinary recreation replace the stale\n * carrier name on the already-renamed table. The reconstruction therefore\n * copies the new column name from a current definition that already contains\n * the rename; it is not a second rename mechanism.\n */\n generateRenameColumn(op: RenameColumnOperation, context: DDLContext): string {\n return this.compileRenameColumn(op, context).join(\";\\n\");\n }\n\n override compileRenameColumn(\n op: RenameColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n const renamed = currentTable?.columns.find(\n (column) => column.name === op.from\n );\n if (currentTable === undefined || renamed?.decimal === undefined) {\n // SQLite 3.25.0+ supports RENAME COLUMN\n return this.filterStatements([\n `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`,\n ]);\n }\n\n const nativeRename =\n `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ` +\n `RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n const renamedTable = applyNativeRename({ tables: [currentTable] }, op)\n .tables[0];\n if (renamedTable === undefined) {\n throw new MigrationError(\n `Cannot rename column: table \"${op.tableName}\" disappeared from the current schema.`,\n VibORMErrorCode.INTERNAL_ERROR,\n { meta: { table: op.tableName, column: op.from } }\n );\n }\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n renamed,\n renamedTable,\n context,\n \"decimal\"\n );\n return this.filterStatements([\n nativeRename,\n ...this.compileTableRecreation(\n op.tableName,\n renamedTable,\n renamedTable,\n context\n ),\n ]);\n }\n\n generateAlterColumn(op: AlterColumnOperation, context: DDLContext): string {\n return this.compileAlterColumn(op, context).join(\";\\n\");\n }\n\n override compileAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n // A derived SQLite driver may own a native single-statement form.\n if (\n this.generateAlterColumn !==\n SQLite3MigrationDriver.prototype.generateAlterColumn\n ) {\n return super.compileAlterColumn(op, context);\n }\n\n return this.compileAlterColumnByRecreation(op, context);\n }\n\n /** SQLite's value-preserving ALTER COLUMN implementation. */\n protected compileAlterColumnByRecreation(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const group = [op];\n if (\n context.followingOperations &&\n this.generateAlterColumn ===\n SQLite3MigrationDriver.prototype.generateAlterColumn\n ) {\n const compatible = (\n candidate: DiffOperation | undefined\n ): candidate is AlterColumnOperation =>\n candidate?.type === \"alterColumn\" &&\n candidate.tableName === op.tableName &&\n isDestructiveOperation(candidate) === isDestructiveOperation(op);\n const previous: AlterColumnOperation[] = [];\n for (const candidate of [\n ...(context.precedingOperations ?? []),\n ].reverse()) {\n if (!compatible(candidate)) break;\n previous.unshift(candidate);\n }\n const following: AlterColumnOperation[] = [];\n for (const candidate of context.followingOperations) {\n if (!compatible(candidate)) break;\n following.push(candidate);\n }\n const run = [...previous, op, ...following];\n // Repeated changes to the same column are sequential semantics, not one projection.\n if (new Set(run.map((change) => change.columnName)).size === run.length) {\n if (previous.length > 0) return [];\n group.push(...following);\n }\n }\n // SQLite doesn't support ALTER COLUMN - need table recreation\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot alter column: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const targets = new Map(\n group.map((change) => [change.columnName, change.to])\n );\n const newColumns = currentTable.columns.map(\n (column) => targets.get(column.name) ?? column\n );\n\n const newTable: TableDef = {\n ...currentTable,\n columns: newColumns,\n };\n\n for (const change of group) {\n if (decimalConversionRequired(change.from, change.to)) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"decimal\"\n );\n } else if (\n sqliteDateTimeTargetRequiresRecreation(\n change.from.dateTime,\n change.to.dateTime\n )\n ) {\n this.assertDomainReconstructionAdmitted(\n op.tableName,\n change.to,\n newTable,\n context,\n \"dateTime\"\n );\n }\n }\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\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 against capabilities (SQLite only supports btree)\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n // SQLite has supported partial indexes since 3.8.0. Dropping the predicate\n // silently would build a different index from the declared one, and the\n // differ would re-create it on every push forever, because introspection\n // reads the predicate back.\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // SQLite doesn't support USING clause - it only has btree indexes\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})${where}`;\n }\n\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string {\n return this.compileAddForeignKey(op, context).join(\";\\n\");\n }\n\n override compileAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): readonly string[] {\n // LibSQL owns the native single-column form; its multi-column fallback\n // remains a SQLite recreation and therefore keeps these boundaries.\n if (\n op.fk.columns.length <= 1 &&\n this.generateAddForeignKey !==\n SQLite3MigrationDriver.prototype.generateAddForeignKey\n ) {\n return super.compileAddForeignKey(op, context);\n }\n\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n foreignKeys: [...currentTable.foreignKeys, op.fk],\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string {\n return this.compileDropForeignKey(op, context).join(\";\\n\");\n }\n\n override compileDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const currentForeignKey = currentTable.foreignKeys.find(\n (fk) => fk.name === op.fkName\n );\n // Preserve a derived driver's native single-column form and its own\n // missing/invalid-constraint diagnostics.\n if (\n (!currentForeignKey || currentForeignKey.columns.length <= 1) &&\n this.generateDropForeignKey !==\n SQLite3MigrationDriver.prototype.generateDropForeignKey\n ) {\n return super.compileDropForeignKey(op, context);\n }\n\n const newTable: TableDef = {\n ...currentTable,\n foreignKeys: currentTable.foreignKeys.filter(\n (fk) => fk.name !== op.fkName\n ),\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n /**\n * A unique constraint is INLINE in `CREATE TABLE` on SQLite, so both halves\n * of the diff go through a table recreation. There is no other spelling that\n * round-trips.\n *\n * SQLite has two ways to spell \"these columns are unique\" and only one of\n * them survives introspection as a constraint. An inline\n * `CONSTRAINT x UNIQUE (...)` is reported by `PRAGMA index_list` with\n * `origin = \"u\"`, which `introspect` files under `uniqueConstraints` —\n * matched by shape against the declared one (see\n * `introspectionReadsConstraintNames`), so an unchanged schema plans nothing.\n * A standalone `CREATE UNIQUE INDEX` is reported with `origin = \"c\"` and\n * filed under `indexes` instead, where no declared unique constraint will\n * ever match it.\n *\n * Measured on better-sqlite3 at `f78fa83`, with the add as a standalone\n * index: push #2 of a model that gained `.unique([\"slug\", \"tenant\"])`\n * planned `addUniqueConstraint` and created the index; push #3 read that\n * index back under the wrong bucket and planned `addUniqueConstraint` again\n * beside `dropIndex` on the same name — and since `addUniqueConstraint` (14)\n * runs ahead of a superseded index drop (15.5), the push died on\n * `index \"…_slug_tenant_key\" already exists`. Every later push died the same\n * way. Before the shape matching landed the FK churn rebuilt the table on\n * every push and destroyed the index before push #3 could collide with it,\n * so the same schema pushed green forever and the unique was never enforced.\n *\n * The drop had no working spelling at all: every `dropUniqueConstraint` the\n * differ plans here names a constraint read out of `PRAGMA index_list` with\n * `origin = \"u\"`, i.e. `sqlite_autoindex_<table>_<n>`, and SQLite refuses\n * `DROP INDEX` on an index it created itself.\n *\n * A database written by the old add still holds the standalone index. It\n * heals on the next push: the recreation rebuilds the table with the\n * constraint inline, and the stale index — dropped with the old table and\n * re-created by step 6 of the recreation, because it is still in the\n * introspected definition — is removed by the `dropIndex` the same batch\n * plans for it.\n */\n generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): string {\n return this.compileAddUniqueConstraint(op, context).join(\";\\n\");\n }\n\n override compileAddUniqueConstraint(\n op: AddUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add unique constraint: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n uniqueConstraints: [...currentTable.uniqueConstraints, op.constraint],\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): string {\n return this.compileDropUniqueConstraint(op, context).join(\";\\n\");\n }\n\n override compileDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop unique constraint: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n uniqueConstraints: currentTable.uniqueConstraints.filter(\n (constraint) => constraint.name !== op.constraintName\n ),\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): string {\n return this.compileAddPrimaryKey(op, context).join(\";\\n\");\n }\n\n override compileAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add primary key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n primaryKey: op.primaryKey,\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): string {\n return this.compileDropPrimaryKey(op, context).join(\";\\n\");\n }\n\n override compileDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context: DDLContext\n ): readonly string[] {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop primary key: table \"${op.tableName}\" not found in current schema. ` +\n \"Supply the current schema when compiling this operation.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n primaryKey: undefined,\n };\n\n return this.compileTableRecreation(\n op.tableName,\n newTable,\n currentTable,\n context\n );\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context: DDLContext): string {\n // SQLite enums use CHECK constraints embedded in column definitions\n // No separate enum type creation needed\n return \"-- SQLite: enum CHECK constraint is part of column definition\";\n }\n\n generateDropEnum(op: DropEnumOperation, context: DDLContext): string {\n return this.compileDropEnum(op, context).join(\";\\n\");\n }\n\n override compileDropEnum(\n op: DropEnumOperation,\n context: DDLContext\n ): readonly string[] {\n // Dropping an enum means removing CHECK constraints from dependent columns\n // This requires table recreation for each dependent table\n const { enumName, dependentColumns } = op;\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return this.filterStatements([\n `-- SQLite: no dependent columns for enum \"${enumName}\"`,\n ]);\n }\n\n const statements: string[] = [];\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found for enum \"${enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n // Change the column type to plain TEXT (remove CHECK constraint)\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName && col.type.includes(\"CHECK\")) {\n return { ...col, type: \"TEXT\" };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context\n )\n );\n }\n\n return this.filterStatements(statements);\n }\n\n generateAlterEnum(op: AlterEnumOperation, context: DDLContext): string {\n return this.compileAlterEnum(op, context).join(\";\\n\\n\");\n }\n\n override compileAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n // Altering an enum means updating CHECK constraints on dependent columns\n // This requires table recreation for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n const statements: string[] = [];\n\n if (!newValues || newValues.length === 0) {\n return this.filterStatements([\n `-- SQLite: no new values provided for enum \"${enumName}\"`,\n ]);\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return this.filterStatements([\n `-- SQLite: no dependent columns found for enum \"${enumName}\"`,\n ]);\n }\n\n // Apply mappings in the reconstruction SELECT. A replacement belongs to\n // the destination CHECK, including a value introduced in this change.\n\n // Generate new CHECK constraint\n const escapedValues = newValues\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n statements.push(`-- SQLite: table \"${dep.tableName}\" not found`);\n continue;\n }\n\n // Build new CHECK constraint for this column\n const newCheckType = `TEXT CHECK(${this.escapeIdentifier(dep.columnName)} IN (${escapedValues}))`;\n\n // Update the column type with new CHECK\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName) {\n return { ...col, type: newCheckType };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n const source = this.escapeIdentifier(dep.columnName);\n const cases = (op.removeValues ?? []).flatMap((value) => {\n const replacement = this.getEnumValueReplacement(\n op,\n dep.tableName,\n dep.columnName,\n value\n );\n return replacement === undefined\n ? []\n : [\n `WHEN ${this.escapeValue(value)} THEN ${replacement === null ? \"NULL\" : this.escapeValue(replacement)}`,\n ];\n });\n const expressions =\n cases.length === 0\n ? undefined\n : new Map([\n [\n dep.columnName,\n `CASE ${source} ${cases.join(\" \")} ELSE ${source} END`,\n ],\n ]);\n statements.push(\n ...this.compileTableRecreation(\n dep.tableName,\n newTable,\n currentTable,\n context,\n undefined,\n expressions\n )\n );\n }\n\n return this.filterStatements(statements);\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n // Return null to signal that locking is handled differently\n return null;\n }\n\n generateReleaseLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n return null;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n params: [],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n // SQLite doesn't support enums\n return null;\n }\n}\n\n// Export singleton instance\nexport const sqlite3MigrationDriver = new SQLite3MigrationDriver();\n","/**\n * LibSQL Migration Driver\n *\n * Extends SQLite3 driver with native ALTER COLUMN support.\n * LibSQL supports ALTER TABLE ALTER COLUMN syntax that SQLite doesn't,\n * avoiding expensive table recreation for column modifications.\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This differs from PostgreSQL's behavior where constraints\n * are validated against all existing rows.\n */\n\nimport { sqliteDateTimeTargetRequiresRecreation } from \"../../../adapters/databases/sqlite/storage/datetime\";\nimport { sqliteDecimalCheck } from \"../../../adapters/databases/sqlite/storage/decimal\";\nimport {\n SQLITE_GEO_POINT_TYPE,\n sqliteGeoPointCheck,\n sqliteGeoPointEncoding,\n} from \"../../../adapters/databases/sqlite/storage/geo-point\";\nimport {\n decimalConversionRequired,\n sqliteDecimalStorageKind,\n} from \"../../decimal\";\nimport type { ColumnDef, ReferentialAction } from \"../../types\";\nimport type {\n AddForeignKeyOperation,\n AlterColumnOperation,\n DDLContext,\n DropForeignKeyOperation,\n} from \"../base\";\nimport { SQLite3MigrationDriver } from \"../sqlite\";\nimport type { MigrationCapabilities } from \"../types\";\n\nexport class LibSQLMigrationDriver extends SQLite3MigrationDriver {\n override readonly driverName: string = \"libsql\";\n\n // Same capabilities as SQLite3 (no native enums, no arrays, btree only)\n override readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n // Adds FKs by rewriting the column (`ALTER COLUMN ... TO`), which needs the\n // existing column def — not a standalone add. Keep FKs inline in CREATE\n // TABLE and rely on lazy reference resolution (forward refs are fine).\n supportsAddForeignKeyViaAlter: false,\n // Inherits SQLite's introspection verbatim, so the same two names are\n // unreadable here.\n introspectionReadsConstraintNames: false,\n };\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: ALTER COLUMN (native support)\n // ===========================================================================\n\n /**\n * LibSQL supports ALTER TABLE ... ALTER COLUMN ... TO syntax.\n * This avoids table recreation for column type/default/nullable changes.\n *\n * Syntax: ALTER TABLE t ALTER COLUMN c TO c <new_column_def>\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This is different from PostgreSQL's behavior.\n */\n override generateAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): string {\n // A decimal descriptor change CONVERTS stored values — SQLite holds the\n // unscaled coefficient, so the same integer means a different number at a\n // different scale. The native ALTER rewrites the column DECLARATION and\n // copies nothing, and by LibSQL's own contract (above) it validates only\n // rows written afterwards, so every existing row would keep its old\n // coefficient under the new domain and read back wrong. Table recreation\n // is the only route that carries the values across; §9.6 states it as a\n // falsifier (\"LibSQL cannot take a native ALTER route that skips\n // conversion\").\n if (\n decimalConversionRequired(op.from, op.to) ||\n sqliteDateTimeTargetRequiresRecreation(op.from.dateTime, op.to.dateTime)\n ) {\n return this.compileAlterColumnByRecreation(op, context).join(\";\\n\");\n }\n\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // Build new column definition\n const colDef = this.generateColumnDef(to, context);\n\n // LibSQL syntax: ALTER TABLE t ALTER COLUMN old_name TO new_def\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n override compileAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n if (\n decimalConversionRequired(op.from, op.to) ||\n sqliteDateTimeTargetRequiresRecreation(op.from.dateTime, op.to.dateTime)\n ) {\n return this.compileAlterColumnByRecreation(op, context);\n }\n return super.compileAlterColumn(op, context);\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n // ===========================================================================\n // HELPER: Build column definition with optional REFERENCES\n // ===========================================================================\n\n /**\n * Builds a column definition string with optional foreign key REFERENCES clause.\n * Used for LibSQL's ALTER COLUMN TO syntax.\n */\n private buildColumnDefWithReferences(\n column: ColumnDef,\n fkRef?: {\n refTable: string;\n refCol: string;\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n }\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (column.type.toUpperCase() === SQLITE_GEO_POINT_TYPE) {\n parts.push(\n sqliteGeoPointCheck(\n column,\n (name) => this.escapeIdentifier(name),\n sqliteGeoPointEncoding(column)\n )\n );\n }\n\n // The reserved decimal CHECK travels with the rewritten declaration.\n // `ALTER COLUMN ... TO` replaces the WHOLE column definition, so a\n // constraint this rebuild left out would be gone from the stored\n // `CREATE TABLE` — and with it the only carrier of the column's declared\n // domain, which introspection would then read as a descriptor change on\n // every push afterwards.\n const kind = sqliteDecimalStorageKind(column);\n if (column.decimal && kind) {\n parts.push(\n sqliteDecimalCheck(column, column.decimal, kind, (name) =>\n this.escapeIdentifier(name)\n )\n );\n }\n\n if (fkRef) {\n parts.push(\n `REFERENCES ${this.escapeIdentifier(fkRef.refTable)}(${this.escapeIdentifier(fkRef.refCol)})`\n );\n if (fkRef.onDelete && fkRef.onDelete !== \"noAction\") {\n parts.push(`ON DELETE ${this.formatReferentialAction(fkRef.onDelete)}`);\n }\n if (fkRef.onUpdate && fkRef.onUpdate !== \"noAction\") {\n parts.push(`ON UPDATE ${this.formatReferentialAction(fkRef.onUpdate)}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n /**\n * LibSQL can add foreign keys by redefining the column with REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n *\n * Note: Multi-column FKs still require table recreation.\n */\n override generateAddForeignKey(\n op: AddForeignKeyOperation,\n context: DDLContext\n ): string {\n const { tableName, fk } = op;\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateAddForeignKey(op, context);\n }\n\n // Validate columns exist FIRST (before any array access)\n const fkColumn = fk.columns[0];\n const refColumn = fk.referencedColumns[0];\n if (!(fkColumn && refColumn)) {\n throw new Error(\n `Invalid foreign key: columns array is empty for table \"${tableName}\".`\n );\n }\n\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the column to alter\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot add foreign key: column \"${fkColumn}\" not found in table \"${tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Build column definition with REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column, {\n refTable: fk.referencedTable,\n refCol: refColumn,\n onDelete: fk.onDelete,\n onUpdate: fk.onUpdate,\n });\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n /**\n * LibSQL can drop foreign keys by redefining the column without REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n */\n override generateDropForeignKey(\n op: DropForeignKeyOperation,\n context: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the FK to drop\n const fk = currentTable.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n throw new Error(\n `Cannot drop foreign key: constraint \"${op.fkName}\" not found in table \"${op.tableName}\".`\n );\n }\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateDropForeignKey(op, context);\n }\n\n const fkColumn = fk.columns[0];\n if (!fkColumn) {\n throw new Error(\n `Invalid foreign key: columns array is empty for constraint \"${op.fkName}\".`\n );\n }\n\n // Find the column\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot drop foreign key: column \"${fkColumn}\" not found in table \"${op.tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(op.tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Rebuild column definition WITHOUT REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column);\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // PRIMARY KEY OPERATIONS\n // LibSQL still requires table recreation for PK changes\n // ===========================================================================\n\n // generateAddPrimaryKey and generateDropPrimaryKey inherit from SQLite3\n // which uses table recreation. LibSQL does not support native PK modifications.\n}\n\n// Export singleton instance\nexport const libsqlMigrationDriver = new LibSQLMigrationDriver();\n","/**\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","/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\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 ReferentialAction,\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 } 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 mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\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, and the one\n * admitted target selection.\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\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","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 { 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 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 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 { introspect as introspectMySQL } from \"./introspect\";\nimport {\n mysqlAcquireLockStatement,\n mysqlLockAnswer,\n mysqlReleaseLockStatement,\n mysqlSelectTargetStatement,\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<void> {\n const names = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n );\n if (names.size === 0) return;\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 }\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 private 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 =\n 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(op: CreateTableOperation, context: DDLContext): string {\n return this.compileCreateTable(op, context).join(\";\\n\");\n }\n\n override compileCreateTable(\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 const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.tableRef(fk.referencedTable, context.destination)} (${refCols})`;\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n columnDefs.push(fkDef);\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 this.filterStatements(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 // ===========================================================================\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(op: AlterColumnOperation, context: DDLContext): string {\n return this.alterColumnStatements(op, context).join(\";\\n\");\n }\n\n override compileAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n return this.filterStatements(this.alterColumnStatements(op, context));\n }\n\n private alterColumnStatements(\n op: AlterColumnOperation,\n context: DDLContext\n ): 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 const { tableName, fk } = op;\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\n let sql = `ALTER TABLE ${this.tableRef(tableName, context.destination)} `;\n sql += `ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n sql += `FOREIGN KEY (${cols}) `;\n sql += `REFERENCES ${this.tableRef(fk.referencedTable, context.destination)} (${refCols})`;\n\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\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(op: AlterEnumOperation, context: DDLContext): string {\n return this.compileAlterEnum(op, context).join(\";\\n\");\n }\n\n override compileAlterEnum(\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 this.filterStatements([\n `-- MySQL: no new values provided for enum \"${enumName}\"`,\n ]);\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return this.filterStatements([\n `-- MySQL: no dependent columns found for enum \"${enumName}\"`,\n ]);\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.buildMySQLEnumReplacementUpdates(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 this.filterStatements(statements);\n }\n\n /**\n * The enum-replacement UPDATEs, with their table position qualified (§5.1).\n *\n * `MigrationDriver.buildEnumReplacementUpdates` renders the same statements\n * database-relative and takes no `DDLContext`, so it cannot express a live\n * table position; `base.ts` is shared with the PostgreSQL and SQLite dialects\n * and is owned by no unit of this change, so MySQL renders its own text here\n * and keeps the SHARED decision — which surviving value (or NULL) replaces a\n * removed one — in `getEnumValueReplacement`.\n *\n * With no namespace or an artifact destination this produces the base\n * builder's exact bytes.\n */\n private buildMySQLEnumReplacementUpdates(\n op: AlterEnumOperation,\n context: DDLContext\n ): string[] {\n const { removeValues, dependentColumns } = op;\n if (!(removeValues?.length && dependentColumns?.length)) {\n return [];\n }\n\n const statements: string[] = [];\n for (const { tableName, columnName } of dependentColumns) {\n const table = this.tableRef(tableName, context.destination);\n const column = this.escapeIdentifier(columnName);\n for (const removedValue of removeValues) {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n removedValue\n );\n if (replacement === undefined) {\n continue;\n }\n const newValue =\n replacement === null ? \"NULL\" : this.escapeValue(replacement);\n statements.push(\n `UPDATE ${table} SET ${column} = ${newValue} WHERE ${column} = ${this.escapeValue(removedValue)}`\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 override generateClearMigrations(tableName: string): string {\n return `DELETE FROM ${this.tableRef(tableName, \"live\")}`;\n }\n\n override generateDropTableSQL(tableName: string): string {\n return `DROP TABLE IF EXISTS ${this.tableRef(tableName, \"live\")}`;\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 * 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","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n","/**\n * Decision 7.4 — the declared partial-index predicate, canonicalized by the\n * database that will store it.\n *\n * PostgreSQL's catalog does not keep the statement it was given. `CREATE INDEX\n * … WHERE published = true` is parsed into a node tree, and\n * `pg_get_expr(indpred, indrelid)` deparses that tree back out as\n * `(published = true)`. The introspection reads the deparsed form; the\n * serializer holds the declared form; they never compare equal, so **every push\n * dropped and re-created every partial index**. SQLite has no such gap — it\n * stores the CREATE INDEX text verbatim — which is why only this dialect\n * implements the hook.\n *\n * The fix asks PostgreSQL itself. A predicate is put through the same parse and\n * deparse the catalog performs, and the differ compares the two answers. If\n * both texts deparse to one text they are one predicate; if either cannot be\n * deparsed, nothing is claimed and the drop/create stands. No client-side text\n * normalization can do this and stay fail-closed: flattening whitespace and\n * parentheses makes `a AND (b OR c)` read equal to `(a AND b) OR c`, and a real\n * predicate change would stop being seen.\n *\n * The vehicle is a session-local view: `SELECT 1 AS c FROM <table> WHERE <p>`,\n * read back with `pg_get_viewdef`. A view is the cheapest parse-and-store\n * PostgreSQL offers — no table scan, no data touched, only an ACCESS SHARE lock\n * on the table, and nothing outside this session can see it. A CHECK constraint\n * or a real index would each parse the same expression, but one locks the table\n * against writers and the other builds the index this is trying to avoid\n * building.\n *\n * Both sides of the comparison go through this same transform, so the answer\n * does not depend on `pg_get_viewdef` and `pg_get_expr` agreeing on\n * parenthesization — only on each being a function of the parsed tree.\n *\n * The predicate is interpolated, not bound: it is an expression, and no\n * parameter placeholder can carry one. It reaches here from the schema's own\n * `.index({ where })`, the same text the emitter already interpolates into\n * `CREATE INDEX`, so this widens nothing.\n */\n\nconst SCRATCH_VIEW_PREFIX = \"viborm_index_predicate_\";\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Deparses each predicate through PostgreSQL and returns the answers\n * positionally.\n *\n * `table` arrives ALREADY QUALIFIED and quoted by the bound migration driver.\n * The scratch view is parsed on whatever `search_path` the session carries, so\n * a bare name would canonicalize this estate's predicate against a same-named\n * table in another schema — and then hand that answer to the differ as if it\n * described the estate's own index.\n *\n * Throws rather than reporting a failure per predicate. The caller runs this\n * inside one transaction: a statement that fails aborts it, every later\n * statement in it fails too, and the rollback is what removes the scratch views\n * — which must go, because a view referencing a table blocks dropping that\n * table later in the same push.\n */\nexport async function canonicalizeIndexPredicates(\n table: string,\n predicates: readonly string[],\n executeRaw: RawExecutor\n): Promise<ReadonlyArray<string | undefined>> {\n if (predicates.length === 0) return [];\n const views = predicates.map((_, position) =>\n quoteIdentifier(`${SCRATCH_VIEW_PREFIX}${position}`)\n );\n\n for (const [position, predicate] of predicates.entries()) {\n // OR REPLACE, not a bare CREATE: the projection is always `1 AS c`, so a\n // scratch view left by an earlier call on this pooled connection is\n // replaceable rather than a collision.\n await executeRaw(\n `CREATE OR REPLACE TEMP VIEW ${views[position]} AS SELECT 1 AS c FROM ${table} WHERE ${predicate}`\n );\n }\n\n const projection = views\n .map(\n (view, position) =>\n `pg_catalog.pg_get_viewdef('pg_temp.${view}'::regclass) AS \"d${position}\"`\n )\n .join(\", \");\n const { rows } = await executeRaw<Record<string, string | null>>(\n `SELECT ${projection}`\n );\n\n await executeRaw(\n `DROP VIEW ${views.map((view) => `pg_temp.${view}`).join(\", \")}`\n );\n\n const row = rows[0];\n return predicates.map((_, position) => row?.[`d${position}`] ?? undefined);\n}\n","/**\n * PostgreSQL Schema Introspection\n *\n * Reads the current database schema from PostgreSQL's information_schema\n * and system catalogs, returning a normalized SchemaSnapshot.\n *\n * Every catalog query is NAMESPACE-RELATIVE: the selected schema arrives as a\n * bound parameter (`$1`), never as a literal in a predicate and never as a\n * `public` fallback. The snapshot it produces stays namespace-RELATIVE in the\n * other direction — table, enum and type names are bare, exactly as the\n * serializer spells them — so one estate's snapshot never carries the schema\n * its DDL renderer qualifies with.\n */\n\nimport {\n canonicalizeDecimal,\n type DecimalDescriptor,\n decimalDefaultText,\n} from \"@validation/primitives/decimal-codec\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { readStoredDecimalDescriptor } from \"../../decimal\";\nimport type {\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { groupBy, groupByNested } from \"../utils\";\nimport type {\n PgColumn,\n PgCrossSchemaForeignKey,\n PgEnum,\n PgForeignKey,\n PgIndex,\n PgPrimaryKey,\n PgTable,\n PgUniqueConstraint,\n} from \"./types\";\n\n// Regex for cleaning up PostgreSQL type casting (e.g., 'value'::text -> 'value')\nconst TYPE_CAST_REGEX =\n /::(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*)(?:\\.(?:\"(?:[^\"]|\"\")+\"|[a-zA-Z_][\\w$]*))?(?:\\s+(?:varying|precision|with time zone|without time zone))?(?:\\(\\d+(?:,\\s*\\d+)?\\))?(?:\\[\\])?$/;\n\n/** The schemas PostgreSQL's own types live in; never estate-owned. */\nconst BUILT_IN_TYPE_SCHEMAS = new Set([\"pg_catalog\", \"information_schema\"]);\n\n/**\n * What one introspection run is bound to.\n *\n * `namespace` is the estate's schema, and `admittedExtensionTypes` is the set\n * of extension-owned base type names the CONCRETE adapter declares typmods\n * for (pgvector's `vector`, PostGIS's `geometry`/`geography`). An extension\n * type outside that set is still read — through `udt_name`, the way every\n * snapshot written before `format_type` was consulted holds it.\n */\nexport interface PostgresIntrospectionScope {\n readonly namespace: string;\n readonly tables?: readonly string[];\n readonly admittedExtensionTypes: ReadonlySet<string>;\n}\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\nexport const POSTGRES_MANAGED_TABLE_NAMES_QUERY = `\nSELECT tables.table_name, tables.table_name AS name, relation.relkind AS relation_kind, relation.relispartition AS is_partition\nFROM information_schema.tables tables\nJOIN pg_catalog.pg_class relation\n ON relation.relname = tables.table_name\nJOIN pg_catalog.pg_namespace relation_namespace\n ON relation_namespace.oid = relation.relnamespace\n AND relation_namespace.nspname = tables.table_schema\nWHERE tables.table_schema = $1\n AND tables.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n JOIN pg_catalog.pg_extension extension\n ON extension.oid = dependency.refobjid\n WHERE dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND dependency.objid = relation.oid\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.deptype = 'e'\n )\nORDER BY tables.table_name;\n`;\n\n/**\n * Columns, with the type identity the snapshot cannot be built without.\n *\n * The catalog join beside `information_schema.columns` exists for two facts\n * that view cannot give: the server's formatted type (modifiers and array\n * structure) and the extension provenance that proves a non-estate type is a\n * provider object rather than an unknown external one. For an ARRAY column the\n * dependency is looked up on the ELEMENT type (`typcategory = 'A'`), because\n * the array type's own dependency is on its element, not on the extension.\n */\nconst COLUMNS_QUERY = `\nSELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_schema,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n a.attgenerated AS generated_kind,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n pg_catalog.format_type(a.atttypid, a.atttypmod) AS formatted_type,\n ext.extname AS type_extension,\n ext_ns.nspname AS type_extension_schema\nFROM information_schema.columns c\nJOIN information_schema.tables t\n ON c.table_name = t.table_name\n AND c.table_schema = t.table_schema\nJOIN pg_catalog.pg_class cls\n ON cls.relname = c.table_name\nJOIN pg_catalog.pg_namespace cls_ns\n ON cls_ns.oid = cls.relnamespace\n AND cls_ns.nspname = c.table_schema\nJOIN pg_catalog.pg_attribute a\n ON a.attrelid = cls.oid\n AND a.attname = c.column_name\nJOIN pg_catalog.pg_type col_type\n ON col_type.oid = a.atttypid\nLEFT JOIN pg_catalog.pg_depend dep\n ON dep.classid = 'pg_catalog.pg_type'::regclass\n AND dep.objid = CASE\n WHEN col_type.typcategory = 'A' THEN col_type.typelem\n ELSE col_type.oid\n END\n AND dep.deptype = 'e'\nLEFT JOIN pg_catalog.pg_extension ext\n ON ext.oid = dep.refobjid\nLEFT JOIN pg_catalog.pg_namespace ext_ns\n ON ext_ns.oid = ext.extnamespace\nWHERE c.table_schema = $1\n AND t.table_type = 'BASE TABLE'\n AND NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend relation_dependency\n JOIN pg_catalog.pg_extension relation_extension\n ON relation_extension.oid = relation_dependency.refobjid\n WHERE relation_dependency.classid = 'pg_catalog.pg_class'::pg_catalog.regclass\n AND relation_dependency.objid = cls.oid\n AND relation_dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND relation_dependency.deptype = 'e'\n )\nORDER BY c.table_name, c.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\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\nORDER BY tc.table_name, kcu.ordinal_position;\n`;\n\n/**\n * Standalone indexes. `conindid` names the index a UNIQUE or PRIMARY KEY\n * constraint owns — those stay in `uniqueConstraints` / `primaryKey`. A\n * foreign key also points `conindid` at the unique index it targets, so the\n * join must not treat that as ownership or a unique-index FK target vanishes\n * from both lists.\n */\nconst INDEXES_QUERY = `\nSELECT\n t.relname AS table_name,\n i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n (ix.indexprs IS NOT NULL OR ix.indnkeyatts <> ix.indnatts OR NOT ix.indisvalid OR NOT ix.indisready OR COALESCE((to_jsonb(ix)->>'indnullsnotdistinct')::boolean,false)\n OR EXISTS (SELECT 1 FROM unnest(ix.indoption) AS flags(value) WHERE flags.value <> 0)\n OR EXISTS (SELECT 1 FROM unnest(ix.indclass) AS classes(oid) JOIN pg_opclass AS opc ON opc.oid=classes.oid WHERE NOT opc.opcdefault)\n OR EXISTS (SELECT 1 FROM generate_series(0,ix.indnkeyatts-1) AS key(position) LEFT JOIN pg_attribute AS attr ON attr.attrelid=t.oid AND attr.attnum=ix.indkey[key.position] WHERE ix.indcollation[key.position] <> COALESCE(attr.attcollation,0))) AS unsupported_structure,\n am.amname AS index_type,\n pg_get_expr(ix.indpred, ix.indrelid) AS filter_condition,\n array_position(ix.indkey, a.attnum) AS ordinal_position\nFROM pg_index ix\nJOIN pg_class t ON t.oid = ix.indrelid\nJOIN pg_class i ON i.oid = ix.indexrelid\nJOIN pg_am am ON am.oid = i.relam\nJOIN pg_namespace n ON n.oid = t.relnamespace\nLEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)\nLEFT JOIN pg_constraint c\n ON c.conindid = ix.indexrelid\n AND c.contype IN ('u', 'p')\nWHERE n.nspname = $1\n AND NOT ix.indisprimary\n AND c.oid IS NULL\n AND t.relkind = 'r'\nORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);\n`;\n\n/**\n * Foreign keys OWNED by the selected schema.\n *\n * Read from `pg_constraint`, not `information_schema.referential_constraints`.\n * A foreign key may target a unique INDEX rather than a unique constraint;\n * that catalog view then leaves `unique_constraint_name` null and the join\n * drops the constraint. `pg_constraint.confrelid`/`confkey` still name the\n * referenced columns. Both sides stay in this schema so `referencedTable` is\n * a bare estate-relative name. A constraint that leaves the schema is not\n * silently dropped — `CROSS_SCHEMA_FOREIGN_KEYS_QUERY` inventories both\n * directions and refuses the whole run before this snapshot is published.\n */\nconst FOREIGN_KEYS_QUERY = `\nSELECT\n owner.relname AS table_name,\n con.conname AS constraint_name,\n local_att.attname AS column_name,\n referenced.relname AS foreign_table_name,\n referenced_att.attname AS foreign_column_name,\n CASE con.confdeltype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS delete_rule,\n CASE con.confupdtype\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'd' THEN 'SET DEFAULT'\n ELSE 'NO ACTION'\n END AS update_rule,\n local.ordinality AS ordinal_position\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nJOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS local(attnum, ordinality) ON TRUE\nJOIN LATERAL unnest(con.confkey) WITH ORDINALITY AS referenced_col(attnum, ordinality)\n ON referenced_col.ordinality = local.ordinality\nJOIN pg_catalog.pg_attribute local_att\n ON local_att.attrelid = owner.oid AND local_att.attnum = local.attnum\nJOIN pg_catalog.pg_attribute referenced_att\n ON referenced_att.attrelid = referenced.oid\n AND referenced_att.attnum = referenced_col.attnum\nWHERE con.contype = 'f'\n AND owner_ns.nspname = $1\n AND referenced_ns.nspname = $1\nORDER BY owner.relname, con.conname, local.ordinality;\n`;\n\n/**\n * Every foreign key with exactly ONE side in the selected schema.\n *\n * `pg_constraint` is joined to its owning and referenced relations through both\n * `pg_class`/`pg_namespace` pairs, so an INBOUND key — owned by a foreign\n * schema, pointing at an estate table — is found as readily as an outbound one.\n * The exclusive-or in the predicate is the whole test: a key with both sides in\n * the schema is ordinary, a key with neither belongs to somebody else.\n */\nconst CROSS_SCHEMA_FOREIGN_KEYS_QUERY = `\nSELECT\n con.conname AS constraint_name,\n owner_ns.nspname AS owning_schema,\n owner.relname AS owning_table,\n referenced_ns.nspname AS referenced_schema,\n referenced.relname AS referenced_table\nFROM pg_catalog.pg_constraint con\nJOIN pg_catalog.pg_class owner ON owner.oid = con.conrelid\nJOIN pg_catalog.pg_namespace owner_ns ON owner_ns.oid = owner.relnamespace\nJOIN pg_catalog.pg_class referenced ON referenced.oid = con.confrelid\nJOIN pg_catalog.pg_namespace referenced_ns ON referenced_ns.oid = referenced.relnamespace\nWHERE con.contype = 'f'\n AND (owner_ns.nspname = $1) <> (referenced_ns.nspname = $1)\nORDER BY owner_ns.nspname, owner.relname, con.conname;\n`;\n\nconst UNIQUE_CONSTRAINTS_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\nWHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\nORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;\n`;\n\nconst ENUMS_QUERY = `\nSELECT\n t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\nFROM pg_type t\nJOIN pg_enum e ON t.oid = e.enumtypid\nJOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE n.nspname = $1\nORDER BY t.typname, e.enumsortorder;\n`;\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction mapReferentialAction(rule: string): ReferentialAction {\n switch (rule) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/** The element type's name for an array type, else the name itself. */\nfunction baseTypeName(udtName: string): string {\n return udtName.startsWith(\"_\") ? udtName.slice(1) : udtName;\n}\n\n/**\n * The extension-owned type spelled the way this estate's DDL spells it.\n *\n * `format_type` qualifies the type when the extension's schema is not on the\n * session's `search_path` and leaves it bare when it is, so the same column\n * reads back two ways on two sessions. Removing exactly the PROVEN extension\n * schema — never a general prefix strip — makes the answer one, and keeps every\n * modifier and the array suffix the catalog supplied.\n */\nfunction stripExtensionSchema(formattedType: string, schema: string): string {\n for (const prefix of [`${schema}.`, `\"${schema.replaceAll('\"', '\"\"')}\".`]) {\n if (formattedType.startsWith(prefix)) {\n return formattedType.slice(prefix.length);\n }\n }\n return formattedType;\n}\n\n/**\n * The one unrepresentable class: a type of another schema that no installed\n * extension owns (§4.2's external enum, domain, composite or UDT).\n *\n * The refusal names both schemas in its MESSAGE. `meta` carries only keys the\n * error metadata allowlist admits (`src/errors/diagnostics.ts`), which has no\n * namespace key today, so the schema travels in the message rather than being\n * silently dropped from a metadata object that claims to carry it.\n */\nfunction refuseUnrepresentableType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): never {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" has type \"${col.udt_schema}\".\"${baseTypeName(col.udt_name)}\", which lives in another schema and no installed extension owns it. ` +\n `VibORM manages one schema (\"${scope.namespace}\") and cannot represent that type in a snapshot or regenerate it as DDL.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n meta: {\n table: col.table_name,\n column: col.column_name,\n type: baseTypeName(col.udt_name),\n feature: \"external-type\",\n },\n }\n );\n}\n\n/**\n * The snapshot spelling of one column's type.\n *\n * Two readings, and a refusal for what neither can spell:\n *\n * 1. A provider object owned by an extension this adapter DECLARES keeps the\n * server's own formatted spelling, so its modifiers and array structure\n * survive the round trip (`vector(3)`, `geometry(Point,4326)`).\n * 2. Everything else keeps the `udt_name` reading every existing snapshot was\n * written with — built-ins, estate-owned types, AND an extension type\n * outside the two admitted capabilities. The capability decides which\n * SPELLING is read, never whether a type is representable: `citext` is a\n * shipped VibORM native type (`src/schema/scalars/native-types.ts`) that no\n * capability can admit, and `udt_name` spells it exactly as the desired\n * side does, so it round-trips. Refusing it would brick `introspect` and\n * `push` for an estate that used it.\n * 3. A type of ANOTHER schema that no extension owns is refused, because\n * nothing here can spell it: a snapshot carries bare names relative to the\n * estate, and re-rendering that name would create a same-named object in\n * the estate rather than reach the one the column actually has.\n */\nfunction formatColumnType(\n col: PgColumn,\n scope: PostgresIntrospectionScope\n): string {\n const extensionType = baseTypeName(col.udt_name);\n if (\n col.type_extension === \"postgis\" &&\n (extensionType === \"geometry\" || extensionType === \"geography\") &&\n !scope.admittedExtensionTypes.has(extensionType)\n ) {\n throw new MigrationError(\n `Column \"${col.table_name}\".\"${col.column_name}\" uses PostGIS ${extensionType}, but this PostgreSQL adapter has no GeoPoint protocol. ` +\n \"Migration introspection refuses to erase its subtype and SRID into a bare extension type; construct the driver with `postgis: true` or use a client that does not manage this estate.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: extensionType,\n feature: \"GeoPoint\",\n },\n }\n );\n }\n if (\n col.type_extension !== null &&\n col.type_extension_schema !== null &&\n scope.admittedExtensionTypes.has(extensionType)\n ) {\n return stripExtensionSchema(col.formatted_type, col.type_extension_schema);\n }\n\n // `type_extension === null` is what keeps an extension type installed\n // OUTSIDE the estate (the ordinary `CREATE EXTENSION citext` into `public`)\n // out of this refusal: the extension owns it, PostgreSQL resolves it for the\n // unqualified type token the renderer emits, and `udt_name` spells it.\n if (\n col.type_extension === null &&\n col.udt_schema !== scope.namespace &&\n !BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)\n ) {\n refuseUnrepresentableType(col, scope);\n }\n\n const elementType = baseTypeName(col.udt_name);\n const snapshotType = col.udt_name.startsWith(\"_\")\n ? `${elementType}[]`\n : elementType;\n\n // The server's formatted built-in type retains every typmod, including\n // precision on timestamp/time, bit widths and array element modifiers.\n if (BUILT_IN_TYPE_SCHEMAS.has(col.udt_schema)) {\n return col.formatted_type;\n }\n\n return snapshotType;\n}\n\n/** `numeric[]`'s `udt_name`; PostgreSQL prefixes an array type with `_`. */\nconst NUMERIC_ARRAY_UDT = \"_numeric\";\n\n/**\n * The declared decimal domain of a PostgreSQL column, or `undefined`.\n *\n * PostgreSQL is the one dialect that needs no reserved carrier: the typmod IS\n * the descriptor, so it is read from the catalog rather than from anything\n * VibORM wrote. A scalar reports it through `information_schema`; an array\n * reports it only inside `format_type`, so the two are recovered from the two\n * places the server keeps them.\n *\n * An unconstrained `numeric` has no typmod and therefore no domain — which is\n * correct, and is what makes the differ plan the conversion to a declared one.\n */\nfunction readDecimalDomain(col: PgColumn): DecimalDescriptor | undefined {\n if (col.data_type === \"numeric\" && col.numeric_precision !== null) {\n return requireDecimalDomain(\n col,\n col.numeric_precision,\n col.numeric_scale ?? 0\n );\n }\n if (col.udt_name !== NUMERIC_ARRAY_UDT) return undefined;\n const match = NUMERIC_ARRAY_TYPMOD.exec(col.formatted_type);\n if (!match) return undefined;\n return requireDecimalDomain(col, match[1], match[2]);\n}\n\nconst NUMERIC_ARRAY_TYPMOD = /^numeric\\((-?\\d+),(-?\\d+)\\)\\[\\]$/;\n\nfunction requireDecimalDomain(\n col: PgColumn,\n precision: unknown,\n scale: unknown\n): DecimalDescriptor {\n const descriptor = readStoredDecimalDescriptor(precision, scale, \"pg\");\n if (descriptor !== undefined) return descriptor;\n throw new MigrationError(\n `PostgreSQL reported column \"${col.table_name}\".\"${col.column_name}\" as NUMERIC(${String(precision)},${String(scale)}), outside VibORM's fixed-decimal domain. Migration introspection is refused rather than publishing an invalid descriptor.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n dialect: \"postgresql\",\n table: col.table_name,\n column: col.column_name,\n type: \"invalid-catalog-decimal-domain\",\n },\n }\n );\n}\n\nfunction isAutoIncrement(columnDefault: string | null): boolean {\n if (!columnDefault) return false;\n return (\n columnDefault.includes(\"nextval(\") ||\n columnDefault.includes(\"_seq'::regclass)\")\n );\n}\n\n/**\n * Every spelling PostgreSQL can give the terminal cast onto ONE named type.\n *\n * The server renders a default expression through `pg_get_expr`, which\n * qualifies the type only when the type's schema is off the session's\n * `search_path` and quotes an identifier only when the identifier needs it.\n * Both facts are session state, so the same column reads back as\n * `'active'::billing.state` on one connection and `'active'::state` on another,\n * and either half may be quoted. The set is enumerated rather than matched by\n * pattern because it must name THIS column's type exactly: a regex loose enough\n * to cover the spellings is also loose enough to eat an unrelated cast.\n */\nfunction terminalCastSpellings(schema: string, typeName: string): string[] {\n const quoted = (name: string) => `\"${name.replaceAll('\"', '\"\"')}\"`;\n const qualifiers = [\"\", `${schema}.`, `${quoted(schema)}.`];\n const names = [typeName, quoted(typeName)];\n const spellings: string[] = [];\n for (const qualifier of qualifiers) {\n for (const name of names) {\n for (const array of [\"\", \"[]\"]) {\n spellings.push(`::${qualifier}${name}${array}`);\n }\n }\n }\n // Longest first: `::billing.state[]` must not be half-stripped by `::state`.\n return spellings.sort((left, right) => right.length - left.length);\n}\n\n/**\n * Removes the cast that names this column's own managed enum type, if the\n * default ends with one.\n *\n * §4.3: the strip is keyed on the column's catalog-proven `udt_schema` /\n * `udt_name` and on that name being an enum this estate manages — never on the\n * text alone. A default casting to a built-in, an extension type, a domain or a\n * composite therefore reaches the generic strip below unchanged, which is what\n * keeps every already-converged column byte-identical.\n */\nfunction stripManagedEnumCast(\n columnDefault: string,\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string {\n const enumName = baseTypeName(col.udt_name);\n if (col.udt_schema !== scope.namespace || !managedEnums.has(enumName)) {\n return columnDefault;\n }\n for (const cast of terminalCastSpellings(col.udt_schema, enumName)) {\n if (columnDefault.endsWith(cast)) {\n return columnDefault.slice(0, -cast.length);\n }\n }\n return columnDefault;\n}\n\nfunction cleanDefault(\n col: PgColumn,\n scope: PostgresIntrospectionScope,\n managedEnums: ReadonlySet<string>\n): string | undefined {\n const columnDefault = col.column_default;\n if (!columnDefault) return undefined;\n\n // Skip auto-increment defaults\n if (isAutoIncrement(columnDefault)) return undefined;\n\n // Clean up type casting (e.g., 'value'::text -> 'value')\n const withoutEnumCast = stripManagedEnumCast(\n columnDefault,\n col,\n scope,\n managedEnums\n );\n const cleaned = withoutEnumCast.replace(TYPE_CAST_REGEX, \"\").trim();\n return renderDecimalDefault(cleaned, readDecimalDomain(col));\n}\n\n/**\n * Re-renders a decimal column's default through the codec, so both snapshot\n * sides hold the SAME of the two renderings.\n *\n * PostgreSQL deparses a decimal default in two spellings and the difference is\n * the sign: `DEFAULT 12.34000` comes back as the bare literal, while\n * `DEFAULT -12.34000` comes back as `'-12.34000'::numeric`, because the minus\n * is a unary operator over a constant and the folded result is spelled as a\n * cast literal. (Measured on PGlite 0.3.) Stripping the cast leaves the quotes\n * behind, so the negative default would never equal the one the serializer\n * emits and the estate would churn forever.\n *\n * Sending it back through `decimalDefaultText` settles both spellings at once:\n * the quotes are dropped by the grammar and the fraction is padded to the\n * scale, which is exactly what the serializer emitted. Anything that is not a\n * decimal literal — a function call, `NULL`, an array literal — is not a value\n * this rendering describes and passes through untouched.\n */\nfunction renderDecimalDefault(\n cleaned: string,\n descriptor: DecimalDescriptor | undefined\n): string {\n if (descriptor === undefined) return cleaned;\n const unquoted =\n cleaned.startsWith(\"'\") && cleaned.endsWith(\"'\") && cleaned.length > 1\n ? cleaned.slice(1, -1)\n : cleaned;\n const canonical = canonicalizeDecimal(unquoted);\n if (canonical === undefined) return cleaned;\n return decimalDefaultText(\"pg\", canonical, descriptor);\n}\n\n/**\n * Refuses a foreign key that crosses the estate boundary, in either direction.\n *\n * This runs BEFORE the snapshot is returned, so push, public introspection and\n * every reset path that inventories objects refuse before planning a single\n * operation — an outbound reference would otherwise be silently dropped from\n * the snapshot (the owned-key query only sees same-schema pairs) and an inbound\n * one would turn a later table drop into somebody else's broken constraint.\n */\nfunction assertNoCrossSchemaForeignKeys(\n crossing: readonly PgCrossSchemaForeignKey[],\n scope: PostgresIntrospectionScope\n): void {\n const first = crossing.find(\n (fk) =>\n scope.tables === undefined ||\n (fk.owning_schema === scope.namespace &&\n scope.tables.includes(fk.owning_table)) ||\n (fk.referenced_schema === scope.namespace &&\n scope.tables.includes(fk.referenced_table))\n );\n if (!first) return;\n\n const direction = first.owning_schema === scope.namespace ? \"out of\" : \"into\";\n throw new MigrationError(\n `Foreign key \"${first.constraint_name}\" points ${direction} the migration estate: ` +\n `\"${first.owning_schema}\".\"${first.owning_table}\" references \"${first.referenced_schema}\".\"${first.referenced_table}\". ` +\n `VibORM manages one schema (\"${scope.namespace}\") per estate, so a constraint with one side outside it is an unsupported migration topology` +\n (crossing.length > 1 ? ` (${crossing.length} such constraints).` : \".\"),\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n {\n // Both schemas are in the message: the metadata allowlist admits no\n // namespace key, and a refusal that cannot say which boundary was\n // crossed is not actionable.\n meta: {\n constraint: first.constraint_name,\n table: first.owning_table,\n relation: first.referenced_table,\n feature: \"cross-schema-foreign-key\",\n },\n }\n );\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspectPostgresSchema(\n executeRaw: RawExecutor,\n scope: PostgresIntrospectionScope\n): Promise<SchemaSnapshot> {\n const namespace = [scope.namespace];\n\n // One after another: `push` runs these on its ONE pinned session, and a\n // connection runs one statement at a time. Overlapping them only queued\n // them inside the provider, which node-postgres warns it will refuse in\n // pg@9. Each is a short catalog read.\n const tablesResult = await executeRaw<PgTable>(\n POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n namespace\n );\n const columnsResult = await executeRaw<PgColumn>(COLUMNS_QUERY, namespace);\n const primaryKeysResult = await executeRaw<PgPrimaryKey>(\n PRIMARY_KEYS_QUERY,\n namespace\n );\n const indexesResult = await executeRaw<PgIndex>(INDEXES_QUERY, namespace);\n const foreignKeysResult = await executeRaw<PgForeignKey>(\n FOREIGN_KEYS_QUERY,\n namespace\n );\n const crossSchemaForeignKeysResult =\n await executeRaw<PgCrossSchemaForeignKey>(\n CROSS_SCHEMA_FOREIGN_KEYS_QUERY,\n namespace\n );\n const uniqueConstraintsResult = await executeRaw<PgUniqueConstraint>(\n UNIQUE_CONSTRAINTS_QUERY,\n namespace\n );\n const enumsResult = await executeRaw<PgEnum>(ENUMS_QUERY, namespace);\n\n assertNoCrossSchemaForeignKeys(crossSchemaForeignKeysResult.rows, scope);\n\n // Group results using helper functions\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,\n (fk) => fk.table_name,\n (fk) => fk.constraint_name\n );\n const uniqueByTable = groupByNested(\n uniqueConstraintsResult.rows,\n (uq) => uq.table_name,\n (uq) => uq.constraint_name\n );\n const enumsByName = groupBy(enumsResult.rows, (e) => e.enum_name);\n const managedEnums = new Set(enumsByName.keys());\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.table_name;\n\n const selected =\n scope.tables === undefined || scope.tables.includes(tableName);\n if (\n selected &&\n (table.relation_kind === \"p\" || table.is_partition === true)\n )\n throw new MigrationError(\n `PostgreSQL table \"${tableName}\" is partitioned or a partition. Synchronization refuses before effects because its physical definition cannot be represented.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: tableName, feature: \"partitioned table\" } }\n );\n const generated = (columnsByTable.get(tableName) ?? []).find(\n (column) =>\n column.generated_kind !== undefined && column.generated_kind !== \"\"\n );\n if (selected && generated)\n throw new MigrationError(\n `PostgreSQL column \"${tableName}.${generated.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: generated.column_name,\n feature: \"generated column\",\n },\n }\n );\n\n // Build columns\n const columns = (columnsByTable.get(tableName) || []).map((col) => ({\n name: col.column_name,\n type:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? col.udt_name.startsWith(\"_\")\n ? `${baseTypeName(col.udt_name)}[]`\n : col.udt_name\n : formatColumnType(col, scope),\n nullable: col.is_nullable === \"YES\",\n default:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : cleanDefault(col, scope, managedEnums),\n autoIncrement: isAutoIncrement(col.column_default),\n decimal:\n scope.tables !== undefined && !scope.tables.includes(tableName)\n ? undefined\n : readDecimalDomain(col),\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 firstPk = pkCols[0];\n if (firstPk) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.column_name),\n name: firstPk.constraint_name,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n indexCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstCol = indexCols[0];\n if (firstCol) {\n const method = firstCol.index_type;\n const managed =\n scope.tables === undefined || scope.tables.includes(tableName);\n if (\n managed &&\n (firstCol.unsupported_structure !== false ||\n (method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"))\n ) {\n throw new MigrationError(\n `PostgreSQL index \"${tableName}.${indexName}\" has physical method/order/expression/include/opclass/collation semantics that this index declaration cannot represent. Synchronization refuses before effects and preserves the index. Manage its table outside this synchronization scope until a faithful declaration is available.`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { table: tableName, indexName } }\n );\n }\n if (\n method !== \"btree\" &&\n method !== \"hash\" &&\n method !== \"gin\" &&\n method !== \"gist\"\n )\n continue;\n if (indexCols.some((column) => column.column_name === null)) continue;\n indexes.push({\n name: indexName,\n columns: indexCols.flatMap((idx) =>\n idx.column_name === null ? [] : [idx.column_name]\n ),\n unique: firstCol.is_unique,\n type: method,\n where: firstCol.filter_condition || 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.foreign_table_name,\n referencedColumns: fkCols.map((fk) => fk.foreign_column_name),\n onDelete: mapReferentialAction(firstFk.delete_rule),\n onUpdate: mapReferentialAction(firstFk.update_rule),\n });\n }\n }\n }\n\n // Build unique constraints\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const tableUniques = uniqueByTable.get(tableName);\n if (tableUniques) {\n for (const [constraintName, uqCols] of tableUniques) {\n uqCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n uniqueConstraints.push({\n name: constraintName,\n columns: uqCols.map((uq) => uq.column_name),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // Build enums\n const enums: EnumDef[] = [];\n for (const [enumName, enumVals] of enumsByName) {\n enumVals.sort((a, b) => a.sort_order - b.sort_order);\n enums.push({\n name: enumName,\n values: enumVals.map((e) => e.enum_value),\n });\n }\n\n return {\n tables,\n enums: enums.length > 0 ? enums : undefined,\n };\n}\n","import { nativeTypeFor } from \"@schema/scalars/native-types\";\nimport { idDomainOfState, idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport {\n arrayLiteralText,\n readArrayLiteralText,\n} from \"../../../adapters/databases/postgres/array-literal\";\nimport { stringifyJson } from \"../../../adapters/shared/standard-sql\";\n/**\n * PostgreSQL Migration Driver\n *\n * Implements the MigrationDriver interface for PostgreSQL databases.\n * Supports all DDL operations natively.\n */\n\nimport type { Scalar, ScalarState } from \"@schema/scalars\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport { hasIdPrefix } from \"@validation/primitives/id-formats\";\nimport { errorCause } from \"../../../drivers/shared/driver-options\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport { renderQualifiedIdentifier } from \"../../../sql/identifiers\";\nimport {\n decimalConversionConstraintName,\n decimalConversionRequired,\n postgresDecimalFitsCheck,\n} from \"../../decimal\";\nimport {\n isPostgresTextToUuid,\n postgresTextToUuidGuard,\n} from \"../../identifier-conversion\";\nimport type { NativeRenameOperation } from \"../../native-rename\";\nimport type {\n ColumnDef,\n DiffOperation,\n IndexDef,\n SchemaSnapshot,\n TableDef,\n} from \"../../types\";\nimport { derivedMigrationName } from \"../../utils\";\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 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 { getPostgresType, PG_TYPE_DEFAULTS } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { canonicalizeIndexPredicates } from \"./canonicalize-index-predicate\";\nimport {\n introspectPostgresSchema,\n POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n} from \"./introspect\";\n\ntype RawExecutor = <T>(\n sql: string,\n params?: unknown[]\n) => Promise<{ rows: T[] }>;\n\n/**\n * One catalog existence proof for the estate's schema.\n *\n * Bound, never interpolated, and asking `pg_namespace` exactly one question:\n * does this schema exist. Privilege failures are deliberately NOT folded in —\n * a schema this role cannot use is a different fact with a different fix, and\n * it surfaces as the provider's own error from the statement that needed the\n * privilege.\n */\nconst VECTOR_TYPE_TOKEN = /^(vector|halfvec|sparsevec)(?:\\(\\d+\\))?(?:\\[\\])?$/i;\nconst TEMPORAL_PRECISION_TOKEN = /\\((\\d+)\\)/;\n\nconst NAMESPACE_EXISTS_QUERY =\n \"SELECT 1 AS present FROM pg_catalog.pg_namespace WHERE nspname = $1\";\n\n/**\n * Extension-owned base types whose SERVER-FORMATTED spelling introspection\n * reads, keyed by the adapter capability that declares them.\n *\n * These are the types whose modifiers a snapshot cannot be written without\n * (`vector(3)`, `geometry(Point,4326)`), so introspection reads\n * `format_type` for them instead of `udt_name`. The set admits a SPELLING,\n * never a type: an extension type outside it — `citext`, and anything else a\n * database has installed — reads back through `udt_name` like every built-in,\n * which is the spelling this driver's own renderer emits for it.\n */\nconst EXTENSION_TYPES_BY_CAPABILITY = {\n supportsVector: [\"vector\", \"halfvec\", \"sparsevec\"],\n geoPoint: [\"geometry\", \"geography\"],\n} as const;\n\nconst POSTGIS_PREFLIGHT_QUERY = `\nWITH postgis AS (\n SELECT oid\n FROM pg_catalog.pg_extension\n WHERE extname = 'postgis'\n), required_objects(classid, objid) AS (\n VALUES\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geometry')::pg_catalog.oid),\n ('pg_catalog.pg_type'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regtype('geography')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_makepoint(double precision,double precision)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_setsrid(geometry,integer)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_x(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_y(geometry)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_geomfromgeojson(text)')::pg_catalog.oid),\n ('pg_catalog.pg_proc'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regprocedure('st_intersects(geography,geography)')::pg_catalog.oid),\n ('pg_catalog.pg_operator'::pg_catalog.regclass::pg_catalog.oid, pg_catalog.to_regoperator('&&(geography,geography)')::pg_catalog.oid)\n)\nSELECT (\n EXISTS (SELECT 1 FROM postgis)\n AND NOT EXISTS (\n SELECT 1\n FROM required_objects required\n WHERE required.objid IS NULL\n OR NOT EXISTS (\n SELECT 1\n FROM pg_catalog.pg_depend dependency\n CROSS JOIN postgis\n WHERE dependency.classid = required.classid\n AND dependency.objid = required.objid\n AND dependency.objsubid = 0\n AND dependency.refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n AND dependency.refobjid = postgis.oid\n AND dependency.deptype = 'e'\n )\n )\n) AS ready\n`;\n\nfunction snapshotUsesGeoPoint(snapshot: SchemaSnapshot): boolean {\n const physicalType = PG_TYPE_DEFAULTS.point.toLowerCase().replace(/\\s+/g, \"\");\n return snapshot.tables.some((table) =>\n table.columns.some(\n (column) => column.type.toLowerCase().replace(/\\s+/g, \"\") === physicalType\n )\n );\n}\n\nconst QUOTED_LITERAL = /^'(.*)'$/s;\n\nconst storesEnum = (column: ColumnDef, enumName: string) =>\n column.type === enumName || column.type === `${enumName}[]`;\n\n/** The labels a default of `enumName`, or of its array, spells. */\nfunction enumDefaultLabels(\n column: ColumnDef,\n enumName: string\n): readonly (string | null)[] {\n if (!storesEnum(column, enumName)) return [];\n const literal = column.default\n ?.match(QUOTED_LITERAL)?.[1]\n ?.replaceAll(\"''\", \"'\");\n if (literal === undefined) return [];\n return column.type === enumName\n ? [literal]\n : (readArrayLiteralText(literal) ?? []);\n}\n\nconst IDENTIFIER_PART = /[\\w$]/;\n\n/**\n * Whether SQL text may name `identifier`: bare in any case, or double-quoted.\n * Matches inside literals and comments count too; they only cost a type\n * recreation that was not needed.\n */\nfunction mayName(sql: string, identifier: string): boolean {\n const text = sql.toLowerCase();\n const name = identifier.replaceAll('\"', '\"\"').toLowerCase();\n for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1))\n if (\n !(\n IDENTIFIER_PART.test(text[at - 1] ?? \"\") ||\n IDENTIFIER_PART.test(text[at + name.length] ?? \"\")\n )\n )\n return true;\n return false;\n}\n\n/**\n * Whether an operation after `ALTER TYPE … ADD VALUE` in the same transaction\n * may read an added label, which PostgreSQL refuses until commit (55P04): a\n * default naming one, a cast of stored data into the enum, or a partial-index\n * predicate naming the type or a column of it. No literal spelling is\n * trusted: `$$archived$$`, `E'archived'` and a function result compare the\n * same.\n */\nfunction readsAddedValue(\n enumName: string,\n added: readonly string[],\n tables: readonly TableDef[],\n following: readonly DiffOperation[]\n): boolean {\n const defaultNamesAdded = (column: ColumnDef) => {\n const labels = enumDefaultLabels(column, enumName);\n return added.some((value) => labels.includes(value));\n };\n // The type and every name the batch gives a column of it, on any table.\n const names = new Set([enumName]);\n const addEnumColumns = (columns: readonly ColumnDef[]) => {\n for (const column of columns)\n if (storesEnum(column, enumName)) names.add(column.name);\n };\n for (const table of tables) addEnumColumns(table.columns);\n const predicateNamesEnum = ({ where }: IndexDef) =>\n where !== undefined && [...names].some((name) => mayName(where, name));\n for (const operation of following) {\n switch (operation.type) {\n case \"createTable\":\n addEnumColumns(operation.table.columns);\n if (\n operation.table.columns.some(defaultNamesAdded) ||\n operation.table.indexes.some(predicateNamesEnum)\n )\n return true;\n break;\n case \"addColumn\":\n if (defaultNamesAdded(operation.column)) return true;\n addEnumColumns([operation.column]);\n break;\n // A column already of the enum is known; one cast into it may hold a label.\n case \"alterColumn\":\n if (\n defaultNamesAdded(operation.to) ||\n (storesEnum(operation.to, enumName) &&\n !storesEnum(operation.from, enumName))\n )\n return true;\n break;\n case \"renameColumn\":\n if (names.has(operation.from)) names.add(operation.to);\n break;\n case \"createIndex\":\n if (predicateNamesEnum(operation.index)) return true;\n break;\n default:\n break;\n }\n }\n return false;\n}\n\nexport class PostgresMigrationDriver extends MigrationDriver {\n readonly dialect = \"postgresql\" as const;\n readonly driverName = \"postgresql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\", \"hash\", \"gin\", \"gist\"],\n supportsNativeArrays: true,\n supportsAddForeignKeyViaAlter: true,\n // `pg_constraint.conname` is the name the DDL gave the constraint.\n introspectionReadsConstraintNames: true,\n };\n\n // ===========================================================================\n // ESTATE QUALIFICATION\n // ===========================================================================\n\n /**\n * The schema this estate's persistent objects are named with, or undefined\n * on the REGISTERED singleton, which is bound to no estate.\n *\n * ONE source: the estate target. `this.namespace` holds the same string for\n * a PostgreSQL estate — `getMigrationDriver` reads both from the same\n * adapter, and the estate gate refuses a schema that is not this\n * one — so reading exactly one of them is what keeps the two from ever being\n * asked to disagree.\n *\n * `DDLContext.destination` does not enter: §3.4 binds GENERATED PostgreSQL\n * SQL to the configured schema for the same reason live SQL is bound, so an\n * artifact and a live statement in one estate name one schema. That is the\n * dialect difference from MySQL, whose artifacts stay database-relative.\n *\n * The dialect comparison is the union narrowing `MigrationTarget` requires\n * before `namespace` is readable at all, not a second check on top of the\n * registry's: a PostgreSQL implementation is only ever bound to a PostgreSQL\n * target.\n */\n private estateNamespace(): string | undefined {\n const target = this.target;\n return target?.dialect === \"postgresql\" ? target.namespace : undefined;\n }\n\n /**\n * The estate schema where a statement cannot be written without one.\n *\n * A catalog predicate and a schema-scoped inventory have no unqualified\n * reading: with no schema operand they answer for every schema in the\n * database, and any default answers for a schema nothing proved. DDL text is\n * the opposite case and renders unqualified off an unbound singleton (see\n * {@link qualify}).\n */\n private requireEstateNamespace(): string {\n const namespace = this.estateNamespace();\n if (namespace === undefined) {\n throw new MigrationError(\n \"This PostgreSQL migration driver is not bound to an estate, so it has no schema to read the catalog for. \" +\n \"Reach the driver through `getMigrationDriver(driver)`, which binds the adapter's namespace, instead of the registered singleton.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect } }\n );\n }\n return namespace;\n }\n\n /**\n * `\"schema\".\"object\"` — the one qualified spelling, through the one shared\n * primitive, with this driver's own quoter (§2.2, N11).\n *\n * An unbound singleton renders `\"object\"`: it is the dialect's renderer with\n * no estate behind it, and every shipped path reaches a bound view because\n * `getMigrationDriver` refuses a PostgreSQL adapter that declares no\n * namespace. Qualification is never composed by hand anywhere in this file.\n */\n private qualify(objectName: string): string {\n return renderQualifiedIdentifier(\n (name) => this.escapeIdentifier(name),\n this.estateNamespace(),\n objectName\n );\n }\n\n /**\n * The enum types this DDL batch may name as a column type.\n *\n * Membership is the ONLY thing that qualifies a column's type token, which is\n * what replaced the `_enum` suffix guess: an explicitly named enum such as\n * `state` is no less managed, and an arbitrary type token cannot prove enum\n * ownership. The set is the introspected schema's enums plus the enums the\n * operations already emitted in this batch have created — a table created\n * beside its own new enum must qualify that enum's name.\n *\n * A `dropEnum` earlier in the batch is deliberately not subtracted: a column\n * type naming a type this batch already dropped is a broken batch either way,\n * and the subtraction would silently UNqualify the very statements that run\n * before the drop.\n *\n * A createEnum introduces a name; alterEnum keeps an existing name from the\n * snapshot. Enum replacement runs before dependent columns, so its full\n * ordered value set and defaults are ready for those subsequent changes.\n */\n private managedEnumNames(context: DDLContext): ReadonlySet<string> {\n const names = new Set<string>();\n for (const enumDef of context.currentSchema?.enums ?? []) {\n names.add(enumDef.name);\n }\n for (const operation of context.precedingOperations ?? []) {\n if (operation.type === \"createEnum\") {\n names.add(operation.enumDef.name);\n }\n }\n return names;\n }\n\n /**\n * A column type token, qualified when it names a managed enum.\n *\n * Built-in types and the adapter-supported extension spellings (`vector(3)`,\n * `geometry(Point,4326)`) pass through untouched: they are provider objects\n * resolved through `search_path`, not estate objects, and prefixing every\n * type token would break them.\n */\n private renderTypeToken(type: string, context: DDLContext): string {\n const isArray = type.endsWith(\"[]\");\n const baseType = isArray ? type.slice(0, -2) : type;\n if (!this.managedEnumNames(context).has(baseType)) {\n return type;\n }\n const qualified = this.qualify(baseType);\n return isArray ? `${qualified}[]` : qualified;\n }\n\n /**\n * The extension-owned base types this driver's adapter declares, and whose\n * `format_type` spelling introspection therefore reads.\n */\n private admittedExtensionTypes(): ReadonlySet<string> {\n const capabilities = this.executionDriver?.adapter.capabilities;\n const admitted = new Set<string>();\n if (capabilities?.supportsVector) {\n for (const type of EXTENSION_TYPES_BY_CAPABILITY.supportsVector) {\n admitted.add(type);\n }\n }\n if (this.executionDriver?.adapter.geoPoint) {\n for (const type of EXTENSION_TYPES_BY_CAPABILITY.geoPoint) {\n admitted.add(type);\n }\n }\n return admitted;\n }\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Reads the estate's schema, and nothing else's.\n *\n * The namespace proof runs FIRST and here rather than at every caller: this\n * is the one inventory every catalog-driven path goes through (public\n * `introspect`, push including dry-run, and force-reset), and a configured\n * but absent schema must not be published as an empty database.\n */\n async introspect(executeRaw: RawExecutor): Promise<SchemaSnapshot> {\n await this.proveNamespaceExists(executeRaw);\n return await introspectPostgresSchema(executeRaw, {\n namespace: this.requireEstateNamespace(),\n tables: this.target?.tables,\n admittedExtensionTypes: this.admittedExtensionTypes(),\n });\n }\n\n override async preflightSchemaRequirements(\n snapshots: readonly SchemaSnapshot[],\n executeRaw: RawExecutor\n ): Promise<void> {\n try {\n const vectors = new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.flatMap((table) =>\n table.columns.flatMap(\n (column) =>\n VECTOR_TYPE_TOKEN.exec(column.type)?.[1]?.toLowerCase() ?? []\n )\n )\n )\n );\n if (\n vectors.size > 0 &&\n !this.executionDriver?.adapter.capabilities.supportsVector\n )\n throw new MigrationError(\n \"This migration requires pgvector support. Construct the PostgreSQL driver with pgvector: true and install the vector extension before applying it. VibORM never installs it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n if (\n snapshots.some(snapshotUsesGeoPoint) &&\n !this.executionDriver?.adapter.geoPoint\n ) {\n throw new MigrationError(\n \"This migration requires PostGIS GeoPoint support, but the bound PostgreSQL adapter has no GeoPoint protocol. Construct the driver with `postgis: true` and ensure PostGIS is installed before applying it.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n const desiredNames = [\n ...new Set(\n snapshots.flatMap((snapshot) =>\n snapshot.tables.map((table) => table.name)\n )\n ),\n ];\n if (desiredNames.length > 0) {\n const views = await executeRaw<{ name: string }>(\n `SELECT relation.relname AS name FROM pg_catalog.pg_class relation JOIN pg_catalog.pg_namespace namespace ON namespace.oid=relation.relnamespace WHERE namespace.nspname=$1 AND relation.relkind IN ('v','m') AND relation.relname=ANY($2::text[])`,\n [this.requireEstateNamespace(), arrayLiteralText(desiredNames)]\n );\n const collision = views.rows.find((row) =>\n desiredNames.includes(row.name)\n );\n if (collision)\n throw new MigrationError(\n `PostgreSQL relation \"${collision.name}\" is a view or materialized view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table: collision.name, feature: \"view\" } }\n );\n }\n if (vectors.size > 0) {\n const proof = await executeRaw<{ ready: boolean }>(\n `SELECT NOT EXISTS (SELECT 1 FROM unnest($1::text[]) AS required(name) WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_extension AS e JOIN pg_catalog.pg_depend AS d ON d.refobjid=e.oid AND d.refclassid='pg_catalog.pg_extension'::regclass AND d.deptype='e' JOIN pg_catalog.pg_type AS t ON t.oid=d.objid AND d.classid='pg_catalog.pg_type'::regclass WHERE e.extname='vector' AND t.typname=required.name AND pg_catalog.pg_type_is_visible(t.oid))) AS ready`,\n [arrayLiteralText([...vectors])]\n );\n if (proof.rows.length !== 1 || proof.rows[0]?.ready !== true)\n throw new MigrationError(\n \"pgvector preflight did not prove every required visible extension-owned vector type. Install the vector extension before migration effects; VibORM never installs it.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"vector\" } }\n );\n }\n if (snapshots.some((snapshot) => (snapshot.enums?.length ?? 0) > 0)) {\n const version = await executeRaw<{ version: string }>(\n \"SELECT current_setting('server_version_num') AS version\"\n );\n const number = Number(version.rows[0]?.version);\n if (!Number.isInteger(number) || number < 120_000)\n throw new MigrationError(\n \"PostgreSQL enum migrations require server_version_num >= 120000 for transactional enum safety\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n if (!snapshots.some(snapshotUsesGeoPoint)) return;\n let rows: readonly { ready?: unknown }[];\n try {\n rows = (await executeRaw<{ ready?: unknown }>(POSTGIS_PREFLIGHT_QUERY))\n .rows;\n } catch (failure) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight could not prove the required extension, types, and functions before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: { dialect: this.dialect, feature: \"GeoPoint\" },\n }\n );\n }\n if (rows.length !== 1 || rows[0]?.ready !== true) {\n throw new MigrationError(\n \"PostGIS GeoPoint preflight did not prove the required extension, visible types, and exact function signatures. VibORM never installs PostGIS.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, feature: \"GeoPoint\" } }\n );\n }\n } catch (failure) {\n if (failure instanceof MigrationError) throw failure;\n throw new MigrationError(\n \"PostgreSQL schema preflight could not prove the required catalog facts before migration effects.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause: errorCause(failure),\n meta: { dialect: this.dialect, feature: \"schema catalog\" },\n }\n );\n }\n }\n\n /**\n * PostgreSQL reports a missing schema as SQLSTATE `3F000` only where the\n * statement names one; a catalog read filtered on a schema name that does not\n * exist just returns nothing. This proof is what makes that silence\n * impossible, and it runs before any missing-tracking-table translation can\n * be consulted, because PostgreSQL reports a missing schema and a missing\n * relation alike as `42P01`.\n */\n override async proveNamespaceExists(executeRaw: RawExecutor): Promise<void> {\n const namespace = this.requireEstateNamespace();\n const { rows } = await executeRaw<{ present: number }>(\n NAMESPACE_EXISTS_QUERY,\n [namespace]\n );\n if (rows.length === 0) {\n // The schema is named in the message AND on the allowlist's `namespace`\n // key (`src/errors/diagnostics.ts`), so a caller can read which estate\n // was missing without parsing prose.\n throw new MigrationError(\n `The configured PostgreSQL schema \"${namespace}\" does not exist. ` +\n \"VibORM never creates or drops a schema: create it (or fix the configured `namespace`) before running migrations.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { dialect: this.dialect, driver: this.driverName, namespace } }\n );\n }\n }\n\n // PostgreSQL deparses an index predicate rather than storing the statement,\n // so the declared spelling and the introspected one never match on their own\n // (Decision 7.4). The other dialects have no such gap and leave this unset.\n override canonicalizeIndexPredicates(\n tableName: string,\n predicates: readonly string[],\n executeRaw: RawExecutor\n ): Promise<ReadonlyArray<string | undefined>> {\n return canonicalizeIndexPredicates(\n this.qualify(tableName),\n predicates,\n executeRaw\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 // An identifier column's type is the ONE storage owner's answer, override\n // included — which is also why the override is not read separately here: a\n // spelling this domain cannot live in was refused at the schema boundary,\n // and a text-family one keeps text storage with the domain still admitted.\n const idStorage =\n idDomain === undefined\n ? undefined\n : idStorageOf(idDomain, declaration, \"pg\");\n if (idStorage) return idStorage.columnType;\n\n // The declaration's PostgreSQL choice, if it makes one\n const nativeType = nativeTypeFor(declaration, \"pg\");\n if (nativeType) {\n return scalarState.array ? `${nativeType.type}[]` : nativeType.type;\n }\n\n // Use centralized type mapping\n return getPostgresType({\n type: scalarState.type,\n array: scalarState.array,\n withTimezone: scalarState.withTimezone,\n dimension: scalarState.dimension,\n decimal: scalarState.decimal,\n });\n }\n\n override finalizeTable(table: TableDef): TableDef {\n return {\n ...table,\n ...(table.primaryKey?.name\n ? {\n primaryKey: {\n ...table.primaryKey,\n name: derivedMigrationName(table.primaryKey.name),\n },\n }\n : {}),\n uniqueConstraints: table.uniqueConstraints.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n foreignKeys: table.foreignKeys.map((item) => ({\n ...item,\n name: derivedMigrationName(item.name),\n })),\n indexes: table.indexes.map((index) => ({\n ...index,\n name: derivedMigrationName(index.name),\n ...(index.type === \"spatial\" ? { type: \"gist\" as const } : {}),\n })),\n };\n }\n\n /**\n * The only generator PostgreSQL can run itself.\n *\n * `gen_random_uuid()` (PostgreSQL 13+) produces exactly what `.uuid()`\n * produces — but ONLY when no prefix is declared: a prefixed field's public\n * value is `prefix-payload`, and a column default that wrote the bare payload\n * would disagree with every row the application inserts. No other format has\n * a server-side equivalent: `uuidv7()` arrives in PostgreSQL 18, and ULID,\n * KSUID, NanoID and CUID2 have none at all, so those fields carry no DDL\n * default and the application's own generator remains their single owner.\n */\n override getDefaultExpression(\n scalar: Scalar,\n scalarState: ScalarState\n ): string | undefined {\n const literal =\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n !scalarState.decimal &&\n (scalarState.array ||\n scalarState.type === \"datetime\" ||\n scalarState.type === \"date\")\n ? this.literalDefaultValue(scalarState)\n : undefined;\n if (\n scalarState.hasDefault &&\n !scalarState.autoGenerate &&\n scalarState.array &&\n Array.isArray(literal)\n ) {\n if (scalarState.decimal)\n return super.getDefaultExpression(scalar, scalarState);\n const members = literal.map((value) =>\n scalarState.type === \"json\"\n ? stringifyJson(value)\n : (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n typeof value === \"string\"\n ? encodePostgresTemporal(value)\n : value\n );\n return this.escapeValue(arrayLiteralText(members));\n }\n // `gen_random_uuid()` produces a `uuid`, so a column that does not hold one\n // cannot take it as a default. A `.uuid()` field whose native type override\n // makes it `bytea` is exactly that column: the value would be a type error\n // at DDL time, and the application generator is already its single owner.\n if (scalarState.hasDefault && scalarState.default === null)\n return undefined;\n if (\n scalarState.type === \"datetime\" &&\n scalarState.autoGenerate?.kind === \"now\"\n ) {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n const clock =\n physical.includes(\"timestamptz\") || physical.includes(\"with time zone\")\n ? \"CURRENT_TIMESTAMP\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n // PostgreSQL's omitted precision is six. Our generated logical DateTime\n // must remain a millisecond value even when native storage is wider.\n const precision = Number(\n TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6\n );\n return precision > 3 ? `date_trunc('milliseconds', ${clock})` : clock;\n }\n if (\n (scalarState.type === \"datetime\" || scalarState.type === \"date\") &&\n scalarState.autoGenerate === undefined &&\n scalarState.hasDefault &&\n typeof literal === \"string\"\n )\n return this.escapeValue(encodePostgresTemporal(literal));\n if (scalarState.autoGenerate?.kind === \"now\") {\n if (scalarState.type === \"date\")\n return \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n if (scalarState.type === \"time\") {\n const physical = this.mapScalarType(scalar, scalarState).toLowerCase();\n if (Number(TEMPORAL_PRECISION_TOKEN.exec(physical)?.[1] ?? 6) > 3)\n return \"timezone('UTC', CURRENT_TIME(3))\";\n return physical.includes(\"timetz\") ||\n physical.includes(\"with time zone\")\n ? \"timezone('UTC', CURRENT_TIME)\"\n : \"(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')\";\n }\n }\n const idDomain = idDomainOfState(scalarState);\n if (\n idDomain !== undefined &&\n idStorageOf(idDomain, scalar[\"~\"].nativeType, \"pg\")?.representation ===\n \"bytes\"\n ) {\n return undefined;\n }\n return super.getDefaultExpression(scalar, scalarState);\n }\n\n protected override getAutoGenerateExpression(\n autoGenerate: import(\"@schema/scalars\").ScalarState[\"autoGenerate\"]\n ): string | undefined {\n switch (autoGenerate?.kind) {\n case \"uuid\":\n // `.id()`'s implicit ULID never reaches here (its kind is `ulid`), and\n // a NAMED `.uuid()` gets the database default only unprefixed.\n return hasIdPrefix(autoGenerate.prefix)\n ? undefined\n : \"gen_random_uuid()\";\n case \"now\":\n // Use database-level NOW() for consistent timestamps\n return \"NOW()\";\n default:\n return undefined;\n }\n }\n\n getEnumColumnType(\n tableName: string,\n columnName: string,\n _values: string[]\n ): string {\n return derivedMigrationName(`${tableName}_${columnName}_enum`);\n }\n\n // ===========================================================================\n // OVERRIDES: Column Definition Helpers\n // ===========================================================================\n\n /**\n * PostgreSQL integer types that support SERIAL auto-increment.\n */\n private static readonly SERIAL_TYPE_MAP: Record<string, string> = {\n integer: \"SERIAL\",\n int4: \"SERIAL\",\n int: \"SERIAL\",\n bigint: \"BIGSERIAL\",\n int8: \"BIGSERIAL\",\n smallint: \"SMALLSERIAL\",\n int2: \"SMALLSERIAL\",\n };\n\n /**\n * Formats the column type for PostgreSQL.\n * Handles SERIAL types for auto-increment and managed-enum qualification.\n */\n protected override formatColumnType(\n column: ColumnDef,\n context: DDLContext\n ): string {\n // Handle auto-increment with SERIAL types\n if (column.autoIncrement) {\n const normalizedType = column.type.toLowerCase();\n const serialType =\n PostgresMigrationDriver.SERIAL_TYPE_MAP[normalizedType];\n\n if (!serialType) {\n throw new MigrationError(\n \"PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n column: column.name,\n type: column.type,\n autoIncrement: true,\n },\n }\n );\n }\n\n return serialType;\n }\n\n // A managed enum is a persistent object of this estate and is qualified\n // exactly like a table; its array form takes the same prefix. Everything\n // else — built-ins and the adapter-supported extension spellings — is a\n // provider object and passes through.\n return this.renderTypeToken(column.type, context);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(op: CreateTableOperation, context: DDLContext): string {\n return this.compileCreateTable(op, context).join(\";\\n\");\n }\n\n override compileCreateTable(\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 if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const pkName = `CONSTRAINT ${this.escapeIdentifier(this.generatedPrimaryKeyName(table.name, table.primaryKey.name))} `;\n columnDefs.push(`${pkName}PRIMARY KEY (${pkCols})`);\n }\n\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 const sql = `CREATE TABLE ${this.qualify(table.name)} (\\n ${columnDefs.join(\",\\n \")}\\n)`;\n\n const statements = [sql];\n\n for (const idx of table.indexes) {\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 for (const fk of table.foreignKeys) {\n statements.push(\n this.generateAddForeignKey(\n {\n type: \"addForeignKey\",\n tableName: table.name,\n fk,\n },\n context\n )\n );\n }\n\n return this.filterStatements(statements);\n }\n\n /**\n * No `CASCADE` (§6.1). It dropped views, foreign keys and dependants in OTHER\n * schemas even though the enumeration behind this operation only ever\n * selected one, which made the namespace a filter instead of a boundary. The\n * foreign keys inside the program are materialized as explicit\n * `dropForeignKey` operations that sort ahead of every table drop\n * (`materializeDroppedTableForeignKeys`), and anything left is a dependency\n * this estate does not own: PostgreSQL's default `RESTRICT` then aborts the\n * transaction instead of deleting it.\n */\n generateDropTable(op: DropTableOperation, _context: DDLContext): string {\n return `DROP TABLE ${this.qualify(op.tableName)}`;\n }\n\n // `RENAME TO` takes ONE unqualified identifier: PostgreSQL renames the table\n // inside its own schema, and a qualified new name is a syntax error, not a\n // move (§4.1).\n generateRenameTable(op: RenameTableOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n override compileRenameTable(\n op: RenameTableOperation,\n context: DDLContext\n ): readonly string[] {\n const statements = [this.generateRenameTable(op, context)];\n const rename = this.defaultPrimaryKeyRename(\n op,\n this.schemaAtOperation(context)\n );\n if (rename) {\n statements.push(\n `ALTER TABLE ${this.qualify(op.to)} RENAME CONSTRAINT ${this.escapeIdentifier(rename.from)} TO ${this.escapeIdentifier(rename.to)}`\n );\n }\n return this.filterStatements(statements);\n }\n\n override projectNativeRename(\n snapshot: SchemaSnapshot,\n operation: NativeRenameOperation\n ): SchemaSnapshot {\n const projected = super.projectNativeRename(snapshot, operation);\n const rename =\n operation.type === \"renameTable\"\n ? this.defaultPrimaryKeyRename(operation, snapshot)\n : undefined;\n if (!rename) return projected;\n return {\n ...projected,\n tables: projected.tables.map((table) =>\n table.name === operation.to && table.primaryKey\n ? { ...table, primaryKey: { ...table.primaryKey, name: rename.to } }\n : table\n ),\n };\n }\n\n private defaultPrimaryKeyRename(\n operation: RenameTableOperation,\n snapshot: SchemaSnapshot | undefined\n ): { from: string; to: string } | undefined {\n const name = snapshot?.tables.find((table) => table.name === operation.from)\n ?.primaryKey?.name;\n return name === this.generatedPrimaryKeyName(operation.from)\n ? { from: name, to: this.generatedPrimaryKeyName(operation.to) }\n : undefined;\n }\n\n /** Generated keys have an explicit bounded name; catalog omissions stay unknown. */\n override generatedPrimaryKeyName(tableName: string, name?: string): string {\n return name || derivedMigrationName(`${tableName}_pkey`);\n }\n\n /** Native identity and PK effects needed by rename and enum DDL at this prefix. */\n private schemaAtOperation(context: DDLContext): SchemaSnapshot | undefined {\n let snapshot = context.currentSchema;\n if (!snapshot) return undefined;\n for (const operation of context.precedingOperations ?? []) {\n if (\n operation.type === \"renameTable\" ||\n operation.type === \"renameColumn\"\n ) {\n snapshot = this.projectNativeRename(snapshot, operation);\n } else if (operation.type === \"createTable\") {\n const table = operation.table;\n snapshot = {\n ...snapshot,\n tables: [\n ...snapshot.tables,\n table.primaryKey\n ? {\n ...table,\n primaryKey: {\n ...table.primaryKey,\n name: this.generatedPrimaryKeyName(\n table.name,\n table.primaryKey.name\n ),\n },\n }\n : table,\n ],\n };\n } else if (operation.type === \"dropTable\") {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== operation.tableName\n ),\n };\n } else if (\n operation.type === \"addPrimaryKey\" ||\n operation.type === \"dropPrimaryKey\"\n ) {\n snapshot = {\n ...snapshot,\n tables: snapshot.tables.map((table) =>\n table.name === operation.tableName\n ? {\n ...table,\n primaryKey:\n operation.type === \"addPrimaryKey\"\n ? {\n ...operation.primaryKey,\n name: this.generatedPrimaryKeyName(\n operation.tableName,\n operation.primaryKey.name\n ),\n }\n : undefined,\n }\n : table\n ),\n };\n }\n }\n return snapshot;\n }\n\n // ===========================================================================\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.qualify(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation, _context: DDLContext): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(\n op: RenameColumnOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(op: AlterColumnOperation, context: DDLContext): string {\n return this.compileAlterColumn(op, context).join(\";\\n\");\n }\n\n override compileAlterColumn(\n op: AlterColumnOperation,\n context: DDLContext\n ): readonly string[] {\n const { tableName, columnName, from, to } = op;\n const statements: string[] = [];\n const table = this.qualify(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // A decimal descriptor change is VALIDATED BEFORE the type moves, and the\n // proof stays live across it. `ALTER TYPE numeric(p,s) USING c::numeric(p,s)`\n // on its own ROUNDS a value with too many fractional digits — silently\n // rewriting stored data, which §7.3 forbids outright (\"No descriptor change\n // rounds existing data\"). The constraint refuses those rows instead, before\n // any DDL runs, and because it is only dropped afterwards no concurrent\n // write can land an unrepresentable value while the conversion is in\n // flight. The whole sequence is one transaction on PostgreSQL, so a\n // refusal takes the validation, the DDL and the metadata back together.\n //\n // The TARGET domain alone is the whole predicate — `c = c::numeric(p,s)`\n // says \"this value survives the conversion unchanged\" without consulting\n // where it came from. So an unconstrained `numeric` adopted by a declared\n // descriptor is validated exactly like a descriptor-to-descriptor change;\n // skipping it there was the one path on which the `USING` cast still\n // rounded.\n const conversion = decimalConversionRequired(from, to);\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n const constraint = this.escapeIdentifier(\n decimalConversionConstraintName(\n targetType.endsWith(\"[]\") ? \"list\" : \"scalar\",\n to.decimal\n )\n );\n // The migration owner's table lock, taken inside the transaction the\n // executor already opened (§7.4): it makes the validation and the type\n // change one lock acquisition rather than two, so nothing interleaves\n // between the row the constraint proved and the row the cast reads.\n statements.push(`LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE`);\n statements.push(\n `ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${postgresDecimalFitsCheck(col, targetType)})`\n );\n }\n\n if (from.type !== to.type) {\n if (from.default !== undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n }\n // The new type is a column type token like any other, so a managed enum\n // is qualified here too — in BOTH positions, since the `USING` cast names\n // the same type the column is being changed to.\n const newType = this.renderTypeToken(to.type, context);\n // text → uuid is the ONE identifier conversion a dialect performs on its\n // own, and the only one whose failure is per-row rather than structural.\n // The guard changes no outcome — the cast below refuses the same estate —\n // it replaces \"invalid input syntax for type uuid\" with the count and the\n // two routes, before the transaction is spent.\n if (isPostgresTextToUuid(from.type, newType)) {\n statements.push(postgresTextToUuidGuard(table, col));\n }\n const fromBase = from.type.endsWith(\"[]\")\n ? from.type.slice(0, -2)\n : from.type;\n const throughText = this.managedEnumNames(context).has(fromBase)\n ? `::text${from.type.endsWith(\"[]\") ? \"[]\" : \"\"}`\n : \"\";\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} TYPE ${newType} USING ${col}${throughText}::${newType}`\n );\n }\n\n if (from.nullable !== to.nullable) {\n if (to.nullable) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP NOT NULL`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET NOT NULL`\n );\n }\n }\n\n if (\n from.default !== to.default ||\n (from.type !== to.type && from.default !== undefined)\n ) {\n if (to.default === undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET DEFAULT ${to.default}`\n );\n }\n }\n\n if (conversion && to.decimal) {\n const targetType = this.renderTypeToken(to.type, context);\n statements.push(\n `ALTER TABLE ${table} DROP CONSTRAINT ${this.escapeIdentifier(decimalConversionConstraintName(targetType.endsWith(\"[]\") ? \"list\" : \"scalar\", to.decimal))}`\n );\n }\n\n return this.filterStatements(statements);\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation, _context: DDLContext): string {\n const { tableName, index } = op;\n const physicalType = index.type === \"spatial\" ? \"gist\" : index.type;\n\n // Validate index type against capabilities\n this.validateIndexType(physicalType, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const indexType = physicalType ? `USING ${physicalType} ` : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n // PostgreSQL does not allow a schema on the index name in CREATE INDEX —\n // the index is created in the target table's schema, which is why the\n // TABLE carries the qualification and the index name is one identifier.\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.qualify(tableName)} ${indexType}(${cols})${where}`;\n }\n\n // DROP INDEX names the index itself, which lives in a schema and takes one\n // (§4.1) — the mirror of CREATE INDEX above.\n generateDropIndex(op: DropIndexOperation, _context: DDLContext): string {\n return `DROP INDEX ${this.qualify(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n _context: DDLContext\n ): string {\n const { tableName, fk } = op;\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 const onDelete = fk.onDelete\n ? ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`\n : \"\";\n const onUpdate = fk.onUpdate\n ? ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`\n : \"\";\n // Both TABLE positions are qualified — the owner and the reference target.\n // A bare `REFERENCES` target resolves through `search_path` and would let\n // one estate's constraint point at another schema's table.\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${this.qualify(fk.referencedTable)} (${refCols})${onDelete}${onUpdate}`;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${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.qualify(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${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 const name = this.escapeIdentifier(\n this.generatedPrimaryKeyName(tableName, primaryKey.name)\n );\n return `ALTER TABLE ${this.qualify(tableName)} ADD CONSTRAINT ${name} PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n _context: DDLContext\n ): string {\n return `ALTER TABLE ${this.qualify(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n // An enum OPERATION names an ORM-managed enum by construction, so its type\n // name is qualified unconditionally — the managed-enum SET exists only to\n // decide whether a COLUMN's type token happens to name one.\n generateCreateEnum(op: CreateEnumOperation, _context: DDLContext): string {\n const { enumDef } = op;\n const values = enumDef.values.map((v) => this.escapeValue(v)).join(\", \");\n return `CREATE TYPE ${this.qualify(enumDef.name)} AS ENUM (${values})`;\n }\n\n generateDropEnum(op: DropEnumOperation, _context: DDLContext): string {\n return `DROP TYPE ${this.qualify(op.enumName)}`;\n }\n\n override generateClearMigrations(tableName: string): string {\n return `DELETE FROM ${this.qualify(tableName)}`;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(lockId: number): string | null {\n return `WITH RECURSIVE lock_attempt AS (\n SELECT pg_try_advisory_lock(${lockId}) AS acquired, clock_timestamp() + interval '10 seconds' AS deadline\n UNION ALL\n SELECT pg_try_advisory_lock(${lockId}), previous.deadline\n FROM lock_attempt previous\n CROSS JOIN LATERAL (SELECT pg_sleep(CASE WHEN previous.acquired THEN 0 ELSE 0.05 END)) waiting\n WHERE NOT previous.acquired AND clock_timestamp() < previous.deadline\n ) SELECT acquired FROM lock_attempt ORDER BY acquired DESC LIMIT 1`;\n }\n\n generateReleaseLock(lockId: number): string | null {\n return `SELECT pg_advisory_unlock(${lockId}) AS released`;\n }\n\n /** One bounded provider-side retry loop; only boolean true proves ownership. */\n override provesLockAcquired(rows: readonly unknown[]): boolean {\n const row = rows[0];\n return (\n rows.length === 1 &&\n typeof row === \"object\" &&\n row !== null &&\n Reflect.get(row, \"acquired\") === true\n );\n }\n\n /**\n * `pg_advisory_unlock` returns a real boolean: `true` when this session held\n * the lock and released it, `false` when it never held it. Only one boolean\n * `true` proves the release; `false`, a missing row, extra rows, or anything\n * that is not a boolean leaves the session holding a lock nobody will free.\n */\n override provesLockReleased(rows: readonly unknown[]): 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 return Reflect.get(row, \"released\") === true;\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n // Both inventories BIND the schema: they are the reads that decide what a\n // reset drops, and §4.2 admits no interpolated catalog operand.\n generateInventoryTables(): { sql: string; params: unknown[] } {\n return {\n sql: POSTGRES_MANAGED_TABLE_NAMES_QUERY,\n params: [this.requireEstateNamespace()],\n };\n }\n\n generateInventoryEnums(): { sql: string; params: unknown[] } | null {\n return {\n sql: `SELECT t.typname AS name\n FROM pg_type t\n JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n WHERE t.typtype = 'e' AND n.nspname = $1\n ORDER BY t.typname`,\n params: [this.requireEstateNamespace()],\n };\n }\n\n // No CASCADE on either drop (§6.1). PostgreSQL's default RESTRICT is the\n // containment boundary: a dependant this estate does not own aborts the\n // operation instead of being deleted with it.\n override generateDropTableSQL(tableName: string): string {\n return `DROP TABLE IF EXISTS ${this.qualify(tableName)}`;\n }\n\n override generateDropEnumSQL(enumName: string): string | null {\n return `DROP TYPE IF EXISTS ${this.qualify(enumName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateAlterEnum(op: AlterEnumOperation, _context: DDLContext): string {\n return this.compileAlterEnum(op, _context).join(\";\\n\");\n }\n\n override compileAlterEnum(\n op: AlterEnumOperation,\n context: DDLContext\n ): readonly string[] {\n const physicalContext = {\n ...context,\n currentSchema: this.schemaAtOperation(context),\n };\n const {\n enumName,\n addValues = [],\n removeValues,\n newValues,\n dependentColumns,\n } = op;\n const statements: string[] = [];\n const enumType = this.qualify(enumName);\n const before =\n physicalContext.currentSchema?.enums?.find(\n (item) => item.name === enumName\n )?.values ?? [];\n const reordered =\n newValues !== undefined &&\n before.filter((value) => newValues.includes(value)).join(\"\\0\") !==\n newValues.filter((value) => before.includes(value)).join(\"\\0\");\n // ADD VALUE only touches the catalog; a recreated type admits a later\n // read of an added value in the same transaction.\n const usesAddedValue = readsAddedValue(\n enumName,\n addValues,\n physicalContext.currentSchema?.tables ?? [],\n context.followingOperations ?? []\n );\n if (!(removeValues?.length || reordered || usesAddedValue)) {\n const available = new Set(before);\n for (const value of addValues) {\n const following = newValues\n ?.slice(newValues.indexOf(value) + 1)\n .find((candidate) => available.has(candidate));\n statements.push(\n `ALTER TYPE ${enumType} ADD VALUE ${this.escapeValue(value)}${following === undefined ? \"\" : ` BEFORE ${this.escapeValue(following)}`}`\n );\n available.add(value);\n }\n return this.filterStatements(statements);\n }\n if (!newValues?.length)\n throw new MigrationError(\n `Cannot alter enum \"${enumName}\" without its full destination values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n if (column?.default !== undefined)\n statements.push(`ALTER TABLE ${reference} DROP DEFAULT`);\n const carrier = column?.type.endsWith(\"[]\") ? \"text[]\" : \"text\";\n statements.push(\n `ALTER TABLE ${reference} TYPE ${carrier} USING ${this.escapeIdentifier(columnName)}::${carrier}`\n );\n }\n statements.push(...this.buildEnumReplacementUpdates(op, physicalContext));\n statements.push(`DROP TYPE ${enumType}`);\n statements.push(\n `CREATE TYPE ${enumType} AS ENUM (${newValues.map((value) => this.escapeValue(value)).join(\", \")})`\n );\n for (const { tableName, columnName } of dependentColumns ?? []) {\n const column = physicalContext.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((item) => item.name === columnName);\n const reference = `${this.qualify(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)}`;\n const target = column?.type.endsWith(\"[]\") ? `${enumType}[]` : enumType;\n statements.push(\n `ALTER TABLE ${reference} TYPE ${target} USING ${this.escapeIdentifier(columnName)}::${target}`\n );\n if (\n column?.default !== undefined &&\n !enumDefaultLabels(column, enumName).some(\n (label) => label !== null && removeValues?.includes(label)\n )\n )\n statements.push(\n `ALTER TABLE ${reference} SET DEFAULT ${column.default}`\n );\n }\n return this.filterStatements(statements);\n }\n\n /**\n * The data migration off removed enum values, with its table qualified.\n *\n * The shared base implementation names the table with one identifier, which\n * is right for a dialect whose statements are namespace-relative. These\n * UPDATEs run in the middle of an enum recreation on THIS estate's tables, so\n * PostgreSQL owns the statement rather than inheriting a spelling that\n * `search_path` resolves.\n */\n protected override buildEnumReplacementUpdates(\n op: AlterEnumOperation,\n context?: DDLContext\n ): string[] {\n const { removeValues, dependentColumns } = op;\n if (!(removeValues?.length && dependentColumns?.length)) {\n return [];\n }\n\n const statements: string[] = [];\n for (const { tableName, columnName } of dependentColumns) {\n const columnType = context?.currentSchema?.tables\n .find((table) => table.name === tableName)\n ?.columns.find((column) => column.name === columnName)?.type;\n if (columnType?.endsWith(\"[]\")) {\n const cases = removeValues.flatMap((value) => {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n value\n );\n return replacement === undefined\n ? []\n : [\n `WHEN ${this.escapeValue(value)} THEN ${replacement === null ? \"NULL\" : this.escapeValue(replacement)}`,\n ];\n });\n if (cases.length > 0) {\n const column = this.escapeIdentifier(columnName);\n statements.push(\n `UPDATE ${this.qualify(tableName)} SET ${column} = ARRAY(SELECT CASE value ${cases.join(\" \")} ELSE value END FROM unnest(${column}) WITH ORDINALITY AS member(value, position) ORDER BY position) WHERE ${column} IS NOT NULL`\n );\n }\n continue;\n }\n for (const removedValue of removeValues) {\n const replacement = this.getEnumValueReplacement(\n op,\n tableName,\n columnName,\n removedValue\n );\n if (replacement === undefined) {\n continue;\n }\n const newValue =\n replacement === null ? \"NULL\" : this.escapeValue(replacement);\n const column = this.escapeIdentifier(columnName);\n statements.push(\n `UPDATE ${this.qualify(tableName)} SET ${column} = ${newValue} WHERE ${column} = ${this.escapeValue(removedValue)}`\n );\n }\n }\n return statements;\n }\n}\n\n// Export singleton instance\nexport const postgresMigrationDriver = new PostgresMigrationDriver();\n","/**\n * Migration Driver Registry\n *\n * Central registry for migration drivers. Drivers are registered by their\n * driver name and can be looked up by driver name or dialect.\n */\n\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { resolveMigrationEstate, selectManagedSnapshot } from \"../target\";\nimport type { MigrationTarget } from \"../types\";\nimport type { MigrationDriver } from \"./base\";\nimport type { Dialect } from \"./types\";\n\nexport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"./base\";\n// Export base class and types\nexport { MigrationDriver } from \"./base\";\nexport type { Dialect, MigrationCapabilities } from \"./types\";\n\n// =============================================================================\n// REGISTRY\n// =============================================================================\n\n/**\n * Registry of migration drivers by driver name.\n */\nconst driverRegistry = new Map<string, MigrationDriver>();\n\n/**\n * Map of dialects to their default driver names.\n */\nconst dialectDefaults = new Map<Dialect, string>([\n [\"postgresql\", \"postgresql\"],\n [\"sqlite\", \"sqlite3\"],\n [\"mysql\", \"mysql\"],\n]);\n\n/**\n * Registers a migration driver.\n *\n * @param driver - The migration driver to register\n */\nexport function registerMigrationDriver(driver: MigrationDriver): void {\n driverRegistry.set(driver.driverName, driver);\n}\n\n/**\n * A migration driver bound to one estate.\n *\n * Binding narrows two of the base class's optional facts — the durable target\n * and the execution driver — to present ones, so an admitted live boundary\n * never has to ask whether its driver knows which estate it serves. The live\n * `namespace` stays optional: an unbound MySQL adapter binds to a real estate,\n * and refusing it for effectful work belongs to the admission owner.\n */\nexport interface BoundMigrationDriver extends MigrationDriver {\n readonly target: MigrationTarget;\n readonly executionDriver: AnyDriver;\n}\n\n/**\n * Looks up the dialect implementation and returns it BOUND to this driver's\n * estate.\n *\n * The registry stays the dialect implementation registry and its entries stay\n * stateless: binding never mutates a registered singleton and never parks an\n * active namespace in module-level state. The bound value is a frozen view\n * whose prototype is the registered instance, so two clients on two schemas\n * hold two immutable targets over one implementation.\n *\n * This is the ONE place a driver becomes a migration estate. Resolving the\n * estate here is what makes an unproven PostgreSQL adapter fail at lookup\n * rather than at some later statement.\n *\n * The durable target and the live namespace are BOTH taken from one\n * `resolveMigrationEstate` call, which reads `adapter.namespace` exactly once.\n * Binding must never read that fact a second time: an accessor-backed custom\n * adapter could answer differently, and the frozen view would then name one\n * estate in its target and render another in its DDL.\n *\n * @throws MigrationError if no implementation is registered, or if the estate\n * target cannot be proven\n */\nexport function getMigrationDriver(\n driver: AnyDriver,\n tables?: readonly string[]\n): BoundMigrationDriver {\n const { target: baseTarget, namespace } = resolveMigrationEstate(driver);\n const target =\n tables === undefined\n ? baseTarget\n : Object.freeze({ ...baseTarget, tables });\n const implementation = findMigrationDriver(driver.driverName, target.dialect);\n\n const bound: BoundMigrationDriver = Object.create(implementation);\n Object.defineProperties(bound, {\n target: { value: target, enumerable: true },\n executionDriver: { value: driver, enumerable: true },\n namespace: { value: namespace, enumerable: true },\n introspect: {\n async value(\n this: MigrationDriver,\n executeRaw: Parameters<MigrationDriver[\"introspect\"]>[0]\n ) {\n return selectManagedSnapshot(\n await implementation.introspect.call(this, executeRaw),\n target\n );\n },\n },\n });\n Object.freeze(bound);\n return bound;\n}\n\n/**\n * Resolves the registered implementation.\n *\n * Lookup order:\n * 1. Exact match by driver name\n * 2. Fallback to dialect default\n */\nfunction findMigrationDriver(\n driverName: string,\n dialect: Dialect\n): MigrationDriver {\n // Try exact driver name match\n let driver = driverRegistry.get(driverName);\n if (driver) return driver;\n\n // Try dialect default\n const defaultDriverName = dialectDefaults.get(dialect);\n if (defaultDriverName) {\n driver = driverRegistry.get(defaultDriverName);\n if (driver) return driver;\n }\n\n throw new MigrationError(\n `No migration driver registered for \"${driverName}\" (dialect: ${dialect}). ` +\n `Available drivers: ${[...driverRegistry.keys()].join(\", \") || \"none\"}`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED\n );\n}\n\n/**\n * Lists all registered migration drivers.\n */\nexport function listMigrationDrivers(): MigrationDriver[] {\n return [...driverRegistry.values()];\n}\n\n/**\n * Checks if a migration driver is registered.\n */\nexport function hasMigrationDriver(driverName: string): boolean {\n return driverRegistry.has(driverName);\n}\n\n// =============================================================================\n// AUTO-REGISTRATION\n// =============================================================================\n\n// Import and register built-in drivers\nimport { libsqlMigrationDriver } from \"./libsql\";\nimport { mysqlMigrationDriver } from \"./mysql\";\nimport { postgresMigrationDriver } from \"./postgres\";\nimport { sqlite3MigrationDriver } from \"./sqlite\";\n\nregisterMigrationDriver(postgresMigrationDriver);\nregisterMigrationDriver(sqlite3MigrationDriver);\nregisterMigrationDriver(libsqlMigrationDriver);\nregisterMigrationDriver(mysqlMigrationDriver);\n","import { selectManagedSnapshot } from \"./target\";\n/**\n * Model-to-SchemaSnapshot Serializer\n *\n * Converts VibORM model definitions into a database-agnostic SchemaSnapshot\n * that can be compared with the current database state.\n *\n * Database-specific logic is delegated to the MigrationDriver:\n * - Type mapping (mapScalarType)\n * - Default expressions (getDefaultExpression)\n * - Enum handling (capabilities.supportsNativeEnums, getEnumColumnType)\n */\n\nimport type { Dialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getModelKeyCatalog,\n getTableName as getModelTableName,\n isTotalIndex,\n type ModelState,\n} from \"../schema/model\";\nimport type { RelationSlot } from \"../schema/relation\";\nimport { automaticForeignKeyIndexName } from \"../schema/relation/helpers\";\nimport type { Scalar } from \"../schema/scalars/base\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport {\n describeDecimalProviderLimitRefusal,\n findDecimalProviderLimitRefusal,\n} from \"../schema/scalars/decimal/provider-limits\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n foreignKeyOnDelete,\n junctionOnDelete,\n type ResolvedRelationEdge,\n type ResolvedRelationIndex,\n type ResolvedVariantJunctionEdge,\n type ResolvedVariantJunctionMember,\n type ResolvedVariantRowEdge,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport type { MigrationDriver } from \"./drivers\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PolymorphicSnapshotStorage,\n PolymorphicToManySnapshotMember,\n PolymorphicToOneSnapshotMember,\n PolymorphicToOneStorageRegistryEntry,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\n\n// =============================================================================\n// REFERENTIAL ACTION MAPPING\n// =============================================================================\n\nfunction mapReferentialAction(\n action: \"cascade\" | \"setNull\" | \"restrict\" | \"noAction\" | undefined,\n fallback: ReferentialAction\n): ReferentialAction {\n switch (action) {\n case \"cascade\":\n return \"cascade\";\n case \"setNull\":\n return \"setNull\";\n case \"restrict\":\n return \"restrict\";\n case \"noAction\":\n return \"noAction\";\n default:\n return fallback;\n }\n}\n\n// =============================================================================\n// SERIALIZER\n// =============================================================================\n\nexport interface SerializeOptions {\n migrationDriver: MigrationDriver;\n}\n\n/** Translate the shared pure refusal into the migration boundary's error. */\nexport function assertMigrationDecimalDomainsFitProvider(\n models: Record<string, AnyModel>,\n dialect: Dialect\n): void {\n const refusal = findDecimalProviderLimitRefusal(models, dialect);\n if (refusal === undefined) return;\n throw new MigrationError(\n describeDecimalProviderLimitRefusal(refusal),\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n}\n\n/** One model's edges, bucketed at their anchors in declaration order. */\ninterface ModelEdges {\n readonly variants: ResolvedVariantEdgeRef[];\n readonly foreignKeys: ResolvedForeignKeyEdge[];\n}\n\ntype ResolvedVariantEdgeRef =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\ntype ResolvedForeignKeyEdge = Extract<\n ResolvedRelationEdge,\n { kind: \"foreignKey\" }\n>;\ntype ResolvedJunctionEdge = Extract<ResolvedRelationEdge, { kind: \"junction\" }>;\n\n/**\n * Stage the ONE derived edge iterator into the two emission buckets the\n * serializer already had (D4): per-model variant storage and foreign keys for\n * the model phase, and ordinary junctions for the phase that follows it.\n *\n * `resolvedEdges` yields each edge exactly once, at its canonical anchor, in\n * schema/model/field order — which is the order both phases already walked. No\n * topology is stored here and none is re-expanded (§11.5.9).\n */\nfunction stageEdges(index: ResolvedRelationIndex): {\n readonly byModel: ReadonlyMap<AnyModel, ModelEdges>;\n readonly junctions: readonly ResolvedJunctionEdge[];\n} {\n const byModel = new Map<AnyModel, ModelEdges>();\n const junctions: ResolvedJunctionEdge[] = [];\n const bucket = (model: AnyModel): ModelEdges => {\n const held = byModel.get(model);\n if (held) return held;\n const created: ModelEdges = { variants: [], foreignKeys: [] };\n byModel.set(model, created);\n return created;\n };\n for (const edge of resolvedEdges(index)) {\n if (edge.kind === \"junction\") {\n junctions.push(edge);\n continue;\n }\n if (edge.kind === \"foreignKey\") {\n bucket(edge.owner.source).foreignKeys.push(edge);\n continue;\n }\n bucket(edge.carrier.source).variants.push(edge);\n }\n return { byModel, junctions };\n}\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nfunction isSlot(one: RelationSlot, other: RelationSlot): boolean {\n return one.source === other.source && one.field === other.field;\n}\n\n/** The endpoint an ordinary edge reaches FROM the given one. */\nfunction partnerOf(\n edge: ResolvedForeignKeyEdge | ResolvedJunctionEdge,\n from: RelationSlot\n): RelationSlot {\n const [first, second] = edge.endpoints;\n return isSlot(first, from) ? second : first;\n}\n\n/**\n * Serializes a collection of VibORM models into a SchemaSnapshot\n */\nexport function serializeModels(\n models: Record<string, AnyModel>,\n options: SerializeOptions\n): SchemaSnapshot {\n hydrateSchemaNames(models);\n assertMigrationDecimalDomainsFitProvider(\n models,\n options.migrationDriver.dialect\n );\n return serializeResolvedModels(\n models,\n options.migrationDriver,\n resolveSchemaOrThrow(models)\n );\n}\n\n/** Internal composition seam for a boundary that already owns resolution. */\nexport function serializeResolvedModels(\n models: Record<string, AnyModel>,\n migrationDriver: MigrationDriver,\n index: ResolvedRelationIndex\n): SchemaSnapshot {\n const { byModel, junctions } = stageEdges(index);\n const tables: TableDef[] = [];\n const enums: EnumDef[] = [];\n const enumsSet = new Set<string>();\n const polymorphicStorage: PolymorphicSnapshotStorage[] = [];\n // One registry for EVERY junction-shaped table — polymorphic member\n // junctions (registered by the model loop below, model iteration order then\n // member declaration order) and ordinary many-to-many junctions (registered\n // by the walk that follows) — so the \"one table name, one definition\"\n // invariant covers both routes through the same map.\n const junctionTables = new Map<string, { def: TableDef; pairKey: string }>();\n\n for (const [modelName, model] of Object.entries(models)) {\n const modelState = model[\"~\"].state;\n const tableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n\n const columns: ColumnDef[] = [];\n const indexes: IndexDef[] = [];\n const foreignKeys: ForeignKeyDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const relationStorage: Record<\n string,\n PolymorphicToOneStorageRegistryEntry\n > = {};\n let primaryKey: PrimaryKeyDef | undefined;\n const pkColumns: string[] = [];\n\n // Process scalars\n for (const [fieldName, scalar] of Object.entries<Scalar>(\n modelState.scalars\n )) {\n const scalarState = scalar[\"~\"].state;\n // Use model's nameRegistry for column name resolution (supports field reuse)\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n\n // Handle enum types (only for databases that support native enums)\n let columnType: string;\n // The LIST representation is decided before enum identity is spelled. A\n // dialect with native arrays keeps both — `enumname[]` — while the others\n // store the list in the same container every other list uses, where an\n // element type has no expression at all: an inline `ENUM(...)` or a\n // `TEXT CHECK(col IN ...)` describes ONE member, so spelling it for a\n // list produces a column that refuses every value the field can hold.\n const spellsEnumColumn =\n scalarState.type === \"enum\" &&\n (scalarState.array !== true ||\n migrationDriver.capabilities.supportsNativeArrays);\n if (spellsEnumColumn) {\n const enumScalar = scalar as any;\n const enumValues = enumScalar.enumValues as string[] | undefined;\n\n if (migrationDriver.capabilities.supportsNativeEnums && enumValues) {\n // Use explicit enum name if provided, otherwise auto-generate\n const enumName =\n scalarState.enumName && migrationDriver.dialect === \"postgresql\"\n ? scalarState.enumName\n : migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues\n );\n\n const previousEnum = enums.find((item) => item.name === enumName);\n if (\n previousEnum &&\n JSON.stringify(previousEnum.values) !== JSON.stringify(enumValues)\n )\n throw new MigrationError(\n `Enum type \"${enumName}\" is declared with incompatible values`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n if (!enumsSet.has(enumName)) {\n enums.push({\n name: enumName,\n values: enumValues,\n });\n enumsSet.add(enumName);\n }\n columnType = scalarState.array ? `${enumName}[]` : enumName;\n } else {\n // Fall back to driver's default enum column type\n columnType = migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues || []\n );\n }\n } else {\n // A foreign key's identifier domain is DERIVED from the key it\n // references, so it is read against the model through the same\n // resolved index this serialization is already built from.\n columnType = migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, fieldName, index)\n );\n }\n\n const columnDef: ColumnDef = {\n name: columnName,\n type: columnType,\n nullable: scalarState.nullable,\n default: migrationDriver.getDefaultExpression(scalar, scalarState),\n autoIncrement: scalarState.autoGenerate?.kind === \"increment\",\n // Carried by REFERENCE off the resolved scalar, never rebuilt: the\n // frozen descriptor is the one source of truth, and the physical type\n // above is derived from it. On SQLite that type is `INTEGER` or `TEXT`\n // whatever the domain is, so without this the differ would see no\n // change when the domain moved.\n decimal: scalarState.decimal,\n geoPointEncoding:\n migrationDriver.dialect === \"sqlite\" && scalarState.type === \"point\"\n ? \"binary64\"\n : undefined,\n dateTime:\n migrationDriver.dialect === \"sqlite\" &&\n scalarState.type === \"datetime\" &&\n scalarState.array !== true\n ? sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType)\n : undefined,\n };\n\n columns.push(columnDef);\n\n // Track primary key columns\n if (scalarState.isId) {\n pkColumns.push(columnName);\n }\n\n // Handle unique constraints on individual fields\n if (scalarState.isUnique && !scalarState.isId) {\n uniqueConstraints.push({\n name: `${tableName}_${columnName}_key`,\n columns: [columnName],\n });\n }\n }\n\n // Handle compound primary key\n if (modelState.compoundId) {\n const firstKey = Object.keys(modelState.compoundId)[0];\n const compoundIdSchema = firstKey\n ? modelState.compoundId[firstKey]\n : undefined;\n if (compoundIdSchema?.entries) {\n pkColumns.push(\n ...Object.keys(compoundIdSchema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n )\n );\n }\n }\n\n // Set primary key\n if (pkColumns.length > 0) {\n primaryKey = {\n columns: pkColumns,\n name: `${tableName}_pkey`,\n };\n }\n\n // Handle compound unique constraints\n const compoundUniques: ModelState[\"compoundUniques\"] =\n modelState.compoundUniques;\n if (compoundUniques) {\n for (const [constraintName, schema] of Object.entries(compoundUniques)) {\n if (schema?.entries) {\n uniqueConstraints.push({\n name: `${tableName}_${constraintName}_key`,\n columns: Object.keys(schema.entries).map(\n (field) => model[\"~\"].getFieldName(field).sql\n ),\n });\n }\n }\n }\n\n // Process indexes from model state\n const declaredIndexColumns: string[][] = [];\n for (const indexDef of modelState.indexes) {\n const indexName =\n indexDef.options.name ||\n `${tableName}_${indexDef.fields.join(\"_\")}_idx`;\n // `.map()` renames the column, so the DDL has to name the column and not\n // the TypeScript field — the same resolution the compound uniques and the\n // FK columns already do. One resolution serves both readers: the CREATE\n // INDEX below, and the foreign-key index's coverage decision, which has\n // to compare the same names or it emits a duplicate index.\n const columns = indexDef.fields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const declared: IndexDef = {\n name: indexName,\n columns,\n unique: indexDef.options.unique ?? false,\n type: indexDef.options.type,\n where: indexDef.options.where,\n };\n indexes.push(declared);\n if (isTotalIndex(declared)) {\n declaredIndexColumns.push(columns);\n }\n }\n\n // Variant storage is relation-owned, so it never appears in the public\n // scalar map. The RESOLVED CARRIER EDGE is the single source for the\n // row-held private columns and index, the collection member junction\n // tables, and generated-file member history.\n const modelEdges = byModel.get(model) ?? { variants: [], foreignKeys: [] };\n for (const edge of modelEdges.variants) {\n if (edge.kind === \"variantJunctionCarrier\") {\n const members: PolymorphicToManySnapshotMember[] = [];\n for (const member of edge.members) {\n const memberDef = serializeMemberJunction(\n model,\n tableName,\n member,\n migrationDriver,\n index\n );\n // pairName is always set for a member junction: the resolved topology\n // is built exclusively by the gate, which passes\n // `${model}.${relation}.${publicType}` — already distinct from every\n // ordinary pairKey spelling.\n const pairKey = member.topology.pairName!;\n const existing = junctionTables.get(memberDef.name);\n if (\n existing &&\n (existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(memberDef))\n ) {\n throw new Error(\n `Junction table \"${memberDef.name}\" is shared by multiple distinct relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n if (!existing) {\n junctionTables.set(memberDef.name, { def: memberDef, pairKey });\n }\n\n const memberTarget = member.topology.target.model;\n const targetModelName = memberTarget[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n memberTarget,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n memberJunctionTable: member.topology.table,\n inverseCardinality: member.uniqueTarget ? \"one\" : \"many\",\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toMany\",\n members,\n });\n continue;\n }\n const storage = edge.storage;\n const typeScalarState = storage.typeColumn.scalar[\"~\"].state;\n const idScalarState = storage.idColumn.scalar[\"~\"].state;\n columns.push(\n {\n name: storage.typeColumn.name,\n type: migrationDriver.mapScalarType(\n storage.typeColumn.scalar,\n typeScalarState\n ),\n nullable: storage.typeColumn.nullable,\n },\n {\n name: storage.idColumn.name,\n // The carrier's id column holds every variant's KEY, and a key's\n // domain may be DERIVED, so the column names the key it stands in for\n // and that key is resolved against the index. Every variant agrees on\n // the answer or this storage does not exist (P002).\n type: migrationDriver.mapScalarType(\n storage.idColumn.scalar,\n idScalarState,\n storage.idColumn.reference === undefined\n ? undefined\n : idDomainOf(\n storage.idColumn.reference.model,\n storage.idColumn.reference.field,\n index\n )\n ),\n nullable: storage.idColumn.nullable,\n }\n );\n indexes.push({\n name: storage.indexName,\n columns: [storage.typeColumn.name, storage.idColumn.name],\n unique: edge.uniqueTarget,\n });\n // The physical facts stay in the TableDef above where the structural\n // differ owns them; the registry annotates which of those parts are\n // relation-owned, keyed by the storage ref the metadata entry carries.\n relationStorage[storage.typeColumn.name] = {\n kind: \"polymorphicToOne\",\n typeColumn: storage.typeColumn.name,\n idColumn: storage.idColumn.name,\n index: storage.indexName,\n };\n\n const members: PolymorphicToOneSnapshotMember[] = [];\n for (const member of edge.members) {\n const targetModelName = member.targetModel[\"~\"].names.ts;\n members.push({\n publicType: member.variant,\n storedType: member.entry.storedValue,\n targetTable: getModelTableName(\n member.targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n ),\n });\n }\n polymorphicStorage.push({\n ownerTable: tableName,\n relation: edge.carrier.field,\n kind: \"toOne\",\n storageRef: storage.typeColumn.name,\n members,\n });\n }\n\n // A UNIQUE foreign key gets a unique constraint at the bottom of the\n // relation loop, and that constraint is an index — so it covers the\n // foreign-key index exactly as a declared unique does. It is collected HERE,\n // before the loop, because `uniqueConstraints` grows INSIDE it: one model may\n // name the same columns from a plural and from a singular edge (legal, and\n // measured through `serializeModels`), and reading the half-built list made\n // the answer depend on which relation the schema happened to spell first —\n // `many` before `one` emitted the redundant index, `one` before `many` did\n // not. The condition mirrors the branch that pushes the constraint, so this\n // claims coverage only where the constraint follows.\n const oneToOneFkColumns: string[][] = [];\n for (const edge of modelEdges.foreignKeys) {\n if (!edge.unique) continue;\n oneToOneFkColumns.push(\n edge.reference.members.map(\n (member) => model[\"~\"].getFieldName(member.foreignField).sql\n )\n );\n }\n\n // Process foreign keys. ONE edge per stored reference, at its OWNER, in the\n // owner's declaration order — the gate decided which endpoint stores the\n // reference, so there is no family label to test and no inverse to discover.\n for (const edge of modelEdges.foreignKeys) {\n const targetSlot = partnerOf(edge, edge.owner);\n const targetModel = targetSlot.source;\n const targetModelState = targetModel[\"~\"].state;\n const targetTableName =\n targetModel[\"~\"].names.sql ||\n targetModelState.tableName ||\n edge.owner.field.toLowerCase();\n\n // Resolve TS field names to actual column names (.map() support)\n const fkFields = edge.reference.members.map(\n (member) => member.foreignField\n );\n const fkColumns = fkFields.map(\n (field) => model[\"~\"].getFieldName(field).sql\n );\n const referencedColumns = edge.reference.members.map(\n (member) => targetModel[\"~\"].getFieldName(member.referencedField).sql\n );\n\n // Prisma parity: without an explicit .onDelete(), a stored reference whose\n // every local member is nullable defaults to SET NULL and a required one to\n // RESTRICT, so deletes behave identically across databases (MySQL checks\n // self-referencing FKs row-by-row where PG/SQLite validate at statement\n // end). The rule has one owner, `foreignKeyOnDelete`, which the engine's\n // referential requirement reads too.\n foreignKeys.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_fkey`,\n columns: fkColumns,\n referencedTable: targetTableName,\n referencedColumns,\n onDelete: foreignKeyOnDelete(edge),\n onUpdate: mapReferentialAction(edge.reference.onUpdate, \"noAction\"),\n });\n\n // The inverse of a plural stored reference is to-many: every include,\n // relation filter and nested-write locate reads this table through the FK\n // columns. MySQL/InnoDB indexes an FK constraint by itself;\n // PostgreSQL and SQLite do not, so serialize the index on every\n // dialect — one snapshot shape for the differ, and on MySQL the\n // explicit index takes the place of the implicit one. A UNIQUE FK\n // needs nothing here: the unique constraint below is its index.\n if (edge.unique) {\n // 1:1 FK must be unique at the DB level, or it degrades to N:1\n const fkKey = [...fkColumns].sort().join(\",\");\n const alreadyUnique =\n [...pkColumns].sort().join(\",\") === fkKey ||\n uniqueConstraints.some(\n (u) => [...u.columns].sort().join(\",\") === fkKey\n ) ||\n indexes.some(\n (i) =>\n i.unique &&\n isTotalIndex(i) &&\n [...i.columns].sort().join(\",\") === fkKey\n );\n if (!alreadyUnique) {\n uniqueConstraints.push({\n name: `${tableName}_${fkColumns.join(\"_\")}_key`,\n columns: fkColumns,\n });\n }\n continue;\n }\n\n // The primary key, every unique constraint and every declared index\n // is backed by an index on all three dialects, and an index serves\n // any prefix of its columns — so a FK index over such a prefix\n // would only duplicate one the database already has.\n const coveringColumns = [\n pkColumns,\n ...uniqueConstraints.map((unique) => unique.columns),\n ...oneToOneFkColumns,\n ...declaredIndexColumns,\n ];\n const alreadyIndexed = coveringColumns.some((columns) =>\n fkColumns.every((column, position) => columns[position] === column)\n );\n if (alreadyIndexed) continue;\n // An index the schema declares over exactly these columns but\n // does not cover them — a partial index — auto-names itself the\n // way this one does, and a database keeps one index per name. So\n // the automatic index falls back on the name of the constraint it\n // serves. Only a schema that has no foreign-key index today can\n // take the fallback, so no database that already holds the index\n // is renamed into a drop and a create.\n //\n // A schema may of course have spent BOTH names on indexes of its\n // own — `.index([...], { name: \"<table>_<cols>_fkey_idx\" })` is\n // legal. Then this index has no name left to take, and pushing it\n // anyway put two entries under one name into the snapshot: the\n // differ emitted two `CREATE INDEX` and the second failed the\n // whole push (measured on better-sqlite3: `index\n // zz_fb_kid_ownerId_fkey_idx already exists`). The index is a read\n // optimization, not a correctness requirement, so it yields to the\n // names the schema declared.\n const name = automaticForeignKeyIndexName(\n tableName,\n fkColumns,\n new Set(indexes.map((index) => index.name))\n );\n if (name !== undefined) {\n indexes.push({ name, columns: fkColumns, unique: false });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n // Key omitted when empty so ordinary tables keep their exact shape.\n ...(Object.keys(relationStorage).length > 0 ? { relationStorage } : {}),\n });\n }\n\n // ==========================================================================\n // ORDINARY JUNCTION TABLES\n //\n // One edge per resolved pair, at `endpoints[0]` — the canonically first\n // endpoint, which is the very endpoint the old two-model walk registered from.\n // A member VIEW of a variant carrier never appears here: the gate resolved\n // that slot onto its carrier's edge, so the skip that used to rescan for a\n // compatible binding is now structural.\n // ==========================================================================\n for (const edge of junctions) {\n const sourceSlot = edge.endpoints[0];\n const model = sourceSlot.source;\n const modelName = model[\"~\"].names.ts;\n const sourceTableName =\n model[\"~\"].names.sql ||\n model[\"~\"].state.tableName ||\n (modelName ?? \"\").toLowerCase();\n const targetSlot = partnerOf(edge, sourceSlot);\n const targetModel = targetSlot.source;\n const targetModelName = targetModel[\"~\"].names.ts;\n if (!(modelName && targetModelName)) {\n throw new Error(\n `Target model for relation \"${sourceSlot.field}\" has no name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n const targetTableName = targetModel[\"~\"].names.sql;\n if (!targetTableName) {\n throw new Error(\n `Target model \"${targetModelName}\" has no SQL table name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n const sourcePkFields = getPrimaryKeyFieldDefs(\n model,\n migrationDriver,\n index\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n index\n );\n const topology = edge.topology;\n // Decorate the owner's members with the driver-typed key defs by index:\n // the members were zipped from these same row-key lists, so both sides\n // carry exactly one member per key def and the lookup cannot miss.\n const sourceMembers = topology.source.members.map((member, index) => ({\n column: member.junctionField,\n pk: sourcePkFields[index]!,\n }));\n const targetMembers = topology.target.members.map((member, index) => ({\n column: member.junctionField,\n pk: targetPkFields[index]!,\n }));\n\n // Canonical column order: sorted model names decide (as the generated\n // table name does), so both sides serialize the identical table. Each\n // side carries its own foreign key's actions, so the reorder below moves\n // an action with the table and columns it constrains. Prisma parity: an\n // action the owner left unstated is CASCADE, so deleting an endpoint row\n // removes its associations.\n const sourceSide = {\n members: sourceMembers,\n table: sourceTableName,\n sortKey: modelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.source),\n onUpdate: mapReferentialAction(topology.source.onUpdate, \"cascade\"),\n };\n const targetSide = {\n members: targetMembers,\n table: targetTableName,\n sortKey: targetModelName.toLowerCase(),\n onDelete: junctionOnDelete(topology.target),\n onUpdate: mapReferentialAction(topology.target.onUpdate, \"cascade\"),\n };\n let [first, second] = [sourceSide, targetSide];\n if (!topology.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map((member) => member.column);\n const secondColumns = second.members.map((member) => member.column);\n\n const junctionDef: TableDef = {\n name: topology.table,\n columns: [\n ...first.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ...second.members.map((member) => ({\n name: member.column,\n type: member.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers first-side lookups; reverse traversal needs one\n // index over the complete second-side stored reference.\n indexes: [\n {\n name: topology.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map((member) => member.pk.column),\n onDelete: first.onDelete,\n onUpdate: first.onUpdate,\n },\n {\n name: topology.foreignKeyName(\n topology.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map((member) => member.pk.column),\n onDelete: second.onDelete,\n onUpdate: second.onUpdate,\n },\n ],\n uniqueConstraints: [],\n };\n\n // Both sides of a pair serialize identically after canonicalization, so\n // a mismatch means two different relation pairs collide on one table.\n // Pair identity (models + relation name) catches collisions even when\n // the column defs happen to be byte-identical.\n const pairKey = `${[first.sortKey, second.sortKey].join(\"::\")}::${\n topology.pairName ?? \"\"\n }`;\n const existing = junctionTables.get(topology.table);\n if (existing) {\n if (\n existing.pairKey !== pairKey ||\n JSON.stringify(existing.def) !== JSON.stringify(junctionDef)\n ) {\n throw new Error(\n `Junction table \"${topology.table}\" is shared by multiple distinct many-to-many relation pairs. ` +\n \"Give each pair a distinct .name() or its own .through() table name.\"\n );\n }\n continue;\n }\n junctionTables.set(topology.table, { def: junctionDef, pairKey });\n }\n\n // Append junction tables to the tables array\n for (const { def } of junctionTables.values()) {\n tables.push(def);\n }\n\n const snapshot: SchemaSnapshot = {\n tables: tables.map((table) => migrationDriver.finalizeTable(table)),\n enums: enums.length > 0 ? enums : undefined,\n ...(polymorphicStorage.length > 0 ? { polymorphicStorage } : {}),\n };\n return migrationDriver.target\n ? selectManagedSnapshot(snapshot, migrationDriver.target, true)\n : snapshot;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/**\n * Serialize ONE polymorphic collection member's junction table, byte-reusing\n * the ordinary junction template: canonical orientation, driver types zipped\n * BY INDEX against the stored topology's sides, PK without a name, one\n * reverse index when uniqueness does not cover it, and two FIXED-cascade foreign keys —\n * `resolveJunctionPairActions` is NEVER called on this path (member actions\n * are cascade by design; a hostile referential-action spelling never reaches\n * this DDL). Consumes ONLY the stored `ResolvedJunctionTopology`: every\n * physical name comes from the topology's own methods, never reconstructed\n * from naming conventions.\n */\nfunction serializeMemberJunction(\n ownerModel: AnyModel,\n ownerTableName: string,\n member: ResolvedVariantJunctionMember,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): TableDef {\n const junction = member.topology;\n const targetModel = junction.target.model;\n const targetModelName = targetModel[\"~\"].names.ts;\n const targetTableName = getModelTableName(\n targetModel,\n targetModelName?.toLowerCase() ?? \"unknown\"\n );\n const sourcePkFields = getPrimaryKeyFieldDefs(\n ownerModel,\n migrationDriver,\n relations\n );\n const targetPkFields = getPrimaryKeyFieldDefs(\n targetModel,\n migrationDriver,\n relations\n );\n // Decorate the sides with the driver-typed key defs by index: the stored\n // topology zipped its members from the same model-key-catalog row keys these\n // defs come from, so both lists carry exactly one entry per key def.\n const sourceMembers = junction.source.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: sourcePkFields[index]!,\n })\n );\n const targetMembers = junction.target.members.map(\n (junctionMember, index) => ({\n column: junctionMember.junctionField,\n pk: targetPkFields[index]!,\n })\n );\n\n const sourceSide = { members: sourceMembers, table: ownerTableName };\n const targetSide = { members: targetMembers, table: targetTableName };\n let [first, second] = [sourceSide, targetSide];\n if (!junction.sourceIsFirst) {\n [first, second] = [second, first];\n }\n\n const firstColumns = first.members.map(\n (junctionMember) => junctionMember.column\n );\n const secondColumns = second.members.map(\n (junctionMember) => junctionMember.column\n );\n\n return {\n name: junction.table,\n columns: [\n ...first.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ...second.members.map((junctionMember) => ({\n name: junctionMember.column,\n type: junctionMember.pk.type,\n nullable: false,\n })),\n ],\n primaryKey: { columns: [...firstColumns, ...secondColumns] },\n // The PK covers the first side. A singular target on the second side has\n // its unique constraint already; otherwise reverse lookup needs an index.\n indexes:\n member.uniqueTarget && junction.sourceIsFirst\n ? []\n : [\n {\n name: junction.reverseIndexName(),\n columns: secondColumns,\n unique: false,\n },\n ],\n foreignKeys: [\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"source\" : \"target\"\n ),\n columns: firstColumns,\n referencedTable: first.table,\n referencedColumns: first.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n {\n name: junction.foreignKeyName(\n junction.sourceIsFirst ? \"target\" : \"source\"\n ),\n columns: secondColumns,\n referencedTable: second.table,\n referencedColumns: second.members.map(\n (junctionMember) => junctionMember.pk.column\n ),\n onDelete: \"cascade\",\n onUpdate: \"cascade\",\n },\n ],\n // The unique side is the complete ordered TARGET side, NOT the reverse\n // index flipped: when the target sorts canonical-first the reverse index\n // covers the OWNER side, and the PK prefix does not make target columns\n // unique. The name is asked LAST (idx → first fkey → second fkey → key)\n // so the other three refusal positions stay where they are.\n uniqueConstraints: member.uniqueTarget\n ? [\n {\n name: junction.uniqueTargetName(),\n columns: targetMembers.map(\n (junctionMember) => junctionMember.column\n ),\n },\n ]\n : [],\n };\n}\n\n/**\n * Get every primary-key member in model-key order.\n */\nfunction getPrimaryKeyFieldDefs(\n model: AnyModel,\n migrationDriver: MigrationDriver,\n relations: ResolvedRelationIndex\n): readonly { field: string; column: string; type: string }[] {\n const modelState = model[\"~\"].state;\n const modelName = model[\"~\"].names.ts;\n const rowKey = getModelKeyCatalog(model).rowKey?.fields;\n if (!rowKey || rowKey.length === 0) {\n throw new Error(\n `Model \"${modelName}\" has no primary key. Schema may not be hydrated.`\n );\n }\n return rowKey.map((field) => {\n const scalar = modelState.scalars[field];\n if (!scalar) {\n throw new Error(\n `Primary-key field '${field}' of model \"${modelName}\" is not a scalar.`\n );\n }\n const scalarState = scalar[\"~\"].state;\n return {\n field,\n column: model[\"~\"].getFieldName(field).sql,\n // A junction column holds the referenced primary KEY's values, and that\n // key's identifier domain may be DERIVED — the one-to-one child whose\n // primary key is its parent foreign key is the ordinary case — so it is\n // read against the model through the same resolved index every other\n // column of this serialization is typed from. Reading the scalar's own\n // declaration types the junction column as text beside the sixteen-byte\n // column it references, which PostgreSQL refuses to key at all.\n type: migrationDriver.mapScalarType(\n scalar,\n scalarState,\n idDomainOf(model, field, relations)\n ),\n };\n });\n}\n\nexport { getColumnName } from \"../schema/model\";\n\n/**\n * Gets the SQL table name for a model\n */\nexport function getTableName(model: AnyModel, modelName: string): string {\n return getModelTableName(model, modelName.toLowerCase());\n}\n","import type { AmbiguousChange, DiffOperation } from \"../types\";\n\n/**\n * Formats an operation for human-readable display.\n */\nexport function formatOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"createTable\":\n return `+ Create table \"${op.table.name}\" with ${op.table.columns.length} columns`;\n case \"dropTable\":\n return `- Drop table \"${op.tableName}\"`;\n case \"renameTable\":\n return `~ Rename table \"${op.from}\" → \"${op.to}\"`;\n case \"addColumn\":\n return `+ Add column \"${op.column.name}\" (${op.column.type}) to \"${op.tableName}\"`;\n case \"dropColumn\":\n return `- Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"renameColumn\":\n return `~ Rename column \"${op.from}\" → \"${op.to}\" in \"${op.tableName}\"`;\n case \"alterColumn\":\n return `~ Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n case \"createIndex\":\n return `+ Create index \"${op.index.name}\" on \"${op.tableName}\"`;\n case \"dropIndex\":\n return `- Drop index \"${op.indexName}\"`;\n case \"addForeignKey\":\n return `+ Add foreign key \"${op.fk.name}\" to \"${op.tableName}\"`;\n case \"dropForeignKey\":\n return `- Drop foreign key \"${op.fkName}\" from \"${op.tableName}\"`;\n case \"addUniqueConstraint\":\n return `+ Add unique constraint \"${op.constraint.name}\" to \"${op.tableName}\"`;\n case \"dropUniqueConstraint\":\n return `- Drop unique constraint \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"addPrimaryKey\":\n return `+ Add primary key to \"${op.tableName}\"`;\n case \"dropPrimaryKey\":\n return `- Drop primary key \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"createEnum\":\n return `+ Create enum \"${op.enumDef.name}\" with values [${op.enumDef.values.join(\", \")}]`;\n case \"dropEnum\":\n return `- Drop enum \"${op.enumName}\"`;\n case \"alterEnum\": {\n const parts: string[] = [];\n if (op.addValues?.length) parts.push(`add: ${op.addValues.join(\", \")}`);\n if (op.removeValues?.length) {\n parts.push(`remove: ${op.removeValues.join(\", \")}`);\n }\n return `~ Alter enum \"${op.enumName}\" (${parts.join(\"; \")})`;\n }\n default:\n return `Unknown operation: ${getOperationType(op)}`;\n }\n}\n\n/**\n * Formats all operations for human-readable display.\n */\nexport function formatOperations(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"No changes detected.\";\n }\n\n return operations.map(formatOperation).join(\"\\n\");\n}\n\nexport function formatDestructiveOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"dropTable\":\n return `[destructive] Drop table \"${op.tableName}\"`;\n case \"dropColumn\":\n return `[destructive] Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"addColumn\":\n return `[destructive] Add required column \"${op.tableName}.${op.column.name}\" without a backfill default`;\n case \"alterColumn\":\n return `[destructive] Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n default:\n return `[destructive] ${getOperationType(op)}`;\n }\n}\n\nexport function formatAmbiguousChangeDescription(\n change: AmbiguousChange\n): string {\n if (change.type === \"ambiguousColumn\") {\n return `[ambiguous] Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in \"${change.tableName}\"`;\n }\n return `[ambiguous] Table \"${change.droppedTable}\" → \"${change.addedTable}\"`;\n}\n\nfunction getOperationType(operation: { type: string }): string {\n return operation.type;\n}\n","import type { AnyDriver } from \"../../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { AnyModel } from \"../../schema/model\";\nimport type { ResolvedRelationIndex } from \"../../schema/validation/relation-resolution\";\nimport { admitLiveMigrationCapability } from \"../admission\";\nimport {\n type DiffOptions,\n diff,\n getDestructiveOperationDescriptions,\n type IndexPredicateCanonicalizer,\n isDestructiveOperation,\n} from \"../differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"../drivers\";\nimport { getMigrationDriver } from \"../drivers\";\nimport { emptyManagedSnapshot } from \"../empty-snapshot\";\nimport { applyNativeRename } from \"../native-rename\";\nimport {\n alwaysAddDropResolver,\n resolveAmbiguousChanges,\n validateResolveResult,\n} from \"../resolver\";\nimport { serializeResolvedModels } from \"../serializer\";\nimport { MANAGED_TABLES } from \"../target\";\nimport {\n type AmbiguousChange,\n type AmbiguousResolveChange,\n type ChangeResolution,\n createAmbiguousChange,\n createDestructiveChange,\n type DestructiveResolveChange,\n type DiffOperation,\n type DiffResult,\n type ResolveCallback,\n type Resolver,\n type SchemaSnapshot,\n} from \"../types\";\nimport { prepareSchemaProgram, sortOperations } from \"../utils\";\nimport {\n applyForceEnumResolutions,\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n type EnumRemoval,\n resolveEnumValueRemovalMappings,\n} from \"./enum-removals\";\nimport {\n formatAmbiguousChangeDescription,\n formatDestructiveOperation,\n} from \"./format\";\n\n/**\n * Minimal client interface required for migrations.\n * This allows push() to work with any object that has $driver and $schema.\n */\nexport interface MigrationClient {\n $driver: AnyDriver;\n $schema: Record<string, AnyModel>;\n readonly [MANAGED_TABLES]?: readonly string[];\n}\n\nexport interface PushOptions {\n /** Planner-only auto-resolution; public V1 push does not expose this key. */\n force?: boolean;\n /**\n * Skip schema validation before pushing. Validation catches definition\n * errors that would otherwise corrupt data silently (e.g. two relation\n * pairs sharing one junction table) — only skip it when deliberately\n * pushing a shape the validator flags.\n */\n skipValidation?: boolean;\n /** Preview SQL without executing */\n dryRun?: boolean;\n /**\n * Rebuild from the empty snapshot. Public V1 requires preview consent before\n * executing the resulting force-reset plan.\n */\n forceReset?: boolean;\n /**\n * Unified callback for resolving changes that require user input.\n * Called once per change, allowing granular control over each decision.\n *\n * Each change has methods for valid resolutions:\n * - Destructive: `change.proceed()`, `change.reject()`\n * - Ambiguous: `change.rename()`, `change.addAndDrop()`, `change.reject()`\n * - Enum value removal: `change.mapValues({...})`, `change.useNull()`, `change.reject()`\n *\n * **Combining with `force`:**\n * When both `resolve` and `force: true` are provided, the resolver takes precedence.\n * If the resolver returns `undefined` (doesn't handle a change), force mode kicks in:\n * - Destructive: auto-accepted\n * - Ambiguous: treated as add+drop\n * - Enum removal: set to NULL\n *\n * This allows patterns like \"accept everything except dropping table X\".\n *\n * @example\n * ```ts\n * // Protect specific tables while auto-accepting everything else\n * await migrations.push({\n * force: true,\n * resolve: async (change) => {\n * if (change.type === \"destructive\" && change.table === \"users\") {\n * return change.reject(); // Protect users table\n * }\n * // Return undefined to let force handle the rest\n * },\n * });\n * ```\n */\n resolve?: ResolveCallback;\n}\n\n// Push deliberately carries NO storage owner. Ordinary push and force-reset\n// synchronize the live namespace and nothing else: they read no journal, write\n// no journal or snapshot, and cannot rewrite an estate's history as a side\n// effect of a schema sync.\n\nexport interface PushPlan {\n operations: DiffOperation[];\n currentSchema: SchemaSnapshot;\n}\n\nexport function getPushMigrationDriver(\n client: MigrationClient\n): BoundMigrationDriver {\n return getMigrationDriver(client.$driver, client[MANAGED_TABLES]);\n}\n\n/**\n * Introspects the current database schema without making any changes.\n * Useful for debugging or displaying current state.\n *\n * It changes nothing, but it READS live state, so it is a live migration\n * command and takes the one shared admission owner like every other one —\n * before any provider work. Without this gate an unbound MySQL client would\n * publish an inventory of whatever database its connection happened to default\n * to, which is exactly the ambient-default target §3.3 refuses to accept.\n * `push({ dryRun: true })` performs the same introspection behind the same\n * `read-only` admission; this entry point must not be the way around it.\n */\nexport async function introspect(\n client: MigrationClient\n): Promise<SchemaSnapshot> {\n const migrationDriver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(migrationDriver, \"read-only\", \"introspect()\");\n return introspectSchema(client.$driver, migrationDriver);\n}\n\nexport async function introspectSchema(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return migrationDriver.introspect((sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\n/**\n * Hands the differ a way to ask the database for its own spelling of a declared\n * partial-index predicate (Decision 7.4). Returns undefined when nobody can\n * answer, and the differ then compares the two texts raw — the reading that\n * plans a drop and a create, which is the safe direction.\n *\n * The whole canonicalization runs inside ONE transaction, for two reasons that\n * both matter: it pins a single connection (the scratch objects it needs are\n * session-local, and a pool hands out a different connection per statement),\n * and a failure anywhere rolls the scratch away instead of leaving it attached\n * to a table this push may be about to drop.\n */\nfunction buildIndexPredicateCanonicalizer(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = migrationDriver.canonicalizeIndexPredicates;\n if (!(canonicalize && driver.supportsTransactions)) return;\n\n return async (tableName, predicates) => {\n try {\n return await driver.withTransaction((tx) =>\n canonicalize.call(\n migrationDriver,\n tableName,\n predicates,\n (sql, params) => tx._executeRaw(sql, params)\n )\n );\n } catch {\n // Fail closed, and stay out of the way. A predicate the database cannot\n // parse, a connection that refused, a dialect that changed under us —\n // none of it may make a push fail, and none of it may be read as \"these\n // two predicates are the same\". Answering nothing leaves the differ with\n // the raw texts, which is exactly the pre-7.4 behavior.\n return predicates.map(() => undefined);\n }\n };\n}\n\n/**\n * The COMPLETE empty-to-desired program, compiled before a force-reset entry.\n *\n * §6.2: \"Before entry, serialize and validate the desired schema, resolve its\n * relation index, compile the empty-to-desired DDL, and prove that program\n * contains no commit-boundary statement.\" Diffing against the LIVE database\n * would describe a program for a database this command is about to empty, so\n * the baseline is the empty snapshot — the state the clear produces.\n *\n * Nothing here reads live state, so it runs before the clear and its result is\n * what the one locked transaction executes.\n */\nexport async function planRebuildFromEmpty(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n const current = emptyManagedSnapshot();\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\nexport async function planPush(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n // Live introspection sees the private columns and index, but a text\n // discriminator cannot reveal historical public/stored member mappings.\n // Push therefore compares structure only. Stored-value history is owned by\n // file-based generate(), where both serialized snapshots are available.\n const current = await introspectSchema(client.$driver, migrationDriver);\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n canonicalizeIndexPredicate: buildIndexPredicateCanonicalizer(\n client.$driver,\n migrationDriver\n ),\n // `current` was just introspected. Where that introspection cannot read a\n // constraint's name back, the name it carries is a synthesis and matching\n // on it would make every unchanged constraint read as a change.\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\nasync function resolvePushOperations(\n diffResult: DiffResult,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n options: PushOptions,\n diffOptions: DiffOptions\n): Promise<DiffOperation[]> {\n const force = options.force ?? false;\n const allEnumRemovals = detectEnumValueRemovals(\n diffResult.operations,\n current\n );\n\n if (options.resolve) {\n return resolveWithCallback(\n diffResult,\n current,\n desired,\n diffOptions,\n allEnumRemovals,\n options.resolve,\n force\n );\n }\n\n if (force) {\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n alwaysAddDropResolver,\n diffOptions\n );\n return applyForceEnumResolutions(resolvedOperations, allEnumRemovals);\n }\n\n rejectUnresolvedChanges(diffResult, allEnumRemovals);\n return [...diffResult.operations];\n}\n\nasync function resolveWithCallback(\n diffResult: DiffResult,\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n diffOptions: DiffOptions,\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force = false\n): Promise<DiffOperation[]> {\n const admittedAmbiguousDrops = new Set<string>();\n const ambiguityResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = validateResolveResult(\n \"ambiguous\",\n resolveChange,\n await resolve(resolveChange)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${resolveChange.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined) {\n if (force) {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n continue;\n }\n const advice =\n change.type === \"ambiguousTable\"\n ? `If \"${change.droppedTable}\" is not this schema's table, set migrations.tables so push does not manage it; otherwise name the pair with change.rename() or change.addAndDrop().`\n : \"Return change.rename() or change.addAndDrop() from the resolver.\";\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n${advice}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n resolutions.set(change, {\n type: result === \"rename\" ? \"rename\" : \"addAndDrop\",\n });\n if (result !== \"rename\") {\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n }\n }\n return resolutions;\n };\n\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n ambiguityResolver,\n diffOptions\n );\n const resolvedEnumRemovals = retargetEnumRemovals(\n enumRemovals,\n current,\n resolvedOperations,\n diffOptions.projectRename\n );\n const finalOperations = await resolveDestructiveOperations(\n resolvedOperations.filter((op) => op.type !== \"alterEnum\"),\n resolve,\n force,\n admittedAmbiguousDrops\n );\n const enumColumnMappings = await resolveEnumValueRemovalMappings(\n resolvedEnumRemovals,\n resolve,\n force\n );\n\n finalOperations.push(\n ...applyResolvedEnumMappings(resolvedOperations, enumColumnMappings)\n );\n\n return sortOperations(finalOperations);\n}\n\nfunction retargetEnumRemovals(\n removals: EnumRemoval[],\n current: SchemaSnapshot,\n operations: DiffOperation[],\n projectRename: typeof applyNativeRename = applyNativeRename\n): EnumRemoval[] {\n let renamedCurrent = current;\n for (const operation of operations) {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n renamedCurrent = projectRename(renamedCurrent, operation);\n }\n }\n\n return removals.map((removal) => {\n const tablePosition = current.tables.findIndex(\n (table) => table.name === removal.tableName\n );\n const currentTable = current.tables[tablePosition];\n const columnPosition = currentTable?.columns.findIndex(\n (column) => column.name === removal.columnName\n );\n const table = renamedCurrent.tables[tablePosition];\n const column =\n columnPosition === undefined ? undefined : table?.columns[columnPosition];\n if (!(currentTable && table && column)) {\n throw new MigrationError(\n `Cannot retarget enum removal for \"${removal.tableName}.${removal.columnName}\" through the accepted renames.`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return { ...removal, tableName: table.name, columnName: column.name };\n });\n}\n\nasync function resolveDestructiveOperations(\n operations: DiffOperation[],\n resolve: ResolveCallback,\n force: boolean,\n admittedDrops: ReadonlySet<string> = new Set()\n): Promise<DiffOperation[]> {\n const admitted: DiffOperation[] = [];\n for (const op of operations) {\n if (\n !isDestructiveOperation(op) ||\n admittedDrops.has(destructiveDropKey(op))\n ) {\n admitted.push(op);\n continue;\n }\n\n const change = operationToResolveChange(op);\n const result = validateResolveResult(\n \"destructive\",\n change,\n await resolve(change)\n );\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined) {\n if (force) {\n admitted.push(op);\n } else {\n throw new MigrationError(\n `Unresolved destructive change: ${change.description}\\n` +\n \"Return change.proceed() or change.reject() from the resolver.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n if (result === \"proceed\") {\n admitted.push(op);\n }\n }\n return admitted;\n}\n\nfunction ambiguousDropKey(change: AmbiguousChange): string {\n return change.type === \"ambiguousTable\"\n ? `table\\u0000${change.droppedTable}`\n : `column\\u0000${change.tableName}\\u0000${change.droppedColumn.name}`;\n}\n\nfunction destructiveDropKey(operation: DiffOperation): string {\n if (operation.type === \"dropTable\") {\n return `table\\u0000${operation.tableName}`;\n }\n if (operation.type === \"dropColumn\") {\n return `column\\u0000${operation.tableName}\\u0000${operation.columnName}`;\n }\n return \"\";\n}\n\nfunction rejectUnresolvedChanges(\n diffResult: {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n },\n enumRemovalsNeedingResolution: EnumRemoval[]\n): void {\n const destructiveOps = diffResult.operations.filter(isDestructiveOperation);\n const hasAmbiguous = diffResult.ambiguousChanges.length > 0;\n\n if (\n destructiveOps.length === 0 &&\n !hasAmbiguous &&\n enumRemovalsNeedingResolution.length === 0\n ) {\n return;\n }\n\n const descriptions: string[] = [];\n\n for (const op of destructiveOps) {\n descriptions.push(formatDestructiveOperation(op));\n }\n\n for (const change of diffResult.ambiguousChanges) {\n descriptions.push(formatAmbiguousChangeDescription(change));\n }\n\n for (const removal of enumRemovalsNeedingResolution) {\n descriptions.push(\n `[enumValueRemoval] \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - removing values: ${removal.removedValues.join(\", \")} (non-nullable)`\n );\n }\n\n throw new MigrationError(\n `Changes requiring resolution detected:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Provide a resolve callback to choose each change explicitly.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n}\n\nfunction operationToResolveChange(op: DiffOperation): DestructiveResolveChange {\n switch (op.type) {\n case \"dropTable\":\n return createDestructiveChange({\n operation: \"dropTable\",\n table: op.tableName,\n description: `Drop table \"${op.tableName}\" (all data will be lost)`,\n });\n case \"dropColumn\":\n return createDestructiveChange({\n operation: \"dropColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`,\n });\n case \"addColumn\":\n return createDestructiveChange({\n operation: \"addColumn\",\n table: op.tableName,\n column: op.column.name,\n description: `Add required column \"${op.tableName}.${op.column.name}\" without a backfill default (fails on populated tables)`,\n });\n case \"alterColumn\":\n return createDestructiveChange({\n operation: \"alterColumn\",\n table: op.tableName,\n column: op.columnName,\n // The SAME sentences the differ already writes for this operation, and\n // not a second summary of it. Rendering `from.type → to.type` here was\n // silent about the one change whose type does not move: a narrowing\n // decimal domain on SQLite reads `(INTEGER → INTEGER)`, so the user was\n // asked to accept a data-refusing change with nothing on screen to say\n // what it was. Every destructive alterColumn produces at least one\n // description, because the differ's description and classifier share\n // the same owner and ask the same three questions.\n description: getDestructiveOperationDescriptions([op]).join(\"; \"),\n });\n default:\n throw new MigrationError(\n `Unexpected operation type: ${op.type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n}\n\nfunction ambiguousToResolveChange(\n change: AmbiguousChange\n): AmbiguousResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n","/**\n * The ONE live-namespace reset owner (§6.2).\n *\n * Three programs used to invent reset SQL: the CLI's own dynamic loop, the\n * dialect drivers' `generateResetSQL()`, and `push({ forceReset: true })`. They\n * disagreed — MySQL's dialect answer dropped nothing at all, and PostgreSQL's\n * enumerated `public` regardless of the estate — so this module replaces all\n * three. Migration `reset()` and force-reset push own different truths about\n * the tracking table, and that difference is a PARAMETER, never an inference\n * from whether a storage driver happens to exist.\n *\n * Containment is the point: the inventory is a bound catalog read scoped to the\n * configured namespace, foreign keys inside it are dropped explicitly rather\n * than cascaded away, and nothing here issues `DROP SCHEMA`, `DROP DATABASE`,\n * or `FOREIGN_KEY_CHECKS = 0`.\n *\n * The owner is TWO calls, and the seam between them is the first effect:\n * {@link planLiveNamespaceReset} decides and renders the whole clear from\n * catalog reads, and {@link executeLiveNamespaceReset} runs it. Every refusal\n * lives in the first, so no caller's commit-model reporter can restate a\n * containment refusal as a failure part-way through a program that never began.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { errorCause } from \"../drivers/shared/driver-options\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { childrenBeforeParents, type TableReference } from \"./drop-order\";\nimport { introspectSchema } from \"./push/planner\";\nimport type { ForeignKeyDef, SchemaSnapshot } from \"./types\";\nimport { createQueryExecutor } from \"./utils\";\n\n/**\n * What this reset does with the declared tracking table.\n *\n * - `preserve` — migration `reset()`: the table's STRUCTURE survives and only\n * its rows are cleared, because the same command is about to replay the\n * estate and restore them.\n * - `drop` — force-reset push: the table is an ordinary managed object of the\n * selected namespace and goes with the rest. Push never reads or writes\n * estate history, so it makes no history claim about the rows it removes.\n */\nexport type TrackingTablePolicy = \"preserve\" | \"drop\";\n\nexport interface LiveNamespaceResetPolicy {\n readonly trackingTable: TrackingTablePolicy;\n /**\n * The already-normalized tracking-table name.\n *\n * A primitive, deliberately: the routine must not have to guess which\n * inventoried table is special, and it must not be handed migration storage\n * to find out. A custom-named table this command did not declare is an\n * ordinary table here and receives no tracking-history claim.\n */\n readonly trackingTableName: string;\n /** Additional tables whose structure must survive the clear. */\n readonly preserveTables?: readonly string[];\n}\n\nexport interface LiveNamespaceResetResult {\n /** Table names dropped, in the order they were dropped. */\n readonly dropped: string[];\n}\n\n/** One table this reset drops, and the statement that drops it. */\ninterface PlannedTableDrop {\n readonly name: string;\n readonly sql: string;\n}\n\n/**\n * The COMPLETE clear, decided and rendered — and nothing executed.\n *\n * The split is the point (§6.2). Everything that can REFUSE the clear —\n * proving the namespace, reading the inventory, both containment refusals, the\n * drop order — is answered from catalog reads, so it belongs before the caller\n * enters a commit model at all. A refusal that has already been wrapped in\n * MySQL's partial-commit reporter tells the caller a database nothing touched\n * \"failed partway through\", and loses the metadata naming the constraint that\n * made it refuse.\n */\nexport interface LiveNamespaceResetPlan {\n /**\n * Every table in the configured namespace, as the inventory read them.\n *\n * The MEMBERSHIP answer, which is not the same as {@link dropTables}: a\n * `preserve` policy keeps the tracking table, and the dry-run preview reports\n * the estate it inspected.\n */\n readonly tables: string[];\n /** The tracking-row clear, or `null` when this estate holds no such table. */\n readonly clearTracking: string | null;\n /** Every foreign key the estate owns, as an explicit drop. */\n readonly dropForeignKeys: string[];\n /** The tables this policy drops, in the order they will be dropped. */\n readonly dropTables: readonly PlannedTableDrop[];\n /** Managed enum drops, which run after the tables that use them. */\n readonly dropEnums: string[];\n}\n\nexport interface LiveNamespaceInventory {\n /** The estate's dependency graph, as the catalog describes it. */\n readonly snapshot: SchemaSnapshot;\n /** Every table in the configured namespace. */\n readonly tables: string[];\n /** Every managed enum type, on dialects that have them. */\n readonly enums: string[];\n}\n\n/**\n * Proves the configured namespace and reads what a reset would touch.\n *\n * ONE owner for both consumers — the effectful reset and the dry run that\n * previews it — because a preview computed a different way is not a preview.\n * `introspect` is what proves the namespace exists before anything is\n * published, and it refuses a foreign key with exactly one side inside the\n * estate, so a cross-namespace dependency is refused BEFORE the first DDL\n * rather than discovered after half the estate is gone.\n *\n * The snapshot describes the GRAPH; the bound catalog read decides MEMBERSHIP,\n * because a table the snapshot cannot model is still a table in this namespace\n * and a reset that skipped it would leave the estate half-cleared. For the same\n * reason the membership read is the one provider result this owner refuses to\n * treat as advisory: see {@link readNames}.\n */\nexport async function inventoryLiveNamespace(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceInventory> {\n const snapshot = await introspectSchema(driver, migrationDriver);\n\n const executor = createQueryExecutor(driver);\n const inventory = migrationDriver.generateInventoryTables();\n const tables = readNames(\n await executor(inventory.sql, inventory.params),\n \"table\"\n ).filter(\n (name) =>\n migrationDriver.target.tables === undefined ||\n migrationDriver.target.tables.includes(name)\n );\n\n const enumInventory = migrationDriver.generateInventoryEnums();\n const enums = enumInventory\n ? readNames(\n await executor(enumInventory.sql, enumInventory.params),\n \"managed enum\"\n )\n : [];\n\n return {\n snapshot,\n tables,\n enums:\n migrationDriver.target.tables === undefined\n ? enums\n : enums.filter((name) =>\n snapshot.enums?.some((item) => item.name === name)\n ),\n };\n}\n\n/**\n * Decides and renders the COMPLETE clear, without executing any of it.\n *\n * Namespace proof, inventory, both containment refusals, foreign-key\n * materialization and drop order all happen here, so every way this clear can\n * refuse is answered from catalog reads alone — before the caller enters a\n * transaction or a sequential program, and therefore before anything can\n * describe a refusal as a partial commit (§6.2). It is also what lets a dry run\n * preview the effectful path rather than a second computation of it.\n *\n * @param driver - the producer to read the catalog on; the caller has already\n * pinned and locked it where its dialect has a lock to take\n * @param migrationDriver - the estate-bound migration driver\n * @param policy - the tracking-table truth this caller owns\n */\nexport async function planLiveNamespaceReset(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver,\n policy: LiveNamespaceResetPolicy\n): Promise<LiveNamespaceResetPlan> {\n const { snapshot, tables, enums } = await inventoryLiveNamespace(\n driver,\n migrationDriver\n );\n\n // MySQL is the one dialect whose DDL commits as it runs, and it cannot make\n // the tracking clear and the destructive DDL one transaction — so an inbound\n // foreign key to the declared tracking table has no safe order: dropping that\n // key first opens a window where the history rows are still there and their\n // schema is going away, and clearing or dropping the referenced table first\n // can simply be blocked.\n if (migrationDriver.target.dialect === \"mysql\") {\n assertNoInboundTrackingReference(snapshot, policy.trackingTableName);\n }\n\n // Drop every foreign key the estate owns, explicitly, before any table\n // drop. This is what replaces `CASCADE` and `FOREIGN_KEY_CHECKS = 0`:\n // cycles and mutually-dropped tables are handled, and a dependency this\n // inventory does NOT represent aborts the operation instead of being\n // deleted with it.\n const dropForeignKeys: string[] = [];\n for (const { table, foreignKey } of ownedForeignKeys(snapshot, tables)) {\n dropForeignKeys.push(\n migrationDriver.generateDDL(\n { type: \"dropForeignKey\", tableName: table, fkName: foreignKey.name },\n { destination: \"live\" }\n )\n );\n }\n\n const preserved = new Set<string>(policy.preserveTables ?? []);\n if (policy.trackingTable === \"preserve\") {\n preserved.add(policy.trackingTableName);\n }\n const droppable = tables.filter((name) => !preserved.has(name));\n\n const dropTables: PlannedTableDrop[] = [];\n for (const table of dependencySafeOrder(droppable, snapshot)) {\n dropTables.push({\n name: table,\n sql: migrationDriver.generateDropTableSQL(table),\n });\n }\n\n // Managed enums go after their tables: a type still used by a column is\n // a dependency, and `RESTRICT` is the point.\n const dropEnums: string[] = [];\n for (const enumName of enums) {\n const statement = migrationDriver.generateDropEnumSQL(enumName);\n if (statement) {\n dropEnums.push(statement);\n }\n }\n\n return {\n tables,\n clearTracking: tables.includes(policy.trackingTableName)\n ? migrationDriver.generateClearMigrations(policy.trackingTableName)\n : null,\n dropForeignKeys,\n dropTables,\n dropEnums,\n };\n}\n\n/**\n * Executes a planned clear. Every statement here CHANGES the estate.\n *\n * On PostgreSQL the caller wraps this in one transaction, so a failure rolls\n * every drop back. On MySQL DDL commits implicitly, which is why the tracking\n * rows are cleared FIRST — that clear commits immediately, so a later failure\n * can never leave rows claiming that now-missing objects are applied.\n *\n * The partial-commit REPORT is the caller's, not this owner's, and that is not\n * delegation for its own sake: the clear is only part of the program on both of\n * its MySQL callers — `reset()` replays the history after it and force-reset\n * rebuilds after it — so a boundary recorded here would fall silent at exactly\n * the point the caller keeps going. Both wrap this in `runSequentialProgram`\n * (`pinned-session.ts`), which records the boundary on the producer itself and\n * therefore spans the whole program. What that reporter must NOT span is the\n * planning above, which is why it is a separate call rather than this one's\n * first act.\n *\n * @param driver - the producer to execute on; the caller decides whether it is\n * inside a transaction, and whether it is inside a sequential program\n * @param plan - the rendered clear, from {@link planLiveNamespaceReset}\n */\nexport async function executeLiveNamespaceReset(\n driver: AnyDriver,\n plan: LiveNamespaceResetPlan\n): Promise<LiveNamespaceResetResult> {\n if (plan.clearTracking !== null) {\n await driver._executeRaw(plan.clearTracking);\n }\n\n for (const statement of plan.dropForeignKeys) {\n await driver._executeRaw(statement);\n }\n\n const dropped: string[] = [];\n for (const { name, sql } of plan.dropTables) {\n await driver._executeRaw(sql);\n dropped.push(name);\n }\n\n for (const statement of plan.dropEnums) {\n await driver._executeRaw(statement);\n }\n\n return { dropped };\n}\n\n/** Every foreign key owned by a table this reset is about to drop. */\nfunction* ownedForeignKeys(\n snapshot: SchemaSnapshot,\n tables: readonly string[]\n): Generator<{ table: string; foreignKey: ForeignKeyDef }> {\n const inventoried = new Set(tables);\n for (const table of snapshot.tables) {\n if (!inventoried.has(table.name)) {\n continue;\n }\n for (const foreignKey of table.foreignKeys) {\n yield { table: table.name, foreignKey };\n }\n }\n}\n\n/**\n * Children before parents, with a stable fallback for cycles.\n *\n * Every foreign key inside the estate has already been dropped by the time\n * these run, so the order is defence rather than necessity: it keeps a\n * constraint the inventory could not see from turning a reset into a failure\n * that has already dropped half the estate. A cycle's keys are already\n * dropped too, so its tables go in inventory order rather than deadlocking.\n */\nfunction dependencySafeOrder(\n tables: readonly string[],\n snapshot: SchemaSnapshot\n): string[] {\n const references: TableReference[] = [];\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== table.name) {\n references.push({ from: table.name, to: foreignKey.referencedTable });\n }\n }\n }\n const { ordered, blocked } = childrenBeforeParents(\n tables,\n (name) => name,\n references\n );\n return [...ordered, ...blocked];\n}\n\n/** Refuses an inbound foreign key to the declared tracking table. */\nfunction assertNoInboundTrackingReference(\n snapshot: SchemaSnapshot,\n trackingTableName: string\n): void {\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== trackingTableName) {\n continue;\n }\n throw new MigrationError(\n `Table \"${table.name}\" holds a foreign key \"${foreignKey.name}\" referencing the migration tracking table \"${trackingTableName}\", so this reset has no safe order and is refused before any statement runs. ` +\n \"MySQL commits DDL implicitly, so the tracking rows cannot be cleared and the schema torn down as one operation; drop the constraint yourself and re-run.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: table.name,\n constraint: foreignKey.name,\n referencedTable: trackingTableName,\n },\n }\n );\n }\n }\n}\n\n/**\n * Why an inventory this read cannot trust refuses the WHOLE clear.\n *\n * One sentence for both refusals below, because they have one reason: the\n * alternative to refusing is a reset that clears part of a namespace and\n * reports success.\n */\nconst UNTRUSTED_INVENTORY =\n \"A reset drops exactly what its inventory names and leaves everything else, so an inventory this read cannot trust would clear part of the namespace and report that it cleared all of it. The whole clear is refused before any statement runs.\";\n\n/**\n * Reads the `name` column off provider-shaped inventory rows, or REFUSES.\n *\n * The inventory is not a report; it is the DROP LIST. Everything it names is\n * destroyed and everything it does not name survives, so a row this read\n * SKIPPED took a real object off the list — the clear then reported success\n * over a namespace it had half cleared, and the rebuild that followed collided\n * with what was left. A repeated name is the same defect written differently:\n * one object planned twice while another was never planned at all.\n *\n * So the read fails closed, and it fails HERE — among\n * {@link planLiveNamespaceReset}'s catalog reads, before a destructive\n * statement exists to have run.\n */\nfunction readNames(rows: readonly unknown[], inventory: string): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const name = readName(row, index, inventory);\n if (seen.has(name)) {\n throw new MigrationError(\n `The ${inventory} inventory for this reset named \"${name}\" twice, at position ${index}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { type: \"duplicate-reset-inventory-name\", resultIndex: index },\n }\n );\n }\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/** The one object an inventory row names, or the refusal it earns. */\nfunction readName(row: unknown, index: number, inventory: string): string {\n // The cause is already an `Error` here: the one caller that has a thrown value\n // normalizes it through {@link errorCause} first. Deciding it here instead\n // meant a bare `thrown instanceof Error`, which BOTH dropped every non-`Error`\n // a provider row threw and, against a Proxy whose `getPrototypeOf` trap\n // throws, replaced this typed refusal with the trap's own error.\n const refuse = (reason: string, cause?: Error): MigrationError =>\n new MigrationError(\n `The ${inventory} inventory for this reset returned a row at position ${index} that does not name one object: ${reason}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause,\n meta: { type: \"unreadable-reset-inventory\", resultIndex: index },\n }\n );\n\n // The executor's contract is `unknown[]`, so this is where a provider row\n // becomes an object at all. A driver's own result contract already refuses a\n // non-object row (`drivers/normalized-result.ts`), which is why no falsifier\n // reaches this line through a driver; what it decides is that the answer for\n // a row from anywhere else is a refusal rather than a shorter drop list.\n if (typeof row !== \"object\" || row === null) {\n throw refuse(`the row is ${row === null ? \"null\" : `a ${typeof row}`}`);\n }\n\n let name: unknown;\n try {\n // Reading a column off a provider's row runs the provider's code, and its\n // failure is still this inventory refusing to be read.\n //\n // OWN properties only, because this inventory names objects a CATALOG\n // reported and a catalog reports columns: a `name` reached through the\n // prototype chain is a carrier's property or `Object.prototype` pollution,\n // and honouring one puts an object on the DROP LIST that no catalog ever\n // named. Asking whether the row owns the column runs the provider's code\n // too — a proxy answers that with a trap — so the ownership test shares\n // this `try` and refuses identically. It is not a second read of the value:\n // it consults the descriptor, not the getter.\n name = Object.hasOwn(row, \"name\") ? Reflect.get(row, \"name\") : undefined;\n } catch (failure) {\n throw refuse(\"reading its `name` threw\", errorCause(failure));\n }\n\n if (typeof name !== \"string\") {\n throw refuse(\n `its \\`name\\` is ${name === undefined ? \"not a column of the row\" : `a ${typeof name}`}`\n );\n }\n // An empty name renders as a quoted nothing, so the statement it would\n // produce does not drop the object the provider meant to report.\n if (name.length === 0) {\n throw refuse(\"its `name` is the empty string\");\n }\n return name;\n}\n","/**\n * One SQL blob builder. Every check and effect dispatch in a state shares\n * one content-addressed blob. No second blob for rollback.\n */\n\nimport type { Sha256 } from \"./identity\";\nimport { composeSqlBlob, refuseMysqlDelimiter } from \"./sql-blob\";\nimport { encodeDispatchIdentity } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\ninterface PendingFragment {\n readonly text: string;\n readonly parameters: readonly MigrationParameterV1[];\n}\n\nexport class SqlAssembly {\n private readonly pending: PendingFragment[] = [];\n\n add(text: string, parameters: readonly MigrationParameterV1[] = []): number {\n refuseMysqlDelimiter(text);\n this.pending.push({ text, parameters });\n return this.pending.length - 1;\n }\n\n seal(): {\n readonly bytes: Uint8Array;\n readonly sqlHash: Sha256;\n readonly dispatches: readonly MigrationDispatchV1[];\n } {\n const blob = composeSqlBlob(this.pending.map((fragment) => fragment.text));\n const dispatches = this.pending.map((fragment, index) => {\n const range = blob.ranges[index]!;\n return {\n dispatchId: encodeDispatchIdentity(\n blob.sqlHash,\n range.offset,\n range.length,\n fragment.parameters\n ),\n sqlHash: blob.sqlHash,\n offset: range.offset,\n length: range.length,\n parameters: fragment.parameters,\n };\n });\n return { bytes: blob.bytes, sqlHash: blob.sqlHash, dispatches };\n }\n}\n","import { isDestructiveOperation } from \"./differ\";\nimport { formatOperation } from \"./push/format\";\n/**\n * History-free push plan: live diff or force-reset rebuild, compiled\n * statements, and plan hash. This module does not execute SQL.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport { classifyGeneratedAtomicity } from \"./compile\";\nimport { controlTableNames, DEFAULT_CONTROL_BASE } from \"./control\";\nimport type {\n BoundMigrationDriver,\n DDLContext,\n MigrationDriver,\n} from \"./drivers\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n type LiveNamespaceResetPlan,\n planLiveNamespaceReset,\n} from \"./live-reset\";\nimport {\n type MigrationClient,\n type PushOptions as PlannerPushOptions,\n planPush,\n planRebuildFromEmpty,\n} from \"./push/planner\";\nimport type { ParsedPlanningOptions } from \"./push-consent\";\nimport {\n canonicalValue,\n fingerprintLive,\n freezeDeep,\n hashSnapshot,\n pushTargetIdentity,\n} from \"./push-fingerprint\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n type DiffOperation,\n type ResolveCallback,\n type ResolveChange,\n type ResolveResult,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"./types\";\nimport type {\n AtomicityClass,\n MigrationDispatchV1,\n PushConsent,\n PushOperation,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PlannedStatement {\n readonly kind: \"clear\" | \"effect\";\n readonly operationId: string;\n readonly dispatch: MigrationDispatchV1;\n}\n\nexport interface InternalPushPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly desiredSchema: SchemaSnapshot;\n readonly schemaHash: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly reportedOperations: readonly PushOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly previewStatements: readonly PushStatementPreview[];\n readonly sqlBlob: Uint8Array;\n readonly atomicity: AtomicityClass;\n readonly destructive: boolean;\n}\n\ntype ResolutionSource =\n | {\n readonly kind: \"record\";\n readonly callback: ResolveCallback | undefined;\n }\n | {\n readonly kind: \"replay\";\n readonly resolutions: readonly PushResolution[];\n };\n\ninterface ResolutionController {\n readonly callback: ResolveCallback;\n finish(): readonly PushResolution[];\n}\n\nexport async function buildPushPlan(\n client: MigrationClient,\n producer: AnyDriver,\n command: BoundMigrationDriver,\n relations: ResolvedRelationIndex,\n options: ParsedPlanningOptions,\n resolutionSource: ResolutionSource\n): Promise<InternalPushPlan> {\n const controller = resolutionController(resolutionSource);\n const plannerOptions: PlannerPushOptions = {\n skipValidation: options.skipValidation,\n resolve: controller.callback,\n };\n const planningDriver = managedPlanningDriver(command);\n const desired = serializeResolvedModels(\n client.$schema,\n planningDriver,\n relations\n );\n await command.preflightSchemaRequirements([desired], (sql, params) =>\n producer._executeRaw(sql, params)\n );\n const mode: PushConsent[\"mode\"] = options.forceReset ? \"force-reset\" : \"diff\";\n\n let reset: LiveNamespaceResetPlan | undefined;\n let current: SchemaSnapshot;\n let operations: readonly DiffOperation[];\n if (options.forceReset) {\n current = await introspectManaged(producer, command);\n const control = controlTableNames(DEFAULT_CONTROL_BASE);\n reset = await planLiveNamespaceReset(producer, command, {\n trackingTable: \"preserve\",\n trackingTableName: control.state,\n preserveTables: [control.log],\n });\n const rebuild = await planRebuildFromEmpty(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n operations = rebuild.operations;\n } else {\n const planned = await planPush(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n current = planned.currentSchema;\n operations = planned.operations;\n }\n if (!options.forceReset)\n for (const operation of operations) {\n if (\n operation.type !== \"addColumn\" ||\n operation.column.nullable ||\n operation.column.default !== undefined ||\n operation.column.autoIncrement\n )\n continue;\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameTable\" &&\n candidate.to === operation.tableName\n );\n const tableName =\n rename?.type === \"renameTable\" ? rename.from : operation.tableName;\n if (!current.tables.some((table) => table.name === tableName)) continue;\n const reference = producer.adapter.identifiers.table(tableName);\n const populated = await producer._executeRaw(\n `SELECT 1 AS present FROM ${reference.toStatement()} LIMIT 1`\n );\n if (populated.rows.length > 0)\n throw new MigrationError(\n `Cannot add required column \"${operation.tableName}.${operation.column.name}\" without a database default to a populated table. Application function/generator defaults do not backfill stored rows. Author a manual data migration that adds a nullable column, fills it, and then makes it required. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: operation.tableName,\n column: operation.column.name,\n command: \"push\",\n hint: \"Use a reviewed manual migration for explicit backfill before making the column required.\",\n },\n }\n );\n }\n const resolutions = controller.finish();\n const target = await pushTargetIdentity(client, producer, command);\n const sourceFingerprint = await fingerprintLive(current, command, producer);\n const desiredFingerprint = await fingerprintLive(desired, command, producer);\n const schemaHash = hashSnapshot(desired);\n const compiled = compilePlanStatements(\n reset,\n operations,\n planningDriver,\n options.forceReset ? emptyManagedSnapshot() : current\n );\n const reportedOperations: PushOperation[] = operations.map(\n (operation, index) => ({\n id: `${operation.type}:${index}`,\n label: formatOperation(operation),\n // A live table rename takes its old name from every other reader, and a\n // history-free push cannot prove that table was ever this schema's.\n risk:\n isDestructiveOperation(operation) || operation.type === \"renameTable\"\n ? \"destructive\"\n : \"safe\",\n })\n );\n const atomicity = classifyPlanAtomicity(command, operations);\n const destructive =\n mode === \"force-reset\" ||\n reportedOperations.some((operation) => operation.risk === \"destructive\");\n const validation: PushConsent[\"validation\"] = options.skipValidation\n ? \"structural-only\"\n : \"full\";\n const planHash = hashPushPlan({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n schemaHash,\n resolutions,\n operations,\n statements: compiled.statements,\n atomicity,\n });\n\n return freezeDeep({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n desiredSchema: desired,\n schemaHash,\n planHash,\n resolutions,\n operations,\n reportedOperations,\n statements: compiled.statements,\n previewStatements: compiled.statements.map((statement) => ({\n sql: sliceDispatch(compiled.bytes, statement.dispatch),\n parameters: statement.dispatch.parameters,\n })),\n sqlBlob: compiled.bytes,\n atomicity,\n destructive,\n });\n}\n\nexport function compilePlanStatements(\n reset: LiveNamespaceResetPlan | undefined,\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot\n): {\n readonly bytes: Uint8Array;\n readonly statements: readonly PlannedStatement[];\n} {\n const assembly = new SqlAssembly();\n const pending: Array<{\n readonly kind: PlannedStatement[\"kind\"];\n readonly operationId: string;\n readonly index: number;\n }> = [];\n\n if (reset) {\n const clear = [\n ...reset.dropForeignKeys,\n ...reset.dropTables.map((table) => table.sql),\n ...reset.dropEnums,\n ];\n for (const [index, sql] of clear.entries()) {\n pending.push({\n kind: \"clear\",\n operationId: `force-reset:clear:${index}`,\n index: assembly.add(sql),\n });\n }\n }\n\n for (const [operationIndex, operation] of operations.entries()) {\n const context: DDLContext = {\n destination: \"live\",\n currentSchema,\n precedingOperations: operations.slice(0, operationIndex),\n followingOperations: operations.slice(operationIndex + 1),\n };\n const statements = driver.compileStatements(operation, context);\n for (const [statementIndex, sql] of statements.entries()) {\n pending.push({\n kind: \"effect\",\n operationId: `${operation.type}:${operationIndex}:${statementIndex}`,\n index: assembly.add(sql),\n });\n }\n }\n\n const sealed = assembly.seal();\n return {\n bytes: sealed.bytes,\n statements: pending.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: requiredDispatch(sealed.dispatches, statement.index),\n })),\n };\n}\n\nexport function hashPushPlan(input: {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly schemaHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly atomicity: AtomicityClass;\n}): Sha256 {\n return domainHash(\n HASH_DOMAIN.plan,\n canonicalizeJson(\n canonicalValue({\n mode: input.mode,\n validation: input.validation,\n target: input.target,\n sourceFingerprint: input.sourceFingerprint,\n desiredFingerprint: input.desiredFingerprint,\n schemaHash: input.schemaHash,\n resolutions: input.resolutions,\n operations: input.operations,\n atomicity: input.atomicity,\n // Review SQL is intentionally absent. Dispatch identity authenticates\n // the sealed statement bytes, exact ranges, and typed parameters.\n statements: input.statements.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: statement.dispatch,\n })),\n })\n )\n );\n}\n\nexport function classifyPlanAtomicity(\n driver: MigrationDriver,\n operations: readonly DiffOperation[]\n): AtomicityClass {\n return classifyGeneratedAtomicity(driver, operations);\n}\n\nexport async function introspectManaged(\n producer: AnyDriver,\n driver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return withoutControlTables(\n await driver.introspect((sql, params) => producer._executeRaw(sql, params))\n );\n}\n\nfunction requiredDispatch(\n dispatches: readonly MigrationDispatchV1[],\n index: number\n): MigrationDispatchV1 {\n const dispatch = dispatches[index];\n if (!dispatch) {\n throw new MigrationError(\n \"The structured push compiler omitted a planned dispatch\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return dispatch;\n}\n\nfunction managedPlanningDriver(\n driver: BoundMigrationDriver\n): BoundMigrationDriver {\n const managed: BoundMigrationDriver = Object.create(driver);\n Object.defineProperty(managed, \"introspect\", {\n value: async (\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ) => withoutControlTables(await driver.introspect(executeRaw)),\n });\n Object.freeze(managed);\n return managed;\n}\n\nfunction withoutControlTables(snapshot: SchemaSnapshot): SchemaSnapshot {\n const names = controlTableNames(DEFAULT_CONTROL_BASE);\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) => table.name !== names.state && table.name !== names.log\n ),\n };\n}\n\nfunction resolutionController(source: ResolutionSource): ResolutionController {\n if (source.kind === \"record\") {\n const recorded: PushResolution[] = [];\n return {\n callback: async (change) => {\n const result = source.callback\n ? await source.callback(change)\n : defaultResolution(change);\n const decision = closeResolution(change, result);\n if (decision) {\n recorded.push({ id: resolutionId(change), decision });\n }\n return result;\n },\n finish: () => freezeDeep([...recorded]),\n };\n }\n\n let cursor = 0;\n return {\n callback: (change) => {\n const expected = source.resolutions[cursor++];\n if (!expected || expected.id !== resolutionId(change)) {\n throw new MigrationError(\n \"The locked push requested a different set of resolutions\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return replayResolution(change, expected.decision);\n },\n finish: () => {\n if (cursor !== source.resolutions.length) {\n throw new MigrationError(\n \"The locked push no longer requests every consented resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return source.resolutions;\n },\n };\n}\n\nfunction defaultResolution(change: ResolveChange): ResolveResult | undefined {\n // Destructive operations have one interpretation. Closing `proceed` lets a\n // preview describe it, while exact plan consent remains mandatory.\n if (change.type === \"destructive\") return change.proceed();\n return undefined;\n}\n\nfunction closeResolution(\n change: ResolveChange,\n result: ResolveResult | undefined | void\n): string | undefined {\n if (result === undefined) return undefined;\n if (result === \"reject\") return \"reject\";\n if (change.type === \"destructive\") {\n if (result !== \"proceed\") invalidResolution(change);\n return \"proceed\";\n }\n if (change.type === \"ambiguous\") {\n if (result !== \"rename\" && result !== \"addAndDrop\") {\n invalidResolution(change);\n }\n return result;\n }\n if (result !== \"enumMapped\") invalidResolution(change);\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n return `map:${canonicalizeJsonText(canonicalValue(decision.mappings))}`;\n }\n if (decision?.kind === \"useNull\") {\n if (!change.isNullable) {\n throw new MigrationError(\n \"A non-nullable enum column cannot resolve removed values to NULL\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return \"useNull\";\n }\n invalidResolution(change);\n}\n\nfunction invalidResolution(change: ResolveChange): never {\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result for a ${change.type} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"invalid-resolution-result\" } }\n );\n}\n\nfunction replayResolution(\n change: ResolveChange,\n decision: string\n): ResolveResult {\n if (change.type === \"destructive\" && decision === \"proceed\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n if (decision === \"rename\") return change.rename();\n if (decision === \"addAndDrop\") return change.addAndDrop();\n }\n if (change.type === \"enumValueRemoval\") {\n if (decision === \"useNull\" && change.isNullable) return change.useNull();\n if (decision.startsWith(\"map:\")) {\n return change.mapValues(parseResolutionMap(decision.slice(4)));\n }\n }\n throw new MigrationError(\n \"Push consent contains a resolution that is invalid for the locked request\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n}\n\nfunction resolutionId(change: ResolveChange): string {\n const identity =\n change.type === \"enumValueRemoval\"\n ? {\n type: change.type,\n enumName: change.enumName,\n tableName: change.tableName,\n columnName: change.columnName,\n isNullable: change.isNullable,\n removedValues: change.removedValues,\n availableValues: change.availableValues,\n }\n : {\n type: change.type,\n operation: change.operation,\n table: change.table,\n column: change.column ?? null,\n oldName:\n change.type === \"ambiguous\" ? (change.oldName ?? null) : null,\n newName:\n change.type === \"ambiguous\" ? (change.newName ?? null) : null,\n oldType:\n change.type === \"ambiguous\" ? (change.oldType ?? null) : null,\n newType:\n change.type === \"ambiguous\" ? (change.newType ?? null) : null,\n };\n return domainHash(HASH_DOMAIN.plan, canonicalizeJson(identity));\n}\n\nfunction parseResolutionMap(text: string): Record<string, string | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (cause) {\n throw new MigrationError(\n \"Push consent contains a malformed enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n if (!isRecord(parsed) || canonicalizeJsonText(parsed) !== text) {\n throw new MigrationError(\n \"Push consent contains a non-canonical enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n const result: Record<string, string | null> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== \"string\" && value !== null) {\n throw new MigrationError(\n \"Push consent enum mappings must contain only strings or null\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n result[key] = value;\n }\n return result;\n}\n","/**\n * Apply V1: authenticate the graph, lock, refuse drift, execute exact slices,\n * then CAS the marker. Production never evaluates TypeScript.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n stepStatements,\n} from \"./compile\";\nimport {\n appendLedger,\n casMarker,\n DEFAULT_CONTROL_BASE,\n ensureControlTables,\n markerFromPath,\n readControlState,\n refuseIncompatibleHistory,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { evaluateAllChecks, executeOperations } from \"./execute-dispatch\";\nimport {\n assertForeignKeysIntact,\n liftForeignKeyPragmas,\n withForeignKeysLifted,\n} from \"./foreign-keys\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n selectRoute,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n mayWrapTransaction,\n runSequentialProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport { eventIdFor } from \"./v1-parse\";\nimport type {\n ApplyV1Options,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface ApplyV1Result {\n readonly outcome: \"applied\" | \"noop\" | \"preview\";\n readonly path: readonly Sha256[];\n readonly statements: readonly string[];\n}\n\nexport async function applyV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ApplyV1Options = {}\n): Promise<ApplyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n const target = resolveStateSelector(graph, options.to);\n const dryRun = options.dryRun === true;\n admitLiveMigrationCapability(\n driver,\n dryRun ? \"read-only\" : \"effectful\",\n dryRun ? \"apply({ dryRun: true })\" : \"apply()\"\n );\n\n if (dryRun) {\n const control = await readControlState(\n client.$driver,\n driver,\n DEFAULT_CONTROL_BASE\n );\n refusePartialControl(control.presence);\n const { marker } = control;\n const origin = marker?.stateId ?? null;\n if (origin === target) return { outcome: \"noop\", path: [], statements: [] };\n const path = selectRoute(graph, origin, target, options.via);\n assertPathArtifacts(graph, origin, path);\n return {\n outcome: \"preview\",\n path,\n statements: previewStatements(graph, origin, path),\n };\n }\n\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n refuseIncompatibleHistory(marker, ledger);\n const unfinished = unfinishedAttempts(ledger);\n if (unfinished.length > 0) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const origin = marker?.stateId ?? null;\n const path =\n origin === target\n ? []\n : selectRoute(graph, origin, target, options.via);\n assertPathArtifacts(graph, origin, path);\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, origin),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n if (marker) {\n await assertNoDrift(pinned, command, graph, marker);\n } else {\n await assertEmptyManaged(pinned, command);\n }\n if (origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n const statements = previewStatements(graph, origin, path);\n const run = async (producer: Parameters<typeof appendLedger>[0]) => {\n await applyPathUnderLock(\n producer,\n command,\n graph,\n marker,\n origin,\n path,\n needsBootstrap\n );\n };\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, run);\n } else {\n await run(pinned);\n }\n return { outcome: \"applied\", path, statements };\n }\n );\n}\n\nexport async function applyPathUnderLock(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n origin: Sha256 | null,\n path: readonly Sha256[],\n needsBootstrap = false\n): Promise<void> {\n const prepared = path.map((to, index) => {\n const from = index === 0 ? origin : path[index - 1]!;\n const transition = parentTransition(graph, from, to);\n const state = graph.states.get(to)!;\n const blob = graph.sql.get(state.sqlHash);\n if (!blob) {\n throw new MigrationError(\n \"Selected transition is missing its SQL blob\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions,\n transition.requestedForwardBoundary\n );\n return {\n from,\n to,\n transition,\n state,\n blob,\n boundary: classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n ),\n };\n });\n\n let current = marker;\n const nextPath = marker ? [...marker.path] : [];\n let bootstrapPending = needsBootstrap;\n const statementsOf = ({ transition, blob }: PreparedForwardEdge) =>\n stepStatements(blob, transition.operations);\n for (const group of groupContiguousAtomicity(prepared, statementsOf)) {\n const statements = group.items.flatMap(statementsOf);\n const lifted = liftForeignKeyPragmas(pinned, statements);\n const run = async (producer: Parameters<typeof appendLedger>[0]) => {\n if (bootstrapPending) {\n await ensureControlTables(producer, command, DEFAULT_CONTROL_BASE);\n bootstrapPending = false;\n }\n for (const item of group.items) {\n current = await executeForwardEdge(\n producer,\n command,\n graph,\n item,\n current,\n nextPath\n );\n }\n };\n if (\n mayWrapTransaction(\n pinned,\n command.target.dialect,\n group.boundary === \"transactional\"\n )\n ) {\n await withForeignKeysLifted(pinned, lifted.bracket, () =>\n pinned.withTransaction(async (transaction) => {\n await run(transaction);\n await assertForeignKeysIntact(transaction, lifted.bracket);\n })\n );\n } else {\n await run(pinned);\n }\n }\n}\n\ninterface PreparedForwardEdge {\n readonly from: Sha256 | null;\n readonly to: Sha256;\n readonly transition: ReturnType<typeof parentTransition>;\n readonly state: MigrationStateManifestV1;\n readonly blob: Uint8Array;\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\nasync function executeForwardEdge(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n item: PreparedForwardEdge,\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[]\n): Promise<MigrationMarkerV1> {\n const { from, to, transition, state, blob, boundary } = item;\n const attemptId = eventIdFor({\n format: \"1\",\n attemptId: \"0\".repeat(64),\n kind: \"started\",\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n direction: \"forward\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n startedAt: new Date().toISOString(),\n finishedAt: null,\n toolVersion: \"v1\",\n failure: null,\n });\n await appendLedger(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n ledgerEvent(\n graph,\n attemptId,\n \"started\",\n from,\n to,\n \"none\",\n null,\n null,\n transition.transitionHash\n )\n );\n if (\n !(await evaluateAllChecks(\n producer,\n blob,\n transition.originChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Origin checks failed before the first dispatch\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n await executeOperations(\n producer,\n blob,\n transition.operations,\n boundary,\n async (progress, effect) => {\n await appendLedger(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n ledgerEvent(\n graph,\n attemptId,\n \"step-confirmed\",\n from,\n to,\n effect,\n progress.operationId,\n progress.dispatchId,\n transition.transitionHash\n )\n );\n },\n command.namespace\n );\n if (\n !(await evaluateAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Destination checks failed before the marker could advance\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n await assertFingerprint(producer, command, graph, state.snapshotHash);\n nextPath.push({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n });\n const next = markerFromPath(\n graph.estateHash,\n state.snapshotHash,\n nextPath,\n (current?.revision ?? 0) + 1\n );\n await casMarker(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n current ? { revision: current.revision, pathHash: current.pathHash } : null,\n next\n );\n await appendLedger(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n ledgerEvent(\n graph,\n attemptId,\n \"applied\",\n from,\n to,\n \"committed\",\n null,\n null,\n transition.transitionHash\n )\n );\n return next;\n}\n\nfunction assertPathArtifacts(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): void {\n let from = origin;\n for (const to of path) {\n parentTransition(graph, from, to);\n const state = graph.states.get(to);\n if (!(state && graph.sql.has(state.sqlHash))) {\n throw new MigrationError(\n \"Selected path references a state or SQL blob that is not authenticated\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n from = to;\n }\n}\n\nfunction previewStatements(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): string[] {\n const statements: string[] = [];\n let from = origin;\n for (const to of path) {\n const transition = parentTransition(graph, from, to);\n const blob = graph.sql.get(graph.states.get(to)!.sqlHash);\n if (blob) statements.push(...stepStatements(blob, transition.operations));\n from = to;\n }\n return statements;\n}\n\nexport async function assertNoDrift(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Promise<void> {\n if (marker.estateHash !== graph.estateHash) {\n throw new MigrationError(\n \"Live marker estate does not match storage\",\n VibORMErrorCode.MIGRATION_DRIFT,\n { meta: { estateHash: marker.estateHash } }\n );\n }\n if (marker.stateId) {\n const state = graph.states.get(marker.stateId);\n if (!state) {\n throw new MigrationError(\n \"Marker state is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (state.snapshotHash !== marker.snapshotHash) {\n throw new MigrationError(\n \"Marker snapshot does not match the authenticated state\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n } else if (marker.snapshotHash !== graph.emptySnapshotHash) {\n throw new MigrationError(\n \"An empty-path marker must name the empty managed snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (marker.path.length === 0) {\n if (marker.stateId !== null) {\n throw new MigrationError(\n \"Marker path does not end at the marked state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n } else {\n if (marker.path.at(-1)!.stateId !== marker.stateId) {\n throw new MigrationError(\n \"Marker path does not end at the marked state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n let from: Sha256 | null = null;\n for (const edge of marker.path) {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) =>\n item.transitionHash === edge.transitionHash && item.fromState === from\n );\n if (!(state && parent)) {\n throw new MigrationError(\n \"Marker path is not an authenticated arrival route\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n from = edge.stateId;\n }\n }\n const snapshotHash = marker.stateId\n ? graph.states.get(marker.stateId)!.snapshotHash\n : graph.emptySnapshotHash;\n if (!graph.snapshots.get(snapshotHash)) {\n throw new MigrationError(\n \"Marker snapshot is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n await assertFingerprint(producer, command, graph, snapshotHash);\n}\n\nasync function assertFingerprint(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n snapshotHash: Sha256\n): Promise<void> {\n const live = await introspectManaged(producer, command);\n const expected =\n graph.snapshots.get(snapshotHash) ??\n (snapshotHash === graph.emptySnapshotHash ? emptyManagedSnapshot() : null);\n if (\n !expected ||\n (await fingerprintLive(live, command, producer)) !==\n (await fingerprintLive(expected, command, producer))\n ) {\n throw new MigrationError(\n `Live managed schema drifted from the authenticated snapshot. Differences: ${expected ? JSON.stringify(await diff(live, expected)) : \"authenticated snapshot is missing\"}`,\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n}\n\nasync function assertEmptyManaged(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver\n): Promise<void> {\n const live = await introspectManaged(producer, command);\n if (live.tables.length > 0 || (live.enums?.length ?? 0) > 0) {\n throw new MigrationError(\n \"Ordinary apply requires an empty managed target; use baseline to adopt an existing schema\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n\nfunction ledgerEvent(\n graph: MigrationGraph,\n attemptId: Sha256,\n kind: LedgerEventV1[\"kind\"],\n from: Sha256 | null,\n to: Sha256,\n effectState: LedgerEventV1[\"effectState\"],\n operationId: string | null = null,\n dispatchId: string | null = null,\n transitionHash: Sha256 | null = null\n): LedgerEventV1 {\n const event = {\n format: \"1\" as const,\n attemptId,\n kind,\n estateHash: graph.estateHash,\n snapshotHash: graph.states.get(to)!.snapshotHash,\n sqlHash: graph.states.get(to)!.sqlHash,\n fromState: from,\n toState: to,\n transitionHash,\n direction: \"forward\" as const,\n operationId,\n dispatchId,\n effectState,\n startedAt: new Date().toISOString(),\n finishedAt: kind === \"started\" ? null : new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n return { ...event, eventId: eventIdFor(event) };\n}\n","/**\n * Offline estate check. CI-safe. Never creates control tables.\n */\n\nimport { loadMigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport {\n encodeSqlBlob,\n parseSnapshotDocument,\n parseStateManifest,\n} from \"./v1-parse\";\n\nexport interface CheckFinding {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface CheckResult {\n readonly ok: boolean;\n readonly findings: readonly CheckFinding[];\n}\n\nexport async function checkEstate(\n storage: MigrationStorageReader\n): Promise<CheckResult> {\n const findings: CheckFinding[] = [];\n try {\n const graph = await loadMigrationGraph(storage);\n if (graph.leaves.length > 1) {\n findings.push({\n code: \"unresolved-branch\",\n message: `Estate has ${graph.leaves.length} leaves; apply requires an explicit target or via`,\n });\n }\n const referencedSnapshots = new Set<Sha256>([graph.emptySnapshotHash]);\n const referencedSql = new Set<Sha256>();\n for (const state of graph.states.values()) {\n referencedSnapshots.add(state.snapshotHash);\n referencedSql.add(state.sqlHash);\n }\n for (const hash of await storage.listSnapshots()) {\n if (!referencedSnapshots.has(hash)) {\n findings.push({\n code: \"orphan-snapshot\",\n message: `Snapshot ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSnapshot(hash);\n if (bytes) parseSnapshotDocument(bytes, hash);\n }\n for (const hash of await storage.listSql()) {\n if (!referencedSql.has(hash)) {\n findings.push({\n code: \"orphan-sql\",\n message: `SQL blob ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSql(hash);\n if (bytes && encodeSqlBlob(bytes) !== hash) {\n findings.push({\n code: \"corrupt-sql\",\n message: `SQL blob ${hash} does not match its bytes`,\n });\n }\n }\n for (const id of await storage.listStates()) {\n const bytes = await storage.readState(id);\n if (bytes) parseStateManifest(bytes, id);\n }\n } catch (error) {\n findings.push({\n code: \"invalid-estate\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n return {\n ok: findings.every((finding) => finding.code.startsWith(\"orphan-\")),\n findings,\n };\n}\n","/**\n * One hostile-input boundary for generation options and manual definitions.\n * It settles every caller-owned accessor before estate or provider access.\n */\n\nimport { Sql } from \"@sql\";\nimport { errorCause } from \"../drivers/shared/driver-options\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationCheckInput,\n} from \"./v1-types\";\n\nexport function normalizeGenerateOptions(options: unknown): GenerateV1Options {\n const record = snapshotExactRecord(\n options,\n [\"name\", \"from\", \"dryRun\", \"resolve\", \"skipValidation\", \"manualMigration\"],\n \"generate options\",\n refuseGenerateOptions\n );\n const { name, from, dryRun, resolve, skipValidation, manualMigration } =\n record;\n if (name !== undefined && typeof name !== \"string\") {\n return refuseGenerateOptions(\"generate name must be a string\");\n }\n if (from !== undefined && from !== null && typeof from !== \"string\") {\n return refuseGenerateOptions(\"generate from must be a state id or null\");\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseGenerateOptions(\"generate dryRun must be a boolean\");\n }\n if (skipValidation !== undefined && typeof skipValidation !== \"boolean\") {\n return refuseGenerateOptions(\"generate skipValidation must be a boolean\");\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseGenerateOptions(\"generate resolve must be a function\");\n }\n return Object.freeze({\n ...(name === undefined ? {} : { name }),\n ...(from === undefined ? {} : { from }),\n ...(dryRun === undefined ? {} : { dryRun }),\n ...(resolve === undefined ? {} : { resolve }),\n ...(skipValidation === undefined ? {} : { skipValidation }),\n ...(manualMigration === undefined\n ? {}\n : { manualMigration: snapshotManualMigration(manualMigration) }),\n });\n}\n\nfunction snapshotManualMigration(value: unknown): ManualMigrationInput {\n const record = snapshotExactRecord(\n value,\n [\"transitions\", \"destinationChecks\"],\n \"manual migration\",\n refuseManualDefinition\n );\n const transitions = snapshotExactArray(\n record.transitions,\n \"manual migration transitions\",\n refuseManualDefinition\n ).map((transition, index) =>\n snapshotManualTransition(transition, `manual transition ${index}`)\n );\n if (transitions.length === 0) {\n return refuseManualDefinition(\n \"A manual migration must define at least one parent transition\"\n );\n }\n const destinationChecks =\n record.destinationChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.destinationChecks,\n \"manual destination checks\",\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `manual destination check ${index}`)\n );\n return Object.freeze({\n transitions: Object.freeze(transitions),\n ...(destinationChecks === undefined\n ? {}\n : { destinationChecks: Object.freeze(destinationChecks) }),\n });\n}\n\nfunction snapshotManualTransition(\n value: unknown,\n label: string\n): ManualTransitionInput {\n const record = snapshotExactRecord(\n value,\n [\"from\", \"execution\", \"up\", \"originChecks\", \"rollback\"],\n label,\n refuseManualDefinition\n );\n const { from, execution } = record;\n if (from !== null && typeof from !== \"string\") {\n return refuseManualDefinition(`${label}.from must be a state id or null`);\n }\n if (execution !== \"transactional\" && execution !== \"stepwise\") {\n return refuseManualDefinition(\n `${label}.execution must be transactional or stepwise`\n );\n }\n const up = snapshotSqlArray(record.up, `${label}.up`);\n const originChecks =\n record.originChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.originChecks,\n `${label}.originChecks`,\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `${label}.originChecks[${index}]`)\n );\n return Object.freeze({\n from,\n execution,\n up,\n ...(originChecks === undefined\n ? {}\n : { originChecks: Object.freeze(originChecks) }),\n rollback: snapshotManualRollback(record.rollback, `${label}.rollback`),\n });\n}\n\nfunction snapshotManualRollback(\n value: unknown,\n label: string\n): ManualTransitionInput[\"rollback\"] {\n const discriminant = snapshotExactRecord(\n value,\n [\"kind\", \"execution\", \"sql\", \"reason\"],\n label,\n refuseManualDefinition\n );\n if (discriminant.kind === \"irreversible\") {\n if (\n discriminant.execution !== undefined ||\n discriminant.sql !== undefined ||\n typeof discriminant.reason !== \"string\"\n ) {\n return refuseManualDefinition(\n `${label} has an invalid irreversible shape`\n );\n }\n return Object.freeze({\n kind: \"irreversible\",\n reason: discriminant.reason,\n });\n }\n if (discriminant.kind !== \"manual\") {\n return refuseManualDefinition(`${label}.kind is invalid`);\n }\n if (\n discriminant.reason !== undefined ||\n (discriminant.execution !== \"transactional\" &&\n discriminant.execution !== \"stepwise\")\n ) {\n return refuseManualDefinition(`${label} has an invalid manual shape`);\n }\n return Object.freeze({\n kind: \"manual\",\n execution: discriminant.execution,\n sql: snapshotSqlArray(discriminant.sql, `${label}.sql`),\n });\n}\n\nfunction snapshotManualCheck(\n value: unknown,\n label: string\n): MigrationCheckInput {\n const record = snapshotExactRecord(\n value,\n [\"kind\", \"query\", \"equals\"],\n label,\n refuseManualDefinition\n );\n if (record.kind !== \"trusted-read\" || typeof record.equals !== \"boolean\") {\n return refuseManualDefinition(`${label} has an invalid check shape`);\n }\n return Object.freeze({\n kind: \"trusted-read\",\n query: snapshotSql(record.query, `${label}.query`),\n equals: record.equals,\n });\n}\n\nfunction snapshotSqlArray(value: unknown, label: string): readonly Sql[] {\n const entries = snapshotExactArray(value, label, refuseManualDefinition);\n const sql: Sql[] = [];\n for (let index = 0; index < entries.length; index++) {\n sql.push(snapshotSql(entries[index], `${label}[${index}]`));\n }\n return Object.freeze(sql);\n}\n\nfunction snapshotSql(value: unknown, label: string): Sql {\n try {\n if (!(value instanceof Sql)) {\n return refuseManualDefinition(`${label} must be a Sql value`);\n }\n const rawStrings: unknown = Reflect.get(value, \"strings\");\n const rawValues: unknown = Reflect.get(value, \"values\");\n if (!(Array.isArray(rawStrings) && Array.isArray(rawValues))) {\n return refuseManualDefinition(\n `${label}.strings and ${label}.values must be arrays`\n );\n }\n const strings = Array.from(rawStrings);\n const values = Array.from(rawValues);\n if (!strings.every((entry) => typeof entry === \"string\")) {\n return refuseManualDefinition(`${label}.strings must contain strings`);\n }\n if (strings.length !== values.length + 1) {\n return refuseManualDefinition(\n `${label} has an invalid strings and values shape`\n );\n }\n return new Sql(Object.freeze(strings), Object.freeze(values));\n } catch (failure) {\n return refuseManualDefinition(\n `${label} could not be read`,\n errorCause(failure)\n );\n }\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseGenerateOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction refuseManualDefinition(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE, {\n cause,\n });\n}\n","/** Immutable, non-executable migration graph projections for public tooling. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { MigrationTarget } from \"./types\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface MigrationStateListItem {\n readonly stateId: Sha256;\n readonly name: string;\n}\n\nexport interface MigrationStateMetadata extends MigrationStateListItem {\n readonly snapshotHash: Sha256;\n readonly sqlHash: Sha256;\n readonly root: boolean;\n readonly leaf: boolean;\n}\n\nexport type MigrationRollbackMetadata =\n | {\n readonly kind: \"schema\" | \"manual\";\n readonly operationCount: number;\n readonly stepCount: number;\n }\n | {\n readonly kind: \"irreversible\";\n readonly reason: string;\n readonly operationCount: 0;\n readonly stepCount: 0;\n };\n\nexport interface MigrationEdgeMetadata {\n readonly fromState: Sha256 | null;\n readonly toState: Sha256;\n readonly transitionHash: Sha256;\n readonly requestedBoundary: \"transactional\" | \"stepwise\" | null;\n readonly operationCount: number;\n readonly stepCount: number;\n readonly origins: readonly (\"generated\" | \"manual\")[];\n readonly risks: readonly (\"safe\" | \"destructive\" | \"opaque\")[];\n readonly rollback: MigrationRollbackMetadata;\n}\n\nexport interface MigrationStateDetails extends MigrationStateMetadata {\n readonly incoming: readonly MigrationEdgeMetadata[];\n readonly outgoing: readonly MigrationEdgeMetadata[];\n}\n\nexport interface GraphResult {\n readonly estateHash: Sha256;\n readonly target: MigrationTarget;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly states: readonly MigrationStateMetadata[];\n readonly edges: readonly MigrationEdgeMetadata[];\n}\n\nexport type ListResult = readonly MigrationStateListItem[];\nexport type ShowResult = MigrationStateDetails;\n\nexport function listMigrationStates(graph: MigrationGraph): ListResult {\n return Object.freeze(\n sortedStates(graph).map((state) =>\n Object.freeze({ stateId: state.stateId, name: state.name })\n )\n );\n}\n\nexport function showMigrationState(\n graph: MigrationGraph,\n stateId: Sha256\n): ShowResult {\n const state = graph.states.get(stateId);\n if (!state) {\n throw new MigrationError(\n \"Resolved migration state is absent from its graph\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const edges = graphEdges(graph);\n return Object.freeze({\n ...stateMetadata(graph, state),\n incoming: Object.freeze(edges.filter((edge) => edge.toState === stateId)),\n outgoing: Object.freeze(edges.filter((edge) => edge.fromState === stateId)),\n });\n}\n\nexport function migrationGraphResult(graph: MigrationGraph): GraphResult {\n return Object.freeze({\n estateHash: graph.estateHash,\n target: migrationTarget(graph.descriptor.target),\n roots: Object.freeze([...graph.roots].sort()),\n leaves: Object.freeze([...graph.leaves].sort()),\n states: Object.freeze(\n sortedStates(graph).map((state) => stateMetadata(graph, state))\n ),\n edges: graphEdges(graph),\n });\n}\n\nfunction sortedStates(graph: MigrationGraph): MigrationStateManifestV1[] {\n return [...graph.states.values()].sort((left, right) =>\n left.stateId.localeCompare(right.stateId)\n );\n}\n\nfunction stateMetadata(\n graph: MigrationGraph,\n state: MigrationStateManifestV1\n): MigrationStateMetadata {\n return Object.freeze({\n stateId: state.stateId,\n name: state.name,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n root: graph.roots.includes(state.stateId),\n leaf: graph.leaves.includes(state.stateId),\n });\n}\n\nfunction graphEdges(graph: MigrationGraph): readonly MigrationEdgeMetadata[] {\n const edges: MigrationEdgeMetadata[] = [];\n for (const state of sortedStates(graph)) {\n for (const transition of state.parents) {\n edges.push(edgeMetadata(state.stateId, transition));\n }\n }\n edges.sort((left, right) => {\n const from = (left.fromState ?? \"\").localeCompare(right.fromState ?? \"\");\n return from === 0 ? left.toState.localeCompare(right.toState) : from;\n });\n return Object.freeze(edges);\n}\n\nfunction edgeMetadata(\n toState: Sha256,\n transition: MigrationParentTransitionV1\n): MigrationEdgeMetadata {\n return Object.freeze({\n fromState: transition.fromState,\n toState,\n transitionHash: transition.transitionHash,\n requestedBoundary: transition.requestedForwardBoundary,\n operationCount: transition.operations.length,\n stepCount: stepCount(transition.operations),\n origins: uniqueOperationValues(transition.operations, \"origin\"),\n risks: uniqueOperationValues(transition.operations, \"risk\"),\n rollback: rollbackMetadata(transition),\n });\n}\n\nfunction rollbackMetadata(\n transition: MigrationParentTransitionV1\n): MigrationRollbackMetadata {\n if (transition.rollback.kind === \"irreversible\") {\n return Object.freeze({\n kind: transition.rollback.kind,\n reason: transition.rollback.reason,\n operationCount: 0,\n stepCount: 0,\n });\n }\n const operations = transition.rollback.operations;\n return Object.freeze({\n kind: transition.rollback.kind,\n operationCount: operations.length,\n stepCount: stepCount(operations),\n });\n}\n\nfunction stepCount(operations: readonly MigrationOperationV1[]): number {\n let count = 0;\n for (const operation of operations) count += operation.steps.length;\n return count;\n}\n\nfunction uniqueOperationValues<K extends \"origin\" | \"risk\">(\n operations: readonly MigrationOperationV1[],\n key: K\n): readonly MigrationOperationV1[K][] {\n const values: MigrationOperationV1[K][] = [];\n for (const operation of operations) {\n const value = operation[key];\n if (!values.includes(value)) values.push(value);\n }\n return Object.freeze(values);\n}\n\nfunction migrationTarget(target: MigrationTarget): MigrationTarget {\n return target.dialect === \"postgresql\"\n ? Object.freeze({ dialect: target.dialect, namespace: target.namespace })\n : Object.freeze({ dialect: target.dialect });\n}\n\n/** A labelled read-only projection; dispatch offsets remain the execution authority. */\nexport function renderMigrationReview(\n parents: readonly MigrationParentTransitionV1[],\n destinationChecks: readonly MigrationBooleanCheckV1[],\n blob: Uint8Array\n): string {\n const lines = [\n \"-- VibORM review: forward, checks and rollback are separate sections.\",\n \"-- Execute authenticated states with migrate apply/down; this review is not an apply script.\",\n ];\n const emit = (label: string, dispatch: MigrationDispatchV1) => {\n lines.push(\n `-- ${label.replace(/[\\r\\n\\u2028\\u2029]/g, \" \")}`,\n `${sliceDispatch(blob, dispatch)};`\n );\n if (dispatch.parameters.length > 0)\n lines.push(`-- Parameters: ${JSON.stringify(dispatch.parameters)}`);\n };\n const operations = (\n direction: string,\n values: readonly MigrationOperationV1[]\n ) => {\n for (const operation of values)\n for (const step of operation.steps) {\n if (step.retry === \"proven\")\n emit(`${direction} precheck ${operation.label}`, step.precheck.query);\n emit(`${direction} execute ${operation.label}`, step.execute);\n if (step.retry === \"proven\")\n emit(\n `${direction} postcheck ${operation.label}`,\n step.postcheck.query\n );\n }\n };\n for (const parent of parents) {\n lines.push(`\\n-- Parent ${parent.fromState ?? \"empty\"}`);\n for (const check of parent.originChecks)\n emit(`Origin check ${check.id}`, check.query);\n operations(\"FORWARD\", parent.operations);\n if (parent.rollback.kind === \"irreversible\")\n lines.push(\n `-- ROLLBACK unavailable: ${parent.rollback.reason.replace(/[\\r\\n\\u2028\\u2029]/g, \" \")}`\n );\n else operations(\"ROLLBACK\", parent.rollback.operations);\n }\n for (const check of destinationChecks)\n emit(`Destination check ${check.id}`, check.query);\n return `${lines.join(\"\\n\\n\")}\\n`;\n}\n","/**\n * Semantic migration storage. Path-level get/put/delete is gone.\n *\n * Readers return raw bytes. Parsers, not drivers, turn those bytes into\n * trusted domain values. Writers promise strongly consistent listing and\n * conditional create.\n */\n\nimport type { Sha256 } from \"../identity\";\n\nexport interface PublishResult {\n readonly outcome: \"created\" | \"identical\";\n}\n\nexport interface MigrationStorageReader {\n readEstate(): Promise<Uint8Array | null>;\n listStates(): Promise<readonly Sha256[]>;\n listSnapshots(): Promise<readonly Sha256[]>;\n listSql(): Promise<readonly Sha256[]>;\n readState(id: Sha256): Promise<Uint8Array | null>;\n readSnapshot(hash: Sha256): Promise<Uint8Array | null>;\n readSql(hash: Sha256): Promise<Uint8Array | null>;\n}\n\nexport interface MigrationStorageWriter extends MigrationStorageReader {\n publishEstate(bytes: Uint8Array): Promise<PublishResult>;\n publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n}\n\nconst READER_METHODS = [\n \"readEstate\",\n \"listStates\",\n \"listSnapshots\",\n \"listSql\",\n \"readState\",\n \"readSnapshot\",\n \"readSql\",\n] as const;\n\nconst WRITER_METHODS = [\n \"publishEstate\",\n \"publishSnapshot\",\n \"publishSql\",\n \"publishState\",\n] as const;\n\nexport function isMigrationStorageReader(\n value: unknown\n): value is MigrationStorageReader {\n return hasStorageMethods(value, READER_METHODS);\n}\n\nexport function isMigrationStorageWriter(\n value: MigrationStorageReader\n): value is MigrationStorageWriter {\n return hasStorageMethods(value, WRITER_METHODS);\n}\n\nfunction hasStorageMethods(\n value: unknown,\n methods: readonly string[]\n): boolean {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return methods.every(\n (method) => typeof Reflect.get(value, method) === \"function\"\n );\n}\n","/**\n * V1 generation: one new state from parent leaves, published atomically.\n * Snapshot and SQL are published before the state manifest.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport { allRules } from \"../schema/validation/rules\";\nimport {\n resolveSchemaOrThrow,\n validateResolvedSchemaOrThrow,\n} from \"../schema/validation/validator\";\nimport {\n assertManualStepwiseProof,\n compileGeneratedTransition,\n compileManualTransition,\n compileTrustedCheck,\n hashParent,\n rebindChecks,\n rebindDispatches,\n rebindRollback,\n sealParent,\n} from \"./compile\";\nimport { type DiffOptions, diff } from \"./differ\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { normalizeGenerateOptions } from \"./generate-input\";\nimport { loadMigrationGraph, type MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { renderMigrationReview } from \"./public-view\";\nimport {\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n resolveEnumValueRemovalMappings,\n} from \"./push/enum-removals\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport {\n callbackAsResolver,\n rejectAllResolver,\n resolveAmbiguousChanges,\n strictResolver,\n} from \"./resolver\";\nimport {\n assertMigrationDecimalDomainsFitProvider,\n serializeResolvedModels,\n} from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { isMigrationStorageWriter } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport type { DiffOperation } from \"./types\";\nimport { generateMigrationName, prepareSchemaProgram } from \"./utils\";\nimport {\n encodeEstateDescriptor,\n encodeSnapshot,\n encodeStateManifest,\n parseEstateDescriptor,\n} from \"./v1-parse\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationBooleanCheckV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface GenerateV1Result {\n readonly outcome: \"published\" | \"preview\" | \"noop\";\n readonly stateId: Sha256 | null;\n readonly name: string | null;\n readonly estateHash: Sha256 | null;\n readonly snapshotHash: Sha256 | null;\n readonly sqlHash: Sha256 | null;\n readonly operations: readonly DiffOperation[];\n readonly warnings: readonly string[];\n readonly operationsByParent: readonly {\n readonly fromState: string | null;\n readonly operations: readonly DiffOperation[];\n }[];\n readonly sql: string;\n readonly reviewSql: string;\n}\n\nconst AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS: DiffOptions = {\n compareDateTimeDeclarations: true,\n};\n\nexport async function generateV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: GenerateV1Options = {}\n): Promise<GenerateV1Result> {\n const request = normalizeGenerateOptions(options);\n if (!isMigrationStorageWriter(storage)) {\n throw new MigrationError(\n \"generate requires a storage writer\",\n VibORMErrorCode.MIGRATION_STORAGE_REQUIRED\n );\n }\n hydrateSchemaNames(client.$schema);\n const relations = request.skipValidation\n ? resolveSchemaOrThrow(client.$schema)\n : validateResolvedSchemaOrThrow(client.$schema, allRules);\n const driver = getPushMigrationDriver(client);\n assertMigrationDecimalDomainsFitProvider(client.$schema, driver.dialect);\n let estateBytes = await storage.readEstate();\n if (!estateBytes) {\n const encoded = encodeEstateDescriptor(driver.target);\n estateBytes = encoded.bytes;\n }\n const publishedEstate = await storage.readEstate();\n if (publishedEstate) estateBytes = publishedEstate;\n const { estateHash, descriptor } = parseEstateDescriptor(estateBytes);\n assertEstateTargetMatches(descriptor.target, driver.target);\n const loaded = publishedEstate\n ? await loadMigrationGraph(storage)\n : emptyGraph(estateHash, descriptor);\n\n const desired = serializeResolvedModels(client.$schema, driver, relations);\n const desiredEncoded = encodeSnapshot(desired);\n const parents = resolveParents(loaded, request);\n refuseUnprovedMerge(loaded, parents, request.manualMigration);\n\n const assembly = new SqlAssembly();\n const parentBodies: Omit<MigrationParentTransitionV1, \"transitionHash\">[] =\n [];\n const reported: DiffOperation[] = [];\n const warnings: string[] = [];\n const operationsByParent: {\n fromState: string | null;\n operations: DiffOperation[];\n }[] = [];\n const destinationPlaceholders: MigrationBooleanCheckV1[] = [];\n\n if (request.manualMigration) {\n assertManualParents(loaded, request.manualMigration.transitions);\n for (const transition of request.manualMigration.transitions) {\n const compiled = compileManualTransition(\n transition.up,\n transition.rollback,\n driver.target.dialect,\n transition.execution,\n transition.originChecks,\n assembly\n );\n parentBodies.push(sealParent(transition.from, compiled));\n }\n for (const [index, check] of (\n request.manualMigration.destinationChecks ?? []\n ).entries()) {\n destinationPlaceholders.push(\n compileTrustedCheck(\n check,\n driver.target.dialect,\n assembly,\n `destination:${index}`\n )\n );\n }\n for (const compiled of parentBodies) {\n assertManualStepwiseProof(\n {\n operations: compiled.operations,\n rollback: compiled.rollback,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n atomicity: compiled.requestedForwardBoundary ?? \"transactional\",\n },\n destinationPlaceholders\n );\n }\n } else {\n for (const from of parents) {\n const current =\n from === null\n ? emptyManagedSnapshot()\n : (loaded.snapshots.get(loaded.states.get(from)!.snapshotHash) ??\n emptyManagedSnapshot());\n const diffOptions = {\n ...AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS,\n projectRename: driver.projectNativeRename.bind(driver),\n refuseConstraintNameChurn:\n driver.capabilities.introspectionReadsConstraintNames,\n };\n const diffed = await diff(current, desired, diffOptions);\n const resolved = await resolveAmbiguousChanges(\n diffed,\n current,\n desired,\n request.resolve ? callbackAsResolver(request.resolve) : strictResolver,\n diffOptions\n );\n const enumMappings = await resolveEnumValueRemovalMappings(\n detectEnumValueRemovals(resolved, current),\n request.resolve ?? rejectAllResolver,\n false\n );\n const withEnumMappings = resolved.map((operation) =>\n operation.type === \"alterEnum\"\n ? applyResolvedEnumMappings([operation], enumMappings)[0]!\n : operation\n );\n const staged = prepareSchemaProgram(withEnumMappings, current, driver);\n reported.push(...staged);\n operationsByParent.push({ fromState: from, operations: staged });\n const compiled = compileGeneratedTransition(\n staged,\n driver,\n \"artifact\",\n current,\n desired,\n assembly\n );\n warnings.push(...(compiled.warnings ?? []));\n if (compiled.rollback.kind === \"irreversible\")\n warnings.push(compiled.rollback.reason);\n parentBodies.push(sealParent(from, compiled));\n }\n }\n\n const sealed = assembly.seal();\n const named = request.name?.trim() || generateMigrationName(reported);\n assertArtifactExecutionSafe(\n sealed.dispatches.map((dispatch) => sliceDispatch(sealed.bytes, dispatch)),\n driver.target.dialect,\n named\n );\n\n const hashedParents = parentBodies\n .map((parent) => ({\n ...parent,\n originChecks: rebindChecks(parent.originChecks, sealed.dispatches),\n operations: rebindDispatches(parent.operations, sealed.dispatches),\n rollback: rebindRollback(parent.rollback, sealed.dispatches),\n }))\n .map((parent) => hashParent(parent));\n\n const singleParent = parents.length === 1;\n const unchangedSnapshot =\n singleParent &&\n parents[0] !== null &&\n loaded.states.get(parents[0]!)?.snapshotHash ===\n desiredEncoded.snapshotHash;\n const emptyProgram = hashedParents.every((parent) =>\n parent.operations.every((operation) => operation.steps.length === 0)\n );\n if (!request.manualMigration && unchangedSnapshot && emptyProgram) {\n return {\n outcome: \"noop\",\n stateId: null,\n name: null,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: null,\n operations: [],\n warnings: [],\n operationsByParent: [],\n sql: \"\",\n reviewSql: \"\",\n };\n }\n\n const withoutId: Omit<MigrationStateManifestV1, \"stateId\"> = {\n format: \"1\",\n estateHash,\n name: named,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n destinationChecks: rebindChecks(destinationPlaceholders, sealed.dispatches),\n parents: hashedParents,\n };\n const encoded = encodeStateManifest(withoutId);\n const sqlText = new TextDecoder().decode(sealed.bytes);\n const reviewSql = renderMigrationReview(\n hashedParents,\n rebindChecks(destinationPlaceholders, sealed.dispatches),\n sealed.bytes\n );\n if (request.dryRun) {\n return {\n outcome: \"preview\",\n stateId: encoded.stateId,\n name: named,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n operations: reported,\n warnings,\n operationsByParent,\n sql: sqlText,\n reviewSql,\n };\n }\n\n if (!publishedEstate) {\n await storage.publishEstate(estateBytes);\n }\n await storage.publishSnapshot(\n desiredEncoded.snapshotHash,\n desiredEncoded.bytes\n );\n await storage.publishSql(sealed.sqlHash, sealed.bytes);\n await storage.publishState(encoded.stateId, encoded.bytes);\n return {\n outcome: \"published\",\n stateId: encoded.stateId,\n name: named,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n operations: reported,\n warnings,\n operationsByParent,\n sql: sqlText,\n reviewSql,\n };\n}\n\nfunction assertManualParents(\n graph: MigrationGraph,\n transitions: readonly ManualTransitionInput[]\n): void {\n const seen = new Set<string>();\n for (const transition of transitions) {\n if (transition.from === null) {\n if (graph.states.size > 0) {\n throw new MigrationError(\n \"A second virtual-root transition is refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else if (!graph.states.has(transition.from)) {\n throw new MigrationError(\n `Unknown parent state ${transition.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const key = transition.from ?? \"null\";\n if (seen.has(key)) {\n throw new MigrationError(\n \"A manual migration names a parent more than once\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n seen.add(key);\n }\n}\n\nfunction resolveParents(\n graph: MigrationGraph,\n options: GenerateV1Options\n): Array<Sha256 | null> {\n if (options.from !== undefined) {\n if (options.from === null) {\n if (graph.states.size > 0) {\n throw new MigrationError(\n \"A second virtual-root transition is refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return [null];\n }\n if (!graph.states.has(options.from)) {\n throw new MigrationError(\n `Unknown parent state ${options.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return [options.from];\n }\n if (graph.states.size === 0) return [null];\n if (graph.leaves.length === 1) return [graph.leaves[0]!];\n if (graph.leaves.length === 0) return [null];\n return [...graph.leaves];\n}\n\nfunction emptyGraph(\n estateHash: Sha256,\n descriptor: ReturnType<typeof parseEstateDescriptor>[\"descriptor\"]\n): MigrationGraph {\n return {\n estateHash,\n descriptor,\n states: new Map(),\n snapshots: new Map(),\n sql: new Map(),\n roots: [],\n leaves: [],\n emptySnapshotHash: encodeSnapshot(emptyManagedSnapshot()).snapshotHash,\n };\n}\n\nfunction ancestryHasCustom(\n graph: MigrationGraph,\n stateId: Sha256 | null,\n seen: Set<string> = new Set()\n): boolean {\n if (stateId === null || seen.has(stateId)) return false;\n seen.add(stateId);\n const state = graph.states.get(stateId);\n if (!state) return false;\n for (const transition of state.parents) {\n if (\n transition.operations.some(\n (operation) => operation.origin === \"manual\"\n ) ||\n transition.requestedForwardBoundary !== null\n ) {\n return true;\n }\n if (ancestryHasCustom(graph, transition.fromState, seen)) return true;\n }\n return false;\n}\n\nfunction refuseUnprovedMerge(\n graph: MigrationGraph,\n parents: Array<Sha256 | null>,\n manual: ManualMigrationInput | undefined\n): void {\n if (parents.length < 2 || manual) return;\n for (const parent of parents) {\n if (ancestryHasCustom(graph, parent)) {\n throw new MigrationError(\n \"A custom or data transition cannot be merged structurally; supply manualMigration for every parent\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","/** One hostile-input boundary for the public down() selector. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport type { StateSelector } from \"./v1-types\";\n\nexport interface NormalizedDownOptions {\n readonly steps: number;\n readonly to?: StateSelector;\n readonly dryRun: boolean;\n}\n\nexport function normalizeDownOptions(options: unknown): NormalizedDownOptions {\n const record = snapshotExactRecord(\n options,\n [\"steps\", \"to\", \"dryRun\"],\n \"down options\",\n refuseDownOptions\n );\n const { steps, to, dryRun } = record;\n if (steps !== undefined && to !== undefined) {\n return refuseDownOptions(\"down accepts either steps or to, not both\");\n }\n let normalizedSteps = 1;\n if (steps !== undefined) {\n if (\n typeof steps !== \"number\" ||\n !Number.isSafeInteger(steps) ||\n steps <= 0\n ) {\n return refuseDownOptions(\"down steps must be a positive safe integer\");\n }\n normalizedSteps = steps;\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseDownOptions(\"down dryRun must be a boolean\");\n }\n return Object.freeze({\n steps: normalizedSteps,\n ...(to === undefined ? {} : { to: normalizeStateSelector(to) }),\n dryRun: dryRun === true,\n });\n}\n\nfunction normalizeStateSelector(value: unknown): StateSelector {\n const record = snapshotExactRecord(\n value,\n [\"id\", \"prefix\", \"name\"],\n \"down to\",\n refuseDownOptions\n );\n const keys = Object.keys(record);\n if (keys.length !== 1) {\n return refuseDownOptions(\"down to must contain exactly one selector key\");\n }\n // The sole OWN key. `\"id\" in record` walks the prototype chain, so a polluted\n // Object.prototype.id made `down({ to: { name: \"baseline\" } })` select the\n // inherited id and roll back to the wrong state.\n const [key] = keys;\n if (!key) {\n return refuseDownOptions(\"down to must contain exactly one selector key\");\n }\n const selected = record[key];\n if (typeof selected !== \"string\" || selected.length === 0) {\n return refuseDownOptions(`down to.${key} must be a non-empty string`);\n }\n if (key === \"id\") return { id: selected };\n if (key === \"prefix\") return { prefix: selected };\n return { name: selected };\n}\n\nfunction refuseDownOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/**\n * History-aware reset. One lock. Clear, replay from null, then one marker CAS.\n * Never re-enters applyV1.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { tableExistsProbe } from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n stepStatements,\n} from \"./compile\";\nimport {\n appendLedger,\n casMarker,\n controlTableNames,\n DEFAULT_CONTROL_BASE,\n ensureControlTables,\n markerFromPath,\n readControlState,\n refuseIncompatibleHistory,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n evaluateAllChecks,\n executeExactSql,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n selectRoute,\n} from \"./graph\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { planLiveNamespaceReset } from \"./live-reset\";\nimport {\n mayWrapTransaction,\n resolveCommandDriver,\n runSequentialProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport { encodeSqlText } from \"./sql-blob\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport { encodeDispatchIdentity, encodeSqlBlob, eventIdFor } from \"./v1-parse\";\nimport type {\n LedgerEventV1,\n MigrationDispatchV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n MigrationStateManifestV1,\n ResetPlanV1,\n ResetV1Options,\n} from \"./v1-types\";\n\nexport async function resetV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: ResetV1Options = {}\n): Promise<{\n readonly preview: boolean;\n readonly path: readonly Sha256[];\n readonly tables?: readonly string[];\n}> {\n const graph = await loadMigrationGraph(storage);\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n const dryRun = options.dryRun === true;\n admitLiveMigrationCapability(\n driver,\n dryRun ? \"read-only\" : \"effectful\",\n \"reset()\"\n );\n if (dryRun) {\n const command = await resolveCommandDriver(client.$driver, driver);\n await command.preflightSchemaRequirements(\n path.map((stateId) => requireStateSnapshot(graph, stateId)),\n (sql, params) => client.$driver._executeRaw(sql, params)\n );\n const names = controlTableNames(DEFAULT_CONTROL_BASE);\n const plan = await planLiveNamespaceReset(client.$driver, command, {\n trackingTable: \"preserve\",\n trackingTableName: names.state,\n preserveTables: [names.log],\n });\n return {\n preview: true,\n path,\n tables: plan.dropTables.map((table) => table.name),\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const names = controlTableNames(DEFAULT_CONTROL_BASE);\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n const open = unfinishedAttempts(ledger);\n const resetAttempt =\n open.length === 1 && open[0]!.kind === \"reset-started\"\n ? open[0]!\n : undefined;\n if (open.length > 0 && !resetAttempt) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking reset\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const targetIdentity = `${command.target.dialect}:${command.namespace ?? \"\"}`;\n const storedResetPlan = resetAttempt\n ? matchingResetPlan(resetAttempt, graph, target, path, targetIdentity)\n : undefined;\n if (!resetAttempt) {\n refuseIncompatibleHistory(marker, ledger);\n }\n const targetSnapshot = requireStateSnapshot(graph, target);\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, marker?.stateId ?? null),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n if (resetAttempt && storedResetPlan && marker) {\n const targetState = graph.states.get(target);\n if (\n targetState &&\n resetMarkerProvesApplied(\n marker,\n graph,\n target,\n path,\n storedResetPlan\n ) &&\n (await fingerprintLive(\n await introspectManaged(pinned, command),\n command,\n pinned\n )) === (await fingerprintLive(targetSnapshot, command, pinned))\n ) {\n const applied = {\n format: \"1\" as const,\n attemptId: resetAttempt.attemptId,\n kind: \"reset-applied\" as const,\n estateHash: graph.estateHash,\n snapshotHash: marker.snapshotHash,\n sqlHash: null,\n fromState: resetAttempt.fromState,\n toState: target,\n transitionHash: null,\n direction: \"reset\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"committed\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(pinned, command, DEFAULT_CONTROL_BASE, {\n ...applied,\n eventId: eventIdFor(applied),\n });\n return { preview: false, path };\n }\n }\n if (\n resetAttempt &&\n storedResetPlan &&\n !resetSourceMarkerMatches(\n marker,\n resetAttempt,\n storedResetPlan,\n graph.emptySnapshotHash\n )\n ) {\n throw new MigrationError(\n \"The unfinished reset source marker no longer matches its plan\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n const hasReplayEvidence = resetAttempt\n ? ledger.some(\n (event) =>\n event.attemptId === resetAttempt.attemptId &&\n event.kind === \"reset-step-confirmed\" &&\n (event.fromState !== null ||\n event.toState !== null ||\n event.transitionHash !== null ||\n event.operationId !== null)\n )\n : false;\n const livePlan = hasReplayEvidence\n ? undefined\n : await planLiveNamespaceReset(pinned, command, {\n trackingTable: \"preserve\",\n trackingTableName: names.state,\n preserveTables: [names.log],\n });\n const clearSql = livePlan\n ? [\n ...livePlan.dropForeignKeys,\n ...livePlan.dropTables.map((table) => table.sql),\n ...livePlan.dropEnums,\n ]\n : [];\n const clearDispatches = clearSql.map((sql) => dispatchForClearSql(sql));\n if (\n livePlan &&\n command.target.dialect === \"mysql\" &&\n (livePlan.dropForeignKeys.length > 0 || livePlan.dropEnums.length > 0)\n ) {\n throw new MigrationError(\n \"Stepwise reset refuses clear dispatches without driver-owned pre/post proof\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n const planBody = {\n estateHash: graph.estateHash,\n targetIdentity,\n sourceRevision: marker?.revision ?? 0,\n sourceFingerprint: marker?.snapshotHash ?? graph.emptySnapshotHash,\n replayPath: path,\n clearDispatches,\n referencedStates: path,\n };\n const stored = storedResetPlan;\n if (stored && livePlan) {\n assertStoredResetPlan(stored, planBody);\n }\n const resetPlanHash = stored\n ? stored.resetPlanHash\n : domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(planBody));\n const plan: ResetPlanV1 = stored ?? { ...planBody, resetPlanHash };\n const prepared = prepareResetReplay(\n pinned.supportsTransactions,\n command,\n graph,\n path\n );\n const remaining = resetAttempt\n ? remainingResetReplay(graph, prepared, resetAttempt, plan, ledger)\n : prepared;\n const started = resetAttempt\n ? undefined\n : {\n format: \"1\" as const,\n attemptId: resetPlanHash,\n kind: \"reset-started\" as const,\n estateHash: graph.estateHash,\n snapshotHash: graph.states.get(target)!.snapshotHash,\n sqlHash: null,\n fromState: marker?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"reset\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"none\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: null,\n toolVersion: \"v1\",\n resetPlan: plan,\n failure: null,\n };\n const begin =\n started || needsBootstrap\n ? async (producer: Parameters<typeof appendLedger>[0]) => {\n if (needsBootstrap) {\n await ensureControlTables(\n producer,\n command,\n DEFAULT_CONTROL_BASE\n );\n }\n if (started) {\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...started,\n eventId: eventIdFor(started),\n });\n }\n }\n : undefined;\n const finish = async (producer: Parameters<typeof appendLedger>[0]) => {\n const live = await introspectManaged(producer, command);\n const expected = graph.snapshots.get(\n graph.states.get(target)!.snapshotHash\n );\n if (\n !expected ||\n (await fingerprintLive(live, command, producer)) !==\n (await fingerprintLive(expected, command, producer))\n ) {\n throw new MigrationError(\n \"Reset replay did not reach the target snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const edges = path.map((stateId, index) => ({\n stateId,\n transitionHash: parentTransition(\n graph,\n index === 0 ? null : path[index - 1]!,\n stateId\n ).transitionHash,\n baselineBoundary: false,\n }));\n const next = markerFromPath(\n graph.estateHash,\n graph.states.get(target)!.snapshotHash,\n edges,\n (marker?.revision ?? 0) + 1\n );\n await casMarker(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n marker\n ? { revision: marker.revision, pathHash: marker.pathHash }\n : null,\n next\n );\n const applied = {\n format: \"1\" as const,\n attemptId: resetPlanHash,\n kind: \"reset-applied\" as const,\n estateHash: graph.estateHash,\n snapshotHash: next.snapshotHash,\n sqlHash: null,\n fromState: marker?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"reset\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"committed\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...applied,\n eventId: eventIdFor(applied),\n });\n };\n const run = async (producer: Parameters<typeof appendLedger>[0]) => {\n await executeResetProgram(\n pinned,\n producer,\n command,\n graph,\n livePlan,\n plan,\n remaining,\n resetPlanHash,\n begin,\n finish\n );\n };\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, run);\n } else {\n await run(pinned);\n }\n return { preview: false, path };\n }\n );\n}\n\nfunction matchingResetPlan(\n attempt: LedgerEventV1,\n graph: MigrationGraph,\n target: Sha256,\n path: readonly Sha256[],\n targetIdentity: string\n): ResetPlanV1 {\n const targetState = graph.states.get(target);\n const plan = attempt.resetPlan;\n const sourceSnapshotHash =\n attempt.fromState === null\n ? graph.emptySnapshotHash\n : graph.states.get(attempt.fromState)?.snapshotHash;\n if (\n !(targetState && plan) ||\n attempt.direction !== \"reset\" ||\n attempt.attemptId !== plan.resetPlanHash ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== targetState.snapshotHash ||\n attempt.toState !== target ||\n plan.estateHash !== graph.estateHash ||\n plan.targetIdentity !== targetIdentity ||\n plan.sourceFingerprint !== sourceSnapshotHash ||\n !sameIds(plan.replayPath, path) ||\n !sameIds(plan.referencedStates, path)\n ) {\n throw new MigrationError(\n \"The unfinished reset does not match the requested reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return plan;\n}\n\nfunction resetMarkerProvesApplied(\n marker: MigrationMarkerV1,\n graph: MigrationGraph,\n target: Sha256,\n path: readonly Sha256[],\n plan: ResetPlanV1\n): boolean {\n const targetState = graph.states.get(target);\n if (!targetState) return false;\n const edges = path.map((stateId, index) => ({\n stateId,\n transitionHash: parentTransition(\n graph,\n index === 0 ? null : path[index - 1]!,\n stateId\n ).transitionHash,\n baselineBoundary: false,\n }));\n const expected = markerFromPath(\n graph.estateHash,\n targetState.snapshotHash,\n edges,\n plan.sourceRevision + 1\n );\n return (\n marker.estateHash === expected.estateHash &&\n marker.stateId === expected.stateId &&\n marker.snapshotHash === expected.snapshotHash &&\n marker.pathHash === expected.pathHash &&\n marker.revision === expected.revision\n );\n}\n\nfunction resetSourceMarkerMatches(\n marker: MigrationMarkerV1 | null,\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n emptySnapshotHash: Sha256\n): boolean {\n return marker\n ? marker.stateId === attempt.fromState &&\n marker.revision === plan.sourceRevision &&\n marker.snapshotHash === plan.sourceFingerprint\n : attempt.fromState === null &&\n plan.sourceRevision === 0 &&\n plan.sourceFingerprint === emptySnapshotHash;\n}\n\nfunction assertStoredResetPlan(\n stored: ResetPlanV1,\n live: Omit<ResetPlanV1, \"resetPlanHash\">\n): void {\n if (stored.estateHash !== live.estateHash) {\n throw new MigrationError(\n \"A stored reset plan does not match the current estate\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (stored.targetIdentity !== live.targetIdentity) {\n throw new MigrationError(\n \"A stored reset plan does not match the current target\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n stored.sourceRevision !== live.sourceRevision ||\n stored.sourceFingerprint !== live.sourceFingerprint\n ) {\n throw new MigrationError(\n \"A stored reset plan does not match the current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (!sameIds(stored.replayPath, live.replayPath)) {\n throw new MigrationError(\n \"A stored reset plan does not match the requested replay path\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const storedIds = new Set(\n stored.clearDispatches.map((dispatch) => dispatch.dispatchId)\n );\n for (const dispatch of live.clearDispatches) {\n if (!storedIds.has(dispatch.dispatchId)) {\n throw new MigrationError(\n \"Live remaining reset clears are not in the stored reset plan\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n}\n\nfunction sameIds(left: readonly Sha256[], right: readonly Sha256[]): boolean {\n if (left.length !== right.length) return false;\n return left.every((id, index) => id === right[index]);\n}\n\nfunction dispatchForClearSql(sql: string): MigrationDispatchV1 {\n const bytes = encodeSqlText(sql);\n const sqlHash = encodeSqlBlob(bytes);\n return {\n dispatchId: encodeDispatchIdentity(sqlHash, 0, bytes.length, []),\n sqlHash,\n offset: 0,\n length: bytes.length,\n parameters: [],\n };\n}\n\nasync function executeResetClear(\n pinned: Parameters<typeof executeExactSql>[0],\n command: Parameters<typeof planLiveNamespaceReset>[1],\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>>,\n attemptId: Sha256,\n graph: MigrationGraph\n): Promise<void> {\n for (const sql of livePlan.dropForeignKeys) {\n await executeExactSql(pinned, sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n for (const table of livePlan.dropTables) {\n const pre = tableExistsProbe(command, table.name, true);\n const post = tableExistsProbe(command, table.name, false);\n if (!(await evaluateProbe(pinned, pre))) {\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n continue;\n }\n await executeExactSql(pinned, table.sql);\n if (!(await evaluateProbe(pinned, post))) {\n throw new MigrationError(\n `Reset clear did not drop table ${table.name}`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n );\n }\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n }\n for (const sql of livePlan.dropEnums) {\n await executeExactSql(pinned, sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n}\n\nasync function evaluateProbe(\n pinned: Parameters<typeof executeExactSql>[0],\n probe: ReturnType<typeof tableExistsProbe>\n): Promise<boolean> {\n const result = await pinned._executeRaw<Record<string, unknown>>(\n probe.sql,\n probe.parameters.map((parameter) =>\n parameter.kind === \"string\" ? parameter.value : null\n )\n );\n const value = Object.values(result.rows[0] ?? {})[0];\n return (\n (value === true || value === 1 || value === \"1\" || value === \"t\") ===\n probe.equals\n );\n}\n\nasync function confirmResetStep(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n sql: string\n): Promise<void> {\n await confirmResetDispatch(\n pinned,\n command,\n graph,\n attemptId,\n dispatchForClearSql(sql)\n );\n}\n\nasync function confirmResetDispatch(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n dispatch: MigrationDispatchV1\n): Promise<void> {\n const event = {\n format: \"1\" as const,\n attemptId,\n kind: \"reset-step-confirmed\" as const,\n estateHash: graph.estateHash,\n snapshotHash: graph.emptySnapshotHash,\n sqlHash: dispatch.sqlHash,\n fromState: null,\n toState: null,\n transitionHash: null,\n direction: \"reset\" as const,\n operationId: null,\n dispatchId: dispatch.dispatchId,\n effectState: \"committed\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(pinned, command, DEFAULT_CONTROL_BASE, {\n ...event,\n eventId: eventIdFor(event),\n });\n}\n\ninterface PreparedResetReplayEdge {\n readonly from: Sha256 | null;\n readonly to: Sha256;\n readonly transition: ReturnType<typeof parentTransition>;\n readonly state: MigrationStateManifestV1;\n readonly blob: Uint8Array;\n readonly boundary: \"transactional\" | \"stepwise\";\n readonly operations: readonly MigrationOperationV1[];\n}\n\nfunction prepareResetReplay(\n supportsTransactions: boolean,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n path: readonly Sha256[]\n): readonly PreparedResetReplayEdge[] {\n return path.map((to, index) => {\n const from = index === 0 ? null : path[index - 1]!;\n const transition = parentTransition(graph, from, to);\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n \"Reset replay target is missing\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const blob = graph.sql.get(state.sqlHash);\n if (!blob) {\n throw new MigrationError(\n \"Reset replay SQL blob is missing\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n assertTransactionalBoundaryHonored(\n supportsTransactions,\n transition.requestedForwardBoundary\n );\n return {\n from,\n to,\n transition,\n state,\n blob,\n boundary,\n operations: transition.operations,\n };\n });\n}\n\nfunction remainingResetReplay(\n graph: MigrationGraph,\n prepared: readonly PreparedResetReplayEdge[],\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n ledger: readonly LedgerEventV1[]\n): readonly PreparedResetReplayEdge[] {\n const clearByDispatch = new Map(\n plan.clearDispatches.map((dispatch, index) => [dispatch.dispatchId, index])\n );\n const clearCommitted = new Set<number>();\n const steps = prepared.flatMap((edge, edgeIndex) =>\n edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ edge, edgeIndex, operation, step }))\n )\n );\n const byDispatch = new Map(\n steps.map((entry, index) => [entry.step.execute.dispatchId, index])\n );\n const completed = new Set<number>();\n const announced = new Set<number>();\n let hasReplayEvidence = false;\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"reset-step-confirmed\"\n ) {\n continue;\n }\n if (\n event.direction !== \"reset\" ||\n event.estateHash !== graph.estateHash ||\n !event.dispatchId\n ) {\n refuseResetProgress(\n \"Reset progress does not match its authenticated plan\"\n );\n }\n const isClear =\n event.fromState === null &&\n event.toState === null &&\n event.transitionHash === null &&\n event.operationId === null;\n if (isClear) {\n const clearIndex = clearByDispatch.get(event.dispatchId);\n if (\n clearIndex === undefined ||\n event.sqlHash !== plan.clearDispatches[clearIndex]!.sqlHash ||\n event.snapshotHash !== graph.emptySnapshotHash ||\n event.effectState !== \"committed\"\n ) {\n refuseResetProgress(\"Reset clear progress names an unknown dispatch\");\n }\n clearCommitted.add(clearIndex);\n continue;\n }\n hasReplayEvidence = true;\n const index = byDispatch.get(event.dispatchId);\n if (index === undefined) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n const entry = steps[index];\n if (\n !entry ||\n event.fromState !== entry.edge.from ||\n event.toState !== entry.edge.to ||\n event.transitionHash !== entry.edge.transition.transitionHash ||\n event.snapshotHash !== entry.edge.state.snapshotHash ||\n event.sqlHash !== entry.edge.state.sqlHash ||\n event.operationId !== entry.operation.id\n ) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n if (event.effectState === \"committed\") {\n completed.add(index);\n } else if (event.effectState === \"none\") {\n if (entry.step.retry === \"proven\") completed.add(index);\n else announced.add(index);\n } else {\n throw new MigrationError(\n \"Reset replay progress has an ambiguous commit outcome\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n );\n }\n }\n assertContiguousPrefix(\n clearCommitted,\n \"Reset clear progress is not a contiguous dispatch prefix\"\n );\n if (\n hasReplayEvidence &&\n clearCommitted.size !== plan.clearDispatches.length\n ) {\n refuseResetProgress(\n \"Reset replay progress exists before the clear prefix is complete\"\n );\n }\n if (!hasReplayEvidence) return prepared;\n const completedCount = contiguousPrefixLength(completed);\n if ([...completed].some((index) => index >= completedCount)) {\n refuseResetProgress(\n \"Reset replay progress is not a contiguous dispatch prefix\"\n );\n }\n if (\n [...announced].some(\n (index) => !completed.has(index) && index !== completedCount\n )\n ) {\n refuseResetProgress(\"Reset replay progress is not contiguous\");\n }\n const next = steps[completedCount];\n if (\n next?.step.retry === \"opaque\" &&\n next.edge.boundary === \"stepwise\" &&\n announced.has(completedCount)\n ) {\n throw new MigrationError(\n \"The next reset dispatch has an ambiguous commit outcome\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n lastConfirmedStep: next.step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n const verificationEdge =\n completedCount === 0 ? undefined : steps[completedCount - 1]?.edgeIndex;\n let skipped = completedCount;\n return prepared.flatMap((edge, edgeIndex) => {\n const operationCount = edge.operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n if (skipped >= operationCount) {\n skipped -= operationCount;\n return edgeIndex === verificationEdge\n ? [{ ...edge, operations: [] }]\n : [];\n }\n const operations = sliceOperations(edge.operations, skipped);\n skipped = 0;\n return [{ ...edge, operations }];\n });\n}\n\nfunction sliceOperations(\n operations: readonly MigrationOperationV1[],\n skip: number\n): readonly MigrationOperationV1[] {\n let remaining = skip;\n return operations.flatMap((operation) => {\n if (remaining >= operation.steps.length) {\n remaining -= operation.steps.length;\n return [];\n }\n const steps = operation.steps.slice(remaining);\n remaining = 0;\n return [{ ...operation, steps }];\n });\n}\n\nfunction contiguousPrefixLength(indices: ReadonlySet<number>): number {\n let length = 0;\n while (indices.has(length)) length += 1;\n return length;\n}\n\nfunction assertContiguousPrefix(\n indices: ReadonlySet<number>,\n message: string\n): void {\n const length = contiguousPrefixLength(indices);\n if ([...indices].some((index) => index >= length)) {\n refuseResetProgress(message);\n }\n}\n\nfunction refuseResetProgress(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_CORRUPTION);\n}\n\nasync function executeResetProgram(\n pinned: Parameters<typeof executeOperations>[0],\n producer: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n plan: ResetPlanV1,\n replay: readonly PreparedResetReplayEdge[],\n attemptId: Sha256,\n beforeFirstEffect:\n | ((producer: Parameters<typeof appendLedger>[0]) => Promise<void>)\n | undefined,\n finish: (producer: Parameters<typeof appendLedger>[0]) => Promise<void>\n): Promise<void> {\n const groups = groupContiguousAtomicity(replay, ({ blob, operations }) =>\n stepStatements(blob, operations)\n );\n const liveClearDispatches = new Set(\n livePlan\n ? [\n ...livePlan.dropForeignKeys,\n ...livePlan.dropTables.map((table) => table.sql),\n ...livePlan.dropEnums,\n ].map((sql) => dispatchForClearSql(sql).dispatchId)\n : []\n );\n let clearPending =\n livePlan &&\n (livePlan.dropForeignKeys.length > 0 ||\n livePlan.dropTables.length > 0 ||\n livePlan.dropEnums.length > 0)\n ? livePlan\n : undefined;\n let clearEvidencePending = livePlan !== undefined;\n let admissionPending = beforeFirstEffect;\n const runBoundary = async (\n boundary: \"transactional\" | \"stepwise\",\n body: (target: Parameters<typeof appendLedger>[0]) => Promise<void>\n ) => {\n if (\n mayWrapTransaction(\n pinned,\n command.target.dialect,\n boundary === \"transactional\"\n )\n ) {\n await pinned.withTransaction(body);\n } else {\n await body(producer);\n }\n };\n const completeClearEvidence = async (\n target: Parameters<typeof appendLedger>[0]\n ) => {\n for (const dispatch of plan.clearDispatches) {\n if (!liveClearDispatches.has(dispatch.dispatchId)) {\n await confirmResetDispatch(target, command, graph, attemptId, dispatch);\n }\n }\n };\n const admit = async (target: Parameters<typeof appendLedger>[0]) => {\n const pending = admissionPending;\n if (!pending) return;\n admissionPending = undefined;\n await pending(target);\n };\n if (clearPending && groups[0]?.boundary === \"stepwise\") {\n const clear = clearPending;\n clearPending = undefined;\n await runBoundary(\"transactional\", async (target) => {\n await admit(target);\n await executeResetClear(target, command, clear, attemptId, graph);\n await completeClearEvidence(target);\n clearEvidencePending = false;\n });\n }\n if (!clearPending && groups[0]?.boundary === \"stepwise\" && admissionPending) {\n await runBoundary(\"transactional\", admit);\n }\n if (groups.length === 0) {\n await runBoundary(\"transactional\", async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph\n );\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n await finish(target);\n });\n return;\n }\n for (const [index, group] of groups.entries()) {\n await runBoundary(group.boundary, async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph\n );\n clearPending = undefined;\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n for (const edge of group.items) {\n await executeResetReplayEdge(target, command, graph, edge, attemptId);\n }\n if (index === groups.length - 1) await finish(target);\n });\n }\n}\n\nasync function executeResetReplayEdge(\n pinned: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n edge: PreparedResetReplayEdge,\n attemptId: Sha256\n): Promise<void> {\n const { from, to, transition, state, blob, boundary, operations } = edge;\n await executeOperations(\n pinned,\n blob,\n operations,\n boundary,\n async (progress, effect) => {\n const event = {\n format: \"1\" as const,\n attemptId,\n kind: \"reset-step-confirmed\" as const,\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n direction: \"reset\" as const,\n operationId: progress.operationId,\n dispatchId: progress.dispatchId,\n effectState: effect,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(pinned, command, DEFAULT_CONTROL_BASE, {\n ...event,\n eventId: eventIdFor(event),\n });\n },\n command.namespace\n );\n if (\n state.destinationChecks.length > 0 &&\n !(await evaluateAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Reset replay failed destination checks\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n}\n","/**\n * V1 operator commands: status, verify, log, baseline, down, resolve, reset.\n * Status/verify/log are read-only and never bootstrap missing control tables.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { assertNoDrift } from \"./apply-v1\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n stepStatements,\n} from \"./compile\";\nimport {\n appendLedger,\n casMarker,\n DEFAULT_CONTROL_BASE,\n ensureControlTables,\n markerFromPath,\n readControlState,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff } from \"./differ\";\nimport { type NormalizedDownOptions, normalizeDownOptions } from \"./down-input\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { evaluateAllChecks, executeOperations } from \"./execute-dispatch\";\nimport {\n assertForeignKeysIntact,\n liftForeignKeyPragmas,\n withForeignKeysLifted,\n} from \"./foreign-keys\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n selectRoute,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n mayWrapTransaction,\n resolveCommandDriver,\n runSequentialProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport { eventIdFor } from \"./v1-parse\";\nimport type {\n BaselineOptions,\n DownV1Options,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ResolveV1Options,\n} from \"./v1-types\";\n\nexport { resetV1 } from \"./reset-v1\";\n\nexport interface StatusV1Result {\n readonly control: \"absent\" | \"present\";\n readonly marker: MigrationMarkerV1 | null;\n readonly pending: readonly Sha256[];\n readonly unfinished: boolean;\n}\n\nexport async function statusV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<StatusV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, \"read-only\", \"status()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readControlState(\n client.$driver,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n return {\n control: \"absent\",\n marker: null,\n pending: [...graph.roots],\n unfinished: false,\n };\n }\n const { marker, ledger } = control;\n const unfinished = unfinishedAttempts(ledger).length > 0;\n let pending: Sha256[] = [];\n if (graph.leaves.length === 1) {\n const leaf = graph.leaves[0]!;\n if ((marker?.stateId ?? null) !== leaf) {\n pending = [...selectRoute(graph, marker?.stateId ?? null, leaf)];\n }\n }\n return { control: \"present\", marker, pending, unfinished };\n}\n\nexport async function verifyV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<{ readonly ok: boolean }> {\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, \"effectful\", \"verify()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n throw new MigrationError(\n \"verify requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const { marker } = control;\n if (!marker) {\n throw new MigrationError(\n \"verify requires a migration marker\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const markedSnapshot = requireStateSnapshot(graph, marker.stateId);\n await command.preflightSchemaRequirements(\n [markedSnapshot],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n await assertNoDrift(pinned, command, graph, marker);\n return { ok: true };\n }\n );\n}\n\nexport async function logV1(\n client: MigrationClient\n): Promise<readonly LedgerEventV1[]> {\n const driver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(driver, \"read-only\", \"log()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readControlState(\n client.$driver,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n throw new MigrationError(\n \"log requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return control.ledger;\n}\n\nexport async function baselineV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: BaselineOptions\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, \"effectful\", \"baseline()\");\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n if (marker || ledger.length > 0) {\n throw new MigrationError(\n \"baseline requires an unmarked database with an empty ledger\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n for (const [index, stateId] of path.entries()) {\n const from = index === 0 ? null : path[index - 1]!;\n const transition = parentTransition(graph, from, stateId);\n const parentSnapshot =\n from === null\n ? graph.emptySnapshotHash\n : graph.states.get(from)?.snapshotHash;\n const childSnapshot = graph.states.get(stateId)?.snapshotHash;\n if (\n transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" || operation.risk === \"opaque\"\n ) ||\n parentSnapshot === childSnapshot\n ) {\n throw new MigrationError(\n \"baseline refuses a path containing manual, opaque, or data-only transitions\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n const expected = requireStateSnapshot(graph, target);\n await command.preflightSchemaRequirements([expected], (sql, params) =>\n pinned._executeRaw(sql, params)\n );\n const live = await introspectManaged(pinned, command);\n if (\n (await fingerprintLive(live, command, pinned)) !==\n (await fingerprintLive(expected, command, pinned))\n ) {\n throw new MigrationError(\n `baseline requires exact live equality with the target snapshot. Differences: ${JSON.stringify(await diff(live, expected))}`,\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const edges = path.map((stateId, index) => ({\n stateId,\n transitionHash: parentTransition(\n graph,\n index === 0 ? null : path[index - 1]!,\n stateId\n ).transitionHash,\n baselineBoundary: index === 0,\n }));\n const next = markerFromPath(\n graph.estateHash,\n graph.states.get(target)!.snapshotHash,\n edges,\n 1\n );\n const event = {\n format: \"1\" as const,\n attemptId: next.pathHash,\n kind: \"baselined\" as const,\n estateHash: graph.estateHash,\n snapshotHash: next.snapshotHash,\n sqlHash: null,\n fromState: null,\n toState: target,\n transitionHash: null,\n direction: \"baseline\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"none\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n const publish = async (producer: Parameters<typeof casMarker>[0]) => {\n if (needsBootstrap) {\n await ensureControlTables(producer, command, DEFAULT_CONTROL_BASE);\n }\n await casMarker(producer, command, DEFAULT_CONTROL_BASE, null, next);\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...event,\n eventId: eventIdFor(event),\n });\n };\n if (pinned.supportsTransactions) {\n await pinned.withTransaction((transaction) => publish(transaction));\n } else {\n await publish(pinned);\n }\n return { stateId: target };\n }\n );\n}\n\nexport async function downV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: DownV1Options = {}\n): Promise<{ readonly path: readonly Sha256[]; readonly preview: boolean }> {\n const request = normalizeDownOptions(options);\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n const dryRun = request.dryRun;\n admitLiveMigrationCapability(\n driver,\n dryRun ? \"read-only\" : \"effectful\",\n \"down()\"\n );\n if (dryRun) {\n const control = await readControlState(\n client.$driver,\n driver,\n DEFAULT_CONTROL_BASE\n );\n refusePartialControl(control.presence);\n const { marker } = control;\n if (!marker) {\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const removed = rollbackSlice(graph, marker, request);\n return { path: removed.map((edge) => edge.stateId), preview: true };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n refusePartialControl(control.presence);\n const { ledger, marker } = control;\n const open = unfinishedAttempts(ledger);\n if (open.length > 1) {\n throw new MigrationError(\n \"Multiple unfinished migration attempts require manual repair\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const rollbackAttempt = open[0];\n if (\n rollbackAttempt &&\n (rollbackAttempt.kind !== \"started\" ||\n rollbackAttempt.direction !== \"rollback\")\n ) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n if (!marker) {\n if (rollbackAttempt?.toState === null) {\n const item = prepareRollbackAttempt(\n graph,\n command,\n pinned.supportsTransactions,\n rollbackAttempt\n );\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, item.nextState)],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n const close = (producer: Parameters<typeof appendLedger>[0]) =>\n closeCompletedRollback(\n producer,\n command,\n graph,\n item,\n rollbackAttempt,\n ledger,\n null\n );\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, close);\n } else {\n await close(pinned);\n }\n return { path: [item.edge.stateId], preview: false };\n }\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n if (rollbackAttempt?.toState === marker.stateId) {\n const item = prepareRollbackAttempt(\n graph,\n command,\n pinned.supportsTransactions,\n rollbackAttempt\n );\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, item.nextState)],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n const close = (producer: Parameters<typeof appendLedger>[0]) =>\n closeCompletedRollback(\n producer,\n command,\n graph,\n item,\n rollbackAttempt,\n ledger,\n marker\n );\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, close);\n } else {\n await close(pinned);\n }\n return { path: [item.edge.stateId], preview: false };\n }\n const removed = rollbackSlice(graph, marker, request);\n if (removed.length === 0) return { path: [], preview: false };\n const reverse = [...removed].reverse();\n for (const edge of reverse) {\n assertReversibleEdge(graph, edge);\n }\n const prepared = reverse.map((edge) =>\n prepareRollbackEdge(graph, command, pinned.supportsTransactions, edge)\n );\n const rollbackSnapshots = prepared.map((item) =>\n requireStateSnapshot(graph, item.nextState)\n );\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, marker.stateId), ...rollbackSnapshots],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n if (!rollbackAttempt) {\n await assertNoDrift(pinned, command, graph, marker);\n }\n if (rollbackAttempt) {\n const resumed = prepareRollbackAttempt(\n graph,\n command,\n pinned.supportsTransactions,\n rollbackAttempt\n );\n const first = prepared[0]!;\n if (\n resumed.edge.stateId !== first.edge.stateId ||\n resumed.nextState !== first.nextState ||\n resumed.edge.transitionHash !== first.edge.transitionHash\n ) {\n throw new MigrationError(\n \"An unfinished rollback does not match the selected reverse path\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n }\n const run = async (producer: Parameters<typeof appendLedger>[0]) => {\n let current = marker;\n const statementsOf = (item: (typeof prepared)[number]) =>\n stepStatements(item.blob, item.rollback.operations);\n for (const group of groupContiguousAtomicity(prepared, statementsOf)) {\n const statements = group.items.flatMap(statementsOf);\n const lifted = liftForeignKeyPragmas(pinned, statements);\n const executeGroup = async (\n groupProducer: Parameters<typeof appendLedger>[0]\n ) => {\n for (const item of group.items) {\n current = await executeRollbackEdge(\n groupProducer,\n command,\n graph,\n item,\n current,\n item === prepared[0] ? rollbackAttempt : undefined,\n ledger\n );\n }\n };\n if (\n mayWrapTransaction(\n pinned,\n command.target.dialect,\n group.boundary === \"transactional\"\n )\n ) {\n await withForeignKeysLifted(pinned, lifted.bracket, () =>\n pinned.withTransaction(async (transaction) => {\n await executeGroup(transaction);\n await assertForeignKeysIntact(transaction, lifted.bracket);\n })\n );\n } else {\n await executeGroup(producer);\n }\n }\n };\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, run);\n } else {\n await run(pinned);\n }\n return { path: removed.map((edge) => edge.stateId), preview: false };\n }\n );\n}\n\nexport async function resolveV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ResolveV1Options\n): Promise<{ readonly outcome: ResolveV1Options[\"outcome\"] }> {\n const graph = await loadMigrationGraph(storage);\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, \"effectful\", \"resolve()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readControlState(\n pinned,\n command,\n DEFAULT_CONTROL_BASE\n );\n refusePartialControl(control.presence);\n const { ledger } = control;\n const open = unfinishedAttempts(ledger);\n if (open.length !== 1) {\n throw new MigrationError(\n open.length === 0\n ? \"resolve requires an unfinished attempt\"\n : \"resolve requires exactly one unfinished attempt\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const attempt = open[0]!;\n if (attempt.kind === \"reset-started\") {\n throw new MigrationError(\n \"An unfinished reset can only be resumed by reset()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (attempt.direction === \"rollback\") {\n throw new MigrationError(\n \"An unfinished rollback can only be resumed by down()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const to = attempt.toState;\n const from = attempt.fromState;\n if (!to) {\n throw new MigrationError(\n \"Unfinished attempt is missing its target state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n \"Unfinished attempt target is absent from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const blob = graph.sql.get(state.sqlHash);\n if (!blob) {\n throw new MigrationError(\n \"SQL blob is missing\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const transition = parentTransition(graph, from, to);\n const destSnapshot = requireStateSnapshot(graph, to);\n const originSnapshot = requireStateSnapshot(graph, from);\n await command.preflightSchemaRequirements(\n [originSnapshot, destSnapshot],\n (sql, params) => pinned._executeRaw(sql, params)\n );\n const live = await introspectManaged(pinned, command);\n const destHolds =\n (await fingerprintLive(live, command, pinned)) ===\n (await fingerprintLive(destSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace\n ));\n const originHolds =\n (await fingerprintLive(live, command, pinned)) ===\n (await fingerprintLive(originSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n transition.originChecks,\n command.namespace\n ));\n const manualOpaque = transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" &&\n operation.steps.some((step) => step.retry === \"opaque\")\n );\n if (options.outcome === \"complete\") {\n if (\n !destHolds ||\n (manualOpaque && state.destinationChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark complete without destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const finish = (producer: Parameters<typeof appendLedger>[0]) =>\n finishResolve(producer, command, graph, attempt, \"applied\", to);\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, finish);\n } else if (pinned.supportsTransactions) {\n await pinned.withTransaction(finish);\n } else {\n await finish(pinned);\n }\n return { outcome: \"complete\" };\n }\n if (options.outcome === \"rolled-back\") {\n if (\n !originHolds ||\n (manualOpaque && transition.originChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark rolled back without origin proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const finish = (producer: Parameters<typeof appendLedger>[0]) =>\n finishResolve(producer, command, graph, attempt, \"rolled-back\", from);\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, finish);\n } else if (pinned.supportsTransactions) {\n await pinned.withTransaction(finish);\n } else {\n await finish(pinned);\n }\n return { outcome: \"rolled-back\" };\n }\n if (manualOpaque) {\n throw new MigrationError(\n \"resolve cannot retry an opaque dispatch without origin or destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n transition.operations.some((operation) =>\n operation.steps.some((step) => step.retry === \"opaque\")\n ) &&\n !originHolds\n ) {\n throw new MigrationError(\n \"resolve cannot retry a generated structural transition except from the origin\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions,\n transition.requestedForwardBoundary\n );\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n const executeRetry = async (\n producer: Parameters<typeof appendLedger>[0]\n ) => {\n await executeOperations(\n producer,\n blob,\n transition.operations,\n boundary,\n undefined,\n command.namespace\n );\n if (\n !(await evaluateAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Retry did not reach the destination\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const liveAfter = await introspectManaged(producer, command);\n if (\n !destSnapshot ||\n (await fingerprintLive(liveAfter, command, producer)) !==\n (await fingerprintLive(destSnapshot, command, producer))\n ) {\n throw new MigrationError(\n \"Retry did not reach the destination\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n };\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, executeRetry);\n } else if (\n mayWrapTransaction(\n pinned,\n command.target.dialect,\n boundary === \"transactional\"\n )\n ) {\n const statements = stepStatements(blob, transition.operations);\n const lifted = liftForeignKeyPragmas(pinned, statements);\n await withForeignKeysLifted(pinned, lifted.bracket, () =>\n pinned.withTransaction(async (transaction) => {\n await executeRetry(transaction);\n await assertForeignKeysIntact(transaction, lifted.bracket);\n })\n );\n } else {\n await executeRetry(pinned);\n }\n return { outcome: \"retry\" };\n }\n );\n}\n\nasync function finishResolve(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attempt: LedgerEventV1,\n kind: \"applied\" | \"rolled-back\",\n to: Sha256 | null\n): Promise<void> {\n const control = await readControlState(pinned, command, DEFAULT_CONTROL_BASE);\n refusePartialControl(control.presence);\n const { marker } = control;\n if (kind === \"applied\" && to && marker?.stateId !== to) {\n const transition = parentTransition(graph, attempt.fromState, to);\n const nextPath = [\n ...(marker?.path ?? []),\n {\n stateId: to,\n transitionHash: attempt.transitionHash ?? transition.transitionHash,\n baselineBoundary: false,\n },\n ];\n const next = markerFromPath(\n graph.estateHash,\n graph.states.get(to)!.snapshotHash,\n nextPath,\n (marker?.revision ?? 0) + 1\n );\n await casMarker(\n pinned,\n command,\n DEFAULT_CONTROL_BASE,\n marker ? { revision: marker.revision, pathHash: marker.pathHash } : null,\n next\n );\n }\n if (kind === \"rolled-back\" && marker && marker.stateId === attempt.toState) {\n const nextPath = marker.path.slice(0, -1);\n const nextState = nextPath.at(-1)?.stateId ?? null;\n const snapshotHash = nextState\n ? graph.states.get(nextState)!.snapshotHash\n : graph.emptySnapshotHash;\n const next = markerFromPath(\n graph.estateHash,\n snapshotHash,\n nextPath,\n marker.revision + 1\n );\n await casMarker(\n pinned,\n command,\n DEFAULT_CONTROL_BASE,\n {\n revision: marker.revision,\n pathHash: marker.pathHash,\n },\n next\n );\n }\n const event = {\n format: \"1\" as const,\n attemptId: attempt.attemptId,\n kind: \"resolved\" as const,\n estateHash: graph.estateHash,\n snapshotHash: to\n ? graph.states.get(to)!.snapshotHash\n : graph.emptySnapshotHash,\n sqlHash: attempt.sqlHash,\n fromState: attempt.fromState,\n toState: to,\n transitionHash: attempt.transitionHash,\n direction: \"resolve\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"none\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(pinned, command, DEFAULT_CONTROL_BASE, {\n ...event,\n eventId: eventIdFor(event),\n });\n}\n\nfunction prepareRollbackEdge(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n edge: MarkerPathEdgeV1\n) {\n const state = graph.states.get(edge.stateId)!;\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n )!;\n const blob = graph.sql.get(state.sqlHash)!;\n const rollback = parent.rollback;\n if (rollback.kind === \"irreversible\") {\n throw new MigrationError(\n rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n const requested =\n rollback.kind === \"manual\" ? rollback.requestedBoundary : null;\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n return {\n edge,\n state,\n parent,\n blob,\n rollback,\n boundary: classifyStoredAtomicity(\n command,\n requested,\n rollback.operations,\n blob\n ),\n nextState: parent.fromState,\n };\n}\n\nfunction prepareRollbackAttempt(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1\n): ReturnType<typeof prepareRollbackEdge> {\n if (!(attempt.fromState && attempt.transitionHash)) {\n throw new MigrationError(\n \"Unfinished rollback is missing its authenticated edge identity\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const item = prepareRollbackEdge(graph, command, supportsTransactions, {\n stateId: attempt.fromState,\n transitionHash: attempt.transitionHash,\n baselineBoundary: false,\n });\n if (\n attempt.toState !== item.nextState ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== item.state.snapshotHash ||\n attempt.sqlHash !== item.state.sqlHash\n ) {\n throw new MigrationError(\n \"Unfinished rollback does not match an authenticated estate edge\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return item;\n}\n\nasync function executeRollbackEdge(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: ReturnType<typeof prepareRollbackEdge>,\n current: MigrationMarkerV1,\n resume: LedgerEventV1 | undefined,\n ledger: readonly LedgerEventV1[]\n): Promise<MigrationMarkerV1> {\n const { edge, state, parent, blob, rollback, boundary, nextState } = item;\n if (\n current.stateId !== edge.stateId ||\n current.path.at(-1)?.stateId !== edge.stateId ||\n current.path.at(-1)?.transitionHash !== edge.transitionHash\n ) {\n throw new MigrationError(\n \"Rollback marker does not name the authenticated edge being reversed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n if (\n !resume &&\n state.destinationChecks.length > 0 &&\n !(await evaluateAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Destination checks failed before rollback\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const attemptId =\n resume?.attemptId ??\n eventIdFor({\n format: \"1\",\n attemptId: \"0\".repeat(64),\n kind: \"started\",\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n startedAt: new Date().toISOString(),\n finishedAt: null,\n toolVersion: \"v1\",\n failure: null,\n });\n if (!resume) {\n const started = {\n format: \"1\" as const,\n attemptId,\n kind: \"started\" as const,\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"none\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: null,\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...started,\n eventId: eventIdFor(started),\n });\n }\n const operations = resume\n ? remainingRollbackOperations(graph, item, resume, ledger)\n : rollback.operations;\n await executeOperations(\n producer,\n blob,\n operations,\n boundary,\n async (progress, effect) => {\n const confirmed = {\n format: \"1\" as const,\n attemptId,\n kind: \"step-confirmed\" as const,\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\" as const,\n operationId: progress.operationId,\n dispatchId: progress.dispatchId,\n effectState: effect,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...confirmed,\n eventId: eventIdFor(confirmed),\n });\n },\n command.namespace\n );\n if (\n parent.originChecks.length > 0 &&\n !(await evaluateAllChecks(\n producer,\n blob,\n parent.originChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Origin checks failed after rollback\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const snapshotHash = nextState\n ? graph.states.get(nextState)!.snapshotHash\n : graph.emptySnapshotHash;\n const expected =\n graph.snapshots.get(snapshotHash) ??\n (snapshotHash === graph.emptySnapshotHash\n ? emptyManagedSnapshot()\n : undefined);\n const live = await introspectManaged(producer, command);\n if (\n !expected ||\n (await fingerprintLive(live, command, producer)) !==\n (await fingerprintLive(expected, command, producer))\n ) {\n throw new MigrationError(\n \"Rollback did not reach the parent snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const nextPath = current.path.slice(0, -1);\n const next = markerFromPath(\n graph.estateHash,\n snapshotHash,\n nextPath,\n current.revision + 1\n );\n await casMarker(\n producer,\n command,\n DEFAULT_CONTROL_BASE,\n {\n revision: current.revision,\n pathHash: current.pathHash,\n },\n next\n );\n await appendRolledBackEvent(\n producer,\n command,\n graph,\n item,\n attemptId,\n snapshotHash\n );\n return next;\n}\n\nasync function closeCompletedRollback(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: ReturnType<typeof prepareRollbackEdge>,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): Promise<void> {\n remainingRollbackOperations(graph, item, attempt, ledger);\n if (marker ? marker.stateId !== item.nextState : item.nextState !== null) {\n throw new MigrationError(\n \"Rollback marker is neither before nor after the unfinished edge\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n const { parent, blob, nextState } = item;\n if (\n parent.originChecks.length > 0 &&\n !(await evaluateAllChecks(\n producer,\n blob,\n parent.originChecks,\n command.namespace\n ))\n ) {\n throw new MigrationError(\n \"Origin checks failed after rollback\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n const snapshotHash = nextState\n ? graph.states.get(nextState)!.snapshotHash\n : graph.emptySnapshotHash;\n const expected =\n graph.snapshots.get(snapshotHash) ??\n (snapshotHash === graph.emptySnapshotHash\n ? emptyManagedSnapshot()\n : undefined);\n const live = await introspectManaged(producer, command);\n if (\n !expected ||\n (await fingerprintLive(live, command, producer)) !==\n (await fingerprintLive(expected, command, producer))\n ) {\n throw new MigrationError(\n \"Rollback did not reach the parent snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n await appendRolledBackEvent(\n producer,\n command,\n graph,\n item,\n attempt.attemptId,\n snapshotHash\n );\n}\n\nasync function appendRolledBackEvent(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: ReturnType<typeof prepareRollbackEdge>,\n attemptId: Sha256,\n snapshotHash: Sha256\n): Promise<void> {\n const { edge, state, nextState } = item;\n const rolled = {\n format: \"1\" as const,\n attemptId,\n kind: \"rolled-back\" as const,\n estateHash: graph.estateHash,\n snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\" as const,\n operationId: null,\n dispatchId: null,\n effectState: \"committed\" as const,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n toolVersion: \"v1\",\n failure: null,\n };\n await appendLedger(producer, command, DEFAULT_CONTROL_BASE, {\n ...rolled,\n eventId: eventIdFor(rolled),\n });\n}\n\nfunction remainingRollbackOperations(\n graph: MigrationGraph,\n item: ReturnType<typeof prepareRollbackEdge>,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): ReturnType<typeof prepareRollbackEdge>[\"rollback\"][\"operations\"] {\n const steps = item.rollback.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ operation, step }))\n );\n const byDispatch = new Map(\n steps.map(({ step }, index) => [step.execute.dispatchId, index])\n );\n const committed = new Set<number>();\n const announced = new Set<number>();\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"step-confirmed\"\n )\n continue;\n if (\n event.direction !== \"rollback\" ||\n event.estateHash !== graph.estateHash ||\n event.fromState !== item.edge.stateId ||\n event.toState !== item.nextState ||\n event.transitionHash !== item.edge.transitionHash ||\n event.sqlHash !== item.state.sqlHash ||\n !event.dispatchId\n ) {\n throw new MigrationError(\n \"Rollback progress does not match its authenticated edge\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const index = byDispatch.get(event.dispatchId);\n if (\n index === undefined ||\n steps[index]!.operation.id !== event.operationId\n ) {\n throw new MigrationError(\n \"Rollback progress names an unknown dispatch\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (event.effectState === \"committed\") committed.add(index);\n if (event.effectState === \"none\") announced.add(index);\n }\n let completed = 0;\n while (committed.has(completed)) completed += 1;\n if ([...committed].some((index) => index >= completed)) {\n throw new MigrationError(\n \"Rollback progress is not a contiguous dispatch prefix\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const next = steps[completed];\n if (\n next?.step.retry === \"opaque\" &&\n item.boundary === \"stepwise\" &&\n announced.has(completed)\n ) {\n throw new MigrationError(\n \"The next rollback dispatch has an ambiguous commit outcome\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n lastConfirmedStep: next.step.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n }\n let skipped = completed;\n return item.rollback.operations.flatMap((operation) => {\n if (skipped >= operation.steps.length) {\n skipped -= operation.steps.length;\n return [];\n }\n const steps = operation.steps.slice(skipped);\n skipped = 0;\n return [{ ...operation, steps }];\n });\n}\n\nfunction assertReversibleEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): void {\n const state = graph.states.get(edge.stateId);\n if (!state) {\n throw new MigrationError(\n \"Rollback target is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n if (!parent) {\n throw new MigrationError(\n \"Rollback cannot find the arrival transition\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (parent.rollback.kind === \"irreversible\") {\n throw new MigrationError(\n parent.rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (!graph.sql.get(state.sqlHash)) {\n throw new MigrationError(\n \"Rollback SQL blob is missing\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n}\n\nfunction rollbackSlice(\n graph: MigrationGraph,\n marker: MigrationMarkerV1,\n options: NormalizedDownOptions\n): MigrationMarkerV1[\"path\"] {\n if (marker.path.length === 0) {\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const steps = options.to\n ? distanceTo(\n marker.path.map((edge) => edge.stateId),\n resolveStateSelector(graph, options.to)\n )\n : options.steps;\n const removed = steps === 0 ? [] : marker.path.slice(-steps);\n if (removed.some((edge) => edge.baselineBoundary)) {\n throw new MigrationError(\n \"down cannot cross a baseline boundary\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return removed;\n}\n\nfunction distanceTo(path: readonly Sha256[], target: Sha256): number {\n const index = path.lastIndexOf(target);\n if (index < 0) {\n throw new MigrationError(\n \"down target is not on the arrival path\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return path.length - 1 - index;\n}\n","/**\n * Hostile admission for push options and inert consent.\n *\n * Consent is not authority. A forged or stale value can only refuse\n * execution. Apply replans under the lock and compares this closed shape.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n PushConsent,\n PushResolution,\n PushTargetIdentity,\n} from \"./v1-types\";\n\ninterface ConsentedPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n}\n\nexport interface ParsedPlanningOptions {\n readonly forceReset: boolean;\n readonly skipValidation: boolean;\n readonly resolve: ResolveCallback | undefined;\n readonly dryRun: boolean;\n}\n\nexport function snapshotPushOptions(\n value: unknown\n): Readonly<Record<string, unknown>> {\n return snapshotExactRecord(\n value,\n [\"consent\", \"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n}\n\nexport function parsePlanningOptions(\n value: unknown,\n dryRun: boolean\n): ParsedPlanningOptions {\n const record = snapshotExactRecord(\n value,\n [\"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n return parseSnapshottedPlanningOptions(record, dryRun);\n}\n\nexport function parseSnapshottedPlanningOptions(\n record: Readonly<Record<string, unknown>>,\n dryRun: boolean\n): ParsedPlanningOptions {\n if (record.dryRun !== undefined && typeof record.dryRun !== \"boolean\") {\n invalidOptions(\"push options.dryRun must be boolean\");\n }\n if (\n record.forceReset !== undefined &&\n typeof record.forceReset !== \"boolean\"\n ) {\n invalidOptions(\"push options.forceReset must be boolean\");\n }\n if (\n record.skipValidation !== undefined &&\n typeof record.skipValidation !== \"boolean\"\n ) {\n invalidOptions(\"push options.skipValidation must be boolean\");\n }\n const candidate = record.resolve;\n if (candidate !== undefined && typeof candidate !== \"function\") {\n invalidOptions(\"push options.resolve must be a function\");\n }\n const resolve: ResolveCallback | undefined =\n typeof candidate === \"function\"\n ? (change) => Reflect.apply(candidate, undefined, [change])\n : undefined;\n return {\n dryRun: dryRun || record.dryRun === true,\n forceReset: record.forceReset === true,\n skipValidation: record.skipValidation === true,\n resolve,\n };\n}\n\nexport function parseConsent(value: unknown): PushConsent {\n const record = snapshotExactRecord(\n value,\n [\"format\", \"mode\", \"planHash\", \"resolutions\", \"target\", \"validation\"],\n \"push consent\",\n consentMismatch\n );\n if (record.format !== \"1\") consentMismatch(\"consent.format must be 1\");\n if (record.mode !== \"diff\" && record.mode !== \"force-reset\") {\n consentMismatch(\"consent.mode is invalid\");\n }\n if (record.validation !== \"full\" && record.validation !== \"structural-only\") {\n consentMismatch(\"consent.validation is invalid\");\n }\n if (!isSha256(record.planHash)) {\n consentMismatch(\"consent.planHash is invalid\");\n }\n const resolutionEntries = snapshotExactArray(\n record.resolutions,\n \"consent.resolutions\",\n consentMismatch\n );\n const resolutions = resolutionEntries.map((resolution, index) => {\n const item = snapshotExactRecord(\n resolution,\n [\"decision\", \"id\"],\n `consent.resolutions[${index}]`,\n consentMismatch\n );\n if (typeof item.id !== \"string\" || typeof item.decision !== \"string\") {\n consentMismatch(`consent.resolutions[${index}] is invalid`);\n }\n return { id: item.id, decision: item.decision };\n });\n return freezeDeep({\n format: \"1\",\n target: parseTarget(record.target),\n planHash: record.planHash,\n mode: record.mode,\n validation: record.validation,\n resolutions,\n });\n}\n\nexport function assertAcceptedPlan(\n accepted: ConsentedPlan,\n locked: ConsentedPlan\n): void {\n if (\n accepted.sourceFingerprint !== locked.sourceFingerprint ||\n accepted.planHash !== locked.planHash\n ) {\n throw new MigrationError(\n \"The live push plan changed before the locked replan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: accepted.planHash,\n actualChecksum: locked.planHash,\n planHash: locked.planHash,\n expectedFingerprint: accepted.sourceFingerprint,\n actualFingerprint: locked.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function assertConsent(consent: PushConsent, plan: ConsentedPlan): void {\n const targetMatches =\n canonicalizeJsonText(consent.target) === canonicalizeJsonText(plan.target);\n const resolutionsMatch =\n canonicalizeJsonText(consent.resolutions) ===\n canonicalizeJsonText(plan.resolutions);\n if (\n consent.mode !== plan.mode ||\n consent.validation !== plan.validation ||\n !targetMatches ||\n !resolutionsMatch ||\n consent.planHash !== plan.planHash\n ) {\n throw new MigrationError(\n \"Push consent does not match the locked live plan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: consent.planHash,\n actualChecksum: plan.planHash,\n planHash: plan.planHash,\n fingerprint: plan.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function hasConsent(\n options: Readonly<Record<string, unknown>>\n): options is Readonly<Record<string, unknown>> & {\n readonly consent: unknown;\n} {\n return \"consent\" in options;\n}\n\nfunction parseTarget(value: unknown): PushTargetIdentity {\n const record = snapshotExactRecord(\n value,\n [\"bindingId\", \"database\", \"dialect\", \"location\", \"namespace\"],\n \"consent.target\",\n consentMismatch\n );\n if (record.dialect === \"postgresql\") {\n refuseTargetKeys(record, [\"bindingId\", \"database\", \"dialect\", \"namespace\"]);\n return {\n dialect: \"postgresql\",\n database: requiredString(record.database, \"consent.target.database\"),\n namespace: requiredString(record.namespace, \"consent.target.namespace\"),\n bindingId: requiredString(record.bindingId, \"consent.target.bindingId\"),\n };\n }\n if (record.dialect === \"mysql\") {\n refuseTargetKeys(record, [\"bindingId\", \"database\", \"dialect\"]);\n return {\n dialect: \"mysql\",\n database: requiredString(record.database, \"consent.target.database\"),\n bindingId: requiredString(record.bindingId, \"consent.target.bindingId\"),\n };\n }\n if (record.dialect === \"sqlite\") {\n refuseTargetKeys(record, [\"bindingId\", \"dialect\", \"location\"]);\n if (record.location !== null && typeof record.location !== \"string\") {\n consentMismatch(\"consent.target.location must be string or null\");\n }\n return {\n dialect: \"sqlite\",\n location: record.location,\n bindingId: requiredString(record.bindingId, \"consent.target.bindingId\"),\n };\n }\n consentMismatch(\"consent.target.dialect is invalid\");\n}\n\nfunction refuseTargetKeys(\n target: Readonly<Record<string, unknown>>,\n allowed: readonly string[]\n): void {\n for (const key of Object.keys(target)) {\n if (!allowed.includes(key)) {\n consentMismatch(`consent.target contains unknown key ${key}`);\n }\n }\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n consentMismatch(`${label} must be a non-empty string`);\n }\n return value;\n}\n\nfunction invalidOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction consentMismatch(message: string, cause?: Error): never {\n throw new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n cause,\n }\n );\n}\n","/**\n * Authenticated, history-free push.\n *\n * A preview exposes review text and inert consent. The executable program stays\n * private, is rebuilt from the live catalog under the target lock, and is\n * dispatched only through the structured-statement compiler.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { allRules } from \"../schema/validation/rules\";\nimport {\n resolveSchemaOrThrow,\n validateResolvedSchemaOrThrow,\n} from \"../schema/validation/validator\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport {\n DEFAULT_CONTROL_BASE,\n readControlState,\n refuseIncompatibleHistory,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { executeDispatch } from \"./execute-dispatch\";\nimport { assertForeignKeysIntact, liftForeignKeyPragmas } from \"./foreign-keys\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n mayWrapTransaction,\n resolveCommandDriver,\n runSequentialProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport {\n assertAcceptedPlan,\n assertConsent,\n hasConsent,\n parseConsent,\n parsePlanningOptions,\n parseSnapshottedPlanningOptions,\n snapshotPushOptions,\n} from \"./push-consent\";\nimport { fingerprintLive, freezeDeep } from \"./push-fingerprint\";\nimport {\n buildPushPlan,\n type InternalPushPlan,\n introspectManaged,\n type PlannedStatement,\n} from \"./push-plan\";\nimport { assertMigrationDecimalDomainsFitProvider } from \"./serializer\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type {\n PushApplyResult as BasePushApplyResult,\n PushPreview as BasePushPreview,\n ExactPushOptions,\n PushConsent,\n PushOptionsV1,\n PushPlanningOptions,\n} from \"./v1-types\";\n\nexport type {\n ExactPushOptions,\n PushConsent,\n PushOperation,\n PushOptionsV1,\n PushOptionsV1 as PushOptions,\n PushPlanningOptions,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PushAttestation {\n readonly pathHash: Sha256;\n readonly planHash: Sha256;\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport interface PushApplyResult extends BasePushApplyResult {\n readonly attestation: PushAttestation;\n}\n\nexport interface PushPreview extends BasePushPreview {\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport type PushResultFor<O> = [O] extends [{ readonly dryRun: true }]\n ? PushPreview\n : PushApplyResult;\n\n/**\n * Effect-free planning. It does not acquire a lock and never receives estate\n * storage. A force reset plans the empty-to-target rebuild rather than diffing\n * the desired schema from the live schema.\n */\nexport async function previewPush(\n client: MigrationClient,\n options: PushPlanningOptions = {}\n): Promise<PushPreview> {\n const parsed = parsePlanningOptions(options, true);\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"read-only\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n const command = await resolveCommandDriver(client.$driver, driver);\n const plan = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n return publicPreview(plan);\n}\n\n/**\n * Replans and executes on one pinned producer under the target lock.\n *\n * Generic force is deliberately absent. Destructive diff work and every\n * force-reset plan require exact preview consent.\n */\nexport function pushV1<O extends PushOptionsV1>(\n client: MigrationClient,\n options?: ExactPushOptions<O>\n): Promise<PushResultFor<O>>;\nexport async function pushV1(\n client: MigrationClient,\n options?: PushOptionsV1\n): Promise<PushApplyResult | PushPreview> {\n const given = snapshotPushOptions(options ?? {});\n if (hasConsent(given)) {\n return applyWithConsent(client, parseConsent(given.consent));\n }\n\n const parsed = parseSnapshottedPlanningOptions(given, given.dryRun === true);\n if (parsed.dryRun) {\n return previewPush(client, parsed);\n }\n\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n\n // A resolver may perform arbitrary user work. Run it only during an unlocked\n // read-only plan, then close its normalized answers for the locked replan.\n let accepted: InternalPushPlan | undefined;\n if (parsed.resolve) {\n admitLiveMigrationCapability(driver, \"read-only\", \"push()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n accepted = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n }\n\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n parsed,\n accepted\n ? { kind: \"replay\", resolutions: accepted.resolutions }\n : { kind: \"record\", callback: undefined }\n );\n if (accepted) assertAcceptedPlan(accepted, plan);\n await assertPushControlInterlock(pinned, command, plan);\n if (plan.destructive) {\n throw new MigrationError(\n \"Destructive or force-reset push requires exact preview consent. Call push({ dryRun: true }), review the plan, then pass its consent unchanged to push({ consent }).\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n command: \"push\",\n dialect: plan.target.dialect,\n expectedChecksum: plan.planHash,\n expectedStatementCount: plan.statements.length,\n hint: \"Review push({ dryRun: true }) and pass the returned consent unchanged to push({ consent }).\",\n },\n }\n );\n }\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function applyWithConsent(\n client: MigrationClient,\n consent: PushConsent\n): Promise<PushApplyResult> {\n const skipValidation = consent.validation === \"structural-only\";\n const { relations, driver } = prepareSchema(client, skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n consent.mode === \"force-reset\"\n ? \"push({ consent: forceResetPreview.consent })\"\n : \"push({ consent })\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n {\n forceReset: consent.mode === \"force-reset\",\n skipValidation,\n resolve: undefined,\n dryRun: false,\n },\n { kind: \"replay\", resolutions: consent.resolutions }\n );\n assertConsent(consent, plan);\n await assertPushControlInterlock(pinned, command, plan);\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function executeLockedPlan(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<PushApplyResult> {\n // A plan with nothing to do still has a MySQL sequential program to run: the\n // interrupted-decimal-conversion recovery belongs to the LOCKED COMMAND, not\n // to having statements. A conversion interrupted after its MODIFY leaves the\n // column already carrying the target domain, so the differ sees no change\n // and the plan is empty — and the remnant CHECK, which no snapshot\n // vocabulary describes, would then survive every later push while refusing\n // values the declared domain admits.\n if (plan.statements.length === 0 && command.target.dialect !== \"mysql\") {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n\n const execute = (producer: AnyDriver): Promise<Sha256> =>\n executeAndAttest(producer, command, plan, plan.statements);\n\n if (\n mayWrapTransaction(\n pinned,\n command.target.dialect,\n plan.atomicity === \"transactional\"\n )\n ) {\n const fingerprint = await executeTransactional(pinned, command, plan);\n return appliedResult(plan, fingerprint, \"applied\");\n }\n if (command.target.dialect === \"mysql\") {\n await runSequentialProgram(pinned, command, async (producer) => {\n for (const statement of plan.statements) {\n await executeDispatch(\n producer,\n plan.sqlBlob,\n statement.dispatch,\n command.namespace\n );\n }\n });\n if (plan.statements.length === 0) {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n const fingerprint = await attestFinalFingerprint(pinned, command, plan);\n return appliedResult(plan, fingerprint, \"applied\");\n }\n const fingerprint = await execute(pinned);\n return appliedResult(plan, fingerprint, \"applied\");\n}\n\nasync function executeAndAttest(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan,\n statements: readonly PlannedStatement[]\n): Promise<Sha256> {\n for (const statement of statements) {\n await executeDispatch(\n producer,\n plan.sqlBlob,\n statement.dispatch,\n command.namespace\n );\n }\n return attestFinalFingerprint(producer, command, plan);\n}\n\nasync function executeTransactional(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<Sha256> {\n const sql = plan.statements.map((statement) =>\n sliceDispatch(plan.sqlBlob, statement.dispatch)\n );\n const lifted = liftForeignKeyPragmas(pinned, sql);\n if (!lifted.bracket) {\n return pinned.withTransaction((transaction) =>\n executeAndAttest(transaction, command, plan, plan.statements)\n );\n }\n\n const disable = findStatement(plan, lifted.bracket.disable);\n const enable = findStatement(plan, lifted.bracket.enable);\n const remaining = takeStatements(plan, [\n disable.dispatch.dispatchId,\n enable.dispatch.dispatchId,\n ]);\n await executeDispatch(\n pinned,\n plan.sqlBlob,\n disable.dispatch,\n command.namespace\n );\n try {\n return await pinned.withTransaction(async (transaction) => {\n for (const statement of remaining) {\n await executeDispatch(\n transaction,\n plan.sqlBlob,\n statement.dispatch,\n command.namespace\n );\n }\n await assertForeignKeysIntact(transaction, lifted.bracket);\n return attestFinalFingerprint(transaction, command, plan);\n });\n } finally {\n await executeDispatch(\n pinned,\n plan.sqlBlob,\n enable.dispatch,\n command.namespace\n );\n }\n}\n\nasync function attestFinalFingerprint(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<Sha256> {\n const finalSnapshot = await introspectManaged(producer, command);\n const fingerprint = await fingerprintLive(finalSnapshot, command, producer);\n const expected = await fingerprintLive(plan.desiredSchema, command, producer);\n if (fingerprint !== expected) {\n throw new MigrationError(\n `Push completed its statements but the final live fingerprint does not match the desired schema: ${JSON.stringify(await diff(finalSnapshot, plan.desiredSchema))}`,\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n }\n );\n }\n return fingerprint;\n}\n\nfunction findStatement(plan: InternalPushPlan, sql: string): PlannedStatement {\n const found = plan.statements.find(\n (statement) =>\n sliceDispatch(plan.sqlBlob, statement.dispatch).trim() === sql.trim()\n );\n if (!found) {\n throw new MigrationError(\n \"The compiled SQLite foreign-key bracket is missing from the authenticated push plan\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return found;\n}\n\nfunction takeStatements(\n plan: InternalPushPlan,\n excludedDispatchIds: readonly string[]\n): readonly PlannedStatement[] {\n const excluded = new Set(excludedDispatchIds);\n return plan.statements.filter(\n (statement) => !excluded.has(statement.dispatch.dispatchId)\n );\n}\n\nfunction appliedResult(\n plan: InternalPushPlan,\n fingerprint: Sha256,\n outcome: PushApplyResult[\"outcome\"]\n): PushApplyResult {\n const pathHash = domainHash(\n HASH_DOMAIN.path,\n canonicalizeJson({\n target: plan.target,\n sourceFingerprint: plan.sourceFingerprint,\n fingerprint,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n })\n );\n return freezeDeep({\n outcome,\n target: plan.target,\n planHash: plan.planHash,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n attestation: {\n pathHash,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n });\n}\n\nasync function assertPushControlInterlock(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<void> {\n const control = await readControlState(\n producer,\n command,\n DEFAULT_CONTROL_BASE\n );\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n return;\n }\n const { marker, ledger } = control;\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking push\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n if (!marker) {\n return;\n }\n if (plan.operations.length > 0 || plan.mode === \"force-reset\") {\n throw new MigrationError(\n \"Non-empty push against a migration marker is refused; use generate/apply or history-aware reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { planHash: plan.planHash } }\n );\n }\n if (\n marker.snapshotHash !== plan.schemaHash ||\n plan.sourceFingerprint !== plan.desiredFingerprint\n ) {\n throw new MigrationError(\n \"A no-op push cannot prove agreement between the marker, live schema, and desired schema\",\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n expectedChecksum: marker.snapshotHash,\n actualChecksum: plan.schemaHash,\n },\n }\n );\n }\n}\n\nfunction publicPreview(plan: InternalPushPlan): PushPreview {\n const consent: PushConsent = {\n format: \"1\",\n target: plan.target,\n planHash: plan.planHash,\n mode: plan.mode,\n validation: plan.validation,\n resolutions: plan.resolutions,\n };\n return freezeDeep({\n outcome: plan.statements.length === 0 ? \"noop\" : \"planned\",\n target: plan.target,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint: plan.sourceFingerprint,\n destructive: plan.destructive,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n consent,\n });\n}\n\nfunction prepareSchema(\n client: MigrationClient,\n skipValidation: boolean\n): {\n readonly relations: ResolvedRelationIndex;\n readonly driver: BoundMigrationDriver;\n} {\n hydrateSchemaNames(client.$schema);\n const relations = skipValidation\n ? resolveSchemaOrThrow(client.$schema)\n : validateResolvedSchemaOrThrow(client.$schema, allRules);\n const driver = getPushMigrationDriver(client);\n assertMigrationDecimalDomainsFitProvider(client.$schema, driver.dialect);\n return { relations, driver };\n}\n","/** One capability-sensitive migration client composition root. */\n\nimport { errorCause } from \"../drivers/shared/driver-options\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { type ApplyV1Result, applyV1 } from \"./apply-v1\";\nimport { type CheckResult, checkEstate } from \"./check\";\nimport { type GenerateV1Result, generateV1 } from \"./generate-v1\";\nimport { loadMigrationGraph, resolveStateSelector } from \"./graph\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport {\n baselineV1,\n downV1,\n logV1,\n resetV1,\n resolveV1,\n type StatusV1Result,\n statusV1,\n verifyV1,\n} from \"./operators\";\nimport {\n type GraphResult,\n type ListResult,\n listMigrationStates,\n migrationGraphResult,\n type ShowResult,\n showMigrationState,\n} from \"./public-view\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { type PushResultFor, pushV1 } from \"./push-v1\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n isMigrationStorageReader,\n isMigrationStorageWriter,\n} from \"./storage/contract\";\nimport { MANAGED_TABLES, normalizeManagedTables } from \"./target\";\nimport type {\n ApplyV1Options,\n BaselineOptions,\n DownV1Options,\n ExactPushOptions,\n GenerateV1Options,\n LedgerEventV1,\n PushOptionsV1,\n ResetV1Options,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationClientOptions<\n S extends MigrationStorageReader = MigrationStorageReader,\n> {\n readonly storage: S;\n readonly tables?: readonly string[];\n}\n\ntype NoExtraMigrationClientOptionKeys<Given> = Record<\n Exclude<keyof Given, \"storage\" | \"tables\">,\n never\n>;\n\nexport type GenerateResult = GenerateV1Result;\nexport type StatusResult = StatusV1Result;\nexport interface VerifyResult {\n readonly ok: boolean;\n}\nexport type LogResult = readonly LedgerEventV1[];\nexport type ApplyResult = ApplyV1Result;\nexport interface DownResult {\n readonly path: readonly string[];\n readonly preview: boolean;\n}\nexport interface BaselineResult {\n readonly stateId: string;\n}\nexport interface ResolveResult {\n readonly outcome: ResolveV1Options[\"outcome\"];\n}\nexport interface ResetResult {\n /** Physical tables selected for a read-only reset preview. */\n readonly tables?: readonly string[];\n readonly preview: boolean;\n readonly path: readonly string[];\n}\nexport interface LiveMigrations {\n log(): Promise<LogResult>;\n push<O extends PushOptionsV1>(\n options?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>>;\n}\n\nexport interface ReadableMigrations extends LiveMigrations {\n check(): Promise<CheckResult>;\n list(): Promise<ListResult>;\n show(selector: StateSelector): Promise<ShowResult>;\n graph(): Promise<GraphResult>;\n status(): Promise<StatusResult>;\n verify(): Promise<VerifyResult>;\n apply(options?: ApplyV1Options): Promise<ApplyResult>;\n down(options?: DownV1Options): Promise<DownResult>;\n baseline(options: BaselineOptions): Promise<BaselineResult>;\n resolve(options: ResolveV1Options): Promise<ResolveResult>;\n}\n\nexport interface WritableMigrations extends ReadableMigrations {\n generate(options?: GenerateV1Options): Promise<GenerateResult>;\n reset(options?: ResetV1Options): Promise<ResetResult>;\n}\n\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageWriter>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): WritableMigrations;\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageReader>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): ReadableMigrations;\nexport function createMigrationClient<\n Options extends { readonly tables: readonly string[] },\n>(\n client: MigrationClient,\n options: Options & Record<Exclude<keyof Options, \"tables\">, never>\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: undefined\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: MigrationClientOptions | { readonly tables: readonly string[] }\n): LiveMigrations | ReadableMigrations | WritableMigrations {\n const record =\n options === undefined\n ? undefined\n : snapshotExactRecord(\n options,\n [\"storage\", \"tables\"],\n \"migration client options\",\n refuseClientOptions\n );\n const tables = normalizeManagedTables(record?.tables);\n const executionClient: MigrationClient =\n tables === undefined\n ? client\n : {\n $driver: client.$driver,\n $schema: client.$schema,\n [MANAGED_TABLES]: tables,\n };\n const live: LiveMigrations = Object.freeze({\n log: () => logV1(executionClient),\n push<O extends PushOptionsV1>(\n pushOptions?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>> {\n return pushV1(executionClient, pushOptions);\n },\n });\n if (record === undefined) return live;\n const storage = record.storage;\n if (storage === undefined) {\n if (tables !== undefined) return live;\n return refuseClientOptions(\n \"migration client options must include storage when supplied\"\n );\n }\n let readableStorage: MigrationStorageReader;\n try {\n if (!isMigrationStorageReader(storage)) {\n return refuseClientOptions(\n \"migration client storage must implement MigrationStorageReader\"\n );\n }\n readableStorage = storage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n const readable: ReadableMigrations = Object.freeze({\n ...live,\n check: () => checkEstate(readableStorage),\n list: async () =>\n listMigrationStates(await loadMigrationGraph(readableStorage)),\n show: async (selector) => {\n const graph = await loadMigrationGraph(readableStorage);\n return showMigrationState(graph, resolveStateSelector(graph, selector));\n },\n graph: async () =>\n migrationGraphResult(await loadMigrationGraph(readableStorage)),\n status: () => statusV1(executionClient, readableStorage),\n verify: () => verifyV1(executionClient, readableStorage),\n apply: (applyOptions) =>\n applyV1(executionClient, readableStorage, applyOptions),\n down: (downOptions) =>\n downV1(executionClient, readableStorage, downOptions),\n baseline: (baselineOptions) =>\n baselineV1(executionClient, readableStorage, baselineOptions),\n resolve: (resolveOptions) =>\n resolveV1(executionClient, readableStorage, resolveOptions),\n });\n let writableStorage: MigrationStorageWriter;\n try {\n if (!isMigrationStorageWriter(readableStorage)) return readable;\n writableStorage = readableStorage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n return Object.freeze({\n ...readable,\n generate: (generateOptions) =>\n generateV1(executionClient, writableStorage, generateOptions),\n reset: (resetOptions) =>\n resetV1(executionClient, writableStorage, resetOptions),\n });\n}\n\nfunction refuseClientOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n"],"mappings":"q+CAOA,MAAM,GAAuB,MACvB,GAAwB,UAExB,GAAqB,uBAEr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