viborm 1.5.1 → 1.6.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 (254) hide show
  1. package/README.md +4 -2
  2. package/dist/{adapter-internals-Dagucesf.mjs → adapter-internals-DULbfdmQ.mjs} +1 -1
  3. package/dist/{adapter-internals-Dagucesf.mjs.map → adapter-internals-DULbfdmQ.mjs.map} +1 -1
  4. package/dist/{adapter-namespace-DuugUuQa.mjs → adapter-namespace-CFtC8LbT.mjs} +2 -2
  5. package/dist/{adapter-namespace-DuugUuQa.mjs.map → adapter-namespace-CFtC8LbT.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-B63ouFIz.mjs → adapter-result-parser-C0vW9am8.mjs} +1 -1
  7. package/dist/{adapter-result-parser-B63ouFIz.mjs.map → adapter-result-parser-C0vW9am8.mjs.map} +1 -1
  8. package/dist/adapters.d.mts +1 -1
  9. package/dist/adapters.mjs +1 -1
  10. package/dist/{array-literal-BU1R9byi.mjs → array-literal-Dohoq5rT.mjs} +1 -1
  11. package/dist/{array-literal-BU1R9byi.mjs.map → array-literal-Dohoq5rT.mjs.map} +1 -1
  12. package/dist/{batch-refs-C3MTcVre.mjs → batch-refs-cBYAKzaE.mjs} +2 -2
  13. package/dist/{batch-refs-C3MTcVre.mjs.map → batch-refs-cBYAKzaE.mjs.map} +1 -1
  14. package/dist/bind-parameter-capacity-4OU6feZG.mjs +2 -0
  15. package/dist/{bind-parameter-capacity-faPOSaLz.mjs.map → bind-parameter-capacity-4OU6feZG.mjs.map} +1 -1
  16. package/dist/{builder-ClblW6Lj.mjs → builder-D0GQK-fA.mjs} +2 -2
  17. package/dist/{builder-ClblW6Lj.mjs.map → builder-D0GQK-fA.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/bun-sqlite.mjs.map +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/cache.d.mts +1 -1
  28. package/dist/cache.mjs +1 -1
  29. package/dist/{canonical-json-JLUMrnoq.mjs → canonical-json-D_FgOt4S.mjs} +1 -1
  30. package/dist/{canonical-json-JLUMrnoq.mjs.map → canonical-json-D_FgOt4S.mjs.map} +1 -1
  31. package/dist/chain-BQoDfo80.mjs +2 -0
  32. package/dist/{chain-C1VPkUpC.mjs.map → chain-BQoDfo80.mjs.map} +1 -1
  33. package/dist/cli.mjs +1 -1
  34. package/dist/{client-C1MxqFtt.mjs → client-BCcIdDl8.mjs} +4 -4
  35. package/dist/client-BCcIdDl8.mjs.map +1 -0
  36. package/dist/client-BqgVSbk0.mjs +2 -0
  37. package/dist/client-BqgVSbk0.mjs.map +1 -0
  38. package/dist/{client-DyIsSin0.d.mts → client-C5BGyg5n.d.mts} +3 -3
  39. package/dist/client.d.mts +1 -1
  40. package/dist/client.mjs +1 -1
  41. package/dist/{clock-CK41KO7t.mjs → clock-QtW83Dcm.mjs} +1 -1
  42. package/dist/{clock-CK41KO7t.mjs.map → clock-QtW83Dcm.mjs.map} +1 -1
  43. package/dist/config.d.mts +2 -2
  44. package/dist/config.mjs +1 -1
  45. package/dist/{current-CKQ4EgeM.mjs → current-CEWlNJcP.mjs} +1 -1
  46. package/dist/{current-CKQ4EgeM.mjs.map → current-CEWlNJcP.mjs.map} +1 -1
  47. package/dist/d1.d.mts +1 -1
  48. package/dist/d1.mjs +1 -1
  49. package/dist/d1.mjs.map +1 -1
  50. package/dist/{datetime-physical-codec-DfVmz14E.mjs → datetime-physical-codec-Bl6M6vF5.mjs} +2 -2
  51. package/dist/{datetime-physical-codec-DfVmz14E.mjs.map → datetime-physical-codec-Bl6M6vF5.mjs.map} +1 -1
  52. package/dist/{driver-DpQbSOUD.mjs → driver-Dv2GJyGs.mjs} +2 -2
  53. package/dist/{driver-DpQbSOUD.mjs.map → driver-Dv2GJyGs.mjs.map} +1 -1
  54. package/dist/driver-szWYBmjD.mjs +2 -0
  55. package/dist/{driver-aqfbJdZC.mjs.map → driver-szWYBmjD.mjs.map} +1 -1
  56. package/dist/driver.d.mts +1 -1
  57. package/dist/driver.mjs +1 -1
  58. package/dist/error-mapping-DRY49A3C.mjs +2 -0
  59. package/dist/error-mapping-DRY49A3C.mjs.map +1 -0
  60. package/dist/every-DIG9CPly.mjs +2 -0
  61. package/dist/{every-BUf842ai.mjs.map → every-DIG9CPly.mjs.map} +1 -1
  62. package/dist/{fs-estate-BXNX7l62.mjs → fs-estate-DNCM7hYC.mjs} +2 -2
  63. package/dist/{fs-estate-BXNX7l62.mjs.map → fs-estate-DNCM7hYC.mjs.map} +1 -1
  64. package/dist/{geo-area-codec-DQpSEgSD.mjs → geo-area-codec-H50rrGiF.mjs} +2 -2
  65. package/dist/{geo-area-codec-DQpSEgSD.mjs.map → geo-area-codec-H50rrGiF.mjs.map} +1 -1
  66. package/dist/geo-point-codec-mjROsQX-.mjs +2 -0
  67. package/dist/{geo-point-codec-DcUTvoEg.mjs.map → geo-point-codec-mjROsQX-.mjs.map} +1 -1
  68. package/dist/{hydration-BK6vRndL.mjs → hydration-BQ7tYLtA.mjs} +2 -2
  69. package/dist/{hydration-BK6vRndL.mjs.map → hydration-BQ7tYLtA.mjs.map} +1 -1
  70. package/dist/{identifier-conversion-8ldidfgu.mjs → identifier-conversion-DV63mwKG.mjs} +2 -2
  71. package/dist/{identifier-conversion-8ldidfgu.mjs.map → identifier-conversion-DV63mwKG.mjs.map} +1 -1
  72. package/dist/{identity-Bu6jbgym.mjs → identity-B75EaVTM.mjs} +2 -2
  73. package/dist/{identity-Bu6jbgym.mjs.map → identity-B75EaVTM.mjs.map} +1 -1
  74. package/dist/{index-Ci8b13Lm.d.mts → index-DRX_LLQM.d.mts} +47 -8
  75. package/dist/index.d.mts +2 -2
  76. package/dist/index.mjs +1 -1
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/instrumentation.d.mts +1 -1
  79. package/dist/instrumentation.mjs +1 -1
  80. package/dist/{invariant-BnLYqsHO.mjs → invariant-B5znICP_.mjs} +1 -1
  81. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-B5znICP_.mjs.map} +1 -1
  82. package/dist/{json-number-CAfNAqDB.mjs → json-number-DoseUwuo.mjs} +1 -1
  83. package/dist/{json-number-CAfNAqDB.mjs.map → json-number-DoseUwuo.mjs.map} +1 -1
  84. package/dist/{key-DJXcPZR_.mjs → key-rszcmZdB.mjs} +2 -2
  85. package/dist/{key-DJXcPZR_.mjs.map → key-rszcmZdB.mjs.map} +1 -1
  86. package/dist/{libsql-Dmtj0O4E.mjs → libsql-CAZVcr9G.mjs} +2 -2
  87. package/dist/{libsql-Dmtj0O4E.mjs.map → libsql-CAZVcr9G.mjs.map} +1 -1
  88. package/dist/libsql.d.mts +1 -1
  89. package/dist/libsql.mjs +1 -1
  90. package/dist/libsql.mjs.map +1 -1
  91. package/dist/{memory-b-dafk9S.mjs → memory-CqWRO6-3.mjs} +2 -2
  92. package/dist/{memory-b-dafk9S.mjs.map → memory-CqWRO6-3.mjs.map} +1 -1
  93. package/dist/migrations/mysql.d.mts +5 -5
  94. package/dist/migrations/mysql.mjs +1 -1
  95. package/dist/migrations/postgres.d.mts +5 -5
  96. package/dist/migrations/postgres.mjs +1 -1
  97. package/dist/migrations/sqlite.d.mts +5 -5
  98. package/dist/migrations/sqlite.mjs +1 -1
  99. package/dist/migrations/storage/durable-object.d.mts +1 -1
  100. package/dist/migrations/storage/durable-object.mjs +1 -1
  101. package/dist/migrations/storage/fs.d.mts +1 -1
  102. package/dist/migrations/storage/fs.mjs +1 -1
  103. package/dist/migrations/storage/r2.d.mts +1 -1
  104. package/dist/migrations/storage/r2.mjs +1 -1
  105. package/dist/migrations/tenant.d.mts +3 -3
  106. package/dist/migrations/tenant.mjs +1 -1
  107. package/dist/migrations.d.mts +5 -5
  108. package/dist/migrations.mjs +1 -1
  109. package/dist/{mysql-DAaUSeBw.mjs → mysql-BPPBSJzl.mjs} +2 -2
  110. package/dist/{mysql-DAaUSeBw.mjs.map → mysql-BPPBSJzl.mjs.map} +1 -1
  111. package/dist/mysql-adapter-Dbo7l0lI.mjs +2 -0
  112. package/dist/mysql-adapter-Dbo7l0lI.mjs.map +1 -0
  113. package/dist/mysql2.d.mts +1 -1
  114. package/dist/mysql2.mjs +1 -1
  115. package/dist/mysql2.mjs.map +1 -1
  116. package/dist/{native-types-BbKWN3JV.mjs → native-types-6wCGP1a1.mjs} +1 -1
  117. package/dist/{native-types-BbKWN3JV.mjs.map → native-types-6wCGP1a1.mjs.map} +1 -1
  118. package/dist/neon-http.d.mts +1 -1
  119. package/dist/neon-http.mjs +1 -1
  120. package/dist/neon-http.mjs.map +1 -1
  121. package/dist/normalized-result-23DWxZVY.mjs +2 -0
  122. package/dist/{normalized-result-VunNi4ID.mjs.map → normalized-result-23DWxZVY.mjs.map} +1 -1
  123. package/dist/{object-store-BHyP-LEI.d.mts → object-store-Cs3AueG5.d.mts} +4 -4
  124. package/dist/{object-store-I1MyfM72.mjs → object-store-DmnlQy7V.mjs} +2 -2
  125. package/dist/{object-store-I1MyfM72.mjs.map → object-store-DmnlQy7V.mjs.map} +1 -1
  126. package/dist/on.d.mts +80 -0
  127. package/dist/on.mjs +2 -0
  128. package/dist/on.mjs.map +1 -0
  129. package/dist/permissions.d.mts +1 -1
  130. package/dist/permissions.mjs +1 -1
  131. package/dist/pg.d.mts +1 -1
  132. package/dist/pg.mjs +1 -1
  133. package/dist/pg.mjs.map +1 -1
  134. package/dist/pglite.d.mts +1 -1
  135. package/dist/pglite.mjs +1 -1
  136. package/dist/{physical-CAZ_LauY.mjs → physical-DT6C54w7.mjs} +2 -2
  137. package/dist/{physical-CAZ_LauY.mjs.map → physical-DT6C54w7.mjs.map} +1 -1
  138. package/dist/pinned-session-BdON2d0V.mjs +2 -0
  139. package/dist/{pinned-session-D8bM5obl.mjs.map → pinned-session-BdON2d0V.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/planetscale.mjs.map +1 -1
  143. package/dist/{planner-BDLdDieE.d.mts → planner-BxCcoO8s.d.mts} +22 -1
  144. package/dist/{postgres-HaFcFACt.mjs → postgres-BK_aOx_C.mjs} +44 -37
  145. package/dist/postgres-BK_aOx_C.mjs.map +1 -0
  146. package/dist/postgres-adapter-CVazEDVI.mjs +2 -0
  147. package/dist/postgres-adapter-CVazEDVI.mjs.map +1 -0
  148. package/dist/postgres-adapter-DxhZu7Qw.mjs +2 -0
  149. package/dist/{postgres-adapter-CnZjhvG1.mjs.map → postgres-adapter-DxhZu7Qw.mjs.map} +1 -1
  150. package/dist/postgres-result-DYeVeHuT.mjs +2 -0
  151. package/dist/{postgres-result-D4_yZqO8.mjs.map → postgres-result-DYeVeHuT.mjs.map} +1 -1
  152. package/dist/postgres.d.mts +1 -1
  153. package/dist/postgres.mjs +1 -1
  154. package/dist/postgres.mjs.map +1 -1
  155. package/dist/{provider-limits-CpitUqW6.mjs → provider-limits-zLe7S_0W.mjs} +2 -2
  156. package/dist/{provider-limits-CpitUqW6.mjs.map → provider-limits-zLe7S_0W.mjs.map} +1 -1
  157. package/dist/{validation-DN1N2OdK.mjs → query-CTna5P9o.mjs} +2 -2
  158. package/dist/query-CTna5P9o.mjs.map +1 -0
  159. package/dist/{relation-bound-5ChGF3n5.mjs → relation-bound-Bj7X-EUE.mjs} +1 -1
  160. package/dist/{relation-bound-5ChGF3n5.mjs.map → relation-bound-Bj7X-EUE.mjs.map} +1 -1
  161. package/dist/{result-parsing-BX3_3Q15.mjs → result-parsing-C2044903.mjs} +1 -1
  162. package/dist/{result-parsing-BX3_3Q15.mjs.map → result-parsing-C2044903.mjs.map} +1 -1
  163. package/dist/result-shape-C8QFUuIt.mjs +2 -0
  164. package/dist/{result-shape-BuGfArOr.mjs.map → result-shape-C8QFUuIt.mjs.map} +1 -1
  165. package/dist/rows-D7ns2l0U.mjs +2 -0
  166. package/dist/{rows-BlONp14o.mjs.map → rows-D7ns2l0U.mjs.map} +1 -1
  167. package/dist/{scalar-B3WLZzJj.mjs → scalar-D6QmJ22_.mjs} +2 -2
  168. package/dist/{scalar-B3WLZzJj.mjs.map → scalar-D6QmJ22_.mjs.map} +1 -1
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/{schema-B_Bc7TQ2.mjs → schema-CY9kOwJ-.mjs} +2 -2
  172. package/dist/{schema-B_Bc7TQ2.mjs.map → schema-CY9kOwJ-.mjs.map} +1 -1
  173. package/dist/{schema-introspection-BqN7d_sA.mjs → schema-introspection-CfqmM3Cz.mjs} +2 -2
  174. package/dist/{schema-introspection-BqN7d_sA.mjs.map → schema-introspection-CfqmM3Cz.mjs.map} +1 -1
  175. package/dist/schema.d.mts +1 -1
  176. package/dist/schema.mjs +1 -1
  177. package/dist/{select-assembly-BP8c4O-0.mjs → select-assembly-D7FEenz2.mjs} +2 -2
  178. package/dist/select-assembly-D7FEenz2.mjs.map +1 -0
  179. package/dist/{settle-B9Vg1FnP.mjs → settle-CObilv26.mjs} +2 -2
  180. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CObilv26.mjs.map} +1 -1
  181. package/dist/{sha256-DDEbgnTU.mjs → sha256-Da07rzvR.mjs} +1 -1
  182. package/dist/{sha256-DDEbgnTU.mjs.map → sha256-Da07rzvR.mjs.map} +1 -1
  183. package/dist/soft-delete.d.mts +1 -1
  184. package/dist/{sql-BR8ZzKn8.mjs → sql-DGtEeP8z.mjs} +1 -1
  185. package/dist/{sql-BR8ZzKn8.mjs.map → sql-DGtEeP8z.mjs.map} +1 -1
  186. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-DL3ooNs7.mjs} +1 -1
  187. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-DL3ooNs7.mjs.map} +1 -1
  188. package/dist/sql.d.mts +1 -1
  189. package/dist/sql.mjs +1 -1
  190. package/dist/sqlite-adapter-DqT6HeDs.mjs +2 -0
  191. package/dist/sqlite-adapter-DqT6HeDs.mjs.map +1 -0
  192. package/dist/{sqlite-utils-CFInz2yY.mjs → sqlite-utils-DeDlMJKj.mjs} +2 -2
  193. package/dist/{sqlite-utils-CFInz2yY.mjs.map → sqlite-utils-DeDlMJKj.mjs.map} +1 -1
  194. package/dist/sqlite3.d.mts +1 -1
  195. package/dist/sqlite3.mjs +1 -1
  196. package/dist/sqlite3.mjs.map +1 -1
  197. package/dist/{standard-sql-wRMNi-Yg.mjs → standard-sql-BErrm6AV.mjs} +2 -2
  198. package/dist/{standard-sql-wRMNi-Yg.mjs.map → standard-sql-BErrm6AV.mjs.map} +1 -1
  199. package/dist/{suppressed-failure-Bdo2aK81.mjs → suppressed-failure-3C4sFXvH.mjs} +1 -1
  200. package/dist/{suppressed-failure-Bdo2aK81.mjs.map → suppressed-failure-3C4sFXvH.mjs.map} +1 -1
  201. package/dist/{to-many-CUBK3CTd.mjs → to-many-DqYv9-vp.mjs} +2 -2
  202. package/dist/{to-many-CUBK3CTd.mjs.map → to-many-DqYv9-vp.mjs.map} +1 -1
  203. package/dist/{transaction-operation-C3Jbblbl.mjs → transaction-operation-Co3hw8yz.mjs} +1 -1
  204. package/dist/{transaction-operation-C3Jbblbl.mjs.map → transaction-operation-Co3hw8yz.mjs.map} +1 -1
  205. package/dist/{types-BNR3u6hH.mjs → types-CJgtjXtu.mjs} +1 -1
  206. package/dist/{types-BNR3u6hH.mjs.map → types-CJgtjXtu.mjs.map} +1 -1
  207. package/dist/{utils-Be91XL14.mjs → utils-DooFtO1V.mjs} +3 -3
  208. package/dist/utils-DooFtO1V.mjs.map +1 -0
  209. package/dist/{v-lthABIXD.mjs → v-yKivkoka.mjs} +2 -2
  210. package/dist/{v-lthABIXD.mjs.map → v-yKivkoka.mjs.map} +1 -1
  211. package/dist/validation-pfpKPPZ_.mjs +2 -0
  212. package/dist/validation-pfpKPPZ_.mjs.map +1 -0
  213. package/dist/{validation-BfJaNYMf.mjs → validation-u-sZDdfD.mjs} +2 -2
  214. package/dist/{validation-BfJaNYMf.mjs.map → validation-u-sZDdfD.mjs.map} +1 -1
  215. package/dist/validation.d.mts +1 -1
  216. package/dist/validation.mjs +1 -1
  217. package/dist/{validator-BJhI364k.mjs → validator-XVm02V0K.mjs} +2 -2
  218. package/dist/{validator-BJhI364k.mjs.map → validator-XVm02V0K.mjs.map} +1 -1
  219. package/dist/version-WvqPqZJ4.mjs +2 -0
  220. package/dist/{version-DAFcmokN.mjs.map → version-WvqPqZJ4.mjs.map} +1 -1
  221. package/dist/write-sinks-CoB5PPw9.mjs +2 -0
  222. package/dist/write-sinks-CoB5PPw9.mjs.map +1 -0
  223. package/dist/writes-CD0mNS5-.mjs +2 -0
  224. package/dist/writes-CD0mNS5-.mjs.map +1 -0
  225. package/package.json +36 -15
  226. package/dist/bind-parameter-capacity-faPOSaLz.mjs +0 -2
  227. package/dist/chain-C1VPkUpC.mjs +0 -2
  228. package/dist/client-C1MxqFtt.mjs.map +0 -1
  229. package/dist/client-DHf2ZfRe.mjs +0 -2
  230. package/dist/client-DHf2ZfRe.mjs.map +0 -1
  231. package/dist/driver-aqfbJdZC.mjs +0 -2
  232. package/dist/error-mapping-Zett_Pnt.mjs +0 -2
  233. package/dist/error-mapping-Zett_Pnt.mjs.map +0 -1
  234. package/dist/every-BUf842ai.mjs +0 -2
  235. package/dist/geo-point-codec-DcUTvoEg.mjs +0 -2
  236. package/dist/mysql-adapter-BrkDrfin.mjs +0 -2
  237. package/dist/mysql-adapter-BrkDrfin.mjs.map +0 -1
  238. package/dist/normalized-result-VunNi4ID.mjs +0 -2
  239. package/dist/pinned-session-D8bM5obl.mjs +0 -2
  240. package/dist/postgres-HaFcFACt.mjs.map +0 -1
  241. package/dist/postgres-adapter-BhNE_3b-.mjs +0 -2
  242. package/dist/postgres-adapter-BhNE_3b-.mjs.map +0 -1
  243. package/dist/postgres-adapter-CnZjhvG1.mjs +0 -2
  244. package/dist/postgres-result-D4_yZqO8.mjs +0 -2
  245. package/dist/result-shape-BuGfArOr.mjs +0 -2
  246. package/dist/rows-BlONp14o.mjs +0 -2
  247. package/dist/select-assembly-BP8c4O-0.mjs.map +0 -1
  248. package/dist/sqlite-adapter-CF-m7LIP.mjs +0 -2
  249. package/dist/sqlite-adapter-CF-m7LIP.mjs.map +0 -1
  250. package/dist/utils-Be91XL14.mjs.map +0 -1
  251. package/dist/validation-DN1N2OdK.mjs.map +0 -1
  252. package/dist/version-DAFcmokN.mjs +0 -2
  253. /package/dist/{contract-Dw0FR78e.d.mts → contract-H_WiAUaR.d.mts} +0 -0
  254. /package/dist/{sql-Q_twK-wW.d.mts → sql-CF5Xi6z-.d.mts} +0 -0
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{m as n,p as r}from"./validation-DN1N2OdK.mjs";import{E as i,g as a}from"./geo-point-codec-DcUTvoEg.mjs";import{o,t as s}from"./sql-BR8ZzKn8.mjs";import{o as ee}from"./native-types-BbKWN3JV.mjs";import{a as te}from"./physical-CAZ_LauY.mjs";import{t as c}from"./geo-area-codec-DQpSEgSD.mjs";import{t as l}from"./adapter-result-parser-B63ouFIz.mjs";import{r as u}from"./adapter-internals-Dagucesf.mjs";import{a as d}from"./datetime-physical-codec-DfVmz14E.mjs";import{t as f}from"./array-literal-BU1R9byi.mjs";import{A as p,C as m,D as h,E as g,N 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,j as O,l as k,m as A,n as j,o as M,p as ne,r as N,s as P,v as F,w as I,x as L,y as R}from"./standard-sql-wRMNi-Yg.mjs";import{r as z}from"./batch-refs-C3MTcVre.mjs";import{t as B}from"./adapter-namespace-DuugUuQa.mjs";import{a as V,c 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-BP8c4O-0.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 o`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresAsciiCaseFold(e){return o`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`}function postgresJsonObject(e){if(e.length===0)return o.raw`'{}'::json`;let t=[],n=o.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let i=e.slice(r,r+50).flatMap(([e,t])=>[o`${e}::text`,t]);t.push(o`${n}(${o.join(i,`, `)})`)}return t.length===1?t[0]:o`(${o.join(t,` || `)})::json`}const re=G(e=>`${e}_pkey`);var CastParameter=class extends s{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends s{};const ie=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=f(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>o`div(${e}, ${t})`,remainder:(e,t)=>o`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){B(this,e,`postgresql`),this.identifiers=T(Q,this.namespace,!0),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:re,select:this.#e.select})}raw=v();identifiers;literals={...g(),dateTime:e=>o`${d(e)}`,true:()=>o.raw`TRUE`,false:()=>o.raw`FALSE`,json:e=>o`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(i(e,t,`text`),a(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):o`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...x(),like:(e,t)=>o`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>o`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>o`${postgresAsciiCaseFold(e)} LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,notIlike:(e,t)=>o`${postgresAsciiCaseFold(e)} NOT LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,containsText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>o`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${p(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>o`${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?o`${e} = ANY(${t})`:o`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?o`${e} <> ALL(${t})`:o`${e} NOT IN ${t}`,...F(),...L(),...E(this.literals.true,this.literals.false),...w()};expressions={...D(),caseSensitiveText:(e,t,r=!1)=>{let i=ee(t,`pg`)?.type;if(!r&&i?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&i&&ae.test(i)?o`CAST(${e} AS TEXT)`:e},asciiCaseFold:postgresAsciiCaseFold,concat:(...e)=>e.length===0?o.raw`''`:e.length===1?e[0]:o`(${o.join(e,` || `)})`,greatest:(...e)=>o`GREATEST(${o.join(e,`, `)})`,least:(...e)=>o`LEAST(${o.join(e,`, `)})`,integerDivide:(e,t)=>o`(${e} / ${t})`,decimalCast:(e,t)=>o`CAST(${e} AS ${o.raw(a(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?o`decode(${e}, 'hex')`:o`CAST(${e} AS ${o.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:N({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>o`encode(${e}, 'hex')`};aggregates={...j(`'Infinity'::float8`),min:(e,t=!1)=>t?o`BOOL_AND(${e})`:o`MIN(${e})`,max:(e,t=!1)=>t?o`BOOL_OR(${e})`:o`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:C(1e3)};json={equals:(e,t)=>o`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?o.raw`'[]'::json`:o`json_build_array(${o.join(e,`, `)})`,emptyArray:()=>o.raw`'[]'::json`,agg:e=>o`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>o`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>o`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>o`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>o`(${e})::jsonb @> ${t}`,lastElement:e=>o`(${e})::jsonb -> -1`,value:e=>o`${Z.from(e)}`};arrays={literal:e=>e.length===0?o.raw`'{}'`:o`ARRAY[${o.join(e,`, `)}]`,value:(e,t)=>o`${t?e.map(e=>typeof e==`string`?d(e):e):e}`,enumValue:e=>o`${f(e)}`,ofRows:e=>o`ARRAY(${e})`,has:(e,t)=>o`${t} = ANY(${e})`,hasEvery:(e,t)=>o`${e} @> ${t}`,hasSome:(e,t)=>o`${e} && ${t}`,isEmpty:e=>o`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>o`CAST(${e} AS TEXT[])`,length:e=>o`cardinality(${e})`,get:(e,t)=>o`${e}[${t}]`,push:(e,t)=>o`array_append(${e}, ${t})`,set:(e,t,n)=>o`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...k(),nullsFirst:(e,t)=>t===`desc`?o`${e} DESC NULLS FIRST`:o`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?o`${e} DESC NULLS LAST`:o`${e} ASC NULLS LAST`};clauses=y();set={...R(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):o`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?H($,e,t,n.decimal):o`${e} = ${e} / ${t}`,push:(e,t)=>o`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>o`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=m();subqueries=h(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?o`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:o`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=P(Q,{inlining:o.raw(`NOT MATERIALIZED`)});mutations={skipDuplicatesStrategy:`sql`,insert:ne(Q),insertDefault:e=>o`INSERT INTO ${e} DEFAULT VALUES`,...b(),returning:e=>o`RETURNING ${e}`,...S()};assertions={exists:e=>o`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>o`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,holds:(e,t)=>o`SELECT CASE WHEN ${e} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS "__viborm_judged__"${t?o` FROM ${t}`:o``}`};joins={...M(),full:(e,t)=>o`FULL OUTER JOIN ${e} ON ${t}`,...A(Q)};setOperations=I(Q,(e,t,n)=>{let r=o.raw(Q(e.alias)),column=e=>o.raw(Q(e)),[i,...a]=t,s=i.map((t,n)=>o`COALESCE(${t}, (${r}."row").${column(e.columns[n])})`);return o`(SELECT NULL::${e.table} AS "row") AS ${r} CROSS JOIN LATERAL (VALUES ${o.join([s,...a].map(O),`, `)}) AS ${o.raw(Q(n))}(${o.join(e.columns.map(column),`, `)})`});capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0,joinsJunctionFilters:`unbounded`};lastInsertId=()=>o.raw`lastval()`;#t=z({table:o.raw`"__viborm_batch_refs"`,batchIdColumn:o.raw`"batch_id"`,keyColumn:o.raw`"ref_key"`,valueColumn:o.raw`"ref_value"`,createTable:o.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=>o`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>o`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 r(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return o`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>o`${e} <-> ${t}`,cosine:(e,t)=>o`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>o`ST_X(${e}::geometry)`,latitude=e=>o`ST_Y(${e}::geometry)`;return{value:(e,t)=>o`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=>o`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>o`ST_Intersects(${o`ST_SetSRID(ST_GeomFromGeoJSON(${V(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=o`RADIANS(ST_X(${e}::geometry))`,r=o`RADIANS(ST_Y(${e}::geometry))`,i=o`RADIANS(ST_X(${t}::geometry))`,a=o`RADIANS(ST_Y(${t}::geometry))`;return o`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${c} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${o`POWER(SIN((${a} - ${r}) / 2), 2) + COS(${r}) * COS(${a}) * POWER(SIN((${i} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>te(e,t,`pg`)?.representation??`text`,parseResult:l,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-BhNE_3b-.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-adapter-BhNE_3b-.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n rowValues,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\nfunction postgresLikeLiteral(value: Sql): Sql {\n return sql`REPLACE(REPLACE(REPLACE(${value}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`;\n}\nfunction postgresAsciiCaseFold(expr: Sql): Sql {\n return sql`TRANSLATE(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace, true);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} NOT LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE (${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)}) ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n asciiCaseFold: postgresAsciiCaseFold,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END) COLLATE \"C\")`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n ofRows: (query: Sql): Sql => sql`ARRAY(${query})`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent, {\n inlining: sql.raw(\"NOT MATERIALIZED\"),\n });\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n setOperations = createSetOperations(quoteIdent, (typed, rows, alias) => {\n const name = sql.raw(quoteIdent(typed.alias));\n const column = (field: string) => sql.raw(quoteIdent(field));\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${column(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${sql.raw(quoteIdent(alias))}(${sql.join(typed.columns.map(column), \", \")})`;\n });\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n joinsJunctionFilters: \"unbounded\",\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.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\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"+gCA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK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"./postgres-adapter-BhNE_3b-.mjs";function installPostgresAdapter(e,a,o){let s=new i(a,o.postgis===!0);s.capabilities.supportsVector=o.pgvector===!0;let c=o.relationsPerStatement;if(c!==void 0&&!(Number.isSafeInteger(c)&&c>0))throw new n(`The "relationsPerStatement" option must be a positive integer (256 for PlanetScale Neki); received ${typeof c==`number`?c:`type "${typeof c}"`}.`);o.sharedRelationBodies!==!1&&(s.capabilities.sharesRelationBodies=!0,s.capabilities.relationsPerStatement=c),o.pgvector||(s.vector=t),r(e,`adapter`,s)}export{installPostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-CnZjhvG1.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t,r as n}from"./normalized-result-VunNi4ID.mjs";import{p as r}from"./validation-DN1N2OdK.mjs";const i=/\s+/,a=/^[A-Za-z]+$/,o=new Set([`COPY`,`DELETE`,`FETCH`,`INSERT`,`MERGE`,`MOVE`,`SELECT`,`UPDATE`]),s=new Set(`ALTER.ANALYZE.BEGIN.CALL.CHECKPOINT.CLOSE.CLUSTER.COMMENT.COMMIT.CREATE.DEALLOCATE.DECLARE.DISCARD.DO.DROP.END.EXPLAIN.GRANT.IMPORT.LISTEN.LOAD.LOCK.NOTIFY.PREPARE.REASSIGN.REFRESH.REINDEX.RELEASE.RESET.REVOKE.ROLLBACK.SAVEPOINT.SECURITY.SET.SHOW.START.TRUNCATE.UNLISTEN.VACUUM`.split(`.`));function malformedPostgresResult(e,t){return new r(`Driver "${e.provider}" returned malformed PostgreSQL result metadata for operation "${e.operation}": ${t}.`,{meta:n(e)})}function normalizePostgresRowCount(e,n,r,c){if(!Array.isArray(r))throw malformedPostgresResult(c,`the rows payload is not an array`);if(typeof n!=`string`||n.trim()===``)throw malformedPostgresResult(c,`the command tag is invalid`);let[l]=n.trim().split(i,1);if(!(l&&a.test(l)))throw malformedPostgresResult(c,`the command tag is invalid`);let u=l.toUpperCase(),d=o.has(u),f=s.has(u);if(!(d||f))throw malformedPostgresResult(c,`the command tag is unknown`);if(e!==null)return t(e,c);if(d)throw malformedPostgresResult(c,`command ${u} requires a numeric row count`);return r.length}export{normalizePostgresRowCount as t};
2
- //# sourceMappingURL=postgres-result-D4_yZqO8.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{C as r,N as i,_ as a,h as o,j as s,r as c,x as l}from"./rows-BlONp14o.mjs";import{f as u,i as d,r as f}from"./chain-C1VPkUpC.mjs";import{a as p,c as m,i as h,s as g}from"./execution-context-_oajgBi4.mjs";import{S as _,t as v}from"./base-wlv81COV.mjs";import{i as y,t as b}from"./observation-BcT8Cs3d.mjs";import{a as x,g as S,r as C}from"./error-mapping-Zett_Pnt.mjs";import{d as w,f as T,p as E,y as D}from"./validation-DN1N2OdK.mjs";import{t as O}from"./transaction-D5LHYn-r.mjs";import{t as k}from"./sql-BR8ZzKn8.mjs";import{p as ee}from"./validator-BJhI364k.mjs";import{o as A,s as j}from"./builder-ClblW6Lj.mjs";import{t as M}from"./types-BNR3u6hH.mjs";import{n as N}from"./transaction-operation-C3Jbblbl.mjs";import{t as P}from"./adapter-result-parser-B63ouFIz.mjs";import{n as F}from"./bind-parameter-capacity-faPOSaLz.mjs";import{t as I}from"./result-parsing-BX3_3Q15.mjs";const L=new WeakMap,R=new WeakMap;function executePreparedQuery(e,t,n,r,i,a,o){return(e===void 0||t===void 0||t.length===0)&&o===void 0?n():!r&&o===void 0&&e!==void 0&&t!==void 0&&t.length>0?runCompiledQueryInterceptors(e,t,n,discardReadWriteOutcomeRegistration,a?.readCommitCertainty,a?.reportAdmissionFailure):executeInterceptedQuery(e,t,n,r,i,a,o)}function discardReadWriteOutcomeRegistration(){}async function executeInterceptedQuery(e,t,n,r,i,a,o){let s=o===void 0?[]:[o];o!==void 0&&i?.stage(o);let captureWriteOutcome=e=>{s.push(e),i?.stage(e)},c=0,l,u=!1,publish=async e=>{if(i){if(s.length===0||u)return;u=!0,i.confirm(s);return}c+=1,l=e,s.length!==0&&await publishWriteOutcomes(s,{certainty:e})},d=Object.freeze({committed:()=>publish(`committed`),mayHaveCommitted:()=>publish(`may-have-committed`)}),executeChild=async()=>{try{let e=await n(d);return r&&(i!==void 0||c===0)&&await publish(`committed`),e}catch(e){throw i&&!u&&i.discard(s),e}};try{return e===void 0||t===void 0||t.length===0?await executeChild():await runCompiledQueryInterceptors(e,t,executeChild,captureWriteOutcome,()=>l??a?.readCommitCertainty?.(),a?.reportAdmissionFailure)}catch(e){throw i&&!u&&i.discard(s),e}}function runCompiledQueryInterceptors(e,t,n,r,i,a){return t===void 0||t.length===0?n():runInterceptorAt(e,t,0,n,r,i,a)}function runInterceptorAt(e,t,n,r,i,a,o){let s=t[n];return s===void 0?r():runOneInterceptor(e,s,()=>runInterceptorAt(e,t,n+1,r,i,a,o),i,a,o)}async function runOneInterceptor(e,n,r,i,a,o){let s=!0,c,l=!1,u=!0,d,recordProtocolFailure=t=>{if(d)return d;let r=interceptorError(n.extension,e,t);return d=r,o?.(r),r},proceed=()=>{if(!s)throw recordProtocolFailure(`called proceed more than once`);if(l)throw recordProtocolFailure(`called proceed after its handler settled`);u=!1,s=!1;let e=startChild(r);return c=settle(e),e},onWriteOutcome=e=>{if(!t(e))throw recordProtocolFailure(`registered a non-function write-outcome listener`);if(!u||l)throw recordProtocolFailure(`registered a write-outcome listener after proceed`);i(Object.freeze({extension:n.extension,listener:e}))},f=exposeHandlerContext(e,proceed,onWriteOutcome,n.controls),p;try{p=Promise.resolve(Reflect.apply(n.handler,void 0,[f]))}catch(e){p=Promise.reject(e)}let m=await settle(p);l=!0,u=!1;let h=m.status===`fulfilled`?m:{...m,failure:d!==void 0&&m.reason===d?d:interceptorFailure(n.extension,e,m.reason,a?.())};if(c!==void 0&&h.status===`rejected`&&h.reason!==d&&o?.(h.failure),c===void 0){if(d)throw d;if(h.status===`rejected`)throw h.failure;if(requiresProceed(e))throw interceptorError(n.extension,e,`completed without proceed`);return h.value}let g=await c;if(g.status===`rejected`){let e=selectExtensionFailures(d,h,g);throw e?retainSuppressedFailures(g.reason,e):g.reason}let _=selectExtensionFailures(d,h,g);return _&&throwExtensionFailures(_),h.value}function selectExtensionFailures(e,t,n){if(e&&n.status===`rejected`&&n.reason===e)return;if(t.status!==`rejected`||e!==void 0&&t.reason===e||n.status===`rejected`&&t.reason===n.reason)return e?[e]:void 0;let r=t.failure;return e?[e,r]:[r]}function exposeHandlerContext(e,t,n,r){return Object.freeze({mode:e.mode,kind:e.kind,model:e.model,operation:e.operation,get input(){return e.input},...e.kind===`model`&&r!==void 0?{controls:a(e.controls,r)}:{},proceed:t,onWriteOutcome:n})}function startChild(e){try{return Promise.resolve(e())}catch(e){return Promise.reject(e)}}async function settle(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function requiresProceed(e){return e.mode===`array`||e.kind!==`model`||!r(e.operation)}function interceptorFailure(e,t,n,r){return _(n)?n:interceptorError(e,t,`failed`,Error(`Query interceptor rejected with a non-Error value`),r)}function interceptorError(e,t,n,r,i){let a=`Extension "${e}" query handler for ${describeOperation(t)} ${n}.`,o={method:`query`,model:t.model,operation:String(t.operation),...i===void 0?{}:{commitCertainty:i}};return r?new E(a,{cause:r,meta:o}):new E(a,{meta:o})}function describeOperation(e){return e.kind===`model`?`${e.model}.${e.operation}`:e.operation}function throwExtensionFailures(e){let t=e[0];throw e.length===1?t:AggregateError(e,`Query interceptor protocol and handler both failed.`,{cause:t})}function retainSuppressedFailures(e,t){let n=AggregateError([e,...t],`Query execution and extension post-work both failed.`,{cause:e});return L.set(n,e),n}function decomposeQueryCoordinationFailure(e){if(!(e instanceof AggregateError)||!L.has(e))return;let t=L.get(e);if(!(e.cause!==t||e.errors[0]!==t))return Object.freeze({child:t,postWork:Object.freeze(e.errors.slice(1))})}var TransactionWriteOutcomes=class{#e=[];stage(e){for(let t of this.#e)if(t.registration===e)return;this.#e.push({registration:e,state:`pending`})}confirm(e){this.#t(e,`confirmed`)}discard(e){this.#t(e,`discarded`)}discardAll(){for(let e of this.#e)e.state=`discarded`}promoteTo(e){for(let t of this.#e)t.state===`confirmed`&&e.#e.push({...t}),t.state=`discarded`}publishCommitted(){return this.publish(`committed`)}async publish(e){let t=[];for(let e of this.#e)e.state===`confirmed`&&t.push(e.registration),e.state=`discarded`;await publishWriteOutcomes(t,{certainty:e})}#t(e,t){for(let n of this.#e)n.state===`pending`&&e.includes(n.registration)&&(n.state=t)}};async function publishWriteOutcomes(e,t){let n;for(let r of e)try{await r.listener(t)}catch(e){let i=_(e)?e:void 0,a=r.failurePolicy===`boundary-owned`&&i!==void 0?i:new E(`Extension "${r.extension}" write-outcome listener failed after ${t.certainty}.`,{cause:i??Error(`Write-outcome listener rejected with a non-Error value`),meta:{method:`onWriteOutcome`,commitCertainty:t.certainty}});(n??=[]).push(a)}if(n===void 0)return;let[r]=n;if(n.length===1)throw r;let i=AggregateError(n,`Multiple extension write-outcome listeners failed.`,{cause:r});throw R.set(i,n),i}function decomposeWriteOutcomePublicationFailure(e){return e instanceof AggregateError?R.get(e)??[e]:[e]}function createOperationExecutionContext(e,t,n){let r=b(n)?.diagnostics?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return h({model:e,operation:t},createCorrelationId,n,r)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let n=g(e);if(n===void 0)return t();let r=b(m(e))?.diagnostics,annotate=t=>{throw t instanceof v?x(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n,diagnostics:r}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}function createPendingOperationInstrumentationFacts(e,t,n,r,i,a,o){return createOperationInstrumentationFacts(e,t,n,r,i,a,o)}function createRawOperationInstrumentationFacts(e,t,n){return createOperationInstrumentationFacts(e,t,void 0,n,n,void 0,!1)}function createOperationInstrumentationFacts(e,t,n,r,a,o,s){let c=b(m(t));if(c?.observesLifecycle===!0)return()=>Object.freeze({kind:`operation`,context:t,identity:u(e),model:n,requestedOperation:r,operation:a,collection:o,complete(e){let n=s?i().readCacheExecutionOutcomes(t):void 0,{failure:r}=e,a=e.status===`failure`&&c.wants(`error-log`)&&isUnloggedError(r)?r:void 0,o=e.status===`failure`&&r instanceof Error&&c.wants(`operation`)?r:void 0;if(!(n===void 0&&a===void 0&&o===void 0))return Object.freeze({kind:`operation`,endedAt:Date.now(),...n===void 0?{}:{readCacheOutcomes:n},...(a??o)===void 0?{}:{failure:a??o},...a===void 0?{skipLog:!0}:{}})}})}async function observeTransactionBatchPhase(e,t,n){let r=b(m(e))?.diagnostics;try{return await n()}catch(n){throw C(n,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:g(e),diagnostics:r,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function isUnloggedError(e){return e instanceof Error&&!S(e)}function captureExecution(e){try{return e()}catch(e){return Promise.reject(e)}}var PendingExecution=class{#e=null;#t=null;#n=!1;#r;#i;constructor(e,t){this.#r=e,this.#i=t}executeDefault(e){if(this.#t!==null&&this.#t!==`default`)throw w.alreadyExecutedWithDriver(this.#r,this.#i);return this.#e||=(this.#t=`default`,captureExecution(e)),this.#e}executeWith(e,t){if(this.#n)throw w.alreadyExecutedWithDriver(this.#r,this.#i);if(this.#t===`default`)throw w.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null&&this.#t!==e)throw w.differentDriverConflict(this.#r,this.#i);return this.#e||=(this.#t=e,captureExecution(t)),this.#e}reserveWith(e){if(this.#t===`default`)throw w.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null)throw this.#t===e?w.alreadyExecutedWithDriver(this.#r,this.#i):w.differentDriverConflict(this.#r,this.#i);this.#t=e,this.#n=!0}executeReserved(e){return this.#e||=captureExecution(e),this.#e}};const z=Object.freeze({accessor:opaqueInspectionValue(`accessor`),function:opaqueInspectionValue(`function`),unsupported:opaqueInspectionValue(`unsupported`)}),B=Object.getOwnPropertyDescriptor(k.prototype,`strings`)?.get,V=Object.getOwnPropertyDescriptor(k.prototype,`values`)?.get;function opaqueInspectionValue(e){let t=Object.create(null);return t.opaque=e,Object.freeze(t)}function snapshotQueryInput(e){return snapshotOwn(e,new Map,!1)}function snapshotOwn(e,t,n){let r=n?[]:Object.create(null);t.set(e,r);let i;try{i=Reflect.ownKeys(e)}catch{return t.set(e,z.unsupported),z.unsupported}for(let a of i){let i;try{i=Object.getOwnPropertyDescriptor(e,a)}catch{return t.set(e,z.unsupported),z.unsupported}if(i!==void 0){if(n&&a===`length`){Object.defineProperty(r,a,i);continue}i.enumerable&&Object.defineProperty(r,a,{configurable:!1,enumerable:!0,value:`value`in i?snapshotValue(i.value,t):z.accessor,writable:!1})}}return Object.freeze(r)}function snapshotValue(e,t){if(typeof e==`function`)return z.function;if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);try{if(Array.isArray(e))return snapshotOwn(e,t,!0);let r=Object.getPrototypeOf(e);if(r===k.prototype&&e instanceof k)return snapshotSql(e,t);if(r===Date.prototype&&e instanceof Date){let n=Object.freeze(new Date(Date.prototype.getTime.call(e)));return t.set(e,n),n}if(e instanceof Uint8Array){let n=new Uint8Array(e);return t.set(e,n),n}if(r===ArrayBuffer.prototype&&e instanceof ArrayBuffer){let n=e.slice(0);return t.set(e,n),n}if(r===Map.prototype&&e instanceof Map){let n=new Map;return t.set(e,n),Map.prototype.forEach.call(e,(e,r)=>{n.set(snapshotValue(r,t),snapshotValue(e,t))}),n}if(r===Set.prototype&&e instanceof Set){let n=new Set;return t.set(e,n),Set.prototype.forEach.call(e,e=>{n.add(snapshotValue(e,t))}),n}if(ArrayBuffer.isView(e)){let n=structuredClone(e);return t.set(e,n),n}if((r===Object.prototype||r===null)&&n(e))return snapshotOwn(e,t,!1)}catch{}return t.set(e,z.unsupported),z.unsupported}function snapshotSql(e,t){if(!(B&&V))throw TypeError(`Sql inspection getters are unavailable`);let n=Reflect.apply(B,e,[]),r=Reflect.apply(V,e,[]),i=Array(n.length);for(let e=0;e<n.length;e+=1){let t=Object.getOwnPropertyDescriptor(n,e);if(!(t&&`value`in t&&typeof t.value==`string`))throw TypeError(`Sql inspection strings are not plain data values`);i[e]=t.value}let a=Array(r.length),o=new k(i,a);t.set(e,o);for(let e=0;e<r.length;e+=1){let n=Object.getOwnPropertyDescriptor(r,e);a[e]=n&&`value`in n?snapshotValue(n.value,t):z.accessor}o.toStatement(`?`),o.toStatement(`$n`),o.toStatement(`:n`);for(let e of Reflect.ownKeys(o)){let t=Reflect.get(o,e);typeof t==`object`&&t&&Object.freeze(t)}return Object.freeze(o),o}function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}const H=Symbol(`run alone`),U={string:e=>typeof e==`string`,int:e=>typeof e==`number`&&Number.isSafeInteger(e),bigint:e=>typeof e==`bigint`};let W;const G=new WeakSet;function enableFindUniqueBatching(e){G.add(e)}const K=(()=>{let e=globalThis.process,t=e?.nextTick;return typeof t==`function`?n=>t.call(e,n):queueMicrotask})();function batchFindUnique(e){if(!engineBatches(e.engine)||e.engine.driver.holdsConnectionScope())return;let t;try{t=e.routed.preparedArgs}catch{return}let n=keyOf(e.model,t.where);if(n===void 0)return;let{where:r,...i}=e.args,a=signatureOf(i);if(a===void 0)return;let o,s=new Promise(e=>{o=e}),c,l=new Promise(e=>{c=e}),u={values:n.values,signature:signatureOf(n.values),orThrow:e.requested!==`findUnique`,decide:o};return(enqueue(e,`${n.selector}\u0000${a}`,n,u,c)?l.then(e=>(runBatch(e),s)):s).then(t=>t===H?e.run():t.value)}function engineBatches(e){let{driver:t}=e;return G.has(e.route)&&t===e.route.driver&&(e.extensionChain?.statement.length??0)===0&&t.result?.parseResult===void 0&&t.adapter.result.parseResult===P}function keyOf(e,t){if(!n(t))return;let r=Object.keys(t);if(r.length!==1)return;let i=r[0],a=ee(e,i);if(a===void 0)return;let o=t[i],s;if(a.name===void 0)s=[o];else{if(!n(o)||Object.keys(o).length!==a.fields.length)return;s=a.fields.map(e=>o[e])}let{scalars:c,omit:l}=e[`~`].state,u=!1;for(let[e,t]of a.fields.entries()){let n=c[t]?.[`~`].state;if(!(n&&!n.array&&U[n.type])?.(s[e])||l?.[t]===!0)return;n.type===`string`&&(u=!0)}return{selector:i,fields:a.fields,values:s,textKey:u}}function enqueue(e,t,n,r,i){W===void 0&&(W=new Map,K(flush));let a=W.get(e.engine);a===void 0&&W.set(e.engine,a=new Map);let o=`${e.model[`~`].names.ts}\u0000${t}`,s=a.get(o);s===void 0&&a.set(o,s=[]);let c=s.find(t=>sameControls(t.leader.controls,e.controls)),l=!1;if(c===void 0){let t={leader:e,start:()=>i(t),fields:n.fields,textKey:n.textKey,members:[]};c=t,s.push(c),l=!0}return c.members.push(r),l}function sameControls(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}function flush(){let e=W;W=void 0;for(let t of e.values())for(let e of t.values())for(let t of e)t.start()}function runBatch(e){let{members:t}=e,runAlone=e=>{for(let t of e)t.decide(H)};if(t.length===1){runAlone(t);return}try{let n=new Map;for(let e of t){let t=n.get(e.signature);t?t.push(e):n.set(e.signature,[e])}let r=planBatch(e,[...n.values()]),{engine:i}=e.leader,a=p(e.leader.context);for(let t of r.chunks){let o=t.signatures.flatMap(e=>n.get(e));t.read.execute({committedWriteSegment:void 0,context:a,driverOverride:void 0,engineDriver:i.driver,isWrite:!1,writeMayBeVisible:void 0}).then(i=>{try{dispatch(e,t,n,r.injected,i)}catch{runAlone(o)}},()=>runAlone(o))}}catch{runAlone(t)}}function planBatch(e,t){let{leader:n,fields:r}=e,i=projectionWithKey(n,r),a=n.rows(),o=new Map,read=(e,s)=>{let c=`${e}:${s}`,l=o.get(c);if(l===void 0){let u=t.slice(e,s).map(e=>e[0].values);l=n.engine.route.operation(n.model,`findMany`,{...i.args,where:mergedWhere(r,u)},a),o.set(c,l)}return l},s=t.map(e=>e[0].signature),c=F(n.engine.driver.maxBindParametersPerStatement);return{chunks:(c===void 0?[{start:0,end:t.length}]:compileBindBudgetChunks(t.length,c,(e,t)=>read(e,t).buildStatement())).map(({start:e,end:t})=>({signatures:s.slice(e,t),read:read(e,t)})),injected:i.injected}}function mergedWhere(e,t){return e.length===1?{[e[0]]:{in:t.map(e=>e[0])}}:{OR:t.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]])))}}function projectionWithKey(e,t){let{where:r,...i}=e.args,a=e.routed.preparedArgs.select,o=[];if(!n(a))return{args:i,injected:o};for(let e of t)a[e]!==!0&&(n(i.select)&&(i.select={...i.select,[e]:!0}),n(i.omit)&&(i.omit={...i.omit,[e]:!1}),o.push(e));return{args:i,injected:o}}function dispatch(e,t,n,r,i){let a=new Map;for(let t of i){let n=signatureOf(e.fields.map(e=>t[e]));for(let e of r)delete t[e];a.has(n)||a.set(n,t)}for(let r of t.signatures){let t=a.get(r);for(let[i,a]of n.get(r).entries())t===void 0?a.orThrow||e.textKey?a.decide(H):a.decide({value:null}):a.decide({value:i===0?t:copyResult(t)})}}function signatureOf(e){switch(typeof e){case`undefined`:return`u`;case`boolean`:case`number`:return String(e);case`string`:return JSON.stringify(e);case`bigint`:return`${e}n`;case`object`:break;default:return}if(e===null)return`null`;if(Array.isArray(e)){let t=[];for(let n of e){let e=signatureOf(n);if(e===void 0)return;t.push(e)}return`[${t.join(`,`)}]`}if(e instanceof Date)return`D${e.getTime()}`;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n=[];for(let[t,r]of Object.entries(e)){let e=signatureOf(r);if(e===void 0)return;n.push(`${JSON.stringify(t)}:${e}`)}return`{${n.join(`,`)}}`}function copyResult(e,t=new Map){if(typeof e!=`object`||!e)return e;let n=t.get(e);if(n!==void 0)return n;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Uint8Array)return Uint8Array.prototype.slice.call(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(copyResult(r,t));return n}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=Object.create(r);t.set(e,i);for(let[n,r]of Object.entries(e))Object.defineProperty(i,n,{value:copyResult(r,t),enumerable:!0,writable:!0,configurable:!0});return i}const q=Symbol.for(`viborm.pendingOperation`);let attachPendingCacheExecutionFriend,readPendingCacheResultFriend;function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,r;try{await e()}catch(e){n=!0,r=e}try{await t()}catch(e){throw n?D(r,e,`Write publication callbacks both failed.`):e}if(n)throw r}}const J=Object.freeze({});let createPendingOperationFriend,Y;var te=class PendingOperation{[Symbol.toStringTag]=`Promise`;[q]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=!1;#p;#m;#h;#g;#_;#v=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(J,e,t,n,r,i,void 0,void 0,a===void 0?void 0:{prepare:a,status:`pending`},void 0,o),attachPendingCacheExecutionFriend=(e,t)=>e.#L(t),readPendingCacheResultFriend=e=>({get args(){return e.cacheKeyArgs()},get controls(){return e.#y(),e.#l?.controls},get codec(){return e.#E()},executionContext:e.#e.attribution}),Y=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,requiresInterception:e=>{let t=String(e.#o.originalOperation),n=d(e.#t.extensionChain,`request`,e.#i,t),r=n!==void 0&&n.length>0&&(e.#t.extensionChain?.observe.length??0)>0,i=d(e.#t.extensionChain,`query`,e.#i,t);return r||i!==void 0&&i.length>0||e.#u!==void 0},prepareAdmission:(e,t=`input`)=>{e.#w(),t===`plan`&&e.#C()},stagePackageWriteOutcomes:(e,t)=>{let n=e.#b();n!==void 0&&t.stage(n)},startInterception:(e,t,n,i)=>{let a=String(e.#o.originalOperation),o=d(e.#t.extensionChain,`query`,e.#i,a),s=e.#w(),c=e.#b();return(o===void 0||o.length===0)&&c===void 0?t():executePreparedQuery(o===void 0||o.length===0?void 0:e.#T(`array`,s),o,t,!r(a),n,i,c)},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#P(t,n?.committed,n?.mayHaveCommitted)),isWrite:e=>!r(String(e.#o.originalOperation)),hasObservation:e=>(e.#t.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#t.extensionChain?.observe;return r===void 0||r.length===0?t():y(r,String(e.#o.originalOperation),e.#i,t,n,e.#k())},reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observe;return n===void 0||n.length===0?e.#s.executeWith(t,()=>e.#P(t)):e.#s.executeWith(t,()=>y(n,String(e.#o.originalOperation),e.#i,()=>e.#P(t),()=>e.#m===void 0?void 0:{commitCertainty:e.#m},e.#k()))},finishResult:(e,t)=>e.#o.finishResult?e.#o.finishResult(t):t,prepare:e=>e.#C()?.queries[0],prepareBatch:e=>e.#x().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let n=e.#C();if(!n)throw new T(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return n.parseResult([t])},observeBatchPhase:(e,t,n)=>observeTransactionBatchPhase(e.#e.attribution,t,n)}),N(PendingOperation.prototype,e=>#e in e,Y),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,i,a,o,s,c,l,u){if(e!==J)throw new O;this.#t=t,this.#n=n,this.#r=i,this.#c=s,this.#l=c,this.#u=u,this.#p=l,this.#h=t.route;let d=r.endsWith(`OrThrow`);this.#a=d?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new PendingExecution(this.#i,this.#a),this.#o=Object.freeze({...a,throwIfNotFound:d||a?.throwIfNotFound,originalOperation:a?.originalOperation??r}),this.#e=o??createPendingOperationContext(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),Object.freeze(this)}#y(){let e=this.#l;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=f(this.#t.extensionChain,this.#i,String(this.#o.originalOperation)),n=t.length===0?void 0:o(this.#i,this.#a,this.#r,t,this.#t.bound),r=e.prepare(n?.args??this.#r,n?.controls);return e.args=r,e.controls=n?.controls,e.status=`success`,r}catch(t){throw e.error=t,e.status=`failure`,t}}#b(){return this.#f?this.#d:(this.#d=this.#u?.(this.#e.attribution,this.#l?.controls),this.#f=!0,this.#d)}#x(){let e=this.#p?.routed;if(e)return e;if(this.#g)return this.#g;if(!l.has(this.#a))throw new T(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...l].sort().join(`, `)}.`);let t=this.#y(),n=this.#h.operation(this.#n,String(this.#o.originalOperation),t,this.#S());return this.#g=n,this.#p&&(this.#p.routed=n),n}#S(){let e=this.#t.extensionChain?.callRows;return e&&c(e,this.#i,this.#l?.controls)}#C(){if(this.#v)return this.#_;let e=this.#x().prepareSingle(this.#e.attribution);return this.#_=e?.queries.length===1?e:void 0,this.#v=!0,this.#_}#w(){return this.#x().preparedArgs}#T(e,t){let n=this.#l?.controls,r;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),get input(){return r??=snapshotQueryInput(t),r},...n===void 0?{}:{controls:n}})}#E(){return this.#x().cacheResultCodec()}#D(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observe;return e===void 0||e.length===0?this.#O(this.#A()):y(e,String(this.#o.originalOperation),this.#i,()=>this.#O(this.#A()),()=>this.#m===void 0?void 0:{commitCertainty:this.#m},this.#k())})}#O(e){let t=this.#o.finishResult;return t?e.then(e=>t(e)):e}#k(){return createPendingOperationInstrumentationFacts(this.#t.driver,this.#e.attribution,this.#i,String(this.#o.originalOperation),String(this.#a),this.#n[`~`].names.sql??this.#i,s(this.#o))}#A(e,t,n){return withOperationErrorContext(this.#e.attribution,()=>this.#j(e,t,n))}#j(e,t,n){let r=this.#N(`committed`),i=this.#N(`may-have-committed`),a=String(this.#o.originalOperation),o=d(this.#t.extensionChain,`query`,this.#i,a);return(o===void 0||o.length===0)&&this.#u===void 0?this.#P(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#M(o,a,r,i,e,t,n)}#M(e,t,n,i,a,o,s){let c;try{c=this.#w()}catch(e){return Promise.reject(e)}let l=this.#b();return(e===void 0||e.length===0)&&l===void 0?this.#P(a,combineWriteNotifications(o,n),combineWriteNotifications(s,i)):executePreparedQuery(e===void 0||e.length===0?void 0:this.#T(this.#t.transactionWriteOutcomes?`transaction`:`direct`,c),e,e=>this.#P(a,combineWriteNotifications(o,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(s,combineWriteNotifications(e?.mayHaveCommitted,i))),!r(t),this.#t.transactionWriteOutcomes,void 0,l)}#N(e){if(!(this.#t.transactionWriteOutcomes!==void 0||(this.#t.extensionChain?.observe.length??0)===0))return async()=>{(e===`committed`||this.#m===void 0)&&(this.#m=e)}}#P(e,t,n){return this.#c?this.#c(e,t,n):this.#F(e,t,n)}#F(e,t,n){let i;try{i=this.#x()}catch(e){return Promise.reject(e)}let run=()=>i.execute({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!r(String(this.#o.originalOperation)),writeMayBeVisible:n});if(this.#a===`findUnique`&&e===void 0){let e=batchFindUnique({engine:this.#t,model:this.#n,requested:String(this.#o.originalOperation),args:this.#y(),controls:this.#l?.controls,rows:()=>this.#S(),routed:i,context:this.#e.attribution,run});if(e!==void 0)return e}return run()}getArgs(){return this.#r}cacheKeyArgs(){let e=this.#I();if(!e)throw new T(`Operation '${this.#a}' on model '${this.#i}' exposes no validated payload to key a cache entry on.`);return e}#I(){if(r(this.#a))return this.#x().preparedArgs}buildStatement(){return this.#x().buildStatement()}#L(e){let t=this.#p??={routed:this.#g},deferredExecution=(t,n,r)=>e((e,i,a)=>this.#P(e??t,combineWriteNotifications(i,n),combineWriteNotifications(a,r)),t);return new PendingOperation(J,this.#t,this.#n,this.#a,this.#r,this.#o,this.#e,deferredExecution,this.#l,t,this.#u)}then(e,t){return this.#D().then(e,t)}catch(e){return this.#D().catch(e)}finally(e){return this.#D().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function attachPendingCacheExecution(e,t){return attachPendingCacheExecutionFriend(e,t)}function readPendingCacheResult(e){return readPendingCacheResultFriend(e)}function isPendingOperation(e){return typeof e==`object`&&!!e&&q in e&&e[q]===!0}const X=`0viborm_distance`,Z=`0viborm_relation_counts`,Q=`0viborm_empty_row`,gateResultKey=e=>`0viborm_gate:${e}`,ne=`0viborm_cursor_`,re=`0viborm_orphans`;function getAggregateResultKey(e){return`0viborm_aggregate:${e.slice(1)}`}function getAggregateResultName(e){switch(e){case`0viborm_aggregate:count`:return`_count`;case`0viborm_aggregate:avg`:return`_avg`;case`0viborm_aggregate:sum`:return`_sum`;case`0viborm_aggregate:min`:return`_min`;case`0viborm_aggregate:max`:return`_max`;default:return}}function getGroupByFields(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[];if(new Set(t).size!==t.length)throw new T(`GroupBy operation does not allow duplicate fields in 'by'`);return t}const ie=new Set([`findFirst`,`findMany`,`findUnique`,`create`,`createManyAndReturn`,`update`,`updateManyAndReturn`,`delete`,`deleteManyAndReturn`,`upsert`]),$=`Distance select supports only one _distance field per select.`;function selectedArm(e,t,r){let i=n(e)?e:void 0;if(!t)return getOwnValue(i,r)??!0;let a=getOwnValue(i,`only`);if(Array.isArray(a)&&!a.includes(r))return;let o=getOwnValue(i,`variants`);return(n(o)?getOwnValue(o,r):void 0)??!0}const ae=[`_count`,`_avg`,`_sum`,`_min`,`_max`];function getOwnValue(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function createShape(e,t=new Map,n=new Map,r=new Set,i=new Map,a){if(new Set(e).size!==e.length)throw new T(`The requested result shape contains colliding output columns.`);return{carrier:`rows`,rawKeys:e,...a?{distanceScalar:a}:{},relations:t,polymorphic:i,aggregates:n,relationCounts:r}}function selectedEntries(e){return n(e)?Object.entries(e).filter(([,e])=>e!==!1&&e!==void 0):[]}function getNestedSelection(e){if(!n(e))return{};let t={},r=getOwnValue(e,`select`),i=getOwnValue(e,`include`);return n(r)&&(t.select=r),n(i)&&(t.include=i),t}function buildModelShape(e,t,r){let i=[],a=new Map,o=new Map,s=e[`~`].state.scalars,c=e[`~`].state.relations,l=getOwnValue(t,`select`),u=getOwnValue(t,`include`),d=n(l)?l:void 0,f=n(u)?u:void 0,p=!1,m;if(d)for(let[e,t]of Object.entries(d)){let r=getOwnValue(s,e);if(r){if(t===!0){i.push(e);continue}if(n(t)&&Object.hasOwn(t,`_distance`)){if(p)throw new T($);p=!0,m=r,i.push(X)}}}else for(let t of j(e))i.push(t);addSelectedRelations(e,c,d,i,a,r),addSelectedPolymorphicRelations(e,d,i,o,r),addSelectedRelations(e,c,f,i,a,r),addSelectedPolymorphicRelations(e,f,i,o,r);let h=[getOwnValue(d,`_count`),getOwnValue(f,`_count`)],g=new Set;for(let e of h){if(!n(e))continue;let t=getOwnValue(e,`select`);if(n(t))for(let[e]of selectedEntries(t)){let t=getOwnValue(c,e);if(!t)continue;let n=t[`~`].state;M(n)&&n.cardinality!==`many`||g.add(e)}}return g.size>0&&i.push(Z),i.length===0&&i.push(Q),createShape(i,a,new Map,g,o,m)}function admittedRecurrence(e){if(n(e))return getOwnValue(e,`recurse`)}function addSelectedRelations(e,t,n,r,i,a){for(let[o,s]of selectedEntries(n)){let n=getOwnValue(t,o);if(!n||M(n[`~`].state))continue;let c=n[`~`].settleTarget();r.push(o);let l=buildModelShape(c,getNestedSelection(s),a),u=a.get(e)?.get(o),d=admittedRecurrence(s);i.set(o,{model:c,shape:l,cardinality:n[`~`].state.cardinality,optional:u!==void 0&&A(u),...d?{recurrence:d}:{}})}}function addSelectedPolymorphicRelations(e,t,n,r,i){let a=e[`~`].state.relations;for(let[o,s]of selectedEntries(t)){let t=getOwnValue(a,o);if(!t)continue;let c=t[`~`].state;if(!M(c))continue;let l=c.cardinality===`many`,u=new Map;for(let e of Object.keys(c.target.entries)){let n=selectedArm(s,l,e);if(n===void 0)continue;let r=t[`~`].settleTarget(e);u.set(e,{model:r,shape:buildModelShape(r,getNestedSelection(n),i)})}n.push(o);let d=i.get(e)?.get(o);r.set(o,{cardinality:c.cardinality,optional:d!==void 0&&A(d),variants:u})}}function buildAggregateShape(e,t=[]){let n=[...t],r=new Set(t),i=new Map;for(let t of ae){let a=getOwnValue(e,t);if(a===void 0||a===!1)continue;let o;if(!(t===`_count`&&a===!0)){let e=selectedEntries(a);if(e.length===0)continue;o=new Set(e.map(([e])=>e))}if(r.has(t))throw new T(`GroupBy cannot return both grouped scalar '${t}' and aggregate '${t}' in one result.`);let s=getAggregateResultKey(t);n.push(s),r.add(t),i.set(s,{...o?{fields:o}:{}})}return createShape(n,new Map,i)}function buildCountShape(e){let t=selectedEntries(getOwnValue(e,`select`)).map(([e])=>e);return{...createShape(t.length===0?[I]:t),carrier:`count`}}function buildExpectedResultShape(e,t,n,r){if(t===`count`)return buildCountShape(n);if(t===`exist`)return{...createShape([I]),carrier:`existence`};if(t===`aggregate`)return buildAggregateShape(n);if(t===`groupBy`)return buildAggregateShape(n,getGroupByFields(getOwnValue(n,`by`)));if(ie.has(t))return buildModelShape(e,n,r)}export{withOperationErrorContext as C,executePreparedQuery as D,decomposeWriteOutcomePublicationFailure as E,observeTransactionBatchPhase as S,decomposeQueryCoordinationFailure as T,compileBindBudgetChunks as _,X as a,createOperationExecutionContext as b,Z as c,te as d,attachPendingCacheExecution as f,enableFindUniqueBatching as g,readPendingCacheResult as h,ne as i,gateResultKey as l,isPendingOperation as m,buildExpectedResultShape as n,Q as o,createPendingOperation as p,selectedArm as r,re as s,$ as t,getAggregateResultName as u,snapshotQueryInput as v,TransactionWriteOutcomes as w,createRawOperationInstrumentationFacts as x,PendingExecution as y};
2
- //# sourceMappingURL=result-shape-BuGfArOr.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,t as i}from"./base-wlv81COV.mjs";import{p as a,r as o,t as s}from"./validation-DN1N2OdK.mjs";import{_ as c,a as l}from"./v-lthABIXD.mjs";import{B as u,rt as d}from"./geo-point-codec-DcUTvoEg.mjs";import{a as f}from"./key-DJXcPZR_.mjs";import{n as p}from"./builder-ClblW6Lj.mjs";const m=`viborm.cache`,h=Object.freeze({cache:Object.freeze({schema:Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>Object.freeze({value:officialCacheRuntime().admitMutationCacheOptions(e)})})}),on:`writes`})}),g=new WeakMap,_=new WeakMap,v=new WeakMap;let y;function registerOfficialCacheQuery(e,t,n){y=n,g.set(e,t)}function installOfficialCacheRuntime(e){y=e}function officialCacheRuntime(){if(y===void 0)throw Error(`The official cache runtime is not loaded: import cache() from viborm/cache.`);return y}function getOfficialCacheQueryCapability(e){return t(e)?g.get(e):void 0}function getOfficialCacheChainDefinition(e){return e===void 0?void 0:_.get(e)}function getOfficialCacheChainCapability(e){return e===void 0?void 0:v.get(e)}function registerOfficialCacheChain(e,t){_.set(e,t)}function setOfficialCacheChainCapability(e,t){v.set(e,t)}function bindOfficialCacheChain(e,t){_.get(e)!==void 0&&officialCacheRuntime().bindChain(e,t)}function isCacheManagedExecution(e){return e?.skipSpan===!0}const b=new Set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function isReadOperation(e){return b.has(e)}const x=new Set([...b,`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`]);function isWriteOperation(e){return x.has(e)&&!isReadOperation(e)}function baseOperation(e){return e===`findUniqueOrThrow`?`findUnique`:e===`findFirstOrThrow`?`findFirst`:e}const S={reads:new Set([...x].filter(isReadOperation)),writes:new Set([...x].filter(isWriteOperation)),all:x},C=new Set([...x].filter(e=>e!==`create`&&e!==`createMany`)),w=new Set([`delete`,`deleteMany`]);function placeControls(e){let t=[],{name:n,controls:r,rows:i,deletion:a,data:o}=e,s=a?.removeWhen??{},c=new Set(Object.keys(a?.models??{})),l=new Set([...c,...Object.keys(i?.models??{}),...Object.keys(i?.verbs??{}),...Object.keys(o?.models??{})]),u=l.size===0?!0:l;for(let[e,i]of Object.entries(r??{})){let r=Object.hasOwn(s,e);t.push({name:e,extension:n,declaration:i,operations:r?w:placementOf(i.on),models:r?c:void 0,required:i.required===!0?u:void 0,...i.bound===!0&&{bound:!0},...i.uncacheable===!0&&{uncacheable:!0}})}return i!==void 0&&t.push({name:i.control,extension:n,declaration:Object.freeze({oneOf:Object.freeze(rowsModes(i))}),operations:C,fallback:i.default}),t}function placementOf(e){return e===void 0?x:typeof e==`string`?S[e]:new Set(e)}function rowsModes(e){let[t]=Object.values(e.models);return t===void 0?[e.default]:Object.keys(t)}const T=new WeakSet;function snapshotControlValue(e){if(typeof e!=`object`||!e||!f(e))return e;let t;try{t=captureOf(e,new WeakSet)}catch{return e}if(t===`opaque`)return e;if(t===`fixed`)return T.add(e),e;let n;try{n=structuredClone(e)}catch{return e}return freezeCopy(n)&&T.add(n),n}function captureOf(e,t){if(ArrayBuffer.isView(e))return`opaque`;if(t.has(e))return`fixed`;t.add(e);let n=e instanceof Date||!Object.isFrozen(e)?`copy`:`fixed`,r=Array.isArray(e);for(let i of Reflect.ownKeys(e)){if(r&&i===`length`)continue;let a=Object.getOwnPropertyDescriptor(e,i);if(typeof i==`symbol`||!a.enumerable||!(`value`in a))return`opaque`;let o=a.value;if(typeof o!=`object`||!o)continue;let s=captureOf(o,t);if(s===`opaque`)return`opaque`;s===`copy`&&(n=`copy`)}return n}function freezeCopy(e){if(e instanceof Date)return!1;let t=!0;for(let n of Object.values(e))typeof n==`object`&&n&&!freezeCopy(n)&&(t=!1);return Object.freeze(e),t}function isStableControlValue(e){return typeof e!=`object`||!e||T.has(e)}function admitControls(e,t,n,r,i){if(typeof n!=`object`||!n)return{args:n,controls:void 0};let a;try{a=Reflect.ownKeys(n)}catch(n){throw controlFailure(`The arguments of ${e}.${t} could not be inspected for controls`,e,t,n)}let o=[],s;for(let c of r){let{name:r,required:l}=c,u;c.bound!==!0&&a.includes(r)&&((s??=new Set).add(r),u=readControl(n,c,e,t));let d=u===void 0?i?.[r]??c.fallback:snapshotControlValue(admitControl(c,u,e,t));if(d!==void 0)o.push([r,d]);else if(l===!0||l?.has(e))throw invalidControl(c,e,t,[`is required`])}return{args:s===void 0?n:withoutControls(n,a,s,e,t),controls:o.length===0?void 0:Object.freeze(Object.fromEntries(o))}}function bindControls(e,t,n,r){let i={...r};for(let[r,a]of Object.entries(n)){let n=e.find(e=>e.name===r&&e.extension===t);if(n===void 0)throw new o(`Extension "${t}" binds control "${r}", which it does not declare.`,{meta:{extension:t}});i[r]=snapshotControlValue(admitControl(n,a))}return Object.freeze(i)}function controlsOwnedBy(e,t){let n=[];for(let r of t)e!==void 0&&Object.hasOwn(e,r)&&n.push([r,e[r]]);return Object.freeze(Object.fromEntries(n))}function readControl(e,t,n,r){try{return Reflect.get(e,t.name)}catch(e){throw controlFailure(`Extension "${t.extension}" control "${t.name}" of ${n}.${r} could not be read`,n,r,e)}}function withoutControls(e,t,n,r,i){let a={};try{for(let r of t){if(n.has(r))continue;let t=Object.getOwnPropertyDescriptor(e,r);t&&Object.defineProperty(a,r,t)}}catch(e){throw controlFailure(`The arguments of ${r}.${i} could not be inspected for controls`,r,i,e)}return a}function admitControl(e,r,i,a){let{declaration:o}=e;if(`oneOf`in o){if(o.oneOf.some(e=>e===r))return r;throw invalidControl(e,i,a,[`must be one of ${o.oneOf.map(e=>JSON.stringify(e)).join(`, `)}`])}let s;try{s=o.schema[`~standard`].validate(r)}catch(t){throw isVibORMFailure(t)?t:validatorFailure(e,i,a,`threw`,t)}let c=`malformed`,l=[],u;try{if(n(s)){let e=`then`in s?s.then:void 0;if(t(e))c=`promise`,Reflect.apply(e,s,[void 0,()=>void 0]);else{let e=s.issues;e===void 0?`value`in s&&(c=`value`,u=s.value):Array.isArray(e)&&(c=`issues`,l=e)}}}catch(t){throw validatorFailure(e,i,a,`returned an unreadable result`,t)}switch(c){case`value`:return u;case`issues`:throw invalidControl(e,i,a,issueMessages(l));case`promise`:throw validatorFailure(e,i,a,`returned a promise`,TypeError(`Control validators must return synchronously`));default:throw validatorFailure(e,i,a,`returned a malformed result`,TypeError(`A Standard Schema result has a value or an issue list`))}}function issueMessages(e){let t=[];try{for(let r of e){let e=n(r)?r.message:void 0;t.push(typeof e==`string`?e:`is invalid`)}}catch{return[`is invalid`]}return t.length===0?[`is invalid`]:t}function isVibORMFailure(e){try{return e instanceof i}catch{return!1}}function uncacheableRead(e,t,n,r){let i=e.find(e=>e.uncacheable===!0&&t?.[e.name]!==void 0);return i&&invalidControl(i,n,r,[`is not cacheable: a read that holds it is not served from the cache`])}function invalidControl(e,t,n,r){return new s(n===void 0?{kind:`schema-builder`,builder:`$bind`,path:e.name}:{kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Control "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,n,r,i){return controlFailure(`Extension "${e.extension}" control "${e.name}" validator for ${n===void 0?`$bind`:`${t}.${n}`} ${r}`,t,n,i)}function controlFailure(e,t,n,i){return new a(`${e}.`,{cause:r(i),meta:{model:t,operation:n}})}const parseStamped=(e,t)=>u((t,n)=>e.get(t)?.create?.[n]!==void 0,t);var Parameter=class{control;path;now;#e;constructor(e,t){e===void 0?this.now=!0:this.control=e,t!==void 0&&(this.path=t),this.#e=t===void 0?[]:t.split(`.`),Object.freeze(this)}read(e,t){if(this.control===void 0)return t();let n=e?.controls[this.control];for(let e of this.#e){if(typeof n!=`object`||!n)return;n=Object.hasOwn(n,e)?n[e]:void 0}return n??void 0}},Condition=class{parameter;test;constructor(e,t){this.parameter=e,this.test=t,Object.freeze(this)}holds(e,t){let n=this.parameter.read(e,t),r=this.test;return`exists`in r?n!==void 0===r.exists:n===void 0?!1:`equals`in r?Object.is(n,r.equals):`in`in r?r.in.includes(n):Array.isArray(n)?`has`in r?n.includes(r.has):r.hasSome.some(e=>n.includes(e)):!1}},OuterColumn=class{$row;up;constructor(e,t){this.$row=e,this.up=t,Object.freeze(this)}},Existence=class{$exists;#e;#t;constructor(e,t){this.#e=e,this.#t=t,this.$exists=Object.freeze({[e]:t}),Object.freeze(this)}get model(){return this.#e}get where(){return this.#t}};const E=new WeakMap;function standaloneRegistry(e){let t=E.get(e);return t===void 0&&(t=p(e),E.set(e,t)),t}const D=new WeakMap,O=new WeakMap,k=new WeakSet,A=new WeakSet,j=new WeakSet,isResolver=e=>j.has(e),resolver=e=>(j.add(e),e);function isImmutableRowData(e,t=new Set,n){if(typeof e==`function`)return n?.(e)===!0;if(typeof e!=`object`||!e)return typeof e!=`symbol`;let r=n?A:k;if(r.has(e)||k.has(e))return!0;if(!Object.isFrozen(e)||t.has(e))return!1;let i=Object.getPrototypeOf(e);if(Array.isArray(e)?i!==Array.prototype||!Array.from({length:e.length},(t,n)=>Object.hasOwn(e,n)).every(Boolean):i!==Object.prototype&&i!==null&&i!==Parameter.prototype&&i!==Condition.prototype&&i!==Existence.prototype&&i!==OuterColumn.prototype)return!1;t.add(e);let a=Reflect.ownKeys(e).every(r=>{let i=Object.getOwnPropertyDescriptor(e,r);return typeof r==`string`&&i&&`value`in i&&isImmutableRowData(i.value,t,n)});return t.delete(e),a&&r.add(e),a}const isAdmittedRows=e=>isImmutableRowData(e,new Set,isResolver),frozenRecord=(e,t)=>c(e)&&Object.isFrozen(e)&&Reflect.ownKeys(e).every(n=>{let r=Object.getOwnPropertyDescriptor(e,n);return typeof n==`string`&&r!==void 0&&`value`in r&&t(n,r.value)}),isImmutableEntry=e=>frozenRecord(e,(e,t)=>e===`acyclic`&&typeof t==`function`||isImmutableRowData(t)),isImmutableRows=e=>frozenRecord(e,(e,t)=>e===`verbs`?frozenRecord(t,(e,t)=>typeof t==`function`||isImmutableEntry(t)):isImmutableRowData(t));function freezeAdmitted(e,t=new Set){if(!(typeof e!=`object`||!e||t.has(e))){t.add(e);for(let n of Object.values(e))freezeAdmitted(n,t);Object.freeze(e)}}const M={predicates:!0,read:!0,update:!0,delete:!0,writes:!0,place:!0,moves:!0,acyclic:!0,evidence:!0,reads:!0},N=/^\$[a-zA-Z_][a-zA-Z0-9_]*$/;function keyFields(e){return new Set([...Object.entries(e.scalars).filter(([,e])=>e[`~`].state.isId===!0).map(([e])=>e),...Object.keys(e.uniques),...[...Object.values(e.compoundId??{}),...Object.values(e.compoundUniques??{})].flatMap(({entries:e})=>Object.keys(e)),...Object.values(e.relations).flatMap(e=>e[`~`].state.foreignKey?.fields??[])])}const P=[`exists`,`equals`,`in`,`has`,`hasSome`];function isReference(e){return c(e)&&typeof e.control==`string`&&Object.keys(e).every(e=>e===`control`||e===`path`)&&(e.path===void 0||typeof e.path==`string`)}const isOuterColumn=e=>c(e)&&Object.keys(e).length===2&&typeof e.$row==`string`&&Number.isSafeInteger(e.up)&&e.up>=0,isInstant=e=>c(e)&&e.now===!0&&Object.keys(e).length===1,F=`a condition names one control and exactly one of ${P.join(`, `)}`;function conditionOf(e){if(!c(e))return F;let{control:t,path:n,...r}=e,[i,...a]=Object.keys(r),o=r[i];return typeof t!=`string`||n!==void 0&&typeof n!=`string`||!P.includes(i)||a.length>0||i===`exists`&&typeof o!=`boolean`||(i===`in`||i===`hasSome`)&&!Array.isArray(o)?F:new Condition(new Parameter(t,n),Object.freeze({[i]:o}))}const I={value:e=>isReference(e)?new Parameter(e.control,e.path):isOuterColumn(e)?new OuterColumn(e.$row,e.up):isInstant(e)?new Parameter:void 0,condition:conditionOf};function cyclePath(e,t,n=new Set,r=[]){if(!(typeof e!=`object`||!e||t.has(e))){if(n.has(e))return r.join(`.`);n.add(e);for(let[i,a]of Object.entries(e)){r.push(i);let e=cyclePath(a,t,n,r);if(e!==void 0)return e;r.pop()}n.delete(e),t.add(e)}}function admitRows(e,t,n,r=standaloneRegistry(t)){let i=Object.values(t).every(e=>{let t=e[`~`].state;return Object.values(t.scalars).every(e=>e[`~`].state.schema===void 0)}),a=i&&isImmutableRows(e),s=a?Object.entries(t):void 0,holds=e=>{let n=Object.entries(t);return e.schema===t&&n.length===e.entries.length&&n.every(([t,n],r)=>t===e.entries[r][0]&&n===e.entries[r][1])},u=a?D.get(r)?.get(e):void 0;if(u&&holds(u))return u.admitted;let refuse=(e,t,r,i)=>{throw new o(`Extension "${n}" rows.${t} at "${r}": ${i}.`,{meta:{extension:n,model:e}})},f=new WeakSet,p=new WeakMap,m={...I,exists:e=>{let n=c(e)?Object.keys(e):[],[i]=n;if(n.length!==1||!Object.hasOwn(t,i)||!c(e[i]))return{message:"names exactly one model of the schema and the `where` its rows must match",path:[]};let a=d(r.getModelSchemas(t[i]).core.where,e[i]);if(a.issues){let[e]=a.issues;return{message:e.message,path:[i,...e.path??[]]}}return new Existence(i,a.value)}},admit=(e,n,i)=>{let a=cyclePath(i,f);a!==void 0&&refuse(e,n,a,`contains itself`);let o=r.getModelSchemas(t[e]).core.where,s=l(m,()=>d(o,i),p);if(!s.issues)return s.value;let[c]=s.issues;return refuse(e,n,c.path?.map(String).join(`.`)||`root`,c.message)},selfKeys=e=>{let{state:n}=t[e][`~`];return Object.keys(n.relations).filter(r=>{let i=n.relations[r][`~`];return i.state.foreignKey!==void 0&&i.settleTarget()===t[e]})},admitAcyclic=(e,t,n)=>{let r=selfKeys(e);for(let i of n)r.includes(i)||refuse(e,t,`acyclic.${i}`,`names no to-one relation of the model to itself holding its key`);return n},admitVerbs=(e,n)=>{let r=`verbs.${e}`;c(n)||refuse(e,r,`root`,`is not an object or a function`);for(let t of Object.keys(n))Object.hasOwn(M,t)||refuse(e,r,t,`is not one of ${Object.keys(M).join(`, `)}`);let{state:i}=t[e][`~`],a=Object.fromEntries(Object.entries(n.predicates).map(([t,n])=>[t,admit(e,`${r}.predicates.${t}`,n)])),known=(t,n)=>{n!==void 0&&!Object.hasOwn(a,n)&&refuse(e,r,t,`names unknown predicate "${n}"`)};known(`read`,n.read),known(`update`,n.update),known(`delete`,n.delete),known(`place`,n.place);for(let t of[`writes`,`moves`])for(let[a,o]of Object.entries(n[t]??{}))Object.hasOwn(i.scalars,a)||Object.hasOwn(i.relations,a)||refuse(e,r,`${t}.${a}`,`names an unknown field`),known(`${t}.${a}`,o);let o,s=n.acyclic;if(typeof s==`function`){let t;o=Object.freeze({candidates:Object.freeze(selfKeys(e)),resolve:()=>t??=Object.freeze([...admitAcyclic(e,r,s())])})}else s!==void 0&&(o=admitAcyclic(e,r,s));let{evidence:l}=n;if(l!==void 0){N.test(l.as)||refuse(e,r,`evidence.as`,"is not `$` and an identifier");for(let[e,t]of l.names.entries())known(`evidence.names.${e}`,t)}let u=n.reads===void 0?void 0:keyFields(i);for(let[t,a]of Object.entries(n.reads??{}))Object.hasOwn(i.scalars,t)||refuse(e,r,`reads.${t}`,`names no scalar of the model`),u.has(t)&&refuse(e,r,`reads.${t}`,`names a key, a unique or a foreign key field`),known(`reads.${t}`,a);return Object.freeze({...n,predicates:Object.freeze(a),...o!==void 0&&{acyclic:o}})},lazily=(e,n)=>{let a;return resolver(()=>{if(a!==void 0)return a;let o=i?O.get(r)?.get(n)?.get(e):void 0;if(o&&holds(o))return a=o.admitted;let s=n(),c=admitVerbs(e,s);if(i&&isImmutableEntry(s)){freezeAdmitted(c);let i=O.get(r);i||(i=new WeakMap,O.set(r,i));let a=i.get(n);a||(a=new Map,i.set(n,a)),a.set(e,{schema:t,entries:Object.entries(t),admitted:c})}return a=c,c})},h={};for(let[n,r]of Object.entries(e.verbs??{}))Object.hasOwn(t,n)||refuse(n,`verbs.${n}`,`root`,`names an unknown model`),h[n]=typeof r==`function`?lazily(n,r):admitVerbs(n,r);let g={};for(let[t,n]of Object.entries(e.models)){let e=new Map,r=h[t];for(let[i,a]of Object.entries(n)){let n={};for(let e of[`root`,`related`]){let o=a[e];if(o===void 0)continue;let s=`${t}.${i}.${e}`;typeof o==`string`?typeof r==`function`?n[e]=resolver(()=>Object.hasOwn(r().predicates,o)?r().predicates[o]:refuse(t,s,`root`,`names unknown predicate "${o}"`)):Object.hasOwn(r?.predicates??{},o)?n[e]=r.predicates[o]:refuse(t,s,`root`,`names unknown predicate "${o}"`):n[e]=admit(t,s,o)}e.set(i,Object.freeze(n))}g[t]=Object.freeze(Object.fromEntries(e))}let _=Object.freeze({...e,models:Object.freeze(g),...e.verbs&&{verbs:Object.freeze(h)}});if(s&&freezeAdmitted(_),s&&isAdmittedRows(_)){let n=D.get(r);n||(n=new WeakMap,D.set(r,n)),n.set(e,{schema:t,entries:s,admitted:_})}return _}const NEVER_REQUIRED=()=>!1,L=Object.freeze(Object.create(null)),R=Object.freeze({}),z=Symbol(`absent`);function collectReferences(e,t,n=new Set){if(e instanceof Existence){collectReferences(e.where,t,n);return}let r=e instanceof Condition?e.parameter:e;if(r instanceof Parameter)r.control!==void 0&&t.add(r.control);else if(isReference(e))t.add(e.control);else if(Array.isArray(e)||c(e)){if(n.has(e))return;n.add(e);for(let r of Object.values(e))collectReferences(r,t,n)}}const B=new WeakMap;function referencesOfRows(e){let t=B.get(e);if(t)return t;let n=new Set,r=new Set;for(let t of Object.values(e.models))for(let e of Object.values(t))collectReferences(e.root,n,r),collectReferences(e.related,n,r);for(let t of Object.values(e.verbs??{}))typeof t!=`function`&&collectReferences(t.predicates,n,r);let i=[...n];return isImmutableRowData(e)&&B.set(e,i),i}function collectStampReferences(e,t){for(let n of Object.values(e??{}))collectReferences(n,t)}function undeclaredControlReferencesOf(e){let t=new Set(Object.keys(e.controls??{}));e.rows&&t.add(e.rows.control);let n=new Set(e.rows?referencesOfRows(e.rows):[]);for(let t of Object.values(e.data?.models??{}))collectStampReferences(t.create,n),collectStampReferences(t.update,n);for(let t of Object.keys(e.deletion?.removeWhen??{}))n.add(t);return[...n].filter(e=>!t.has(e))}function readsCall(e){return e instanceof Parameter||e instanceof Condition?!0:e instanceof Existence?readsCall(e.where):Array.isArray(e)?e.some(readsCall):c(e)&&Object.values(e).some(readsCall)}function stampValue(e,t){if(isReference(e)){let n=t?.[e.control],{path:r}=e;for(let e of r===void 0?[]:r.split(`.`))n=c(n)&&Object.hasOwn(n,e)?n[e]:void 0;return n===void 0?z:n}if(Array.isArray(e)){let n=e.map(e=>stampValue(e,t));return n.includes(z)?z:n.every((t,n)=>t===e[n])?e:n}if(!c(e))return e;let n;for(let[r,i]of Object.entries(e)){let a=stampValue(i,t);if(a===z)return z;a!==i&&((n??={...e})[r]=a)}return n??e}function boundStamp(e,t){if(e===void 0)return;let n={},r=!1;for(let[i,a]of Object.entries(e)){let e=stampValue(a,t);r||=e!==a,e!==z&&(n[i]=e)}return r?Object.freeze(n):e}function boundStamps(e,t){let n=new Map;for(let[r,i]of e){let e=boundStamp(i.create,t),a=boundStamp(i.update,t);n.set(r,e===i.create&&a===i.update?i:Object.freeze({create:e,update:a}))}return n}const V=new Parameter;function withInstants(e){let t;for(let[n,r]of Object.entries(e??{}))isInstant(r)&&((t??={...e})[n]=V);return t===void 0?e:Object.freeze(t)}function requiredOn(e){let t=new Map;for(let n of e?.all??[])n.required!==void 0&&t.set(n.name,n.required);return t.size===0?NEVER_REQUIRED:(e,n)=>{let r=t.get(e);return r===!0||r?.has(n)===!0}}var LazyMap=class extends Map{#e;constructor(e,t){super(e),this.#e=t}#t(e){let t=this.#e.get(e);if(t===void 0)return;let n=t();this.#e.delete(e),super.set(e,n)}#n(){for(let e of[...this.#e.keys()])this.#t(e)}get(e){return this.#t(e),super.get(e)}has(e){return this.#e.has(e)||super.has(e)}get size(){return this.#n(),super.size}keys(){return this.#n(),super.keys()}values(){return this.#n(),super.values()}entries(){return this.#n(),super.entries()}[Symbol.iterator](){return this.entries()}forEach(e,t){this.#n(),super.forEach(e,t)}};function lazyMap(e,t){return t.size===0?e:new LazyMap(e,t)}function modelDomain(e,t,n){let r=new Map;for(let[i,a]of e.entries())for(let[e,o]of Object.entries(a.models)){let a=o[t[i]]?.[n];if(a===void 0)continue;let s=r.get(e)??[];s[i]=a,r.set(e,s)}let i=new Map,a=new Map;for(let[e,t]of r)t.some(e=>typeof e==`function`)?a.set(e,()=>{let e=[];for(let[n,r]of t.entries())r!==void 0&&(e[n]=typeof r==`function`?r():r);return e}):i.set(e,t);return lazyMap(i,a)}const H=Object.freeze({OR:Object.freeze([])}),fieldsOf=(e,t)=>new Map(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));function layerVerbs(e){let named=t=>t===void 0?H:e.predicates[t],t=e.acyclic;return Object.freeze({read:named(e.read),update:named(e.update),delete:named(e.delete),writes:fieldsOf(e.writes,named),...e.place!==void 0&&{place:named(e.place)},moves:fieldsOf(e.moves,named),acyclic:Array.isArray(t)?Object.freeze([...t]):t??U,...e.evidence&&{evidence:Object.freeze({as:e.evidence.as,names:Object.freeze(e.evidence.names.map(e=>Object.freeze([e,named(e)]))),ordered:e.evidence.ordered===!0})},reads:fieldsOf(e.reads,named)})}const U=Object.freeze([]);function modelVerbs(e){let t=new Map;for(let[n,r]of e.entries())for(let[e,i]of Object.entries(r.verbs??{})){let r=t.get(e)??[];r[n]=i,t.set(e,r)}let layers=(e,t)=>{let n=new Set,r=[];for(let[i,a]of t.entries()){if(a===void 0)continue;let t=a.evidence?.as;if(t!==void 0&&n.has(t))throw new o(`rows.verbs.${e}.evidence.as "${t}" is declared by two extensions of the chain.`,{meta:{model:e}});t!==void 0&&n.add(t),r[i]=layerVerbs(a)}return r},n=new Map,r=new Map;for(let[e,i]of t)i.some(e=>typeof e==`function`)?r.set(e,()=>layers(e,Array.from(i,e=>typeof e==`function`?e():e))):n.set(e,layers(e,i));if(t.size!==0)return lazyMap(n,r)}const isLazy=e=>Object.values(e.verbs??{}).some(e=>typeof e==`function`);function checkingLazyReferences(e,t,n){if(!isLazy(e))return e;let r=new Map,i=Object.fromEntries(Object.entries(e.verbs).map(([e,i])=>{if(typeof i!=`function`)return[e,i];let a,check=()=>{if(a!==void 0)return a;let e=i();for(let r of verbsReferences(e))t(r)||n(r);return a=e,e};return r.set(e,check),[e,check]})),a=Object.fromEntries(Object.entries(e.models).map(([e,t])=>{let n=r.get(e);return n===void 0?[e,t]:[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,typeof t==`function`?()=>(n(),t()):t]))]))]})),o=Object.freeze({...e,models:a,verbs:Object.freeze(i)});return W.set(o,e),o}const W=new WeakMap,admittedRowsOf=e=>W.get(e)??e,G=new WeakMap;function verbsReferences(e){let t=G.get(e);if(t)return t;let n=new Set;collectReferences(e.predicates,n);let r=[...n];return Object.isFrozen(e)&&G.set(e,r),r}function bindRows(e,t,n,r){let i=e??[],a=1,o=i.map(e=>{let t=rowsModes(e),n={control:e.control,names:t,modes:new Map(t.map((e,t)=>[e,t])),fallback:t.indexOf(e.default),stride:a};return a*=t.length,n}),s=[],c=modelVerbs(i),l=i.some(e=>Object.values(e.verbs??{}).some(e=>typeof e==`function`||e.evidence!==void 0||Object.keys(e.reads??{}).length>0));for(let e=0;e<a;e++){let t=o.map(t=>t.names[Math.floor(e/t.stride)%t.names.length]);s.push(Object.freeze({root:modelDomain(i,t,`root`),related:modelDomain(i,t,`related`),...c&&{verbs:c,projects:l}}))}let u=s[o.reduce((e,t)=>e+t.fallback*t.stride,0)],d=t===void 0?void 0:new Map(Object.entries(t)),f=n===void 0?void 0:new Map(Object.entries(n).map(([e,t])=>{let n=withInstants(t.create),r=withInstants(t.update);return[e,n===t.create&&r===t.update?t:Object.freeze({create:n,update:r})]})),p=new Set;for(let e of f?.values()??[])collectStampReferences(e.create,p),collectStampReferences(e.update,p);let m=s.map(e=>Object.freeze({domain:e,defaults:u,...f&&{stamps:f}})),h=i.some(isLazy)||i.some(e=>Object.values(e.verbs??{}).some(e=>typeof e!=`function`&&readsCall(e.predicates))),reads=e=>h||[e.root,e.related].some(e=>[...e.values()].some(readsCall));return Object.freeze({members:o,deletion:t??L,physical:m,tombstoning:d===void 0?m:m.map(e=>Object.freeze({...e,tombstones:d})),parametric:s.map(e=>reads(e)||reads(u)),bindsStamps:p.size>0,required:requiredOn(r)})}function callRows(e,t,n){let r=0;for(let t of e.members)r+=t.stride*(t.modes.get(n?.[t.control])??t.fallback);let i=e.deletion[t]?.removeWhen,a=(i!==void 0&&Object.entries(i).every(([e,t])=>n?.[e]===t)?e.physical:e.tombstoning)[r],o=e.parametric[r];return o||e.bindsStamps?Object.freeze({...a,...o&&{values:Object.freeze({controls:n??R,required:e.required})},...e.bindsStamps&&{stamps:boundStamps(a.stamps,n)}}):a}export{installOfficialCacheRuntime as A,isReadOperation as C,getOfficialCacheChainCapability as D,bindOfficialCacheChain as E,registerOfficialCacheQuery as F,setOfficialCacheChainCapability as I,h as M,officialCacheRuntime as N,getOfficialCacheChainDefinition as O,registerOfficialCacheChain as P,baseOperation as S,m as T,controlsOwnedBy as _,isLazy as a,uncacheableRead as b,isAdmittedRows as c,Existence as d,OuterColumn as f,bindControls as g,admitControls as h,checkingLazyReferences as i,isCacheManagedExecution as j,getOfficialCacheQueryCapability as k,isImmutableRowData as l,parseStamped as m,bindRows as n,undeclaredControlReferencesOf as o,Parameter as p,callRows as r,admitRows as s,admittedRowsOf as t,Condition as u,isStableControlValue as v,isWriteOperation as w,x,placeControls as y};
2
- //# sourceMappingURL=rows-BlONp14o.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"select-assembly-BP8c4O-0.mjs","names":["sql","sql"],"sources":["../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n like: (column: Sql, pattern: Sql) => Sql;\n notLike: (column: Sql, pattern: Sql) => Sql;\n /** Case-insensitive LIKE. */\n ilike: (column: Sql, pattern: Sql) => Sql;\n notIlike: (column: Sql, pattern: Sql) => Sql;\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /** Fold ASCII A-Z to a-z without provider-native Unicode case folding. */\n asciiCaseFold: (expr: Sql) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and so does a bytes list longer than `literals.list` keeps\n * parenthesized; nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** EXISTS wrapper for \"some\" relation filter (to-many) */\n some: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"every\" - negated condition (to-many) */\n every: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"none\" (to-many) */\n none: (subquery: Sql) => Sql;\n /** EXISTS wrapper for \"is\" relation filter (to-one) */\n is: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"isNot\" relation filter (to-one) */\n isNot: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n /**\n * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n /**\n * A one-column SELECT answering 1 where `condition` holds (over `from`'s\n * row when given), aborting the statement it is part of otherwise, NULL\n * included: the guard a write carries for the row it produces, read as a\n * scalar inside that write.\n */\n holds: (condition: Sql, from?: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /** UNION ALL (keeps duplicates). */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n /**\n * `rows` as ONE FROM item `alias` whose columns are `typed.columns`,\n * each typed as that column of the table `typed.from` reads under\n * `typed.alias`: the rows a judged write produces, read before it writes\n * them. `typed.head` is the empty read of those columns (`… WHERE\n * FALSE`); a row lists its values in `columns`' order and may refer to\n * the enclosing query. The form is the dialect's, because every one\n * spends a different limit on the row count first: one `UNION ALL\n * SELECT` arm per row (the default, MySQL: 65,535 arms measured) is a\n * compound term each, refused past `SQLITE_MAX_COMPOUND_SELECT` (500) on\n * SQLite, and one parser recursion each on PostgreSQL (`54001` at 8,000\n * rows), where a `VALUES` list is neither. The bind budget stays the\n * only bound on a chunk (ENG-3, review 2).\n */\n typedRows: (\n typed: {\n readonly head: Sql;\n readonly from: Sql;\n /** The table itself, unaliased: its row type names the columns' types. */\n readonly table: Sql;\n readonly alias: string;\n readonly columns: readonly string[];\n },\n rows: readonly (readonly Sql[])[],\n alias: string\n ) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * Matches filter schema: { l2, cosine }\n * Drivers that don't support vector operations can override\n * this property with an object that throws FeatureNotSupportedError.\n *\n * Reserved — the query engine does not call these yet; vector filters are\n * rejected in the where-builder today.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance operator for ORDER BY: column <-> vector */\n l2: (column: Sql, vector: Sql) => Sql;\n /** Cosine distance operator for ORDER BY: column <=> vector */\n cosine: (column: Sql, vector: Sql) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n appendFilterParts(fragments, parts);\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (fragments: Sql[], parts: QueryParts): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n appendFilterParts(innerFragments, parts);\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outerFragments: Sql[] = [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (order) {\n outerFragments.push(sql`ORDER BY ${order.orderBy}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFA0BA,SAAgB,gCACd,E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,EAAM,SACR,EAAU,KAAK,CAAG,YAAY,EAAM,UAAU,CAG5C,EAAM,QACR,EAAU,KAAK,CAAG,UAAU,EAAM,SAAS,EAIzC,mBACJ,EACA,EACA,EACA,IACS,CACL,EACF,EAAU,KAAK,CAAG,SAAS,IAAQ,CAC1B,GAAU,GAEnB,EAAU,KAAK,CAAG,SAAS,IAAe,CAGxC,GACF,EAAU,KAAK,CAAG,UAAU,IAAS,EA8B5B,6BACX,EACA,EACA,EACA,IACQ,CAER,IAAM,EAAiB,EAAM,iBAAmB,EAAM,SAAW,EAC3D,EAAQ,EAAM,cAEd,EAAuB,CAAC,EAAM,QAAQ,CACxC,GACF,EAAc,KAAK,EAAM,KAAK,CAEhC,EAAc,KACZ,CAAG,mCAAmC,EAAS,YAAY,EAAe,OAAO,EAAiB,MAAM,GACzG,CAGD,IAAM,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAe,KAAK,GAC1C,CAAG,QAAQ,EAAM,OAClB,CAED,kBAAkB,EAAgB,EAAM,CAExC,IAAM,EAAaA,EAAI,KAAK,EAAgB,IAAI,CAK1C,EAAe,EAAM,sBAAuB,IAAI,EAAiB,CACjE,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAc,KAAK,CAAC,SAAS,EAAW,OAAO,EAAiB,qBAAqB,GAC3G,CAAG,SAAS,EAAiB,MAAM,CAAC,MACrC,CAQD,OANI,GACF,EAAe,KAAK,CAAG,YAAY,EAAM,UAAU,CAGrD,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,m as n}from"./validation-DN1N2OdK.mjs";import{E as r}from"./geo-point-codec-DcUTvoEg.mjs";import{o as i,t as a}from"./sql-BR8ZzKn8.mjs";import{a as o,t as s}from"./physical-CAZ_LauY.mjs";import{t as c}from"./adapter-result-parser-B63ouFIz.mjs";import{r as l}from"./adapter-internals-Dagucesf.mjs";import{i as u}from"./datetime-physical-codec-DfVmz14E.mjs";import{t as ee}from"./json-number-CAfNAqDB.mjs";import{C as d,D as f,E as p,M as m,N as h,O as te,S as ne,T as re,_ as ie,a as ae,b as oe,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,n as w,o as T,p as E,r as D,s as O,v as k,w as A,x as j,y as M}from"./standard-sql-wRMNi-Yg.mjs";import{r as N,t as P}from"./batch-refs-C3MTcVre.mjs";import{f as F,h as I,n as L,o as R,p as z,r as B,t as V,u as H}from"./select-assembly-BP8c4O-0.mjs";const U=h(`"`),W={quotient:(e,t)=>i`(${e} / ${t})`,remainder:(e,t)=>i`(${e} % ${t})`};function sqliteIntegerPrecision(e){let t=te(e);if(t<19)return t;if(!(t>19))return(e.startsWith(`-`)?e.slice(1)<=`9223372036854775808`:e<=`9223372036854775807`)?t:void 0}const G=i.raw(`1000000000000000000`),overflowCoefficient=e=>i.raw(`1${`0`.repeat(Math.min(e.precision,18))}`),guardedCoefficientAssignment=(e,t,n,r)=>i`${e} = CASE WHEN ${e} IS NULL OR ${t} THEN ${n} ELSE ${overflowCoefficient(r)} END`,K=/^\d+$/,q=/["\\]/,jsonPathLeg=e=>{if(K.test(e))return`$[${e}]`;if(q.test(e))throw Error(`SQLite JSON path segments containing " or \\ must be rejected by the portable query contract.`);return`$."${e}"`},jsonExtract=(e,t)=>{let n=i`${e} -> '$'`;for(let e of t)n=i`${n} -> ${jsonPathLeg(e)}`;return n},jsonExtractText=(e,t)=>{if(t.length===0)return i`${e} ->> '$'`;let n=t.map(jsonPathLeg),r=n.pop(),a=e;for(let e of n)a=i`${a} -> ${e}`;return i`${a} ->> ${r}`},jsonArrayConcat=(e,t)=>i`(CASE WHEN ${e} = '[]' THEN ${t} WHEN ${t} = '[]' THEN ${e} ELSE substr(${e}, 1, length(${e}) - 1) || ',' || substr(${t}, 2) END)`,sqliteJsonListValue=e=>i`${m(e)}`,se=[``,``],J=[`CAST(`,` AS INTEGER)`],ce=/\p{Cs}/u,Y=p().list;function jsonMember(e){return typeof e==`string`?ce.test(e)?void 0:JSON.stringify(e):e instanceof Uint8Array?`"${Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}"`:typeof e==`bigint`||typeof e==`boolean`||Number.isSafeInteger(e)?String(e):void 0}function sqliteList(e){if(e.length<=25)return Y(e);let[t]=e,n=t?.strings[0]===J[0]?J:se,r=[],o=0;for(let t of e){let[i,a,s]=t.strings,c=t.values[0],l=jsonMember(c);if(l===void 0||i!==n[0]||a!==n[1]||s!==void 0)return Y(e);c instanceof Uint8Array&&o++,r.push(l)}return o!==0&&o!==e.length?Y(e):i`(SELECT ${new a(n,[i.raw(o===0?`value`:`unhex(value)`)])} FROM json_each(${`[${r.join(`,`)}]`}))`}const X={...p(),value:e=>{if(typeof e==`bigint`&&sqliteIntegerPrecision(String(e))===void 0)throw new n(`SQLite bigint values must fit signed 64-bit integers.`);return i`${e}`},true:()=>i.raw(`1`),false:()=>i.raw(`0`),json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t)=>i`${u(e,s(t))}`,decimal:(e,t)=>new a(J,[r(e,t,`coefficient`)]),id:(e,t)=>i`${e}`,list:sqliteList},Z={...ae(),like:(e,t)=>i`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>i`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>i`lower(${e}) LIKE lower(${t}) ESCAPE '\\'`,notIlike:(e,t)=>i`lower(${e}) NOT LIKE lower(${t}) ESCAPE '\\'`,containsText:(e,t)=>i`instr(${e}, ${t}) > 0`,startsWithText:(e,t)=>i`substr(${e}, 1, length(${t})) COLLATE BINARY = ${t}`,endsWithText:(e,t)=>i`substr(${e}, length(${e}) - length(${t}) + 1) COLLATE BINARY = ${t}`,startsWithPrefix:(e,t)=>i`${e} GLOB ${`${S(t)}*`}`,exactTextEq:(e,t)=>i`${e} COLLATE BINARY = ${t}`,exactTextIn:(e,t)=>i`${e} COLLATE BINARY IN ${t}`,...v(),...k(),...j(),...y(X.true,X.false),...g()},le={...b(),asciiCaseFold:e=>i`lower(${e})`,caseSensitiveText:e=>i`${e} COLLATE BINARY`,concat:(...e)=>e.length===0?i.raw(`''`):e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`MAX(${i.join(e,`, `)})`,least:(...e)=>i`MIN(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / CAST(${t} AS INTEGER))`,decimalCast:(e,t)=>i`CAST(${e} AS INTEGER)`,idCast:(e,t)=>t===`bytes`?i`unhex(${e})`:i`CAST(${e} AS TEXT)`,cast:D({text:`TEXT`,integer:`INTEGER`,bigint:`INTEGER`,boolean:`INTEGER`,numeric:`NUMERIC`}),blobToHex:e=>i`lower(hex(${e}))`},ue={...w(`9e999`),decimalAvg:(e,t)=>R(W,i`SUM(${e})`,i`COUNT(${e})`),decimalSumOperandPrecision:sqliteIntegerPrecision,integerSum:e=>{let t=i`SUM(${e} >> 32)`,n=i`SUM(${e} - ((${e} >> 32) << 32))`,r=i`(${t} + (${n} >> 32))`,a=i`(${n} & 4294967295)`,o=i`${r} * 4294967296.0 + ${a}`;return{parts:[t,n],value:i`CASE WHEN ${r} > 2147483647 THEN ${o} WHEN ${r} >= -2147483648 THEN ${r} * 4294967296 + ${a} ELSE MIN(${o}, -9223372036854777856.0) END`,order:[r,a]}}};function sqliteJsonEquals(e,t){let nodes=e=>i`SELECT fullkey, CASE WHEN type IN ('integer', 'real') THEN 'number' ELSE type END, atom FROM json_tree(${e})`;return i`(CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE NOT EXISTS (${nodes(e)} EXCEPT ${nodes(t)}) AND NOT EXISTS (${nodes(t)} EXCEPT ${nodes(e)}) END)`}const sqliteJsonObject=e=>{if(e.length===0)return i.raw(`json_object()`);let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`json_object(${i.join(t,`, `)})`},de={equals:sqliteJsonEquals,number:e=>i`CASE WHEN ${e} IS NULL THEN NULL ELSE printf(${i.raw(`'${ee}'`)}, ${e}) END`,boolean:e=>i`json(CASE WHEN ${e} THEN 'true' ELSE 'false' END)`,document:e=>i`json(${e})`,object:sqliteJsonObject,array:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,emptyArray:()=>i.raw(`json_array()`),agg:e=>i`json_group_array(${e})`,objectFromColumns:sqliteJsonObject,extract:jsonExtract,extractText:jsonExtractText,numberAtPath:(e,t)=>i`(CASE WHEN json_type(${jsonExtract(e,t)}) IN ('integer', 'real') THEN CAST(${jsonExtractText(e,t)} AS REAL) END)`,stringAtPath:(e,t)=>i`((CASE WHEN json_type(${jsonExtract(e,t)}) = 'text' THEN ${jsonExtractText(e,t)} END) COLLATE BINARY)`,contains:(e,t)=>i`(json_type(${e}) = 'array' AND NOT EXISTS (SELECT 1 FROM json_each(${t}) AS required WHERE NOT EXISTS (SELECT 1 FROM json_each(${e}) AS candidate WHERE ${sqliteJsonEquals(i`${e} -> candidate.fullkey`,i`${t} -> required.fullkey`)})))`,lastElement:e=>i`${e} -> '$[#-1]'`,value:e=>i`${m(e)}`},fe={literal:e=>e.length===0?i.raw(`json_array()`):i`json_array(${i.join(e,`, `)})`,value:sqliteJsonListValue,enumValue:sqliteJsonListValue,has:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) WHERE value = ${t})`,hasEvery:(e,t)=>i`(SELECT COUNT(*) FROM json_each(${t}) WHERE value IN (SELECT value FROM json_each(${e}))) = json_array_length(${t})`,hasSome:(e,t)=>i`EXISTS (SELECT 1 FROM json_each(${e}) AS a, json_each(${t}) AS b WHERE a.value = b.value)`,isEmpty:e=>i`(json_array_length(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT)`,length:e=>i`json_array_length(${e})`,get:(e,t)=>i`json_extract(${e}, '$[' || ${t} || ']')`,push:(e,t)=>i`json_insert(${e}, '$[#]', ${t})`,set:(e,t,n)=>i`json_set(${e}, '$[' || ${t} || ']', ${n})`},pe={...C(),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`},me={...M(),multiply:(e,t,n)=>{let r=n?.decimal;return r?guardedCoefficientAssignment(e,i`${t} = 0 OR ABS(${e}) <= ${G} / ABS(${t})`,R(W,i`(${e} * ${t})`,H(r.scale)),r):i`${e} = ${e} * ${t}`},divide:(e,t,n)=>{let r=n?.decimal;if(r){let n=H(r.scale);return guardedCoefficientAssignment(e,i`ABS(${e}) <= ${G} / ${n}`,R(W,F(i`(${e} * ${n})`,t),i`ABS(${t})`),r)}return n?.integer?i`${e} = ${e} / CAST(${t} AS INTEGER)`:i`${e} = ${e} / ${t}`},push:(e,t)=>i`${e} = ${jsonArrayConcat(i`json(COALESCE(${e}, '[]'))`,t)}`,unshift:(e,t)=>i`${e} = ${jsonArrayConcat(t,i`json(COALESCE(${e}, '[]'))`)}`},Q={skipDuplicatesStrategy:`sql`,insert:E(U),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...ie(),returning:e=>i`RETURNING ${e}`,...oe()},he={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE json_extract('x', '$') END AS "__viborm_assert__"`,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE json_extract('{}', '__viborm_refused__') END AS "__viborm_judged__"${t?i` FROM ${t}`:i``}`},ge={...T(),right:(e,t)=>{throw Error(`SQLite does not support RIGHT JOIN. Restructure the query with joins.left and swapped operands.`)},full:(e,t)=>{throw Error(`SQLite does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},lateral:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)},lateralLeft:(e,t)=>{throw Error(`SQLite does not support LATERAL joins. Check adapter.capabilities.supportsLateralJoins before calling.`)}},_e={supportsReturning:!0,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!1,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!1,joinsJunctionFilters:!0},ve={decimalRepresentation:`coefficient`,decimalListRepresentation:`coefficient`,dateTimeRepresentation:s,idRepresentation:(e,t)=>o(e,t,`sqlite`)?.representation??`text`,parseResult:c,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()},ye=_(U),be=re(),xe=d(),$=f(U),Se=O(U,{materializing:i.raw(`MATERIALIZED`)}),Ce=A(U,(e,t,n)=>i`(${e.head} UNION ALL VALUES ${i.join(t.map(x),`, `)}) AS ${i.raw(U(n))}`),we=ne();function balancedConjunction(e){let balanced=(...t)=>{if(t.length<=2)return e(...t);let n=Math.floor(t.length/2);return e(balanced(...t.slice(0,n)),balanced(...t.slice(n)))};return balanced}var SQLiteAdapter=class{constructor({temporaryObjects:e=!0,deepExpressions:t=!0,sharedRelationBodies:n=!1,compoundSelectTerms:r,relationsPerStatement:a,countsCascadedChanges:o}={}){z(this,this.geoPoint),t||(this.subqueries.existsCheck=(e,t)=>i`SELECT 1 FROM (${$.existsCheck(e,t)})`,this.subqueries.isolated=e=>i`EXISTS (SELECT 1 FROM (SELECT 1 WHERE ${e}))`,this.operators.and=balancedConjunction(Z.and),this.capabilities.boundsExpressionDepth=!0),n&&(this.capabilities.sharesRelationBodies=!0),r!==void 0&&(this.capabilities.compoundSelectTerms=r),a!==void 0&&(this.capabilities.relationsPerStatement=a),o&&(this.capabilities.countsCascadedChanges=!0);let s,createBatchRefs=()=>this.#t(e);l(this,{get batchRefs(){return s??=createBatchRefs(),s},constraints:I,select:this.#e.select})}raw=we;identifiers={...ye};literals={...X};operators={...Z};expressions={...le};aggregates={...ue};json={...de};arrays={...fe};orderBy={...pe};clauses={...be};set={...me};filters={...xe};subqueries={...$};noLimitValue=i.raw(`-1`);#e={select:e=>e.distinct?V(e,e.distinct,this.identifiers.escape,this.noLimitValue):L(i`SELECT ${e.columns}`,e,{forUpdate:`omit`,noLimitValue:this.noLimitValue})};cte={...Se};mutations={...Q};assertions={...he};joins={...ge};setOperations={...Ce};capabilities={..._e};lastInsertId=()=>i.raw(`last_insert_rowid()`);#t(e){let t=i.raw(U(P)),n=i.raw(e?`CREATE TEMP TABLE IF NOT EXISTS`:`CREATE TABLE IF NOT EXISTS`);return N({table:t,batchIdColumn:i.raw(`"batch_id"`),keyColumn:i.raw(`"ref_key"`),valueColumn:i.raw(`"ref_value"`),createTable:i`${n} ${t} ("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)`,lastInsertId:()=>this.lastInsertId()})}vector=t;geoPoint=(()=>{let longitude=e=>this.json.numberAtPath(e,[`longitude`]),latitude=e=>this.json.numberAtPath(e,[`latitude`]);return{value:(e,t)=>i`json_object('longitude', ${this.json.document(this.json.number(e))}, 'latitude', ${this.json.document(this.json.number(t))})`,longitude,latitude,...B(longitude,latitude,this.operators)}})();result={...ve}};export{SQLiteAdapter as t};
2
- //# sourceMappingURL=sqlite-adapter-CF-m7LIP.mjs.map