viborm 1.2.4 → 1.3.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.
Files changed (275) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-Df24l2Bd.mjs +2 -0
  17. package/dist/builder-Df24l2Bd.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-C7c1YTXD.mjs +2 -0
  35. package/dist/chain-C7c1YTXD.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  39. package/dist/client-DM1UHfYG.mjs +49 -0
  40. package/dist/{client-B3VWFhv_.mjs.map → client-DM1UHfYG.mjs.map} +1 -1
  41. package/dist/client-_WKrPNmm.mjs +2 -0
  42. package/dist/client-_WKrPNmm.mjs.map +1 -0
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-Da-efekX.mjs +2 -0
  50. package/dist/controls-Da-efekX.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-1pKZteeB.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-1pKZteeB.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-DsyHNSDS.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
  78. package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D_kagnFv.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-DFAoHXrI.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-CDTUZQWL.mjs → memory-GTWgeDNY.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  119. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  120. package/dist/{mysql-D7zC03yD.mjs → mysql-xChEivOe.mjs} +6 -6
  121. package/dist/{mysql-D7zC03yD.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-Dv-QnnbD.mjs → postgres-BqAxDWTQ.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-CDgX_vzn.mjs +2 -0
  166. package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
  167. package/dist/scalar-S8yMvdmx.mjs +4 -0
  168. package/dist/scalar-S8yMvdmx.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-9N9jQlVL.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C1PuFIpf.mjs +2 -0
  204. package/dist/to-many-C1PuFIpf.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
  213. package/dist/v-CYTUI0H5.mjs +2 -0
  214. package/dist/v-CYTUI0H5.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-DgffZq9C.mjs +2 -0
  222. package/dist/validator-DgffZq9C.mjs.map +1 -0
  223. package/dist/version-CXuJzC-q.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
  225. package/package.json +35 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B3VWFhv_.mjs +0 -49
  232. package/dist/client-BLiBmykn.mjs +0 -2
  233. package/dist/client-BLiBmykn.mjs.map +0 -1
  234. package/dist/controls-DXgIn4zh.mjs +0 -2
  235. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  236. package/dist/driver-BlnKXPFF.mjs +0 -2
  237. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  238. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  239. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  240. package/dist/every-o-Nu9Em8.mjs +0 -2
  241. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  243. package/dist/hydration-CAxOL4aI.mjs +0 -2
  244. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  245. package/dist/identifier-hQCs8M1n.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  247. package/dist/key-BeoOwGr3.mjs +0 -2
  248. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  249. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  251. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  252. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  253. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  254. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  255. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  256. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  257. package/dist/scalar-U0wD5bKy.mjs +0 -2
  258. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  259. package/dist/schema-Cjem1-0f.mjs +0 -2
  260. package/dist/sql-Bp7jicEX.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  262. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  264. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  265. package/dist/terminal-C8cq1WWX.mjs +0 -2
  266. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  267. package/dist/v-D5Z06FKN.mjs +0 -2
  268. package/dist/v-D5Z06FKN.mjs.map +0 -1
  269. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  270. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  271. package/dist/validation-PF9-_nKd.mjs +0 -2
  272. package/dist/validator-X9-bwtRo.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  274. package/dist/version-nt0parEY.mjs +0 -2
  275. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"mysql-adapter-DkJPfoGf.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,E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G,oCAAoC,EAAe,SAAS,EAAc,sCAC/E,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,iBAAiB,EAAM,uBAAuB,EAAQ,aAC5D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,sBAAsB,EACzC,EACD,CAAC,YACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,EACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
1
+ {"version":3,"file":"mysql-adapter-C6c5govr.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \\`__viborm_judged__\\`${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations(quoteIdent);\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAA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oB,KAAK,cAAc,CACxC,CAAC,CAEF,OAAS,EAET,cAAwC,CACtC,IAAM,UAAa,GAAoB,CAAG,gBAAgB,EAAM,GAC1D,SAAY,GAAoB,CAAG,eAAe,EAAM,GAC9D,MAAO,CAGL,OAAQ,EAAgB,IACtB,CAAG,oCAAoC,EAAe,SAAS,EAAc,sCAC/E,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,iBAAiB,EAAM,uBAAuB,EAAQ,aAC5D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,sBAAsB,EACzC,EACD,CAAC,YACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,GACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
@@ -1,9 +1,9 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{E as r,N as i}from"./geo-point-codec-lhxH42SK.mjs";import{r as a}from"./datetime-physical-codec-oIhiYZEP.mjs";import{o}from"./native-types-veeTk36s.mjs";import{a as s}from"./physical-6V_LNU3L.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-B3VWFhv_.mjs";import{r as T}from"./identity-CLFhCTZx.mjs";import{N as E}from"./standard-sql-Bk4RZPqJ.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-GgbwHc2G.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{t as n}from"./migrations-Bn1SatyB.mjs";import{j as r,w as i}from"./geo-point-codec-DyEHMdJg.mjs";import{o as a}from"./native-types-asNCr26n.mjs";import{a as o}from"./physical-CAOaNM4R.mjs";import{r as s}from"./datetime-physical-codec-BEqQbIP_.mjs";import{A as c,B as l,G as u,H as d,I as f,K as p,L as m,N as h,R as g,U as _,V as v,W as y,Y as b,j as x,m as S,q as C,z as w}from"./client-DM1UHfYG.mjs";import{r as T}from"./identity-oQvIe7u8.mjs";import{P as E}from"./standard-sql-CoGqv-iX.mjs";import{a as D,i as O,o as k}from"./identifier-conversion-DaZ9yNpv.mjs";const namespaceMeta=e=>({dialect:`mysql`,namespace:e});async function resolveCatalogNamespace(e,r){if(r===void 0)throw new n(`This MySQL client's adapter declares no database, so there is no catalog to read. MySQL migration artifacts are database-relative on purpose: supply the live destination explicitly, in the connection URL, or through the driver's database option.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});let{rows:i}=await e(`
2
2
  SELECT SCHEMA_NAME
3
3
  FROM information_schema.SCHEMATA
4
4
  WHERE LOWER(SCHEMA_NAME) = LOWER(?)
5
5
  ORDER BY SCHEMA_NAME
6
- `,[r]),a=i.map(e=>e.SCHEMA_NAME).filter(e=>typeof e==`string`);if(a.length===0)throw new n(`The MySQL database "${r}" does not exist or is not visible to this connection. VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`missing-database`}});let o=a.find(e=>e===r);if(o!==void 0)return o;let[s]=a;if(a.length===1&&s!==void 0)return s;throw new n(`The MySQL database "${r}" matches ${a.length} existing databases that differ only by case (${a.join(`, `)}). Configure the exact name this server reports so migration work cannot land in the wrong one.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`ambiguous-database`,candidates:a}})}const A=/^viborm_decimal_([sl])_(\d+)_(\d+)$/,j=/^_[a-zA-Z0-9]+(?=')/,M=/\s/;function refuseReservedConstraint(e,r,i){throw new n(`The MySQL CHECK constraint "${e}" on table "${r}" uses VibORM's reserved decimal-conversion namespace but ${i}. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`decimal-conversion-constraint-collision`,table:r,constraint:e}})}function readString(e,t,n,r){if(typeof e==`string`)return e;refuseReservedConstraint(t,n,`its catalog ${r} is not a string`)}function normalizeCheckClause(e){let t=e.replaceAll(`\\'`,`'`),n=``,r=0;for(;r<t.length;){let i=t[r];if(i===`'`){let e=r;for(r++;r<t.length;){if(t[r]===`\\`&&r+1<t.length){r+=2;continue}if(t[r]===`'`&&t[r+1]===`'`){r+=2;continue}if(t[r]===`'`){r++;break}r++}n+=t.slice(e,r);continue}if(i==="`"){let i=t.indexOf("`",r+1);if(i<0)return e;n+=t.slice(r,i+1),r=i+1;continue}if(M.test(i??``)){r++;continue}if(i===`_`){let e=j.exec(t.slice(r));if(e!==null){r+=e[0].length;continue}}n+=i?.toLowerCase()??``,r++}return n}function expectedConstraint(e,t,n){let r=`\`${e.name}\``;return t===`s`?d(r,`DECIMAL(${n.precision},${n.scale})`):y(r,n)}function readDescriptor(e,t,n){let r=i(e[2],e[3],`mysql`);return r===void 0&&refuseReservedConstraint(t,n,`its name declares a decimal domain this provider does not admit`),w(e[1]===`s`?`scalar`:`list`,r)!==t&&refuseReservedConstraint(t,n,`its name is not the canonical spelling of its decimal proof`),r}function proveConstraint(e,t){let n=typeof e.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,r=typeof e.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,i=readString(e.CONSTRAINT_NAME,n,r,`CONSTRAINT_NAME`),a=readString(e.TABLE_NAME,i,r,`TABLE_NAME`),o=readString(e.CHECK_CLAUSE,i,a,`CHECK_CLAUSE`);readString(e.ENFORCED,i,a,`ENFORCED`)!==`YES`&&refuseReservedConstraint(i,a,`its CHECK is not enforced`);let s=A.exec(i);s===null&&refuseReservedConstraint(i,a,`its name does not match the complete reserved proof identity`);let c=s[1]===`s`?`s`:`l`,l=readDescriptor(s,i,a),u=t.get(a)??[],d=normalizeCheckClause(o);for(let e of u){if(normalizeCheckClause(expectedConstraint(e,c,l))!==d)continue;if(c===`s`){if(e.dataType===`decimal`||e.dataType===`int`||e.dataType===`bigint`)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its scalar proof is attached to impossible ${e.dataType} storage`)}e.dataType!==`json`&&refuseReservedConstraint(i,a,`its list proof is attached to impossible ${e.dataType} storage`);let t;try{t=b(e.comment)}catch{refuseReservedConstraint(i,a,`its JSON column carries an invalid decimal-list marker`)}if(t!==void 0&&t.scale===l.scale&&t.precision>=l.precision)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its JSON column does not carry a compatible source or target decimal-list marker`)}refuseReservedConstraint(i,a,`its concrete CHECK predicate does not match that proof identity`)}function groupColumns(e){let t=new Map;for(let n of e){let e=typeof n.TABLE_NAME==`string`?n.TABLE_NAME:``,r=typeof n.COLUMN_NAME==`string`?n.COLUMN_NAME:``,i=typeof n.DATA_TYPE==`string`?n.DATA_TYPE:``,a=typeof n.COLUMN_COMMENT==`string`?n.COLUMN_COMMENT:``;if(e===``||r===``||i===``)continue;let o=t.get(e)??[];o.push({name:r,dataType:i.toLowerCase(),comment:a}),t.set(e,o)}return t}async function planInterruptedMySQLDecimalRecovery(e,t,n){let{rows:r}=await e(`
6
+ `,[r]),a=i.map(e=>e.SCHEMA_NAME).filter(e=>typeof e==`string`);if(a.length===0)throw new n(`The MySQL database "${r}" does not exist or is not visible to this connection. VibORM never creates or drops a database: create it, or grant this user access to it, before running migration work against it.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`missing-database`}});let o=a.find(e=>e===r);if(o!==void 0)return o;let[s]=a;if(a.length===1&&s!==void 0)return s;throw new n(`The MySQL database "${r}" matches ${a.length} existing databases that differ only by case (${a.join(`, `)}). Configure the exact name this server reports so migration work cannot land in the wrong one.`,t.MIGRATION_INVALID_STATE,{meta:{...namespaceMeta(r),type:`ambiguous-database`,candidates:a}})}const A=/^viborm_decimal_([sl])_(\d+)_(\d+)$/,j=/^_[a-zA-Z0-9]+(?=')/,M=/\s/;function refuseReservedConstraint(e,r,i){throw new n(`The MySQL CHECK constraint "${e}" on table "${r}" uses VibORM's reserved decimal-conversion namespace but ${i}. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`decimal-conversion-constraint-collision`,table:r,constraint:e}})}function readString(e,t,n,r){if(typeof e==`string`)return e;refuseReservedConstraint(t,n,`its catalog ${r} is not a string`)}function normalizeCheckClause(e){let t=e.replaceAll(`\\'`,`'`),n=``,r=0;for(;r<t.length;){let i=t[r];if(i===`'`){let e=r;for(r++;r<t.length;){if(t[r]===`\\`&&r+1<t.length){r+=2;continue}if(t[r]===`'`&&t[r+1]===`'`){r+=2;continue}if(t[r]===`'`){r++;break}r++}n+=t.slice(e,r);continue}if(i==="`"){let i=t.indexOf("`",r+1);if(i<0)return e;n+=t.slice(r,i+1),r=i+1;continue}if(M.test(i??``)){r++;continue}if(i===`_`){let e=j.exec(t.slice(r));if(e!==null){r+=e[0].length;continue}}n+=i?.toLowerCase()??``,r++}return n}function expectedConstraint(e,t,n){let r=`\`${e.name}\``;return t===`s`?d(r,`DECIMAL(${n.precision},${n.scale})`):y(r,n)}function readDescriptor(e,t,n){let i=r(e[2],e[3],`mysql`);return i===void 0&&refuseReservedConstraint(t,n,`its name declares a decimal domain this provider does not admit`),w(e[1]===`s`?`scalar`:`list`,i)!==t&&refuseReservedConstraint(t,n,`its name is not the canonical spelling of its decimal proof`),i}function proveConstraint(e,t){let n=typeof e.CONSTRAINT_NAME==`string`?e.CONSTRAINT_NAME:`<unreported>`,r=typeof e.TABLE_NAME==`string`?e.TABLE_NAME:`<unreported>`,i=readString(e.CONSTRAINT_NAME,n,r,`CONSTRAINT_NAME`),a=readString(e.TABLE_NAME,i,r,`TABLE_NAME`),o=readString(e.CHECK_CLAUSE,i,a,`CHECK_CLAUSE`);readString(e.ENFORCED,i,a,`ENFORCED`)!==`YES`&&refuseReservedConstraint(i,a,`its CHECK is not enforced`);let s=A.exec(i);s===null&&refuseReservedConstraint(i,a,`its name does not match the complete reserved proof identity`);let c=s[1]===`s`?`s`:`l`,l=readDescriptor(s,i,a),u=t.get(a)??[],d=normalizeCheckClause(o);for(let e of u){if(normalizeCheckClause(expectedConstraint(e,c,l))!==d)continue;if(c===`s`){if(e.dataType===`decimal`||e.dataType===`int`||e.dataType===`bigint`)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its scalar proof is attached to impossible ${e.dataType} storage`)}e.dataType!==`json`&&refuseReservedConstraint(i,a,`its list proof is attached to impossible ${e.dataType} storage`);let t;try{t=b(e.comment)}catch{refuseReservedConstraint(i,a,`its JSON column carries an invalid decimal-list marker`)}if(t!==void 0&&t.scale===l.scale&&t.precision>=l.precision)return{tableName:a,constraintName:i};refuseReservedConstraint(i,a,`its JSON column does not carry a compatible source or target decimal-list marker`)}refuseReservedConstraint(i,a,`its concrete CHECK predicate does not match that proof identity`)}function groupColumns(e){let t=new Map;for(let n of e){let e=typeof n.TABLE_NAME==`string`?n.TABLE_NAME:``,r=typeof n.COLUMN_NAME==`string`?n.COLUMN_NAME:``,i=typeof n.DATA_TYPE==`string`?n.DATA_TYPE:``,a=typeof n.COLUMN_COMMENT==`string`?n.COLUMN_COMMENT:``;if(e===``||r===``||i===``)continue;let o=t.get(e)??[];o.push({name:r,dataType:i.toLowerCase(),comment:a}),t.set(e,o)}return t}async function planInterruptedMySQLDecimalRecovery(e,t,n){let{rows:r}=await e(`
7
7
  SELECT
8
8
  tc.TABLE_NAME,
9
9
  tc.CONSTRAINT_NAME,
@@ -22,7 +22,7 @@ SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
22
22
  FROM information_schema.COLUMNS
23
23
  WHERE TABLE_SCHEMA = ?
24
24
  ORDER BY TABLE_NAME, ORDINAL_POSITION
25
- `,[t])).rows);return r.map(e=>proveConstraint(e,i)).map(e=>`ALTER TABLE ${n(t)}.${n(e.tableName)} DROP CHECK ${n(e.constraintName)}`)}const N=new Set([`bigint`,`bit`,`decimal`,`double`,`float`,`int`,`integer`,`mediumint`,`numeric`,`real`,`smallint`,`tinyint`]);function formatColumnType(e){if(e.DATA_TYPE.toLowerCase()===`point`){let t=readSrid(e);return t===void 0?`POINT`:`POINT SRID ${t}`}if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE);return t?f(t):e.COLUMN_TYPE}let t=e.COLUMN_TYPE.toLowerCase();return t.includes(`unsigned`)||t.includes(`zerofill`)||t.includes(`(`)&&e.DATA_TYPE!==`enum`?e.COLUMN_TYPE:e.DATA_TYPE===`varchar`&&e.CHARACTER_MAXIMUM_LENGTH?`VARCHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`char`&&e.CHARACTER_MAXIMUM_LENGTH?`CHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION?e.NUMERIC_SCALE!==null&&e.NUMERIC_SCALE!==void 0?`DECIMAL(${e.NUMERIC_PRECISION},${e.NUMERIC_SCALE})`:`DECIMAL(${e.NUMERIC_PRECISION})`:e.DATA_TYPE.toUpperCase()}function readSrid(e){if(e.SRS_ID===null||e.SRS_ID===void 0)return;let r=Number(e.SRS_ID);if(Number.isSafeInteger(r)&&r>=0&&r<=4294967295)return r;throw new n(`MySQL reported an invalid SRID for column "${e.TABLE_NAME}"."${e.COLUMN_NAME}". Migration introspection is refused rather than publishing an unprovable spatial type.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-srid`}})}function isAutoIncrement(e){return e.toLowerCase().includes(`auto_increment`)}function readDecimalDomain(e){if(e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION!==null){let r=i(e.NUMERIC_PRECISION,e.NUMERIC_SCALE??0,`mysql`);if(r!==void 0)return r;throw new n(`MySQL reported column "${e.TABLE_NAME}"."${e.COLUMN_NAME}" as DECIMAL(${String(e.NUMERIC_PRECISION)},${String(e.NUMERIC_SCALE??0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-decimal-domain`}})}if(e.DATA_TYPE===`json`)return b(e.COLUMN_COMMENT)}const P=/^_([A-Za-z0-9_]+)\\'([\s\S]*)\\'$/,F=/\\([\s\S]?)/g;function decodeSingleByte(e){return Array.from(e,e=>String.fromCharCode(e)).join(``)}const I=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];function decodeLatin1(e){return Array.from(e,e=>String.fromCharCode(e>=128&&e<=159?I[e-128]??e:e)).join(``)}const L=new Map([[`utf8`,T],[`utf8mb3`,T],[`utf8mb4`,T],[`latin1`,decodeLatin1],[`ascii`,decodeSingleByte],[`binary`,decodeSingleByte]]);function decodeIntroducedLiteral(e,t){let n=L.get(e.toLowerCase());if(n===void 0)return;let r=[...t].map(e=>e.codePointAt(0)??0);if(!r.some(e=>e>255))try{return n(Uint8Array.from(r))}catch{return}}function unescapeOneLayer(e){let t=!0,n=e.replace(F,(e,n)=>{let r=c.get(n);return r===void 0?(t=!1,n):r});return t?n:void 0}function deparsedStringValue(e){let t=P.exec(e),n=t?.[1],r=t?.[2],i=n===void 0||r===void 0?void 0:decodeIntroducedLiteral(n,r),a=i===void 0?void 0:unescapeOneLayer(i);return a===void 0?void 0:unescapeOneLayer(a)}function cleanDefault(e){let t=e.COLUMN_DEFAULT;if(t!==null){if(e.EXTRA.toUpperCase().includes(`DEFAULT_GENERATED`)){let e=deparsedStringValue(t);return e===void 0?t:`(${m(e)})`}return N.has(e.DATA_TYPE.toLowerCase())?t:m(t)}}function admitContainedForeignKeys(e,r,i){for(let a of e)if(!(i!==void 0&&!(a.TABLE_SCHEMA===r&&i.includes(a.TABLE_NAME))&&!(a.REFERENCED_TABLE_SCHEMA===r&&i.includes(a.REFERENCED_TABLE_NAME)))&&!(a.TABLE_SCHEMA===r&&a.REFERENCED_TABLE_SCHEMA===r))throw new n(`Foreign key "${a.CONSTRAINT_NAME}" crosses a database boundary: \`${a.TABLE_SCHEMA}\`.\`${a.TABLE_NAME}\` references \`${a.REFERENCED_TABLE_SCHEMA}\`.\`${a.REFERENCED_TABLE_NAME}\`, and this client manages only "${r}". 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`cross-database-foreign-key`,constraint:a.CONSTRAINT_NAME,namespace:r,table:`${a.TABLE_SCHEMA}.${a.TABLE_NAME}`,referencedTable:`${a.REFERENCED_TABLE_SCHEMA}.${a.REFERENCED_TABLE_NAME}`}})}async function introspect(e,r,i){let a=await resolveCatalogNamespace(e,r),o=[a],s=await e(`
25
+ `,[t])).rows);return r.map(e=>proveConstraint(e,i)).map(e=>`ALTER TABLE ${n(t)}.${n(e.tableName)} DROP CHECK ${n(e.constraintName)}`)}const N=new Set([`bigint`,`bit`,`decimal`,`double`,`float`,`int`,`integer`,`mediumint`,`numeric`,`real`,`smallint`,`tinyint`]);function formatColumnType(e){if(e.DATA_TYPE.toLowerCase()===`point`){let t=readSrid(e);return t===void 0?`POINT`:`POINT SRID ${t}`}if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE);return t?f(t):e.COLUMN_TYPE}let t=e.COLUMN_TYPE.toLowerCase();return t.includes(`unsigned`)||t.includes(`zerofill`)||t.includes(`(`)&&e.DATA_TYPE!==`enum`?e.COLUMN_TYPE:e.DATA_TYPE===`varchar`&&e.CHARACTER_MAXIMUM_LENGTH?`VARCHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`char`&&e.CHARACTER_MAXIMUM_LENGTH?`CHAR(${e.CHARACTER_MAXIMUM_LENGTH})`:e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION?e.NUMERIC_SCALE!==null&&e.NUMERIC_SCALE!==void 0?`DECIMAL(${e.NUMERIC_PRECISION},${e.NUMERIC_SCALE})`:`DECIMAL(${e.NUMERIC_PRECISION})`:e.DATA_TYPE.toUpperCase()}function readSrid(e){if(e.SRS_ID===null||e.SRS_ID===void 0)return;let r=Number(e.SRS_ID);if(Number.isSafeInteger(r)&&r>=0&&r<=4294967295)return r;throw new n(`MySQL reported an invalid SRID for column "${e.TABLE_NAME}"."${e.COLUMN_NAME}". Migration introspection is refused rather than publishing an unprovable spatial type.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-srid`}})}function isAutoIncrement(e){return e.toLowerCase().includes(`auto_increment`)}function readDecimalDomain(e){if(e.DATA_TYPE===`decimal`&&e.NUMERIC_PRECISION!==null){let i=r(e.NUMERIC_PRECISION,e.NUMERIC_SCALE??0,`mysql`);if(i!==void 0)return i;throw new n(`MySQL reported column "${e.TABLE_NAME}"."${e.COLUMN_NAME}" as DECIMAL(${String(e.NUMERIC_PRECISION)},${String(e.NUMERIC_SCALE??0)}), outside VibORM's complete exact-decimal domain for this provider. Migration introspection is refused rather than publishing an invalid descriptor.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.TABLE_NAME,column:e.COLUMN_NAME,type:`invalid-catalog-decimal-domain`}})}if(e.DATA_TYPE===`json`)return b(e.COLUMN_COMMENT)}const P=/^_([A-Za-z0-9_]+)\\'([\s\S]*)\\'$/,F=/\\([\s\S]?)/g;function decodeSingleByte(e){return Array.from(e,e=>String.fromCharCode(e)).join(``)}const I=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];function decodeLatin1(e){return Array.from(e,e=>String.fromCharCode(e>=128&&e<=159?I[e-128]??e:e)).join(``)}const L=new Map([[`utf8`,T],[`utf8mb3`,T],[`utf8mb4`,T],[`latin1`,decodeLatin1],[`ascii`,decodeSingleByte],[`binary`,decodeSingleByte]]);function decodeIntroducedLiteral(e,t){let n=L.get(e.toLowerCase());if(n===void 0)return;let r=[...t].map(e=>e.codePointAt(0)??0);if(!r.some(e=>e>255))try{return n(Uint8Array.from(r))}catch{return}}function unescapeOneLayer(e){let t=!0,n=e.replace(F,(e,n)=>{let r=c.get(n);return r===void 0?(t=!1,n):r});return t?n:void 0}function deparsedStringValue(e){let t=P.exec(e),n=t?.[1],r=t?.[2],i=n===void 0||r===void 0?void 0:decodeIntroducedLiteral(n,r),a=i===void 0?void 0:unescapeOneLayer(i);return a===void 0?void 0:unescapeOneLayer(a)}function cleanDefault(e){let t=e.COLUMN_DEFAULT;if(t!==null){if(e.EXTRA.toUpperCase().includes(`DEFAULT_GENERATED`)){let e=deparsedStringValue(t);return e===void 0?t:`(${m(e)})`}return N.has(e.DATA_TYPE.toLowerCase())?t:m(t)}}function admitContainedForeignKeys(e,r,i){for(let a of e)if(!(i!==void 0&&!(a.TABLE_SCHEMA===r&&i.includes(a.TABLE_NAME))&&!(a.REFERENCED_TABLE_SCHEMA===r&&i.includes(a.REFERENCED_TABLE_NAME)))&&!(a.TABLE_SCHEMA===r&&a.REFERENCED_TABLE_SCHEMA===r))throw new n(`Foreign key "${a.CONSTRAINT_NAME}" crosses a database boundary: \`${a.TABLE_SCHEMA}\`.\`${a.TABLE_NAME}\` references \`${a.REFERENCED_TABLE_SCHEMA}\`.\`${a.REFERENCED_TABLE_NAME}\`, and this client manages only "${r}". 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`cross-database-foreign-key`,constraint:a.CONSTRAINT_NAME,namespace:r,table:`${a.TABLE_SCHEMA}.${a.TABLE_NAME}`,referencedTable:`${a.REFERENCED_TABLE_SCHEMA}.${a.REFERENCED_TABLE_NAME}`}})}async function introspect(e,r,i){let a=await resolveCatalogNamespace(e,r),o=[a],s=await e(`
26
26
  SELECT TABLE_NAME
27
27
  FROM information_schema.TABLES
28
28
  WHERE TABLE_SCHEMA = ?
@@ -94,6 +94,6 @@ JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
94
94
  WHERE tc.CONSTRAINT_TYPE = 'FOREIGN KEY'
95
95
  AND (tc.TABLE_SCHEMA = ? OR kcu.REFERENCED_TABLE_SCHEMA = ?)
96
96
  ORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
97
- `,[a,a]);admitContainedForeignKeys(d.rows,a,i);let p=O(c.rows,e=>e.TABLE_NAME),m=O(l.rows,e=>e.TABLE_NAME),h=D(u.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),_=D(d.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),v=[],y=new Set,b=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE),n=t&&f(t);t&&n&&!y.has(n)&&(v.push({name:n,values:t}),y.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=m.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=h.get(r),u=new Set(_.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(u.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0];if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let d=[],x=_.get(r);if(x)for(let[e,t]of x){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&d.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:k(n.DELETE_RULE),onUpdate:k(n.UPDATE_RULE)})}b.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:d,uniqueConstraints:[]})}return{tables:b,enums:v.length>0?v:void 0}}const R=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(R,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const z=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. 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.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=z.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const B=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],V=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,H=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const U=x.point.indexOf(` `),W=x.point.slice(0,U),G=x.point.slice(U+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||B.some(e=>e.test(t))}const K=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=K.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(H,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const q=new class MySQLMigrationDriver extends S{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||C(e.from)!==`list`||C(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${r(t)} to ${r(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}escapeValue(e){return e==null?`NULL`:m(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return E(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:s(n,r,`mysql`);if(i)return i.columnType;let a=o(r,`mysql`);return a&&!t.array?a.type:h({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(a(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!e.type||e.type===`btree`),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&V.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return f(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(H)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===x.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?W:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push(G),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&C(e)===`list`&&n.push(`COMMENT ${this.escapeValue(p(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
98
- `)}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,i,a){let{from:o,to:s}=e,c=o.decimal,u=s.decimal;if(u===void 0||!l(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let d=C(s);if(c===void 0)return(d!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,d),this.decimalScalarConversionBracket(e,i,s.type,u);let f=C(o);if((d===void 0||f!==d)&&this.refuseDecimalConversion(e,a,`moves it from ${v(f)} to ${v(d)} storage, which`),d===`list`){let t=classifyDecimalListDescriptorChange(c,u);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${r(c)} to ${r(u)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${r(c)} to ${r(u)}, which`),this.decimalListConversionBracket(e,i,c)}return this.decimalScalarConversionBracket(e,i,s.type,u)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(w(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${u(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(w(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${_(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${v(i)}. 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. 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.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. 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.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{q as t};
99
- //# sourceMappingURL=mysql-D7zC03yD.mjs.map
97
+ `,[a,a]);admitContainedForeignKeys(d.rows,a,i);let p=O(c.rows,e=>e.TABLE_NAME),m=O(l.rows,e=>e.TABLE_NAME),h=D(u.rows,e=>e.TABLE_NAME,e=>e.INDEX_NAME),_=D(d.rows.filter(e=>e.TABLE_SCHEMA===a),e=>e.TABLE_NAME,e=>e.CONSTRAINT_NAME),v=[],y=new Set,b=[];for(let e of s.rows){let r=e.TABLE_NAME,a=[];for(let e of p.get(r)||[]){if((i===void 0||i.includes(r))&&(e.EXTRA.toUpperCase().includes(`VIRTUAL GENERATED`)||e.EXTRA.toUpperCase().includes(`STORED GENERATED`)))throw new n(`MySQL column "${r}.${e.COLUMN_NAME}" is generated. Synchronization refuses before effects because its expression cannot be represented.`,t.MIGRATION_INVALID_STATE,{meta:{table:r,column:e.COLUMN_NAME,feature:`generated column`}});if(e.DATA_TYPE===`enum`){let t=g(e.COLUMN_TYPE),n=t&&f(t);t&&n&&!y.has(n)&&(v.push({name:n,values:t}),y.add(n))}let o=i===void 0||i.includes(r),s=o?readDecimalDomain(e):void 0;a.push({name:e.COLUMN_NAME,type:o?formatColumnType(e):e.COLUMN_TYPE,nullable:e.IS_NULLABLE===`YES`,default:o?cleanDefault(e):void 0,autoIncrement:isAutoIncrement(e.EXTRA),decimal:s})}let o,s=m.get(r);if(s&&s.length>0){s.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let e=s[0];e&&(o={columns:s.map(e=>e.COLUMN_NAME),name:e.CONSTRAINT_NAME})}let c=[],l=h.get(r),u=new Set(_.get(r)?.keys()??[]);if(l)for(let[e,t]of l){if(u.has(e))continue;t.sort((e,t)=>e.SEQ_IN_INDEX-t.SEQ_IN_INDEX);let n=t[0];if(n){let r=n.INDEX_TYPE.toLowerCase(),i=r===`rtree`?`spatial`:r;c.push({name:e,columns:t.map(e=>e.COLUMN_NAME),unique:n.NON_UNIQUE===0,type:i===`btree`||i===`hash`||i===`fulltext`||i===`spatial`?i:void 0})}}let d=[],x=_.get(r);if(x)for(let[e,t]of x){t.sort((e,t)=>e.ORDINAL_POSITION-t.ORDINAL_POSITION);let n=t[0];n&&d.push({name:e,columns:t.map(e=>e.COLUMN_NAME),referencedTable:n.REFERENCED_TABLE_NAME,referencedColumns:t.map(e=>e.REFERENCED_COLUMN_NAME),onDelete:k(n.DELETE_RULE),onUpdate:k(n.UPDATE_RULE)})}b.push({name:r,columns:a,primaryKey:o,indexes:c,foreignKeys:d,uniqueConstraints:[]})}return{tables:b,enums:v.length>0?v:void 0}}const R=/[^a-z0-9_]/g;function hashLockScope(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function mysqlMigrationLockName(e){let t=e.toLowerCase();return`viborm_migration_${t.replace(R,`_`).slice(0,38)}_${hashLockScope(t)}`}function mysqlAcquireLockStatement(e,t,n){return`SELECT GET_LOCK(${n(mysqlMigrationLockName(e))}, ${t}) AS acquired`}function mysqlReleaseLockStatement(e,t){return`SELECT RELEASE_LOCK(${t(mysqlMigrationLockName(e))}) AS released`}function mysqlLockAnswer(e,t){if(e.length!==1)return!1;let n=e[0];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,t);return typeof r==`number`?r===1:typeof r==`string`?Number(r)===1:!1}function mysqlSelectTargetStatement(e,t){return`USE ${t(e)}`}const z=/^(\d+)\.(\d+)\.(\d+)/;async function proveMySQLExactValueSession(e,r){let{rows:i}=await e(`SELECT @@SESSION.sql_mode AS sql_mode, VERSION() AS server_version`),a=i[0],o=typeof a==`object`&&a?Reflect.get(a,`sql_mode`):void 0,s=typeof o==`string`?o:``,c=typeof a==`object`&&a?Reflect.get(a,`server_version`):void 0,l=typeof c==`string`?c:`<unreported>`;if(!supportsEnforcedMySQLChecks(l))throw new n(`This MySQL migration session reports version "${l}". Fixed-decimal conversions require MySQL 8.0.16 or later, where CHECK constraints are enforced; the command is refused before any migration effect.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`unenforced-check-constraints`,target:r}});if(!s.split(`,`).some(e=>{let t=e.trim();return t===`STRICT_TRANS_TABLES`||t===`STRICT_ALL_TABLES`}))throw new n(`This MySQL session runs in sql_mode "${s}", which has neither STRICT_TRANS_TABLES nor STRICT_ALL_TABLES. 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.`,t.DRIVER_NOT_SUPPORTED,{meta:{dialect:`mysql`,type:`non-strict-sql-mode`,target:r}})}function supportsEnforcedMySQLChecks(e){if(e.toLowerCase().includes(`mariadb`))return!1;let t=z.exec(e);if(t===null)return!1;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return n>8||n===8&&(r>0||i>=16)}const B=[/^GEOMETRY\b/,/^POINT\b/,/^LINESTRING\b/,/^POLYGON\b/,/^MULTIPOINT\b/,/^MULTILINESTRING\b/,/^MULTIPOLYGON\b/,/^GEOMETRYCOLLECTION\b/],V=/^(?:(?:TINY|MEDIUM|LONG)?(?:TEXT|BLOB)|JSON|GEOMETRY|POINT|LINESTRING|POLYGON|MULTI(?:POINT|LINESTRING|POLYGON)|GEOMETRYCOLLECTION)\b/i,H=/[\s(]/;function classifyDecimalListDescriptorChange(e,t){return e.scale===t.scale?e.precision<t.precision?`widening`:e.precision>t.precision?`narrowing`:`same`:`rescaling`}const U=x.point.indexOf(` `),W=x.point.slice(0,U),G=x.point.slice(U+1);function mysqlRefusesLiteralDefault(e){let t=e.toUpperCase();return t.includes(`TEXT`)||t.includes(`BLOB`)||t.includes(`JSON`)||B.some(e=>e.test(t))}const K=/^(?:DATETIME|TIMESTAMP)\s*(?:\((\d+)\))?$/i;function mysqlNowExpression(e){let t=K.exec(e.trim());if(t!==null)return t[1]===void 0?`CURRENT_TIMESTAMP`:`CURRENT_TIMESTAMP(${t[1]})`}function finalizeMySQLColumn(e,t){let n=e.type.toUpperCase()===`TEXT`&&t?`VARCHAR(191)`:e.type,r=e.default!==void 0&&mysqlRefusesLiteralDefault(n)?`(${e.default})`:e.default;return n===e.type&&r===e.default?e:{...e,type:n,default:r}}function isMySQLExactIntegerType(e){let t=e.trim().toUpperCase().split(H,1)[0];return t===`INT`||t===`INTEGER`||t===`BIGINT`}const q=new class MySQLMigrationDriver extends S{dialect=`mysql`;driverName=`mysql`;capabilities={supportsNativeEnums:!0,supportsAddEnumValueInTransaction:!1,supportsIndexTypes:[`btree`,`fulltext`,`spatial`],supportsNativeArrays:!1,supportsAddForeignKeyViaAlter:!0,introspectionReadsConstraintNames:!0};getIrreversibleRollbackReason(e){if(e.type!==`alterColumn`)return;let t=e.from.decimal,n=e.to.decimal;if(!(t===void 0||n===void 0||C(e.from)!==`list`||C(e.to)!==`list`||classifyDecimalListDescriptorChange(t,n)!==`narrowing`))return`MySQL cannot automatically roll back the decimal-list widening of "${e.tableName}"."${e.columnName}": the inverse narrows ${i(t)} to ${i(n)}, and its implicit DDL commits cannot make the stricter proof, descriptor-marker change, and cleanup indivisible.`}async preflightSchemaRequirements(e,r){let i=new Set(e.flatMap(e=>e.tables.map(e=>e.name)));if(i.size===0)return!1;let a=await resolveCatalogNamespace(r,this.namespace),o=(await r(`SELECT TABLE_NAME FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ?`,[a])).rows.find(e=>i.has(e.TABLE_NAME));if(o)throw new n(`MySQL relation "${o.TABLE_NAME}" is a view, but this schema declares a table. Synchronization refuses before effects and preserves the view.`,t.MIGRATION_INVALID_STATE,{meta:{table:o.TABLE_NAME,feature:`view`,namespace:a}});return!1}introspect(e){return introspect(e,this.namespace,this.target?.tables)}escapeValue(e){return e==null?`NULL`:m(String(e))}escapeIdentifier(e){if(e==null)throw new n(`Cannot escape null or undefined identifier`,t.INVALID_INPUT);return`\`${String(e).replace(/`/g,"``")}\``}tableRef(e,t){return E(e=>this.escapeIdentifier(e),t===`live`?this.namespace:void 0,e)}mapScalarType(e,t,n){let r=e[`~`].nativeType,i=n===void 0||t.array===!0?void 0:o(n,r,`mysql`);if(i)return i.columnType;let s=a(r,`mysql`);return s&&!t.array?s.type:h({type:t.type,array:t.array,decimal:t.decimal})}getDefaultExpression(e,t){let n=t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate?this.literalDefaultValue(t):void 0;if(t.type===`datetime`&&!t.array&&t.hasDefault&&!t.autoGenerate&&typeof n==`string`)return this.escapeValue(s(n));if(!(t.hasDefault&&t.default===null))return t.autoGenerate?.kind===`now`?mysqlNowExpression(this.mapScalarType(e,t)):super.getDefaultExpression(e,t)}finalizeTable(e){let r=new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),i=new Set(e.indexes.map(e=>e.name)),a=e.uniqueConstraints.filter(e=>!i.has(e.name)).map(e=>({name:e.name,columns:e.columns,unique:!0})),o={...e,primaryKey:e.primaryKey?{...e.primaryKey,name:`PRIMARY`}:void 0,columns:e.columns.map(e=>finalizeMySQLColumn(e,r.has(e.name))),indexes:[...e.indexes,...a],uniqueConstraints:[]},s=o.indexes.filter(e=>!e.type||e.type===`btree`),c=[{name:`PRIMARY`,columns:o.primaryKey?.columns??[]},...s.map(e=>({name:e.name,columns:e.columns})),...o.foreignKeys.map(e=>({name:e.name,columns:e.columns}))];for(let{name:r,columns:i}of c)for(let a of i){let i=o.columns.find(e=>e.name===a);if(i&&V.test(i.type))throw new n(`MySQL key "${e.name}.${r}" cannot directly index ${i.type} column "${i.name}". Use an indexable native type such as VARCHAR, or manage a reviewed prefix/expression index outside this declaration.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.name,column:i.name}})}let l=o.columns.filter(e=>e.autoIncrement);if(l.length>1||l.some(e=>o.primaryKey?.columns[0]!==e.name&&!s.some(t=>t.columns[0]===e.name&&!t.where)&&!o.foreignKeys.some(t=>t.columns[0]===e.name)))throw new n(`MySQL table "${e.name}" requires at most one AUTO_INCREMENT column, first in an ordinary key. Declare its primary key or leading index explicitly.`,t.INVALID_INPUT,{meta:{table:e.name}});return o}formatBooleanDefault(e){return e?`1`:`0`}getEnumColumnType(e,t,n){return f(n)}static AUTO_INCREMENT_TYPES=new Set([`tinyint`,`smallint`,`mediumint`,`int`,`integer`,`bigint`]);validateAutoIncrementType(e){let r=e.type.toLowerCase().split(H)[0];if(!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(r))throw new n(`MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). Column "${e.name}" has type "${e.type}" which is not compatible with AUTO_INCREMENT.`,t.INVALID_INPUT,{meta:{column:e.name,type:e.type,autoIncrement:!0}})}generateColumnDef(e,t){let n=[this.escapeIdentifier(e.name)],r=e.type.toUpperCase()===x.point;return e.autoIncrement?(this.validateAutoIncrementType(e),n.push(e.type),n.push(`AUTO_INCREMENT`)):n.push(r?W:e.type),e.nullable||n.push(`NOT NULL`),r&&n.push(G),e.default!==void 0&&!e.autoIncrement&&n.push(`DEFAULT ${e.default}`),e.decimal&&C(e)===`list`&&n.push(`COMMENT ${this.escapeValue(p(e.decimal))}`),n.join(` `)}generateCreateTable(e,t){let{table:n}=e,r=n.columns.map(e=>this.generateColumnDef(e,t)),i=n.columns.find(e=>e.autoIncrement),a=i&&n.primaryKey?.columns[0]!==i.name?n.indexes.find(e=>(!e.type||e.type===`btree`)&&!e.where&&e.columns[0]===i.name):void 0;if(a&&r.push(`${a.unique?`UNIQUE `:``}KEY ${this.escapeIdentifier(a.name)} (${a.columns.map(e=>this.escapeIdentifier(e)).join(`, `)})`),n.primaryKey){let e=n.primaryKey.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`PRIMARY KEY (${e})`)}for(let e of n.uniqueConstraints){let t=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `);r.push(`CONSTRAINT ${this.escapeIdentifier(e.name)} UNIQUE (${t})`)}for(let e of n.foreignKeys)r.push(this.foreignKeyClause(e,t));let o=[`CREATE TABLE ${this.tableRef(n.name,t.destination)} (\n ${r.join(`,
98
+ `)}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin`];for(let e of n.indexes)e!==a&&o.push(this.generateCreateIndex({type:`createIndex`,tableName:n.name,index:e},t));return o}generateDropTable(e,t){return`DROP TABLE IF EXISTS ${this.tableRef(e.tableName,t.destination)}`}generateRenameTable(e,t){return`RENAME TABLE ${this.tableRef(e.from,t.destination)} TO ${this.tableRef(e.to,t.destination)}`}renameDerivedNames(e,t,n,r){let i=[...t].map(([e,{to:t}])=>{let i=n.foreignKeys.find(t=>t.name===e);return i?`DROP FOREIGN KEY ${this.escapeIdentifier(e)}, ADD ${this.foreignKeyClause({...i,name:t},r)}`:`RENAME INDEX ${this.escapeIdentifier(e)} TO ${this.escapeIdentifier(t)}`});return[`ALTER TABLE ${this.tableRef(e,r.destination)} ${i.join(`, `)}`]}generateAddColumn(e,t){let n=this.generateColumnDef(e.column,t);return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD COLUMN ${n}`}generateDropColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP COLUMN ${this.escapeIdentifier(e.columnName)}`}generateRenameColumn(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} RENAME COLUMN ${this.escapeIdentifier(e.from)} TO ${this.escapeIdentifier(e.to)}`}generateAlterColumn(e,t){let{tableName:n,columnName:r,to:i}=e,a=this.tableRef(n,t.destination),o=this.generateColumnDef(i,t),s=r===i.name?`ALTER TABLE ${a} MODIFY COLUMN ${o}`:`ALTER TABLE ${a} CHANGE COLUMN ${this.escapeIdentifier(r)} ${o}`,c=this.decimalConversionBracket(e,a,t);return c===null?[s]:[c.validate,s,c.release]}decimalConversionBracket(e,r,a){let{from:o,to:s}=e,c=o.decimal,u=s.decimal;if(u===void 0||!l(o,s))return null;if(e.columnName!==s.name)throw new n(`The MySQL decimal conversion for "${e.tableName}"."${e.columnName}" also renames the column to "${s.name}". 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,table:e.tableName,column:e.columnName,type:`decimal-conversion-with-rename`}});let d=C(s);if(c===void 0)return(d!==`scalar`||!isMySQLExactIntegerType(o.type))&&this.refuseDecimalAdoption(e,a,d),this.decimalScalarConversionBracket(e,r,s.type,u);let f=C(o);if((d===void 0||f!==d)&&this.refuseDecimalConversion(e,a,`moves it from ${v(f)} to ${v(d)} storage, which`),d===`list`){let t=classifyDecimalListDescriptorChange(c,u);return t===`rescaling`&&this.refuseDecimalConversion(e,a,`moves its JSON list from ${i(c)} to ${i(u)}, which rescales every member and so`),t===`narrowing`&&this.refuseDecimalConversion(e,a,`narrows its JSON list from ${i(c)} to ${i(u)}, which`),this.decimalListConversionBracket(e,r,c)}return this.decimalScalarConversionBracket(e,r,s.type,u)}decimalListConversionBracket(e,t,n){let r=this.escapeIdentifier(w(`list`,n));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${r} CHECK (${u(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${r}`}}decimalScalarConversionBracket(e,t,n,r){let i=this.escapeIdentifier(w(`scalar`,r));return{validate:`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${_(this.escapeIdentifier(e.columnName),n)})`,release:`ALTER TABLE ${t} DROP CHECK ${i}`}}refuseDecimalAdoption(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" would adopt unmarked ${e.from.type} storage as a fixed-decimal ${v(i)}. 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. 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.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal storage adoption`,dialect:`mysql`,target:r.destination}})}refuseDecimalConversion(e,r,i){throw new n(`The declared change to "${e.tableName}"."${e.columnName}" ${i} would rewrite every stored value, and MySQL commits each DDL statement implicitly. There is no boundary that could make the member rewrite and its descriptor-marker change indivisible. 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.`,t.FEATURE_NOT_SUPPORTED,{meta:{table:e.tableName,column:e.columnName,feature:`decimal descriptor conversion`,dialect:`mysql`,target:r.destination}})}generateCreateIndex(e,r){let{tableName:i,index:a}=e;if(this.validateIndexType(a.type,a.name),a.where)throw new n(`Index "${a.name}" declares a partial index predicate (where: "${a.where}"). MySQL does not support partial indexes. Either remove 'where' from the index definition, or move the predicate into a generated column and index that.`,t.FEATURE_NOT_SUPPORTED,{meta:{indexName:a.name,indexWhere:a.where}});let o=a.columns.map(e=>this.escapeIdentifier(e)).join(`, `),s=``;if(a.type===`fulltext`?s=`FULLTEXT `:a.type===`spatial`&&(s=`SPATIAL `),a.unique&&s)throw new n(`Cannot combine UNIQUE with ${a.type?.toUpperCase()} index "${a.name}". MySQL does not support UNIQUE ${a.type?.toUpperCase()} indexes. Either remove 'unique: true' from the index definition, or create a separate unique index.`,t.MIGRATION_FAILED,{meta:{indexName:a.name,indexType:a.type}});return`CREATE ${a.unique?`UNIQUE `:``}${s}INDEX ${this.escapeIdentifier(a.name)} ON ${this.tableRef(i,r.destination)} (${o})`}generateDropIndex(e,t){return`DROP INDEX ${this.escapeIdentifier(e.indexName)} ON ${this.tableRef(e.tableName,t.destination)}`}generateAddForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} ADD ${this.foreignKeyClause(e.fk,t)}`}foreignKeyClause(e,t){let n=e.columns.map(e=>this.escapeIdentifier(e)).join(`, `),r=e.referencedColumns.map(e=>this.escapeIdentifier(e)).join(`, `),i=`CONSTRAINT ${this.escapeIdentifier(e.name)} `;return i+=`FOREIGN KEY (${n}) `,i+=`REFERENCES ${this.tableRef(e.referencedTable,t.destination)} (${r})`,e.onDelete&&e.onDelete!==`noAction`&&(i+=` ON DELETE ${this.formatReferentialAction(e.onDelete)}`),e.onUpdate&&e.onUpdate!==`noAction`&&(i+=` ON UPDATE ${this.formatReferentialAction(e.onUpdate)}`),i}generateDropForeignKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP FOREIGN KEY ${this.escapeIdentifier(e.fkName)}`}generateAddUniqueConstraint(e,t){let{tableName:n,constraint:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD CONSTRAINT ${this.escapeIdentifier(r.name)} UNIQUE (${i})`}generateDropUniqueConstraint(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP INDEX ${this.escapeIdentifier(e.constraintName)}`}generateAddPrimaryKey(e,t){let{tableName:n,primaryKey:r}=e,i=r.columns.map(e=>this.escapeIdentifier(e)).join(`, `);return`ALTER TABLE ${this.tableRef(n,t.destination)} ADD PRIMARY KEY (${i})`}generateDropPrimaryKey(e,t){return`ALTER TABLE ${this.tableRef(e.tableName,t.destination)} DROP PRIMARY KEY`}generateCreateEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateDropEnum(e,t){return`-- MySQL: ENUM type is part of column definition`}generateAlterEnum(e,t){let{enumName:n,newValues:r,dependentColumns:i}=e;if(!r||r.length===0)return[`-- MySQL: no new values provided for enum "${n}"`];if(!i||i.length===0)return[`-- MySQL: no dependent columns found for enum "${n}"`];let a=[],o=this.getEnumColumnType(``,``,r);a.push(...this.buildEnumReplacementUpdates(e,t));for(let e of i){let n=(t.currentSchema?.tables.find(t=>t.name===e.tableName))?.columns.find(t=>t.name===e.columnName);if(!n){a.push(`-- MySQL: column "${e.columnName}" not found in table "${e.tableName}"`);continue}let r=this.tableRef(e.tableName,t.destination),i=this.escapeIdentifier(e.columnName),s=n.nullable?``:` NOT NULL`,c=n.default===void 0?``:` DEFAULT ${n.default}`;a.push(`ALTER TABLE ${r} MODIFY COLUMN ${i} ${o}${s}${c}`)}return a}async proveNamespaceExists(e){await this.resolveCommandNamespace(e)}async resolveCommandNamespace(e){return await resolveCatalogNamespace(e,this.namespace)}generateAcquireLock(e){return mysqlAcquireLockStatement(this.requireLockScope(),30,e=>this.escapeValue(e))}generateReleaseLock(e){return mysqlReleaseLockStatement(this.requireLockScope(),e=>this.escapeValue(e))}provesLockAcquired(e){return mysqlLockAnswer(e,`acquired`)}provesLockReleased(e){return mysqlLockAnswer(e,`released`)}generateSelectTarget(){return this.namespace===void 0?null:mysqlSelectTargetStatement(this.namespace,e=>this.escapeIdentifier(e))}async proveSession(e){await proveMySQLExactValueSession(e,`database "${this.namespace??`(unbound)`}"`);let t=this.requireLockScope(),n=!1,r,i=Object.create(this);return Object.defineProperty(i,`programPreamble`,{value:async e=>{if(n)return[];if(r!==void 0)return await r,[];r=planInterruptedMySQLDecimalRecovery((t,n)=>e._executeRaw(t,n),t,e=>this.escapeIdentifier(e));try{let e=await r;return n=!0,e}catch(e){throw r=void 0,e}}}),Object.freeze(i),i}programPreamble(){return Promise.reject(new n(`This MySQL sequential migration program is not bound to its locked command's decimal-recovery scope.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-migration-command`}}))}requireLockScope(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no lock scope to name. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return this.namespace}generateInventoryTables(){if(this.namespace===void 0)throw new n(`This MySQL migration driver is not bound to a database, so there is no table inventory to read. 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.`,t.MIGRATION_INVALID_STATE,{meta:{dialect:`mysql`,type:`unbound-database`}});return{sql:`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,params:[this.namespace]}}generateInventoryEnums(){return null}};export{q as t};
99
+ //# sourceMappingURL=mysql-xChEivOe.mjs.map