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,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,r as n}from"./validation--qS7OPmg.mjs";import{o as r}from"./driver-BIXhOH2_.mjs";import{t as i}from"./postgres-adapter-Dlr3ZWd7.mjs";function installPostgresAdapter(e,a,o){let s=new i(a,o.postgis===!0);s.capabilities.supportsVector=o.pgvector===!0;let c=o.relationsPerStatement;if(c!==void 0&&!(Number.isSafeInteger(c)&&c>0))throw new n(`The "relationsPerStatement" option must be a positive integer (256 for PlanetScale Neki); received ${typeof c==`number`?c:`type "${typeof c}"`}.`);o.sharedRelationBodies!==!1&&(s.capabilities.sharesRelationBodies=!0,s.capabilities.relationsPerStatement=c),o.pgvector||(s.vector=t),r(e,`adapter`,s)}export{installPostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-axapXX8d.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{b as t,r as n}from"./validation--qS7OPmg.mjs";import{o as r}from"./driver-Df88hu4U.mjs";import{t as i}from"./postgres-adapter-Ia4u0-Ht.mjs";function installPostgresAdapter(e,a,o){let s=new i(a,o.postgis===!0);s.capabilities.supportsVector=o.pgvector===!0;let c=o.relationsPerStatement;if(c!==void 0&&!(Number.isSafeInteger(c)&&c>0))throw new n(`The "relationsPerStatement" option must be a positive integer (256 for PlanetScale Neki); received ${typeof c==`number`?c:`type "${typeof c}"`}.`);o.sharedRelationBodies!==!1&&(s.capabilities.sharesRelationBodies=!0,s.capabilities.relationsPerStatement=c),o.pgvector||(s.vector=t),r(e,`adapter`,s)}export{installPostgresAdapter as t};
2
+ //# sourceMappingURL=postgres-adapter-Byp7Zpop.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-adapter-axapXX8d.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { ClientInitializationError, unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one, `sharedRelationBodies` whether a\n * statement states each relation body it repeats once (the default: the\n * answers are the same and the statement smaller; `false` keeps every body\n * inline, as 1.2.4 spelled it), `relationsPerStatement` the relations a\n * statement may reference before it trades plans for fewer (absent:\n * unbounded until the server says otherwise, `relation-bound.ts`; PlanetScale\n * Neki needs 256).\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: {\n readonly pgvector?: boolean;\n readonly postgis?: boolean;\n readonly sharedRelationBodies?: boolean;\n readonly relationsPerStatement?: number;\n }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n const bound = options.relationsPerStatement;\n // A bound of 0, a fraction or NaN would escalate every statement or none.\n if (bound !== undefined && !(Number.isSafeInteger(bound) && bound > 0))\n throw new ClientInitializationError(\n `The \"relationsPerStatement\" option must be a positive integer (256 for PlanetScale Neki); received ${typeof bound === \"number\" ? bound : `type \"${typeof bound}\"`}.`\n );\n if (options.sharedRelationBodies !== false) {\n adapter.capabilities.sharesRelationBodies = true;\n adapter.capabilities.relationsPerStatement = bound;\n }\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"4LAcA,SAAgB,uBACd,EACA,EACA,EAMM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GAC3D,IAAM,EAAQ,EAAQ,sBAEtB,GAAI,IAAU,IAAA,IAAa,EAAE,OAAO,cAAc,EAAM,EAAI,EAAQ,GAClE,MAAM,IAAI,EACR,sGAAsG,OAAO,GAAU,SAAW,EAAQ,SAAS,OAAO,EAAM,GAAG,GACpK,CACC,EAAQ,uBAAyB,KACnC,EAAQ,aAAa,qBAAuB,GAC5C,EAAQ,aAAa,sBAAwB,GAE1C,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
1
+ {"version":3,"file":"postgres-adapter-Byp7Zpop.mjs","names":[],"sources":["../src/drivers/shared/postgres-adapter.ts"],"sourcesContent":["import { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport { ClientInitializationError, unsupportedVector } from \"@errors\";\nimport { defineImmutableDriverFact } from \"./driver-options\";\n\n/**\n * Install a PostgreSQL driver's adapter: `pgvector` alone decides the vector\n * capability, `postgis` the spatial one, `sharedRelationBodies` whether a\n * statement states each relation body it repeats once (the default: the\n * answers are the same and the statement smaller; `false` keeps every body\n * inline, as 1.2.4 spelled it), `relationsPerStatement` the relations a\n * statement may reference before it trades plans for fewer (absent:\n * unbounded until the server says otherwise, `relation-bound.ts`; PlanetScale\n * Neki needs 256).\n */\nexport function installPostgresAdapter(\n driver: object,\n namespace: string | undefined,\n options: {\n readonly pgvector?: boolean;\n readonly postgis?: boolean;\n readonly sharedRelationBodies?: boolean;\n readonly relationsPerStatement?: number;\n }\n): void {\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n const bound = options.relationsPerStatement;\n // A bound of 0, a fraction or NaN would escalate every statement or none.\n if (bound !== undefined && !(Number.isSafeInteger(bound) && bound > 0))\n throw new ClientInitializationError(\n `The \"relationsPerStatement\" option must be a positive integer (256 for PlanetScale Neki); received ${typeof bound === \"number\" ? bound : `type \"${typeof bound}\"`}.`\n );\n if (options.sharedRelationBodies !== false) {\n adapter.capabilities.sharesRelationBodies = true;\n adapter.capabilities.relationsPerStatement = bound;\n }\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(driver, \"adapter\", adapter);\n}\n"],"mappings":"4LAcA,SAAgB,uBACd,EACA,EACA,EAMM,CACN,IAAM,EAAU,IAAI,EAAgB,EAAW,EAAQ,UAAY,GAAK,CACxE,EAAQ,aAAa,eAAiB,EAAQ,WAAa,GAC3D,IAAM,EAAQ,EAAQ,sBAEtB,GAAI,IAAU,IAAA,IAAa,EAAE,OAAO,cAAc,EAAM,EAAI,EAAQ,GAClE,MAAM,IAAI,EACR,sGAAsG,OAAO,GAAU,SAAW,EAAQ,SAAS,OAAO,EAAM,GAAG,GACpK,CACC,EAAQ,uBAAyB,KACnC,EAAQ,aAAa,qBAAuB,GAC5C,EAAQ,aAAa,sBAAwB,GAE1C,EAAQ,WAAU,EAAQ,OAAS,GACxC,EAA0B,EAAQ,UAAW,EAAQ"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{m as n,p as r}from"./validation--qS7OPmg.mjs";import{o as i,t as a}from"./sql-BGjAsoBE.mjs";import{t as o}from"./adapter-result-parser-3WP82Cm-.mjs";import{N as s,T as c,o as l}from"./native-types-DspZ0Z5E.mjs";import{a as u}from"./adapter-internals-DOqI8IlQ.mjs";import{a as ee}from"./physical-wboFLAg9.mjs";import{t as d}from"./geo-area-codec-BDvW7IH-.mjs";import{a as f}from"./datetime-physical-codec-BS2T81sD.mjs";import{t as p}from"./identifiers-BTCfD5ic.mjs";import{C as m,D as h,E as te,O as ne,S as g,T as _,a as v,b as y,c as b,d as x,f as S,g as C,h as w,i as T,j as E,l as D,m as O,n as k,o as A,p as j,r as M,s as N,v as P,w as F,x as re,y as I}from"./standard-sql-Bsf5nrla.mjs";import{t as L}from"./json-parameter-oQ8nGaKr.mjs";import{t as R}from"./array-literal-DHinAnVs.mjs";import{r as z}from"./batch-refs-BmEpMmjI.mjs";import{t as B}from"./adapter-namespace-DD-BQ2Wk.mjs";import{a as V,c as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-SuVxJjps.mjs";const Z=p(`"`);function postgresLikePattern(e,t){let n=e===`startsWith`?``:`%`,r=e===`endsWith`?``:`%`,[a,o]=t.values;return t.strings.join(``)===``&&typeof a==`string`&&o===void 0?i`${n+E(a)+r}`:i`(${i.raw(n&&`'%' || `)}REPLACE(REPLACE(REPLACE(CAST(${t} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${i.raw(r&&` || '%'`)})`}const Q=[];function postgresJsonArray(e){if(e.length===0)return i.raw`'[]'::json`;if(e.length<=100){let t=Q[e.length];if(t===void 0){t=[`json_build_array(`];for(let n=1;n<e.length;n++)t.push(`, `);t.push(`)`),Q[e.length]=t}return new a(t,e)}let t=[];for(let n=0;n<e.length;n+=100){let r=Math.min(e.length,n+100),i=[`jsonb_build_array(`];for(let e=n+1;e<r;e++)i.push(`, `);i.push(`)`),t.push(new a(i,e.slice(n,r)))}return i`(${i.join(t,` || `)})::json`}function postgresJsonObject(e){if(e.length===0)return i.raw`'{}'::json`;let t=[],n=e.length>50?`jsonb_build_object`:`json_build_object`;for(let r=0;r<e.length;r+=50){let i=[],o=[];for(let t=r;t<e.length&&t<r+50;t++){let[a,s]=e[t];i.push(t===r?`${n}(`:`, `,`::text, `),o.push(a,s)}i.push(`)`),t.push(new a(i,o))}return t.length===1?t[0]:i`(${i.join(t,` || `)})::json`}const ie=G(e=>`${e}_pkey`);var CastParameter=class extends a{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends a{};const ae=h().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=R(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>i`div(${e}, ${t})`,remainder:(e,t)=>i`mod(${e}, ${t})`},oe=Object.freeze({day:i.raw`'day'`,week:i.raw`'week'`,month:i.raw`'month'`,quarter:i.raw`'quarter'`,year:i.raw`'year'`}),storesInstant=({withTimezone:e,nativeType:t})=>{let n=l(t,`pg`)?.type.toLowerCase();return n===void 0?e:n.includes(`timestamptz`)||n.includes(`with time zone`)},se=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){B(this,e,`postgresql`),this.identifiers=S(Z,this.namespace,this.capabilities.namesQualifiedColumns),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:ie,pinnedTable:this.identifiers.table,select:this.#e.select})}raw=m();period=Object.freeze({of:(e,t,n,r)=>{let a=n.date?i`CAST(${e} AS TIMESTAMP)`:storesInstant(n)?i`(${e} AT TIME ZONE ${r})`:e;return i`CAST(date_trunc(${oe[t]}, ${a}) AS DATE)`},text:e=>i`to_char(CAST(${e} AS TIMESTAMP), 'YYYY-MM-DD BC')`});identifiers;literals={...h(),dateTime:e=>i`${f(e)}`,true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${L.from(e)}`,decimal:(e,t)=>new CastParameter(s(e,t,`text`),c(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):i`${e}`,list:e=>arrayParameter(e)??ae(e)};operators={...v(),containsText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`contains`,t)} ESCAPE '\\'`,startsWithText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`startsWith`,t)} ESCAPE '\\'`,endsWithText:(e,t)=>i`${e} LIKE ${postgresLikePattern(`endsWith`,t)} ESCAPE '\\'`,insensitiveText:(e,t,n,r)=>i`${this.expressions.caseSensitiveText(t,r,!0)} ILIKE ${postgresLikePattern(e,n)} ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${E(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>i`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?i`${e} = ANY(${t})`:i`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?i`${e} <> ALL(${t})`:i`${e} NOT IN ${t}`,...I(),...g(),...C(this.literals.true,this.literals.false),...x()};expressions={...T(),caseSensitiveText:(e,t,r=!1)=>{let a=l(t,`pg`)?.type;if(!r&&a?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&a&&se.test(a)?i`CAST(${e} AS TEXT)`:e},caseFold:(e,t)=>i`LOWER(${this.expressions.caseSensitiveText(e,t,!0)})`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`(${i.join(e,` || `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`(${e} / ${t})`,decimalCast:(e,t)=>i`CAST(${e} AS ${i.raw(c(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?i`decode(${e}, 'hex')`:i`CAST(${e} AS ${i.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:M({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>i`encode(${e}, 'hex')`};aggregates={...k(`'Infinity'::float8`),min:(e,t=!1)=>t?i`BOOL_AND(${e})`:i`MIN(${e})`,max:(e,t=!1)=>t?i`BOOL_OR(${e})`:i`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:b(1e3)};json={equals:(e,t)=>i`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:postgresJsonArray,emptyArray:()=>i.raw`'[]'::json`,agg:e=>i`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>i`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>i`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>i`(${this.json.foldableStringAtPath(e,t)} COLLATE "C")`,foldableStringAtPath:(e,t)=>i`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END)`,contains:(e,t)=>i`(${e})::jsonb @> ${t}`,lastElement:e=>i`(${e})::jsonb -> -1`,value:e=>i`${L.from(e)}`};arrays={literal:e=>e.length===0?i.raw`'{}'`:i`ARRAY[${i.join(e,`, `)}]`,value:(e,t)=>i`${t?e.map(e=>typeof e==`string`?f(e):e):e}`,enumValue:e=>i`${R(e)}`,ofRows:e=>i`ARRAY(${e})`,has:(e,t)=>i`${t} = ANY(${e})`,hasEvery:(e,t)=>i`${e} @> ${t}`,hasSome:(e,t)=>i`${e} && ${t}`,isEmpty:e=>i`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS TEXT[])`,length:e=>i`cardinality(${e})`,get:(e,t)=>i`${e}[${t}]`,push:(e,t)=>i`array_append(${e}, ${t})`,set:(e,t,n)=>i`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...D(),nullsFirst:(e,t)=>t===`desc`?i`${e} DESC NULLS FIRST`:i`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?i`${e} DESC NULLS LAST`:i`${e} ASC NULLS LAST`};clauses=te();set={...y(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?H($,e,t,n.decimal):i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>i`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=F();subqueries=ne(Z);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e,{forUpdate:`append`},e.distinct)};cte=N(Z,{inlining:i.raw(`NOT MATERIALIZED`)});mutations={skipDuplicatesStrategy:`sql`,insert:O(Z),insertAbsent:j(Z),insertDefault:e=>i`INSERT INTO ${e} DEFAULT VALUES`,...P(),returning:e=>i`RETURNING ${e}`,upserted:i.raw(`(xmax = 0)`),...re()};assertions={exists:e=>i`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>i`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`};joins={...A(),full:(e,t)=>i`FULL OUTER JOIN ${e} ON ${t}`,...w(Z)};setOperations=_();capabilities={namesQualifiedColumns:!0,supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0,joinsJunctionFilters:`unbounded`,readsNodesByKey:!0,joinsToOneLaterally:!0,carriesDocumentsAsArrays:!0};lastInsertId=()=>i.raw`lastval()`;#t=z({table:i.raw`"__viborm_batch_refs"`,batchIdColumn:i.raw`"batch_id"`,keyColumn:i.raw`"ref_key"`,valueColumn:i.raw`"ref_value"`,createTable:i.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>i`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>i`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new r(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return i`${`[${e.join(`,`)}]`}::vector`},l2:(e,t,n)=>n===`exact`?i`(${e} <-> ${t}) + 0`:i`${e} <-> ${t}`,cosine:(e,t,n)=>n===`servable`?i`${e} <=> ${t}`:i`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>i`ST_X(${e}::geometry)`,latitude=e=>i`ST_Y(${e}::geometry)`;return{value:(e,t)=>i`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_SetSRID(ST_GeomFromGeoJSON(${V(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=i`RADIANS(ST_X(${e}::geometry))`,r=i`RADIANS(ST_Y(${e}::geometry))`,a=i`RADIANS(ST_X(${t}::geometry))`,o=i`RADIANS(ST_Y(${t}::geometry))`;return i`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${d} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${i`POWER(SIN((${o} - ${r}) / 2), 2) + COS(${r}) * COS(${o}) * POWER(SIN((${a} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>ee(e,t,`pg`)?.representation??`text`,parseResult:o,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
+ //# sourceMappingURL=postgres-adapter-Ia4u0-Ht.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-adapter-Ia4u0-Ht.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport type { TimeStep } from \"@validation/model/args/time-step\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n type PeriodSource,\n type PeriodSql,\n type TextMatch,\n type VectorOrderKey,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertAbsent,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\n/**\n * The `LIKE` pattern matching `value` literally where `kind` says. A plain\n * string (a bare bound parameter) is escaped here and bound as the finished\n * pattern; any other operand (a column, a JSON path) is escaped by the server.\n */\nfunction postgresLikePattern(kind: TextMatch, value: Sql): Sql {\n const head = kind === \"startsWith\" ? \"\" : \"%\";\n const tail = kind === \"endsWith\" ? \"\" : \"%\";\n const [literal, other] = value.values;\n if (\n value.strings.join(\"\") === \"\" &&\n typeof literal === \"string\" &&\n other === undefined\n )\n return sql`${head + escapeLikeLiteral(literal) + tail}`;\n return sql`(${sql.raw(head && \"'%' || \")}REPLACE(REPLACE(REPLACE(CAST(${value} AS TEXT), CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')${sql.raw(tail && \" || '%'\")})`;\n}\n/** The strings of `json_build_array` over `count` members, made once per count. */\nconst ARRAY_STRINGS: string[][] = [];\nfunction postgresJsonArray(items: Sql[]): Sql {\n if (items.length === 0) return sql.raw`'[]'::json`;\n // One call: its strings are a fact of the member count alone, and the\n // caller's own list holds its values, so a related row's document is one\n // fragment and nothing else.\n if (items.length <= 100) {\n let strings = ARRAY_STRINGS[items.length];\n if (strings === undefined) {\n strings = [\"json_build_array(\"];\n for (let at = 1; at < items.length; at++) strings.push(\", \");\n strings.push(\")\");\n ARRAY_STRINGS[items.length] = strings;\n }\n return new Sql(strings, items);\n }\n const chunks: Sql[] = [];\n // PostgreSQL limits a function call to 100 arguments, and one fragment\n // per call is what {@link postgresJsonObject} measured.\n for (let start = 0; start < items.length; start += 100) {\n const end = Math.min(items.length, start + 100);\n const strings = [\"jsonb_build_array(\"];\n for (let at = start + 1; at < end; at++) strings.push(\", \");\n strings.push(\")\");\n chunks.push(new Sql(strings, items.slice(start, end)));\n }\n return sql`(${sql.join(chunks, \" || \")})::json`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject =\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\";\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n // One fragment per call, each key its parameter: a fragment per key,\n // the list of them and the function's name were as many more to make\n // and to walk for every object of every nested read.\n const strings: string[] = [];\n const values: unknown[] = [];\n for (let at = start; at < pairs.length && at < start + 50; at++) {\n const [key, value] = pairs[at]!;\n strings.push(at === start ? `${buildObject}(` : \", \", \"::text, \");\n values.push(key, value);\n }\n strings.push(\")\");\n chunks.push(new Sql(strings, values));\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** `date_trunc`'s field for each step: a closed table, never caller text. */\nconst PERIOD_FIELD: Readonly<Record<TimeStep, Sql>> = Object.freeze({\n day: sql.raw`'day'`,\n week: sql.raw`'week'`,\n month: sql.raw`'month'`,\n quarter: sql.raw`'quarter'`,\n year: sql.raw`'year'`,\n});\n\n/**\n * Whether the column stores an instant: declared with a zone, or a native\n * type PostgreSQL reads as `timestamptz` in any spelling — the rule the\n * PostgreSQL migration driver applies to the same column.\n */\nconst storesInstant = ({ withTimezone, nativeType }: PeriodSource): boolean => {\n const native = nativeTypeFor(nativeType, \"pg\")?.type.toLowerCase();\n return native === undefined\n ? withTimezone\n : native.includes(\"timestamptz\") || native.includes(\"with time zone\");\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(\n quoteIdent,\n this.namespace,\n this.capabilities.namesQualifiedColumns\n );\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n // Always qualified by its schema.\n pinnedTable: this.identifiers.table,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n /**\n * `date_trunc` reads a `timestamptz` in the SESSION zone and turns a `date`\n * into one, so the wall time it truncates is always stated: the instant in\n * `zone`, a `timestamp` as stored, a `date` as a `timestamp`. The period is\n * a `date`, grouped and ordered as one, so it keeps its era (year zero is\n * 1 BC here); its text is `to_char`'s over a `timestamp`, which neither the\n * session's `DateStyle` nor its zone changes. A `week` starts on Monday.\n */\n period: PeriodSql = Object.freeze({\n of: (\n column: Sql,\n step: TimeStep,\n source: PeriodSource,\n zone: string\n ): Sql => {\n const wall = source.date\n ? sql`CAST(${column} AS TIMESTAMP)`\n : storesInstant(source)\n ? sql`(${column} AT TIME ZONE ${zone})`\n : column;\n return sql`CAST(date_trunc(${PERIOD_FIELD[step]}, ${wall}) AS DATE)`;\n },\n // `to_char` has no `date` form: given one, PostgreSQL picks the\n // `timestamptz` form, whose midnight is the session zone's and may not\n // exist there (Samoa skipped 2011-12-30). A `timestamp` has no zone.\n text: (period: Sql): Sql =>\n sql`to_char(CAST(${period} AS TIMESTAMP), 'YYYY-MM-DD BC')`,\n });\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"contains\", value)} ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"startsWith\", value)} ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ${postgresLikePattern(\"endsWith\", value)} ESCAPE '\\\\'`,\n // `ILIKE` folds case as the column's collation does: every letter on a\n // libc or ICU locale, ASCII only on a `C` one. On the bare column, so a\n // trigram index on it serves the filter.\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} ILIKE ${postgresLikePattern(kind, value)} ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration): Sql =>\n sql`LOWER(${this.expressions.caseSensitiveText(expr, nativeType, true)})`,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: postgresJsonArray,\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(${this.json.foldableStringAtPath(column, path)} COLLATE \"C\")`,\n foldableStringAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END)`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n ofRows: (query: Sql): Sql => sql`ARRAY(${query})`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n return assembleSelectQuery(\n parts,\n { forUpdate: \"append\" },\n parts.distinct\n );\n },\n };\n\n cte = createCteBuilders(quoteIdent, {\n inlining: sql.raw(\"NOT MATERIALIZED\"),\n });\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertAbsent: createInsertAbsent(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n // An inserted row version has no deleting transaction yet; the row an\n // ON CONFLICT update rewrote carries the updating one.\n upserted: sql.raw(\"(xmax = 0)\"),\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations();\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n namesQualifiedColumns: true,\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n joinsJunctionFilters: \"unbounded\",\n readsNodesByKey: true,\n joinsToOneLaterally: true,\n carriesDocumentsAsArrays: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n // pgvector's index serves `column <-> vector` as an ORDER BY key, and\n // nothing else: an exact order adds a zero it cannot see through.\n l2: (column: Sql, vector: Sql, order?: VectorOrderKey): Sql =>\n order === \"exact\"\n ? sql`(${column} <-> ${vector}) + 0`\n : sql`${column} <-> ${vector}`,\n\n // A zero vector's cosine distance is NaN; the value reads it as NULL, and\n // so does an exact order, which that NULLIF already keeps from an index.\n cosine: (column: Sql, vector: Sql, order?: VectorOrderKey): Sql =>\n order === \"servable\"\n ? sql`${column} <=> ${vector}`\n : sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"mkCAsFA,MAAM,EAAa,EAAuB,IAAI,CAM9C,SAAS,oBAAoB,EAAiB,EAAiB,CAC7D,IAAM,EAAO,IAAS,aAAe,GAAK,IACpC,EAAO,IAAS,WAAa,GAAK,IAClC,CAAC,EAAS,GAAS,EAAM,OAO/B,OALE,EAAM,QAAQ,KAAK,GAAG,GAAK,IAC3B,OAAO,GAAY,UACnB,IAAU,IAAA,GAEH,CAAG,GAAG,EAAO,EAAkB,EAAQ,CAAG,IAC5C,CAAG,IAAIA,EAAI,IAAI,GAAQ,UAAU,CAAC,+BAA+B,EAAM,qFAAqFA,EAAI,IAAI,GAAQ,UAAU,CAAC,GAGhM,MAAM,EAA4B,EAAE,CACpC,SAAS,kBAAkB,EAAmB,CAC5C,GAAI,EAAM,SAAW,EAAG,MAAO,GAAI,GAAG,aAItC,GAAI,EAAM,QAAU,IAAK,CACvB,IAAI,EAAU,EAAc,EAAM,QAClC,GAAI,IAAY,IAAA,GAAW,CACzB,EAAU,CAAC,oBAAoB,CAC/B,IAAK,IAAI,EAAK,EAAG,EAAK,EAAM,OAAQ,IAAM,EAAQ,KAAK,KAAK,CAC5D,EAAQ,KAAK,IAAI,CACjB,EAAc,EAAM,QAAU,EAEhC,OAAO,IAAI,EAAI,EAAS,EAAM,CAEhC,IAAM,EAAgB,EAAE,CAGxB,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,OAAQ,GAAS,IAAK,CACtD,IAAM,EAAM,KAAK,IAAI,EAAM,OAAQ,EAAQ,IAAI,CACzC,EAAU,CAAC,qBAAqB,CACtC,IAAK,IAAI,EAAK,EAAQ,EAAG,EAAK,EAAK,IAAM,EAAQ,KAAK,KAAK,CAC3D,EAAQ,KAAK,IAAI,CACjB,EAAO,KAAK,IAAI,EAAI,EAAS,EAAM,MAAM,EAAO,EAAI,C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AO,4BACzC,CAED,IAAkC,CAChC,IAAM,UAAa,GAAoB,CAAG,QAAQ,EAAM,aAClD,SAAY,GAAoB,CAAG,QAAQ,EAAM,aACvD,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,2BAA2B,EAAe,IAAI,EAAc,qBACjE,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,GAAG,EAAM,oCAAoC,EAAQ,qBAC3D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,iCAAiC,EACpD,EACD,CAAC,qBACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IAAU,CACzB,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,GAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./validation--qS7OPmg.mjs";import{o as n,r}from"./normalized-result-B8pifWS0.mjs";const i=/\s+/,a=/^[A-Za-z]+$/,o=new Set([`COPY`,`DELETE`,`FETCH`,`INSERT`,`MERGE`,`MOVE`,`SELECT`,`UPDATE`]),s=new Set(`ALTER.ANALYZE.BEGIN.CALL.CHECKPOINT.CLOSE.CLUSTER.COMMENT.COMMIT.CREATE.DEALLOCATE.DECLARE.DISCARD.DO.DROP.END.EXPLAIN.GRANT.IMPORT.LISTEN.LOAD.LOCK.NOTIFY.PREPARE.REASSIGN.REFRESH.REINDEX.RELEASE.RESET.REVOKE.ROLLBACK.SAVEPOINT.SECURITY.SET.SHOW.START.TRUNCATE.UNLISTEN.VACUUM`.split(`.`));function malformedPostgresResult(e,n){return new t(`Driver "${e.provider}" returned malformed PostgreSQL result metadata for operation "${e.operation}": ${n}.`,{meta:r(e)})}function commandTokenOf(e,t){let[n]=e.trim().split(i,1);if(!(n&&a.test(n)))throw malformedPostgresResult(t,`the command tag is invalid`);return n.toUpperCase()}function normalizePostgresRowCount(e,t,r,i){if(!Array.isArray(r))throw malformedPostgresResult(i,`the rows payload is not an array`);if(typeof t!=`string`)throw malformedPostgresResult(i,`the command tag is invalid`);let a=o.has(t)||s.has(t)?t:commandTokenOf(t,i),c=o.has(a),l=s.has(a);if(!(c||l))throw malformedPostgresResult(i,`the command tag is unknown`);if(e!==null)return n(e,i);if(c)throw malformedPostgresResult(i,`command ${a} requires a numeric row count`);return r.length}export{normalizePostgresRowCount as t};
2
+ //# sourceMappingURL=postgres-result-CiS5OWp1.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-result-CiS5OWp1.mjs","names":[],"sources":["../src/drivers/shared/postgres-result.ts"],"sourcesContent":["import { QueryError } from \"@errors\";\nimport {\n createNormalizedResultMeta,\n type NormalizedResultContext,\n normalizeProviderRowCount,\n} from \"../normalized-result\";\n\nconst COMMAND_SEPARATOR_REGEX = /\\s+/;\nconst COMMAND_TOKEN_REGEX = /^[A-Za-z]+$/;\n\nconst COUNTED_COMMANDS = new Set([\n \"COPY\",\n \"DELETE\",\n \"FETCH\",\n \"INSERT\",\n \"MERGE\",\n \"MOVE\",\n \"SELECT\",\n \"UPDATE\",\n]);\n\nconst NULLABLE_COUNT_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"BEGIN\",\n \"CALL\",\n \"CHECKPOINT\",\n \"CLOSE\",\n \"CLUSTER\",\n \"COMMENT\",\n \"COMMIT\",\n \"CREATE\",\n \"DEALLOCATE\",\n \"DECLARE\",\n \"DISCARD\",\n \"DO\",\n \"DROP\",\n \"END\",\n \"EXPLAIN\",\n \"GRANT\",\n \"IMPORT\",\n \"LISTEN\",\n \"LOAD\",\n \"LOCK\",\n \"NOTIFY\",\n \"PREPARE\",\n \"REASSIGN\",\n \"REFRESH\",\n \"REINDEX\",\n \"RELEASE\",\n \"RESET\",\n \"REVOKE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"SECURITY\",\n \"SET\",\n \"SHOW\",\n \"START\",\n \"TRUNCATE\",\n \"UNLISTEN\",\n \"VACUUM\",\n]);\n\nfunction malformedPostgresResult(\n context: NormalizedResultContext,\n reason: string\n): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned malformed PostgreSQL result metadata for operation \"${context.operation}\": ${reason}.`,\n { meta: createNormalizedResultMeta(context) }\n );\n}\n\n/** The command a tag names, upper case; a tag naming none is malformed. */\nfunction commandTokenOf(\n command: string,\n context: NormalizedResultContext\n): string {\n const [commandToken] = command.trim().split(COMMAND_SEPARATOR_REGEX, 1);\n if (!(commandToken && COMMAND_TOKEN_REGEX.test(commandToken))) {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n return commandToken.toUpperCase();\n}\n\n/**\n * PostgreSQL command tags carry a numeric count only for a defined set of\n * commands. Other known tags legitimately expose null, while missing metadata\n * and null counts for counted commands are malformed provider successes.\n */\nexport function normalizePostgresRowCount(\n value: unknown,\n command: unknown,\n rows: unknown,\n context: NormalizedResultContext\n): number {\n if (!Array.isArray(rows)) {\n throw malformedPostgresResult(context, \"the rows payload is not an array\");\n }\n if (typeof command !== \"string\") {\n throw malformedPostgresResult(context, \"the command tag is invalid\");\n }\n // A tag that is exactly a known command (`SELECT`, the one nearly every\n // statement answers) is its own token: read without trimming or splitting.\n const normalizedCommand =\n COUNTED_COMMANDS.has(command) || NULLABLE_COUNT_COMMANDS.has(command)\n ? command\n : commandTokenOf(command, context);\n const isCountedCommand = COUNTED_COMMANDS.has(normalizedCommand);\n const isNullableCountCommand = NULLABLE_COUNT_COMMANDS.has(normalizedCommand);\n if (!(isCountedCommand || isNullableCountCommand)) {\n throw malformedPostgresResult(context, \"the command tag is unknown\");\n }\n if (value !== null) {\n return normalizeProviderRowCount(value, context);\n }\n if (isCountedCommand) {\n throw malformedPostgresResult(\n context,\n `command ${normalizedCommand} requires a numeric row count`\n );\n }\n return rows.length;\n}\n"],"mappings":"8IAOA,MAAM,EAA0B,MAC1B,EAAsB,cAEtB,EAAmB,IAAI,IAAI,CAC/B,OACA,SACA,QACA,SACA,QACA,OACA,SACA,SACD,CAAC,CAEI,EAA0B,IAAI,IAAI,kSAwCvC,CAAC,CAEF,SAAS,wBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,WAAW,EAAQ,SAAS,iEAAiE,EAAQ,UAAU,KAAK,EAAO,GAC3H,CAAE,KAAM,EAA2B,EAAQ,CAAE,CAC9C,CAIH,SAAS,eACP,EACA,EACQ,CACR,GAAM,CAAC,GAAgB,EAAQ,MAAM,CAAC,MAAM,EAAyB,EAAE,CACvE,GAAI,EAAE,GAAgB,EAAoB,KAAK,EAAa,EAC1D,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,OAAO,EAAa,aAAa,CAQnC,SAAgB,0BACd,EACA,EACA,EACA,EACQ,CACR,GAAI,CAAC,MAAM,QAAQ,EAAK,CACtB,MAAM,wBAAwB,EAAS,mCAAmC,CAE5E,GAAI,OAAO,GAAY,SACrB,MAAM,wBAAwB,EAAS,6BAA6B,CAItE,IAAM,EACJ,EAAiB,IAAI,EAAQ,EAAI,EAAwB,IAAI,EAAQ,CACjE,EACA,eAAe,EAAS,EAAQ,CAChC,EAAmB,EAAiB,IAAI,EAAkB,CAC1D,EAAyB,EAAwB,IAAI,EAAkB,CAC7E,GAAI,EAAE,GAAoB,GACxB,MAAM,wBAAwB,EAAS,6BAA6B,CAEtE,GAAI,IAAU,KACZ,OAAO,EAA0B,EAAO,EAAQ,CAElD,GAAI,EACF,MAAM,wBACJ,EACA,WAAW,EAAkB,+BAC9B,CAEH,OAAO,EAAK"}
@@ -1,4 +1,5 @@
1
- import { Ma as DriverTransactionOptions, Na as TransactionOptionSupport, Ra as QueryExecutionContext, f as MigrationSessionAttestation, g as PinnedSessionReservation, it as NoExtraDriverConfigKeys, l as Driver, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
1
+ import { $a as QueryResult, Ka as DriverTransactionOptions, Qa as QueryExecutionContext, S as PinnedSessionReservation, h as Driver, li as Schema, pt as VibORMClient, qa as TransactionOptionSupport, st as DriverConfig, t as DatabaseAdapter, ut as NoExtraDriverConfigKeys, v as MigrationSessionAttestation, xi as LinkedClientConfig } from "./database-adapter-D62c-uC6.mjs";
2
+ import { t as NamedStatementsOption } from "./named-statements-Bdz2GD5R.mjs";
2
3
  import postgres, { Options, Sql } from "postgres";
3
4
 
4
5
  //#region src/drivers/postgres/index.d.ts
@@ -24,6 +25,19 @@ interface PostgresDriverOptions {
24
25
  * need it.
25
26
  */
26
27
  migrationSessionAttestation?: MigrationSessionAttestation;
28
+ /**
29
+ * Prepare statements on the server: each connection parses one once, and
30
+ * the statements of a transaction then go out together instead of one round
31
+ * trip each. With `true` (`{ max: 100, auto: true }`) a statement is
32
+ * prepared the second time it is sent; with `"explicit"`
33
+ * (`{ max: 100, auto: false }`) only the statements of a call that passes
34
+ * `named: true` are. A call's `named: true` prepares its statements at their
35
+ * first sending, `named: false` never, not even under
36
+ * `options: { prepare: true }`. A connection holds at most `max` of them.
37
+ * Off by default: behind PgBouncer in transaction mode, set
38
+ * `max_prepared_statements` first.
39
+ */
40
+ namedStatements?: NamedStatementsOption;
27
41
  }
28
42
  declare const vibormTypes: Record<string, postgres.PostgresType>;
29
43
  type PostgresClientConfig<C extends DriverConfig> = PostgresDriverOptions & C;
@@ -40,6 +54,8 @@ declare class PostgresDriver extends Driver<PostgresClient, PostgresTransaction>
40
54
  * holding the caller's transport while believing it had made its own.
41
55
  */
42
56
  private readonly suppliedClient;
57
+ /** The statements prepared, when `namedStatements` asks for them. */
58
+ private readonly named;
43
59
  constructor(options?: PostgresDriverOptions);
44
60
  /** Every host or URL this driver's client connects through, for migration admission. */
45
61
  protected migrationSessionEndpoints(): readonly unknown[];
package/dist/postgres.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{B as t,f as n,r,u as i}from"./error-mapping-B1-IWkCQ.mjs";import{n as a}from"./base-z-cH5ZBI.mjs";import{r as o}from"./validation--qS7OPmg.mjs";import{n as s}from"./suppressed-failure-CQkQsMVS.mjs";import{n as c}from"./client-DRpX3-vw.mjs";import{i as l,t as u}from"./pinned-session-DCoAZDOz.mjs";import{c as d,d as f,f as p,m,o as h,r as g,s as _,u as v}from"./driver-BIXhOH2_.mjs";import{t as y}from"./postgres-result-DF6DmW3r.mjs";import{t as b}from"./postgres-adapter-axapXX8d.mjs";import{n as x,t as S}from"./relation-bound-ku_cMdye.mjs";import C from"postgres";const w={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...w,...e.types}}),T={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends g{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client;let{host:n,hostname:r}=this.driverOptions.options??{};if(_(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==w.timestamp?.parse)throw new o(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}b(this,t,e),S(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?C(p(e),withVibormTypes(t)):C(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=await e.unsafe(t,n,{prepare:this.driverOptions.options?.prepare===!0}).catch(e=>{throw x(this.adapter,e),e});return{rows:o,rowCount:y(o.count,o.command,o,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,r,a,o){if(isTransaction(e))throw i(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,o?.maxWaitMs??5e3),t}},callback:r,phases:t(a),close:async()=>void 0})}isConnectionFailure(e){let t=r(e,{driverName:this.driverName,dialect:this.dialect});return t.code===a.CONNECTION_FAILED||t.code===a.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{await m(async()=>{await e.unsafe(`SELECT 1`)},()=>void 0,n,{driverName:this.driverName,form:`callback`});return}catch(e){if(s(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw i(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,T);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s}))}export{PostgresDriver,createClient,w as vibormTypes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{B as t,f as n,r,u as i}from"./error-mapping-DIRlrmDK.mjs";import{n as a}from"./base-z-cH5ZBI.mjs";import{r as o}from"./validation--qS7OPmg.mjs";import{n as s}from"./suppressed-failure-CQkQsMVS.mjs";import{n as c}from"./client-CVCC-D1j.mjs";import{i as l,t as u}from"./pinned-session-DCoAZDOz.mjs";import{c as d,d as f,f as p,m,o as h,r as g,s as _,u as v}from"./driver-Df88hu4U.mjs";import{t as y}from"./postgres-result-CiS5OWp1.mjs";import{i as b,r as x,t as S}from"./named-statements-CMj1QEyw.mjs";import{t as C}from"./postgres-adapter-Byp7Zpop.mjs";import{n as w,t as T}from"./relation-bound-BaU-LuuI.mjs";import E from"postgres";const D={timestamp:{to:1114,from:[1082,1114,1184],serialize:e=>e instanceof Date?e.toISOString():String(e),parse:e=>e},json:{to:114,from:[114,3802],serialize:e=>typeof e==`string`?e:JSON.stringify(e),parse:e=>JSON.parse(e)}};function encodeListParameters(e){return e.map(e=>Array.isArray(e)?`{${e.map(e=>e===null?`NULL`:`"${String(e).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`).join(`,`)}}`:e)}const withVibormTypes=(e={})=>({...e,types:{...D,...e.types}}),O={client:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,databaseUrl:!0,namespace:!0,migrationSessionAttestation:!0,namedStatements:!0},isTransaction=e=>`savepoint`in e;var PostgresDriver=class extends g{maxBindParametersPerStatement=65533;driverOptions;suppliedClient;named;constructor(e={}){super(`postgresql`,`postgres`);let t=f(e);this.driverOptions={databaseUrl:e.databaseUrl,options:{...e.options}},this.suppliedClient=e.client,this.named=x(`postgres`,e.namedStatements);let{host:n,hostname:r}=this.driverOptions.options??{};if(_(`postgres`,e,!!(this.suppliedClient||n||r)),this.suppliedClient){for(let e of[1082,1114,1184])if(this.suppliedClient.options?.parsers[e]!==D.timestamp?.parse)throw new o(`A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).`,{meta:{driver:`postgres`,operation:`configuration`}});this.client=this.suppliedClient}C(this,t,e),T(this.adapter,()=>{let e=this.client;return e&&!isTransaction(e)?e.parameters.server_version:void 0}),h(this,`migrationSessionAttestation`,v(e))}migrationSessionEndpoints(){let{databaseUrl:e,options:t}=this.driverOptions;return[e,t?.host,t?.hostname,...this.suppliedClient?.options.host??[]]}async initClient(){if(this.suppliedClient!==void 0)return this.suppliedClient;let{databaseUrl:e,options:t}=this.driverOptions;return e?E(p(e),withVibormTypes(t)):E(withVibormTypes(t))}async closeClient(e){e!==this.suppliedClient&&await e.end()}async execute(e,t,n,r){return this.executeQuery(e,t,encodeListParameters(n),r,`execute`)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n,r,`executeRaw`)}async executeQuery(e,t,n,r,i){let a=r?.operation??i,o=i===`execute`&&n?.length!==void 0&&n.length>0&&r?.model!==`$raw`&&this.named?.name(t,r?.named)!==void 0,fail=e=>{throw w(this.adapter,e),e},s=await e.unsafe(t,n,{prepare:o||r?.named!==!1&&this.driverOptions.options?.prepare===!0}).catch(r=>!o||b(r)!==S||(this.named?.drop(t),isTransaction(e))?fail(r):e.unsafe(t,n,{prepare:!1}).catch(fail));return{rows:s,rowCount:y(s.count,s.command,s,{provider:`postgres`,operation:a})}}transactionOptionSupport(){return{isolationLevel:`post-begin`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said`}}async transaction(e,r,a,o){if(isTransaction(e))throw i(this.driverName);return n({run:async t=>{let n=!1;try{return await e.begin(e=>(n=!0,t(e)))}catch(t){throw!n&&this.isConnectionFailure(t)&&await this.recoverFailedBegin(e,t,o?.maxWaitMs??5e3),t}},callback:r,phases:t(a),close:async()=>void 0})}isConnectionFailure(e){let t=r(e,{driverName:this.driverName,dialect:this.dialect});return t.code===a.CONNECTION_FAILED||t.code===a.CONNECTION_TIMEOUT}async recoverFailedBegin(e,t,n){let r=Date.now()+n;for(let n=0;n<2;n++){let n=r-Date.now();if(n<=0)break;try{await m(async()=>{await e.unsafe(`SELECT 1`)},()=>void 0,n,{driverName:this.driverName,form:`callback`});return}catch(e){if(s(t,e),!this.isConnectionFailure(e))break}}}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(isTransaction(e))throw i(this.driverName);let t=await e.reserve();return{session:t,release:(n,r)=>l({driverName:this.driverName,discard:n,lost:r,reset:()=>t.unsafe(`SELECT pg_advisory_unlock_all()`),release:()=>t.release(),closeOwnedTransport:e===this.suppliedClient?void 0:async()=>{this.client=null,this.initPromise=null,await e.end({timeout:u/1e3})}})}}};function createClient(e){d(e,`postgres`,O);let{client:t,options:n={},pgvector:r,postgis:i,databaseUrl:a}=e,o=f(e),s=v(e);return c(e,new PostgresDriver({client:t,options:n,...Object.hasOwn(e,`databaseUrl`)?{databaseUrl:a}:{},pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:o,migrationSessionAttestation:s,namedStatements:e.namedStatements}))}export{PostgresDriver,createClient,D as vibormTypes};
2
2
  //# sourceMappingURL=postgres.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n // postgres.js keeps every parameter status its connections received.\n boundByServer(this.adapter, () => {\n const client = this.client;\n return client && !isTransaction(client)\n ? client.parameters.server_version\n : undefined;\n });\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client\n .unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n })\n .catch((error: unknown) => {\n learnRelationLimit(this.adapter, error);\n throw error;\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with the\n // driver's own probe, never caller SQL; the callback above has provably\n // not entered. Not with `reserve()`: where the retained error refuses a\n // lease, postgres.js loses the connection the lease asked for, and with\n // `max: 1` every later query waits for ever (seen on Neon's direct\n // endpoint, where the socket closes before the fatal response is read).\n // A drain that cannot connect needs no quarantine: a connection failure\n // before the callback leaves no live session, and the next statement\n // that connects clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n await acquireWithMaxWait(\n async () => {\n await client.unsafe(\"SELECT 1\");\n },\n () => undefined,\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"umBAkFA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,QAAQ,EAAM,CAChB,IAAI,EAAM,IAAK,GAAY,IAAW,KAAO,OAAS,IAAI,OAAO,EAAO,CAAC,QAAQ,MAAO,OAAO,CAAC,QAAQ,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AAE,CAAE,WAAU,UAAS,eAAgB,EAC3D,EAAY,EAAuB,EAAO,CAC1C,EACJ,EAAyC,EAAO,CAelD,OAAO,EAAmD,EAb3C,IAAI,eAAe,CAChC,SACA,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACA,8BACD,CAAC,CAEuE"}
1
+ {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility. `namedStatements` prepares the\n * generated statements VibORM repeats, a bounded number of them per\n * connection; options.prepare: true prepares every statement, unbounded.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport {\n type NamedStatements,\n type NamedStatementsOption,\n namedStatements,\n REPLACED_TYPE,\n routineOf,\n} from \"../shared/named-statements\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport { boundByServer, learnRelationLimit } from \"../shared/relation-bound\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n /** Each relation filter body a statement repeats is stated once (default `true`); `false` keeps every body inline. */\n sharedRelationBodies?: boolean;\n /** The most relations (`FROM` items) one statement may reference: past it, a statement repeating recursive filters states them as key sets, which some plans pay for. PlanetScale Neki refuses more than 256: absent, the driver reads each connection's startup, 256 on Neki and before the first connection, none elsewhere. A stated bound always wins. Only where relation bodies are shared. */\n relationsPerStatement?: number;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n /**\n * Prepare statements on the server: each connection parses one once, and\n * the statements of a transaction then go out together instead of one round\n * trip each. With `true` (`{ max: 100, auto: true }`) a statement is\n * prepared the second time it is sent; with `\"explicit\"`\n * (`{ max: 100, auto: false }`) only the statements of a call that passes\n * `named: true` are. A call's `named: true` prepares its statements at their\n * first sending, `named: false` never, not even under\n * `options: { prepare: true }`. A connection holds at most `max` of them.\n * Off by default: behind PgBouncer in transaction mode, set\n * `max_prepared_statements` first.\n */\n namedStatements?: NamedStatementsOption;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n sharedRelationBodies: true,\n relationsPerStatement: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n namedStatements: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n /** The statements prepared, when `namedStatements` asks for them. */\n private readonly named: NamedStatements | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n this.named = namedStatements(\"postgres\", options.namedStatements);\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n // postgres.js keeps every parameter status its connections received.\n boundByServer(this.adapter, () => {\n const client = this.client;\n return client && !isTransaction(client)\n ? client.parameters.server_version\n : undefined;\n });\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n // postgres.js retries a prepared statement the server lost, once, itself.\n // Raw SQL is the caller's text, tagged or not: never prepared here.\n const named =\n fallbackOperation === \"execute\" &&\n params?.length !== undefined &&\n params.length > 0 &&\n context?.model !== \"$raw\" &&\n this.named?.name(sqlStr, context?.named) !== undefined;\n const fail = (error: unknown): never => {\n learnRelationLimit(this.adapter, error);\n throw error;\n };\n const result = await client\n .unsafe<T[]>(sqlStr, params, {\n prepare:\n named ||\n (context?.named !== false &&\n this.driverOptions.options?.prepare === true),\n })\n .catch((error: unknown) => {\n // postgres.js retries a statement the server lost, or whose result\n // type changed, itself, but not one whose parameter type a migration\n // replaced, and it keys its statements by text: this text is no\n // longer prepared. Alone, the statement failed before it did anything\n // and is sent once more; in a transaction, the failure aborted it.\n if (!named || routineOf(error) !== REPLACED_TYPE) return fail(error);\n this.named?.drop(sqlStr);\n if (isTransaction(client)) return fail(error);\n return client\n .unsafe<T[]>(sqlStr, params, { prepare: false })\n .catch(fail);\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with the\n // driver's own probe, never caller SQL; the callback above has provably\n // not entered. Not with `reserve()`: where the retained error refuses a\n // lease, postgres.js loses the connection the lease asked for, and with\n // `max: 1` every later query waits for ever (seen on Neon's direct\n // endpoint, where the socket closes before the fatal response is read).\n // A drain that cannot connect needs no quarantine: a connection failure\n // before the callback leaves no live session, and the next statement\n // that connects clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n await acquireWithMaxWait(\n async () => {\n await client.unsafe(\"SELECT 1\");\n },\n () => undefined,\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n sharedRelationBodies: config.sharedRelationBodies,\n relationsPerStatement: config.relationsPerStatement,\n namespace,\n migrationSessionAttestation,\n namedStatements: config.namedStatements,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"yqBAuGA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,QAAQ,EAAM,CAChB,IAAI,EAAM,IAAK,GAAY,IAAW,KAAO,OAAS,IAAI,OAAO,EAAO,CAAC,QAAQ,MAAO,OAAO,CAAC,QAAQ,KAAM,MAAM,CAAC,GAAI,CAAC,KAAK,IAAI,CAAC,GACpI,EACL,CAGH,MAAM,iBAAmB,EAA2B,EAAE,IAAuB,CAC3E,GAAG,EACH,MAAO,CAAE,GAAG,EAAa,GAAG,EAAQ,MAAO,CAC5C,EAKK,EAAkE,CACtE,OAAQ,GACR,QAAS,GACT,SAAU,GACV,QAAS,GACT,qBAAsB,GACtB,sBAAuB,GACvB,YAAa,GACb,UAAW,GACX,4BAA6B,GAC7B,gBAAiB,G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AAC,EAE/D,CAAC,CACL,GAQL,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,WAAY,EAAqB,CACvE,GAAM,CAAE,SAAQ,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAC3D,EAAY,EAAuB,EAAO,CAC1C,EACJ,EAAyC,EAAO,CAgBlD,OAAO,EAAmD,EAd3C,IAAI,eAAe,CAChC,SACA,UAEA,GAAI,OAAO,OAAO,EAAQ,cAAc,CAAG,CAAE,cAAa,CAAG,EAAE,CAC/D,WACA,UACA,qBAAsB,EAAO,qBAC7B,sBAAuB,EAAO,sBAC9B,YACA,8BACA,gBAAiB,EAAO,gBACzB,CAAC,CAEuE"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{M as t}from"./native-types-DgjMUikz.mjs";const n={postgresql:`pg`,mysql:`mysql`,sqlite:`sqlite`};function findDecimalProviderLimitRefusal(e,r){let i=n[r];if(i)for(let[n,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(i,e.decimal);if(s!==void 0)return{modelName:n,fieldName:a,dialect:r,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
- //# sourceMappingURL=provider-limits-Ccsb8PTb.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{M as t}from"./native-types-DspZ0Z5E.mjs";const n={postgresql:`pg`,mysql:`mysql`,sqlite:`sqlite`};function findDecimalProviderLimitRefusal(e,r){let i=n[r];if(i)for(let[n,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(i,e.decimal);if(s!==void 0)return{modelName:n,fieldName:a,dialect:r,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
+ //# sourceMappingURL=provider-limits-CCOa4d1E.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-limits-Ccsb8PTb.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { Dialect } from \"@drivers/types\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: Dialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/**\n * The dialects with no limit to fit: a SurrealDB `decimal` holds any\n * precision and scale, and VibORM stores nothing in Snowflake.\n */\ntype NoDecimalLimit = \"surrealql\" | \"snowflake\";\n\n/**\n * Every other dialect in the decimal codec's physical vocabulary: one added\n * to `Dialect` does not compile until it is here or above. Checked by the type\n * only, so the dialects above cost an application no byte.\n */\nconst DECIMAL_DIALECT: Readonly<Partial<Record<Dialect, DecimalDialect>>> = {\n postgresql: \"pg\",\n mysql: \"mysql\",\n sqlite: \"sqlite\",\n} satisfies Record<Exclude<Dialect, NoDecimalLimit>, DecimalDialect>;\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: Dialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = DECIMAL_DIALECT[dialect];\n if (!decimalDialect) return;\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"yFAsCA,MAAM,EAAsE,CAC1E,WAAY,KACZ,MAAO,QACP,OAAQ,SACT,CAGD,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,EAAgB,GAClC,KACL,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
1
+ {"version":3,"file":"provider-limits-CCOa4d1E.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { Dialect } from \"@drivers/types\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: Dialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/**\n * The dialects with no limit to fit: a SurrealDB `decimal` holds any\n * precision and scale, and VibORM stores nothing in Snowflake.\n */\ntype NoDecimalLimit = \"surrealql\" | \"snowflake\";\n\n/**\n * Every other dialect in the decimal codec's physical vocabulary: one added\n * to `Dialect` does not compile until it is here or above. Checked by the type\n * only, so the dialects above cost an application no byte.\n */\nconst DECIMAL_DIALECT: Readonly<Partial<Record<Dialect, DecimalDialect>>> = {\n postgresql: \"pg\",\n mysql: \"mysql\",\n sqlite: \"sqlite\",\n} satisfies Record<Exclude<Dialect, NoDecimalLimit>, DecimalDialect>;\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: Dialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = DECIMAL_DIALECT[dialect];\n if (!decimalDialect) return;\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"yFAsCA,MAAM,EAAsE,CAC1E,WAAY,KACZ,MAAO,QACP,OAAQ,SACT,CAGD,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,EAAgB,GAClC,KACL,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{p as n}from"./validation--qS7OPmg.mjs";import{t as r}from"./sql-3o4DOKm9.mjs";import{r as i}from"./value-guards-CBuxSC66.mjs";const a=new WeakMap;function registerPreparedStatement(e,t){a.set(e,t)}function transferPreparedStatement(e,t){let n=a.get(e);return n!==void 0&&a.set(t,n),t}function snapshotPreparedStatement(e,t,n){let i=a.get(e);return i!==void 0&&a.set(t,new r([...i.strings],[...n])),t}function readPreparedStatement(e){return a.get(e)}const o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const c=captureBuiltinPrototype(Object.prototype),l=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!s.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,c)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,t,n){if(!i(e))return;let r=Date.prototype.getTime.call(e);if(Number.isNaN(r))throw n(t);return r}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,r){return new n(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${r}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:t.INVALID_INPUT,meta:{parameterIndex:r,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,r){return new n(`Operation "${e.operation??`statement`}" received raw array parameter ${r} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:t.INVALID_INPUT,meta:{parameterIndex:r,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}export{readPreparedStatement as a,transferPreparedStatement as c,markVerbatimBatchQuery as i,validateRawParameters as n,registerPreparedStatement as o,isVerbatimBatchQuery as r,snapshotPreparedStatement as s,snapshotProviderParameters as t};
2
- //# sourceMappingURL=provider-parameter-snapshot-BikrgKqI.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{p as n}from"./validation--qS7OPmg.mjs";import{t as r}from"./sql-BGjAsoBE.mjs";import{r as i}from"./value-guards-CBuxSC66.mjs";const a=new WeakMap;function registerPreparedStatement(e,t){a.set(e,t)}function transferPreparedStatement(e,t){let n=a.get(e);return n!==void 0&&a.set(t,n),t}function snapshotPreparedStatement(e,t,n){let i=a.get(e);return i!==void 0&&a.set(t,new r([...i.strings],[...n])),t}function readPreparedStatement(e){return a.get(e)}const o=Symbol(`viborm.verbatimBatchQuery`);function markVerbatimBatchQuery(e){return Object.defineProperty(e,o,{configurable:!1,enumerable:!1,value:!0,writable:!1}),e}function isVerbatimBatchQuery(e){return Reflect.get(e,o)===!0}const s=/^(?:0|[1-9]\d*)$/;function captureBuiltinPrototype(e){let t=[];for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&t.push({descriptor:r,key:n})}return Object.freeze(t)}const c=captureBuiltinPrototype(Object.prototype),l=captureBuiltinPrototype(Array.prototype);function isArrayIndex(e){if(typeof e!=`string`||!s.test(e))return!1;let t=Number(e);return t<=4294967294&&String(t)===e}function functionSource(e){if(typeof e==`function`)try{return Function.prototype.toString.call(e)}catch{return}}function sameInertRecord(e,t){if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return Object.is(e,t);try{if(Object.getPrototypeOf(e)!==null||Object.getPrototypeOf(t)!==null)return!1;let n=Reflect.ownKeys(e),r=Reflect.ownKeys(t);if(n.length!==r.length)return!1;for(let i=0;i<r.length;i+=1){let a=n[i],o=r[i];if(a!==o||o===void 0)return!1;let s=Object.getOwnPropertyDescriptor(e,o),c=Object.getOwnPropertyDescriptor(t,o);if(s===void 0||c===void 0||!(`value`in s)||!(`value`in c)||s.configurable!==c.configurable||s.enumerable!==c.enumerable||s.writable!==c.writable||!Object.is(s.value,c.value))return!1}return!0}catch{return!1}}function sameBuiltinDescriptor(e,t){if(e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t)return!1;if(`value`in e&&`value`in t){if(e.writable!==t.writable)return!1;let n=functionSource(t.value);return n===void 0?sameInertRecord(e.value,t.value):functionSource(e.value)===n}return functionSource(e.get)===functionSource(t.get)&&functionSource(e.set)===functionSource(t.set)}function hasBuiltinPrototypeShape(e,t){try{let n=Reflect.ownKeys(e);if(n.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i===void 0||n[r]!==i.key)return!1;let a=Object.getOwnPropertyDescriptor(e,i.key);if(a===void 0||!sameBuiltinDescriptor(a,i.descriptor))return!1}return!0}catch{return!1}}function isObjectPrototype(e){try{return Object.getPrototypeOf(e)===null&&hasBuiltinPrototypeShape(e,c)}catch{return!1}}function isArrayPrototype(e){try{let t=Object.getPrototypeOf(e);return t!==null&&isObjectPrototype(t)&&hasBuiltinPrototypeShape(e,l)}catch{return!1}}function rawParameterNodeShape(e){let t=!1;try{t=Array.isArray(e);let n=Object.getPrototypeOf(e);if(t&&n!==null&&!isArrayPrototype(n)||!t&&n!==null&&!isObjectPrototype(n))return{kind:t?`unsupported-array`:`opaque`};let r=[],i=[];for(let n of Reflect.ownKeys(e)){let a=Object.getOwnPropertyDescriptor(e,n);if(a!==void 0&&(i.push({descriptor:a,key:n}),t?isArrayIndex(n):a.enumerable&&typeof n==`string`)){if(!(`value`in a))return{kind:t?`unsupported-array`:`opaque`};r.push({descriptor:a,key:n,value:a.value})}}let a=i.find(e=>e.key===`toJSON`);return a&&(!(`value`in a.descriptor)||typeof a.descriptor.value==`function`)?{kind:t?`unsupported-array`:`opaque`}:{kind:`node`,shape:{edges:r,isArray:t,properties:i,prototype:n}}}catch{return{kind:t?`unsupported-array`:`opaque`}}}function rawDateTime(e,t,n){if(!i(e))return;let r=Date.prototype.getTime.call(e);if(Number.isNaN(r))throw n(t);return r}function analyzeRawParameterGraph(e,t){let n=new WeakMap,r=new WeakMap,i=[],a=Array(e.length),discover=(e,a)=>{let o=rawDateTime(e,a,t.invalidDate);if(o!==void 0&&typeof e==`object`&&e){r.set(e,o);return}if(typeof e!=`object`||!e)return;let s=n.get(e);if(s)return s;let c=rawParameterNodeShape(e);if(c.kind===`unsupported-array`)throw t.unsupportedArray(a);if(c.kind===`opaque`)return;let l={...c.shape,source:e};return n.set(e,l),i.push(l),l};for(let n=0;n<e.length;n++){if(!Object.hasOwn(e,n))continue;let o=e[n];a[n]=o;let s=rawDateTime(o,n,t.invalidDate);if(s!==void 0&&typeof o==`object`&&o){r.set(o,s);continue}let c=discover(o,n);if(!c)continue;let l=[c],u=0;for(;u<l.length;){let e=l[u];if(u+=1,e)for(let t of e.edges){let e=i.length,r=discover(t.value,n);r&&i.length>e&&l.push(r)}}}return{dateTimes:r,nodes:i,roots:a}}function validateRawParameters(e,t){analyzeRawParameterGraph(e,t)}function snapshotRawParameterGraph(e,t){let n=analyzeRawParameterGraph(e,t),r=new WeakMap,i=new WeakMap;for(let e of n.nodes){let t=e.isArray?[]:{};e.prototype===null&&Object.setPrototypeOf(t,null),r.set(e.source,t)}let copiedValue=e=>{if(typeof e!=`object`||!e)return e;let t=n.dateTimes.get(e);if(t!==void 0){let n=i.get(e);if(n)return n;let r=new Date(t);return i.set(e,r),r}return r.get(e)??e};for(let e of n.nodes){let t=r.get(e.source);if(t){for(let n of e.properties){if(e.isArray&&n.key===`length`)continue;let r=n.descriptor;Object.defineProperty(t,n.key,`value`in r&&(e.isArray?isArrayIndex(n.key):r.enumerable&&typeof n.key==`string`)?{...r,value:copiedValue(r.value)}:r)}if(e.isArray){let n=e.properties.find(e=>e.key===`length`);n&&Object.defineProperty(t,`length`,n.descriptor)}}}let a=Array(n.roots.length);for(let e=0;e<n.roots.length;e++)Object.hasOwn(n.roots,e)&&(a[e]=copiedValue(n.roots[e]));return a}function invalidProviderDateError(e,r){return new n(`Operation "${e.operation??`statement`}" received an invalid Date as bound parameter ${r}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,{code:t.INVALID_INPUT,meta:{parameterIndex:r,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function unsupportedProviderArrayError(e,r){return new n(`Operation "${e.operation??`statement`}" received raw array parameter ${r} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,{code:t.INVALID_INPUT,meta:{parameterIndex:r,model:e.model,operation:e.operation,correlationId:e.correlationId}})}function snapshotProviderParameters(e,t){return t.model===`$raw`?snapshotRawParameterGraph(e,{invalidDate:e=>invalidProviderDateError(t,e),unsupportedArray:e=>unsupportedProviderArrayError(t,e)}):[...e]}export{readPreparedStatement as a,transferPreparedStatement as c,markVerbatimBatchQuery as i,validateRawParameters as n,registerPreparedStatement as o,isVerbatimBatchQuery as r,snapshotPreparedStatement as s,snapshotProviderParameters as t};
2
+ //# sourceMappingURL=provider-parameter-snapshot-C0ehKSAA.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-parameter-snapshot-BikrgKqI.mjs","names":[],"sources":["../src/drivers/prepared-statement-provenance.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/provider-parameter-snapshot.ts"],"sourcesContent":["import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before any first moment runs. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n"],"mappings":"sNAEA,MAAM,EAAqB,IAAI,QAG/B,SAAgB,0BAA0B,EAAe,EAAsB,CAC7E,EAAmB,IAAI,EAAO,EAAU,CAI1C,SAAgB,0BACd,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAEhD,OADI,IAAc,IAAA,IAAW,EAAmB,IAAI,EAAQ,EAAU,CAC/D,EAIT,SAAgB,0BACd,EACA,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAOhD,OANI,IAAc,IAAA,IAChB,EAAmB,IACjB,EACA,IAAI,EAAI,CAAC,GAAG,EAAU,QAAQ,CAAE,CAAC,GAAG,EAAO,CAAC,CAC7C,CAEI,EAIT,SAAgB,sBAAsB,EAAgC,CACpE,OAAO,EAAmB,IAAI,EAAM,CCnCtC,MAAM,EAAuB,OAAO,4BAA4B,CAGhE,SAAgB,uBAAyC,EAAa,CAOpE,OANA,OAAO,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AI,EAAK,QAAS,CAChB,IAAM,EAAS,EAAK,WAAW,KAC5B,GAAa,EAAS,MAAQ,SAChC,CACG,GAAQ,OAAO,eAAe,EAAM,SAAU,EAAO,WAAW,GAIxE,IAAM,EAAe,MAAe,EAAM,MAAM,OAAO,CACvD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAM,MAAM,OAAQ,IACzC,OAAO,OAAO,EAAM,MAAO,EAAM,GACtC,EAAS,GAAS,YAAY,EAAM,MAAM,GAAO,EAEnD,OAAO,EAGT,SAAS,yBACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,cAAc,EAAQ,WAAa,YAAY,gDAAgD,EAAe,oHAC9G,CACE,KAAM,EAAgB,cACtB,KAAM,CACJ,iBACA,MAAO,EAAQ,MACf,UAAW,EAAQ,UACnB,cAAe,EAAQ,cACxB,CACF,CACF,CAGH,SAAS,8BACP,EACA,EACY,CACZ,OAAO,IAAI,EACT,cAAc,EAAQ,WAAa,YAAY,iCAAiC,EAAe,iIAC/F,CACE,KAAM,EAAgB,cACtB,KAAM,CACJ,iBACA,MAAO,EAAQ,MACf,UAAW,EAAQ,UACnB,cAAe,EAAQ,cACxB,CACF,CACF,CAcH,SAAgB,2BACd,EACA,EACW,CAEX,OADI,EAAQ,QAAU,OACf,0BAA0B,EAAQ,CACvC,YAAc,GACZ,yBAAyB,EAAS,EAAe,CACnD,iBAAmB,GACjB,8BAA8B,EAAS,EAAe,CACzD,CAAC,CANmC,CAAC,GAAG,EAAO"}
1
+ {"version":3,"file":"provider-parameter-snapshot-C0ehKSAA.mjs","names":[],"sources":["../src/drivers/prepared-statement-provenance.ts","../src/drivers/driver-batch-query-kind.ts","../src/drivers/provider-parameter-snapshot.ts"],"sourcesContent":["import { Sql } from \"@sql\";\n\nconst preparedStatements = new WeakMap<object, Sql>();\n\n/** Retain the typed Sql behind a rendered batch query without publishing it. */\nexport function registerPreparedStatement(query: object, statement: Sql): void {\n preparedStatements.set(query, statement);\n}\n\n/** Preserve private provenance when an internal owner snapshots a batch query. */\nexport function transferPreparedStatement<Output extends object>(\n source: object,\n output: Output\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) preparedStatements.set(output, statement);\n return output;\n}\n\n/** Preserve provenance with the exact detached values a batch will execute. */\nexport function snapshotPreparedStatement<Output extends object>(\n source: object,\n output: Output,\n values: readonly unknown[]\n): Output {\n const statement = preparedStatements.get(source);\n if (statement !== undefined) {\n preparedStatements.set(\n output,\n new Sql([...statement.strings], [...values])\n );\n }\n return output;\n}\n\n/** Read provenance only at the trusted typed-statement execution boundary. */\nexport function readPreparedStatement(query: object): Sql | undefined {\n return preparedStatements.get(query);\n}\n","/** Internal execution-kind metadata for prepared batch queries. */\n\nconst VERBATIM_BATCH_QUERY = Symbol(\"viborm.verbatimBatchQuery\");\n\n/** Mark a prepared raw statement that must retain verbatim driver semantics. */\nexport function markVerbatimBatchQuery<T extends object>(query: T): T {\n Object.defineProperty(query, VERBATIM_BATCH_QUERY, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n return query;\n}\n\n/** Whether a prepared statement came from an unsafe or legacy raw call. */\nexport function isVerbatimBatchQuery(query: object): boolean {\n return Reflect.get(query, VERBATIM_BATCH_QUERY) === true;\n}\n","import { QueryError, VibORMErrorCode } from \"@errors\";\nimport { isDate } from \"@validation/value-guards\";\nimport type { QueryExecutionContext } from \"./types\";\n\ntype InvalidRawDateError = (parameterIndex: number) => Error;\ntype UnsupportedRawArrayError = (parameterIndex: number) => Error;\n\ninterface RawParameterErrors {\n readonly invalidDate: InvalidRawDateError;\n readonly unsupportedArray: UnsupportedRawArrayError;\n}\n\ninterface RawParameterEdge {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n readonly value: unknown;\n}\n\ninterface RawParameterNode {\n readonly edges: readonly RawParameterEdge[];\n readonly isArray: boolean;\n readonly properties: readonly RawParameterProperty[];\n readonly prototype: object | null;\n readonly source: object;\n}\n\ninterface RawParameterProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\ninterface RawParameterGraph {\n readonly dateTimes: WeakMap<object, number>;\n readonly nodes: readonly RawParameterNode[];\n readonly roots: readonly unknown[];\n}\n\ntype RawParameterNodeAnalysis =\n | { readonly kind: \"node\"; readonly shape: Omit<RawParameterNode, \"source\"> }\n | { readonly kind: \"opaque\" }\n | { readonly kind: \"unsupported-array\" };\n\nconst arrayIndex = /^(?:0|[1-9]\\d*)$/;\nconst maximumArrayIndex = 4_294_967_294;\n\ninterface BuiltinPrototypeProperty {\n readonly descriptor: PropertyDescriptor;\n readonly key: PropertyKey;\n}\n\nfunction captureBuiltinPrototype(\n prototype: object\n): readonly BuiltinPrototypeProperty[] {\n const properties: BuiltinPrototypeProperty[] = [];\n for (const key of Reflect.ownKeys(prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, key);\n if (descriptor) properties.push({ descriptor, key });\n }\n return Object.freeze(properties);\n}\n\nconst objectPrototypeShape = captureBuiltinPrototype(Object.prototype);\nconst arrayPrototypeShape = captureBuiltinPrototype(Array.prototype);\n\nfunction isArrayIndex(key: PropertyKey): boolean {\n if (typeof key !== \"string\" || !arrayIndex.test(key)) return false;\n const index = Number(key);\n return index <= maximumArrayIndex && String(index) === key;\n}\n\nfunction functionSource(value: unknown): string | undefined {\n if (typeof value !== \"function\") return;\n try {\n return Function.prototype.toString.call(value);\n } catch {\n return;\n }\n}\n\nfunction sameInertRecord(left: unknown, right: unknown): boolean {\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\"\n ) {\n return Object.is(left, right);\n }\n try {\n if (\n Object.getPrototypeOf(left) !== null ||\n Object.getPrototypeOf(right) !== null\n ) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length) return false;\n for (let index = 0; index < rightKeys.length; index += 1) {\n const leftKey = leftKeys[index];\n const rightKey = rightKeys[index];\n if (leftKey !== rightKey || rightKey === undefined) return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, rightKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, rightKey);\n if (\n leftDescriptor === undefined ||\n rightDescriptor === undefined ||\n !(\"value\" in leftDescriptor) ||\n !(\"value\" in rightDescriptor) ||\n leftDescriptor.configurable !== rightDescriptor.configurable ||\n leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.writable !== rightDescriptor.writable ||\n !Object.is(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction sameBuiltinDescriptor(\n actual: PropertyDescriptor,\n expected: PropertyDescriptor\n): boolean {\n if (\n actual.configurable !== expected.configurable ||\n actual.enumerable !== expected.enumerable ||\n \"value\" in actual !== \"value\" in expected\n ) {\n return false;\n }\n if (\"value\" in actual && \"value\" in expected) {\n if (actual.writable !== expected.writable) return false;\n const expectedSource = functionSource(expected.value);\n if (expectedSource !== undefined) {\n return functionSource(actual.value) === expectedSource;\n }\n return sameInertRecord(actual.value, expected.value);\n }\n return (\n functionSource(actual.get) === functionSource(expected.get) &&\n functionSource(actual.set) === functionSource(expected.set)\n );\n}\n\nfunction hasBuiltinPrototypeShape(\n prototype: object,\n shape: readonly BuiltinPrototypeProperty[]\n): boolean {\n try {\n const keys = Reflect.ownKeys(prototype);\n if (keys.length !== shape.length) return false;\n for (let index = 0; index < shape.length; index += 1) {\n const expected = shape[index];\n if (expected === undefined || keys[index] !== expected.key) return false;\n const actual = Object.getOwnPropertyDescriptor(prototype, expected.key);\n if (\n actual === undefined ||\n !sameBuiltinDescriptor(actual, expected.descriptor)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isObjectPrototype(prototype: object): boolean {\n try {\n return (\n Object.getPrototypeOf(prototype) === null &&\n hasBuiltinPrototypeShape(prototype, objectPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\nfunction isArrayPrototype(prototype: object): boolean {\n try {\n const parent = Object.getPrototypeOf(prototype);\n return (\n parent !== null &&\n isObjectPrototype(parent) &&\n hasBuiltinPrototypeShape(prototype, arrayPrototypeShape)\n );\n } catch {\n return false;\n }\n}\n\n/** Only arrays and records with inert inherited behavior are interpreted. */\nfunction rawParameterNodeShape(value: object): RawParameterNodeAnalysis {\n let isArray = false;\n try {\n isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (\n (isArray && prototype !== null && !isArrayPrototype(prototype)) ||\n (!isArray && prototype !== null && !isObjectPrototype(prototype))\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n\n const edges: RawParameterEdge[] = [];\n const properties: RawParameterProperty[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n properties.push({ descriptor, key });\n const isProviderVisible = isArray\n ? isArrayIndex(key)\n : descriptor.enumerable && typeof key === \"string\";\n if (!isProviderVisible) continue;\n if (!(\"value\" in descriptor)) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n edges.push({ descriptor, key, value: descriptor.value });\n }\n const toJSON = properties.find((property) => property.key === \"toJSON\");\n if (\n toJSON &&\n (!(\"value\" in toJSON.descriptor) ||\n typeof toJSON.descriptor.value === \"function\")\n ) {\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n return {\n kind: \"node\",\n shape: { edges, isArray, properties, prototype },\n };\n } catch {\n // An exotic record owns its traversal semantics. If reflection refuses an\n // array shape, it cannot safely reach provider array semantics.\n return { kind: isArray ? \"unsupported-array\" : \"opaque\" };\n }\n}\n\nfunction rawDateTime(\n value: unknown,\n parameterIndex: number,\n invalidDateError: InvalidRawDateError\n): number | undefined {\n if (!isDate(value)) return;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) throw invalidDateError(parameterIndex);\n return time;\n}\n\nfunction analyzeRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): RawParameterGraph {\n const nodesBySource = new WeakMap<object, RawParameterNode>();\n const dateTimes = new WeakMap<object, number>();\n const nodes: RawParameterNode[] = [];\n const roots = new Array<unknown>(params.length);\n\n const discover = (\n value: unknown,\n parameterIndex: number\n ): RawParameterNode | undefined => {\n const time = rawDateTime(value, parameterIndex, errors.invalidDate);\n if (time !== undefined && typeof value === \"object\" && value !== null) {\n dateTimes.set(value, time);\n return;\n }\n if (typeof value !== \"object\" || value === null) return;\n\n const known = nodesBySource.get(value);\n if (known) return known;\n const analysis = rawParameterNodeShape(value);\n if (analysis.kind === \"unsupported-array\") {\n throw errors.unsupportedArray(parameterIndex);\n }\n if (analysis.kind === \"opaque\") return;\n const node: RawParameterNode = {\n ...analysis.shape,\n source: value,\n };\n nodesBySource.set(value, node);\n nodes.push(node);\n return node;\n };\n\n for (\n let parameterIndex = 0;\n parameterIndex < params.length;\n parameterIndex++\n ) {\n if (!Object.hasOwn(params, parameterIndex)) continue;\n const root = params[parameterIndex];\n roots[parameterIndex] = root;\n const rootTime = rawDateTime(root, parameterIndex, errors.invalidDate);\n if (rootTime !== undefined && typeof root === \"object\" && root !== null) {\n dateTimes.set(root, rootTime);\n continue;\n }\n const rootNode = discover(root, parameterIndex);\n if (!rootNode) continue;\n\n const pending = [rootNode];\n let cursor = 0;\n while (cursor < pending.length) {\n const node = pending[cursor];\n cursor += 1;\n if (!node) continue;\n for (const edge of node.edges) {\n const before = nodes.length;\n const child = discover(edge.value, parameterIndex);\n if (child && nodes.length > before) pending.push(child);\n }\n }\n }\n\n return { dateTimes, nodes, roots };\n}\n\n/** Validate every interpreted raw parameter before any first moment runs. */\nexport function validateRawParameters(\n params: readonly unknown[],\n errors: RawParameterErrors\n): void {\n analyzeRawParameterGraph(params, errors);\n}\n\n/**\n * Snapshot every admitted data-descriptor JSON container, preserving aliases,\n * cycles, and property descriptors. Foreign built-in containers normalize to\n * local prototypes. Custom record carriers and provider-native objects remain\n * opaque; arrays with custom provider-visible behavior are refused. A Proxy\n * can run reflection traps while presenting an admitted container shape; the\n * captured descriptor view, never the later mutable Proxy, reaches dispatch.\n */\nfunction snapshotRawParameterGraph(\n params: readonly unknown[],\n errors: RawParameterErrors\n): unknown[] {\n const graph = analyzeRawParameterGraph(params, errors);\n const copies = new WeakMap<object, object>();\n const copiedDates = new WeakMap<object, Date>();\n\n for (const node of graph.nodes) {\n const copy: object = node.isArray ? [] : {};\n if (node.prototype === null) Object.setPrototypeOf(copy, null);\n copies.set(node.source, copy);\n }\n\n const copiedValue = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) return value;\n const time = graph.dateTimes.get(value);\n if (time !== undefined) {\n const known = copiedDates.get(value);\n if (known) return known;\n const copy = new Date(time);\n copiedDates.set(value, copy);\n return copy;\n }\n return copies.get(value) ?? value;\n };\n\n for (const node of graph.nodes) {\n const copy = copies.get(node.source);\n if (!copy) continue;\n for (const property of node.properties) {\n if (node.isArray && property.key === \"length\") continue;\n const descriptor = property.descriptor;\n Object.defineProperty(\n copy,\n property.key,\n \"value\" in descriptor &&\n (node.isArray\n ? isArrayIndex(property.key)\n : descriptor.enumerable && typeof property.key === \"string\")\n ? { ...descriptor, value: copiedValue(descriptor.value) }\n : descriptor\n );\n }\n if (node.isArray) {\n const length = node.properties.find(\n (property) => property.key === \"length\"\n );\n if (length) Object.defineProperty(copy, \"length\", length.descriptor);\n }\n }\n\n const snapshot = new Array<unknown>(graph.roots.length);\n for (let index = 0; index < graph.roots.length; index++) {\n if (!Object.hasOwn(graph.roots, index)) continue;\n snapshot[index] = copiedValue(graph.roots[index]);\n }\n return snapshot;\n}\n\nfunction invalidProviderDateError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received an invalid Date as bound parameter ${parameterIndex}. An invalid Date names no instant, so a provider either refuses the statement after dispatch or binds it as null.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\nfunction unsupportedProviderArrayError(\n context: QueryExecutionContext,\n parameterIndex: number\n): QueryError {\n return new QueryError(\n `Operation \"${context.operation ?? \"statement\"}\" received raw array parameter ${parameterIndex} with custom inherited or accessor behavior. VibORM cannot validate that behavior without invoking caller code before dispatch.`,\n {\n code: VibORMErrorCode.INVALID_INPUT,\n meta: {\n parameterIndex,\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n },\n }\n );\n}\n\n/**\n * Preserve the raw Date admission invariant after the last trusted statement\n * transform. Non-raw statements keep the old shallow-copy path: their typed\n * inputs were validated upstream, and statement transforms are trusted. Raw\n * Date leaves are revalidated and every admitted data-descriptor array or\n * ordinary JSON record is detached. Reflection does not invoke accessors,\n * iterators, or `toJSON`; a Proxy may run its reflection traps, so its captured\n * descriptor view is the stable provider value. Arrays with custom inherited\n * or accessor behavior are refused. Custom record and provider-native carriers\n * remain opaque and are not traversed.\n */\nexport function snapshotProviderParameters(\n params: readonly unknown[],\n context: QueryExecutionContext\n): unknown[] {\n if (context.model !== \"$raw\") return [...params];\n return snapshotRawParameterGraph(params, {\n invalidDate: (parameterIndex) =>\n invalidProviderDateError(context, parameterIndex),\n unsupportedArray: (parameterIndex) =>\n unsupportedProviderArrayError(context, parameterIndex),\n });\n}\n"],"mappings":"sNAEA,MAAM,EAAqB,IAAI,QAG/B,SAAgB,0BAA0B,EAAe,EAAsB,CAC7E,EAAmB,IAAI,EAAO,EAAU,CAI1C,SAAgB,0BACd,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAEhD,OADI,IAAc,IAAA,IAAW,EAAmB,IAAI,EAAQ,EAAU,CAC/D,EAIT,SAAgB,0BACd,EACA,EACA,EACQ,CACR,IAAM,EAAY,EAAmB,IAAI,EAAO,CAOhD,OANI,IAAc,IAAA,IAChB,EAAmB,IACjB,EACA,IAAI,EAAI,CAAC,GAAG,EAAU,QAAQ,CAAE,CAAC,GAAG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