viborm 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/README.md +4 -3
  2. package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
  3. package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
  4. package/dist/adapters.d.mts +1 -1
  5. package/dist/adapters.mjs +1 -1
  6. package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  7. package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  8. package/dist/base-AdXAoy6l.mjs +2 -0
  9. package/dist/base-AdXAoy6l.mjs.map +1 -0
  10. package/dist/batch-refs-4L8ECdPU.mjs +2 -0
  11. package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
  12. package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
  13. package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
  14. package/dist/builder-Ycvq3ETg.mjs +2 -0
  15. package/dist/builder-Ycvq3ETg.mjs.map +1 -0
  16. package/dist/bun-sql.d.mts +19 -2
  17. package/dist/bun-sql.mjs +1 -1
  18. package/dist/bun-sql.mjs.map +1 -1
  19. package/dist/bun-sqlite.d.mts +9 -8
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/bun-sqlite.mjs.map +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache/memory.mjs.map +1 -1
  27. package/dist/cache-BO57X0TT.mjs +2 -0
  28. package/dist/cache-BO57X0TT.mjs.map +1 -0
  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 +2 -0
  33. package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
  34. package/dist/chain-Dh0FV72b.mjs +2 -0
  35. package/dist/chain-Dh0FV72b.mjs.map +1 -0
  36. package/dist/cli.mjs +5 -6
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-BLiBmykn.mjs +2 -0
  39. package/dist/client-BLiBmykn.mjs.map +1 -0
  40. package/dist/client-CCgfcp5A.mjs +52 -0
  41. package/dist/client-CCgfcp5A.mjs.map +1 -0
  42. package/dist/client-CRBo95D0.d.mts +610 -0
  43. package/dist/client.d.mts +1 -1
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
  46. package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-DXgIn4zh.mjs +2 -0
  50. package/dist/controls-DXgIn4zh.mjs.map +1 -0
  51. package/dist/d1.d.mts +1 -1
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
  55. package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
  56. package/dist/driver-B19QlFqn.mjs +2 -0
  57. package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
  58. package/dist/driver-BlnKXPFF.mjs +2 -0
  59. package/dist/driver-BlnKXPFF.mjs.map +1 -0
  60. package/dist/driver.d.mts +2 -2
  61. package/dist/driver.mjs +1 -1
  62. package/dist/error-mapping-CnPCv1dm.mjs +2 -0
  63. package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
  64. package/dist/every-4KE0p2Gw.mjs +2 -0
  65. package/dist/every-4KE0p2Gw.mjs.map +1 -0
  66. package/dist/execution-context-BKR3bgES.mjs +2 -0
  67. package/dist/execution-context-BKR3bgES.mjs.map +1 -0
  68. package/dist/fs-estate-CAhDg7nY.mjs +2 -0
  69. package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
  70. package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
  71. package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
  72. package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
  73. package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
  74. package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
  75. package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
  76. package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
  77. package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
  78. package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
  79. package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
  80. package/dist/identity-CLFhCTZx.mjs +2 -0
  81. package/dist/identity-CLFhCTZx.mjs.map +1 -0
  82. package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
  83. package/dist/index.d.mts +2 -2
  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/instrumentation.mjs.map +1 -1
  89. package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
  90. package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
  91. package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
  92. package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  93. package/dist/key-BeoOwGr3.mjs +2 -0
  94. package/dist/key-BeoOwGr3.mjs.map +1 -0
  95. package/dist/libsql-Bu_IdFU1.mjs +11 -0
  96. package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
  97. package/dist/libsql.d.mts +8 -3
  98. package/dist/libsql.mjs +1 -1
  99. package/dist/libsql.mjs.map +1 -1
  100. package/dist/memory-D4yxtCPK.mjs +2 -0
  101. package/dist/memory-D4yxtCPK.mjs.map +1 -0
  102. package/dist/migrations/mysql.d.mts +6 -0
  103. package/dist/migrations/mysql.mjs +2 -0
  104. package/dist/migrations/mysql.mjs.map +1 -0
  105. package/dist/migrations/postgres.d.mts +6 -0
  106. package/dist/migrations/postgres.mjs +2 -0
  107. package/dist/migrations/postgres.mjs.map +1 -0
  108. package/dist/migrations/sqlite.d.mts +6 -0
  109. package/dist/migrations/sqlite.mjs +2 -0
  110. package/dist/migrations/sqlite.mjs.map +1 -0
  111. package/dist/migrations/storage/durable-object.d.mts +17 -0
  112. package/dist/migrations/storage/durable-object.mjs +2 -0
  113. package/dist/migrations/storage/durable-object.mjs.map +1 -0
  114. package/dist/migrations/storage/fs.d.mts +6 -1
  115. package/dist/migrations/storage/fs.mjs +1 -1
  116. package/dist/migrations/storage/r2.d.mts +14 -0
  117. package/dist/migrations/storage/r2.mjs +2 -0
  118. package/dist/migrations/storage/r2.mjs.map +1 -0
  119. package/dist/migrations/tenant.d.mts +92 -0
  120. package/dist/migrations/tenant.mjs +2 -0
  121. package/dist/migrations/tenant.mjs.map +1 -0
  122. package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
  123. package/dist/migrations-DTObIjAm.mjs.map +1 -0
  124. package/dist/migrations.d.mts +6 -559
  125. package/dist/migrations.mjs +1 -1
  126. package/dist/migrations.mjs.map +1 -1
  127. package/dist/mysql-CibPaHSp.mjs +99 -0
  128. package/dist/mysql-CibPaHSp.mjs.map +1 -0
  129. package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
  130. package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
  131. package/dist/mysql2.d.mts +1 -3
  132. package/dist/mysql2.mjs +1 -1
  133. package/dist/mysql2.mjs.map +1 -1
  134. package/dist/neon-http.d.mts +1 -1
  135. package/dist/neon-http.mjs +1 -1
  136. package/dist/neon-http.mjs.map +1 -1
  137. package/dist/object-store-DQR6bTBY.mjs +2 -0
  138. package/dist/object-store-DQR6bTBY.mjs.map +1 -0
  139. package/dist/object-store-DyYOCtmX.d.mts +156 -0
  140. package/dist/observation-DUSm7oXK.mjs +2 -0
  141. package/dist/observation-DUSm7oXK.mjs.map +1 -0
  142. package/dist/pg.d.mts +37 -12
  143. package/dist/pg.mjs +1 -1
  144. package/dist/pg.mjs.map +1 -1
  145. package/dist/pglite.d.mts +2 -1
  146. package/dist/pglite.mjs +1 -1
  147. package/dist/pglite.mjs.map +1 -1
  148. package/dist/physical-6V_LNU3L.mjs +2 -0
  149. package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
  150. package/dist/pinned-session-CLxj5M5e.mjs +2 -0
  151. package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
  152. package/dist/planetscale.d.mts +1 -1
  153. package/dist/planetscale.mjs +1 -1
  154. package/dist/planetscale.mjs.map +1 -1
  155. package/dist/{planner-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
  156. package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
  157. package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
  158. package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
  159. package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
  160. package/dist/postgres-oqNW9xqo.mjs +415 -0
  161. package/dist/postgres-oqNW9xqo.mjs.map +1 -0
  162. package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
  163. package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
  164. package/dist/postgres.d.mts +11 -1
  165. package/dist/postgres.mjs +1 -1
  166. package/dist/postgres.mjs.map +1 -1
  167. package/dist/provider-limits-BHATED_m.mjs +2 -0
  168. package/dist/provider-limits-BHATED_m.mjs.map +1 -0
  169. package/dist/registration-preflight-DEjv050M.mjs +4 -0
  170. package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
  171. package/dist/result-shape-CTNdNSW3.mjs +2 -0
  172. package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
  173. package/dist/scalar-U0wD5bKy.mjs +2 -0
  174. package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
  175. package/dist/schema/json.d.mts +1 -1
  176. package/dist/schema/json.mjs +1 -1
  177. package/dist/schema/json.mjs.map +1 -1
  178. package/dist/schema-Cjem1-0f.mjs +2 -0
  179. package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
  180. package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
  181. package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
  182. package/dist/schema.d.mts +1 -1
  183. package/dist/schema.mjs +1 -1
  184. package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
  185. package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
  186. package/dist/settle-B9Vg1FnP.mjs +2 -0
  187. package/dist/settle-B9Vg1FnP.mjs.map +1 -0
  188. package/dist/soft-delete.d.mts +1 -1
  189. package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
  190. package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
  191. package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
  192. package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
  193. package/dist/sql.d.mts +1 -1
  194. package/dist/sql.mjs +1 -1
  195. package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
  196. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
  197. package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
  198. package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
  199. package/dist/sqlite3.d.mts +2 -8
  200. package/dist/sqlite3.mjs +1 -1
  201. package/dist/sqlite3.mjs.map +1 -1
  202. package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
  203. package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
  204. package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
  205. package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
  206. package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
  207. package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
  208. package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
  209. package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
  210. package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
  211. package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
  212. package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
  213. package/dist/utils-CZNaOZR7.mjs.map +1 -0
  214. package/dist/v-D5Z06FKN.mjs +2 -0
  215. package/dist/v-D5Z06FKN.mjs.map +1 -0
  216. package/dist/validation-Dk9Q_-C7.mjs +2 -0
  217. package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
  218. package/dist/validation-PF9-_nKd.mjs +2 -0
  219. package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
  220. package/dist/validation.d.mts +1 -1
  221. package/dist/validation.mjs +1 -1
  222. package/dist/validator-X9-bwtRo.mjs +2 -0
  223. package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
  224. package/dist/value-guards-CK9guf2Z.mjs +2 -0
  225. package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
  226. package/dist/version-JDaZht4U.mjs +2 -0
  227. package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
  228. package/package.json +75 -34
  229. package/dist/base-vfur-DaU.mjs +0 -2
  230. package/dist/base-vfur-DaU.mjs.map +0 -1
  231. package/dist/batch-refs-BY51FIXm.mjs +0 -6
  232. package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
  233. package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
  234. package/dist/builder-bPfagDQV.mjs +0 -2
  235. package/dist/builder-bPfagDQV.mjs.map +0 -1
  236. package/dist/chain-uIFlkkXS.mjs +0 -2
  237. package/dist/chain-uIFlkkXS.mjs.map +0 -1
  238. package/dist/client-NleI4Nm-.mjs +0 -434
  239. package/dist/client-NleI4Nm-.mjs.map +0 -1
  240. package/dist/client-tjSMPjeZ.mjs +0 -2
  241. package/dist/client-tjSMPjeZ.mjs.map +0 -1
  242. package/dist/controls-BhxRnPYS.mjs +0 -2
  243. package/dist/controls-BhxRnPYS.mjs.map +0 -1
  244. package/dist/decimal-12NERGYZ.mjs +0 -3
  245. package/dist/decimal-12NERGYZ.mjs.map +0 -1
  246. package/dist/driver-CRaDT4B7.mjs +0 -2
  247. package/dist/driver-options-DxlB1tms.mjs +0 -2
  248. package/dist/driver-options-DxlB1tms.mjs.map +0 -1
  249. package/dist/driver-yCYqzIQg.mjs +0 -2
  250. package/dist/driver-yCYqzIQg.mjs.map +0 -1
  251. package/dist/error-mapping-BWzb-l02.mjs +0 -2
  252. package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
  253. package/dist/execution-context-BPk0YLhd.mjs +0 -2
  254. package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
  255. package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
  256. package/dist/fs-estate-BcjgY4iY.mjs +0 -2
  257. package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
  258. package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
  259. package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
  260. package/dist/identifiers-By-JRCb5.mjs +0 -2
  261. package/dist/identifiers-By-JRCb5.mjs.map +0 -1
  262. package/dist/key-DKaqPb8w.mjs +0 -2
  263. package/dist/key-DKaqPb8w.mjs.map +0 -1
  264. package/dist/migrations-BWZSBMZh.mjs.map +0 -1
  265. package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
  266. package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
  267. package/dist/observation-CLp8ylmL.mjs +0 -2
  268. package/dist/observation-CLp8ylmL.mjs.map +0 -1
  269. package/dist/physical-BkelResN.mjs +0 -2
  270. package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
  271. package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
  272. package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
  273. package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
  274. package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
  275. package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
  276. package/dist/result-shape-DKTu8yre.mjs +0 -2
  277. package/dist/result-shape-DKTu8yre.mjs.map +0 -1
  278. package/dist/scalar-BTktMqvO.mjs +0 -2
  279. package/dist/schema-BFNcMdO6.mjs +0 -2
  280. package/dist/schema-introspection-DsXPfCst.mjs +0 -6
  281. package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
  282. package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
  283. package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
  284. package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
  285. package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
  286. package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
  287. package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
  288. package/dist/transaction-oskVwmsf.mjs.map +0 -1
  289. package/dist/transactions-gjmrWN5W.mjs +0 -2
  290. package/dist/transactions-gjmrWN5W.mjs.map +0 -1
  291. package/dist/utils-DfztpPvR.mjs.map +0 -1
  292. package/dist/v-B2WwtcRz.mjs +0 -2
  293. package/dist/v-B2WwtcRz.mjs.map +0 -1
  294. package/dist/validation-Du6j0Q38.mjs +0 -2
  295. package/dist/validation-Du6j0Q38.mjs.map +0 -1
  296. package/dist/validation-tgjL_9n8.mjs +0 -2
  297. package/dist/validator-DMlEScV3.mjs +0 -2
  298. package/dist/version-Cr80LFvx.mjs +0 -2
  299. /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
  300. /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
@@ -0,0 +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,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW,EAAU,GAAG,EAAM,GAAG,CAAC,GA0B5D,kBAAoB,EAAY,IAAuC,CAC3E,GAAM,CAAE,SAAU,EAClB,GAAI,IAAU,EAAG,OAAO,EACxB,IAAM,EAAS,EAAe,EAAM,CAC9B,EAAQ,CAAG,YAAY,EAAM,MAEnC,MA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ACC,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"}
package/dist/mysql2.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, Vt as DriverTransactionOptions, d as PinnedSessionReservation, jt as DriverConfig, p as MigrationNamespaceAttestation, s as DatabaseAdapter, u as Driver } from "./index-T0YKKw66.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, En as DriverTransactionOptions, Mn as QueryResult, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, g as MigrationNamespaceAttestation, jn as QueryExecutionContext, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
2
2
  import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
