viborm 1.14.2 → 1.15.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 (272) hide show
  1. package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +15 -3
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
  6. package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
  7. package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
  8. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +2 -2
  18. package/dist/cache.mjs +1 -1
  19. package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
  20. package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
  21. package/dist/cli.mjs +2 -2
  22. package/dist/cli.mjs.map +1 -1
  23. package/dist/client-CVCC-D1j.mjs +2 -0
  24. package/dist/client-CVCC-D1j.mjs.map +1 -0
  25. package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
  26. package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
  27. package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
  28. package/dist/client.d.mts +3 -3
  29. package/dist/client.mjs +1 -1
  30. package/dist/config.d.mts +1 -1
  31. package/dist/config.mjs +1 -1
  32. package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
  33. package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
  34. package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
  35. package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
  39. package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
  40. package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
  41. package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
  42. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
  43. package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
  44. package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
  45. package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
  46. package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
  47. package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
  48. package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
  49. package/dist/driver.d.mts +1 -1
  50. package/dist/driver.mjs +1 -1
  51. package/dist/durable-object.d.mts +1 -1
  52. package/dist/durable-object.mjs +1 -1
  53. package/dist/error-mapping-DIRlrmDK.mjs +2 -0
  54. package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
  55. package/dist/every-BHEmfLOW.mjs +2 -0
  56. package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
  57. package/dist/execution-context-VMQm-9CH.mjs +2 -0
  58. package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
  59. package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
  60. package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
  61. package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
  62. package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
  63. package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
  64. package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
  65. package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
  66. package/dist/identifiers-BTCfD5ic.mjs +2 -0
  67. package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
  68. package/dist/index.d.mts +2 -2
  69. package/dist/index.mjs +1 -1
  70. package/dist/instrumentation.d.mts +1 -1
  71. package/dist/instrumentation.mjs +1 -1
  72. package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
  73. package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
  74. package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
  75. package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
  76. package/dist/judge-words-DpwxOfre.mjs +2 -0
  77. package/dist/judge-words-DpwxOfre.mjs.map +1 -0
  78. package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
  79. package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
  80. package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
  81. package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
  82. package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
  83. package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
  84. package/dist/libsql.d.mts +1 -1
  85. package/dist/libsql.mjs +1 -1
  86. package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
  87. package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
  88. package/dist/methods-part-DoTrY6b9.mjs +2 -0
  89. package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
  90. package/dist/migrations/mysql.d.mts +4 -4
  91. package/dist/migrations/mysql.mjs +1 -1
  92. package/dist/migrations/postgres.d.mts +4 -4
  93. package/dist/migrations/postgres.mjs +1 -1
  94. package/dist/migrations/snowflake.d.mts +4 -4
  95. package/dist/migrations/snowflake.mjs +1 -1
  96. package/dist/migrations/sqlite.d.mts +4 -4
  97. package/dist/migrations/sqlite.mjs +1 -1
  98. package/dist/migrations/storage/durable-object.mjs +1 -1
  99. package/dist/migrations/storage/r2.mjs +1 -1
  100. package/dist/migrations/surrealdb.d.mts +4 -4
  101. package/dist/migrations/surrealdb.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
  107. package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
  108. package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
  109. package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
  113. package/dist/named-statements-CMj1QEyw.mjs +2 -0
  114. package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
  115. package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
  116. package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
  117. package/dist/neon-http.d.mts +1 -1
  118. package/dist/neon-http.mjs +1 -1
  119. package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
  120. package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
  121. package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
  122. package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
  123. package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering/keys.mjs +1 -1
  127. package/dist/ordering.d.mts +1 -1
  128. package/dist/ordering.mjs +1 -1
  129. package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
  130. package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
  131. package/dist/permissions.d.mts +1 -1
  132. package/dist/permissions.mjs +1 -1
  133. package/dist/pg.d.mts +27 -1
  134. package/dist/pg.mjs +1 -1
  135. package/dist/pg.mjs.map +1 -1
  136. package/dist/pglite.d.mts +1 -1
  137. package/dist/pglite.mjs +1 -1
  138. package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
  139. package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
  143. package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
  144. package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
  145. package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
  146. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
  147. package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
  148. package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
  149. package/dist/postgres-result-CiS5OWp1.mjs +2 -0
  150. package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
  151. package/dist/postgres.d.mts +17 -1
  152. package/dist/postgres.mjs +1 -1
  153. package/dist/postgres.mjs.map +1 -1
  154. package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
  155. package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
  156. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
  157. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
  158. package/dist/query-Cdy8E2jM.mjs +2 -0
  159. package/dist/query-Cdy8E2jM.mjs.map +1 -0
  160. package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
  161. package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
  162. package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
  163. package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
  164. package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
  165. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
  166. package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
  167. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
  168. package/dist/scalar-B9WizsvR.mjs +4 -0
  169. package/dist/scalar-B9WizsvR.mjs.map +1 -0
  170. package/dist/schema/introspect.d.mts +2 -2
  171. package/dist/schema/introspect.mjs +1 -1
  172. package/dist/schema/json.d.mts +2 -2
  173. package/dist/schema/json.mjs +1 -1
  174. package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
  175. package/dist/schema-MB-pPNTO.mjs.map +1 -0
  176. package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
  177. package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
  178. package/dist/schema-introspection-wMVZowIF.mjs +6 -0
  179. package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
  180. package/dist/schema.d.mts +1 -1
  181. package/dist/schema.mjs +1 -1
  182. package/dist/select-assembly-SuVxJjps.mjs +2 -0
  183. package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
  184. package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
  185. package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
  186. package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
  187. package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
  188. package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
  189. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
  190. package/dist/snowflake.d.mts +2 -2
  191. package/dist/snowflake.mjs +1 -1
  192. package/dist/snowflake.mjs.map +1 -1
  193. package/dist/soft-delete.d.mts +1 -1
  194. package/dist/soft-delete.mjs +1 -1
  195. package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
  196. package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
  197. package/dist/sql-BGjAsoBE.mjs +2 -0
  198. package/dist/sql-BGjAsoBE.mjs.map +1 -0
  199. package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
  200. package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
  201. package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
  202. package/dist/sql.d.mts +1 -1
  203. package/dist/sql.mjs +1 -1
  204. package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
  205. package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
  206. package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
  207. package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
  208. package/dist/sqlite3.d.mts +1 -1
  209. package/dist/sqlite3.mjs +1 -1
  210. package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
  211. package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
  212. package/dist/surrealdb.d.mts +2 -2
  213. package/dist/surrealdb.mjs +1 -1
  214. package/dist/surrealdb.mjs.map +1 -1
  215. package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
  216. package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
  217. package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
  218. package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
  219. package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
  220. package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
  221. package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
  222. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
  223. package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
  224. package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
  225. package/dist/validation-D0LG854o.mjs +2 -0
  226. package/dist/validation-D0LG854o.mjs.map +1 -0
  227. package/dist/validation.d.mts +1 -1
  228. package/dist/validation.mjs +1 -1
  229. package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
  230. package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
  231. package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
  232. package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
  233. package/dist/version-B_ZLWzLW.mjs +2 -0
  234. package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
  235. package/package.json +35 -35
  236. package/dist/client-DRpX3-vw.mjs +0 -2
  237. package/dist/client-DRpX3-vw.mjs.map +0 -1
  238. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  239. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  240. package/dist/every-tOgQmaIE.mjs +0 -2
  241. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  242. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  243. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  244. package/dist/identifiers-s00pGES8.mjs +0 -2
  245. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  246. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  247. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  248. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  249. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  250. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  251. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  252. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  253. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  254. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  255. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  256. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  257. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  258. package/dist/query-BZVHfA0s.mjs +0 -2
  259. package/dist/query-BZVHfA0s.mjs.map +0 -1
  260. package/dist/scalar-BHCh7aUz.mjs +0 -4
  261. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  262. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  263. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  264. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  265. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  266. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  267. package/dist/sql-3o4DOKm9.mjs +0 -2
  268. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  269. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  270. package/dist/validation-CYaJ8ndO.mjs +0 -2
  271. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  272. package/dist/version-CXGIA82S.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"snowflake.mjs","names":["sql","#select","text","configuration","text","#credentials","#now","#jwt","#key","#keyedCursor","#relation","#order","#orderList","sql","#carried","#options","#send","#partitions","#request","body","text","#options","#context","#baseUrl","#parameters","#run"],"sources":["../src/adapters/databases/snowflake/snowflake-adapter.ts","../src/drivers/snowflake/auth.ts","../src/drivers/snowflake/queries.ts","../src/drivers/snowflake/read-only.ts","../src/drivers/snowflake/transport.ts","../src/drivers/snowflake/values.ts","../src/drivers/snowflake/index.ts"],"sourcesContent":["/**\n * Snowflake's SQL, for the reads VibORM runs on a warehouse (`viborm/snowflake`).\n *\n * VibORM only READS Snowflake: the driver refuses every write before it builds a\n * statement, so the members below that spell a write exist for the interface\n * and are never asked. What this adapter owns is the reading side:\n *\n * - identifiers are always quoted, so a name is the catalog's own spelling\n * (an unquoted `orders` is stored `ORDERS`; introspection reports it so);\n * - JSON is Snowflake's semi-structured `VARIANT`: `OBJECT_CONSTRUCT_KEEP_NULL`,\n * `ARRAY_AGG`, `GET_PATH`-style bracket access and `PARSE_JSON` operands;\n * - a datetime operand binds as an instant (`TIMESTAMP_TZ`), which the\n * driver's UTC session compares against `TIMESTAMP_NTZ`, `_LTZ` and `_TZ`\n * columns alike;\n * - `LIKE` patterns escape with a backslash, which a Snowflake string literal\n * spells `'\\\\'`;\n * - `s.vector()` is `VECTOR(FLOAT, n)` and `s.point()` a `GEOGRAPHY` point.\n *\n * Nested relation reads are not spelled here: Snowflake refuses a correlated\n * subquery holding a `LIMIT` or a correlated derived table, so the driver's\n * `SnowflakeQueries` writes them as uncorrelated grouped tables.\n */\n\nimport { FeatureNotSupportedError, UnsupportedOperationError } from \"@errors\";\nimport { type Sql, sql } from \"@sql\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n CastType,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\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 type TextMatch,\n} from \"../../database-adapter\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\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 createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\nconst ARRAY_INDEX = /^\\d+$/;\nconst LEADING_ZEROS = /^0+/;\n\n/** Snowflake's widest `NUMBER`. */\nexport const SNOWFLAKE_MAX_PRECISION = 38;\n\n/** A string literal: Snowflake reads a backslash in one as an escape. */\nexport const snowflakeString = (value: string): string =>\n `'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\")}'`;\n\n/** The `NUMBER(p,s)` a fixed decimal reads in: no wider than Snowflake's. */\nconst numberType = ({ precision, scale }: DecimalDescriptor): string =>\n `NUMBER(${Math.min(precision, SNOWFLAKE_MAX_PRECISION)},${scale})`;\n\n/**\n * Exact integer arithmetic on `NUMBER`: `/` widens the scale and rounds, so a\n * quotient that would round up to the next integer is taken as the exact\n * division of a multiple instead. `MOD` takes its sign from `n`.\n */\nconst SNOWFLAKE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`((${n} - MOD(${n}, ${d})) / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * `value`'s match as a function of its own: `CONTAINS`, `STARTSWITH` and\n * `ENDSWITH` are exact and case-sensitive on any operand, a column included,\n * so no pattern has to be escaped in SQL.\n */\nconst TEXT_FUNCTION: Readonly<Record<TextMatch, string>> = {\n contains: \"CONTAINS\",\n startsWith: \"STARTSWITH\",\n endsWith: \"ENDSWITH\",\n};\n\n/** One JSON path as bracket accesses; the empty path is the document. */\nfunction jsonPath(column: Sql, path: readonly string[]): Sql {\n if (path.length === 0) return column;\n const steps = path\n .map((segment) =>\n ARRAY_INDEX.test(segment)\n ? `[${segment}]`\n : `[${snowflakeString(segment)}]`\n )\n .join(\"\");\n return sql`(${column})${sql.raw(steps)}`;\n}\n\n/** A SQL NULL inside an `ARRAY_CONSTRUCT` would be `undefined`, not JSON null. */\nconst jsonMember = (value: Sql): Sql =>\n sql`COALESCE(TO_VARIANT(${value}), PARSE_JSON('null'))`;\n\nfunction jsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw(\"OBJECT_CONSTRUCT()\");\n return sql`OBJECT_CONSTRUCT_KEEP_NULL(${sql.join(\n pairs.map(\n ([key, value]) => sql`${sql.raw(snowflakeString(key))}, ${value}`\n ),\n \", \"\n )})`;\n}\n\n/** A semi-structured operand: the JSON text, parsed by Snowflake. */\nconst parsedJson = (value: unknown): Sql =>\n sql`PARSE_JSON(${stringifyJson(value)})`;\n\n/**\n * A list's members with a number's text read as that number: the engine binds\n * a `bigint` or `decimal` member as its exact digits, a string, while a\n * Snowflake ARRAY holds numbers; parsed, `\"9007199254740993\"` is that exact\n * number. Any other member stays as it is: a string's text that reads as\n * other JSON (`\"foo\"` with its quotes, `[1]`, `true`) is still that string.\n */\nconst parsedMembers = (values: Sql): Sql =>\n sql`TRANSFORM(${values}, member VARIANT -> IFF(TYPEOF(TRY_PARSE_JSON(member::VARCHAR)) IN ('INTEGER', 'DECIMAL', 'DOUBLE'), TRY_PARSE_JSON(member::VARCHAR), member))`;\n\n/** Some member of `values`, as it is or as its text reads, is in `column`. */\nconst overlaps = (column: Sql, values: Sql): Sql =>\n sql`(ARRAYS_OVERLAP(${column}, ${values}) OR ARRAYS_OVERLAP(${column}, ${parsedMembers(values)}))`;\n\n/** Every member of the JSON array `values` is a member of `column`. */\nconst containsEvery = (column: Sql, values: Sql): Sql =>\n sql`(ARRAY_SIZE(ARRAY_EXCEPT(ARRAY_DISTINCT(${values}), ${column})) = 0)`;\n\n/**\n * A recursive walk, which every recursive filter lowers to: Snowflake refuses\n * the one VibORM writes (a correlated anchor, `UNION`), measured as \"is an\n * invalid Recursive CTE\". Refused while the statement is built, so nothing\n * is sent, whether the filter is the caller's or a permission rule's.\n */\nfunction noRecursion(): never {\n throw new UnsupportedOperationError(\n \"Snowflake reads a relation without recursion. Read it with a second query, or with $queryRaw.\",\n { meta: { dialect: \"snowflake\", feature: \"recursion\" } }\n );\n}\n\n/** A statement Snowflake has no spelling for, asked only of a write. */\nfunction noSpelling(statement: string): never {\n throw new FeatureNotSupportedError(\n \"snowflake\",\n statement,\n \"VibORM only reads Snowflake, which has no such statement here.\"\n );\n}\n\n/**\n * A timestamp ending a VARIANT's text (`2024-01-02 03:04:05.678 -0800`) or a\n * nanosecond ISO instant, as the provider timestamp grammar reads it: the\n * fraction cut to microseconds and the offset joined to the clock.\n */\nconst VARIANT_TIMESTAMP =\n /^(\\d{4,}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(?:\\.(\\d+))?(?: ?(Z|[+-]\\d{2}:?\\d{2}))?$/;\n\n/**\n * A TIME as the driver answers it (`12:34:56.120000000`, nine digits) without\n * its fraction's trailing zeros (`12:34:56.12`): the provider time grammar\n * holds six digits, and VibORM's time milliseconds. A digit past the\n * millisecond that is not zero stays, and the time decoder refuses it.\n */\nexport function normalizeSnowflakeTime(value: string): string {\n return value.includes(\".\") ? value.replace(FRACTION_ZEROS, \"\") : value;\n}\n\nconst FRACTION_ZEROS = /\\.?0+$/;\n\nexport function normalizeSnowflakeTimestamp(value: string): string {\n const match = VARIANT_TIMESTAMP.exec(value);\n if (!match) return value;\n const [, date, clock, fraction, zone] = match;\n const micros = fraction ? `.${fraction.slice(0, 6)}` : \"\";\n return `${date}T${clock}${micros}${zone ?? \"Z\"}`;\n}\n\n/**\n * GeoPoint on `GEOGRAPHY`: `ST_MAKEPOINT`, `ST_X`/`ST_Y`, the shared exact\n * coordinate predicates, `ST_INTERSECTS` with a GeoJSON polygon (geodesic\n * edges, boundary included, holes excluded, measured on a real account), and\n * the haversine distance PostgreSQL spells, on the same fixed radius, so the\n * metres agree across providers.\n */\nfunction createSnowflakeGeoPointSql(\n operators: Parameters<typeof createGeoPointCoordinatePredicates>[2]\n): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point})`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_MAKEPOINT(${pointLongitude}, ${pointLatitude})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(longitude, latitude, operators),\n withinPolygon: (point, polygon) =>\n sql`ST_INTERSECTS(TO_GEOGRAPHY(${geoPolygonJson(polygon)}), ${point})`,\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // LEAST/GREATEST would answer NULL for a NULL point anyway; the arm\n // says it where a reader looks for it.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS FLOAT) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n}\n\nexport class SnowflakeAdapter implements DatabaseAdapter {\n /**\n * The schema persistent objects are qualified with, exactly as the\n * catalog spells it, or absent: unqualified names then resolve in the\n * session's schema, which the driver states on every request.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n if (\n namespace !== undefined &&\n (typeof namespace !== \"string\" || namespace.length === 0)\n )\n throw new TypeError(\n \"A Snowflake namespace is a schema name: a non-empty string.\"\n );\n Object.defineProperty(this, \"namespace\", {\n value: namespace,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n this.identifiers = createIdentifiers(quoteIdent, namespace, true);\n // A GeoPoint is a GEOGRAPHY point: WGS 84, VibORM's own EPSG:4326.\n installGeoPointSql(this, createSnowflakeGeoPointSql(this.operators));\n installAdapterInternals(this, {\n batchRefs: SNOWFLAKE_BATCH_REFS,\n constraints: createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n ),\n select: this.#select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n // An instant: the driver binds a `Date` as `TIMESTAMP_TZ` at UTC, which\n // compares against every timestamp column kind in the UTC session.\n dateTime: (iso: string): Sql => sql`${new Date(iso)}`,\n\n true: (): Sql => sql.raw(\"TRUE\"),\n false: (): Sql => sql.raw(\"FALSE\"),\n\n json: parsedJson,\n\n // Snowflake's NUMBER holds 38 digits, so NUMBER(38,s) holds 38 - s of\n // them before the point: an operand that fits is exact there, and one\n // that does not is refused rather than rounded or failed by the cast.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql => {\n const text = encodePhysicalDecimal(canonical, descriptor, \"text\");\n const whole = text\n .replace(\"-\", \"\")\n .split(\".\")[0]!\n .replace(LEADING_ZEROS, \"\");\n if (\n descriptor.scale >= SNOWFLAKE_MAX_PRECISION ||\n whole.length > SNOWFLAKE_MAX_PRECISION - descriptor.scale\n )\n throw new UnsupportedOperationError(\n `Snowflake's NUMBER holds ${SNOWFLAKE_MAX_PRECISION} digits, and the decimal ${canonical} at scale ${descriptor.scale} needs more: no stored value can be compared with it.`,\n { meta: { dialect: \"snowflake\", scalarType: \"decimal\" } }\n );\n return sql`CAST(${text} AS ${sql.raw(numberType(descriptor))})`;\n },\n\n // A text-stored identifier compares as text and a byte-stored one as the\n // binary parameter blobs bind; Snowflake has no UUID type.\n id: (physical: string | Uint8Array): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`CONTAINS(${column}, ${value})`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`STARTSWITH(${column}, ${value})`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`ENDSWITH(${column}, ${value})`,\n // Snowflake folds case with its own `LOWER`, Unicode-aware.\n insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n sql`${sql.raw(TEXT_FUNCTION[kind])}(LOWER(${column}), LOWER(${value}))`,\n // A constant `LIKE 'abc%'` is what Snowflake prunes micro-partitions on.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\'`,\n\n exactTextEq: (column: Sql, value: Sql): Sql => sql`${column} = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n\n in: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql => sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n ...createRangeOperators(),\n ...createLogicalOperators(this.literals.true, this.literals.false),\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n // Without a column collation Snowflake compares text by its bytes.\n caseSensitiveText: (expr: Sql): Sql => expr,\n caseFold: (expr: Sql): Sql => sql`LOWER(${expr})`,\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 integerDivide: (left: Sql, right: Sql): Sql =>\n SNOWFLAKE_INTEGERS.quotient(left, right),\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(numberType(descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`TO_BINARY(${expr}, 'HEX')`\n : sql`CAST(${expr} AS VARCHAR)`,\n\n cast: (expr: Sql, type: CastType): Sql =>\n sql`CAST(${expr} AS ${sql.raw(CAST_TYPES[type])})`,\n\n blobToHex: (expr: Sql): Sql => sql`HEX_ENCODE(${expr}, 0)`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'inf'::FLOAT\"),\n\n // An integer column's AVG is a NUMBER whose scale Snowflake chooses; the\n // public `_avg` is a double.\n avg: (expr: Sql): Sql => sql`CAST(AVG(${expr}) AS FLOAT)`,\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOLAND_AGG(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOLOR_AGG(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(SNOWFLAKE_INTEGERS, column, descriptor),\n\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(\n SNOWFLAKE_MAX_PRECISION\n ),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`(${left}) = (${right})`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n // A double inside a VARIANT prints with 16 significant digits, one short\n // of what reads every double back: it travels as its own shortest text\n // (`0.30000000000000004`), which every number decoder reads.\n number: (expression: Sql): Sql => sql`TO_VARCHAR(${expression})`,\n object: jsonObject,\n array: (items: Sql[]): Sql =>\n sql`ARRAY_CONSTRUCT(${sql.join(items.map(jsonMember), \", \")})`,\n emptyArray: (): Sql => sql.raw(\"ARRAY_CONSTRUCT()\"),\n agg: (expr: Sql): Sql =>\n sql`COALESCE(ARRAY_AGG(${expr}), ARRAY_CONSTRUCT())`,\n objectFromColumns: jsonObject,\n extract: jsonPath,\n extractText: (column: Sql, path: string[]): Sql =>\n sql`TO_VARCHAR(${jsonPath(column, path)})`,\n // NULL for any member that is not a number. A CAST under a CASE on its\n // TYPEOF is not enough: Snowflake may evaluate the CAST first, and fails\n // on an array (measured).\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`AS_DOUBLE(${jsonPath(column, path)})`,\n // Without a collation Snowflake orders text by code point already.\n stringAtPath: (column: Sql, path: string[]): Sql =>\n this.json.foldableStringAtPath(column, path),\n foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const value = jsonPath(column, path);\n return sql`(CASE WHEN TYPEOF(${value}) = 'VARCHAR' THEN TO_VARCHAR(${value}) END)`;\n },\n contains: (target: Sql, value: Sql): Sql =>\n sql`(IS_ARRAY(${target}) AND ${containsEvery(sql`${target}::ARRAY`, sql`${value}::ARRAY`)})`,\n lastElement: (target: Sql): Sql =>\n sql`GET(${target}, ARRAY_SIZE(${target}) - 1)`,\n value: parsedJson,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql =>\n sql`ARRAY_CONSTRUCT(${sql.join(items.map(jsonMember), \", \")})`,\n value: (values: unknown[]): Sql => sql`${parsedJson(values)}::ARRAY`,\n enumValue: (values: unknown[]): Sql => sql`${parsedJson(values)}::ARRAY`,\n // A list member compared as it is bound and as its text reads, so a\n // number list matches the exact text a bigint or decimal binds as\n // (measured: ARRAY_CONTAINS of the text found no number).\n has: (column: Sql, value: Sql): Sql =>\n overlaps(column, sql`ARRAY_CONSTRUCT(${value})`),\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(ARRAY_SIZE(ARRAY_EXCEPT(${parsedMembers(\n sql`ARRAY_EXCEPT(ARRAY_DISTINCT(${values}), ${column})`\n )}, ${column})) = 0)`,\n hasSome: overlaps,\n isEmpty: (column: Sql): Sql =>\n sql`(ARRAY_SIZE(${column}) = 0 OR ${column} IS NULL)`,\n // Each member as exact text, so no JSON number rounds it on the way.\n exactNumericProjection: (column: Sql): Sql =>\n sql`TRANSFORM(${column}, member VARIANT -> TO_VARCHAR(member))`,\n length: (column: Sql): Sql => sql`ARRAY_SIZE(${column})`,\n get: (column: Sql, index: Sql): Sql => sql`GET(${column}, ${index})`,\n push: (column: Sql, value: Sql): Sql =>\n sql`ARRAY_APPEND(${column}, ${value})`,\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`ARRAY_CAT(ARRAY_APPEND(ARRAY_SLICE(${column}, 0, ${index}), ${value}), ARRAY_SLICE(${column}, ${index} + 1, ARRAY_SIZE(${column})))`,\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 /**\n * The spellings a nested relation read takes here (`SnowflakeQueries`\n * decides its structure): rows numbered per key, a page kept by its\n * numbers, an ordered aggregate and its first member, and the text a\n * timestamp or a date travels as inside a document.\n */\n relations = {\n rank: (partition: readonly Sql[], order: Sql | undefined): Sql =>\n sql`ROW_NUMBER() OVER (PARTITION BY ${sql.join(partition, \", \")} ORDER BY ${order ?? sql.raw(\"1\")})`,\n qualify: (select: Sql, condition: Sql): Sql =>\n sql`${select} QUALIFY ${condition}`,\n arrayAgg: (value: Sql, order: Sql | undefined): Sql =>\n order\n ? sql`ARRAY_AGG(${value}) WITHIN GROUP (ORDER BY ${order})`\n : sql`ARRAY_AGG(${value})`,\n first: (array: Sql): Sql => sql`GET(${array}, 0)`,\n timestampText: (column: Sql): Sql =>\n sql`TO_VARCHAR(CAST(${column} AS TIMESTAMP_TZ), 'YYYY-MM-DD\"T\"HH24:MI:SS.FF3TZH:TZM')`,\n dateText: (column: Sql): Sql => sql`TO_VARCHAR(${column}, 'YYYY-MM-DD')`,\n /**\n * A time as {@link normalizeSnowflakeTime} spells the driver's: its nine\n * digits without their trailing zeros. A VARIANT drops a TIME's fraction\n * (`12:34:56.123456789` prints `\"12:34:56\"`, measured).\n */\n timeText: (column: Sql): Sql =>\n sql`RTRIM(RTRIM(TO_VARCHAR(${column}, 'HH24:MI:SS.FF9'), '0'), '.')`,\n /**\n * A vector as the JSON text of its members, each the exact double its\n * float32 widens to (`0.10000000149011612`): the SQL API prints a VECTOR\n * with six decimals, and a VARIANT prints a double with sixteen digits,\n * both short of it. The vector decoder parses the text, flat or carried.\n */\n vectorText: (column: Sql): Sql =>\n sql`('[' || ARRAY_TO_STRING(TRANSFORM(CAST(${column} AS ARRAY), member VARIANT -> TO_VARCHAR(member::FLOAT)), ',') || ']')`,\n /**\n * A point as its two coordinates, each a JSON number parsed from the\n * double's shortest text, so no VARIANT print rounds it; NULL stays NULL.\n */\n pointObject: (column: Sql): Sql =>\n sql`IFF(${column} IS NULL, NULL, OBJECT_CONSTRUCT_KEEP_NULL('longitude', PARSE_JSON(TO_VARCHAR(ST_X(${column}))), 'latitude', PARSE_JSON(TO_VARCHAR(ST_Y(${column})))))`,\n };\n\n /** `LIMIT NULL OFFSET n`: Snowflake has no bare `OFFSET`. */\n noLimitValue = sql.raw(\"NULL\");\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(SNOWFLAKE_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(SNOWFLAKE_INTEGERS, column, by, target.decimal)\n : target?.integer\n ? sql`${column} = ${SNOWFLAKE_INTEGERS.quotient(column, by)}`\n : sql`${column} = ${column} / ${by}`,\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ARRAY_CAT(COALESCE(${column}, ARRAY_CONSTRUCT()), ${values})`,\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ARRAY_CAT(${values}, COALESCE(${column}, ARRAY_CONSTRUCT()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #select = (parts: QueryParts): Sql =>\n // Snowflake has no `DISTINCT ON`: a distinct page keeps each group's\n // first row by `ROW_NUMBER()`, as MySQL and SQLite do.\n parts.distinct\n ? assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n )\n : assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n // Snowflake takes no row lock a read could ask for.\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n\n // Every walk is this one: Snowflake shares no relation body, so none is a\n // recursive member of a statement's WITH list.\n cte: DatabaseAdapter[\"cte\"] = {\n ...createCteBuilders(quoteIdent),\n recursive: noRecursion,\n };\n\n mutations = {\n // Snowflake enforces no unique key, so there is no duplicate to skip.\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} SELECT NULL WHERE FALSE`,\n ...createMutationCommands(),\n returning: (): Sql => noSpelling(\"RETURNING\"),\n onConflict: (): Sql => noSpelling(\"ON CONFLICT\"),\n onConflictUpdate: (): Sql => noSpelling(\"ON CONFLICT\"),\n insertAbsent: (): Sql[] => noSpelling(\"ON CONFLICT\"),\n skipDuplicates: (): { prefix: Sql; suffix: Sql } =>\n noSpelling(\"ON CONFLICT\"),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / IFF(EXISTS (${query}), 1, 0) AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / IFF(NOT EXISTS (${query}), 1, 0) AS \"__viborm_assert__\"`,\n };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: false,\n supportsCteWithMutations: false,\n supportsFullOuterJoin: true,\n // Snowflake refuses most correlated inline views; nothing reads through one.\n supportsLateralJoins: false,\n supportsVector: true,\n supportsUpsertWhere: false,\n supportsTargetedUpsert: false,\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n };\n\n lastInsertId = (): Sql => noSpelling(\"LAST_INSERT_ID\");\n\n joins = {\n ...createCoreJoins(),\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n /**\n * `VECTOR(FLOAT, n)`: an operand is its JSON array cast into the column's\n * type. Snowflake has no vector index, so every order is exact, whatever\n * key the engine asks for.\n */\n vector = {\n literal: (values: number[]): Sql =>\n sql`CAST(PARSE_JSON(${JSON.stringify(values)}) AS ARRAY)::VECTOR(FLOAT, ${sql.raw(String(values.length))})`,\n l2: (column: Sql, vector: Sql): Sql =>\n sql`VECTOR_L2_DISTANCE(${column}, ${vector})`,\n // A zero vector's cosine is NaN; read as NULL, as on PostgreSQL.\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(1 - VECTOR_COSINE_SIMILARITY(${column}, ${vector}), 'NaN'::FLOAT)`,\n };\n\n result: DatabaseAdapter[\"result\"] = {\n parseResult: passThroughParseResult,\n // The driver parses every semi-structured value it reads.\n parseRelation: (_value: unknown, next: (value?: unknown) => unknown) =>\n next(),\n // A timestamp inside a VARIANT keeps Snowflake's own text; a top-level\n // one arrives as a nanosecond ISO instant. Both cross to the provider\n // timestamp grammar here, where the leaf says it is a timestamp.\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n if (scalarType === \"datetime\" && typeof value === \"string\")\n return next(normalizeSnowflakeTimestamp(value));\n if (scalarType === \"time\" && typeof value === \"string\")\n return next(normalizeSnowflakeTime(value));\n return next();\n },\n };\n}\n\nconst CAST_TYPES: Readonly<Record<CastType, string>> = {\n text: \"VARCHAR\",\n integer: \"INTEGER\",\n bigint: \"NUMBER(38,0)\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMBER(38,10)\",\n};\n\n/** Snowflake keeps no batch scratch: VibORM writes nothing there. */\nconst SNOWFLAKE_BATCH_REFS: BatchReferenceSqlAdapter = {\n setup: () => noSpelling(\"batch references\"),\n cleanup: () => noSpelling(\"batch references\"),\n store: () => noSpelling(\"batch references\"),\n read: () => noSpelling(\"batch references\"),\n};\n","/**\n * How the driver authenticates to Snowflake's SQL API, with WebCrypto only, so\n * the same code signs in Node, Bun, a Worker and a Durable Object.\n *\n * Key-pair authentication signs a JWT with the user's RSA private key\n * (docs.snowflake.com/en/developer-guide/sql-api/authenticating):\n *\n * - `iss` is `ACCOUNT.USER.SHA256:<fingerprint>`, the fingerprint being the\n * base64 SHA-256 of the public key's DER `SubjectPublicKeyInfo`;\n * - `sub` is `ACCOUNT.USER`, both upper-cased, the account without its region\n * or any part after a period;\n * - the token is valid for at most an hour, so it is renewed a minute before.\n *\n * WebCrypto cannot export a public key from a private one, so the public key\n * is rebuilt from the private key's JWK modulus and exponent.\n *\n * An OAuth or programmatic access token is sent as given, or asked of the\n * caller's function on each request, which is where a refresh belongs.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\nexport type SnowflakeTokenType =\n | \"KEYPAIR_JWT\"\n | \"OAUTH\"\n | \"PROGRAMMATIC_ACCESS_TOKEN\";\n\nexport interface SnowflakeCredentials {\n readonly account: string;\n readonly username?: string;\n /** PKCS#8 (`BEGIN PRIVATE KEY`) or PKCS#1 (`BEGIN RSA PRIVATE KEY`) PEM, or a key you imported, extractable. */\n readonly privateKey?: string | CryptoKey;\n /** An OAuth or programmatic access token, or a function answering one. */\n readonly token?: string | (() => string | Promise<string>);\n readonly tokenType?: Exclude<SnowflakeTokenType, \"KEYPAIR_JWT\">;\n}\n\nexport interface Authorization {\n readonly token: string;\n readonly type: SnowflakeTokenType;\n}\n\nconst LIFETIME_SECONDS = 3600;\nconst RENEW_BEFORE_SECONDS = 60;\nconst RSA = { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" } as const;\nconst PEM = /-----BEGIN ([A-Z ]+)-----([\\s\\S]*?)-----END \\1-----/;\nconst PADDING = /=+$/;\nconst PLUS = /\\+/g;\nconst SLASH = /\\//g;\n\nfunction configuration(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"snowflake\", operation: \"configuration\" },\n });\n}\n\nfunction base64ToBytes(text: string): Uint8Array<ArrayBuffer> {\n const binary = atob(text.replace(/\\s+/g, \"\"));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++)\n bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nconst base64Url = (bytes: Uint8Array): string =>\n bytesToBase64(bytes)\n .replace(PADDING, \"\")\n .replace(PLUS, \"-\")\n .replace(SLASH, \"_\");\n\nconst utf8 = (text: string): Uint8Array<ArrayBuffer> =>\n new Uint8Array(new TextEncoder().encode(text));\n\n/** One DER length. */\nfunction derLength(length: number): number[] {\n if (length < 0x80) return [length];\n const bytes: number[] = [];\n for (let rest = length; rest > 0; rest = Math.floor(rest / 256))\n bytes.unshift(rest % 256);\n return [0x80 + bytes.length, ...bytes];\n}\n\nfunction der(tag: number, content: Uint8Array): Uint8Array<ArrayBuffer> {\n const head = [tag, ...derLength(content.length)];\n const out = new Uint8Array(head.length + content.length);\n out.set(head);\n out.set(content, head.length);\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(\n parts.reduce((size, part) => size + part.length, 0)\n );\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n}\n\n/** `AlgorithmIdentifier { rsaEncryption, NULL }`. */\nconst RSA_ALGORITHM = new Uint8Array([\n 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,\n 0x05, 0x00,\n]);\n\n/** A PKCS#1 `RSAPrivateKey` wrapped as the PKCS#8 WebCrypto imports. */\nexport function pkcs1ToPkcs8(pkcs1: Uint8Array): Uint8Array<ArrayBuffer> {\n return der(\n 0x30,\n concat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALGORITHM, der(0x04, pkcs1))\n );\n}\n\n/** The private key a PEM holds, as the PKCS#8 bytes WebCrypto imports. */\nexport function privateKeyBytes(pem: string): Uint8Array<ArrayBuffer> {\n // An environment variable often holds the PEM's line breaks as \"\\n\".\n const match = PEM.exec(pem.replaceAll(\"\\\\n\", \"\\n\"));\n if (!match)\n throw configuration(\n \"The Snowflake private key must be a PEM block: -----BEGIN PRIVATE KEY----- (PKCS#8) or -----BEGIN RSA PRIVATE KEY----- (PKCS#1).\"\n );\n const [, label, body] = match;\n if (label === \"PRIVATE KEY\") return base64ToBytes(body!);\n if (label === \"RSA PRIVATE KEY\") return pkcs1ToPkcs8(base64ToBytes(body!));\n if (label === \"ENCRYPTED PRIVATE KEY\")\n throw configuration(\n \"The Snowflake private key is encrypted. Decrypt it first (openssl pkcs8 -in key.p8 -out key.pem), or import it yourself and pass the CryptoKey, extractable.\"\n );\n throw configuration(`A \"${label}\" PEM block is not an RSA private key.`);\n}\n\n/** The account as a JWT names it: upper-cased, without region or suffix. */\nexport function jwtAccount(account: string): string {\n return account.split(\".\")[0]!.toUpperCase();\n}\n\nasync function importPrivateKey(key: string | CryptoKey): Promise<CryptoKey> {\n if (typeof key !== \"string\") return key;\n try {\n return await crypto.subtle.importKey(\n \"pkcs8\",\n privateKeyBytes(key),\n RSA,\n true,\n [\"sign\"]\n );\n } catch (error) {\n if (error instanceof ClientInitializationError) throw error;\n throw configuration(\n `The Snowflake private key could not be imported as an RSA key: ${error instanceof Error ? error.message : String(error)}.`\n );\n }\n}\n\n/** `SHA256:` and the base64 SHA-256 of the public key's DER encoding. */\nexport async function publicKeyFingerprint(key: CryptoKey): Promise<string> {\n if (!key.extractable)\n throw configuration(\n \"The Snowflake private key's CryptoKey is not extractable: the driver reads its modulus and exponent to compute the fingerprint Snowflake checks. Import it with extractable set to true, or pass the PEM.\"\n );\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n const publicKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"RSA\", n: jwk.n, e: jwk.e, ext: true },\n RSA,\n true,\n [\"verify\"]\n );\n const spki = new Uint8Array(await crypto.subtle.exportKey(\"spki\", publicKey));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", spki));\n return `SHA256:${bytesToBase64(digest)}`;\n}\n\n/** One signed key-pair JWT, issued at `now` (seconds). */\nexport async function signKeyPairJwt(\n account: string,\n username: string,\n key: CryptoKey,\n now: number,\n fingerprint?: string\n): Promise<string> {\n const subject = `${jwtAccount(account)}.${username.toUpperCase()}`;\n const payload = {\n iss: `${subject}.${fingerprint ?? (await publicKeyFingerprint(key))}`,\n sub: subject,\n iat: now,\n exp: now + LIFETIME_SECONDS,\n };\n const signingInput = `${base64Url(utf8(JSON.stringify({ alg: \"RS256\", typ: \"JWT\" })))}.${base64Url(utf8(JSON.stringify(payload)))}`;\n const signature = new Uint8Array(\n await crypto.subtle.sign(RSA, key, utf8(signingInput))\n );\n return `${signingInput}.${base64Url(signature)}`;\n}\n\n/**\n * The Authorization a request carries. One per driver: it keeps the imported\n * key, its fingerprint and the current JWT, never anything module-wide.\n */\nexport class SnowflakeAuthenticator {\n readonly #credentials: SnowflakeCredentials;\n readonly #now: () => number;\n #key: Promise<{ key: CryptoKey; fingerprint: string }> | undefined;\n #jwt: { token: string; renewAt: number } | undefined;\n\n constructor(credentials: SnowflakeCredentials, now = () => Date.now()) {\n const { privateKey, token, username } = credentials;\n if ((privateKey === undefined) === (token === undefined))\n throw configuration(\n \"Snowflake needs exactly one credential: a privateKey (with a username) for key-pair authentication, or a token for OAuth.\"\n );\n if (privateKey !== undefined && !username)\n throw configuration(\n \"Snowflake key-pair authentication needs the username the key belongs to.\"\n );\n this.#credentials = credentials;\n this.#now = now;\n }\n\n async authorization(): Promise<Authorization> {\n const { token, tokenType } = this.#credentials;\n if (token !== undefined) {\n const value = typeof token === \"function\" ? await token() : token;\n if (typeof value !== \"string\" || value.length === 0)\n throw configuration(\"The Snowflake token function answered no token.\");\n return { token: value, type: tokenType ?? \"OAUTH\" };\n }\n const now = Math.floor(this.#now() / 1000);\n if (this.#jwt && now < this.#jwt.renewAt)\n return { token: this.#jwt.token, type: \"KEYPAIR_JWT\" };\n this.#key ??= importPrivateKey(this.#credentials.privateKey!).then(\n async (key) => ({ key, fingerprint: await publicKeyFingerprint(key) })\n );\n let imported: { key: CryptoKey; fingerprint: string };\n try {\n imported = await this.#key;\n } catch (error) {\n this.#key = undefined;\n throw error;\n }\n const jwt = await signKeyPairJwt(\n this.#credentials.account,\n this.#credentials.username!,\n imported.key,\n now,\n imported.fingerprint\n );\n this.#jwt = {\n token: jwt,\n renewAt: now + LIFETIME_SECONDS - RENEW_BEFORE_SECONDS,\n };\n return { token: jwt, type: \"KEYPAIR_JWT\" };\n }\n}\n","/**\n * Snowflake's reads: the SQL backend's, with one form changed.\n *\n * The SQL backend reads a relation as a correlated subquery over a correlated\n * page (`(SELECT json_agg(…) FROM (SELECT … WHERE parent.id = child.fk ORDER\n * BY … LIMIT n) AS page)`). Snowflake refuses both halves of that: a `LIMIT`\n * is allowed only in an uncorrelated subquery, and a derived table may not\n * read an outer row (`Unsupported subquery type cannot be evaluated`). What it\n * does evaluate is a correlated scalar subquery that is an aggregate, whose\n * correlation is an equality in its own `WHERE`\n * (docs.snowflake.com/en/user-guide/querying-subqueries): it decorrelates\n * that into a grouped join.\n *\n * So a relation here is read from an UNCORRELATED page, which projects the\n * key it joins its parent on and windows itself per key, and only the\n * aggregate around it is correlated:\n *\n * ```sql\n * (SELECT COALESCE(ARRAY_AGG(OBJECT_CONSTRUCT_KEEP_NULL('id', \"p\".\"id\", …))\n * WITHIN GROUP (ORDER BY \"p\".\"$rn\"), ARRAY_CONSTRUCT())\n * FROM (SELECT \"c\".\"id\", …, \"c\".\"authorId\" AS \"$k0\",\n * ROW_NUMBER() OVER (PARTITION BY \"c\".\"authorId\" ORDER BY …) AS \"$rn\"\n * FROM \"posts\" AS \"c\" WHERE …\n * QUALIFY \"$rn\" <= 2) AS \"p\"\n * WHERE \"p\".\"$k0\" = \"parent\".\"id\")\n * ```\n *\n * A deeper relation is the same form inside the page's own select list,\n * correlated to the page's row. Every other part of a read — the root page,\n * filters (`EXISTS` correlated in a `WHERE` is supported), `_count`,\n * aggregates and groups — is the SQL backend's, through the Snowflake\n * adapter.\n *\n * Refused, with a typed error before anything is sent: a nested `cursor` or\n * `distinct`, a nested order by a relation or a `_count`, a recursive\n * relation, a polymorphic slot and a junction's `$through` row; a root\n * `cursor` whose order is not the model's single-field key alone.\n */\n\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport type { SnowflakeAdapter } from \"@adapters/databases/snowflake/snowflake-adapter\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport type {\n Leaf,\n PreparedDomain,\n PreparedProjection,\n PreparedProjectionField,\n PreparedRelationProjection,\n ProjectionShape,\n Queries,\n Read,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { CallScope } from \"@query-engine/raptor3/shared/row-scope\";\nimport type {\n Arguments,\n ReadOperation,\n} from \"@query-engine/raptor3/shared/schema\";\nimport { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport { physicalField } from \"@query-engine/raptor3/shared/storage\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\nimport { isRecord } from \"@validation/value-guards\";\n\n/** What a nested read on Snowflake does not express. */\nfunction refused(what: string): never {\n throw new UnsupportedOperationError(\n `Snowflake reads a relation without ${what}. Read it with a second query, or with $queryRaw.`,\n { meta: { dialect: \"snowflake\", feature: what } }\n );\n}\n\ninterface OrderKey {\n readonly expression: Sql;\n readonly descending: boolean;\n readonly nulls: \"first\" | \"last\";\n readonly nullable: boolean;\n}\n\nconst KEY = (index: number) => `$k${index}`;\nconst ORDER = (index: number) => `$o${index}`;\nconst RANK = \"$rn\";\n\nexport class SnowflakeQueries extends SqlQueries {\n declare readonly adapter: SnowflakeAdapter;\n\n /**\n * Under a domain (an extension's rows, order or permissions) the reads stay\n * Snowflake's: the SQL backend's `under` answers its own class.\n */\n override under(domain: PreparedDomain, call?: CallScope): Queries {\n return new SnowflakeQueries(\n this.schema,\n this.adapter,\n this.result,\n domain,\n call\n );\n }\n\n /**\n * A root `cursor` ordered by the model's single-field key alone (the\n * caller's order, else the one an extension gives the model): the SQL\n * backend then compares that key with one uncorrelated scalar subquery,\n * which Snowflake evaluates (measured, ascending and descending, with\n * `distinct` too). A longer order compares a row of keys with a\n * multi-column subquery, which it refuses (\"Scalar subquery with\n * multi-column SELECT clause\").\n */\n override read(\n model: AnyModel,\n operation: ReadOperation,\n args: Arguments\n ): Read {\n if (args.cursor !== undefined && !this.#keyedCursor(model, args))\n throw new UnsupportedOperationError(\n \"Snowflake pages with a cursor only in the order of the model's single-field key, alone. Order by that key, or page with skip.\",\n { meta: { dialect: \"snowflake\", feature: \"cursor\" } }\n );\n return super.read(model, operation, args);\n }\n\n #keyedCursor(\n model: AnyModel,\n { cursor, orderBy }: Pick<Arguments, \"cursor\" | \"orderBy\">\n ): boolean {\n const [key, ...more] = this.keyOrder(model);\n if (key === undefined || more.length > 0) return false;\n const order = orderBy ?? this.defaultOrder(model);\n const terms = Array.isArray(order) ? order : order ? [order] : [];\n // One term at most: the key twice is two comparisons, a row again.\n return (\n terms.length <= 1 &&\n [cursor, ...terms].every(\n (term) =>\n isRecord(term) && Object.keys(term).every((field) => field === key)\n )\n );\n }\n\n override lowerProjection(\n projection: PreparedProjection,\n alias?: string,\n visible = false\n ): Sql[] {\n const a = this.adapter;\n return projection.fields.map((field) => {\n if (field.kind === \"relation\")\n return a.identifiers.aliased(\n this.#relation(field, alias ?? \"\"),\n field.name\n );\n if (field.kind === \"variants\") refused(\"a polymorphic slot\");\n // A vector and a point are spelled exactly here: the SQL backend's\n // projections would read them through prints that round them.\n const type =\n field.kind === \"scalar\"\n ? physicalField(this.schema, projection.model, field.name).scalar[\"~\"]\n .state.type\n : undefined;\n if (type === \"vector\" || type === \"point\") {\n const column = this.column(projection.model, field.name, alias);\n return a.identifiers.aliased(\n type === \"vector\"\n ? a.relations.vectorText(column)\n : a.relations.pointObject(column),\n field.name\n );\n }\n return super.lowerProjection(\n { ...projection, fields: [field] },\n alias,\n visible\n )[0]!;\n });\n }\n\n /** One relation of the row at `parentAlias`, as one aggregate value. */\n #relation(\n field: Extract<PreparedProjectionField, { kind: \"relation\" }>,\n parentAlias: string\n ): Sql {\n const relation: PreparedRelationProjection = field;\n const { edge, arguments: nested, projection } = relation;\n if (relation.recurrence) refused(\"recursion\");\n if (relation.linkRow || relation.linkWhere) refused(\"its $through row\");\n if (edge.discriminator) refused(\"a polymorphic slot\");\n if (nested.cursor !== undefined) refused(\"a cursor\");\n if (nested.distinct?.length) refused(\"distinct\");\n\n const a = this.adapter;\n const childAlias = this.alias();\n const columns = this.lowerProjection(projection, childAlias, true);\n const where: Sql[] = [];\n let from: Sql;\n let joins: Sql[] | undefined;\n // The child's side of each key pair, and the parent column it equals.\n const keys: [child: Sql, parent: Sql][] = [];\n if (edge.kind === \"reference\") {\n from = this.table(edge.target, childAlias);\n for (const pair of edge.pairs)\n keys.push([\n this.column(edge.target, pair.target, childAlias),\n this.column(edge.source, pair.source, parentAlias),\n ]);\n } else {\n const link = this.alias();\n from = a.identifiers.table(edge.table, link);\n joins = [\n a.joins.inner(\n this.table(edge.target, childAlias),\n a.operators.and(\n ...this.junctionSideConditions(edge.targetSide, link, childAlias)\n )\n ),\n ];\n for (const pair of edge.sourceSide.members)\n keys.push([\n a.identifiers.column(link, pair.junctionField),\n this.column(edge.source, pair.referencedField, parentAlias),\n ]);\n }\n // The related domain enters where the SQL backend's `correlation` puts\n // it: on the target row, outside any quantifier.\n const domain = this.domainOf(edge.target, \"related\");\n if (domain) where.push(this.lowerSelector(domain, childAlias)!);\n if (nested.selector)\n where.push(this.lowerSelector(nested.selector, childAlias)!);\n\n const order = this.#order(edge.target, nested.orderBy, childAlias);\n // A negative `take` reads the window backwards; the decoder restores it.\n const backward = nested.take !== undefined && nested.take < 0;\n const presented = backward\n ? order.map((key) => ({\n ...key,\n descending: !key.descending,\n nulls: key.nulls === \"first\" ? (\"last\" as const) : (\"first\" as const),\n }))\n : order;\n const windowed =\n !edge.many || nested.take !== undefined || nested.skip !== undefined;\n const pageColumns = [...columns];\n for (const [index, [child]] of keys.entries())\n pageColumns.push(a.identifiers.aliased(child, KEY(index)));\n const qualify: Sql[] = [];\n if (windowed) {\n pageColumns.push(\n a.identifiers.aliased(\n a.relations.rank(\n keys.map(([child]) => child),\n this.#orderList(presented)\n ),\n RANK\n )\n );\n const rank = a.identifiers.escape(RANK);\n const skip = nested.skip ?? 0;\n if (skip > 0) qualify.push(a.operators.gt(rank, this.value(skip)));\n if (!edge.many) qualify.push(a.operators.eq(rank, this.value(1)));\n else if (nested.take !== undefined)\n qualify.push(\n a.operators.lte(rank, this.value(skip + Math.abs(nested.take)))\n );\n } else {\n for (const [index, key] of presented.entries())\n pageColumns.push(a.identifiers.aliased(key.expression, ORDER(index)));\n }\n const page = assembleAdapterSelect(a, {\n columns: sql.join(pageColumns, \", \"),\n from,\n joins,\n where: where.length === 0 ? undefined : a.operators.and(...where),\n });\n const pageAlias = this.alias();\n const qualified =\n qualify.length === 0\n ? page\n : a.relations.qualify(page, a.operators.and(...qualify));\n\n const members: [string, Sql][] = Object.entries(\n projection.shape.fields\n ).map(([name, leaf]) => [\n name,\n this.#carried(leaf, a.identifiers.column(pageAlias, name)),\n ]);\n for (const gate of projection.shape.gates ?? [])\n members.push([gate, a.identifiers.column(pageAlias, gate)]);\n const object = a.json.object(members);\n const within = windowed\n ? a.orderBy.asc(a.identifiers.column(pageAlias, RANK))\n : this.#orderList(\n presented.map((key, index) => ({\n ...key,\n expression: a.identifiers.column(pageAlias, ORDER(index)),\n }))\n );\n const aggregated = a.relations.arrayAgg(object, within);\n const read = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: edge.many ? aggregated : a.relations.first(aggregated),\n from: a.subqueries.correlate(qualified, pageAlias),\n where: a.operators.and(\n ...keys.map(([, parent], index) =>\n a.operators.eq(a.identifiers.column(pageAlias, KEY(index)), parent)\n )\n ),\n })\n );\n // Snowflake evaluates the subquery as a grouped join, so a parent with no\n // row has no group and reads NULL, whatever the aggregate would answer\n // over zero rows: the empty list is stated outside it (measured on a real\n // account, 2026-11-11).\n return edge.many ? a.expressions.coalesce(read, a.json.emptyArray()) : read;\n }\n\n /**\n * A nested page's order: the caller's scalar terms, then the target's key,\n * NULLs placed as the SQL backend's page places them.\n */\n #order(model: AnyModel, input: unknown, alias: string): OrderKey[] {\n const keys: OrderKey[] = [];\n const ordered = new Set<string>();\n const terms = Array.isArray(input) ? input : input ? [input] : [];\n for (const term of terms) {\n // Admitted by the orderBy schema already: a record of field terms.\n if (!isRecord(term)) continue;\n for (const [field, direction] of Object.entries(term)) {\n if (direction === undefined) continue;\n if (model[\"~\"].state.relations[field])\n refused(\"an order by a related row or its _count\");\n let descending: boolean;\n let nulls: \"first\" | \"last\" | undefined;\n if (direction === \"asc\" || direction === \"desc\")\n descending = direction === \"desc\";\n else if (isRecord(direction)) {\n if (direction._distance !== undefined)\n refused(\"an order by distance\");\n descending = direction.sort === \"desc\";\n if (direction.nulls === \"first\" || direction.nulls === \"last\")\n nulls = direction.nulls;\n } else continue;\n ordered.add(field);\n // An operand the caller wrote, as the backend's own order spells it:\n // a read-gated field reads NULL on a row that does not carry it.\n const column = this.column(model, field, alias);\n keys.push({\n expression:\n this.domain?.project?.guarded(this, model, field, column, alias) ??\n column,\n descending,\n nulls: nulls ?? (descending ? \"first\" : \"last\"),\n nullable:\n physicalField(this.schema, model, field).nullable ||\n this.domain?.project?.projected(model)?.gates.has(field) === true,\n });\n }\n }\n for (const field of this.keyOrder(model)) {\n if (ordered.has(field)) continue;\n keys.push({\n expression: this.column(model, field, alias),\n descending: false,\n nulls: \"last\",\n nullable: physicalField(this.schema, model, field).nullable,\n });\n }\n return keys;\n }\n\n #orderList(keys: readonly OrderKey[]): Sql | undefined {\n if (keys.length === 0) return undefined;\n const a = this.adapter;\n return sql.join(\n keys.map((key) => {\n const direction = key.descending ? \"desc\" : \"asc\";\n if (!key.nullable) return a.orderBy[direction](key.expression);\n return key.nulls === \"first\"\n ? a.orderBy.nullsFirst(key.expression, direction)\n : a.orderBy.nullsLast(key.expression, direction);\n }),\n \", \"\n );\n }\n\n /**\n * A page column carried inside the relation's document, in the spelling\n * its decoder reads: exact text for what a JSON number would round, hex for\n * bytes, and an ISO instant for a timestamp, which a VARIANT would otherwise\n * spell in the session's output format.\n */\n #carried(leaf: ProjectionShape | Leaf, column: Sql): Sql {\n const a = this.adapter;\n if (leaf.kind !== \"scalar\") return a.json.document(column);\n if (leaf.list)\n return leaf.type === \"decimal\" ||\n leaf.type === \"bigint\" ||\n leaf.type === \"number\"\n ? a.arrays.exactNumericProjection(column)\n : column;\n switch (leaf.type) {\n case \"decimal\":\n case \"bigint\":\n return a.expressions.cast(column, \"text\");\n case \"number\":\n return a.json.number(column);\n case \"datetime\":\n return a.relations.timestampText(column);\n case \"date\":\n return a.relations.dateText(column);\n case \"time\":\n return a.relations.timeText(column);\n case \"blob\":\n return a.expressions.caseWhen(\n [{ when: a.operators.isNull(column), then: a.literals.null() }],\n a.expressions.blobToHex(column)\n );\n default:\n return column;\n }\n }\n}\n","/**\n * The one refusal of a write on Snowflake.\n *\n * Snowflake enforces no `PRIMARY KEY`, `UNIQUE` or `FOREIGN KEY` (only\n * `NOT NULL`), has no savepoint and no `RETURNING`, and charges for every\n * statement a warehouse runs: the guarantees VibORM's writes give — a unique\n * row addressed, a relation that holds, a nested write that rolls back to\n * where it failed — would not hold there. So the driver reads only.\n *\n * Every operation the engine runs gets its context before its first\n * statement — to execute it, to prepare it for a batch, or to publish it as\n * one statement — so a write verb is refused here, by its name, before\n * anything is built or sent. Raw writes have no context: `refuseRawWrite`\n * answers for `$executeRaw`, which the driver asks before it sends one.\n */\n\nimport { FeatureNotSupportedError } from \"@errors\";\nimport { SqlOperationContext } from \"@query-engine/raptor3/shared/sql-operation-context\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\n\nconst REASON =\n \"VibORM only reads Snowflake: it enforces no primary, unique or foreign key, has no savepoint and no RETURNING, so a write's guarantees would not hold there. Write with Snowflake's own tools.\";\n\nexport function readOnlyRefusal(operation: string): FeatureNotSupportedError {\n return new FeatureNotSupportedError(\"snowflake\", operation, REASON);\n}\n\nexport class SnowflakeOperationContext extends SqlOperationContext {\n constructor(...args: ConstructorParameters<typeof SqlOperationContext>) {\n const operation = args[3];\n if (!isReadOperation(operation)) throw readOnlyRefusal(operation);\n super(...args);\n }\n}\n\n/** `$executeRaw` and `$executeRawUnsafe`, which state a write by their name. */\nexport function isRawWrite(operation: string | undefined): boolean {\n return operation === \"$executeRaw\" || operation === \"$executeRawUnsafe\";\n}\n","/**\n * Snowflake's SQL API v2 over `fetch`: one statement per request, so it runs\n * wherever `fetch` and WebCrypto do (Node, Bun, Workers, Durable Objects).\n *\n * docs.snowflake.com/en/developer-guide/sql-api:\n *\n * - `POST /api/v2/statements?requestId=<uuid>` runs a statement with its\n * context (warehouse, database, schema, role) and typed bindings. It answers\n * 200 with the first partition of the result, 202 while it still runs, or\n * 422 with the failure;\n * - `GET /api/v2/statements/<handle>` is asked until a 202 becomes 200 or 422\n * (429 also means \"still running\");\n * - `GET /api/v2/statements/<handle>?partition=<n>` reads partition n > 0;\n * - `POST /api/v2/statements/<handle>/cancel` stops a statement this driver\n * no longer waits for.\n *\n * A request that failed before Snowflake answered (a network error, 429 on\n * submission, 502/503/504) is sent again with the same `requestId` and\n * `retry=true`, which Snowflake runs at most once.\n */\n\nimport {\n ClientInitializationError,\n ConnectionError,\n QueryError,\n VibORMErrorCode,\n} from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { SnowflakeAuthenticator } from \"./auth\";\nimport type { SnowflakeBinding, SnowflakeColumn } from \"./values\";\n\nexport interface SnowflakeContext {\n readonly warehouse?: string;\n readonly database?: string;\n readonly schema?: string;\n readonly role?: string;\n}\n\nexport interface SnowflakeTransportOptions {\n /** `https://<account>.snowflakecomputing.com`, without a trailing slash. */\n readonly baseUrl: string;\n readonly authenticator: SnowflakeAuthenticator;\n readonly context: SnowflakeContext;\n /** Seconds a statement may run, sent to Snowflake and held by the driver. */\n readonly timeout?: number;\n /**\n * Seconds the driver alone lets a statement run, where no `timeout` is\n * sent: Snowflake keeps its own limit, which a shorter one still wins.\n */\n readonly deadline?: number;\n /** Session parameters every statement runs with. */\n readonly parameters: Readonly<Record<string, string>>;\n readonly fetch: (input: string, init: RequestInit) => Promise<Response>;\n /** First poll delay; doubles up to {@link MAX_POLL_MS}. */\n readonly pollIntervalMs?: number;\n /** Partitions read at once. */\n readonly partitionConcurrency?: number;\n /**\n * Sends of one submission before its failure is final; a status or a\n * partition read gets {@link MORE_READ_ATTEMPTS} more.\n */\n readonly attempts?: number;\n readonly userAgent?: string;\n}\n\nexport interface StatementResult {\n readonly columns: readonly SnowflakeColumn[];\n readonly rows: readonly (readonly unknown[])[];\n readonly handle: string;\n}\n\n/** An answer's JSON body, read field by field: nothing in it is trusted. */\ntype Body = Readonly<Record<string, unknown>>;\n\nfunction text(body: Body | undefined, key: string): string | undefined {\n const value = body?.[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction isColumn(value: unknown): value is SnowflakeColumn {\n return (\n isRecord(value) &&\n typeof value.name === \"string\" &&\n typeof value.type === \"string\"\n );\n}\n\nfunction isRows(value: unknown): value is unknown[][] {\n return Array.isArray(value) && value.every((row) => Array.isArray(row));\n}\n\nconst MAX_POLL_MS = 2000;\n/** How long a cancel may hold the caller's error back. */\nconst CANCEL_MS = 2000;\n/**\n * More sends for a status read than for a submission: a GET changes nothing,\n * and giving up on one leaves a statement running.\n */\nconst MORE_READ_ATTEMPTS = 3;\n\n/** A failure Snowflake answered, as the error mapping reads it. */\nexport class SnowflakeApiError extends Error {\n readonly code: string | undefined;\n readonly sqlstate: string | undefined;\n readonly status: number;\n readonly statementHandle: string | undefined;\n constructor(status: number, body: Body | undefined, fallback: string) {\n super(text(body, \"message\") ?? fallback);\n this.name = \"SnowflakeApiError\";\n this.status = status;\n this.code = text(body, \"code\");\n this.sqlstate = text(body, \"sqlState\");\n this.statementHandle = text(body, \"statementHandle\");\n }\n}\n\nfunction malformedResult(reason: string): QueryError {\n return new QueryError(\n `Snowflake answered a result VibORM cannot read: ${reason}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\" },\n }\n );\n}\n\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n\n/** `promise`, or `signal`'s reason as soon as it aborts. */\nfunction untilAborted<T>(\n promise: Promise<T>,\n signal?: AbortSignal\n): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) {\n promise.catch(() => undefined);\n return Promise.reject(signal.reason);\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n}\n\nasync function readBody(response: Response): Promise<Body | undefined> {\n const answered = await response.text();\n if (answered.length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(answered);\n return isRecord(parsed) ? parsed : { message: answered.slice(0, 500) };\n } catch {\n return { message: answered.slice(0, 500) };\n }\n}\n\nexport class SnowflakeTransport {\n readonly #options: SnowflakeTransportOptions;\n\n constructor(options: SnowflakeTransportOptions) {\n this.#options = options;\n }\n\n /** Run one statement and read every partition of its result. */\n async run(\n statement: string,\n bindings: Record<string, SnowflakeBinding> | undefined,\n signal?: AbortSignal\n ): Promise<StatementResult> {\n const { timeout } = this.#options;\n const limit = timeout ?? this.#options.deadline;\n const deadline = new AbortController();\n const timer =\n limit === undefined\n ? undefined\n : setTimeout(\n () =>\n deadline.abort(\n new QueryError(\n `The Snowflake statement ran past its ${limit} s timeout and was cancelled.`,\n {\n code: VibORMErrorCode.QUERY_TIMEOUT,\n meta: { driver: \"snowflake\" },\n }\n )\n ),\n limit * 1000\n );\n const onAbort = () => deadline.abort(signal?.reason);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n let handle: string | undefined;\n // Until Snowflake answers the statement's outcome, a failure here leaves\n // it running: it is cancelled then, whatever the failure.\n let settled = false;\n try {\n const requestId = crypto.randomUUID();\n const body = JSON.stringify({\n statement,\n ...(timeout === undefined ? {} : { timeout }),\n ...this.#options.context,\n ...(bindings ? { bindings } : {}),\n parameters: this.#options.parameters,\n });\n let answer = await this.#send(\n (attempt) =>\n `/api/v2/statements?requestId=${requestId}${attempt > 0 ? \"&retry=true\" : \"\"}`,\n { method: \"POST\", body },\n deadline.signal\n );\n handle = text(answer.body, \"statementHandle\");\n let delay = this.#options.pollIntervalMs ?? 100;\n while (answer.status === 202 || answer.status === 429) {\n if (!handle)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n \"Snowflake accepted the statement without a handle to poll.\"\n );\n await sleep(delay, deadline.signal);\n delay = Math.min(delay * 2, MAX_POLL_MS);\n answer = await this.#send(\n () => `/api/v2/statements/${encodeURIComponent(handle!)}`,\n { method: \"GET\" },\n deadline.signal\n );\n }\n settled = true;\n if (answer.status !== 200)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n `Snowflake answered HTTP ${answer.status}.`\n );\n const result = answer.body;\n const metadata = isRecord(result?.resultSetMetaData)\n ? result.resultSetMetaData\n : undefined;\n const columns = metadata?.rowType;\n const first = result?.data;\n // A result states its columns and its first partition, empty or not;\n // without them the rows are not known, and no read answers [] for them.\n if (\n !(\n metadata &&\n Array.isArray(columns) &&\n columns.every(isColumn) &&\n isRows(first)\n )\n )\n throw malformedResult(\"its rowType or its data is missing\");\n handle = text(result, \"statementHandle\") ?? handle ?? \"\";\n const partitions = Array.isArray(metadata.partitionInfo)\n ? metadata.partitionInfo.length\n : 1;\n const rows: (readonly unknown[])[] = [...first];\n if (partitions > 1)\n for (const part of await this.#partitions(\n handle,\n partitions,\n deadline.signal\n ))\n for (const row of part) rows.push(row);\n const { numRows } = metadata;\n if (typeof numRows === \"number\" && rows.length !== numRows)\n throw malformedResult(\n `it states ${numRows} rows and holds ${rows.length}`\n );\n return { columns, rows, handle };\n } catch (error) {\n if (handle && !settled) await this.cancel(handle);\n throw deadline.signal.aborted && deadline.signal.reason instanceof Error\n ? deadline.signal.reason\n : error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n\n /**\n * Stop a statement, waiting at most `CANCEL_MS` for Snowflake to say so: a\n * failure to stop it is not the caller's failure, and the caller's deadline\n * must not wait on it.\n */\n async cancel(handle: string): Promise<void> {\n try {\n await this.#request(\n `/api/v2/statements/${encodeURIComponent(handle)}/cancel`,\n { method: \"POST\" },\n AbortSignal.timeout(CANCEL_MS)\n );\n } catch {\n // The statement's own timeout ends it anyway.\n }\n }\n\n /** Partitions 1..count-1, in order, at most `partitionConcurrency` at once. */\n async #partitions(\n handle: string,\n count: number,\n signal: AbortSignal\n ): Promise<unknown[][][]> {\n const out: unknown[][][] = new Array(count - 1);\n let next = 1;\n const worker = async () => {\n while (next < count) {\n const partition = next++;\n const answer = await this.#send(\n () =>\n `/api/v2/statements/${encodeURIComponent(handle)}?partition=${partition}`,\n { method: \"GET\" },\n signal\n );\n if (answer.status !== 200)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n `Snowflake answered HTTP ${answer.status} for partition ${partition}.`\n );\n const data = answer.body?.data;\n if (!isRows(data))\n throw malformedResult(`partition ${partition} holds no data`);\n out[partition - 1] = data;\n }\n };\n const workers = Math.min(\n this.#options.partitionConcurrency ?? 4,\n count - 1\n );\n await Promise.all(Array.from({ length: workers }, worker));\n return out;\n }\n\n /**\n * One request, sent again while it failed before Snowflake answered it: a\n * network failure, a 5xx, or a 429 on a submission (the same `requestId`\n * with `retry=true` never runs a statement twice). A 4xx other than 429,\n * and every 2xx, is Snowflake's answer and is returned; a 5xx still\n * answered after the last send is a connection failure, not a refusal,\n * whose statement may have started.\n */\n async #send(\n path: (attempt: number) => string,\n init: { method: string; body?: string },\n signal: AbortSignal\n ): Promise<{ status: number; body: Body | undefined }> {\n const attempts =\n (this.#options.attempts ?? 3) +\n (init.method === \"GET\" ? MORE_READ_ATTEMPTS : 0);\n const pause = (attempt: number) =>\n sleep(Math.min(200 * 2 ** attempt, MAX_POLL_MS), signal);\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n try {\n response = await this.#request(path(attempt), init, signal);\n } catch (error) {\n if (signal.aborted || attempt + 1 >= attempts) throw error;\n await pause(attempt);\n continue;\n }\n const unanswered =\n response.status >= 500 ||\n // A 429 while polling means \"still running\", not \"send again\".\n (response.status === 429 && init.method !== \"GET\");\n if (unanswered && attempt + 1 < attempts) {\n await response.body?.cancel();\n await pause(attempt);\n continue;\n }\n if (response.status >= 500) {\n await response.body?.cancel();\n // A 5xx can follow the start of the statement (a gateway's 504):\n // its outcome is not known, and a submission's has no handle.\n throw new ConnectionError(\n init.method === \"POST\"\n ? `Snowflake answered HTTP ${response.status} to ${attempts} sends of the statement: its outcome is not known, and it may have started, with no handle to cancel it by; only Snowflake's limit for it (a timeout sent with it, else STATEMENT_TIMEOUT_IN_SECONDS) bounds it.`\n : `Snowflake answered HTTP ${response.status} to ${attempts} reads of the statement.`,\n { meta: { driver: \"snowflake\", status: response.status } }\n );\n }\n if (response.status === 401 || response.status === 403) {\n const body = await readBody(response);\n throw new ClientInitializationError(\n `Snowflake refused the credentials: ${text(body, \"message\") ?? `HTTP ${response.status}`}`,\n {\n cause: new SnowflakeApiError(response.status, body, \"unauthorized\"),\n meta: { driver: \"snowflake\", providerCode: text(body, \"code\") },\n }\n );\n }\n // The headers came; the body can still be cut off on its way, which is\n // a failed send like any other.\n let body: Body | undefined;\n try {\n body = await readBody(response);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (attempt + 1 >= attempts)\n throw new ConnectionError(\n `Snowflake's answer was cut off ${attempts} times before it ended.`,\n {\n cause: error instanceof Error ? error : undefined,\n meta: { driver: \"snowflake\" },\n }\n );\n await pause(attempt);\n continue;\n }\n return { status: response.status, body };\n }\n }\n\n async #request(\n path: string,\n init: { method: string; body?: string },\n signal?: AbortSignal\n ): Promise<Response> {\n // A token function may be slow to refresh: the request's deadline bounds\n // that wait too.\n const { token, type } = await untilAborted(\n this.#options.authenticator.authorization(),\n signal\n );\n try {\n return await this.#options.fetch(`${this.#options.baseUrl}${path}`, {\n method: init.method,\n headers: {\n Authorization: `Bearer ${token}`,\n \"X-Snowflake-Authorization-Token-Type\": type,\n Accept: \"application/json\",\n \"User-Agent\": this.#options.userAgent ?? \"viborm\",\n ...(init.body === undefined\n ? {}\n : { \"Content-Type\": \"application/json\" }),\n },\n ...(init.body === undefined ? {} : { body: init.body }),\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n if (signal?.aborted) throw signal.reason;\n throw new ConnectionError(\"Snowflake could not be reached\", {\n cause: error instanceof Error ? error : undefined,\n meta: { driver: \"snowflake\" },\n });\n }\n }\n}\n","/**\n * Values across Snowflake's SQL API, both ways, exactly.\n *\n * The API binds every parameter as a typed string\n * (docs.snowflake.com/en/developer-guide/sql-api/submitting-requests) and\n * answers every value as a string, typed by the result's `rowType`\n * (…/handling-responses). Nothing here goes through a JavaScript `number`\n * unless the value fits one exactly:\n *\n * | Snowflake | read as |\n * | ----------------------- | -------------------------------------------------- |\n * | `NUMBER(p,0)` | `number` when a safe integer, else `bigint` |\n * | `NUMBER(p,s)`, s > 0 | the decimal text (`\"12.50\"`) |\n * | `FLOAT` | `number` (`inf`, `-inf`, `NaN` included) |\n * | `TEXT` | `string` |\n * | `BOOLEAN` | `boolean` |\n * | `DATE` | `\"YYYY-MM-DD\"` |\n * | `TIME` | `\"HH:MM:SS.fffffffff\"` |\n * | `TIMESTAMP_NTZ` / `LTZ` | `\"YYYY-MM-DDTHH:MM:SS.fffffffffZ\"` (nanoseconds) |\n * | `TIMESTAMP_TZ` | the same at its own offset (`…+05:30`) |\n * | `BINARY` | `Uint8Array` |\n * | `VARIANT`/`OBJECT`/`ARRAY`/`VECTOR` | the parsed JSON |\n * | anything else | the text as answered |\n *\n * A `TIMESTAMP_NTZ` is a wall clock with no zone: VibORM reads it as UTC, and\n * the driver runs every statement with `TIMEZONE = 'UTC'`, so the database\n * compares it the same way.\n */\n\nimport { QueryError, VibORMErrorCode } from \"@errors\";\n\n/** One `rowType` entry of a result set. */\nexport interface SnowflakeColumn {\n readonly name: string;\n readonly type: string;\n readonly scale?: number | null;\n readonly precision?: number | null;\n readonly nullable?: boolean;\n}\n\nexport interface SnowflakeBinding {\n readonly type:\n | \"FIXED\"\n | \"REAL\"\n | \"TEXT\"\n | \"BOOLEAN\"\n | \"BINARY\"\n | \"TIMESTAMP_TZ\";\n readonly value: string | null;\n}\n\nconst NANOS_PER_SECOND = 1_000_000_000n;\nconst NANOS_PER_MILLISECOND = 1_000_000n;\n/** `TIMESTAMP_TZ` offsets travel as minutes plus 1440. */\nconst OFFSET_BIAS = 1440;\nconst NOT_HEX = /[^0-9a-fA-F]/;\nconst INTEGER = /^-?\\d+$/;\n/**\n * A JSON string, or a token Snowflake prints that JSON has no spelling for:\n * the `undefined` of a SQL NULL inside an array (`ARRAY_CONSTRUCT(1, NULL)`\n * prints `[1, undefined]`), and a non-finite double (`NaN`, `Infinity`,\n * `-Infinity`), unless the account sets `STRICT_JSON_OUTPUT`.\n */\nconst UNSPELLED_MEMBER =\n /\"(?:[^\"\\\\]|\\\\.)*\"|\\bundefined\\b|-?\\bInfinity\\b|\\bNaN\\b/g;\nconst UNSPELLED_HINT = /undefined|Infinity|NaN/;\n\n/**\n * Semi-structured text as JSON: `undefined` reads as null, and a non-finite\n * double as the string `STRICT_JSON_OUTPUT` would print (`\"NaN\"`), so the\n * value is the same whatever the account sets.\n */\nfunction spelledJson(value: string): string {\n return UNSPELLED_HINT.test(value)\n ? value.replace(UNSPELLED_MEMBER, (token) => {\n if (token.startsWith('\"')) return token;\n return token === \"undefined\" ? \"null\" : `\"${token}\"`;\n })\n : value;\n}\n\nfunction hex(bytes: Uint8Array): string {\n let text = \"\";\n for (const byte of bytes) text += byte.toString(16).padStart(2, \"0\");\n return text;\n}\n\nfunction unhex(text: string): Uint8Array {\n if (text.length % 2 !== 0 || NOT_HEX.test(text))\n throw malformed(\"BINARY\", text);\n const bytes = new Uint8Array(text.length / 2);\n for (let index = 0; index < bytes.length; index++)\n bytes[index] = Number.parseInt(text.slice(index * 2, index * 2 + 2), 16);\n return bytes;\n}\n\nfunction malformed(type: string, value: string): QueryError {\n return new QueryError(\n `Snowflake answered a ${type} value VibORM cannot read: ${JSON.stringify(value.slice(0, 64))}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\", type },\n }\n );\n}\n\n/** One parameter as the SQL API binds it. */\nexport function encodeBinding(value: unknown): SnowflakeBinding {\n if (value === null || value === undefined)\n return { type: \"TEXT\", value: null };\n switch (typeof value) {\n case \"string\":\n return { type: \"TEXT\", value };\n case \"boolean\":\n return { type: \"BOOLEAN\", value: value ? \"true\" : \"false\" };\n case \"bigint\":\n return { type: \"FIXED\", value: value.toString() };\n case \"number\":\n // NUMBER holds 38 digits: a larger integer double binds as the double.\n if (Number.isInteger(value) && Math.abs(value) < 1e38)\n return { type: \"FIXED\", value: BigInt(value).toString() };\n // Snowflake refuses a REAL \"inf\", and reads a text one as FLOAT.\n if (!Number.isFinite(value))\n return {\n type: \"TEXT\",\n value: Number.isNaN(value) ? \"NaN\" : value > 0 ? \"inf\" : \"-inf\",\n };\n // The shortest text that reads back as this double.\n return { type: \"REAL\", value: String(value) };\n default:\n break;\n }\n if (value instanceof Date) {\n const time = value.getTime();\n if (Number.isNaN(time))\n throw new QueryError(\"An invalid Date cannot be bound.\", {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: { driver: \"snowflake\" },\n });\n return {\n type: \"TIMESTAMP_TZ\",\n value: `${BigInt(time) * NANOS_PER_MILLISECOND} ${OFFSET_BIAS}`,\n };\n }\n if (value instanceof Uint8Array) return { type: \"BINARY\", value: hex(value) };\n if (typeof value === \"object\")\n return {\n type: \"TEXT\",\n value: JSON.stringify(value, (_key, member) =>\n typeof member === \"bigint\" ? member.toString() : member\n ),\n };\n throw new QueryError(`A ${typeof value} cannot be bound to Snowflake.`, {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: { driver: \"snowflake\" },\n });\n}\n\n/** Every parameter, keyed `\"1\"`, `\"2\"`, … as the `?` placeholders count. */\nexport function encodeBindings(\n params: readonly unknown[]\n): Record<string, SnowflakeBinding> | undefined {\n if (params.length === 0) return undefined;\n const bindings: Record<string, SnowflakeBinding> = {};\n for (const [index, value] of params.entries())\n bindings[String(index + 1)] = encodeBinding(value);\n return bindings;\n}\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\n\n/** `-12.5` seconds as exact nanoseconds. */\nfunction nanoseconds(text: string, type: string): bigint {\n const match = DECIMAL.exec(text);\n if (!match) throw malformed(type, text);\n const [, sign, whole, fraction = \"\"] = match;\n if (fraction.length > 9) throw malformed(type, text);\n const nanos =\n BigInt(whole!) * NANOS_PER_SECOND + BigInt(fraction.padEnd(9, \"0\"));\n return sign ? -nanos : nanos;\n}\n\nconst pad = (value: number, width = 2): string =>\n String(value).padStart(width, \"0\");\n\n/** A calendar date of the proleptic Gregorian calendar, years beyond 9999 signed. */\nfunction isoDate(date: Date): string {\n const year = date.getUTCFullYear();\n const yearText =\n year >= 0 && year <= 9999\n ? pad(year, 4)\n : `${year < 0 ? \"-\" : \"+\"}${pad(Math.abs(year), 6)}`;\n return `${yearText}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;\n}\n\n/** Exact nanoseconds since the epoch as an ISO date-time, without a zone. */\nfunction isoLocal(nanos: bigint, type: string, text: string): string {\n let seconds = nanos / NANOS_PER_SECOND;\n let fraction = nanos % NANOS_PER_SECOND;\n if (fraction < 0n) {\n fraction += NANOS_PER_SECOND;\n seconds -= 1n;\n }\n const date = new Date(Number(seconds) * 1000);\n // Past JavaScript's ±8.64e15 ms, no calendar date is read.\n if (Number.isNaN(date.getTime())) throw malformed(type, text);\n const clock = `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;\n return `${isoDate(date)}T${clock}.${fraction.toString().padStart(9, \"0\")}`;\n}\n\nfunction offsetText(minutes: number): string {\n const sign = minutes < 0 ? \"-\" : \"+\";\n const magnitude = Math.abs(minutes);\n return `${sign}${pad(Math.floor(magnitude / 60))}:${pad(magnitude % 60)}`;\n}\n\n/** One answered value, as the table above says. */\nexport function decodeValue(column: SnowflakeColumn, value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value !== \"string\") return value;\n const type = column.type.toLowerCase();\n switch (type) {\n case \"fixed\": {\n if ((column.scale ?? 0) > 0) return value;\n if (!INTEGER.test(value)) throw malformed(\"NUMBER\", value);\n const number = Number(value);\n return Number.isSafeInteger(number) ? number : BigInt(value);\n }\n case \"real\": {\n const lowered = value.toLowerCase();\n if (lowered === \"inf\" || lowered === \"infinity\")\n return Number.POSITIVE_INFINITY;\n if (lowered === \"-inf\" || lowered === \"-infinity\")\n return Number.NEGATIVE_INFINITY;\n if (lowered === \"nan\") return Number.NaN;\n const number = Number(value);\n if (Number.isNaN(number)) throw malformed(\"FLOAT\", value);\n return number;\n }\n case \"boolean\":\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n throw malformed(\"BOOLEAN\", value);\n case \"date\": {\n if (!INTEGER.test(value)) throw malformed(\"DATE\", value);\n return isoDate(new Date(Number(value) * 86_400_000));\n }\n case \"time\":\n return isoLocal(nanoseconds(value, \"TIME\"), \"TIME\", value).slice(11);\n case \"timestamp_ntz\":\n case \"timestamp_ltz\":\n return `${isoLocal(nanoseconds(value, column.type), column.type, value)}Z`;\n case \"timestamp_tz\": {\n const [instant, bias] = value.split(\" \");\n const minutes = Number(bias) - OFFSET_BIAS;\n if (!(instant && Number.isInteger(minutes)))\n throw malformed(\"TIMESTAMP_TZ\", value);\n const local =\n nanoseconds(instant, column.type) +\n BigInt(minutes) * 60n * NANOS_PER_SECOND;\n return `${isoLocal(local, column.type, value)}${offsetText(minutes)}`;\n }\n case \"binary\":\n return unhex(value);\n case \"variant\":\n case \"object\":\n case \"array\":\n case \"map\":\n case \"vector\":\n try {\n return JSON.parse(spelledJson(value));\n } catch {\n throw malformed(column.type.toUpperCase(), value);\n }\n default:\n return value;\n }\n}\n\n/**\n * Every answered row, keyed by its columns' names. A row keys each value by\n * its column's name, so a result naming one column twice (`SELECT a.id,\n * b.id`) would keep only the last: it is refused.\n */\nexport function decodeRows<T = Record<string, unknown>>(\n columns: readonly SnowflakeColumn[],\n rows: readonly (readonly unknown[])[]\n): T[] {\n const names = new Set<string>();\n for (const { name } of columns) {\n if (names.has(name))\n throw new QueryError(\n `The result names the column ${JSON.stringify(name)} twice, and a row holds one value per name: alias one of them (SELECT a.id AS a_id, b.id AS b_id).`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\" },\n }\n );\n names.add(name);\n }\n return rows.map((row) => decodeRow<T>(columns, row));\n}\n\n/** One answered row, keyed by its columns' names. */\nexport function decodeRow<T = Record<string, unknown>>(\n columns: readonly SnowflakeColumn[],\n row: readonly unknown[]\n): T {\n const decoded: T = Object.create(Object.prototype);\n // Defined, not assigned: a column named `__proto__` is a column.\n for (const [index, column] of columns.entries())\n Object.defineProperty(decoded, column.name, {\n value: decodeValue(column, row[index]),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return decoded;\n}\n","/**\n * `viborm/snowflake`: read a Snowflake warehouse through its SQL API v2.\n *\n * VibORM only READS Snowflake. `findMany`, `findFirst`, `findUnique` (and their\n * `OrThrow` forms) with nested `include`/`select`, `count`, `exist`,\n * `aggregate`, `groupBy` and `$queryRaw` run; every write — `create`,\n * `update`, `delete`, `upsert`, the `Many` forms, nested writes,\n * `$executeRaw` — and every migration command is refused with a\n * `FeatureNotSupportedError` before anything is sent (`read-only.ts` says\n * why). There is no transaction either: the SQL API runs each statement on\n * its own.\n *\n * The transport is `fetch` and the signature WebCrypto, so the driver runs in\n * Node, Bun, Cloudflare Workers and Durable Objects without `snowflake-sdk`.\n */\n\nimport { SnowflakeAdapter } from \"@adapters/databases/snowflake/snowflake-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n type QueryErrorCode,\n VibORMErrorCode,\n} from \"@errors\";\nimport { queryBackend } from \"@query-engine/raptor3/shared/query-backend\";\nimport { Writer } from \"@query-engine/raptor3/write/statements\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport type { TransactionOptionSupport } from \"../shared\";\nimport {\n defineImmutableDriverFact,\n refuseUnknownDriverConfigKeys,\n} from \"../shared/driver-options\";\nimport { unsupportedCallbackTransactionError } from \"../shared/transactions\";\nimport type { QueryResult } from \"../types\";\nimport { SnowflakeAuthenticator, type SnowflakeTokenType } from \"./auth\";\nimport { SnowflakeQueries } from \"./queries\";\nimport {\n isRawWrite,\n readOnlyRefusal,\n SnowflakeOperationContext,\n} from \"./read-only\";\nimport {\n SnowflakeApiError,\n type SnowflakeContext,\n SnowflakeTransport,\n} from \"./transport\";\nimport { decodeRows, encodeBindings } from \"./values\";\n\nexport interface SnowflakeDriverOptions {\n /**\n * `snowflake://USER@ACCOUNT/DATABASE/SCHEMA?warehouse=WH&role=ROLE`. The key\n * or token is passed beside it, never in it. A field given beside the URL\n * takes precedence over the URL's.\n */\n readonly databaseUrl?: string;\n /** The account identifier: `ORGNAME-ACCOUNTNAME`, or a locator (`xy12345.us-east-1`). */\n readonly account?: string;\n readonly username?: string;\n /**\n * The RSA private key of key-pair authentication: PKCS#8 or PKCS#1 PEM,\n * unencrypted, or an imported `CryptoKey` that is extractable (the driver\n * reads its public half for the fingerprint Snowflake checks).\n */\n readonly privateKey?: string | CryptoKey;\n /** An OAuth (or programmatic access) token, or a function answering a fresh one. */\n readonly token?: string | (() => string | Promise<string>);\n readonly tokenType?: Exclude<SnowflakeTokenType, \"KEYPAIR_JWT\">;\n readonly warehouse?: string;\n readonly database?: string;\n /**\n * The Snowflake schema every statement runs in, and the one VibORM\n * qualifies its tables with (the adapter's namespace), spelled as the\n * catalog spells it (usually upper case).\n */\n readonly namespace?: string;\n readonly role?: string;\n /**\n * Seconds a statement may run, sent to Snowflake (it replaces a user's or\n * account's `STATEMENT_TIMEOUT_IN_SECONDS`, longer or shorter) and held by\n * the driver. Absent: 1,800 seconds (half an hour), held by the driver\n * alone, so a shorter account, user or warehouse limit still applies.\n * `false`: no limit of the driver's; Snowflake's alone.\n */\n readonly timeout?: number | false;\n /**\n * Where the API lives, when not `https://<account>.snowflakecomputing.com`\n * (a proxy, a region outside `.com`): an `https://` URL, since the token\n * goes wherever it says.\n */\n readonly host?: string;\n /** The `fetch` to send with: a Worker's, a proxy's, a test's. */\n readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;\n /**\n * Session parameters added to every statement's: `QUERY_TAG`,\n * `USE_CACHED_RESULT` and `CLIENT_RESULT_CHUNK_SIZE`, in any case. Any other\n * is refused: the driver decodes results in the formats and the time zone\n * it fixes, one statement at a time. A value is sent as text; one that is\n * `undefined` is not sent.\n */\n readonly parameters?: Readonly<\n Record<string, string | number | boolean | undefined>\n >;\n}\n\nexport type SnowflakeClientConfig<C extends DriverConfig> =\n SnowflakeDriverOptions & C;\n\nconst SNOWFLAKE_CONFIG_KEYS: Record<keyof SnowflakeDriverOptions, true> = {\n databaseUrl: true,\n account: true,\n username: true,\n privateKey: true,\n token: true,\n tokenType: true,\n warehouse: true,\n database: true,\n namespace: true,\n role: true,\n timeout: true,\n host: true,\n fetch: true,\n parameters: true,\n};\n\n/**\n * The session every statement runs in. A `TIMESTAMP_NTZ` is read as UTC, and\n * the database compares it with an instant the same way only in a UTC\n * session; the result format is the JSON the driver decodes.\n */\nconst SESSION = {\n TIMEZONE: \"UTC\",\n // Every row: 0 is no cap, whatever the account or the user sets.\n ROWS_PER_RESULTSET: \"0\",\n // One statement per request, stated rather than left to the default.\n MULTI_STATEMENT_COUNT: \"1\",\n} as const;\n\n/**\n * The session parameters a caller may set (keys compared lower-cased, as the\n * SQL API documents them): none changes how a value is printed, which rows a\n * result holds, or how many statements run.\n */\nconst CALLER_PARAMETERS = new Set([\n \"query_tag\",\n \"use_cached_result\",\n \"client_result_chunk_size\",\n]);\n\n/** Seconds a statement may run when the caller states no `timeout`. */\nconst DEFAULT_TIMEOUT = 1800;\n\nconst TRAILING_SLASHES = /\\/+$/;\n\nfunction configuration(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"snowflake\", operation: \"configuration\" },\n });\n}\n\nfunction callerParameters(\n parameters: unknown = {}\n): Readonly<Record<string, string>> {\n if (!isRecord(parameters))\n throw configuration(\n \"The Snowflake parameters are an object of session parameter names and their values.\"\n );\n const sent: Record<string, string> = {};\n for (const [key, value] of Object.entries(parameters)) {\n // An undefined value is an absent key, as every driver option is.\n if (value === undefined) continue;\n if (!CALLER_PARAMETERS.has(key.toLowerCase()))\n throw configuration(\n `VibORM does not pass the Snowflake session parameter ${key}: it decodes results in the formats and the time zone it fixes, and runs one statement at a time. It passes QUERY_TAG, USE_CACHED_RESULT and CLIENT_RESULT_CHUNK_SIZE.`\n );\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n )\n throw configuration(\n `The Snowflake session parameter ${key} is a string, a number or a boolean.`\n );\n sent[key] = String(value);\n }\n return sent;\n}\n\n/**\n * The API's URL for an account. The account is the host's first labels, and\n * the URL must name exactly that host: a path, a user, a port, a query or a\n * pasted URL in it would send the token elsewhere.\n */\nfunction accountUrl(account: string): string {\n const url = `https://${account.toLowerCase()}.snowflakecomputing.com`;\n if (URL.canParse(url) && new URL(url).origin === url) return url;\n throw configuration(\n `The Snowflake account ${JSON.stringify(account)} is not an account identifier: write ORGNAME-ACCOUNTNAME, or a locator such as xy12345.us-east-1, with no scheme, path or port. Pass host for any other endpoint.`\n );\n}\n\n/** A caller's `host`: https only, since every request carries the token. */\nfunction secureHost(host: string): string {\n if (URL.canParse(host) && new URL(host).protocol === \"https:\")\n return host.replace(TRAILING_SLASHES, \"\");\n throw configuration(\n \"The Snowflake host is an https:// URL: every request carries the token.\"\n );\n}\n\n/** The fields a `snowflake://` URL names. */\nfunction parseSnowflakeUrl(url: string): SnowflakeDriverOptions {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw configuration(\"The Snowflake databaseUrl is not a URL.\");\n }\n if (parsed.protocol !== \"snowflake:\")\n throw configuration(\n `A Snowflake databaseUrl starts with snowflake://, not ${parsed.protocol}//.`\n );\n if (parsed.port)\n throw configuration(\n \"A Snowflake databaseUrl names no port: the API answers https on 443. Pass host for any other endpoint.\"\n );\n if (parsed.password)\n throw configuration(\n \"A Snowflake databaseUrl carries no secret: pass privateKey or token beside it.\"\n );\n const [database, schema, extra] = parsed.pathname\n .split(\"/\")\n .filter((part) => part.length > 0)\n .map(decodeURIComponent);\n if (extra !== undefined)\n throw configuration(\n \"A Snowflake databaseUrl names at most /DATABASE/SCHEMA.\"\n );\n const query = (name: string) => parsed.searchParams.get(name) ?? undefined;\n return {\n account: decodeURIComponent(parsed.hostname),\n ...(parsed.username\n ? { username: decodeURIComponent(parsed.username) }\n : {}),\n ...(database ? { database } : {}),\n ...(schema ? { namespace: schema } : {}),\n ...(query(\"warehouse\") ? { warehouse: query(\"warehouse\") } : {}),\n ...(query(\"role\") ? { role: query(\"role\") } : {}),\n ...(query(\"host\") ? { host: query(\"host\") } : {}),\n };\n}\n\n/** Snowflake's failure in VibORM's words; a VibORM error passes as it is. */\nfunction snowflakeFailure(error: unknown): unknown {\n if (isVibORMError(error) || !(error instanceof SnowflakeApiError))\n return error;\n const meta = {\n driver: \"snowflake\",\n providerCode: error.code,\n sqlState: error.sqlstate,\n statementHandle: error.statementHandle,\n status: error.status,\n };\n // 390xxx: authentication and session; 000606: no warehouse is running.\n if (error.code?.startsWith(\"390\") || error.code === \"000606\")\n return new ClientInitializationError(\n `Snowflake refused the session: ${error.message}`,\n { cause: error, meta }\n );\n let code: QueryErrorCode = VibORMErrorCode.QUERY_FAILED;\n if (\n error.code === \"000630\" ||\n error.code === \"000604\" ||\n error.sqlstate === \"57014\"\n )\n code = VibORMErrorCode.QUERY_TIMEOUT;\n else if (\n error.code === \"002003\" ||\n error.code === \"000904\" ||\n error.sqlstate === \"42S02\" ||\n error.sqlstate === \"42S22\"\n )\n code = VibORMErrorCode.QUERY_SCHEMA_MISMATCH;\n else if (error.code === \"001003\") code = VibORMErrorCode.QUERY_SYNTAX;\n else if (error.sqlstate === \"22003\")\n code = VibORMErrorCode.QUERY_OUT_OF_RANGE;\n return new QueryError(`Snowflake refused the statement: ${error.message}`, {\n cause: error,\n code,\n meta,\n });\n}\n\nexport class SnowflakeDriver extends Driver<\n SnowflakeTransport,\n SnowflakeTransport\n> {\n declare readonly adapter: SnowflakeAdapter;\n override readonly backend = queryBackend({\n queries: SnowflakeQueries,\n context: SnowflakeOperationContext,\n // Never built: SnowflakeOperationContext refuses every write call first.\n writer: Writer,\n });\n // The SQL API runs each statement on its own: there is nothing to hold a\n // transaction open across two, and a read needs none.\n readonly supportsTransactions = false;\n readonly supportsBatch = false;\n readonly supportsOrderedCommittedSegments = false;\n\n readonly #options: SnowflakeDriverOptions;\n readonly #context: SnowflakeContext;\n readonly #baseUrl: string;\n readonly #parameters: Readonly<Record<string, string>>;\n\n constructor(options: SnowflakeDriverOptions = {}) {\n super(\"snowflake\", \"snowflake\");\n const fromUrl = options.databaseUrl\n ? parseSnowflakeUrl(options.databaseUrl)\n : {};\n const resolved: SnowflakeDriverOptions = {\n ...options,\n account: options.account ?? fromUrl.account,\n username: options.username ?? fromUrl.username,\n warehouse: options.warehouse ?? fromUrl.warehouse,\n database: options.database ?? fromUrl.database,\n namespace: options.namespace ?? fromUrl.namespace,\n role: options.role ?? fromUrl.role,\n host: options.host ?? fromUrl.host,\n };\n if (!resolved.account)\n throw configuration(\n \"Snowflake needs an account (ORGNAME-ACCOUNTNAME), or a databaseUrl naming one.\"\n );\n if (\n resolved.timeout !== undefined &&\n resolved.timeout !== false &&\n !(Number.isSafeInteger(resolved.timeout) && resolved.timeout > 0)\n )\n throw configuration(\n \"The Snowflake timeout is a positive whole number of seconds, or false for no limit of the driver's (Snowflake reads 0 as its maximum, seven days).\"\n );\n this.#options = resolved;\n this.#baseUrl =\n resolved.host === undefined\n ? accountUrl(resolved.account)\n : secureHost(resolved.host);\n this.#parameters = { ...callerParameters(resolved.parameters), ...SESSION };\n this.#context = {\n ...(resolved.warehouse ? { warehouse: resolved.warehouse } : {}),\n ...(resolved.database ? { database: resolved.database } : {}),\n ...(resolved.namespace ? { schema: resolved.namespace } : {}),\n ...(resolved.role ? { role: resolved.role } : {}),\n };\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new SnowflakeAdapter(resolved.namespace)\n );\n }\n\n protected async initClient(): Promise<SnowflakeTransport> {\n const options = this.#options;\n const account = options.account!;\n // Throws a configuration error for a missing or double credential, before\n // any request.\n const authenticator = new SnowflakeAuthenticator({\n account,\n ...(options.username ? { username: options.username } : {}),\n ...(options.privateKey ? { privateKey: options.privateKey } : {}),\n ...(options.token ? { token: options.token } : {}),\n ...(options.tokenType ? { tokenType: options.tokenType } : {}),\n });\n const send = options.fetch ?? globalThis.fetch;\n if (typeof send !== \"function\")\n throw configuration(\n \"This runtime has no fetch: pass one as the Snowflake driver's fetch option.\"\n );\n return new SnowflakeTransport({\n baseUrl: this.#baseUrl,\n authenticator,\n context: this.#context,\n // Absent, the driver alone holds the default: sent, it would replace a\n // shorter user or account limit (measured).\n ...(options.timeout === undefined\n ? { deadline: DEFAULT_TIMEOUT }\n : options.timeout === false\n ? {}\n : { timeout: options.timeout }),\n parameters: this.#parameters,\n // A Worker's fetch must be called unbound from the global.\n fetch: (input, init) => send(input, init),\n });\n }\n\n protected async closeClient(): Promise<void> {\n // HTTP keeps nothing open.\n }\n\n protected execute<T>(\n client: SnowflakeTransport,\n statement: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.#run<T>(client, statement, params, context);\n }\n\n protected executeRaw<T>(\n client: SnowflakeTransport,\n statement: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.#run<T>(client, statement, params ?? [], context);\n }\n\n async #run<T>(\n client: SnowflakeTransport,\n statement: string,\n params: readonly unknown[],\n context: QueryExecutionContext | undefined\n ): Promise<QueryResult<T>> {\n if (isRawWrite(context?.operation))\n throw readOnlyRefusal(context!.operation!);\n try {\n const result = await client.run(statement, encodeBindings(params));\n const rows = decodeRows<T>(result.columns, result.rows);\n return { rows, rowCount: rows.length };\n } catch (error) {\n throw snowflakeFailure(error);\n }\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"the Snowflake SQL API runs each statement on its own\",\n timeout: false,\n timeoutReason: \"the Snowflake SQL API runs each statement on its own\",\n maxWait: \"unsupported\",\n maxWaitReason: \"the Snowflake SQL API runs each statement on its own\",\n };\n }\n\n protected transaction<T>(): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n}\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SnowflakeClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SnowflakeDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SnowflakeDriver }\n >]: LinkedClientConfig<C & { driver: SnowflakeDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"snowflake\", SNOWFLAKE_CONFIG_KEYS);\n const {\n databaseUrl,\n account,\n username,\n privateKey,\n token,\n tokenType,\n warehouse,\n database,\n namespace,\n role,\n timeout,\n host,\n fetch,\n parameters,\n } = config;\n return createClientFromDriverConfig<S, C, SnowflakeDriver>(\n config,\n new SnowflakeDriver({\n databaseUrl,\n account,\n username,\n privateKey,\n token,\n tokenType,\n warehouse,\n database,\n namespace,\n role,\n timeout,\n host,\n fetch,\n parameters,\n })\n );\n}\n"],"mappings":"6kCAwFA,MAAM,EAAa,EAAuB,IAAI,CAExC,GAAc,QACd,GAAgB,MAMT,gBAAmB,GAC9B,IAAI,EAAM,WAAW,KAAM,OAAO,CAAC,WAAW,IAAK,MAAM,CAAC,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,CACJ,cACA,UACA,WACA,aACA,QACA,YACA,YACA,WACA,YACA,OACA,UACA,OACA,QACA,cACE,EACJ,OAAO,EACL,EACA,IAAI,gBAAgB,CAClB,cACA,UACA,WACA,aACA,QACA,YACA,YACA,WACA,YACA,OACA,UACA,OACA,QACA,aACD,CAAC,CACH"}
