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
@@ -1 +1 @@
1
- {"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\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 PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { unsupportedVector } from \"@errors\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\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 PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\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 /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!(client instanceof PGlite)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!(client instanceof PGlite)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"6iBAyCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAwBD,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,SAAS,CAC7B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAAK,iBACP,KAAK,OAAS,KAAK,eACnB,OAAO,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CAGH,YACE,EACA,EACA,EACY,CACZ,GAAI,EAAE,aAAkB,GACtB,MAAM,EAA+B,KAAK,WAAW,CAEvD,OAAO,EAA8B,CACnC,IAAM,GAAa,EAAO,YAAY,EAAS,CAC/C,SAAU,EACV,OAAQ,EAA8B,EAAQ,CAG9C,MAAO,SAAY,IAAA,GACpB,CAAC,CAaJ,MAAyB,uBAAyC,CAChE,OAAO,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CAoB7D,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,EAAE,aAAkB,GACtB,MAAM,EAA+B,KAAK,WAAW,CAEvD,MAAO,CACL,QAAS,EACT,QAAS,KAAO,IAAY,CACrB,KAGL,GAAI,CACF,MAAM,EAAO,MAAM,kCAAkC,OAC9C,EAAc,CAErB,MADA,EAAuB,EAAO,CACxB,EACJ,KAAK,WACL,4KACA,EACD,GAGN,GAQL,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,UAAS,UAAS,WAAU,WAAY,EAYxD,OAAO,EAAiD,EATzC,IAAI,aAAa,CAC9B,SACA,UACA,UACA,WACA,UACA,UARgB,EAAuB,EAAO,CAS/C,CAAC,CAEqE"}
1
+ {"version":3,"file":"pglite.mjs","names":[],"sources":["../src/drivers/pglite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\n/**\n * PGlite Driver\n *\n * Driver implementation for PGlite (PostgreSQL in WebAssembly).\n * Supports optional pgvector and PostGIS extensions.\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 {\n PGlite,\n type PGliteOptions,\n type Transaction,\n} from \"@electric-sql/pglite\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport { normalizeProviderRowCount } from \"../normalized-result\";\nimport {\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n condemnPhysicalSession,\n type PinnedSessionReservation,\n unprovenLockStateError,\n} from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nconst temporalParsers = Object.fromEntries(\n [1082, 1114, 1184, 1115, 1182, 1185].map((oid) => [\n oid,\n (value: string) => value,\n ])\n);\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type { PGliteOptions } from \"@electric-sql/pglite\";\n\nexport interface PGliteDriverOptions {\n client?: PGlite;\n dataDir?: string;\n options?: PGliteOptions;\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 PGliteConfig<C extends DriverConfig> = PGliteDriverOptions & C;\n\nconst PGLITE_CONFIG_KEYS: Record<keyof PGliteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n pgvector: true,\n postgis: true,\n namespace: true,\n};\n\n/**\n * The database, as opposed to a transaction handle, which has no `transaction`\n * method. Not `instanceof PGlite`: a PGlite built by another copy of\n * `@electric-sql/pglite` (its CommonJS build beside the ESM one, or a second\n * installed version) has another class, and every transaction and pinned\n * command on it used to fail as \"nested provider state\".\n */\nfunction isPGliteDatabase(client: PGlite | Transaction): client is PGlite {\n return \"transaction\" in client;\n}\n\n// === ======================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PGliteDriver extends Driver<PGlite, Transaction> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 32_767;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: PGliteDriverOptions;\n /**\n * The EXACT database the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's database while believing it had made its own.\n */\n private readonly suppliedClient: PGlite | undefined;\n\n constructor(options: PGliteDriverOptions = {}) {\n super(\"postgresql\", \"pglite\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = options;\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n\n installPostgresAdapter(this, namespace, options);\n }\n\n /**\n * The database this driver runs on.\n *\n * A caller's database is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second, EMPTY in-memory PGlite behind their\n * back — a database they never asked for, holding none of their data, while\n * the one they handed over stayed open and unused.\n */\n protected async initClient(): Promise<PGlite> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const dataDir = this.driverOptions.dataDir;\n const userOptions = this.driverOptions.options ?? {};\n const options: PGliteOptions = {\n ...userOptions,\n parsers: {\n // TIMESTAMP WITHOUT TIME ZONE: PGlite builds process-local Dates,\n // shifting the stored UTC wall clock. Keep the raw string — the\n // shared result parser builds a UTC Date, matching other drivers.\n 1114: (value: string) => value,\n ...userOptions.parsers,\n },\n };\n\n // PGlite.create accepts dataDir as first argument or in options\n return dataDir\n ? await PGlite.create(dataDir, options)\n : await PGlite.create(options);\n }\n\n /**\n * A supplied database belongs to the caller, who may be running two\n * schema-scoped estates over it — the documented shape — and closing it here\n * would take the sibling's data down with this one's `$disconnect()`, on an\n * in-memory database for good.\n *\n * The test is on the client's IDENTITY against what construction captured, so\n * it answers for the database actually being closed rather than for whatever\n * the caller's record says now.\n */\n protected async closeClient(client: PGlite): Promise<void> {\n if (client === this.suppliedClient) {\n return;\n }\n await client.close();\n }\n\n protected async execute<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"execute\");\n }\n\n protected async executeRaw<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sql, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PGlite | Transaction,\n sql: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.query<T>(sql, params, {\n parsers: temporalParsers,\n });\n const affectedRows = normalizeProviderRowCount(result.affectedRows, {\n provider: \"pglite\",\n operation,\n });\n return {\n rows: result.rows,\n rowCount: result.rows.length > 0 ? result.rows.length : affectedRows,\n };\n }\n\n /**\n * PGlite is a full PostgreSQL, so the isolation level is a real post-BEGIN\n * statement. It is also single-connection, so top-level transactions queue —\n * and that queue wait is exactly what `maxWait` bounds.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"queue\",\n };\n }\n\n protected transaction<T>(\n client: PGlite | Transaction,\n fn: (tx: Transaction) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return runProviderManagedTransaction({\n run: (callback) => client.transaction(callback),\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n /**\n * The PGlite instance itself — the physical session a pinned command runs on.\n *\n * A caller may hand ONE PGlite to several drivers (two schema-scoped estates\n * over one database is the documented shape), and each of those drivers owns\n * its own connection queue. The client is what they all agree on, so it is\n * what serializes their pinned commands; without it the second command\n * re-acquires the reentrant session advisory lock the first is holding and\n * runs inside the first command's session.\n */\n protected override async physicalPinnedSession(): Promise<object> {\n return await this.getClient({ operation: \"pinnedSession\" });\n }\n\n /**\n * PGlite's single client, under the queue it already owns — plan §3.5's\n * pinned producer here. There is nothing to reserve and nothing to return:\n * one connection IS the session, which is exactly what a session lock needs.\n *\n * A condemned session can be neither destroyed nor abandoned: closing this\n * client closes the DATABASE, which for an in-memory one takes the caller's\n * data with it and for a supplied one is not VibORM's to do at all. So the\n * session is reset with `pg_advisory_unlock_all()`, and when that reset FAILS\n * the CLIENT is condemned instead — the subject of an unknown lock state is\n * the session, so the condemnation is recorded on it and refuses the next\n * pinned command through every driver over it. Ordinary queries keep working\n * — the data was never in doubt. Swallowing that reset failure was the\n * alternative, and it left the next migration command running inside a\n * session that may still hold the lock, on the one transport where the lock\n * is reentrant and would not stop it.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PGlite | Transaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (!isPGliteDatabase(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n return {\n session: client,\n release: async (discard) => {\n if (!discard) {\n return;\n }\n try {\n await client.query(\"SELECT pg_advisory_unlock_all()\");\n } catch (resetFailure) {\n condemnPhysicalSession(client);\n throw unprovenLockStateError(\n this.driverName,\n \"No driver will pin a further migration session on that client. The client itself was NOT closed: it is the caller's database, not a pooled connection VibORM may discard.\",\n resetFailure\n );\n }\n },\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PGliteConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PGliteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PGliteDriver }\n >]: LinkedClientConfig<C & { driver: PGliteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"pglite\", PGLITE_CONFIG_KEYS);\n const { client, dataDir, options, pgvector, postgis } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PGliteDriver({\n client,\n dataDir,\n options,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PGliteDriver>(config, driver);\n}\n"],"mappings":"gdAwCA,MAAM,EAAkB,OAAO,YAC7B,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAK,CAAC,IAAK,GAAQ,CAChD,EACC,GAAkB,EACpB,CAAC,CACH,CAoBK,EAA8D,CAClE,OAAQ,GACR,QAAS,GACT,QAAS,GACT,SAAU,GACV,QAAS,GACT,UAAW,GACZ,CASD,SAAS,iBAAiB,EAAgD,CACxE,MAAO,gBAAiB,EAO1B,IAAa,aAAb,cAAkC,CAA4B,CAE5D,8BAA6D,MAC7D,sBAAoD,GAEpD,cAQA,eAEA,YAAY,EAA+B,EAAE,CAAE,CAC7C,MAAM,aAAc,SAAS,CAC7B,IAAM,EAAY,EAAuB,EAAQ,CACjD,KAAK,cAAgB,EACrB,KAAK,eAAiB,EAAQ,OAE1B,KAAK,iBACP,KAAK,OAAS,KAAK,eACnB,OAAO,eAAe,KAAM,kBAAmB,CAC7C,MAAO,EAAwB,KAAK,eAAe,CACpD,CAAC,EAGJ,EAAuB,KAAM,EAAW,EAAQ,CAWlD,MAAgB,YAA8B,CAC5C,GAAI,KAAK,iBAAmB,IAAA,GAC1B,OAAO,KAAK,eAEd,IAAM,EAAU,KAAK,cAAc,QAC7B,EAAc,KAAK,cAAc,SAAW,EAAE,CAC9C,EAAyB,CAC7B,GAAG,EACH,QAAS,CAIP,KAAO,GAAkB,EACzB,GAAG,EAAY,QAChB,CACF,CAGD,OAAO,EACH,MAAM,EAAO,OAAO,EAAS,EAAQ,CACrC,MAAM,EAAO,OAAO,EAAQ,CAalC,MAAgB,YAAY,EAA+B,CACrD,IAAW,KAAK,gBAGpB,MAAM,EAAO,OAAO,CAGtB,MAAgB,QACd,EACA,EACA,EACA,EACyB,CACzB,OAAO,KAAK,aAAa,EAAQ,EAAK,EAAQ,EAAS,UAAU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ACA,UACA,WACA,UACA,UARgB,EAAuB,EAAO,CAS/C,CAAC,CAEqE"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{at as t,rt as n}from"./geo-point-codec-lhxH42SK.mjs";import{i as r,o as i,r as a,t as o}from"./native-types-veeTk36s.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let n=s.get(e);if(n)return n;let r=e.autoGenerate;if(r===void 0||!t(r.kind)||r.implicit===!0)return;let i={format:r.kind,prefix:r.prefix,length:r.length};return s.set(e,i),i}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,t){let i=n(e);if(i===void 0)switch(t){case`pg`:return{representation:`text`,columnType:a.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:r.STRING.TEXT.type}}switch(t){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:a.STRING.UUID.type}:{representation:`bytes`,columnType:a.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:o.BLOB.BINARY(i).type};default:return{representation:`bytes`,columnType:r.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,t,i){let s=n(t);if(s===void 0)return;if(i===`pg`)return e===a.BLOB.BYTEA.type?`bytes`:e===a.STRING.UUID.type&&(t===`uuid`||t===`uuidv7`)?`uuid`:void 0;if(i===`sqlite`)return e===r.BLOB.BLOB.type?`bytes`:void 0;if(e===o.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let r=i(t,n);if(r===void 0)return defaultIdStorage(e.format,n);let a=r.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,t){let r=n(e),i=t===`pg`?`text, citext, varchar(n)`:t===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${t===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:t===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=i(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
2
+ //# sourceMappingURL=physical-6V_LNU3L.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"physical-BkelResN.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"wKAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,I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../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"0KAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,EAuBT,MAAM,EAAiB,mCACjB,EACJ,qEACI,EAAqB,SACrB,EAAqB,kCAG3B,SAAS,iBAAiB,EAAkB,EAA+B,CACzE,IAAM,EAAQ,EAAa,EAAO,CAClC,GAAI,IAAU,IAAA,GAEZ,OAAQ,EAAR,CACE,IAAK,KACH,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAG,OAAO,KAAK,KAAM,CACpE,IAAK,QACH,MAAO,CAAE,eAAgB,OAAQ,WAAY,OAAQ,CACvD,QACE,MAAO,CACL,eAAgB,OAChB,WAAY,EAAO,OAAO,KAAK,KAChC,CAGP,OAAQ,EAAR,CACE,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IAAmB,IAAA,GACtB,IAAA,GACA,CAAE,iBAAgB,WAAY,EAAM,CAI1C,SAAgB,sBACd,EACA,EACQ,CACR,IAAM,EAAQ,EAAa,EAAO,CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,n}from"./base-AdXAoy6l.mjs";import{i as r}from"./validation-Dk9Q_-C7.mjs";import{n as i}from"./suppressed-failure-BwULh-8h.mjs";import{t as a}from"./settle-B9Vg1FnP.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,n,r){return abandonedSessionError(e,s,n,t(r))}function abandonedSessionError(e,t,i,a){return new r(`Driver "${e}" ${t} ${i}`,{code:n.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:n.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,n,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,n,l,t(r));try{await a()}catch(e){throw i(abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,t(r)),e)}throw abandonedSessionError(o,n,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,t(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
2
+ //# sourceMappingURL=pinned-session-CLxj5M5e.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pinned-session-CLxj5M5e.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"iOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAcH,MAAM,EACJ,yLA4BF,eAAsB,+BAA+B,EAUnC,CAChB,GAAI,EAAY,OAAS,GAAM,CAC7B,GAAM,CAAE,sBAAqB,cAAe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 -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, jt as DriverConfig, 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, jn as QueryExecutionContext, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
2
2
  import { Client, Config, Connection } from "@planetscale/database";
3
3
 
4
4
  //#region src/drivers/planetscale/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{T as t,f as n}from"./validation-Du6j0Q38.mjs";import{c as r,s as i}from"./bind-parameter-capacity-DzMcIB95.mjs";import{r as a,s as o}from"./transactions-gjmrWN5W.mjs";import{s}from"./execution-context-BPk0YLhd.mjs";import{n as c}from"./client-tjSMPjeZ.mjs";import{i as l,t as u}from"./driver-options-DxlB1tms.mjs";import{i as d,t as f}from"./driver-yCYqzIQg.mjs";import{t as p}from"./sql-statement-tokens-CykxFmOJ.mjs";import{t as m}from"./mysql-adapter-D9FoHlWE.mjs";const h=/^(?:0|[1-9]\d*)$/,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,_=new Set([`ANALYZE`,`CALL`,`DESC`,`DESCRIBE`,`EXPLAIN`,`SELECT`,`SHOW`,`VALUES`]),v=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),y=new Set([`ALTER`,`BEGIN`,`COMMIT`,`CREATE`,`DROP`,`LOCK`,`RELEASE`,`RENAME`,`ROLLBACK`,`SAVEPOINT`,`SET`,`TRUNCATE`,`UNLOCK`,`USE`]),b=new Set([..._,...v]),defaultFetch=async(e,t)=>globalThis.fetch(e,t);function isRecord(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function isExecuteEndpoint(e){try{return new URL(e).pathname===`/psdb.v1alpha1.Database/Execute`}catch{return!1}}function getRequestQuery(e){if(typeof e==`string`)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.query==`string`?t.query:void 0}catch{return}}function classifyStatement(e){if(!e)return`unknown`;let t=p(e,{backslashEscapes:!0}),n=t?.[0];if(!(t&&n)||n.kind!==`word`)return`unknown`;let r=0;if(n.value===`WITH`&&(r=t.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r<0))return`unknown`;let i=t[r]?.value;return i?_.has(i)?`rows`:v.has(i)?t.slice(r+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:y.has(i)?`no-rows`:`unknown`:`unknown`}function malformedPlanetScaleResponse(e){return new n(`Driver "planetscale" returned a malformed successful response: ${e}.`,{meta:{driver:`planetscale`}})}function assertDenseArray(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!Object.hasOwn(e,t))return!1;return!0}function validateFields(e){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.fields is not a dense array`);let t=[],n=new Set;for(let r of e){if(!isRecord(r)||typeof r.name!=`string`||r.name.length===0||r.type!==void 0&&typeof r.type!=`string`)throw malformedPlanetScaleResponse(`result.fields contains an invalid field descriptor`);if(r.name===`__proto__`||n.has(r.name))throw malformedPlanetScaleResponse(`result.fields contains an unsafe or duplicate field name`);n.add(r.name),t.push(r)}return t}function validateRows(e,t){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.rows is not a dense array`);if(e.length>0&&t.length===0)throw malformedPlanetScaleResponse(`non-empty result.rows has no matching field metadata`);for(let n of e){if(!(isRecord(n)&&assertDenseArray(n.lengths)))throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`);let e=getExpectedRowByteLength(n.lengths,t.length),r=getBase64ByteLength(n.values);if(e===void 0||r!==e)throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`)}}function getExpectedRowByteLength(e,t){if(e.length!==t)return;let n=0;for(let t of e){if(t===`-1`)continue;if(typeof t!=`string`||!h.test(t))return;let e=Number(t);if(!Number.isSafeInteger(e)||n>2**53-1-e)return;n+=e}return n}function getBase64ByteLength(e){if(e===void 0)return 0;if(!(typeof e!=`string`||!g.test(e)))try{let t=atob(e);return btoa(t)===e?t.length:void 0}catch{return}}function validateExecuteEnvelope(e,t){if(!isRecord(e))throw malformedPlanetScaleResponse(`the response body is not an object`);if(Object.hasOwn(e,`error`)&&e.error!=null)return;if(!Object.hasOwn(e,`result`))throw malformedPlanetScaleResponse(`the result member is absent`);let n=e.result;if(n===null){if(t===`no-rows`)return;throw malformedPlanetScaleResponse(`a row-producing or unknown statement has a null result member`)}if(!isRecord(n))throw malformedPlanetScaleResponse(`the result member is not an object or null`);let r=[];if(Object.hasOwn(n,`fields`)&&n.fields!==null&&(r=validateFields(n.fields)),t!==`no-rows`&&r.length===0)throw malformedPlanetScaleResponse(`a row-producing or unknown statement has no field metadata`);if(Object.hasOwn(n,`rows`)&&validateRows(n.rows,r),Object.hasOwn(n,`rowsAffected`)&&n.rowsAffected!==null&&(typeof n.rowsAffected!=`string`||!h.test(n.rowsAffected)))throw malformedPlanetScaleResponse(`result.rowsAffected is malformed`);if(Object.hasOwn(n,`insertId`)&&n.insertId!==null&&(typeof n.insertId!=`string`||!h.test(n.insertId)))throw malformedPlanetScaleResponse(`result.insertId is malformed`)}function wrapExecuteResponse(e,t){return new Proxy(e,{get(e,n){if(n===`json`)return async()=>{let n;try{n=await e.json()}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(n,t),n};if(n===`text`)return async()=>{let n=await e.text(),r;try{r=JSON.parse(n)}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(r,t),n};let r=Reflect.get(e,n,e);return typeof r==`function`?r.bind(e):r}})}function createValidatedPlanetScaleFetch(e){let t=e??defaultFetch;return async(e,n)=>{let r=classifyStatement(getRequestQuery(n?.body)),i=await t(e,n);return isExecuteEndpoint(e)&&i.ok?wrapExecuteResponse(i,r):i}}function toQueryResult(e,t){let n={provider:`planetscale`,operation:t},a=i(e.insertId,n);return{rows:e.rows,rowCount:r(e.rowsAffected,n),...a===void 0?{}:{insertId:a}}}var PlanetScaleDriver=class extends f{maxBindParametersPerStatement=65535;supportsTransactions=!0;driverOptions;constructor(e={}){let t=l(e);super(`mysql`,`planetscale`),this.driverOptions=e,u(this,`adapter`,new m(t))}async initClient(){let{Client:e}=await import(`@planetscale/database`),n=this.driverOptions.client;if(n){if(!t(n.config))return n;let r={...n.config};return r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}let r={...this.driverOptions.options};return this.driverOptions.databaseUrl&&(r.url=this.driverOptions.databaseUrl),r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}async closeClient(e){}async execute(e,t,n,r){let i=r?.operation??`execute`;return toQueryResult(await e.execute(t,n),i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`;return toQueryResult(await e.execute(t,n),i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound`}}async transaction(e,t,n,r){if(!(`transaction`in e))throw a(this.driverName);let i=`connection`in e?e.connection():e,c=r?.isolationLevel;return o({begin:async()=>{await i.execute(`SET transaction_mode = 'single'`),c&&await i.execute(d(c)),await i.execute(`BEGIN`)},callback:()=>t(i),commit:()=>i.execute(`COMMIT`),rollback:()=>i.execute(`ROLLBACK`),phases:s(n)})}transactionCleanupFailed(e){this.client&&`connection`in this.client||super.transactionCleanupFailed(e)}};function createClient(e){let{client:t,databaseUrl:n,options:r}=e;return c(e,new PlanetScaleDriver({client:t,databaseUrl:n,options:r,namespace:l(e)}))}export{PlanetScaleDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{c as n,s as r}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{l as i,p as a}from"./error-mapping-CnPCv1dm.mjs";import{f as o}from"./validation-Dk9Q_-C7.mjs";import{s}from"./execution-context-BKR3bgES.mjs";import{n as c}from"./client-BLiBmykn.mjs";import{a as l,c as u,d,o as f,t as p}from"./driver-BlnKXPFF.mjs";import{t as m}from"./sql-statement-tokens-BBcoGmJb.mjs";import{t as h}from"./mysql-adapter-DkJPfoGf.mjs";const g=/^(?:0|[1-9]\d*)$/,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,v=new Set([`ANALYZE`,`CALL`,`DESC`,`DESCRIBE`,`EXPLAIN`,`SELECT`,`SHOW`,`VALUES`]),y=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),b=new Set([`ALTER`,`BEGIN`,`COMMIT`,`CREATE`,`DROP`,`LOCK`,`RELEASE`,`RENAME`,`ROLLBACK`,`SAVEPOINT`,`SET`,`TRUNCATE`,`UNLOCK`,`USE`]),x=new Set([...v,...y]),defaultFetch=async(e,t)=>globalThis.fetch(e,t);function isRecord(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function isExecuteEndpoint(e){try{return new URL(e).pathname===`/psdb.v1alpha1.Database/Execute`}catch{return!1}}function getRequestQuery(e){if(typeof e==`string`)try{let t=JSON.parse(e);return isRecord(t)&&typeof t.query==`string`?t.query:void 0}catch{return}}function classifyStatement(e){if(!e)return`unknown`;let t=m(e,{backslashEscapes:!0}),n=t?.[0];if(!(t&&n)||n.kind!==`word`)return`unknown`;let r=0;if(n.value===`WITH`&&(r=t.findIndex((e,t)=>t>0&&e.kind===`word`&&x.has(e.value)),r<0))return`unknown`;let i=t[r]?.value;return i?v.has(i)?`rows`:y.has(i)?t.slice(r+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:b.has(i)?`no-rows`:`unknown`:`unknown`}function malformedPlanetScaleResponse(e){return new o(`Driver "planetscale" returned a malformed successful response: ${e}.`,{meta:{driver:`planetscale`}})}function assertDenseArray(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!Object.hasOwn(e,t))return!1;return!0}function validateFields(e){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.fields is not a dense array`);let t=[],n=new Set;for(let r of e){if(!isRecord(r)||typeof r.name!=`string`||r.name.length===0||r.type!==void 0&&typeof r.type!=`string`)throw malformedPlanetScaleResponse(`result.fields contains an invalid field descriptor`);if(r.name===`__proto__`||n.has(r.name))throw malformedPlanetScaleResponse(`result.fields contains an unsafe or duplicate field name`);n.add(r.name),t.push(r)}return t}function validateRows(e,t){if(!assertDenseArray(e))throw malformedPlanetScaleResponse(`result.rows is not a dense array`);if(e.length>0&&t.length===0)throw malformedPlanetScaleResponse(`non-empty result.rows has no matching field metadata`);for(let n of e){if(!(isRecord(n)&&assertDenseArray(n.lengths)))throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`);let e=getExpectedRowByteLength(n.lengths,t.length),r=getBase64ByteLength(n.values);if(e===void 0||r!==e)throw malformedPlanetScaleResponse(`result.rows contains a row that does not match result.fields`)}}function getExpectedRowByteLength(e,t){if(e.length!==t)return;let n=0;for(let t of e){if(t===`-1`)continue;if(typeof t!=`string`||!g.test(t))return;let e=Number(t);if(!Number.isSafeInteger(e)||n>2**53-1-e)return;n+=e}return n}function getBase64ByteLength(e){if(e===void 0)return 0;if(!(typeof e!=`string`||!_.test(e)))try{let t=atob(e);return btoa(t)===e?t.length:void 0}catch{return}}function validateExecuteEnvelope(e,t){if(!isRecord(e))throw malformedPlanetScaleResponse(`the response body is not an object`);if(Object.hasOwn(e,`error`)&&e.error!=null)return;if(!Object.hasOwn(e,`result`))throw malformedPlanetScaleResponse(`the result member is absent`);let n=e.result;if(n===null){if(t===`no-rows`)return;throw malformedPlanetScaleResponse(`a row-producing or unknown statement has a null result member`)}if(!isRecord(n))throw malformedPlanetScaleResponse(`the result member is not an object or null`);let r=[];if(Object.hasOwn(n,`fields`)&&n.fields!==null&&(r=validateFields(n.fields)),t!==`no-rows`&&r.length===0)throw malformedPlanetScaleResponse(`a row-producing or unknown statement has no field metadata`);if(Object.hasOwn(n,`rows`)&&validateRows(n.rows,r),Object.hasOwn(n,`rowsAffected`)&&n.rowsAffected!==null&&(typeof n.rowsAffected!=`string`||!g.test(n.rowsAffected)))throw malformedPlanetScaleResponse(`result.rowsAffected is malformed`);if(Object.hasOwn(n,`insertId`)&&n.insertId!==null&&(typeof n.insertId!=`string`||!g.test(n.insertId)))throw malformedPlanetScaleResponse(`result.insertId is malformed`)}function wrapExecuteResponse(e,t){return new Proxy(e,{get(e,n){if(n===`json`)return async()=>{let n;try{n=await e.json()}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(n,t),n};if(n===`text`)return async()=>{let n=await e.text(),r;try{r=JSON.parse(n)}catch{throw malformedPlanetScaleResponse(`the response body is not valid JSON`)}return validateExecuteEnvelope(r,t),n};let r=Reflect.get(e,n,e);return typeof r==`function`?r.bind(e):r}})}function createValidatedPlanetScaleFetch(e){let t=e??defaultFetch;return async(e,n)=>{let r=classifyStatement(getRequestQuery(n?.body)),i=await t(e,n);return isExecuteEndpoint(e)&&i.ok?wrapExecuteResponse(i,r):i}}const S={client:!0,databaseUrl:!0,options:!0,namespace:!0};function toQueryResult(e,t){let i={provider:`planetscale`,operation:t},a=r(e.insertId,i);return{rows:e.rows,rowCount:n(e.rowsAffected,i),...a===void 0?{}:{insertId:a}}}var PlanetScaleDriver=class extends p{maxBindParametersPerStatement=65535;supportsTransactions=!0;driverOptions;constructor(e={}){let t=d(e);super(`mysql`,`planetscale`),this.driverOptions=e,f(this,`adapter`,new h(t))}async initClient(){let{Client:e}=await import(`@planetscale/database`),n=this.driverOptions.client;if(n){if(!t(n.config))return n;let r={...n.config};return r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}let r={...this.driverOptions.options};return this.driverOptions.databaseUrl&&(r.url=this.driverOptions.databaseUrl),r.fetch=createValidatedPlanetScaleFetch(r.fetch),new e(r)}async closeClient(e){}async execute(e,t,n,r){let i=r?.operation??`execute`;return toQueryResult(await e.execute(t,n),i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`;return toQueryResult(await e.execute(t,n),i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound`}}async transaction(e,t,n,r){if(!(`transaction`in e))throw i(this.driverName);let o=`connection`in e?e.connection():e,c=r?.isolationLevel;return a({begin:async()=>{await o.execute(`SET transaction_mode = 'single'`),c&&await o.execute(l(c)),await o.execute(`BEGIN`)},callback:()=>t(o),commit:()=>o.execute(`COMMIT`),rollback:()=>o.execute(`ROLLBACK`),phases:s(n)})}transactionCleanupFailed(e){this.client&&`connection`in this.client||super.transactionCleanupFailed(e)}};function createClient(e){u(e,`planetscale`,S);let{client:t,databaseUrl:n,options:r}=e;return c(e,new PlanetScaleDriver({client:t,databaseUrl:n,options:r,namespace:d(e)}))}export{PlanetScaleDriver,createClient};
2
2
  //# sourceMappingURL=planetscale.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planetscale.mjs","names":["isRecord","config"],"sources":["../src/drivers/planetscale/response-contract.ts","../src/drivers/planetscale/index.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport type { Config } from \"@planetscale/database\";\nimport { getTopLevelStatementTokens } from \"../shared/sql-statement-tokens\";\n\ntype PlanetScaleFetch = NonNullable<Config[\"fetch\"]>;\ntype PlanetScaleResponse = Awaited<ReturnType<PlanetScaleFetch>>;\n\nconst NON_NEGATIVE_DECIMAL = /^(?:0|[1-9]\\d*)$/;\nconst BASE64_REGEX =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst ROW_COMMANDS = new Set([\n \"ANALYZE\",\n \"CALL\",\n \"DESC\",\n \"DESCRIBE\",\n \"EXPLAIN\",\n \"SELECT\",\n \"SHOW\",\n \"VALUES\",\n]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DROP\",\n \"LOCK\",\n \"RELEASE\",\n \"RENAME\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SET\",\n \"TRUNCATE\",\n \"UNLOCK\",\n \"USE\",\n]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\ntype StatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst defaultFetch: PlanetScaleFetch = async (input, init) => {\n return globalThis.fetch(input, init);\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction isExecuteEndpoint(input: string): boolean {\n try {\n return new URL(input).pathname === \"/psdb.v1alpha1.Database/Execute\";\n } catch {\n return false;\n }\n}\n\nfunction getRequestQuery(body: unknown): string | undefined {\n if (typeof body !== \"string\") return undefined;\n try {\n const value: unknown = JSON.parse(body);\n return isRecord(value) && typeof value.query === \"string\"\n ? value.query\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction classifyStatement(sql: string | undefined): StatementResultKind {\n if (!sql) return \"unknown\";\n const tokens = getTopLevelStatementTokens(sql, { backslashEscapes: true });\n const first = tokens?.[0];\n if (!(tokens && first) || first.kind !== \"word\") return \"unknown\";\n\n let commandIndex = 0;\n if (first.value === \"WITH\") {\n commandIndex = tokens.findIndex(\n (token, index) =>\n index > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n if (commandIndex < 0) return \"unknown\";\n }\n\n const command = tokens[commandIndex]?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) return \"rows\";\n if (MUTATION_COMMANDS.has(command)) {\n return tokens\n .slice(commandIndex + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\nfunction malformedPlanetScaleResponse(reason: string): QueryError {\n return new QueryError(\n `Driver \"planetscale\" returned a malformed successful response: ${reason}.`,\n { meta: { driver: \"planetscale\" } }\n );\n}\n\nfunction assertDenseArray(value: unknown): value is unknown[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) return false;\n }\n return true;\n}\n\nfunction validateFields(value: unknown): Record<string, unknown>[] {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.fields is not a dense array\");\n }\n const fields: Record<string, unknown>[] = [];\n const fieldNames = new Set<string>();\n for (const field of value) {\n if (\n !isRecord(field) ||\n typeof field.name !== \"string\" ||\n field.name.length === 0 ||\n (field.type !== undefined && typeof field.type !== \"string\")\n ) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an invalid field descriptor\"\n );\n }\n if (field.name === \"__proto__\" || fieldNames.has(field.name)) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an unsafe or duplicate field name\"\n );\n }\n fieldNames.add(field.name);\n fields.push(field);\n }\n return fields;\n}\n\nfunction validateRows(\n value: unknown,\n fields: readonly Record<string, unknown>[]\n): void {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.rows is not a dense array\");\n }\n if (value.length > 0 && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"non-empty result.rows has no matching field metadata\"\n );\n }\n for (const row of value) {\n if (!(isRecord(row) && assertDenseArray(row.lengths))) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n const expectedBytes = getExpectedRowByteLength(row.lengths, fields.length);\n const actualBytes = getBase64ByteLength(row.values);\n if (expectedBytes === undefined || actualBytes !== expectedBytes) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n }\n}\n\nfunction getExpectedRowByteLength(\n lengths: readonly unknown[],\n fieldCount: number\n): number | undefined {\n if (lengths.length !== fieldCount) return undefined;\n let total = 0;\n for (const length of lengths) {\n if (length === \"-1\") continue;\n if (typeof length !== \"string\" || !NON_NEGATIVE_DECIMAL.test(length)) {\n return undefined;\n }\n const parsed = Number(length);\n if (\n !Number.isSafeInteger(parsed) ||\n total > Number.MAX_SAFE_INTEGER - parsed\n ) {\n return undefined;\n }\n total += parsed;\n }\n return total;\n}\n\nfunction getBase64ByteLength(value: unknown): number | undefined {\n if (value === undefined) return 0;\n if (typeof value !== \"string\" || !BASE64_REGEX.test(value)) return undefined;\n try {\n const decoded = atob(value);\n return btoa(decoded) === value ? decoded.length : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validateExecuteEnvelope(\n value: unknown,\n statementKind: StatementResultKind\n): void {\n if (!isRecord(value)) {\n throw malformedPlanetScaleResponse(\"the response body is not an object\");\n }\n\n // The SDK owns database-error translation. HTTP-200 error envelopes may omit\n // result, so leave them intact for its existing DatabaseError path.\n if (Object.hasOwn(value, \"error\") && value.error != null) return;\n\n if (!Object.hasOwn(value, \"result\")) {\n throw malformedPlanetScaleResponse(\"the result member is absent\");\n }\n const result = value.result;\n if (result === null) {\n if (statementKind === \"no-rows\") return;\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has a null result member\"\n );\n }\n if (!isRecord(result)) {\n throw malformedPlanetScaleResponse(\n \"the result member is not an object or null\"\n );\n }\n\n let fields: Record<string, unknown>[] = [];\n if (Object.hasOwn(result, \"fields\") && result.fields !== null) {\n fields = validateFields(result.fields);\n }\n if (statementKind !== \"no-rows\" && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has no field metadata\"\n );\n }\n if (Object.hasOwn(result, \"rows\")) {\n validateRows(result.rows, fields);\n }\n if (\n Object.hasOwn(result, \"rowsAffected\") &&\n result.rowsAffected !== null &&\n (typeof result.rowsAffected !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.rowsAffected))\n ) {\n throw malformedPlanetScaleResponse(\"result.rowsAffected is malformed\");\n }\n if (\n Object.hasOwn(result, \"insertId\") &&\n result.insertId !== null &&\n (typeof result.insertId !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.insertId))\n ) {\n throw malformedPlanetScaleResponse(\"result.insertId is malformed\");\n }\n}\n\nfunction wrapExecuteResponse(\n response: PlanetScaleResponse,\n statementKind: StatementResultKind\n): PlanetScaleResponse {\n return new Proxy(response, {\n get(target, property) {\n if (property === \"json\") {\n return async () => {\n let value: unknown;\n try {\n value = await target.json();\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return value;\n };\n }\n if (property === \"text\") {\n return async () => {\n const body = await target.text();\n let value: unknown;\n try {\n value = JSON.parse(body);\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return body;\n };\n }\n const member = Reflect.get(target, property, target);\n return typeof member === \"function\" ? member.bind(target) : member;\n },\n });\n}\n\nexport function createValidatedPlanetScaleFetch(\n fetchOption: Config[\"fetch\"]\n): PlanetScaleFetch {\n const fetchImpl = fetchOption ?? defaultFetch;\n return async (input, init) => {\n const statementKind = classifyStatement(getRequestQuery(init?.body));\n const response = await fetchImpl(input, init);\n return isExecuteEndpoint(input) && response.ok\n ? wrapExecuteResponse(response, statementKind)\n : response;\n };\n}\n","/**\n * PlanetScale Driver (Vitess MySQL)\n *\n * Driver implementation for @planetscale/database - PlanetScale's serverless MySQL driver.\n * Transactions pin one Connection and enable Vitess SINGLE mode before BEGIN;\n * Client.transaction() is intentionally not used because it hides that setup.\n */\n\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 type { Client, Config, Connection } from \"@planetscale/database\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\nimport { createValidatedPlanetScaleFetch } from \"./response-contract\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type PlanetScaleOptions = Omit<Config, \"url\">;\n\nexport interface PlanetScaleDriverOptions {\n client?: Client;\n databaseUrl?: string;\n options?: PlanetScaleOptions;\n /**\n * The Vitess keyspace qualifier this driver submits before VTGate applies\n * routing rules. It is never inferred from the PlanetScale database\n * resource, the SDK config, the URL, or a `@primary`/`@replica` selector,\n * and an omitted value leaves routing entirely with PlanetScale.\n */\n namespace?: string;\n}\n\nexport type PlanetScaleClientConfig<C extends DriverConfig> =\n PlanetScaleDriverOptions & C;\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\ntype PlanetScaleClient = Client | Connection;\ntype PlanetScaleTransaction = Pick<Connection, \"execute\">;\n\n/** PlanetScale reports insertId as a string; \"0\" means none was generated. */\nfunction toQueryResult<T>(\n result: {\n rows: unknown[];\n rowsAffected: number;\n insertId: string;\n },\n operation: string\n): QueryResult<T> {\n const context = { provider: \"planetscale\", operation };\n const insertId = normalizeProviderInsertId(result.insertId, context);\n return {\n rows: result.rows as T[],\n rowCount: normalizeProviderRowCount(result.rowsAffected, context),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\nexport class PlanetScaleDriver extends Driver<\n PlanetScaleClient,\n PlanetScaleTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n readonly supportsTransactions = true;\n\n private readonly driverOptions: PlanetScaleDriverOptions;\n\n constructor(options: PlanetScaleDriverOptions = {}) {\n // Only the explicit option records a qualifier here. This driver exposes no\n // attestation option and never reads one, so its base fact stays an\n // immutable `undefined` whatever the caller's object carries.\n const namespace = resolveNamespaceOption(options);\n super(\"mysql\", \"planetscale\");\n this.driverOptions = options;\n defineImmutableDriverFact(this, \"adapter\", new MySQLAdapter(namespace));\n }\n\n protected async initClient(): Promise<PlanetScaleClient> {\n const { Client } = await import(\"@planetscale/database\");\n\n const providedClient = this.driverOptions.client;\n if (providedClient) {\n if (!isRecord(providedClient.config)) return providedClient;\n const config: Config = { ...providedClient.config };\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n return new Client(config);\n }\n\n const config: Config = { ...this.driverOptions.options };\n\n if (this.driverOptions.databaseUrl) {\n config.url = this.driverOptions.databaseUrl;\n }\n\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n\n return new Client(config);\n }\n\n protected async closeClient(_client: PlanetScaleClient): Promise<void> {\n // PlanetScale HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n protected async executeRaw<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n /**\n * MySQL semantics: the level must be set before BEGIN, and this driver owns\n * both statements on one `Connection`. Every transaction gets a fresh HTTP\n * `Connection` created synchronously, so there is no slot to wait for.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound\",\n };\n }\n\n protected async transaction<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n fn: (tx: PlanetScaleTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"transaction\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n const connection: Connection =\n \"connection\" in client ? client.connection() : client;\n const isolationLevel = options?.isolationLevel;\n\n return runTransactionLifecycle({\n begin: async () => {\n // Vitess SINGLE mode rejects cross-shard transactions instead of using\n // best-effort multi-shard commit semantics.\n await connection.execute(\"SET transaction_mode = 'single'\");\n // Session-scoped-next-transaction: must precede BEGIN on this same\n // connection to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.execute(isolationLevelStatement(isolationLevel));\n }\n await connection.execute(\"BEGIN\");\n },\n callback: () => fn(connection),\n commit: () => connection.execute(\"COMMIT\"),\n rollback: () => connection.execute(\"ROLLBACK\"),\n phases: getExecutionTransactionPhases(context),\n });\n }\n\n protected override transactionCleanupFailed(error: Error): void {\n if (this.client && \"connection\" in this.client) {\n // Each transaction used a fresh Connection that is now discarded.\n return;\n }\n super.transactionCleanupFailed(error);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PlanetScaleClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PlanetScaleDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PlanetScaleDriver }\n >]: LinkedClientConfig<C & { driver: PlanetScaleDriver }>[P];\n}> {\n const { client, databaseUrl, options } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PlanetScaleDriver({\n client,\n databaseUrl,\n options,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PlanetScaleDriver>(config, driver);\n}\n"],"mappings":"ogBAOA,MAAM,EAAuB,mBACvB,EACJ,mEACI,EAAe,IAAI,IAAI,CAC3B,UACA,OACA,OACA,WACA,UACA,SACA,OACA,SACD,CAAC,CACI,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,QACA,SACA,SACA,OACA,OACA,UACA,SACA,WACA,YACA,MACA,WACA,SACA,MACD,CAAC,CACI,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAIhE,aAAiC,MAAO,EAAO,IAC5C,WAAW,MAAM,EAAO,EAAK,CAGtC,SAAS,SAAS,EAAkD,CAClE,OACE,OAAO,GAAU,YACjB,GACA,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,kBAI9C,SAAS,kBAAkB,EAAwB,CACjD,GAAI,CACF,OAAO,IAAI,IAAI,EAAM,CAAC,WAAa,uCAC7B,CACN,MAAO,IAIX,SAAS,gBAAgB,EAAmC,CACtD,UAAO,GAAS,SACpB,GAAI,CACF,IAAM,EAAiB,KAAK,MAAM,EAAK,CACvC,OAAO,SAAS,EAAM,EAAI,OAAO,EAAM,OAAU,SAC7C,EAAM,MACN,IAAA,QACE,CACN,QAIJ,SAAS,kBAAkB,EAA8C,CACvE,GAAI,CAAC,EAAK,MAAO,UACjB,IAAM,EAAS,EAA2B,EAAK,CAAE,iBAAkB,GAAM,CAAC,CACpE,EAAQ,IAAS,GACvB,GAAI,EAAE,GAAU,IAAU,EAAM,OAAS,OAAQ,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,EACA,EACA,EACA,EACyB,CACzB,IAAM,EAAY,GAAS,WAAa,aAExC,OAAO,cADQ,MAAM,EAAO,QAAQ,EAAK,EAAO,CAChB,EAAU,CAQ5C,0BAAwE,CACtE,MAAO,CACL,eAAgB,YAChB,QAAS,GACT,QAAS,cACT,cACE,oIACH,CAGH,MAAgB,YACd,EACA,EACA,EACA,EACY,CACZ,GAAI,EAAE,gBAAiB,GACrB,MAAM,EAA+B,KAAK,WAAW,CAGvD,IAAM,EACJ,eAAgB,EAAS,EAAO,YAAY,CAAG,EAC3C,EAAiB,GAAS,eAEhC,OAAO,EAAwB,CAC7B,MAAO,SAAY,CAGjB,MAAM,EAAW,QAAQ,kCAAkC,CAGvD,GACF,MAAM,EAAW,QAAQ,EAAwB,EAAe,CAAC,CAEnE,MAAM,EAAW,QAAQ,QAAQ,EAEnC,aAAgB,EAAG,EAAW,CAC9B,WAAc,EAAW,QAAQ,SAAS,CAC1C,aAAgB,EAAW,QAAQ,WAAW,CAC9C,OAAQ,EAA8B,EAAQ,CAC/C,CAAC,CAGJ,yBAA4C,EAAoB,CAC1D,KAAK,QAAU,eAAgB,KAAK,QAIxC,MAAM,yBAAyB,EAAM,GAQzC,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,cAAa,WAAY,EAUzC,OAAO,EAAsD,EAP9C,IAAI,kBAAkB,CACnC,SACA,cACA,UACA,UANgB,EAAuB,EAAO,CAO/C,CAAC,CAE0E"}
1
+ {"version":3,"file":"planetscale.mjs","names":["isRecord","config"],"sources":["../src/drivers/planetscale/response-contract.ts","../src/drivers/planetscale/index.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport type { Config } from \"@planetscale/database\";\nimport { getTopLevelStatementTokens } from \"../shared/sql-statement-tokens\";\n\ntype PlanetScaleFetch = NonNullable<Config[\"fetch\"]>;\ntype PlanetScaleResponse = Awaited<ReturnType<PlanetScaleFetch>>;\n\nconst NON_NEGATIVE_DECIMAL = /^(?:0|[1-9]\\d*)$/;\nconst BASE64_REGEX =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst ROW_COMMANDS = new Set([\n \"ANALYZE\",\n \"CALL\",\n \"DESC\",\n \"DESCRIBE\",\n \"EXPLAIN\",\n \"SELECT\",\n \"SHOW\",\n \"VALUES\",\n]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DROP\",\n \"LOCK\",\n \"RELEASE\",\n \"RENAME\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SET\",\n \"TRUNCATE\",\n \"UNLOCK\",\n \"USE\",\n]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\ntype StatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst defaultFetch: PlanetScaleFetch = async (input, init) => {\n return globalThis.fetch(input, init);\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction isExecuteEndpoint(input: string): boolean {\n try {\n return new URL(input).pathname === \"/psdb.v1alpha1.Database/Execute\";\n } catch {\n return false;\n }\n}\n\nfunction getRequestQuery(body: unknown): string | undefined {\n if (typeof body !== \"string\") return undefined;\n try {\n const value: unknown = JSON.parse(body);\n return isRecord(value) && typeof value.query === \"string\"\n ? value.query\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction classifyStatement(sql: string | undefined): StatementResultKind {\n if (!sql) return \"unknown\";\n const tokens = getTopLevelStatementTokens(sql, { backslashEscapes: true });\n const first = tokens?.[0];\n if (!(tokens && first) || first.kind !== \"word\") return \"unknown\";\n\n let commandIndex = 0;\n if (first.value === \"WITH\") {\n commandIndex = tokens.findIndex(\n (token, index) =>\n index > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n if (commandIndex < 0) return \"unknown\";\n }\n\n const command = tokens[commandIndex]?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) return \"rows\";\n if (MUTATION_COMMANDS.has(command)) {\n return tokens\n .slice(commandIndex + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\nfunction malformedPlanetScaleResponse(reason: string): QueryError {\n return new QueryError(\n `Driver \"planetscale\" returned a malformed successful response: ${reason}.`,\n { meta: { driver: \"planetscale\" } }\n );\n}\n\nfunction assertDenseArray(value: unknown): value is unknown[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) return false;\n }\n return true;\n}\n\nfunction validateFields(value: unknown): Record<string, unknown>[] {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.fields is not a dense array\");\n }\n const fields: Record<string, unknown>[] = [];\n const fieldNames = new Set<string>();\n for (const field of value) {\n if (\n !isRecord(field) ||\n typeof field.name !== \"string\" ||\n field.name.length === 0 ||\n (field.type !== undefined && typeof field.type !== \"string\")\n ) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an invalid field descriptor\"\n );\n }\n if (field.name === \"__proto__\" || fieldNames.has(field.name)) {\n throw malformedPlanetScaleResponse(\n \"result.fields contains an unsafe or duplicate field name\"\n );\n }\n fieldNames.add(field.name);\n fields.push(field);\n }\n return fields;\n}\n\nfunction validateRows(\n value: unknown,\n fields: readonly Record<string, unknown>[]\n): void {\n if (!assertDenseArray(value)) {\n throw malformedPlanetScaleResponse(\"result.rows is not a dense array\");\n }\n if (value.length > 0 && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"non-empty result.rows has no matching field metadata\"\n );\n }\n for (const row of value) {\n if (!(isRecord(row) && assertDenseArray(row.lengths))) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n const expectedBytes = getExpectedRowByteLength(row.lengths, fields.length);\n const actualBytes = getBase64ByteLength(row.values);\n if (expectedBytes === undefined || actualBytes !== expectedBytes) {\n throw malformedPlanetScaleResponse(\n \"result.rows contains a row that does not match result.fields\"\n );\n }\n }\n}\n\nfunction getExpectedRowByteLength(\n lengths: readonly unknown[],\n fieldCount: number\n): number | undefined {\n if (lengths.length !== fieldCount) return undefined;\n let total = 0;\n for (const length of lengths) {\n if (length === \"-1\") continue;\n if (typeof length !== \"string\" || !NON_NEGATIVE_DECIMAL.test(length)) {\n return undefined;\n }\n const parsed = Number(length);\n if (\n !Number.isSafeInteger(parsed) ||\n total > Number.MAX_SAFE_INTEGER - parsed\n ) {\n return undefined;\n }\n total += parsed;\n }\n return total;\n}\n\nfunction getBase64ByteLength(value: unknown): number | undefined {\n if (value === undefined) return 0;\n if (typeof value !== \"string\" || !BASE64_REGEX.test(value)) return undefined;\n try {\n const decoded = atob(value);\n return btoa(decoded) === value ? decoded.length : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction validateExecuteEnvelope(\n value: unknown,\n statementKind: StatementResultKind\n): void {\n if (!isRecord(value)) {\n throw malformedPlanetScaleResponse(\"the response body is not an object\");\n }\n\n // The SDK owns database-error translation. HTTP-200 error envelopes may omit\n // result, so leave them intact for its existing DatabaseError path.\n if (Object.hasOwn(value, \"error\") && value.error != null) return;\n\n if (!Object.hasOwn(value, \"result\")) {\n throw malformedPlanetScaleResponse(\"the result member is absent\");\n }\n const result = value.result;\n if (result === null) {\n if (statementKind === \"no-rows\") return;\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has a null result member\"\n );\n }\n if (!isRecord(result)) {\n throw malformedPlanetScaleResponse(\n \"the result member is not an object or null\"\n );\n }\n\n let fields: Record<string, unknown>[] = [];\n if (Object.hasOwn(result, \"fields\") && result.fields !== null) {\n fields = validateFields(result.fields);\n }\n if (statementKind !== \"no-rows\" && fields.length === 0) {\n throw malformedPlanetScaleResponse(\n \"a row-producing or unknown statement has no field metadata\"\n );\n }\n if (Object.hasOwn(result, \"rows\")) {\n validateRows(result.rows, fields);\n }\n if (\n Object.hasOwn(result, \"rowsAffected\") &&\n result.rowsAffected !== null &&\n (typeof result.rowsAffected !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.rowsAffected))\n ) {\n throw malformedPlanetScaleResponse(\"result.rowsAffected is malformed\");\n }\n if (\n Object.hasOwn(result, \"insertId\") &&\n result.insertId !== null &&\n (typeof result.insertId !== \"string\" ||\n !NON_NEGATIVE_DECIMAL.test(result.insertId))\n ) {\n throw malformedPlanetScaleResponse(\"result.insertId is malformed\");\n }\n}\n\nfunction wrapExecuteResponse(\n response: PlanetScaleResponse,\n statementKind: StatementResultKind\n): PlanetScaleResponse {\n return new Proxy(response, {\n get(target, property) {\n if (property === \"json\") {\n return async () => {\n let value: unknown;\n try {\n value = await target.json();\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return value;\n };\n }\n if (property === \"text\") {\n return async () => {\n const body = await target.text();\n let value: unknown;\n try {\n value = JSON.parse(body);\n } catch {\n throw malformedPlanetScaleResponse(\n \"the response body is not valid JSON\"\n );\n }\n validateExecuteEnvelope(value, statementKind);\n return body;\n };\n }\n const member = Reflect.get(target, property, target);\n return typeof member === \"function\" ? member.bind(target) : member;\n },\n });\n}\n\nexport function createValidatedPlanetScaleFetch(\n fetchOption: Config[\"fetch\"]\n): PlanetScaleFetch {\n const fetchImpl = fetchOption ?? defaultFetch;\n return async (input, init) => {\n const statementKind = classifyStatement(getRequestQuery(init?.body));\n const response = await fetchImpl(input, init);\n return isExecuteEndpoint(input) && response.ok\n ? wrapExecuteResponse(response, statementKind)\n : response;\n };\n}\n","/**\n * PlanetScale Driver (Vitess MySQL)\n *\n * Driver implementation for @planetscale/database - PlanetScale's serverless MySQL driver.\n * Transactions pin one Connection and enable Vitess SINGLE mode before BEGIN;\n * Client.transaction() is intentionally not used because it hides that setup.\n */\n\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 type { Client, Config, Connection } from \"@planetscale/database\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n normalizeProviderInsertId,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\nimport {\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n isolationLevelStatement,\n nestedTransactionDispatchError,\n resolveNamespaceOption,\n runTransactionLifecycle,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport type { QueryResult } from \"../types\";\nimport { createValidatedPlanetScaleFetch } from \"./response-contract\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport type PlanetScaleOptions = Omit<Config, \"url\">;\n\nexport interface PlanetScaleDriverOptions {\n client?: Client;\n databaseUrl?: string;\n options?: PlanetScaleOptions;\n /**\n * The Vitess keyspace qualifier this driver submits before VTGate applies\n * routing rules. It is never inferred from the PlanetScale database\n * resource, the SDK config, the URL, or a `@primary`/`@replica` selector,\n * and an omitted value leaves routing entirely with PlanetScale.\n */\n namespace?: string;\n}\n\nexport type PlanetScaleClientConfig<C extends DriverConfig> =\n PlanetScaleDriverOptions & C;\n\nconst PLANETSCALE_CONFIG_KEYS: Record<keyof PlanetScaleDriverOptions, true> = {\n client: true,\n databaseUrl: true,\n options: true,\n namespace: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\ntype PlanetScaleClient = Client | Connection;\ntype PlanetScaleTransaction = Pick<Connection, \"execute\">;\n\n/** PlanetScale reports insertId as a string; \"0\" means none was generated. */\nfunction toQueryResult<T>(\n result: {\n rows: unknown[];\n rowsAffected: number;\n insertId: string;\n },\n operation: string\n): QueryResult<T> {\n const context = { provider: \"planetscale\", operation };\n const insertId = normalizeProviderInsertId(result.insertId, context);\n return {\n rows: result.rows as T[],\n rowCount: normalizeProviderRowCount(result.rowsAffected, context),\n ...(insertId === undefined ? {} : { insertId }),\n };\n}\n\nexport class PlanetScaleDriver extends Driver<\n PlanetScaleClient,\n PlanetScaleTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_535;\n readonly supportsTransactions = true;\n\n private readonly driverOptions: PlanetScaleDriverOptions;\n\n constructor(options: PlanetScaleDriverOptions = {}) {\n // Only the explicit option records a qualifier here. This driver exposes no\n // attestation option and never reads one, so its base fact stays an\n // immutable `undefined` whatever the caller's object carries.\n const namespace = resolveNamespaceOption(options);\n super(\"mysql\", \"planetscale\");\n this.driverOptions = options;\n defineImmutableDriverFact(this, \"adapter\", new MySQLAdapter(namespace));\n }\n\n protected async initClient(): Promise<PlanetScaleClient> {\n const { Client } = await import(\"@planetscale/database\");\n\n const providedClient = this.driverOptions.client;\n if (providedClient) {\n if (!isRecord(providedClient.config)) return providedClient;\n const config: Config = { ...providedClient.config };\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n return new Client(config);\n }\n\n const config: Config = { ...this.driverOptions.options };\n\n if (this.driverOptions.databaseUrl) {\n config.url = this.driverOptions.databaseUrl;\n }\n\n config.fetch = createValidatedPlanetScaleFetch(config.fetch);\n\n return new Client(config);\n }\n\n protected async closeClient(_client: PlanetScaleClient): Promise<void> {\n // PlanetScale HTTP client doesn't need to be closed\n }\n\n protected async execute<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n protected async executeRaw<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.execute(sql, params);\n return toQueryResult<T>(result, operation);\n }\n\n /**\n * MySQL semantics: the level must be set before BEGIN, and this driver owns\n * both statements on one `Connection`. Every transaction gets a fresh HTTP\n * `Connection` created synchronously, so there is no slot to wait for.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"pre-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"each PlanetScale transaction gets its own HTTP connection created without waiting, so there is no acquisition maxWait could bound\",\n };\n }\n\n protected async transaction<T>(\n client: PlanetScaleClient | PlanetScaleTransaction,\n fn: (tx: PlanetScaleTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (!(\"transaction\" in client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n const connection: Connection =\n \"connection\" in client ? client.connection() : client;\n const isolationLevel = options?.isolationLevel;\n\n return runTransactionLifecycle({\n begin: async () => {\n // Vitess SINGLE mode rejects cross-shard transactions instead of using\n // best-effort multi-shard commit semantics.\n await connection.execute(\"SET transaction_mode = 'single'\");\n // Session-scoped-next-transaction: must precede BEGIN on this same\n // connection to bind to the transaction it opens.\n if (isolationLevel) {\n await connection.execute(isolationLevelStatement(isolationLevel));\n }\n await connection.execute(\"BEGIN\");\n },\n callback: () => fn(connection),\n commit: () => connection.execute(\"COMMIT\"),\n rollback: () => connection.execute(\"ROLLBACK\"),\n phases: getExecutionTransactionPhases(context),\n });\n }\n\n protected override transactionCleanupFailed(error: Error): void {\n if (this.client && \"connection\" in this.client) {\n // Each transaction used a fresh Connection that is now discarded.\n return;\n }\n super.transactionCleanupFailed(error);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PlanetScaleClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PlanetScaleDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PlanetScaleDriver }\n >]: LinkedClientConfig<C & { driver: PlanetScaleDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"planetscale\", PLANETSCALE_CONFIG_KEYS);\n const { client, databaseUrl, options } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PlanetScaleDriver({\n client,\n databaseUrl,\n options,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PlanetScaleDriver>(config, driver);\n}\n"],"mappings":"qgBAOA,MAAM,EAAuB,mBACvB,EACJ,mEACI,EAAe,IAAI,IAAI,CAC3B,UACA,OACA,OACA,WACA,UACA,SACA,OACA,SACD,CAAC,CACI,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,QACA,SACA,SACA,OACA,OACA,UACA,SACA,WACA,YACA,MACA,WACA,SACA,MACD,CAAC,CACI,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAIhE,aAAiC,MAAO,EAAO,IAC5C,WAAW,MAAM,EAAO,EAAK,CAGtC,SAAS,SAAS,EAAkD,CAClE,OACE,OAAO,GAAU,YACjB,GACA,OAAO,UAAU,SAAS,KAAK,EAAM,GAAK,kBAI9C,SAAS,kBAAkB,EAAwB,CACjD,GAAI,CACF,OAAO,IAAI,IAAI,EAAM,CAAC,WAAa,uCAC7B,CACN,MAAO,IAIX,SAAS,gBAAgB,EAAmC,CACtD,UAAO,GAAS,SACpB,GAAI,CACF,IAAM,EAAiB,KAAK,MAAM,EAAK,CACvC,OAAO,SAAS,EAAM,EAAI,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AC,CAE0E"}
@@ -1,5 +1,56 @@
1
- import { Bi as DecimalDescriptor, Rn as AnyModel, fn as DateTimePhysicalForm, l as AnyDriver } from "./index-T0YKKw66.mjs";
1
+ import { Ui as DecimalDescriptor, Vn as AnyModel, fn as DateTimePhysicalForm, l as AnyDriver } from "./index-C_XLSTy2.mjs";
2
2
 
3
+ //#region src/migrations/limits.d.ts
4
+
5
+ /**
6
+ * The limits of one migration command (plans S1, T5a): their type, their
7
+ * defaults and the one resolver. Only migration code imports this module, so
8
+ * an application bundle carries none of it.
9
+ */
10
+ /**
11
+ * The limits of one migration command's pinned session (plan S1), and the
12
+ * table size it may rewrite in-request (plan T5a).
13
+ *
14
+ * Every value but `largeTableRows` is in milliseconds. `lockTimeout`, `statementTimeout` and
15
+ * `idleTimeout` are PostgreSQL server settings, where 0 means "no limit";
16
+ * `lockWait` and `connectionWait` are waits VibORM itself bounds. `lockWait`
17
+ * also bounds SQLite's `BEGIN IMMEDIATE`, and `connectionWait` applies to
18
+ * MySQL as well; the others, `largeTableRows` included, are PostgreSQL-only,
19
+ * and MySQL keeps its fixed named-lock wait.
20
+ */
21
+ interface MigrationLimits {
22
+ /**
23
+ * `lock_timeout`, for the session and, with `SET LOCAL`, every migration
24
+ * transaction: how long one DDL statement may queue for a table lock.
25
+ */
26
+ readonly lockTimeout?: number;
27
+ /**
28
+ * `statement_timeout`, for every migration transaction and for the session
29
+ * around the lock and stepwise programs. 0, or longer than `lockWait`.
30
+ */
31
+ readonly statementTimeout?: number;
32
+ /**
33
+ * `idle_in_transaction_session_timeout` and, on PostgreSQL 14+,
34
+ * `idle_session_timeout`: how long the server keeps a migration session
35
+ * whose client stopped talking — the one that vanished holding the lock.
36
+ */
37
+ readonly idleTimeout?: number;
38
+ /** How long the command waits for the migration lock another one holds. */
39
+ readonly lockWait?: number;
40
+ /** How long the command waits for its pinned connection. */
41
+ readonly connectionWait?: number;
42
+ /**
43
+ * A row count, not milliseconds: the planner's estimate above which a
44
+ * statement that rewrites or scans a table under a lock that blocks it (a
45
+ * column type change, `SET NOT NULL`, a volatile `ADD COLUMN` default, a
46
+ * FOREIGN KEY or CHECK added without `NOT VALID`) is refused before any
47
+ * effect, because it would hold that lock longer than a request should.
48
+ * 0 admits every size.
49
+ */
50
+ readonly largeTableRows?: number;
51
+ }
52
+ type ResolvedMigrationLimits = Readonly<Required<MigrationLimits>>;
53
+ //#endregion
3
54
  //#region src/migrations/types.d.ts
4
55
  interface SchemaSnapshot {
5
56
  tables: TableDef[];
@@ -417,6 +468,8 @@ type MigrationTarget = ({
417
468
  //#endregion
418
469
  //#region src/migrations/target.d.ts
419
470
  declare const MANAGED_TABLES: unique symbol;
471
+ /** The client's resolved limits (plans S1, T5a), bound with its driver. */
472
+ declare const MIGRATION_LIMITS: unique symbol;
420
473
  //#endregion
421
474
  //#region src/migrations/push/planner.d.ts
422
475
  /**
@@ -426,7 +479,8 @@ declare const MANAGED_TABLES: unique symbol;
426
479
  interface MigrationClient {
427
480
  $driver: AnyDriver;
428
481
  $schema: Record<string, AnyModel>;
429
- readonly [MANAGED_TABLES]?: readonly string[];
482
+ readonly [MANAGED_TABLES]?: readonly string[] | undefined;
483
+ readonly [MIGRATION_LIMITS]?: ResolvedMigrationLimits | undefined;
430
484
  }
431
485
  //#endregion
432
- export { ResolveChange as a, ResolveCallback as i, DiffOperation as n, SchemaSnapshot as o, MigrationTarget as r, MigrationClient as t };
486
+ export { ResolveChange as a, ResolveCallback as i, DiffOperation as n, SchemaSnapshot as o, MigrationTarget as r, MigrationLimits as s, MigrationClient as t };
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{f as n,p as r}from"./validation-Dk9Q_-C7.mjs";import{o as i,t as a}from"./sql-Bp7jicEX.mjs";import{r as o}from"./adapter-internals-n3Mf3css.mjs";import{O as s,v as c}from"./geo-point-codec-lhxH42SK.mjs";import{a as l}from"./datetime-physical-codec-oIhiYZEP.mjs";import{t as u}from"./geo-area-codec-1SY9im7O.mjs";import{o as d}from"./native-types-veeTk36s.mjs";import{a as f}from"./physical-6V_LNU3L.mjs";import{t as p}from"./array-literal-BsbbSLw3.mjs";import{A as m,C as ee,D as h,E as g,M as _,S as v,T as y,_ as b,a as x,b as S,c as C,d as w,f as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,v as te,w as F,x as I,y as L}from"./standard-sql-Bk4RZPqJ.mjs";import{r as R}from"./batch-refs-4L8ECdPU.mjs";import{t as z}from"./adapter-namespace-DqkJQdrD.mjs";import{a as B,c as V,g as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-f1UGoblh.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=_(`"`);function postgresLikeLiteral(e){return i`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresAsciiCaseFold(e){return i`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`}function postgresJsonObject(e){if(e.length===0)return i.raw`'{}'::json`;let t=[],n=i.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let a=e.slice(r,r+50).flatMap(([e,t])=>[i`${e}::text`,t]);t.push(i`${n}(${i.join(a,`, `)})`)}return t.length===1?t[0]:i`(${i.join(t,` || `)})::json`}const ne=G(e=>`${e}_pkey`);var CastParameter=class extends a{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends a{};const re=g().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=p(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>i`div(${e}, ${t})`,remainder:(e,t)=>i`mod(${e}, ${t})`},ie=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){z(this,e,`postgresql`),this.identifiers=T(Q,this.namespace),q(this,t?this.#r():void 0),o(this,{batchRefs:this.#n,constraints:ne,select:this.#e.select})}raw=v();identifiers;literals={...g(),dateTime:e=>i`${l(e)}`,true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(s(e,t,`text`),c(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):i`${e}`,list:e=>arrayParameter(e)??re(e)};operators={...x(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`${postgresAsciiCaseFold(e)} LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,notIlike:(e,t)=>i`${postgresAsciiCaseFold(e)} NOT LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,containsText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>i`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>i`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${m(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?i`${e} = ANY(${t})`:i`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?i`${e} <> ALL(${t})`:i`${e} NOT IN ${t}`,...te(),...I(),...E(this.literals.true,this.literals.false),...w()};expressions={...D(),caseSensitiveText:(e,t,n=!1)=>{let a=d(t,`pg`)?.type;if(!n&&a?.toLowerCase()===`xml`)throw new r(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return n&&a&&ie.test(a)?i`CAST(${e} AS TEXT)`:e},asciiCaseFold:postgresAsciiCaseFold,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / ${t})`,decimalCast:(e,t)=>i`CAST(${e} AS ${i.raw(c(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?i`decode(${e}, 'hex')`:i`CAST(${e} AS ${i.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:N({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>i`encode(${e}, 'hex')`};aggregates={...A(`'Infinity'::float8`),min:(e,t=!1)=>t?i`BOOL_AND(${e})`:i`MIN(${e})`,max:(e,t=!1)=>t?i`BOOL_OR(${e})`:i`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:C(1e3)};json={equals:(e,t)=>i`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?i.raw`'[]'::json`:i`json_build_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw`'[]'::json`,agg:e=>i`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>i`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>i`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>i`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>i`(${e})::jsonb @> ${t}`,lastElement:e=>i`(${e})::jsonb -> -1`,value:e=>i`${Z.from(e)}`};arrays={literal:e=>e.length===0?i.raw`'{}'`:i`ARRAY[${i.join(e,`, `)}]`,value:(e,t)=>i`${t?e.map(e=>typeof e==`string`?l(e):e):e}`,enumValue:e=>i`${p(e)}`,has:(e,t)=>i`${t} = ANY(${e})`,hasEvery:(e,t)=>i`${e} @> ${t}`,hasSome:(e,t)=>i`${e} && ${t}`,isEmpty:e=>i`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT[])`,length:e=>i`cardinality(${e})`,get:(e,t)=>i`${e}[${t}]`,push:(e,t)=>i`array_append(${e}, ${t})`,set:(e,t,n)=>i`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...O(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`};clauses=y();set={...L(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?V($,e,t,n.decimal):i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>i`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=ee();subqueries=h(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?i`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:i`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q);mutations={skipDuplicatesStrategy:`sql`,insert:M(Q),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...b(),returning:e=>i`RETURNING ${e}`,...S()};assertions={exists:e=>i`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>i`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`};joins={...j(),full:(e,t)=>i`FULL OUTER JOIN ${e} ON ${t}`,...k(Q)};setOperations=F();capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0};lastInsertId=()=>i.raw`lastval()`;#t=R({table:i.raw`"__viborm_batch_refs"`,batchIdColumn:i.raw`"batch_id"`,keyColumn:i.raw`"ref_key"`,valueColumn:i.raw`"ref_value"`,createTable:i.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>i`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new n(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return i`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>i`${e} <-> ${t}`,cosine:(e,t)=>i`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>i`ST_X(${e}::geometry)`,latitude=e=>i`ST_Y(${e}::geometry)`;return{value:(e,t)=>i`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_SetSRID(ST_GeomFromGeoJSON(${B(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=i`RADIANS(ST_X(${e}::geometry))`,r=i`RADIANS(ST_Y(${e}::geometry))`,a=i`RADIANS(ST_X(${t}::geometry))`,o=i`RADIANS(ST_Y(${t}::geometry))`;return i`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${u} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${i`POWER(SIN((${o} - ${r}) / 2), 2) + COS(${r}) * COS(${o}) * POWER(SIN((${a} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>f(e,t,`pg`)?.representation??`text`,parseResult:H,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
+ //# sourceMappingURL=postgres-adapter-B3SQvcV1.mjs.map