3
3
 
4
4
  //#region src/drivers/mysql2/index.d.ts
@@ -26,8 +26,6 @@ type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions & C;
26
26
  declare class MySQL2Driver extends Driver<Pool, PoolConnection> {
27
27
  readonly adapter: DatabaseAdapter;
28
28
  readonly maxBindParametersPerStatement: number | undefined;
29
- /** The caller's `databaseUrl` as parsed at construction; see above. */
30
- private readonly urlOptions;
31
29
  /** The caller's pool and connection record, as construction captured them. */
32
30
  private readonly suppliedPool;
33
31
  private readonly connectionOptions;
package/dist/mysql2.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,r as n}from"./validation-Du6j0Q38.mjs";import{c as r,o as i,s as a}from"./bind-parameter-capacity-DzMcIB95.mjs";import{n as o}from"./transaction-oskVwmsf.mjs";import{r as s,s as c}from"./transactions-gjmrWN5W.mjs";import{s as l}from"./execution-context-BPk0YLhd.mjs";import{n as u}from"./client-tjSMPjeZ.mjs";import{i as d,r as f,t as p}from"./driver-options-DxlB1tms.mjs";import{i as m,r as h,t as g}from"./driver-yCYqzIQg.mjs";import{t as _}from"./mysql-adapter-D9FoHlWE.mjs";import{Buffer as v}from"node:buffer";const y=/^(?:ssl|tls)/i;function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(y.test(e)&&e!==`ssl`&&e!==`sslmode`)throw TypeError(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw TypeError(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw TypeError(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}return Reflect.deleteProperty(r,`sslmode`),{host:t.hostname,port:t.port?Number.parseInt(t.port,10):3306,...n===``?{}:{database:n},user:decodeURIComponent(t.username)||void 0,password:decodeURIComponent(t.password)||void 0,...r}}function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!v.isBuffer(e)?v.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,n){return new t(`Driver "mysql2" returned a malformed result for operation "${e}": ${n}.`,{meta:{driver:`mysql2`,operation:e}})}const b=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,t){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&b.test(e)))return a(e,t,{allowNumber:!0})}function toQueryResult(e,n,a){if(isMultiStatementFields(n))throw new t(`Driver "mysql2" returned multiple statement results for operation "${a}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:a}});if(Array.isArray(e)){if(!Array.isArray(n)||n.some(e=>!i(e)))throw malformedMySQL2Result(a,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(n!==void 0)throw malformedMySQL2Result(a,`mutation results require undefined field metadata`);if(!i(e))throw malformedMySQL2Result(a,`expected a mutation result object`);let o={provider:`mysql2`,operation:a},s=normalizeMySQL2InsertId(e.insertId,o);return{rows:[],rowCount:r(e.affectedRows,o,{allowDecimalString:!0}),...s===void 0?{}:{insertId:s}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.urlOptions?.database??e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=d(e),n=e.databaseUrl,r=n?parseMySQL2ConfiguredUrl(n):void 0,i={urlOptions:r,suppliedPool:e.pool,connectionOptions:{...e.options,...r}};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw new n(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends g{maxBindParametersPerStatement=65535;urlOptions;suppliedPool;connectionOptions;constructor(e={}){let t=f(e),r=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),r.connectionOptions.multipleStatements===!0)throw new n(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(r.connectionOptions.rowsAsArray===!0)throw new n(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(r.connectionOptions.nestTables===!0||typeof r.connectionOptions.nestTables==`string`)throw new n(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.urlOptions=r.urlOptions,this.suppliedPool=r.suppliedPool,this.connectionOptions=r.connectionOptions,p(this,`adapter`,new _(r.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.urlOptions&&(t={...t,...this.urlOptions}),this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw s(this.driverName);let i=e,a=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),u=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw u=!0,e}},d=r?.isolationLevel;return c({begin:()=>runOrDestroy(async()=>{d&&await a.query(m(d)),await a.beginTransaction()}),callback:()=>t(a),commit:()=>runOrDestroy(()=>a.commit()),rollback:()=>runOrDestroy(()=>a.rollback()),phases:l(n),close:()=>{try{if(u){a.destroy();return}a.release()}catch(e){throw super.transactionCleanupFailed(new o(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw s(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){let{pool:t,options:n={},databaseUrl:r}=e,i=f(e),a=d(e),o={pool:t,options:r?{...n,...parseMySQL2ConfiguredUrl(r)}:n};return a!==void 0&&(o.namespace=a),i!==void 0&&(o.migrationNamespaceAttestation=i),u(e,new MySQL2Driver(o))}export{MySQL2Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t,o as n,s as r}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{i}from"./base-AdXAoy6l.mjs";import{l as a,p as o}from"./error-mapping-CnPCv1dm.mjs";import{f as s,r as c}from"./validation-Dk9Q_-C7.mjs";import{n as l}from"./transaction-Bnl6ULTw.mjs";import{s as u}from"./execution-context-BKR3bgES.mjs";import{n as d}from"./client-BLiBmykn.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-BlnKXPFF.mjs";import{t as y}from"./mysql-adapter-DkJPfoGf.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new c(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new s(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,t){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return r(e,t,{allowNumber:!0})}function toQueryResult(e,r,i){if(isMultiStatementFields(r))throw new s(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(r)||r.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(r!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:t(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw i(e)?e:new c(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new c(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new c(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new c(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw a(this.driverName);let i=e,s=await h(()=>i.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),c=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw c=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await s.query(f(d)),await s.beginTransaction()}),callback:()=>t(s),commit:()=>runOrDestroy(()=>s.commit()),rollback:()=>runOrDestroy(()=>s.rollback()),phases:u(n),close:()=>{try{if(c){s.destroy();return}s.release()}catch(e){throw super.transactionCleanupFailed(new l(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw a(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
2
2
  //# sourceMappingURL=mysql2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\n/**\n * Parse a MySQL database URL into connection options.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw new TypeError(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw new TypeError(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw new TypeError(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n return {\n host: parsed.hostname,\n port: parsed.port ? Number.parseInt(parsed.port, 10) : 3306,\n // A pathless URL selects no database. The key stays absent so merging this\n // over connection options cannot replace a configured database with \"\".\n ...(database === \"\" ? {} : { database }),\n user: decodeURIComponent(parsed.username) || undefined,\n password: decodeURIComponent(parsed.password) || undefined,\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the URL's database\n * path, then the connection options' `database`. A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured =\n configuration.urlOptions?.database ??\n configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /** The parsed `databaseUrl`, or `undefined` when the caller supplied none. */\n readonly urlOptions: MySQLConnectionOptions | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const captured = {\n urlOptions,\n suppliedPool: options.pool,\n connectionOptions: { ...options.options, ...urlOptions },\n };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/** The URL now decides a target, so a malformed one fails at construction. */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's `databaseUrl` as parsed at construction; see above. */\n private readonly urlOptions: MySQLConnectionOptions | undefined;\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.urlOptions = configuration.urlOptions;\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n ...this.connectionOptions,\n };\n\n // The URL still wins over the copied connection options, from the one\n // parse construction made: this driver never re-reads the caller's\n // `databaseUrl`, so the pool cannot be pointed somewhere the resolved\n // target never saw.\n if (this.urlOptions) {\n options = { ...options, ...this.urlOptions };\n }\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n const { pool, options = {}, databaseUrl } = config;\n const attestation = resolveMigrationNamespaceAttestationOption(config);\n const namespace = resolveNamespaceOption(config);\n\n const driverOptions: MySQL2DriverOptions = {\n pool,\n // The URL still wins over the caller's option keys, on a copy this wrapper\n // owns rather than in the caller's record.\n options: databaseUrl\n ? { ...options, ...parseMySQL2ConfiguredUrl(databaseUrl) }\n : options,\n };\n if (namespace !== undefined) driverOptions.namespace = namespace;\n if (attestation !== undefined) {\n driverOptions.migrationNamespaceAttestation = attestation;\n }\n\n const driver = new MySQL2Driver(driverOptions);\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"0jBAoBA,MAAM,EAAyB,gBAE/B,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,MAAU,UACR,sEACD,CAEH,GAAI,CACF,EAAa,GAAO,KAAK,MAAM,EAAM,MAC/B,CACN,EAAa,GAAO,GAKxB,IAAM,EAAU,EAAO,aAAa,IAAI,UAAU,CAClD,GAAI,GAAW,IAAY,UAAW,CACpC,GAAI,CAAC,CAAC,UAAW,YAAa,cAAc,CAAC,SAAS,EAAQ,CAC5D,MAAU,UACR,+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,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,OAAM,UAAU,EAAE,CAAE,eAAgB,EACtC,EAAc,EAA2C,EAAO,CAChE,EAAY,EAAuB,EAAO,CAE1C,EAAqC,CACzC,OAGA,QAAS,EACL,CAAE,GAAG,EAAS,GAAG,yBAAyB,EAAY,CAAE,CACxD,EACL,CAQD,OAPI,IAAc,IAAA,KAAW,EAAc,UAAY,GACnD,IAAgB,IAAA,KAClB,EAAc,8BAAgC,GAKzC,EAAiD,EAFzC,IAAI,aAAa,EAAc,CAEyB"}
1
+ {"version":3,"file":"mysql2.mjs","names":[],"sources":["../src/drivers/shared/mysql-utils.ts","../src/drivers/mysql2/index.ts"],"sourcesContent":["/**\n * Shared MySQL Utilities\n *\n * Shared connection utilities for MySQL-based drivers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\n/**\n * The connection options a MySQL database URL carries: only the keys it\n * spells, so merged under a caller's options it fills what they left out\n * instead of replacing it with `undefined` or a default port.\n */\nexport interface MySQLConnectionOptions {\n [option: string]: unknown;\n ssl?: object | string;\n host: string;\n port?: number;\n /** Absent when the URL carries no database path. */\n database?: string;\n user?: string;\n password?: string;\n}\n\nconst TLS_URL_OPTION_PATTERN = /^(?:ssl|tls)/i;\n\n/**\n * A TLS request VibORM cannot honour. Its own text, which carries no part of\n * the URL, so the driver surfaces it rather than redacting it.\n */\nfunction tlsRefusal(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"mysql2\", operation: \"configuration\" },\n });\n}\n\nexport function parseMySQLUrl(url: string): MySQLConnectionOptions {\n const parsed = new URL(url);\n const database = decodeURIComponent(parsed.pathname.slice(1));\n const queryOptions: Record<string, unknown> = {};\n for (const [key, value] of parsed.searchParams) {\n if (\n TLS_URL_OPTION_PATTERN.test(key) &&\n key !== \"ssl\" &&\n key !== \"sslmode\"\n ) {\n throw tlsRefusal(\n \"Unsupported MySQL TLS URL option; configure options.ssl explicitly.\"\n );\n }\n try {\n queryOptions[key] = JSON.parse(value);\n } catch {\n queryOptions[key] = value;\n }\n }\n // mysql2 understands ssl, but not libpq's sslmode. Refuse a TLS request\n // whose policy cannot be represented instead of silently opening plaintext.\n const sslmode = parsed.searchParams.get(\"sslmode\");\n if (sslmode && sslmode !== \"disable\") {\n if (![\"require\", \"verify-ca\", \"verify-full\"].includes(sslmode)) {\n throw tlsRefusal(\n \"Unsupported MySQL sslmode; configure options.ssl explicitly.\"\n );\n }\n if (\n queryOptions.ssl !== undefined &&\n (queryOptions.ssl === null ||\n (typeof queryOptions.ssl !== \"object\" &&\n typeof queryOptions.ssl !== \"string\"))\n )\n throw tlsRefusal(\"MySQL sslmode requires a TLS configuration\");\n queryOptions.ssl ??= {};\n }\n Reflect.deleteProperty(queryOptions, \"sslmode\");\n const user = decodeURIComponent(parsed.username);\n const password = decodeURIComponent(parsed.password);\n return {\n host: parsed.hostname,\n ...(parsed.port ? { port: Number.parseInt(parsed.port, 10) } : {}),\n ...(database === \"\" ? {} : { database }),\n ...(user === \"\" ? {} : { user }),\n ...(password === \"\" ? {} : { password }),\n ...queryOptions,\n };\n}\n","/**\n * MySQL2 Driver\n *\n * Driver implementation for mysql2/promise with connection pooling.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { MySQLAdapter } from \"@adapters/databases/mysql/mysql-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n TransactionError,\n} from \"@errors\";\nimport type { Pool, PoolConnection, PoolOptions } from \"mysql2/promise\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n isNormalizedResultRow,\n type NormalizedResultContext,\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n type MigrationNamespaceAttestation,\n type MySQLConnectionOptions,\n nestedTransactionDispatchError,\n type PinnedSessionReservation,\n parseMySQLUrl,\n resolveMigrationNamespaceAttestationOption,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type MySQL2Options = PoolOptions;\n\nexport interface MySQL2DriverOptions {\n pool?: Pool;\n options?: PoolOptions;\n databaseUrl?: string;\n /**\n * The MySQL database this driver's persistent objects live in. Omitted, the\n * target is derived from a driver-created pool's own configuration, and a\n * driver that resolves none keeps the existing unqualified mode.\n */\n namespace?: string;\n /**\n * Caller-owned assertion that qualified `database.table` references and the\n * pinned migration session's `USE` cannot be redirected by VTGate\n * schema-routing rules or an equivalent proxy. It selects nothing, is never\n * inferred, and only effectful live migration work requires it.\n */\n migrationNamespaceAttestation?: MigrationNamespaceAttestation;\n}\n\nexport type MySQL2ClientConfig<C extends DriverConfig> = MySQL2DriverOptions &\n C;\n\nconst MYSQL2_CONFIG_KEYS: Record<keyof MySQL2DriverOptions, true> = {\n pool: true,\n options: true,\n databaseUrl: true,\n namespace: true,\n migrationNamespaceAttestation: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\n/** mysql2 escapes plain Uint8Array as an object — convert to Buffer for blobs. */\nfunction convertValuesForMySQL(values: unknown[]): unknown[] {\n return values.map((v) =>\n v instanceof Uint8Array && !Buffer.isBuffer(v)\n ? Buffer.from(v.buffer, v.byteOffset, v.byteLength)\n : v\n );\n}\n\nfunction isMultiStatementFields(fields: unknown): boolean {\n return (\n Array.isArray(fields) &&\n fields.every(\n (fieldSet) => fieldSet === undefined || Array.isArray(fieldSet)\n )\n );\n}\n\nfunction malformedMySQL2Result(operation: string, reason: string): QueryError {\n return new QueryError(\n `Driver \"mysql2\" returned a malformed result for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n}\n\nconst CANONICAL_NEGATIVE_DECIMAL = /^-[1-9]\\d*$/;\n\n/** mysql2 echoes an explicit negative AUTO_INCREMENT key in ResultSetHeader.insertId. */\nfunction normalizeMySQL2InsertId(\n value: unknown,\n context: NormalizedResultContext\n): number | bigint | undefined {\n if (\n (typeof value === \"number\" && Number.isSafeInteger(value) && value < 0) ||\n (typeof value === \"string\" && CANONICAL_NEGATIVE_DECIMAL.test(value))\n ) {\n return undefined;\n }\n return normalizeProviderInsertId(value, context, { allowNumber: true });\n}\n\n/** SELECT returns a row array; mutations return a ResultSetHeader. */\nfunction toQueryResult<T>(\n result: unknown,\n fields: unknown,\n operation: string\n): QueryResult<T> {\n if (isMultiStatementFields(fields)) {\n throw new QueryError(\n `Driver \"mysql2\" returned multiple statement results for operation \"${operation}\"; VibORM requires exactly one statement result.`,\n { meta: { driver: \"mysql2\", operation } }\n );\n }\n\n if (Array.isArray(result)) {\n if (\n !Array.isArray(fields) ||\n fields.some((field) => !isNormalizedResultRow(field))\n ) {\n throw malformedMySQL2Result(\n operation,\n \"row arrays require one flat field metadata array\"\n );\n }\n return {\n rows: result as T[],\n rowCount: result.length,\n };\n }\n\n if (fields !== undefined) {\n throw malformedMySQL2Result(\n operation,\n \"mutation results require undefined field metadata\"\n );\n }\n if (!isNormalizedResultRow(result)) {\n throw malformedMySQL2Result(operation, \"expected a mutation result object\");\n }\n const context = { provider: \"mysql2\", operation };\n const insertId = normalizeMySQL2InsertId(result.insertId, context);\n return {\n rows: [] as T[],\n rowCount: normalizeProviderRowCount(result.affectedRows, context, {\n allowDecimalString: true,\n }),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\n/**\n * The target derived from a pool this driver will create: the `database` it\n * connects with, which is the caller's option when given and otherwise the\n * URL's path (see `resolveMySQL2Configuration`). A supplied `Pool` is opaque —\n * VibORM does not inspect mysql2 internals, so only an explicit `namespace` can\n * bind one. A pathless URL contributes nothing, and neither does an empty\n * `options.database`: §1.3's empty candidate is an absent one rather than a\n * name handed to identifier validation. A non-empty derived name is validated\n * exactly like an explicit one, by the adapter that installs it.\n */\nfunction deriveMySQL2Namespace(\n configuration: Omit<MySQL2Configuration, \"namespace\">\n): string | undefined {\n if (configuration.suppliedPool) return undefined;\n const configured = configuration.connectionOptions.database;\n return configured === \"\" ? undefined : configured;\n}\n\n/** What this driver settles from its caller's object, each source read once. */\ninterface MySQL2Configuration {\n readonly namespace: string | undefined;\n /**\n * The EXACT pool the caller supplied, or absent when this driver makes its\n * own. Identity, settled once, is the whole ownership answer: the caller's\n * options object is theirs to change, and a `pool` key deleted after\n * construction used to make `$disconnect()` end a transport VibORM was handed.\n */\n readonly suppliedPool: Pool | undefined;\n /**\n * The caller's connection record, copied once, over the keys its\n * `databaseUrl` carries: the URL fills only what the record leaves out, and\n * a key the record sets to `undefined` (an unset environment variable) is\n * left out. A per-tenant URL plus a password from a secret is this shape.\n *\n * A copy of THIS record, not of what it points at: a nested `ssl` object or\n * stream is the caller's to own, and the keys that decide where a pool\n * connects — host, port, user, database — all live here. It is also what the\n * constructor's refusals read, so the options this driver validated are the\n * exact options it later connects with.\n */\n readonly connectionOptions: PoolOptions;\n}\n\n/**\n * The one immutable ORM target for this driver, in the plan's exact order: an\n * explicit `namespace`, then the driver-created pool's own derivation.\n *\n * `databaseUrl` is read once and parsed once, here, and the parse is kept: a\n * second read at connect time would let a caller-owned accessor hand the\n * provider a different URL than the one that decided the target. A present URL\n * is parsed even when an explicit `namespace` outranks it, because an unusable\n * connection string is a construction failure either way; `\"\"`, `null`, and an\n * absent property are the same absent request. Both rules are the convenience\n * wrapper's too, so the two entry points cannot disagree.\n *\n * None of these sources is transport evidence: the attestation is read\n * separately and never derived from a resolved target.\n */\nfunction resolveMySQL2Configuration(\n options: MySQL2DriverOptions\n): MySQL2Configuration {\n const explicit = resolveNamespaceOption(options);\n const databaseUrl = options.databaseUrl;\n const urlOptions = databaseUrl\n ? parseMySQL2ConfiguredUrl(databaseUrl)\n : undefined;\n const connectionOptions: PoolOptions = { ...urlOptions };\n for (const [key, value] of Object.entries(options.options ?? {})) {\n if (value !== undefined) Reflect.set(connectionOptions, key, value);\n }\n const captured = { suppliedPool: options.pool, connectionOptions };\n return {\n namespace: explicit ?? deriveMySQL2Namespace(captured),\n ...captured,\n };\n}\n\n/**\n * The URL now decides a target, so a malformed one fails at construction. A\n * TLS refusal is VibORM's own secret-free text and passes through; the URL\n * parser's failure can carry the URL, so it is replaced and redacted.\n */\nfunction parseMySQL2ConfiguredUrl(databaseUrl: string): MySQLConnectionOptions {\n try {\n return parseMySQLUrl(databaseUrl);\n } catch (cause) {\n if (isVibORMError(cause)) throw cause;\n throw new ClientInitializationError(\n 'Driver \"mysql2\" could not parse its databaseUrl.',\n { cause: cause instanceof Error ? cause : undefined }\n );\n }\n}\n\nexport class MySQL2Driver extends Driver<Pool, PoolConnection> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n /** The caller's pool and connection record, as construction captured them. */\n private readonly suppliedPool: Pool | undefined;\n private readonly connectionOptions: PoolOptions;\n\n constructor(options: MySQL2DriverOptions = {}) {\n // Both facts are read before `super(...)` so the transport assertion is\n // installed by the base constructor and no option can be read twice.\n const attestation = resolveMigrationNamespaceAttestationOption(options);\n const configuration = resolveMySQL2Configuration(options);\n super(\"mysql\", \"mysql2\", {}, attestation);\n if (configuration.connectionOptions.multipleStatements === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.multipleStatements=true because VibORM operations require one result per statement.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (configuration.connectionOptions.rowsAsArray === true) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n if (\n configuration.connectionOptions.nestTables === true ||\n typeof configuration.connectionOptions.nestTables === \"string\"\n ) {\n throw new ClientInitializationError(\n 'Driver \"mysql2\" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.',\n { meta: { driver: \"mysql2\", operation: \"configuration\" } }\n );\n }\n this.suppliedPool = configuration.suppliedPool;\n this.connectionOptions = configuration.connectionOptions;\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new MySQLAdapter(configuration.namespace)\n );\n if (this.suppliedPool) {\n this.client = this.suppliedPool;\n }\n }\n\n /**\n * The pool this driver connects through.\n *\n * A caller's pool is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second pool behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<Pool> {\n if (this.suppliedPool !== undefined) {\n return this.suppliedPool;\n }\n const mysql = await import(\"mysql2/promise\");\n\n let options: PoolOptions = {\n // DATETIME is stored as naive UTC wall-clock; read it back as UTC\n // instead of shifting by the process timezone\n timezone: \"Z\",\n // BIGINT/DECIMAL values outside Number's safe range arrive as strings\n // (the result parser converts them losslessly) instead of lossy numbers\n supportBigNumbers: true,\n // DATE as plain \"YYYY-MM-DD\" — the result parser builds a UTC-midnight\n // Date, matching every other driver (mysql2 would build local midnight)\n dateStrings: [\"DATE\"],\n // Already merged with the URL, from the one parse construction made:\n // this driver never re-reads the caller's `databaseUrl`.\n ...this.connectionOptions,\n };\n\n // The pool this driver creates defaults to the same database the adapter\n // qualifies with, whichever source resolved it. A supplied pool never\n // reaches here, so VibORM never changes a caller's connection state.\n if (this.adapter.namespace !== undefined) {\n options = { ...options, database: this.adapter.namespace };\n }\n\n return mysql.createPool(options);\n }\n\n /**\n * Ends only a pool this driver created.\n *\n * A supplied pool belongs to the caller, who may be sharing it with other\n * clients or with their own code, and §5.3's rule is that VibORM never\n * changes a caller's connection state. `$disconnect()` used to end it\n * regardless, so disconnecting one client tore down every other consumer of\n * that pool.\n *\n * The test is on the pool's IDENTITY against what construction captured, so\n * it answers for the pool actually being closed rather than for whatever the\n * caller's record says now: every pool this driver made is ended, and the one\n * it was handed never is.\n */\n protected async closeClient(pool: Pool): Promise<void> {\n if (pool === this.suppliedPool) {\n return;\n }\n await pool.end();\n }\n\n protected async execute<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const [result, fields] = await client.query({\n sql,\n values: convertValuesForMySQL(params),\n // Per-statement decoding also covers borrowed pools without mutating\n // their connection options. Text protocol avoids a statement per IN size.\n typeCast: (field, next) =>\n [\"DATE\", \"DATETIME\", \"TIMESTAMP\", \"LONGLONG\", \"NEWDECIMAL\"].includes(\n field.type\n )\n ? field.string()\n : next(),\n });\n return toQueryResult<T>(result, fields, operation);\n }\n\n protected async executeRaw<T>(\n client: Pool | PoolConnection,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const [result, fields] = await client.query(\n sql,\n params && convertValuesForMySQL(params)\n );\n return toQueryResult<T>(result, fields, operation);\n }\n\n /**\n * MySQL rejects `SET TRANSACTION ISOLATION LEVEL` once a transaction is open\n * (ER_CANT_CHANGE_TX_CHARACTERISTICS), so the level must be set on the\n * transaction's own connection *before* BEGIN, where it applies to exactly\n * the next transaction on that session. mysql2 pools hand out a connection we\n * can wait for with a bound and release if we stop waiting.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"acquisition\",\n };\n }\n\n protected async transaction<T>(\n client: Pool | PoolConnection,\n fn: (tx: PoolConnection) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n // Start a new transaction from pool\n const pool = client as Pool;\n const connection = await acquireWithMaxWait(\n () => pool.getConnection(),\n (acquired) => acquired.release(),\n options?.maxWaitMs,\n { driverName: this.driverName, form: \"callback\" }\n );\n let shouldDestroy = false;\n const runOrDestroy = async (operation: () => Promise<void>) => {\n try {\n await operation();\n } catch (error) {\n shouldDestroy = true;\n throw error;\n }\n };\n const isolationLevel = options?.isolationLevel;\n return runTransactionLifecycle({\n begin: () =>\n runOrDestroy(async () => {\n // Session-scoped-next-transaction: this statement must land before\n // beginTransaction() to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.query(isolationLevelStatement(isolationLevel));\n }\n await connection.beginTransaction();\n }),\n callback: () => fn(connection),\n commit: () => runOrDestroy(() => connection.commit()),\n rollback: () => runOrDestroy(() => connection.rollback()),\n phases: getExecutionTransactionPhases(context),\n close: () => {\n try {\n if (shouldDestroy) {\n connection.destroy();\n return;\n }\n connection.release();\n } catch (error) {\n super.transactionCleanupFailed(\n new TransactionError(\n 'Driver \"mysql2\" could not release an unsafe transaction connection.',\n { meta: { driver: \"mysql2\", method: \"$transaction\" } }\n )\n );\n throw error;\n }\n },\n });\n }\n\n protected override transactionCleanupFailed(_error: Error): void {\n // A connection with failed cleanup is destroyed; the pool remains usable.\n }\n\n /**\n * One `PoolConnection` from `pool.getConnection()` — plan §3.5's pinned\n * producer for MySQL2.\n *\n * It is ALWAYS destroyed, never released, and the `discard` flag is therefore\n * ignored: this session has executed `USE` to select the migration target and\n * may have executed author-owned statements from a manual artifact, and\n * mysql2's release resets neither. Returning it to an owned or a supplied\n * pool would leak that state into unrelated queries. This is correctness, not\n * an optimization.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<Pool | PoolConnection>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(\"getConnection\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const connection = await client.getConnection();\n return {\n session: connection,\n release: () => {\n connection.destroy();\n return Promise.resolve();\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: MySQL2ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, MySQL2DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: MySQL2Driver }\n >]: LinkedClientConfig<C & { driver: MySQL2Driver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"mysql2\", MYSQL2_CONFIG_KEYS);\n const { pool, options, databaseUrl } = config;\n const driver = new MySQL2Driver({\n // Attestation first, then namespace: the order a refusal reports in.\n migrationNamespaceAttestation:\n resolveMigrationNamespaceAttestationOption(config),\n namespace: resolveNamespaceOption(config),\n pool,\n options,\n databaseUrl,\n });\n\n return createClientFromDriverConfig<S, C, MySQL2Driver>(config, driver);\n}\n"],"mappings":"0jBAwBA,MAAM,EAAyB,gBAM/B,SAAS,WAAW,EAA4C,CAC9D,OAAO,IAAI,EAA0B,EAAS,CAC5C,KAAM,CAAE,OAAQ,SAAU,UAAW,gBAAiB,CACvD,CAAC,CAGJ,SAAgB,cAAc,EAAqC,CACjE,IAAM,EAAS,IAAI,IAAI,EAAI,CACrB,EAAW,mBAAmB,EAAO,SAAS,MAAM,EAAE,CAAC,CACvD,EAAwC,EAAE,CAChD,IAAK,GAAM,CAAC,EAAK,KAAU,EAAO,aAAc,CAC9C,GACE,EAAuB,KAAK,EAAI,EAChC,IAAQ,OACR,IAAQ,UAER,M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AAS,eAChC,OAAO,EAAwB,CAC7B,UACE,aAAa,SAAY,CAGnB,GACF,MAAM,EAAW,MAAM,EAAwB,EAAe,CAAC,CAEjE,MAAM,EAAW,kBAAkB,EACnC,CACJ,aAAgB,EAAG,EAAW,CAC9B,WAAc,iBAAmB,EAAW,QAAQ,CAAC,CACrD,aAAgB,iBAAmB,EAAW,UAAU,CAAC,CACzD,OAAQ,EAA8B,EAAQ,CAC9C,UAAa,CACX,GAAI,CACF,GAAI,EAAe,CACjB,EAAW,SAAS,CACpB,OAEF,EAAW,SAAS,OACb,EAAO,CAOd,MANA,MAAM,yBACJ,IAAI,EACF,sEACA,CAAE,KAAM,CAAE,OAAQ,SAAU,OAAQ,eAAgB,CAAE,CACvD,CACF,CACK,IAGX,CAAC,CAGJ,yBAA4C,EAAqB,EAejE,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,kBAAmB,GACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAa,MAAM,EAAO,eAAe,CAC/C,MAAO,CACL,QAAS,EACT,aACE,EAAW,SAAS,CACb,QAAQ,SAAS,EAE3B,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,SAAU,EAAmB,CACnE,GAAM,CAAE,OAAM,UAAS,eAAgB,EAWvC,OAAO,EAAiD,EAVzC,IAAI,aAAa,CAE9B,8BACE,EAA2C,EAAO,CACpD,UAAW,EAAuB,EAAO,CACzC,OACA,UACA,cACD,CAAC,CAEqE"}
@@ -1,4 +1,4 @@
1
- import { Bt as BatchTransactionOptions, D as Schema, Dn as QueryExecutionContext, Ft as NoExtraDriverConfigKeys, Ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, Tn as CommittedBatchNotification, jt as DriverConfig, s as DatabaseAdapter, u as Driver, wn as BatchQuery } from "./index-T0YKKw66.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, On as BatchQuery, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, Tn as BatchTransactionOptions, jn as QueryExecutionContext, kn as CommittedBatchNotification, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
2
2
  import { NeonQueryFunction } from "@neondatabase/serverless";