1
+ {"version":3,"file":"snowflake.mjs","names":["sql","#select","text","configuration","text","#credentials","#now","#jwt","#key","#keyedCursor","#relation","#order","#orderList","sql","#carried","#options","#send","#partitions","#request","body","text","#options","#context","#baseUrl","#parameters","#run"],"sources":["../src/adapters/databases/snowflake/snowflake-adapter.ts","../src/drivers/snowflake/auth.ts","../src/drivers/snowflake/queries.ts","../src/drivers/snowflake/read-only.ts","../src/drivers/snowflake/transport.ts","../src/drivers/snowflake/values.ts","../src/drivers/snowflake/index.ts"],"sourcesContent":["/**\n * Snowflake's SQL, for the reads VibORM runs on a warehouse (`viborm/snowflake`).\n *\n * VibORM only READS Snowflake: the driver refuses every write before it builds a\n * statement, so the members below that spell a write exist for the interface\n * and are never asked. What this adapter owns is the reading side:\n *\n * - identifiers are always quoted, so a name is the catalog's own spelling\n * (an unquoted `orders` is stored `ORDERS`; introspection reports it so);\n * - JSON is Snowflake's semi-structured `VARIANT`: `OBJECT_CONSTRUCT_KEEP_NULL`,\n * `ARRAY_AGG`, `GET_PATH`-style bracket access and `PARSE_JSON` operands;\n * - a datetime operand binds as an instant (`TIMESTAMP_TZ`), which the\n * driver's UTC session compares against `TIMESTAMP_NTZ`, `_LTZ` and `_TZ`\n * columns alike;\n * - `LIKE` patterns escape with a backslash, which a Snowflake string literal\n * spells `'\\\\'`;\n * - `s.vector()` is `VECTOR(FLOAT, n)` and `s.point()` a `GEOGRAPHY` point.\n *\n * Nested relation reads are not spelled here: Snowflake refuses a correlated\n * subquery holding a `LIMIT` or a correlated derived table, so the driver's\n * `SnowflakeQueries` writes them as uncorrelated grouped tables.\n */\n\nimport { FeatureNotSupportedError, UnsupportedOperationError } from \"@errors\";\nimport { type Sql, sql } from \"@sql\";\nimport {\n type DecimalDescriptor,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n CastType,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\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 type TextMatch,\n} from \"../../database-adapter\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\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 createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n\nconst ARRAY_INDEX = /^\\d+$/;\nconst LEADING_ZEROS = /^0+/;\n\n/** Snowflake's widest `NUMBER`. */\nexport const SNOWFLAKE_MAX_PRECISION = 38;\n\n/** A string literal: Snowflake reads a backslash in one as an escape. */\nexport const snowflakeString = (value: string): string =>\n `'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\")}'`;\n\n/** The `NUMBER(p,s)` a fixed decimal reads in: no wider than Snowflake's. */\nconst numberType = ({ precision, scale }: DecimalDescriptor): string =>\n `NUMBER(${Math.min(precision, SNOWFLAKE_MAX_PRECISION)},${scale})`;\n\n/**\n * Exact integer arithmetic on `NUMBER`: `/` widens the scale and rounds, so a\n * quotient that would round up to the next integer is taken as the exact\n * division of a multiple instead. `MOD` takes its sign from `n`.\n */\nconst SNOWFLAKE_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`((${n} - MOD(${n}, ${d})) / ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * `value`'s match as a function of its own: `CONTAINS`, `STARTSWITH` and\n * `ENDSWITH` are exact and case-sensitive on any operand, a column included,\n * so no pattern has to be escaped in SQL.\n */\nconst TEXT_FUNCTION: Readonly<Record<TextMatch, string>> = {\n contains: \"CONTAINS\",\n startsWith: \"STARTSWITH\",\n endsWith: \"ENDSWITH\",\n};\n\n/** One JSON path as bracket accesses; the empty path is the document. */\nfunction jsonPath(column: Sql, path: readonly string[]): Sql {\n if (path.length === 0) return column;\n const steps = path\n .map((segment) =>\n ARRAY_INDEX.test(segment)\n ? `[${segment}]`\n : `[${snowflakeString(segment)}]`\n )\n .join(\"\");\n return sql`(${column})${sql.raw(steps)}`;\n}\n\n/** A SQL NULL inside an `ARRAY_CONSTRUCT` would be `undefined`, not JSON null. */\nconst jsonMember = (value: Sql): Sql =>\n sql`COALESCE(TO_VARIANT(${value}), PARSE_JSON('null'))`;\n\nfunction jsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw(\"OBJECT_CONSTRUCT()\");\n return sql`OBJECT_CONSTRUCT_KEEP_NULL(${sql.join(\n pairs.map(\n ([key, value]) => sql`${sql.raw(snowflakeString(key))}, ${value}`\n ),\n \", \"\n )})`;\n}\n\n/** A semi-structured operand: the JSON text, parsed by Snowflake. */\nconst parsedJson = (value: unknown): Sql =>\n sql`PARSE_JSON(${stringifyJson(value)})`;\n\n/**\n * A list's members with a number's text read as that number: the engine binds\n * a `bigint` or `decimal` member as its exact digits, a string, while a\n * Snowflake ARRAY holds numbers; parsed, `\"9007199254740993\"` is that exact\n * number. Any other member stays as it is: a string's text that reads as\n * other JSON (`\"foo\"` with its quotes, `[1]`, `true`) is still that string.\n */\nconst parsedMembers = (values: Sql): Sql =>\n sql`TRANSFORM(${values}, member VARIANT -> IFF(TYPEOF(TRY_PARSE_JSON(member::VARCHAR)) IN ('INTEGER', 'DECIMAL', 'DOUBLE'), TRY_PARSE_JSON(member::VARCHAR), member))`;\n\n/** Some member of `values`, as it is or as its text reads, is in `column`. */\nconst overlaps = (column: Sql, values: Sql): Sql =>\n sql`(ARRAYS_OVERLAP(${column}, ${values}) OR ARRAYS_OVERLAP(${column}, ${parsedMembers(values)}))`;\n\n/** Every member of the JSON array `values` is a member of `column`. */\nconst containsEvery = (column: Sql, values: Sql): Sql =>\n sql`(ARRAY_SIZE(ARRAY_EXCEPT(ARRAY_DISTINCT(${values}), ${column})) = 0)`;\n\n/**\n * A recursive walk, which every recursive filter lowers to: Snowflake refuses\n * the one VibORM writes (a correlated anchor, `UNION`), measured as \"is an\n * invalid Recursive CTE\". Refused while the statement is built, so nothing\n * is sent, whether the filter is the caller's or a permission rule's.\n */\nfunction noRecursion(): never {\n throw new UnsupportedOperationError(\n \"Snowflake reads a relation without recursion. Read it with a second query, or with $queryRaw.\",\n { meta: { dialect: \"snowflake\", feature: \"recursion\" } }\n );\n}\n\n/** A statement Snowflake has no spelling for, asked only of a write. */\nfunction noSpelling(statement: string): never {\n throw new FeatureNotSupportedError(\n \"snowflake\",\n statement,\n \"VibORM only reads Snowflake, which has no such statement here.\"\n );\n}\n\n/**\n * A timestamp ending a VARIANT's text (`2024-01-02 03:04:05.678 -0800`) or a\n * nanosecond ISO instant, as the provider timestamp grammar reads it: the\n * fraction cut to microseconds and the offset joined to the clock.\n */\nconst VARIANT_TIMESTAMP =\n /^(\\d{4,}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(?:\\.(\\d+))?(?: ?(Z|[+-]\\d{2}:?\\d{2}))?$/;\n\n/**\n * A TIME as the driver answers it (`12:34:56.120000000`, nine digits) without\n * its fraction's trailing zeros (`12:34:56.12`): the provider time grammar\n * holds six digits, and VibORM's time milliseconds. A digit past the\n * millisecond that is not zero stays, and the time decoder refuses it.\n */\nexport function normalizeSnowflakeTime(value: string): string {\n return value.includes(\".\") ? value.replace(FRACTION_ZEROS, \"\") : value;\n}\n\nconst FRACTION_ZEROS = /\\.?0+$/;\n\nexport function normalizeSnowflakeTimestamp(value: string): string {\n const match = VARIANT_TIMESTAMP.exec(value);\n if (!match) return value;\n const [, date, clock, fraction, zone] = match;\n const micros = fraction ? `.${fraction.slice(0, 6)}` : \"\";\n return `${date}T${clock}${micros}${zone ?? \"Z\"}`;\n}\n\n/**\n * GeoPoint on `GEOGRAPHY`: `ST_MAKEPOINT`, `ST_X`/`ST_Y`, the shared exact\n * coordinate predicates, `ST_INTERSECTS` with a GeoJSON polygon (geodesic\n * edges, boundary included, holes excluded, measured on a real account), and\n * the haversine distance PostgreSQL spells, on the same fixed radius, so the\n * metres agree across providers.\n */\nfunction createSnowflakeGeoPointSql(\n operators: Parameters<typeof createGeoPointCoordinatePredicates>[2]\n): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point})`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_MAKEPOINT(${pointLongitude}, ${pointLatitude})`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(longitude, latitude, operators),\n withinPolygon: (point, polygon) =>\n sql`ST_INTERSECTS(TO_GEOGRAPHY(${geoPolygonJson(polygon)}), ${point})`,\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // LEAST/GREATEST would answer NULL for a NULL point anyway; the arm\n // says it where a reader looks for it.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS FLOAT) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n}\n\nexport class SnowflakeAdapter implements DatabaseAdapter {\n /**\n * The schema persistent objects are qualified with, exactly as the\n * catalog spells it, or absent: unqualified names then resolve in the\n * session's schema, which the driver states on every request.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n if (\n namespace !== undefined &&\n (typeof namespace !== \"string\" || namespace.length === 0)\n )\n throw new TypeError(\n \"A Snowflake namespace is a schema name: a non-empty string.\"\n );\n Object.defineProperty(this, \"namespace\", {\n value: namespace,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n this.identifiers = createIdentifiers(\n quoteIdent,\n namespace,\n this.capabilities.namesQualifiedColumns\n );\n // A GeoPoint is a GEOGRAPHY point: WGS 84, VibORM's own EPSG:4326.\n installGeoPointSql(this, createSnowflakeGeoPointSql(this.operators));\n installAdapterInternals(this, {\n batchRefs: SNOWFLAKE_BATCH_REFS,\n constraints: createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n ),\n select: this.#select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n // An instant: the driver binds a `Date` as `TIMESTAMP_TZ` at UTC, which\n // compares against every timestamp column kind in the UTC session.\n dateTime: (iso: string): Sql => sql`${new Date(iso)}`,\n\n true: (): Sql => sql.raw(\"TRUE\"),\n false: (): Sql => sql.raw(\"FALSE\"),\n\n json: parsedJson,\n\n // Snowflake's NUMBER holds 38 digits, so NUMBER(38,s) holds 38 - s of\n // them before the point: an operand that fits is exact there, and one\n // that does not is refused rather than rounded or failed by the cast.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql => {\n const text = encodePhysicalDecimal(canonical, descriptor, \"text\");\n const whole = text\n .replace(\"-\", \"\")\n .split(\".\")[0]!\n .replace(LEADING_ZEROS, \"\");\n if (\n descriptor.scale >= SNOWFLAKE_MAX_PRECISION ||\n whole.length > SNOWFLAKE_MAX_PRECISION - descriptor.scale\n )\n throw new UnsupportedOperationError(\n `Snowflake's NUMBER holds ${SNOWFLAKE_MAX_PRECISION} digits, and the decimal ${canonical} at scale ${descriptor.scale} needs more: no stored value can be compared with it.`,\n { meta: { dialect: \"snowflake\", scalarType: \"decimal\" } }\n );\n return sql`CAST(${text} AS ${sql.raw(numberType(descriptor))})`;\n },\n\n // A text-stored identifier compares as text and a byte-stored one as the\n // binary parameter blobs bind; Snowflake has no UUID type.\n id: (physical: string | Uint8Array): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`CONTAINS(${column}, ${value})`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`STARTSWITH(${column}, ${value})`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`ENDSWITH(${column}, ${value})`,\n // Snowflake folds case with its own `LOWER`, Unicode-aware.\n insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n sql`${sql.raw(TEXT_FUNCTION[kind])}(LOWER(${column}), LOWER(${value}))`,\n // A constant `LIKE 'abc%'` is what Snowflake prunes micro-partitions on.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\'`,\n\n exactTextEq: (column: Sql, value: Sql): Sql => sql`${column} = ${value}`,\n exactTextIn: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n\n in: (column: Sql, values: Sql): Sql => sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql => sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n ...createRangeOperators(),\n ...createLogicalOperators(this.literals.true, this.literals.false),\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n // Without a column collation Snowflake compares text by its bytes.\n caseSensitiveText: (expr: Sql): Sql => expr,\n caseFold: (expr: Sql): Sql => sql`LOWER(${expr})`,\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 integerDivide: (left: Sql, right: Sql): Sql =>\n SNOWFLAKE_INTEGERS.quotient(left, right),\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(numberType(descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`TO_BINARY(${expr}, 'HEX')`\n : sql`CAST(${expr} AS VARCHAR)`,\n\n cast: (expr: Sql, type: CastType): Sql =>\n sql`CAST(${expr} AS ${sql.raw(CAST_TYPES[type])})`,\n\n blobToHex: (expr: Sql): Sql => sql`HEX_ENCODE(${expr}, 0)`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'inf'::FLOAT\"),\n\n // An integer column's AVG is a NUMBER whose scale Snowflake chooses; the\n // public `_avg` is a double.\n avg: (expr: Sql): Sql => sql`CAST(AVG(${expr}) AS FLOAT)`,\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOLAND_AGG(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOLOR_AGG(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(SNOWFLAKE_INTEGERS, column, descriptor),\n\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(\n SNOWFLAKE_MAX_PRECISION\n ),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`(${left}) = (${right})`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n // A double inside a VARIANT prints with 16 significant digits, one short\n // of what reads every double back: it travels as its own shortest text\n // (`0.30000000000000004`), which every number decoder reads.\n number: (expression: Sql): Sql => sql`TO_VARCHAR(${expression})`,\n object: jsonObject,\n array: (items: Sql[]): Sql =>\n sql`ARRAY_CONSTRUCT(${sql.join(items.map(jsonMember), \", \")})`,\n emptyArray: (): Sql => sql.raw(\"ARRAY_CONSTRUCT()\"),\n agg: (expr: Sql): Sql =>\n sql`COALESCE(ARRAY_AGG(${expr}), ARRAY_CONSTRUCT())`,\n objectFromColumns: jsonObject,\n extract: jsonPath,\n extractText: (column: Sql, path: string[]): Sql =>\n sql`TO_VARCHAR(${jsonPath(column, path)})`,\n // NULL for any member that is not a number. A CAST under a CASE on its\n // TYPEOF is not enough: Snowflake may evaluate the CAST first, and fails\n // on an array (measured).\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`AS_DOUBLE(${jsonPath(column, path)})`,\n // Without a collation Snowflake orders text by code point already.\n stringAtPath: (column: Sql, path: string[]): Sql =>\n this.json.foldableStringAtPath(column, path),\n foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const value = jsonPath(column, path);\n return sql`(CASE WHEN TYPEOF(${value}) = 'VARCHAR' THEN TO_VARCHAR(${value}) END)`;\n },\n contains: (target: Sql, value: Sql): Sql =>\n sql`(IS_ARRAY(${target}) AND ${containsEvery(sql`${target}::ARRAY`, sql`${value}::ARRAY`)})`,\n lastElement: (target: Sql): Sql =>\n sql`GET(${target}, ARRAY_SIZE(${target}) - 1)`,\n value: parsedJson,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql =>\n sql`ARRAY_CONSTRUCT(${sql.join(items.map(jsonMember), \", \")})`,\n value: (values: unknown[]): Sql => sql`${parsedJson(values)}::ARRAY`,\n enumValue: (values: unknown[]): Sql => sql`${parsedJson(values)}::ARRAY`,\n // A list member compared as it is bound and as its text reads, so a\n // number list matches the exact text a bigint or decimal binds as\n // (measured: ARRAY_CONTAINS of the text found no number).\n has: (column: Sql, value: Sql): Sql =>\n overlaps(column, sql`ARRAY_CONSTRUCT(${value})`),\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`(ARRAY_SIZE(ARRAY_EXCEPT(${parsedMembers(\n sql`ARRAY_EXCEPT(ARRAY_DISTINCT(${values}), ${column})`\n )}, ${column})) = 0)`,\n hasSome: overlaps,\n isEmpty: (column: Sql): Sql =>\n sql`(ARRAY_SIZE(${column}) = 0 OR ${column} IS NULL)`,\n // Each member as exact text, so no JSON number rounds it on the way.\n exactNumericProjection: (column: Sql): Sql =>\n sql`TRANSFORM(${column}, member VARIANT -> TO_VARCHAR(member))`,\n length: (column: Sql): Sql => sql`ARRAY_SIZE(${column})`,\n get: (column: Sql, index: Sql): Sql => sql`GET(${column}, ${index})`,\n push: (column: Sql, value: Sql): Sql =>\n sql`ARRAY_APPEND(${column}, ${value})`,\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`ARRAY_CAT(ARRAY_APPEND(ARRAY_SLICE(${column}, 0, ${index}), ${value}), ARRAY_SLICE(${column}, ${index} + 1, ARRAY_SIZE(${column})))`,\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 /**\n * The spellings a nested relation read takes here (`SnowflakeQueries`\n * decides its structure): rows numbered per key, a page kept by its\n * numbers, an ordered aggregate and its first member, and the text a\n * timestamp or a date travels as inside a document.\n */\n relations = {\n rank: (partition: readonly Sql[], order: Sql | undefined): Sql =>\n sql`ROW_NUMBER() OVER (PARTITION BY ${sql.join(partition, \", \")} ORDER BY ${order ?? sql.raw(\"1\")})`,\n qualify: (select: Sql, condition: Sql): Sql =>\n sql`${select} QUALIFY ${condition}`,\n arrayAgg: (value: Sql, order: Sql | undefined): Sql =>\n order\n ? sql`ARRAY_AGG(${value}) WITHIN GROUP (ORDER BY ${order})`\n : sql`ARRAY_AGG(${value})`,\n first: (array: Sql): Sql => sql`GET(${array}, 0)`,\n timestampText: (column: Sql): Sql =>\n sql`TO_VARCHAR(CAST(${column} AS TIMESTAMP_TZ), 'YYYY-MM-DD\"T\"HH24:MI:SS.FF3TZH:TZM')`,\n dateText: (column: Sql): Sql => sql`TO_VARCHAR(${column}, 'YYYY-MM-DD')`,\n /**\n * A time as {@link normalizeSnowflakeTime} spells the driver's: its nine\n * digits without their trailing zeros. A VARIANT drops a TIME's fraction\n * (`12:34:56.123456789` prints `\"12:34:56\"`, measured).\n */\n timeText: (column: Sql): Sql =>\n sql`RTRIM(RTRIM(TO_VARCHAR(${column}, 'HH24:MI:SS.FF9'), '0'), '.')`,\n /**\n * A vector as the JSON text of its members, each the exact double its\n * float32 widens to (`0.10000000149011612`): the SQL API prints a VECTOR\n * with six decimals, and a VARIANT prints a double with sixteen digits,\n * both short of it. The vector decoder parses the text, flat or carried.\n */\n vectorText: (column: Sql): Sql =>\n sql`('[' || ARRAY_TO_STRING(TRANSFORM(CAST(${column} AS ARRAY), member VARIANT -> TO_VARCHAR(member::FLOAT)), ',') || ']')`,\n /**\n * A point as its two coordinates, each a JSON number parsed from the\n * double's shortest text, so no VARIANT print rounds it; NULL stays NULL.\n */\n pointObject: (column: Sql): Sql =>\n sql`IFF(${column} IS NULL, NULL, OBJECT_CONSTRUCT_KEEP_NULL('longitude', PARSE_JSON(TO_VARCHAR(ST_X(${column}))), 'latitude', PARSE_JSON(TO_VARCHAR(ST_Y(${column})))))`,\n };\n\n /** `LIMIT NULL OFFSET n`: Snowflake has no bare `OFFSET`. */\n noLimitValue = sql.raw(\"NULL\");\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(SNOWFLAKE_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(SNOWFLAKE_INTEGERS, column, by, target.decimal)\n : target?.integer\n ? sql`${column} = ${SNOWFLAKE_INTEGERS.quotient(column, by)}`\n : sql`${column} = ${column} / ${by}`,\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = ARRAY_CAT(COALESCE(${column}, ARRAY_CONSTRUCT()), ${values})`,\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = ARRAY_CAT(${values}, COALESCE(${column}, ARRAY_CONSTRUCT()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #select = (parts: QueryParts): Sql =>\n // Snowflake has no `DISTINCT ON`: a distinct page keeps each group's\n // first row by `ROW_NUMBER()`, as MySQL and SQLite do.\n parts.distinct\n ? assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n )\n : assembleSelectQuery(parts, {\n // Snowflake takes no row lock a read could ask for.\n forUpdate: \"omit\",\n noLimitValue: this.noLimitValue,\n });\n\n // Every walk is this one: Snowflake shares no relation body, so none is a\n // recursive member of a statement's WITH list.\n cte: DatabaseAdapter[\"cte\"] = {\n ...createCteBuilders(quoteIdent),\n recursive: noRecursion,\n };\n\n mutations = {\n // Snowflake enforces no unique key, so there is no duplicate to skip.\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} SELECT NULL WHERE FALSE`,\n ...createMutationCommands(),\n returning: (): Sql => noSpelling(\"RETURNING\"),\n onConflict: (): Sql => noSpelling(\"ON CONFLICT\"),\n onConflictUpdate: (): Sql => noSpelling(\"ON CONFLICT\"),\n insertAbsent: (): Sql[] => noSpelling(\"ON CONFLICT\"),\n skipDuplicates: (): { prefix: Sql; suffix: Sql } =>\n noSpelling(\"ON CONFLICT\"),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / IFF(EXISTS (${query}), 1, 0) AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / IFF(NOT EXISTS (${query}), 1, 0) AS \"__viborm_assert__\"`,\n };\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n namesQualifiedColumns: true,\n supportsReturning: false,\n supportsCteWithMutations: false,\n supportsFullOuterJoin: true,\n // Snowflake refuses most correlated inline views; nothing reads through one.\n supportsLateralJoins: false,\n supportsVector: true,\n supportsUpsertWhere: false,\n supportsTargetedUpsert: false,\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false,\n supportsRowLocks: false,\n };\n\n lastInsertId = (): Sql => noSpelling(\"LAST_INSERT_ID\");\n\n joins = {\n ...createCoreJoins(),\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n /**\n * `VECTOR(FLOAT, n)`: an operand is its JSON array cast into the column's\n * type. Snowflake has no vector index, so every order is exact, whatever\n * key the engine asks for.\n */\n vector = {\n literal: (values: number[]): Sql =>\n sql`CAST(PARSE_JSON(${JSON.stringify(values)}) AS ARRAY)::VECTOR(FLOAT, ${sql.raw(String(values.length))})`,\n l2: (column: Sql, vector: Sql): Sql =>\n sql`VECTOR_L2_DISTANCE(${column}, ${vector})`,\n // A zero vector's cosine is NaN; read as NULL, as on PostgreSQL.\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(1 - VECTOR_COSINE_SIMILARITY(${column}, ${vector}), 'NaN'::FLOAT)`,\n };\n\n result: DatabaseAdapter[\"result\"] = {\n parseResult: passThroughParseResult,\n // The driver parses every semi-structured value it reads.\n parseRelation: (_value: unknown, next: (value?: unknown) => unknown) =>\n next(),\n // A timestamp inside a VARIANT keeps Snowflake's own text; a top-level\n // one arrives as a nanosecond ISO instant. Both cross to the provider\n // timestamp grammar here, where the leaf says it is a timestamp.\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n if (scalarType === \"datetime\" && typeof value === \"string\")\n return next(normalizeSnowflakeTimestamp(value));\n if (scalarType === \"time\" && typeof value === \"string\")\n return next(normalizeSnowflakeTime(value));\n return next();\n },\n };\n}\n\nconst CAST_TYPES: Readonly<Record<CastType, string>> = {\n text: \"VARCHAR\",\n integer: \"INTEGER\",\n bigint: \"NUMBER(38,0)\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMBER(38,10)\",\n};\n\n/** Snowflake keeps no batch scratch: VibORM writes nothing there. */\nconst SNOWFLAKE_BATCH_REFS: BatchReferenceSqlAdapter = {\n setup: () => noSpelling(\"batch references\"),\n cleanup: () => noSpelling(\"batch references\"),\n store: () => noSpelling(\"batch references\"),\n read: () => noSpelling(\"batch references\"),\n};\n","/**\n * How the driver authenticates to Snowflake's SQL API, with WebCrypto only, so\n * the same code signs in Node, Bun, a Worker and a Durable Object.\n *\n * Key-pair authentication signs a JWT with the user's RSA private key\n * (docs.snowflake.com/en/developer-guide/sql-api/authenticating):\n *\n * - `iss` is `ACCOUNT.USER.SHA256:<fingerprint>`, the fingerprint being the\n * base64 SHA-256 of the public key's DER `SubjectPublicKeyInfo`;\n * - `sub` is `ACCOUNT.USER`, both upper-cased, the account without its region\n * or any part after a period;\n * - the token is valid for at most an hour, so it is renewed a minute before.\n *\n * WebCrypto cannot export a public key from a private one, so the public key\n * is rebuilt from the private key's JWK modulus and exponent.\n *\n * An OAuth or programmatic access token is sent as given, or asked of the\n * caller's function on each request, which is where a refresh belongs.\n */\n\nimport { ClientInitializationError } from \"@errors\";\n\nexport type SnowflakeTokenType =\n | \"KEYPAIR_JWT\"\n | \"OAUTH\"\n | \"PROGRAMMATIC_ACCESS_TOKEN\";\n\nexport interface SnowflakeCredentials {\n readonly account: string;\n readonly username?: string;\n /** PKCS#8 (`BEGIN PRIVATE KEY`) or PKCS#1 (`BEGIN RSA PRIVATE KEY`) PEM, or a key you imported, extractable. */\n readonly privateKey?: string | CryptoKey;\n /** An OAuth or programmatic access token, or a function answering one. */\n readonly token?: string | (() => string | Promise<string>);\n readonly tokenType?: Exclude<SnowflakeTokenType, \"KEYPAIR_JWT\">;\n}\n\nexport interface Authorization {\n readonly token: string;\n readonly type: SnowflakeTokenType;\n}\n\nconst LIFETIME_SECONDS = 3600;\nconst RENEW_BEFORE_SECONDS = 60;\nconst RSA = { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" } as const;\nconst PEM = /-----BEGIN ([A-Z ]+)-----([\\s\\S]*?)-----END \\1-----/;\nconst PADDING = /=+$/;\nconst PLUS = /\\+/g;\nconst SLASH = /\\//g;\n\nfunction configuration(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"snowflake\", operation: \"configuration\" },\n });\n}\n\nfunction base64ToBytes(text: string): Uint8Array<ArrayBuffer> {\n const binary = atob(text.replace(/\\s+/g, \"\"));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++)\n bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nconst base64Url = (bytes: Uint8Array): string =>\n bytesToBase64(bytes)\n .replace(PADDING, \"\")\n .replace(PLUS, \"-\")\n .replace(SLASH, \"_\");\n\nconst utf8 = (text: string): Uint8Array<ArrayBuffer> =>\n new Uint8Array(new TextEncoder().encode(text));\n\n/** One DER length. */\nfunction derLength(length: number): number[] {\n if (length < 0x80) return [length];\n const bytes: number[] = [];\n for (let rest = length; rest > 0; rest = Math.floor(rest / 256))\n bytes.unshift(rest % 256);\n return [0x80 + bytes.length, ...bytes];\n}\n\nfunction der(tag: number, content: Uint8Array): Uint8Array<ArrayBuffer> {\n const head = [tag, ...derLength(content.length)];\n const out = new Uint8Array(head.length + content.length);\n out.set(head);\n out.set(content, head.length);\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(\n parts.reduce((size, part) => size + part.length, 0)\n );\n let at = 0;\n for (const part of parts) {\n out.set(part, at);\n at += part.length;\n }\n return out;\n}\n\n/** `AlgorithmIdentifier { rsaEncryption, NULL }`. */\nconst RSA_ALGORITHM = new Uint8Array([\n 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,\n 0x05, 0x00,\n]);\n\n/** A PKCS#1 `RSAPrivateKey` wrapped as the PKCS#8 WebCrypto imports. */\nexport function pkcs1ToPkcs8(pkcs1: Uint8Array): Uint8Array<ArrayBuffer> {\n return der(\n 0x30,\n concat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALGORITHM, der(0x04, pkcs1))\n );\n}\n\n/** The private key a PEM holds, as the PKCS#8 bytes WebCrypto imports. */\nexport function privateKeyBytes(pem: string): Uint8Array<ArrayBuffer> {\n // An environment variable often holds the PEM's line breaks as \"\\n\".\n const match = PEM.exec(pem.replaceAll(\"\\\\n\", \"\\n\"));\n if (!match)\n throw configuration(\n \"The Snowflake private key must be a PEM block: -----BEGIN PRIVATE KEY----- (PKCS#8) or -----BEGIN RSA PRIVATE KEY----- (PKCS#1).\"\n );\n const [, label, body] = match;\n if (label === \"PRIVATE KEY\") return base64ToBytes(body!);\n if (label === \"RSA PRIVATE KEY\") return pkcs1ToPkcs8(base64ToBytes(body!));\n if (label === \"ENCRYPTED PRIVATE KEY\")\n throw configuration(\n \"The Snowflake private key is encrypted. Decrypt it first (openssl pkcs8 -in key.p8 -out key.pem), or import it yourself and pass the CryptoKey, extractable.\"\n );\n throw configuration(`A \"${label}\" PEM block is not an RSA private key.`);\n}\n\n/** The account as a JWT names it: upper-cased, without region or suffix. */\nexport function jwtAccount(account: string): string {\n return account.split(\".\")[0]!.toUpperCase();\n}\n\nasync function importPrivateKey(key: string | CryptoKey): Promise<CryptoKey> {\n if (typeof key !== \"string\") return key;\n try {\n return await crypto.subtle.importKey(\n \"pkcs8\",\n privateKeyBytes(key),\n RSA,\n true,\n [\"sign\"]\n );\n } catch (error) {\n if (error instanceof ClientInitializationError) throw error;\n throw configuration(\n `The Snowflake private key could not be imported as an RSA key: ${error instanceof Error ? error.message : String(error)}.`\n );\n }\n}\n\n/** `SHA256:` and the base64 SHA-256 of the public key's DER encoding. */\nexport async function publicKeyFingerprint(key: CryptoKey): Promise<string> {\n if (!key.extractable)\n throw configuration(\n \"The Snowflake private key's CryptoKey is not extractable: the driver reads its modulus and exponent to compute the fingerprint Snowflake checks. Import it with extractable set to true, or pass the PEM.\"\n );\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n const publicKey = await crypto.subtle.importKey(\n \"jwk\",\n { kty: \"RSA\", n: jwk.n, e: jwk.e, ext: true },\n RSA,\n true,\n [\"verify\"]\n );\n const spki = new Uint8Array(await crypto.subtle.exportKey(\"spki\", publicKey));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", spki));\n return `SHA256:${bytesToBase64(digest)}`;\n}\n\n/** One signed key-pair JWT, issued at `now` (seconds). */\nexport async function signKeyPairJwt(\n account: string,\n username: string,\n key: CryptoKey,\n now: number,\n fingerprint?: string\n): Promise<string> {\n const subject = `${jwtAccount(account)}.${username.toUpperCase()}`;\n const payload = {\n iss: `${subject}.${fingerprint ?? (await publicKeyFingerprint(key))}`,\n sub: subject,\n iat: now,\n exp: now + LIFETIME_SECONDS,\n };\n const signingInput = `${base64Url(utf8(JSON.stringify({ alg: \"RS256\", typ: \"JWT\" })))}.${base64Url(utf8(JSON.stringify(payload)))}`;\n const signature = new Uint8Array(\n await crypto.subtle.sign(RSA, key, utf8(signingInput))\n );\n return `${signingInput}.${base64Url(signature)}`;\n}\n\n/**\n * The Authorization a request carries. One per driver: it keeps the imported\n * key, its fingerprint and the current JWT, never anything module-wide.\n */\nexport class SnowflakeAuthenticator {\n readonly #credentials: SnowflakeCredentials;\n readonly #now: () => number;\n #key: Promise<{ key: CryptoKey; fingerprint: string }> | undefined;\n #jwt: { token: string; renewAt: number } | undefined;\n\n constructor(credentials: SnowflakeCredentials, now = () => Date.now()) {\n const { privateKey, token, username } = credentials;\n if ((privateKey === undefined) === (token === undefined))\n throw configuration(\n \"Snowflake needs exactly one credential: a privateKey (with a username) for key-pair authentication, or a token for OAuth.\"\n );\n if (privateKey !== undefined && !username)\n throw configuration(\n \"Snowflake key-pair authentication needs the username the key belongs to.\"\n );\n this.#credentials = credentials;\n this.#now = now;\n }\n\n async authorization(): Promise<Authorization> {\n const { token, tokenType } = this.#credentials;\n if (token !== undefined) {\n const value = typeof token === \"function\" ? await token() : token;\n if (typeof value !== \"string\" || value.length === 0)\n throw configuration(\"The Snowflake token function answered no token.\");\n return { token: value, type: tokenType ?? \"OAUTH\" };\n }\n const now = Math.floor(this.#now() / 1000);\n if (this.#jwt && now < this.#jwt.renewAt)\n return { token: this.#jwt.token, type: \"KEYPAIR_JWT\" };\n this.#key ??= importPrivateKey(this.#credentials.privateKey!).then(\n async (key) => ({ key, fingerprint: await publicKeyFingerprint(key) })\n );\n let imported: { key: CryptoKey; fingerprint: string };\n try {\n imported = await this.#key;\n } catch (error) {\n this.#key = undefined;\n throw error;\n }\n const jwt = await signKeyPairJwt(\n this.#credentials.account,\n this.#credentials.username!,\n imported.key,\n now,\n imported.fingerprint\n );\n this.#jwt = {\n token: jwt,\n renewAt: now + LIFETIME_SECONDS - RENEW_BEFORE_SECONDS,\n };\n return { token: jwt, type: \"KEYPAIR_JWT\" };\n }\n}\n","/**\n * Snowflake's reads: the SQL backend's, with one form changed.\n *\n * The SQL backend reads a relation as a correlated subquery over a correlated\n * page (`(SELECT json_agg(…) FROM (SELECT … WHERE parent.id = child.fk ORDER\n * BY … LIMIT n) AS page)`). Snowflake refuses both halves of that: a `LIMIT`\n * is allowed only in an uncorrelated subquery, and a derived table may not\n * read an outer row (`Unsupported subquery type cannot be evaluated`). What it\n * does evaluate is a correlated scalar subquery that is an aggregate, whose\n * correlation is an equality in its own `WHERE`\n * (docs.snowflake.com/en/user-guide/querying-subqueries): it decorrelates\n * that into a grouped join.\n *\n * So a relation here is read from an UNCORRELATED page, which projects the\n * key it joins its parent on and windows itself per key, and only the\n * aggregate around it is correlated:\n *\n * ```sql\n * (SELECT COALESCE(ARRAY_AGG(OBJECT_CONSTRUCT_KEEP_NULL('id', \"p\".\"id\", …))\n * WITHIN GROUP (ORDER BY \"p\".\"$rn\"), ARRAY_CONSTRUCT())\n * FROM (SELECT \"c\".\"id\", …, \"c\".\"authorId\" AS \"$k0\",\n * ROW_NUMBER() OVER (PARTITION BY \"c\".\"authorId\" ORDER BY …) AS \"$rn\"\n * FROM \"posts\" AS \"c\" WHERE …\n * QUALIFY \"$rn\" <= 2) AS \"p\"\n * WHERE \"p\".\"$k0\" = \"parent\".\"id\")\n * ```\n *\n * A deeper relation is the same form inside the page's own select list,\n * correlated to the page's row. Every other part of a read — the root page,\n * filters (`EXISTS` correlated in a `WHERE` is supported), `_count`,\n * aggregates and groups — is the SQL backend's, through the Snowflake\n * adapter.\n *\n * Refused, with a typed error before anything is sent: a nested `cursor` or\n * `distinct`, a nested order by a relation or a `_count`, a recursive\n * relation, a polymorphic slot and a junction's `$through` row; a root\n * `cursor` whose order is not the model's single-field key alone.\n */\n\nimport { assembleAdapterSelect } from \"@adapters/adapter-internals\";\nimport type { SnowflakeAdapter } from \"@adapters/databases/snowflake/snowflake-adapter\";\nimport { UnsupportedOperationError } from \"@errors\";\nimport type {\n Leaf,\n PreparedDomain,\n PreparedProjection,\n PreparedProjectionField,\n PreparedRelationProjection,\n ProjectionShape,\n Queries,\n Read,\n} from \"@query-engine/raptor3/shared/query\";\nimport type { CallScope } from \"@query-engine/raptor3/shared/row-scope\";\nimport type {\n Arguments,\n ReadOperation,\n} from \"@query-engine/raptor3/shared/schema\";\nimport { SqlQueries } from \"@query-engine/raptor3/shared/sql-queries\";\nimport { physicalField } from \"@query-engine/raptor3/shared/storage\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type Sql, sql } from \"@sql\";\nimport { isRecord } from \"@validation/value-guards\";\n\n/** What a nested read on Snowflake does not express. */\nfunction refused(what: string): never {\n throw new UnsupportedOperationError(\n `Snowflake reads a relation without ${what}. Read it with a second query, or with $queryRaw.`,\n { meta: { dialect: \"snowflake\", feature: what } }\n );\n}\n\ninterface OrderKey {\n readonly expression: Sql;\n readonly descending: boolean;\n readonly nulls: \"first\" | \"last\";\n readonly nullable: boolean;\n}\n\nconst KEY = (index: number) => `$k${index}`;\nconst ORDER = (index: number) => `$o${index}`;\nconst RANK = \"$rn\";\n\nexport class SnowflakeQueries extends SqlQueries {\n declare readonly adapter: SnowflakeAdapter;\n\n /**\n * Under a domain (an extension's rows, order or permissions) the reads stay\n * Snowflake's: the SQL backend's `under` answers its own class.\n */\n override under(domain: PreparedDomain, call?: CallScope): Queries {\n return new SnowflakeQueries(\n this.schema,\n this.adapter,\n this.result,\n domain,\n call\n );\n }\n\n /**\n * A root `cursor` ordered by the model's single-field key alone (the\n * caller's order, else the one an extension gives the model): the SQL\n * backend then compares that key with one uncorrelated scalar subquery,\n * which Snowflake evaluates (measured, ascending and descending, with\n * `distinct` too). A longer order compares a row of keys with a\n * multi-column subquery, which it refuses (\"Scalar subquery with\n * multi-column SELECT clause\").\n */\n override read(\n model: AnyModel,\n operation: ReadOperation,\n args: Arguments\n ): Read {\n if (args.cursor !== undefined && !this.#keyedCursor(model, args))\n throw new UnsupportedOperationError(\n \"Snowflake pages with a cursor only in the order of the model's single-field key, alone. Order by that key, or page with skip.\",\n { meta: { dialect: \"snowflake\", feature: \"cursor\" } }\n );\n return super.read(model, operation, args);\n }\n\n #keyedCursor(\n model: AnyModel,\n { cursor, orderBy }: Pick<Arguments, \"cursor\" | \"orderBy\">\n ): boolean {\n const [key, ...more] = this.keyOrder(model);\n if (key === undefined || more.length > 0) return false;\n const order = orderBy ?? this.defaultOrder(model);\n const terms = Array.isArray(order) ? order : order ? [order] : [];\n // One term at most: the key twice is two comparisons, a row again.\n return (\n terms.length <= 1 &&\n [cursor, ...terms].every(\n (term) =>\n isRecord(term) && Object.keys(term).every((field) => field === key)\n )\n );\n }\n\n override lowerProjection(\n projection: PreparedProjection,\n alias?: string,\n visible = false\n ): Sql[] {\n const a = this.adapter;\n return projection.fields.map((field) => {\n if (field.kind === \"relation\")\n return a.identifiers.aliased(\n this.#relation(field, alias ?? \"\"),\n field.name\n );\n if (field.kind === \"variants\") refused(\"a polymorphic slot\");\n // A vector and a point are spelled exactly here: the SQL backend's\n // projections would read them through prints that round them.\n const type =\n field.kind === \"scalar\"\n ? physicalField(this.schema, projection.model, field.name).scalar[\"~\"]\n .state.type\n : undefined;\n if (type === \"vector\" || type === \"point\") {\n const column = this.column(projection.model, field.name, alias);\n return a.identifiers.aliased(\n type === \"vector\"\n ? a.relations.vectorText(column)\n : a.relations.pointObject(column),\n field.name\n );\n }\n return super.lowerProjection(\n { ...projection, fields: [field] },\n alias,\n visible\n )[0]!;\n });\n }\n\n /** One relation of the row at `parentAlias`, as one aggregate value. */\n #relation(\n field: Extract<PreparedProjectionField, { kind: \"relation\" }>,\n parentAlias: string\n ): Sql {\n const relation: PreparedRelationProjection = field;\n const { edge, arguments: nested, projection } = relation;\n if (relation.recurrence) refused(\"recursion\");\n if (relation.linkRow || relation.linkWhere) refused(\"its $through row\");\n if (edge.discriminator) refused(\"a polymorphic slot\");\n if (nested.cursor !== undefined) refused(\"a cursor\");\n if (nested.distinct?.length) refused(\"distinct\");\n\n const a = this.adapter;\n const childAlias = this.alias();\n const columns = this.lowerProjection(projection, childAlias, true);\n const where: Sql[] = [];\n let from: Sql;\n let joins: Sql[] | undefined;\n // The child's side of each key pair, and the parent column it equals.\n const keys: [child: Sql, parent: Sql][] = [];\n if (edge.kind === \"reference\") {\n from = this.table(edge.target, childAlias);\n for (const pair of edge.pairs)\n keys.push([\n this.column(edge.target, pair.target, childAlias),\n this.column(edge.source, pair.source, parentAlias),\n ]);\n } else {\n const link = this.alias();\n from = a.identifiers.table(edge.table, link);\n joins = [\n a.joins.inner(\n this.table(edge.target, childAlias),\n a.operators.and(\n ...this.junctionSideConditions(edge.targetSide, link, childAlias)\n )\n ),\n ];\n for (const pair of edge.sourceSide.members)\n keys.push([\n a.identifiers.column(link, pair.junctionField),\n this.column(edge.source, pair.referencedField, parentAlias),\n ]);\n }\n // The related domain enters where the SQL backend's `correlation` puts\n // it: on the target row, outside any quantifier.\n const domain = this.domainOf(edge.target, \"related\");\n if (domain) where.push(this.lowerSelector(domain, childAlias)!);\n if (nested.selector)\n where.push(this.lowerSelector(nested.selector, childAlias)!);\n\n const order = this.#order(edge.target, nested.orderBy, childAlias);\n // A negative `take` reads the window backwards; the decoder restores it.\n const backward = nested.take !== undefined && nested.take < 0;\n const presented = backward\n ? order.map((key) => ({\n ...key,\n descending: !key.descending,\n nulls: key.nulls === \"first\" ? (\"last\" as const) : (\"first\" as const),\n }))\n : order;\n const windowed =\n !edge.many || nested.take !== undefined || nested.skip !== undefined;\n const pageColumns = [...columns];\n for (const [index, [child]] of keys.entries())\n pageColumns.push(a.identifiers.aliased(child, KEY(index)));\n const qualify: Sql[] = [];\n if (windowed) {\n pageColumns.push(\n a.identifiers.aliased(\n a.relations.rank(\n keys.map(([child]) => child),\n this.#orderList(presented)\n ),\n RANK\n )\n );\n const rank = a.identifiers.escape(RANK);\n const skip = nested.skip ?? 0;\n if (skip > 0) qualify.push(a.operators.gt(rank, this.value(skip)));\n if (!edge.many) qualify.push(a.operators.eq(rank, this.value(1)));\n else if (nested.take !== undefined)\n qualify.push(\n a.operators.lte(rank, this.value(skip + Math.abs(nested.take)))\n );\n } else {\n for (const [index, key] of presented.entries())\n pageColumns.push(a.identifiers.aliased(key.expression, ORDER(index)));\n }\n const page = assembleAdapterSelect(a, {\n columns: sql.join(pageColumns, \", \"),\n from,\n joins,\n where: where.length === 0 ? undefined : a.operators.and(...where),\n });\n const pageAlias = this.alias();\n const qualified =\n qualify.length === 0\n ? page\n : a.relations.qualify(page, a.operators.and(...qualify));\n\n const members: [string, Sql][] = Object.entries(\n projection.shape.fields\n ).map(([name, leaf]) => [\n name,\n this.#carried(leaf, a.identifiers.column(pageAlias, name)),\n ]);\n for (const gate of projection.shape.gates ?? [])\n members.push([gate, a.identifiers.column(pageAlias, gate)]);\n const object = a.json.object(members);\n const within = windowed\n ? a.orderBy.asc(a.identifiers.column(pageAlias, RANK))\n : this.#orderList(\n presented.map((key, index) => ({\n ...key,\n expression: a.identifiers.column(pageAlias, ORDER(index)),\n }))\n );\n const aggregated = a.relations.arrayAgg(object, within);\n const read = a.subqueries.scalar(\n assembleAdapterSelect(a, {\n columns: edge.many ? aggregated : a.relations.first(aggregated),\n from: a.subqueries.correlate(qualified, pageAlias),\n where: a.operators.and(\n ...keys.map(([, parent], index) =>\n a.operators.eq(a.identifiers.column(pageAlias, KEY(index)), parent)\n )\n ),\n })\n );\n // Snowflake evaluates the subquery as a grouped join, so a parent with no\n // row has no group and reads NULL, whatever the aggregate would answer\n // over zero rows: the empty list is stated outside it (measured on a real\n // account, 2026-11-11).\n return edge.many ? a.expressions.coalesce(read, a.json.emptyArray()) : read;\n }\n\n /**\n * A nested page's order: the caller's scalar terms, then the target's key,\n * NULLs placed as the SQL backend's page places them.\n */\n #order(model: AnyModel, input: unknown, alias: string): OrderKey[] {\n const keys: OrderKey[] = [];\n const ordered = new Set<string>();\n const terms = Array.isArray(input) ? input : input ? [input] : [];\n for (const term of terms) {\n // Admitted by the orderBy schema already: a record of field terms.\n if (!isRecord(term)) continue;\n for (const [field, direction] of Object.entries(term)) {\n if (direction === undefined) continue;\n if (model[\"~\"].state.relations[field])\n refused(\"an order by a related row or its _count\");\n let descending: boolean;\n let nulls: \"first\" | \"last\" | undefined;\n if (direction === \"asc\" || direction === \"desc\")\n descending = direction === \"desc\";\n else if (isRecord(direction)) {\n if (direction._distance !== undefined)\n refused(\"an order by distance\");\n descending = direction.sort === \"desc\";\n if (direction.nulls === \"first\" || direction.nulls === \"last\")\n nulls = direction.nulls;\n } else continue;\n ordered.add(field);\n // An operand the caller wrote, as the backend's own order spells it:\n // a read-gated field reads NULL on a row that does not carry it.\n const column = this.column(model, field, alias);\n keys.push({\n expression:\n this.domain?.project?.guarded(this, model, field, column, alias) ??\n column,\n descending,\n nulls: nulls ?? (descending ? \"first\" : \"last\"),\n nullable:\n physicalField(this.schema, model, field).nullable ||\n this.domain?.project?.projected(model)?.gates.has(field) === true,\n });\n }\n }\n for (const field of this.keyOrder(model)) {\n if (ordered.has(field)) continue;\n keys.push({\n expression: this.column(model, field, alias),\n descending: false,\n nulls: \"last\",\n nullable: physicalField(this.schema, model, field).nullable,\n });\n }\n return keys;\n }\n\n #orderList(keys: readonly OrderKey[]): Sql | undefined {\n if (keys.length === 0) return undefined;\n const a = this.adapter;\n return sql.join(\n keys.map((key) => {\n const direction = key.descending ? \"desc\" : \"asc\";\n if (!key.nullable) return a.orderBy[direction](key.expression);\n return key.nulls === \"first\"\n ? a.orderBy.nullsFirst(key.expression, direction)\n : a.orderBy.nullsLast(key.expression, direction);\n }),\n \", \"\n );\n }\n\n /**\n * A page column carried inside the relation's document, in the spelling\n * its decoder reads: exact text for what a JSON number would round, hex for\n * bytes, and an ISO instant for a timestamp, which a VARIANT would otherwise\n * spell in the session's output format.\n */\n #carried(leaf: ProjectionShape | Leaf, column: Sql): Sql {\n const a = this.adapter;\n if (leaf.kind !== \"scalar\") return a.json.document(column);\n if (leaf.list)\n return leaf.type === \"decimal\" ||\n leaf.type === \"bigint\" ||\n leaf.type === \"number\"\n ? a.arrays.exactNumericProjection(column)\n : column;\n switch (leaf.type) {\n case \"decimal\":\n case \"bigint\":\n return a.expressions.cast(column, \"text\");\n case \"number\":\n return a.json.number(column);\n case \"datetime\":\n return a.relations.timestampText(column);\n case \"date\":\n return a.relations.dateText(column);\n case \"time\":\n return a.relations.timeText(column);\n case \"blob\":\n return a.expressions.caseWhen(\n [{ when: a.operators.isNull(column), then: a.literals.null() }],\n a.expressions.blobToHex(column)\n );\n default:\n return column;\n }\n }\n}\n","/**\n * The one refusal of a write on Snowflake.\n *\n * Snowflake enforces no `PRIMARY KEY`, `UNIQUE` or `FOREIGN KEY` (only\n * `NOT NULL`), has no savepoint and no `RETURNING`, and charges for every\n * statement a warehouse runs: the guarantees VibORM's writes give — a unique\n * row addressed, a relation that holds, a nested write that rolls back to\n * where it failed — would not hold there. So the driver reads only.\n *\n * Every operation the engine runs gets its context before its first\n * statement — to execute it, to prepare it for a batch, or to publish it as\n * one statement — so a write verb is refused here, by its name, before\n * anything is built or sent. Raw writes have no context: `refuseRawWrite`\n * answers for `$executeRaw`, which the driver asks before it sends one.\n */\n\nimport { FeatureNotSupportedError } from \"@errors\";\nimport { SqlOperationContext } from \"@query-engine/raptor3/shared/sql-operation-context\";\nimport { isReadOperation } from \"@query-engine/routed-operations\";\n\nconst REASON =\n \"VibORM only reads Snowflake: it enforces no primary, unique or foreign key, has no savepoint and no RETURNING, so a write's guarantees would not hold there. Write with Snowflake's own tools.\";\n\nexport function readOnlyRefusal(operation: string): FeatureNotSupportedError {\n return new FeatureNotSupportedError(\"snowflake\", operation, REASON);\n}\n\nexport class SnowflakeOperationContext extends SqlOperationContext {\n constructor(...args: ConstructorParameters<typeof SqlOperationContext>) {\n const operation = args[3];\n if (!isReadOperation(operation)) throw readOnlyRefusal(operation);\n super(...args);\n }\n}\n\n/** `$executeRaw` and `$executeRawUnsafe`, which state a write by their name. */\nexport function isRawWrite(operation: string | undefined): boolean {\n return operation === \"$executeRaw\" || operation === \"$executeRawUnsafe\";\n}\n","/**\n * Snowflake's SQL API v2 over `fetch`: one statement per request, so it runs\n * wherever `fetch` and WebCrypto do (Node, Bun, Workers, Durable Objects).\n *\n * docs.snowflake.com/en/developer-guide/sql-api:\n *\n * - `POST /api/v2/statements?requestId=<uuid>` runs a statement with its\n * context (warehouse, database, schema, role) and typed bindings. It answers\n * 200 with the first partition of the result, 202 while it still runs, or\n * 422 with the failure;\n * - `GET /api/v2/statements/<handle>` is asked until a 202 becomes 200 or 422\n * (429 also means \"still running\");\n * - `GET /api/v2/statements/<handle>?partition=<n>` reads partition n > 0;\n * - `POST /api/v2/statements/<handle>/cancel` stops a statement this driver\n * no longer waits for.\n *\n * A request that failed before Snowflake answered (a network error, 429 on\n * submission, 502/503/504) is sent again with the same `requestId` and\n * `retry=true`, which Snowflake runs at most once.\n */\n\nimport {\n ClientInitializationError,\n ConnectionError,\n QueryError,\n VibORMErrorCode,\n} from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { SnowflakeAuthenticator } from \"./auth\";\nimport type { SnowflakeBinding, SnowflakeColumn } from \"./values\";\n\nexport interface SnowflakeContext {\n readonly warehouse?: string;\n readonly database?: string;\n readonly schema?: string;\n readonly role?: string;\n}\n\nexport interface SnowflakeTransportOptions {\n /** `https://<account>.snowflakecomputing.com`, without a trailing slash. */\n readonly baseUrl: string;\n readonly authenticator: SnowflakeAuthenticator;\n readonly context: SnowflakeContext;\n /** Seconds a statement may run, sent to Snowflake and held by the driver. */\n readonly timeout?: number;\n /**\n * Seconds the driver alone lets a statement run, where no `timeout` is\n * sent: Snowflake keeps its own limit, which a shorter one still wins.\n */\n readonly deadline?: number;\n /** Session parameters every statement runs with. */\n readonly parameters: Readonly<Record<string, string>>;\n readonly fetch: (input: string, init: RequestInit) => Promise<Response>;\n /** First poll delay; doubles up to {@link MAX_POLL_MS}. */\n readonly pollIntervalMs?: number;\n /** Partitions read at once. */\n readonly partitionConcurrency?: number;\n /**\n * Sends of one submission before its failure is final; a status or a\n * partition read gets {@link MORE_READ_ATTEMPTS} more.\n */\n readonly attempts?: number;\n readonly userAgent?: string;\n}\n\nexport interface StatementResult {\n readonly columns: readonly SnowflakeColumn[];\n readonly rows: readonly (readonly unknown[])[];\n readonly handle: string;\n}\n\n/** An answer's JSON body, read field by field: nothing in it is trusted. */\ntype Body = Readonly<Record<string, unknown>>;\n\nfunction text(body: Body | undefined, key: string): string | undefined {\n const value = body?.[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction isColumn(value: unknown): value is SnowflakeColumn {\n return (\n isRecord(value) &&\n typeof value.name === \"string\" &&\n typeof value.type === \"string\"\n );\n}\n\nfunction isRows(value: unknown): value is unknown[][] {\n return Array.isArray(value) && value.every((row) => Array.isArray(row));\n}\n\nconst MAX_POLL_MS = 2000;\n/** How long a cancel may hold the caller's error back. */\nconst CANCEL_MS = 2000;\n/**\n * More sends for a status read than for a submission: a GET changes nothing,\n * and giving up on one leaves a statement running.\n */\nconst MORE_READ_ATTEMPTS = 3;\n\n/** A failure Snowflake answered, as the error mapping reads it. */\nexport class SnowflakeApiError extends Error {\n readonly code: string | undefined;\n readonly sqlstate: string | undefined;\n readonly status: number;\n readonly statementHandle: string | undefined;\n constructor(status: number, body: Body | undefined, fallback: string) {\n super(text(body, \"message\") ?? fallback);\n this.name = \"SnowflakeApiError\";\n this.status = status;\n this.code = text(body, \"code\");\n this.sqlstate = text(body, \"sqlState\");\n this.statementHandle = text(body, \"statementHandle\");\n }\n}\n\nfunction malformedResult(reason: string): QueryError {\n return new QueryError(\n `Snowflake answered a result VibORM cannot read: ${reason}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\" },\n }\n );\n}\n\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n\n/** `promise`, or `signal`'s reason as soon as it aborts. */\nfunction untilAborted<T>(\n promise: Promise<T>,\n signal?: AbortSignal\n): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) {\n promise.catch(() => undefined);\n return Promise.reject(signal.reason);\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n}\n\nasync function readBody(response: Response): Promise<Body | undefined> {\n const answered = await response.text();\n if (answered.length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(answered);\n return isRecord(parsed) ? parsed : { message: answered.slice(0, 500) };\n } catch {\n return { message: answered.slice(0, 500) };\n }\n}\n\nexport class SnowflakeTransport {\n readonly #options: SnowflakeTransportOptions;\n\n constructor(options: SnowflakeTransportOptions) {\n this.#options = options;\n }\n\n /** Run one statement and read every partition of its result. */\n async run(\n statement: string,\n bindings: Record<string, SnowflakeBinding> | undefined,\n signal?: AbortSignal\n ): Promise<StatementResult> {\n const { timeout } = this.#options;\n const limit = timeout ?? this.#options.deadline;\n const deadline = new AbortController();\n const timer =\n limit === undefined\n ? undefined\n : setTimeout(\n () =>\n deadline.abort(\n new QueryError(\n `The Snowflake statement ran past its ${limit} s timeout and was cancelled.`,\n {\n code: VibORMErrorCode.QUERY_TIMEOUT,\n meta: { driver: \"snowflake\" },\n }\n )\n ),\n limit * 1000\n );\n const onAbort = () => deadline.abort(signal?.reason);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n let handle: string | undefined;\n // Until Snowflake answers the statement's outcome, a failure here leaves\n // it running: it is cancelled then, whatever the failure.\n let settled = false;\n try {\n const requestId = crypto.randomUUID();\n const body = JSON.stringify({\n statement,\n ...(timeout === undefined ? {} : { timeout }),\n ...this.#options.context,\n ...(bindings ? { bindings } : {}),\n parameters: this.#options.parameters,\n });\n let answer = await this.#send(\n (attempt) =>\n `/api/v2/statements?requestId=${requestId}${attempt > 0 ? \"&retry=true\" : \"\"}`,\n { method: \"POST\", body },\n deadline.signal\n );\n handle = text(answer.body, \"statementHandle\");\n let delay = this.#options.pollIntervalMs ?? 100;\n while (answer.status === 202 || answer.status === 429) {\n if (!handle)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n \"Snowflake accepted the statement without a handle to poll.\"\n );\n await sleep(delay, deadline.signal);\n delay = Math.min(delay * 2, MAX_POLL_MS);\n answer = await this.#send(\n () => `/api/v2/statements/${encodeURIComponent(handle!)}`,\n { method: \"GET\" },\n deadline.signal\n );\n }\n settled = true;\n if (answer.status !== 200)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n `Snowflake answered HTTP ${answer.status}.`\n );\n const result = answer.body;\n const metadata = isRecord(result?.resultSetMetaData)\n ? result.resultSetMetaData\n : undefined;\n const columns = metadata?.rowType;\n const first = result?.data;\n // A result states its columns and its first partition, empty or not;\n // without them the rows are not known, and no read answers [] for them.\n if (\n !(\n metadata &&\n Array.isArray(columns) &&\n columns.every(isColumn) &&\n isRows(first)\n )\n )\n throw malformedResult(\"its rowType or its data is missing\");\n handle = text(result, \"statementHandle\") ?? handle ?? \"\";\n const partitions = Array.isArray(metadata.partitionInfo)\n ? metadata.partitionInfo.length\n : 1;\n const rows: (readonly unknown[])[] = [...first];\n if (partitions > 1)\n for (const part of await this.#partitions(\n handle,\n partitions,\n deadline.signal\n ))\n for (const row of part) rows.push(row);\n const { numRows } = metadata;\n if (typeof numRows === \"number\" && rows.length !== numRows)\n throw malformedResult(\n `it states ${numRows} rows and holds ${rows.length}`\n );\n return { columns, rows, handle };\n } catch (error) {\n if (handle && !settled) await this.cancel(handle);\n throw deadline.signal.aborted && deadline.signal.reason instanceof Error\n ? deadline.signal.reason\n : error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n\n /**\n * Stop a statement, waiting at most `CANCEL_MS` for Snowflake to say so: a\n * failure to stop it is not the caller's failure, and the caller's deadline\n * must not wait on it.\n */\n async cancel(handle: string): Promise<void> {\n try {\n await this.#request(\n `/api/v2/statements/${encodeURIComponent(handle)}/cancel`,\n { method: \"POST\" },\n AbortSignal.timeout(CANCEL_MS)\n );\n } catch {\n // The statement's own timeout ends it anyway.\n }\n }\n\n /** Partitions 1..count-1, in order, at most `partitionConcurrency` at once. */\n async #partitions(\n handle: string,\n count: number,\n signal: AbortSignal\n ): Promise<unknown[][][]> {\n const out: unknown[][][] = new Array(count - 1);\n let next = 1;\n const worker = async () => {\n while (next < count) {\n const partition = next++;\n const answer = await this.#send(\n () =>\n `/api/v2/statements/${encodeURIComponent(handle)}?partition=${partition}`,\n { method: \"GET\" },\n signal\n );\n if (answer.status !== 200)\n throw new SnowflakeApiError(\n answer.status,\n answer.body,\n `Snowflake answered HTTP ${answer.status} for partition ${partition}.`\n );\n const data = answer.body?.data;\n if (!isRows(data))\n throw malformedResult(`partition ${partition} holds no data`);\n out[partition - 1] = data;\n }\n };\n const workers = Math.min(\n this.#options.partitionConcurrency ?? 4,\n count - 1\n );\n await Promise.all(Array.from({ length: workers }, worker));\n return out;\n }\n\n /**\n * One request, sent again while it failed before Snowflake answered it: a\n * network failure, a 5xx, or a 429 on a submission (the same `requestId`\n * with `retry=true` never runs a statement twice). A 4xx other than 429,\n * and every 2xx, is Snowflake's answer and is returned; a 5xx still\n * answered after the last send is a connection failure, not a refusal,\n * whose statement may have started.\n */\n async #send(\n path: (attempt: number) => string,\n init: { method: string; body?: string },\n signal: AbortSignal\n ): Promise<{ status: number; body: Body | undefined }> {\n const attempts =\n (this.#options.attempts ?? 3) +\n (init.method === \"GET\" ? MORE_READ_ATTEMPTS : 0);\n const pause = (attempt: number) =>\n sleep(Math.min(200 * 2 ** attempt, MAX_POLL_MS), signal);\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n try {\n response = await this.#request(path(attempt), init, signal);\n } catch (error) {\n if (signal.aborted || attempt + 1 >= attempts) throw error;\n await pause(attempt);\n continue;\n }\n const unanswered =\n response.status >= 500 ||\n // A 429 while polling means \"still running\", not \"send again\".\n (response.status === 429 && init.method !== \"GET\");\n if (unanswered && attempt + 1 < attempts) {\n await response.body?.cancel();\n await pause(attempt);\n continue;\n }\n if (response.status >= 500) {\n await response.body?.cancel();\n // A 5xx can follow the start of the statement (a gateway's 504):\n // its outcome is not known, and a submission's has no handle.\n throw new ConnectionError(\n init.method === \"POST\"\n ? `Snowflake answered HTTP ${response.status} to ${attempts} sends of the statement: its outcome is not known, and it may have started, with no handle to cancel it by; only Snowflake's limit for it (a timeout sent with it, else STATEMENT_TIMEOUT_IN_SECONDS) bounds it.`\n : `Snowflake answered HTTP ${response.status} to ${attempts} reads of the statement.`,\n { meta: { driver: \"snowflake\", status: response.status } }\n );\n }\n if (response.status === 401 || response.status === 403) {\n const body = await readBody(response);\n throw new ClientInitializationError(\n `Snowflake refused the credentials: ${text(body, \"message\") ?? `HTTP ${response.status}`}`,\n {\n cause: new SnowflakeApiError(response.status, body, \"unauthorized\"),\n meta: { driver: \"snowflake\", providerCode: text(body, \"code\") },\n }\n );\n }\n // The headers came; the body can still be cut off on its way, which is\n // a failed send like any other.\n let body: Body | undefined;\n try {\n body = await readBody(response);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (attempt + 1 >= attempts)\n throw new ConnectionError(\n `Snowflake's answer was cut off ${attempts} times before it ended.`,\n {\n cause: error instanceof Error ? error : undefined,\n meta: { driver: \"snowflake\" },\n }\n );\n await pause(attempt);\n continue;\n }\n return { status: response.status, body };\n }\n }\n\n async #request(\n path: string,\n init: { method: string; body?: string },\n signal?: AbortSignal\n ): Promise<Response> {\n // A token function may be slow to refresh: the request's deadline bounds\n // that wait too.\n const { token, type } = await untilAborted(\n this.#options.authenticator.authorization(),\n signal\n );\n try {\n return await this.#options.fetch(`${this.#options.baseUrl}${path}`, {\n method: init.method,\n headers: {\n Authorization: `Bearer ${token}`,\n \"X-Snowflake-Authorization-Token-Type\": type,\n Accept: \"application/json\",\n \"User-Agent\": this.#options.userAgent ?? \"viborm\",\n ...(init.body === undefined\n ? {}\n : { \"Content-Type\": \"application/json\" }),\n },\n ...(init.body === undefined ? {} : { body: init.body }),\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n if (signal?.aborted) throw signal.reason;\n throw new ConnectionError(\"Snowflake could not be reached\", {\n cause: error instanceof Error ? error : undefined,\n meta: { driver: \"snowflake\" },\n });\n }\n }\n}\n","/**\n * Values across Snowflake's SQL API, both ways, exactly.\n *\n * The API binds every parameter as a typed string\n * (docs.snowflake.com/en/developer-guide/sql-api/submitting-requests) and\n * answers every value as a string, typed by the result's `rowType`\n * (…/handling-responses). Nothing here goes through a JavaScript `number`\n * unless the value fits one exactly:\n *\n * | Snowflake | read as |\n * | ----------------------- | -------------------------------------------------- |\n * | `NUMBER(p,0)` | `number` when a safe integer, else `bigint` |\n * | `NUMBER(p,s)`, s > 0 | the decimal text (`\"12.50\"`) |\n * | `FLOAT` | `number` (`inf`, `-inf`, `NaN` included) |\n * | `TEXT` | `string` |\n * | `BOOLEAN` | `boolean` |\n * | `DATE` | `\"YYYY-MM-DD\"` |\n * | `TIME` | `\"HH:MM:SS.fffffffff\"` |\n * | `TIMESTAMP_NTZ` / `LTZ` | `\"YYYY-MM-DDTHH:MM:SS.fffffffffZ\"` (nanoseconds) |\n * | `TIMESTAMP_TZ` | the same at its own offset (`…+05:30`) |\n * | `BINARY` | `Uint8Array` |\n * | `VARIANT`/`OBJECT`/`ARRAY`/`VECTOR` | the parsed JSON |\n * | anything else | the text as answered |\n *\n * A `TIMESTAMP_NTZ` is a wall clock with no zone: VibORM reads it as UTC, and\n * the driver runs every statement with `TIMEZONE = 'UTC'`, so the database\n * compares it the same way.\n */\n\nimport { QueryError, VibORMErrorCode } from \"@errors\";\n\n/** One `rowType` entry of a result set. */\nexport interface SnowflakeColumn {\n readonly name: string;\n readonly type: string;\n readonly scale?: number | null;\n readonly precision?: number | null;\n readonly nullable?: boolean;\n}\n\nexport interface SnowflakeBinding {\n readonly type:\n | \"FIXED\"\n | \"REAL\"\n | \"TEXT\"\n | \"BOOLEAN\"\n | \"BINARY\"\n | \"TIMESTAMP_TZ\";\n readonly value: string | null;\n}\n\nconst NANOS_PER_SECOND = 1_000_000_000n;\nconst NANOS_PER_MILLISECOND = 1_000_000n;\n/** `TIMESTAMP_TZ` offsets travel as minutes plus 1440. */\nconst OFFSET_BIAS = 1440;\nconst NOT_HEX = /[^0-9a-fA-F]/;\nconst INTEGER = /^-?\\d+$/;\n/**\n * A JSON string, or a token Snowflake prints that JSON has no spelling for:\n * the `undefined` of a SQL NULL inside an array (`ARRAY_CONSTRUCT(1, NULL)`\n * prints `[1, undefined]`), and a non-finite double (`NaN`, `Infinity`,\n * `-Infinity`), unless the account sets `STRICT_JSON_OUTPUT`.\n */\nconst UNSPELLED_MEMBER =\n /\"(?:[^\"\\\\]|\\\\.)*\"|\\bundefined\\b|-?\\bInfinity\\b|\\bNaN\\b/g;\nconst UNSPELLED_HINT = /undefined|Infinity|NaN/;\n\n/**\n * Semi-structured text as JSON: `undefined` reads as null, and a non-finite\n * double as the string `STRICT_JSON_OUTPUT` would print (`\"NaN\"`), so the\n * value is the same whatever the account sets.\n */\nfunction spelledJson(value: string): string {\n return UNSPELLED_HINT.test(value)\n ? value.replace(UNSPELLED_MEMBER, (token) => {\n if (token.startsWith('\"')) return token;\n return token === \"undefined\" ? \"null\" : `\"${token}\"`;\n })\n : value;\n}\n\nfunction hex(bytes: Uint8Array): string {\n let text = \"\";\n for (const byte of bytes) text += byte.toString(16).padStart(2, \"0\");\n return text;\n}\n\nfunction unhex(text: string): Uint8Array {\n if (text.length % 2 !== 0 || NOT_HEX.test(text))\n throw malformed(\"BINARY\", text);\n const bytes = new Uint8Array(text.length / 2);\n for (let index = 0; index < bytes.length; index++)\n bytes[index] = Number.parseInt(text.slice(index * 2, index * 2 + 2), 16);\n return bytes;\n}\n\nfunction malformed(type: string, value: string): QueryError {\n return new QueryError(\n `Snowflake answered a ${type} value VibORM cannot read: ${JSON.stringify(value.slice(0, 64))}.`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\", type },\n }\n );\n}\n\n/** One parameter as the SQL API binds it. */\nexport function encodeBinding(value: unknown): SnowflakeBinding {\n if (value === null || value === undefined)\n return { type: \"TEXT\", value: null };\n switch (typeof value) {\n case \"string\":\n return { type: \"TEXT\", value };\n case \"boolean\":\n return { type: \"BOOLEAN\", value: value ? \"true\" : \"false\" };\n case \"bigint\":\n return { type: \"FIXED\", value: value.toString() };\n case \"number\":\n // NUMBER holds 38 digits: a larger integer double binds as the double.\n if (Number.isInteger(value) && Math.abs(value) < 1e38)\n return { type: \"FIXED\", value: BigInt(value).toString() };\n // Snowflake refuses a REAL \"inf\", and reads a text one as FLOAT.\n if (!Number.isFinite(value))\n return {\n type: \"TEXT\",\n value: Number.isNaN(value) ? \"NaN\" : value > 0 ? \"inf\" : \"-inf\",\n };\n // The shortest text that reads back as this double.\n return { type: \"REAL\", value: String(value) };\n default:\n break;\n }\n if (value instanceof Date) {\n const time = value.getTime();\n if (Number.isNaN(time))\n throw new QueryError(\"An invalid Date cannot be bound.\", {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: { driver: \"snowflake\" },\n });\n return {\n type: \"TIMESTAMP_TZ\",\n value: `${BigInt(time) * NANOS_PER_MILLISECOND} ${OFFSET_BIAS}`,\n };\n }\n if (value instanceof Uint8Array) return { type: \"BINARY\", value: hex(value) };\n if (typeof value === \"object\")\n return {\n type: \"TEXT\",\n value: JSON.stringify(value, (_key, member) =>\n typeof member === \"bigint\" ? member.toString() : member\n ),\n };\n throw new QueryError(`A ${typeof value} cannot be bound to Snowflake.`, {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: { driver: \"snowflake\" },\n });\n}\n\n/** Every parameter, keyed `\"1\"`, `\"2\"`, … as the `?` placeholders count. */\nexport function encodeBindings(\n params: readonly unknown[]\n): Record<string, SnowflakeBinding> | undefined {\n if (params.length === 0) return undefined;\n const bindings: Record<string, SnowflakeBinding> = {};\n for (const [index, value] of params.entries())\n bindings[String(index + 1)] = encodeBinding(value);\n return bindings;\n}\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\n\n/** `-12.5` seconds as exact nanoseconds. */\nfunction nanoseconds(text: string, type: string): bigint {\n const match = DECIMAL.exec(text);\n if (!match) throw malformed(type, text);\n const [, sign, whole, fraction = \"\"] = match;\n if (fraction.length > 9) throw malformed(type, text);\n const nanos =\n BigInt(whole!) * NANOS_PER_SECOND + BigInt(fraction.padEnd(9, \"0\"));\n return sign ? -nanos : nanos;\n}\n\nconst pad = (value: number, width = 2): string =>\n String(value).padStart(width, \"0\");\n\n/** A calendar date of the proleptic Gregorian calendar, years beyond 9999 signed. */\nfunction isoDate(date: Date): string {\n const year = date.getUTCFullYear();\n const yearText =\n year >= 0 && year <= 9999\n ? pad(year, 4)\n : `${year < 0 ? \"-\" : \"+\"}${pad(Math.abs(year), 6)}`;\n return `${yearText}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;\n}\n\n/** Exact nanoseconds since the epoch as an ISO date-time, without a zone. */\nfunction isoLocal(nanos: bigint, type: string, text: string): string {\n let seconds = nanos / NANOS_PER_SECOND;\n let fraction = nanos % NANOS_PER_SECOND;\n if (fraction < 0n) {\n fraction += NANOS_PER_SECOND;\n seconds -= 1n;\n }\n const date = new Date(Number(seconds) * 1000);\n // Past JavaScript's ±8.64e15 ms, no calendar date is read.\n if (Number.isNaN(date.getTime())) throw malformed(type, text);\n const clock = `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;\n return `${isoDate(date)}T${clock}.${fraction.toString().padStart(9, \"0\")}`;\n}\n\nfunction offsetText(minutes: number): string {\n const sign = minutes < 0 ? \"-\" : \"+\";\n const magnitude = Math.abs(minutes);\n return `${sign}${pad(Math.floor(magnitude / 60))}:${pad(magnitude % 60)}`;\n}\n\n/** One answered value, as the table above says. */\nexport function decodeValue(column: SnowflakeColumn, value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value !== \"string\") return value;\n const type = column.type.toLowerCase();\n switch (type) {\n case \"fixed\": {\n if ((column.scale ?? 0) > 0) return value;\n if (!INTEGER.test(value)) throw malformed(\"NUMBER\", value);\n const number = Number(value);\n return Number.isSafeInteger(number) ? number : BigInt(value);\n }\n case \"real\": {\n const lowered = value.toLowerCase();\n if (lowered === \"inf\" || lowered === \"infinity\")\n return Number.POSITIVE_INFINITY;\n if (lowered === \"-inf\" || lowered === \"-infinity\")\n return Number.NEGATIVE_INFINITY;\n if (lowered === \"nan\") return Number.NaN;\n const number = Number(value);\n if (Number.isNaN(number)) throw malformed(\"FLOAT\", value);\n return number;\n }\n case \"boolean\":\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n throw malformed(\"BOOLEAN\", value);\n case \"date\": {\n if (!INTEGER.test(value)) throw malformed(\"DATE\", value);\n return isoDate(new Date(Number(value) * 86_400_000));\n }\n case \"time\":\n return isoLocal(nanoseconds(value, \"TIME\"), \"TIME\", value).slice(11);\n case \"timestamp_ntz\":\n case \"timestamp_ltz\":\n return `${isoLocal(nanoseconds(value, column.type), column.type, value)}Z`;\n case \"timestamp_tz\": {\n const [instant, bias] = value.split(\" \");\n const minutes = Number(bias) - OFFSET_BIAS;\n if (!(instant && Number.isInteger(minutes)))\n throw malformed(\"TIMESTAMP_TZ\", value);\n const local =\n nanoseconds(instant, column.type) +\n BigInt(minutes) * 60n * NANOS_PER_SECOND;\n return `${isoLocal(local, column.type, value)}${offsetText(minutes)}`;\n }\n case \"binary\":\n return unhex(value);\n case \"variant\":\n case \"object\":\n case \"array\":\n case \"map\":\n case \"vector\":\n try {\n return JSON.parse(spelledJson(value));\n } catch {\n throw malformed(column.type.toUpperCase(), value);\n }\n default:\n return value;\n }\n}\n\n/**\n * Every answered row, keyed by its columns' names. A row keys each value by\n * its column's name, so a result naming one column twice (`SELECT a.id,\n * b.id`) would keep only the last: it is refused.\n */\nexport function decodeRows<T = Record<string, unknown>>(\n columns: readonly SnowflakeColumn[],\n rows: readonly (readonly unknown[])[]\n): T[] {\n const names = new Set<string>();\n for (const { name } of columns) {\n if (names.has(name))\n throw new QueryError(\n `The result names the column ${JSON.stringify(name)} twice, and a row holds one value per name: alias one of them (SELECT a.id AS a_id, b.id AS b_id).`,\n {\n code: VibORMErrorCode.QUERY_RESULT_INVALID,\n meta: { driver: \"snowflake\" },\n }\n );\n names.add(name);\n }\n return rows.map((row) => decodeRow<T>(columns, row));\n}\n\n/** One answered row, keyed by its columns' names. */\nexport function decodeRow<T = Record<string, unknown>>(\n columns: readonly SnowflakeColumn[],\n row: readonly unknown[]\n): T {\n const decoded: T = Object.create(Object.prototype);\n // Defined, not assigned: a column named `__proto__` is a column.\n for (const [index, column] of columns.entries())\n Object.defineProperty(decoded, column.name, {\n value: decodeValue(column, row[index]),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return decoded;\n}\n","/**\n * `viborm/snowflake`: read a Snowflake warehouse through its SQL API v2.\n *\n * VibORM only READS Snowflake. `findMany`, `findFirst`, `findUnique` (and their\n * `OrThrow` forms) with nested `include`/`select`, `count`, `exist`,\n * `aggregate`, `groupBy` and `$queryRaw` run; every write — `create`,\n * `update`, `delete`, `upsert`, the `Many` forms, nested writes,\n * `$executeRaw` — and every migration command is refused with a\n * `FeatureNotSupportedError` before anything is sent (`read-only.ts` says\n * why). There is no transaction either: the SQL API runs each statement on\n * its own.\n *\n * The transport is `fetch` and the signature WebCrypto, so the driver runs in\n * Node, Bun, Cloudflare Workers and Durable Objects without `snowflake-sdk`.\n */\n\nimport { SnowflakeAdapter } from \"@adapters/databases/snowflake/snowflake-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n isVibORMError,\n QueryError,\n type QueryErrorCode,\n VibORMErrorCode,\n} from \"@errors\";\nimport { queryBackend } from \"@query-engine/raptor3/shared/query-backend\";\nimport { Writer } from \"@query-engine/raptor3/write/statements\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport type { TransactionOptionSupport } from \"../shared\";\nimport {\n defineImmutableDriverFact,\n refuseUnknownDriverConfigKeys,\n} from \"../shared/driver-options\";\nimport { unsupportedCallbackTransactionError } from \"../shared/transactions\";\nimport type { QueryResult } from \"../types\";\nimport { SnowflakeAuthenticator, type SnowflakeTokenType } from \"./auth\";\nimport { SnowflakeQueries } from \"./queries\";\nimport {\n isRawWrite,\n readOnlyRefusal,\n SnowflakeOperationContext,\n} from \"./read-only\";\nimport {\n SnowflakeApiError,\n type SnowflakeContext,\n SnowflakeTransport,\n} from \"./transport\";\nimport { decodeRows, encodeBindings } from \"./values\";\n\nexport interface SnowflakeDriverOptions {\n /**\n * `snowflake://USER@ACCOUNT/DATABASE/SCHEMA?warehouse=WH&role=ROLE`. The key\n * or token is passed beside it, never in it. A field given beside the URL\n * takes precedence over the URL's.\n */\n readonly databaseUrl?: string;\n /** The account identifier: `ORGNAME-ACCOUNTNAME`, or a locator (`xy12345.us-east-1`). */\n readonly account?: string;\n readonly username?: string;\n /**\n * The RSA private key of key-pair authentication: PKCS#8 or PKCS#1 PEM,\n * unencrypted, or an imported `CryptoKey` that is extractable (the driver\n * reads its public half for the fingerprint Snowflake checks).\n */\n readonly privateKey?: string | CryptoKey;\n /** An OAuth (or programmatic access) token, or a function answering a fresh one. */\n readonly token?: string | (() => string | Promise<string>);\n readonly tokenType?: Exclude<SnowflakeTokenType, \"KEYPAIR_JWT\">;\n readonly warehouse?: string;\n readonly database?: string;\n /**\n * The Snowflake schema every statement runs in, and the one VibORM\n * qualifies its tables with (the adapter's namespace), spelled as the\n * catalog spells it (usually upper case).\n */\n readonly namespace?: string;\n readonly role?: string;\n /**\n * Seconds a statement may run, sent to Snowflake (it replaces a user's or\n * account's `STATEMENT_TIMEOUT_IN_SECONDS`, longer or shorter) and held by\n * the driver. Absent: 1,800 seconds (half an hour), held by the driver\n * alone, so a shorter account, user or warehouse limit still applies.\n * `false`: no limit of the driver's; Snowflake's alone.\n */\n readonly timeout?: number | false;\n /**\n * Where the API lives, when not `https://<account>.snowflakecomputing.com`\n * (a proxy, a region outside `.com`): an `https://` URL, since the token\n * goes wherever it says.\n */\n readonly host?: string;\n /** The `fetch` to send with: a Worker's, a proxy's, a test's. */\n readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;\n /**\n * Session parameters added to every statement's: `QUERY_TAG`,\n * `USE_CACHED_RESULT` and `CLIENT_RESULT_CHUNK_SIZE`, in any case. Any other\n * is refused: the driver decodes results in the formats and the time zone\n * it fixes, one statement at a time. A value is sent as text; one that is\n * `undefined` is not sent.\n */\n readonly parameters?: Readonly<\n Record<string, string | number | boolean | undefined>\n >;\n}\n\nexport type SnowflakeClientConfig<C extends DriverConfig> =\n SnowflakeDriverOptions & C;\n\nconst SNOWFLAKE_CONFIG_KEYS: Record<keyof SnowflakeDriverOptions, true> = {\n databaseUrl: true,\n account: true,\n username: true,\n privateKey: true,\n token: true,\n tokenType: true,\n warehouse: true,\n database: true,\n namespace: true,\n role: true,\n timeout: true,\n host: true,\n fetch: true,\n parameters: true,\n};\n\n/**\n * The session every statement runs in. A `TIMESTAMP_NTZ` is read as UTC, and\n * the database compares it with an instant the same way only in a UTC\n * session; the result format is the JSON the driver decodes.\n */\nconst SESSION = {\n TIMEZONE: \"UTC\",\n // Every row: 0 is no cap, whatever the account or the user sets.\n ROWS_PER_RESULTSET: \"0\",\n // One statement per request, stated rather than left to the default.\n MULTI_STATEMENT_COUNT: \"1\",\n} as const;\n\n/**\n * The session parameters a caller may set (keys compared lower-cased, as the\n * SQL API documents them): none changes how a value is printed, which rows a\n * result holds, or how many statements run.\n */\nconst CALLER_PARAMETERS = new Set([\n \"query_tag\",\n \"use_cached_result\",\n \"client_result_chunk_size\",\n]);\n\n/** Seconds a statement may run when the caller states no `timeout`. */\nconst DEFAULT_TIMEOUT = 1800;\n\nconst TRAILING_SLASHES = /\\/+$/;\n\nfunction configuration(message: string): ClientInitializationError {\n return new ClientInitializationError(message, {\n meta: { driver: \"snowflake\", operation: \"configuration\" },\n });\n}\n\nfunction callerParameters(\n parameters: unknown = {}\n): Readonly<Record<string, string>> {\n if (!isRecord(parameters))\n throw configuration(\n \"The Snowflake parameters are an object of session parameter names and their values.\"\n );\n const sent: Record<string, string> = {};\n for (const [key, value] of Object.entries(parameters)) {\n // An undefined value is an absent key, as every driver option is.\n if (value === undefined) continue;\n if (!CALLER_PARAMETERS.has(key.toLowerCase()))\n throw configuration(\n `VibORM does not pass the Snowflake session parameter ${key}: it decodes results in the formats and the time zone it fixes, and runs one statement at a time. It passes QUERY_TAG, USE_CACHED_RESULT and CLIENT_RESULT_CHUNK_SIZE.`\n );\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n )\n throw configuration(\n `The Snowflake session parameter ${key} is a string, a number or a boolean.`\n );\n sent[key] = String(value);\n }\n return sent;\n}\n\n/**\n * The API's URL for an account. The account is the host's first labels, and\n * the URL must name exactly that host: a path, a user, a port, a query or a\n * pasted URL in it would send the token elsewhere.\n */\nfunction accountUrl(account: string): string {\n const url = `https://${account.toLowerCase()}.snowflakecomputing.com`;\n if (URL.canParse(url) && new URL(url).origin === url) return url;\n throw configuration(\n `The Snowflake account ${JSON.stringify(account)} is not an account identifier: write ORGNAME-ACCOUNTNAME, or a locator such as xy12345.us-east-1, with no scheme, path or port. Pass host for any other endpoint.`\n );\n}\n\n/** A caller's `host`: https only, since every request carries the token. */\nfunction secureHost(host: string): string {\n if (URL.canParse(host) && new URL(host).protocol === \"https:\")\n return host.replace(TRAILING_SLASHES, \"\");\n throw configuration(\n \"The Snowflake host is an https:// URL: every request carries the token.\"\n );\n}\n\n/** The fields a `snowflake://` URL names. */\nfunction parseSnowflakeUrl(url: string): SnowflakeDriverOptions {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw configuration(\"The Snowflake databaseUrl is not a URL.\");\n }\n if (parsed.protocol !== \"snowflake:\")\n throw configuration(\n `A Snowflake databaseUrl starts with snowflake://, not ${parsed.protocol}//.`\n );\n if (parsed.port)\n throw configuration(\n \"A Snowflake databaseUrl names no port: the API answers https on 443. Pass host for any other endpoint.\"\n );\n if (parsed.password)\n throw configuration(\n \"A Snowflake databaseUrl carries no secret: pass privateKey or token beside it.\"\n );\n const [database, schema, extra] = parsed.pathname\n .split(\"/\")\n .filter((part) => part.length > 0)\n .map(decodeURIComponent);\n if (extra !== undefined)\n throw configuration(\n \"A Snowflake databaseUrl names at most /DATABASE/SCHEMA.\"\n );\n const query = (name: string) => parsed.searchParams.get(name) ?? undefined;\n return {\n account: decodeURIComponent(parsed.hostname),\n ...(parsed.username\n ? { username: decodeURIComponent(parsed.username) }\n : {}),\n ...(database ? { database } : {}),\n ...(schema ? { namespace: schema } : {}),\n ...(query(\"warehouse\") ? { warehouse: query(\"warehouse\") } : {}),\n ...(query(\"role\") ? { role: query(\"role\") } : {}),\n ...(query(\"host\") ? { host: query(\"host\") } : {}),\n };\n}\n\n/** Snowflake's failure in VibORM's words; a VibORM error passes as it is. */\nfunction snowflakeFailure(error: unknown): unknown {\n if (isVibORMError(error) || !(error instanceof SnowflakeApiError))\n return error;\n const meta = {\n driver: \"snowflake\",\n providerCode: error.code,\n sqlState: error.sqlstate,\n statementHandle: error.statementHandle,\n status: error.status,\n };\n // 390xxx: authentication and session; 000606: no warehouse is running.\n if (error.code?.startsWith(\"390\") || error.code === \"000606\")\n return new ClientInitializationError(\n `Snowflake refused the session: ${error.message}`,\n { cause: error, meta }\n );\n let code: QueryErrorCode = VibORMErrorCode.QUERY_FAILED;\n if (\n error.code === \"000630\" ||\n error.code === \"000604\" ||\n error.sqlstate === \"57014\"\n )\n code = VibORMErrorCode.QUERY_TIMEOUT;\n else if (\n error.code === \"002003\" ||\n error.code === \"000904\" ||\n error.sqlstate === \"42S02\" ||\n error.sqlstate === \"42S22\"\n )\n code = VibORMErrorCode.QUERY_SCHEMA_MISMATCH;\n else if (error.code === \"001003\") code = VibORMErrorCode.QUERY_SYNTAX;\n else if (error.sqlstate === \"22003\")\n code = VibORMErrorCode.QUERY_OUT_OF_RANGE;\n return new QueryError(`Snowflake refused the statement: ${error.message}`, {\n cause: error,\n code,\n meta,\n });\n}\n\nexport class SnowflakeDriver extends Driver<\n SnowflakeTransport,\n SnowflakeTransport\n> {\n declare readonly adapter: SnowflakeAdapter;\n override readonly backend = queryBackend({\n queries: SnowflakeQueries,\n context: SnowflakeOperationContext,\n // Never built: SnowflakeOperationContext refuses every write call first.\n writer: Writer,\n });\n // The SQL API runs each statement on its own: there is nothing to hold a\n // transaction open across two, and a read needs none.\n readonly supportsTransactions = false;\n readonly supportsBatch = false;\n readonly supportsOrderedCommittedSegments = false;\n\n readonly #options: SnowflakeDriverOptions;\n readonly #context: SnowflakeContext;\n readonly #baseUrl: string;\n readonly #parameters: Readonly<Record<string, string>>;\n\n constructor(options: SnowflakeDriverOptions = {}) {\n super(\"snowflake\", \"snowflake\");\n const fromUrl = options.databaseUrl\n ? parseSnowflakeUrl(options.databaseUrl)\n : {};\n const resolved: SnowflakeDriverOptions = {\n ...options,\n account: options.account ?? fromUrl.account,\n username: options.username ?? fromUrl.username,\n warehouse: options.warehouse ?? fromUrl.warehouse,\n database: options.database ?? fromUrl.database,\n namespace: options.namespace ?? fromUrl.namespace,\n role: options.role ?? fromUrl.role,\n host: options.host ?? fromUrl.host,\n };\n if (!resolved.account)\n throw configuration(\n \"Snowflake needs an account (ORGNAME-ACCOUNTNAME), or a databaseUrl naming one.\"\n );\n if (\n resolved.timeout !== undefined &&\n resolved.timeout !== false &&\n !(Number.isSafeInteger(resolved.timeout) && resolved.timeout > 0)\n )\n throw configuration(\n \"The Snowflake timeout is a positive whole number of seconds, or false for no limit of the driver's (Snowflake reads 0 as its maximum, seven days).\"\n );\n this.#options = resolved;\n this.#baseUrl =\n resolved.host === undefined\n ? accountUrl(resolved.account)\n : secureHost(resolved.host);\n this.#parameters = { ...callerParameters(resolved.parameters), ...SESSION };\n this.#context = {\n ...(resolved.warehouse ? { warehouse: resolved.warehouse } : {}),\n ...(resolved.database ? { database: resolved.database } : {}),\n ...(resolved.namespace ? { schema: resolved.namespace } : {}),\n ...(resolved.role ? { role: resolved.role } : {}),\n };\n defineImmutableDriverFact(\n this,\n \"adapter\",\n new SnowflakeAdapter(resolved.namespace)\n );\n }\n\n protected async initClient(): Promise<SnowflakeTransport> {\n const options = this.#options;\n const account = options.account!;\n // Throws a configuration error for a missing or double credential, before\n // any request.\n const authenticator = new SnowflakeAuthenticator({\n account,\n ...(options.username ? { username: options.username } : {}),\n ...(options.privateKey ? { privateKey: options.privateKey } : {}),\n ...(options.token ? { token: options.token } : {}),\n ...(options.tokenType ? { tokenType: options.tokenType } : {}),\n });\n const send = options.fetch ?? globalThis.fetch;\n if (typeof send !== \"function\")\n throw configuration(\n \"This runtime has no fetch: pass one as the Snowflake driver's fetch option.\"\n );\n return new SnowflakeTransport({\n baseUrl: this.#baseUrl,\n authenticator,\n context: this.#context,\n // Absent, the driver alone holds the default: sent, it would replace a\n // shorter user or account limit (measured).\n ...(options.timeout === undefined\n ? { deadline: DEFAULT_TIMEOUT }\n : options.timeout === false\n ? {}\n : { timeout: options.timeout }),\n parameters: this.#parameters,\n // A Worker's fetch must be called unbound from the global.\n fetch: (input, init) => send(input, init),\n });\n }\n\n protected async closeClient(): Promise<void> {\n // HTTP keeps nothing open.\n }\n\n protected execute<T>(\n client: SnowflakeTransport,\n statement: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.#run<T>(client, statement, params, context);\n }\n\n protected executeRaw<T>(\n client: SnowflakeTransport,\n statement: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.#run<T>(client, statement, params ?? [], context);\n }\n\n async #run<T>(\n client: SnowflakeTransport,\n statement: string,\n params: readonly unknown[],\n context: QueryExecutionContext | undefined\n ): Promise<QueryResult<T>> {\n if (isRawWrite(context?.operation))\n throw readOnlyRefusal(context!.operation!);\n try {\n const result = await client.run(statement, encodeBindings(params));\n const rows = decodeRows<T>(result.columns, result.rows);\n return { rows, rowCount: rows.length };\n } catch (error) {\n throw snowflakeFailure(error);\n }\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"the Snowflake SQL API runs each statement on its own\",\n timeout: false,\n timeoutReason: \"the Snowflake SQL API runs each statement on its own\",\n maxWait: \"unsupported\",\n maxWaitReason: \"the Snowflake SQL API runs each statement on its own\",\n };\n }\n\n protected transaction<T>(): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n}\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: SnowflakeClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, SnowflakeDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: SnowflakeDriver }\n >]: LinkedClientConfig<C & { driver: SnowflakeDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"snowflake\", SNOWFLAKE_CONFIG_KEYS);\n const {\n databaseUrl,\n account,\n username,\n privateKey,\n token,\n tokenType,\n warehouse,\n database,\n namespace,\n role,\n timeout,\n host,\n fetch,\n parameters,\n } = config;\n return createClientFromDriverConfig<S, C, SnowflakeDriver>(\n config,\n new SnowflakeDriver({\n databaseUrl,\n account,\n username,\n privateKey,\n token,\n tokenType,\n warehouse,\n database,\n namespace,\n role,\n timeout,\n host,\n fetch,\n parameters,\n })\n );\n}\n"],"mappings":"6kCAwFA,MAAM,EAAa,EAAuB,IAAI,CAExC,GAAc,QACd,GAAgB,MAMT,gBAAmB,GAC9B,IAAI,EAAM,WAAW,KAAM,OAAO,CAAC,WAAW,IAAK,MAAM,CAAC,GAGtD,YAAc,CAAE,YAAW,WAC/B,UAAU,KAAK,IAAI,EAAW,GAAwB,CAAC,GAAG,EAAM,GAO5D,EAA6C,CACjD,UAAW,EAAQ,IAAgB,CAAG,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,GACvE,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CAOK,GAAqD,CACzD,SAAU,WACV,WAAY,aACZ,SAAU,WACX,CAGD,SAAS,SAAS,EAAa,EAA8B,CAC3D,GAAI,EAAK,SAAW,EAAG,OAAO,EAC9B,IAAM,EAAQ,EACX,IAAK,GACJ,GAAY,KAAK,EAAQ,CACrB,IAAI,EAAQ,GACZ,IAAI,gBAAgB,EAAQ,CAAC,GAClC,CACA,KAAK,GAAG,CACX,MAAO,EAAG,IAAI,EAAO,GAAGA,EAAI,IAAI,EAAM,GAIxC,MAAM,WAAc,GAClB,CAAG,uBAAuB,EAAM,wBAElC,SAAS,WAAW,EAA6B,CAE/C,OADI,EAAM,SAAW,EAAUA,EAAI,IAAI,qBAAqB,CACrD,CAAG,8BAA8BA,EAAI,KAC1C,EAAM,KACH,CAAC,EAAK,KAAW,CAAG,GAAGA,EAAI,IAAI,gBAAgB,EAAI,CAAC,CAAC,IAAI,IAC3D,CACD,KACD,CAAC,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