3
3
 
4
4
  //#region src/drivers/neon-http/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t,r as n,y as r}from"./validation-Du6j0Q38.mjs";import{o as i}from"./bind-parameter-capacity-DzMcIB95.mjs";import{c as a}from"./transactions-gjmrWN5W.mjs";import{n as o}from"./client-tjSMPjeZ.mjs";import{i as s,t as c}from"./driver-options-DxlB1tms.mjs";import{t as l}from"./driver-yCYqzIQg.mjs";import{t as u}from"./postgres-adapter-T2Iko-vt.mjs";import{t as d}from"./postgres-result-Dc_iW3Hb.mjs";function malformedNeonResult(e,n){let r=e.operation??`execute`;return new t(`Driver "neon-http" returned a malformed result payload for operation "${r}": ${n}.`,{meta:{driver:`neon-http`,...e,operation:r}})}function assertNeonFullResult(e,t){if(!(i(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(i)||e.rowAsArray!==!1)throw malformedNeonResult(t,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends l{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e;let n=new u(t,e.postgis===!0);n.capabilities.supportsVector=e.pgvector===!0,e.pgvector||(n.vector=r),c(this,`adapter`,n)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new n(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(a(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:d(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e;return o(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,namespace:s(e)}))}export{NeonHTTPDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{m as n}from"./error-mapping-CnPCv1dm.mjs";import{f as r,r as i}from"./validation-Dk9Q_-C7.mjs";import{n as a}from"./client-BLiBmykn.mjs";import{c as o,d as s,t as c}from"./driver-BlnKXPFF.mjs";import{t as l}from"./postgres-result-7F0DllQe.mjs";import{t as u}from"./postgres-adapter-CQD2oGuD.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e;return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,namespace:s(e)}))}export{NeonHTTPDriver,createClient};
2
2
  //# sourceMappingURL=neon-http.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n QueryError,\n unsupportedVector,\n} from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n defineImmutableDriverFact,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"ocAmFA,SAAS,oBACP,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,WAAa,UACvC,OAAO,IAAI,EACT,yEAAyE,EAAU,KAAK,EAAO,GAC/F,CAAE,KAAM,CAAE,OAAQ,YAAa,GAAG,EAAS,YAAW,CAAE,CACzD,CAGH,SAAS,qBACP,EACA,EACqC,CACrC,GACE,EAAE,EAAsB,EAAO,EAAI,MAAM,QAAQ,EAAO,OAAO,GAC/D,OAAO,EAAO,SAAY,UAC1B,CAAC,OAAO,OAAO,EAAQ,WAAW,EACjC,EAAO,WAAa,OAClB,OAAO,EAAO,UAAa,UAC1B,CAAC,OAAO,SAAS,EAAO,SAAS,EACjC,CAAC,OAAO,cAAc,EAAO,SAAS,EACtC,EAAO,SAAW,IACtB,CAAC,MAAM,QAAQ,EAAO,KAAK,EAC3B,CAAC,EAAO,KAAK,MAAM,EAAsB,EACzC,EAAO,aAAe,GAEtB,MAAM,oBACJ,EACA,qEACD,CAQL,IAAa,eAAb,cAAoC,CAA6B,CAE/D,8BAA6D,MAI7D,qBAAgC,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AAI,eAAe,CAChC,cACA,UACA,WACA,UACA,UAPgB,EAAuB,EAAO,CAQ/C,CAAC,CAEuE"}
1
+ {"version":3,"file":"neon-http.mjs","names":[],"sources":["../src/drivers/neon-http/index.ts"],"sourcesContent":["/**\n * Neon HTTP Driver\n *\n * Driver implementation for @neondatabase/serverless - Neon's HTTP-based PostgreSQL driver.\n *\n * Note: Neon's HTTP API uses non-interactive transactions. This means:\n * - Batch transactions ($transaction([...])) work via executeBatch\n * - Callback transactions ($transaction(async (tx) => {...})) are NOT supported\n * because Neon HTTP requires all queries to be submitted at once\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, QueryError } from \"@errors\";\nimport type {\n CustomTypesConfig,\n NeonQueryFunction,\n} from \"@neondatabase/serverless\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { isNormalizedResultRow } from \"../normalized-result\";\nimport {\n type BatchTransactionOptions,\n normalizePostgresRowCount,\n resolveNamespaceOption,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface NeonHTTPDriverOptions {\n databaseUrl?: string;\n options?: {\n fetchOptions?: RequestInit;\n authToken?: string | (() => Promise<string> | string);\n };\n pgvector?: boolean;\n postgis?: boolean;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport type NeonHTTPClientConfig<C extends DriverConfig> =\n NeonHTTPDriverOptions & C;\n\nconst NEON_HTTP_CONFIG_KEYS: Record<keyof NeonHTTPDriverOptions, true> = {\n databaseUrl: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n};\n\n// ============================================================\n// TYPE DECLARATIONS\n// ============================================================\n\n/**\n * NeonQuery is the main query function returned by neon().\n * Configured with arrayMode=false (object rows) and fullResults=true (includes rowCount).\n */\ntype NeonQuery = NeonQueryFunction<false, true>;\n\ninterface NeonFullResult<T> {\n fields: unknown[];\n command: string;\n rowCount: number | null;\n rows: T[];\n rowAsArray: false;\n}\n\nfunction malformedNeonResult(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"neon-http\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"neon-http\", ...context, operation } }\n );\n}\n\nfunction assertNeonFullResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is NeonFullResult<T> {\n if (\n !(isNormalizedResultRow(result) && Array.isArray(result.fields)) ||\n typeof result.command !== \"string\" ||\n !Object.hasOwn(result, \"rowCount\") ||\n (result.rowCount !== null &&\n (typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0)) ||\n !Array.isArray(result.rows) ||\n !result.rows.every(isNormalizedResultRow) ||\n result.rowAsArray !== false\n ) {\n throw malformedNeonResult(\n context,\n \"expected fullResults object with object rows and explicit rowCount\"\n );\n }\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class NeonHTTPDriver extends Driver<NeonQuery, NeonQuery> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n\n // Neon HTTP only supports non-interactive (batch) transactions\n // Callback-style transactions are not supported\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n\n // Hosted rollback, durable visibility and malformed post-commit metadata\n // witnesses qualify this notification before driver result validation.\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: NeonHTTPDriverOptions;\n private queryTypes: CustomTypesConfig | undefined;\n\n constructor(options: NeonHTTPDriverOptions = {}) {\n super(\"postgresql\", \"neon-http\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n\n installPostgresAdapter(this, namespace, options);\n }\n\n protected async initClient(): Promise<NeonQuery> {\n const { neon, types } = await import(\"@neondatabase/serverless\");\n\n if (!this.driverOptions.databaseUrl) {\n throw new ClientInitializationError(\n \"Neon HTTP driver requires a databaseUrl\",\n { meta: { driver: this.driverName } }\n );\n }\n\n // DATE (1082) / TIMESTAMP WITHOUT TIME ZONE (1114): the default parsers\n // build process-local Dates, shifting the stored value by the process\n // timezone. Return raw strings — the shared result parser builds UTC\n // Dates from them, matching every other driver.\n const identityParser = (value: string) => value;\n // pg-types declares getTypeParser with per-format overloads that a single\n // wrapper function can't express — the cast is unavoidable here\n const getTypeParser = ((oid: number, format?: string) => {\n if (\n [1082, 1114, 1184, 1115, 1182, 1185].includes(oid) &&\n format !== \"binary\"\n ) {\n return identityParser;\n }\n return types.getTypeParser(oid as never, format as never);\n }) as typeof types.getTypeParser;\n this.queryTypes = { getTypeParser };\n\n // Always use arrayMode=false (object rows) and fullResults=true (includes rowCount)\n const client = neon(this.driverOptions.databaseUrl, {\n fetchOptions: this.driverOptions.options?.fetchOptions,\n authToken: this.driverOptions.options?.authToken,\n fullResults: true,\n arrayMode: false,\n });\n\n return client;\n }\n\n protected async closeClient(_client: NeonQuery): Promise<void> {\n // HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(client, sql, params, context, \"execute\");\n }\n\n private async executeQuery<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext | undefined,\n fallbackOperation: string\n ): Promise<QueryResult<T>> {\n const executionContext = context ?? { operation: fallbackOperation };\n const result = await client.query(sql, params, {\n arrayMode: false,\n fullResults: true,\n types: this.queryTypes,\n });\n\n return this.parseResult<T>(result, executionContext);\n }\n\n protected async executeRaw<T>(\n client: NeonQuery,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery<T>(\n client,\n sql,\n params ?? [],\n context,\n \"executeRaw\"\n );\n }\n\n /**\n * Neon HTTP sends the whole batch as one request through `client.transaction`\n * and offers no callback transaction. The provider opens and closes that\n * transaction server-side in a single round trip. The SDK receives the\n * requested isolation level; timeout/maxWait need an interactive body or\n * acquired connection, which this HTTP transport does not have.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"provider\",\n timeout: false,\n timeoutReason:\n \"Neon HTTP runs a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"Neon HTTP submits the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: NeonQuery,\n _fn: (tx: NeonQuery) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using Neon's transaction() function.\n * This provides atomic batch execution with full PostgreSQL transaction semantics.\n */\n protected async executeBatch<T>(\n client: NeonQuery,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification,\n options?: BatchTransactionOptions\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n // Query promises retain their own parser options in the public SDK API.\n const results: unknown = await client.transaction(\n queries.map((query) => {\n const statementContext = query.context ?? batchContext;\n try {\n return client.query(query.sql, query.params ?? [], {\n types: this.queryTypes,\n });\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }),\n {\n isolationLevel: options?.isolationLevel,\n arrayMode: false,\n fullResults: true,\n }\n );\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedNeonResult(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n return results.map((result, index) =>\n this.parseResult<T>(result, queries[index]?.context ?? batchContext)\n );\n }\n\n /**\n * Parse Neon result into QueryResult format.\n */\n private parseResult<T>(\n result: unknown,\n context: QueryExecutionContext\n ): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertNeonFullResult<T>(result, context);\n return {\n rows: result.rows,\n rowCount: normalizePostgresRowCount(\n result.rowCount,\n result.command,\n result.rows,\n {\n provider: \"neon-http\",\n operation,\n model: context.model,\n correlationId: context.correlationId,\n }\n ),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: NeonHTTPClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, NeonHTTPDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: NeonHTTPDriver }\n >]: LinkedClientConfig<C & { driver: NeonHTTPDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"neon-http\", NEON_HTTP_CONFIG_KEYS);\n const { databaseUrl, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new NeonHTTPDriver({\n databaseUrl,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, NeonHTTPDriver>(config, driver);\n}\n"],"mappings":"mZA6DA,MAAM,EAAmE,CACvE,YAAa,GACb,QAAS,GACT,SAAU,GACV,QAAS,GACT,UAAW,GACZ,CAoBD,SAAS,oBACP,EACA,EACY,CACZ,IAAM,EAAY,EAAQ,WAAa,UACvC,OAAO,IAAI,EACT,yEAAyE,EAAU,KAAK,EAAO,GAC/F,CAAE,KAAM,CAAE,OAAQ,YAAa,GAAG,EAAS,YAAW,CAAE,CACzD,CAGH,SAAS,qBACP,EACA,EACqC,CACrC,GACE,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ACA,EACgB,CAChB,IAAM,EAAY,EAAQ,WAAa,UAEvC,OADA,qBAAwB,EAAQ,EAAQ,CACjC,CACL,KAAM,EAAO,KACb,SAAU,EACR,EAAO,SACP,EAAO,QACP,EAAO,KACP,CACE,SAAU,YACV,YACA,MAAO,EAAQ,MACf,cAAe,EAAQ,cACxB,CACF,CACF,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,YAAa,EAAsB,CACzE,GAAM,CAAE,cAAa,UAAS,WAAU,WAAY,EAWpD,OAAO,EAAmD,EAR3C,IAAI,eAAe,CAChC,cACA,UACA,WACA,UACA,UAPgB,EAAuB,EAAO,CAQ/C,CAAC,CAEuE"}
@@ -0,0 +1,2 @@
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{n as r}from"./canonical-json-rfC2Dg0X.mjs";import{a as i}from"./identity-CLFhCTZx.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
2
+ //# sourceMappingURL=object-store-DQR6bTBY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object-store-DQR6bTBY.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH,IAAa,yBAAb,KAAwE,CACtE,MAEA,YAAY,EAAkC,CAC5C,KAAK,MAAQ,EAGf,MAAM,YAAyC,CAC7C,OAAO,KAAK,MAAM,IAAI,cAAc,CAGtC,MAAM,YAAyC,CAC7C,OAAO,KAAK,QAAQ,UAAW,QAAQ,CAGzC,MAAM,eAA4C,CAChD,OAAO,KAAK,QAAQ,aAAc,QAAQ,CAG5C,MAAM,SAAsC,CAC1C,OAAO,KAAK,QAAQ,OAAQ,OAAO,CAGrC,MAAM,UAAU,EAAwC,CACtD,OAAO,KAAK,MAAM,IAAI,UAAU,EAAG,OAAO,CAG5C,MAAM,aAAa,EAA0C,CAC3D,OAAO,KAAK,MAAM,IAAI,aAAa,EAAK,OAAO,CAGjD,MAAM,QAAQ,EAA0C,CACtD,OAAO,KAAK,MAAM,IAAI,OAAO,EAAK,MAAM,CAG1C,MAAM,cAAc,EAA2C,CAC7D,OAAO,KAAK,QAAQ,cAAe,EAAM,CAG3C,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,KAAK,QAAQ,aAAa,EAAK,OAAQ,EAAM,CAGtD,MAA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