@prisma/orm-family-sql 8.0.0-rc.2-dev.2 → 8.0.0-rc.20

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 (564) hide show
  1. package/README.md +2 -6
  2. package/dist/{aggregate-descriptor-registry-C7hel5O7.mjs → aggregate-descriptor-registry-ZrKjxwQe.mjs} +5 -5
  3. package/dist/aggregate-descriptor-registry-ZrKjxwQe.mjs.map +1 -0
  4. package/dist/ast-D0miQ1B6.mjs +372 -0
  5. package/dist/ast-D0miQ1B6.mjs.map +1 -0
  6. package/dist/ast-YEMe_B8z.d.mts +292 -0
  7. package/dist/ast-YEMe_B8z.d.mts.map +1 -0
  8. package/dist/attribute-specs-DA_RwQFB.d.mts +114 -0
  9. package/dist/attribute-specs-DA_RwQFB.d.mts.map +1 -0
  10. package/dist/{authored-check-naming-Hf9990DV.mjs → authored-check-naming-BHGJhjqn.mjs} +5 -5
  11. package/dist/authored-check-naming-BHGJhjqn.mjs.map +1 -0
  12. package/dist/{authored-check-naming-BWBe-PVE.d.mts → authored-check-naming-D-o196ry.d.mts} +3 -3
  13. package/dist/authored-check-naming-D-o196ry.d.mts.map +1 -0
  14. package/dist/authoring-entity-types-CgKIgWq5-pEdfjam5.d.mts +9 -0
  15. package/dist/authoring-entity-types-CgKIgWq5-pEdfjam5.d.mts.map +1 -0
  16. package/dist/builder.d.mts +4 -3
  17. package/dist/builder__runtime.d.mts +29 -31
  18. package/dist/builder__runtime.d.mts.map +1 -1
  19. package/dist/builder__runtime.mjs +261 -191
  20. package/dist/builder__runtime.mjs.map +1 -1
  21. package/dist/builder__types.d.mts +6 -3
  22. package/dist/{canonicalization-hooks-dmXkOR4a.mjs → canonicalization-hooks-Ce1v_TDl.mjs} +2 -2
  23. package/dist/canonicalization-hooks-Ce1v_TDl.mjs.map +1 -0
  24. package/dist/{canonicalization-hooks-CYnW_sGn.d.mts → canonicalization-hooks-DyapQ0my.d.mts} +2 -2
  25. package/dist/canonicalization-hooks-DyapQ0my.d.mts.map +1 -0
  26. package/dist/{check-constraint-B7qGu6rc-HvQjjX82.d.mts → check-constraint-B7qGu6rc-Bk2ezWXu.d.mts} +4 -4
  27. package/dist/check-constraint-B7qGu6rc-Bk2ezWXu.d.mts.map +1 -0
  28. package/dist/{codec-descriptor-registry-N0dhtKaH.mjs → codec-descriptor-registry-CiiFzMtb.mjs} +13 -40
  29. package/dist/codec-descriptor-registry-CiiFzMtb.mjs.map +1 -0
  30. package/dist/collection-methods-BB8YH69u.d.mts +1 -0
  31. package/dist/collection-methods-D2UnCS0S-DOy2qHYS.d.mts +77 -0
  32. package/dist/collection-methods-D2UnCS0S-DOy2qHYS.d.mts.map +1 -0
  33. package/dist/{config-types-D9fdKG3g.d.mts → config-types-C-1mIiJO.d.mts} +5 -5
  34. package/dist/config-types-C-1mIiJO.d.mts.map +1 -0
  35. package/dist/{config-types-gAm54C_v.mjs → config-types-DkEeq_qq.mjs} +10 -6
  36. package/dist/config-types-DkEeq_qq.mjs.map +1 -0
  37. package/dist/{contract-builder-D4a5dT7j.mjs → contract-builder-50lF0kz1.mjs} +431 -226
  38. package/dist/contract-builder-50lF0kz1.mjs.map +1 -0
  39. package/dist/contract-builder-C_Zi57iD.d.mts +1967 -0
  40. package/dist/contract-builder-C_Zi57iD.d.mts.map +1 -0
  41. package/dist/contract-emitter.d.mts +4 -7
  42. package/dist/contract-emitter.d.mts.map +1 -1
  43. package/dist/contract-emitter.mjs +1 -1
  44. package/dist/{contract-errors-BCN6RVI5-5IHBF_lg.mjs → contract-errors-BCN6RVI5-DoH6b_KZ.mjs} +2 -2
  45. package/dist/contract-errors-BCN6RVI5-DoH6b_KZ.mjs.map +1 -0
  46. package/dist/contract-prisma7__provider.d.mts +97 -0
  47. package/dist/contract-prisma7__provider.d.mts.map +1 -0
  48. package/dist/contract-prisma7__provider.mjs +2011 -0
  49. package/dist/contract-prisma7__provider.mjs.map +1 -0
  50. package/dist/contract-psl.d.mts +18 -29
  51. package/dist/contract-psl.d.mts.map +1 -1
  52. package/dist/contract-psl.mjs +1 -1
  53. package/dist/contract-psl__attribute-specs.d.mts +2 -0
  54. package/dist/contract-psl__attribute-specs.mjs +2 -0
  55. package/dist/contract-psl__default-table-name.d.mts +7 -0
  56. package/dist/contract-psl__default-table-name.d.mts.map +1 -0
  57. package/dist/contract-psl__default-table-name.mjs +2 -0
  58. package/dist/contract-psl__diagnostics.d.mts +12 -0
  59. package/dist/contract-psl__diagnostics.d.mts.map +1 -0
  60. package/dist/contract-psl__diagnostics.mjs +2 -0
  61. package/dist/contract-psl__map-names.d.mts +16 -0
  62. package/dist/contract-psl__map-names.d.mts.map +1 -0
  63. package/dist/contract-psl__map-names.mjs +21 -0
  64. package/dist/contract-psl__map-names.mjs.map +1 -0
  65. package/dist/contract-psl__provider.d.mts +3 -3
  66. package/dist/contract-psl__provider.d.mts.map +1 -1
  67. package/dist/contract-psl__provider.mjs +95 -46
  68. package/dist/contract-psl__provider.mjs.map +1 -1
  69. package/dist/contract-ts.d.mts +5 -5
  70. package/dist/contract-ts.mjs +5 -4
  71. package/dist/contract-ts__config-types.d.mts +1 -1
  72. package/dist/contract-ts__config-types.mjs +1 -1
  73. package/dist/contract-ts__contract-builder.d.mts +4 -4
  74. package/dist/contract-ts__contract-builder.mjs +4 -3
  75. package/dist/{contract-view-BMR5IWk4.mjs → contract-view-DqpzeYeE.mjs} +2 -2
  76. package/dist/contract-view-DqpzeYeE.mjs.map +1 -0
  77. package/dist/{contract-view-CPHxoAEX.d.mts → contract-view-DuB35or0.d.mts} +3 -3
  78. package/dist/contract-view-DuB35or0.d.mts.map +1 -0
  79. package/dist/contract.d.mts +30 -28
  80. package/dist/contract.mjs +23 -18
  81. package/dist/contract__authored-check-naming.d.mts +1 -1
  82. package/dist/contract__authored-check-naming.mjs +1 -1
  83. package/dist/contract__canonicalization-hooks.d.mts +1 -1
  84. package/dist/contract__canonicalization-hooks.mjs +1 -1
  85. package/dist/contract__contract-view.d.mts +1 -1
  86. package/dist/contract__contract-view.mjs +1 -1
  87. package/dist/contract__data-type-support.d.mts +2 -0
  88. package/dist/contract__data-type-support.mjs +2 -0
  89. package/dist/contract__data-type.d.mts +2 -0
  90. package/dist/contract__data-type.mjs +3 -0
  91. package/dist/contract__entity-handle-lowering-hook.d.mts +2 -2
  92. package/dist/contract__entity-handle-lowering-hook.mjs +2 -2
  93. package/dist/contract__entity-kinds.d.mts +1 -1
  94. package/dist/contract__entity-kinds.mjs +1 -1
  95. package/dist/contract__factories.d.mts +1 -1
  96. package/dist/contract__factories.mjs +1 -1
  97. package/dist/contract__foreign-key-materialization.d.mts +2 -2
  98. package/dist/contract__foreign-key-materialization.mjs +3 -2
  99. package/dist/contract__index-naming.d.mts +2 -2
  100. package/dist/contract__index-naming.mjs +2 -2
  101. package/dist/contract__index-type-validation.d.mts +2 -2
  102. package/dist/contract__index-type-validation.mjs +1 -1
  103. package/dist/contract__index-types.d.mts +3 -3
  104. package/dist/contract__index-types.mjs +2 -2
  105. package/dist/contract__referential-action-sql.d.mts +1 -1
  106. package/dist/contract__referential-action-sql.mjs +1 -1
  107. package/dist/contract__resolve-storage-table.d.mts +1 -1
  108. package/dist/contract__resolve-storage-table.mjs +1 -1
  109. package/dist/contract__sql-expression.d.mts +2 -0
  110. package/dist/contract__sql-expression.mjs +2 -0
  111. package/dist/contract__types.d.mts +12 -12
  112. package/dist/contract__types.mjs +4 -4
  113. package/dist/contract__validators.d.mts +2 -2
  114. package/dist/contract__validators.mjs +3 -3
  115. package/dist/contract__value-set-derivation-hook.d.mts +1 -1
  116. package/dist/contract__value-set-derivation-hook.mjs +1 -1
  117. package/dist/control-BK50zF6c.mjs +2721 -0
  118. package/dist/control-BK50zF6c.mjs.map +1 -0
  119. package/dist/control-ChAUdOOu.d.mts +1416 -0
  120. package/dist/control-ChAUdOOu.d.mts.map +1 -0
  121. package/dist/{control-adapter-C99J7aEF-B7eQd7vD.d.mts → control-adapter-Bn0uhplA-BzP2uPqJ.d.mts} +27 -44
  122. package/dist/control-adapter-Bn0uhplA-BzP2uPqJ.d.mts.map +1 -0
  123. package/dist/control-adapter-NZ2kKc4x.d.mts +13 -0
  124. package/dist/control-adapter-NZ2kKc4x.d.mts.map +1 -0
  125. package/dist/control-adapter-SlQkTEwT.mjs +16 -0
  126. package/dist/control-adapter-SlQkTEwT.mjs.map +1 -0
  127. package/dist/data-type-BFSpaotu.mjs +52 -0
  128. package/dist/data-type-BFSpaotu.mjs.map +1 -0
  129. package/dist/data-type-DJIvKQHf.d.mts +158 -0
  130. package/dist/data-type-DJIvKQHf.d.mts.map +1 -0
  131. package/dist/data-type-support-BhSoPUFj.mjs +9 -0
  132. package/dist/data-type-support-BhSoPUFj.mjs.map +1 -0
  133. package/dist/data-type-support-CXpA0ex-.d.mts +7 -0
  134. package/dist/data-type-support-CXpA0ex-.d.mts.map +1 -0
  135. package/dist/{db-D18PrXKW-DvTv4JFn.d.mts → db-D1d75IvM-D4mRDC6w.d.mts} +123 -128
  136. package/dist/db-D1d75IvM-D4mRDC6w.d.mts.map +1 -0
  137. package/dist/{ddl-types-CXx4vPz6-BsgrnSUY.d.mts → ddl-types-By5mT2_S-CdaaFvsX.d.mts} +24 -29
  138. package/dist/ddl-types-By5mT2_S-CdaaFvsX.d.mts.map +1 -0
  139. package/dist/default-mapping-CAOONlKQ-4m07nb-O.d.mts +39 -0
  140. package/dist/default-mapping-CAOONlKQ-4m07nb-O.d.mts.map +1 -0
  141. package/dist/default-table-name-BfFY8qYR-CWZFDX6v.mjs +9 -0
  142. package/dist/default-table-name-BfFY8qYR-CWZFDX6v.mjs.map +1 -0
  143. package/dist/derived-checks-D5HVRvqN-BJx1gwPA.mjs +1508 -0
  144. package/dist/derived-checks-D5HVRvqN-BJx1gwPA.mjs.map +1 -0
  145. package/dist/{derived-checks-DPdD01O0-DGqOFjs6.d.mts → derived-checks-DpPkO6Dt-9U9UJZOo.d.mts} +4 -4
  146. package/dist/derived-checks-DpPkO6Dt-9U9UJZOo.d.mts.map +1 -0
  147. package/dist/diagnostics-RHJxoiIk.mjs +23 -0
  148. package/dist/diagnostics-RHJxoiIk.mjs.map +1 -0
  149. package/dist/{diff-DbTNVm2f.d.mts → diff-1qHOLoUB.d.mts} +23 -10
  150. package/dist/diff-1qHOLoUB.d.mts.map +1 -0
  151. package/dist/diff-C1rFOhek.mjs +21 -0
  152. package/dist/diff-C1rFOhek.mjs.map +1 -0
  153. package/dist/{dist-ZK6oeI5e.mjs → dist-C8Y-PPuE.mjs} +36 -212
  154. package/dist/dist-C8Y-PPuE.mjs.map +1 -0
  155. package/dist/{dist-C_q1_QR9.mjs → dist-CHz1hF8M.mjs} +2 -2
  156. package/dist/dist-CHz1hF8M.mjs.map +1 -0
  157. package/dist/{dist-x6jvtkKM.mjs → dist-CMDXybwm.mjs} +2 -2
  158. package/dist/dist-CMDXybwm.mjs.map +1 -0
  159. package/dist/{driver-types-BQtRkOJ0-Bv2RPSfr.d.mts → driver-types-DRsYeq3j-BimeCnUk.d.mts} +11 -2
  160. package/dist/driver-types-DRsYeq3j-BimeCnUk.d.mts.map +1 -0
  161. package/dist/entity-handle-lowering-hook-BJZSlVVF.mjs +16 -0
  162. package/dist/entity-handle-lowering-hook-BJZSlVVF.mjs.map +1 -0
  163. package/dist/{entity-handle-lowering-hook-CIvRKBfa.d.mts → entity-handle-lowering-hook-BuvLtgFi.d.mts} +8 -11
  164. package/dist/entity-handle-lowering-hook-BuvLtgFi.d.mts.map +1 -0
  165. package/dist/{entity-kinds-B5cUFU22.d.mts → entity-kinds-BPG2xCZV.d.mts} +7 -7
  166. package/dist/entity-kinds-BPG2xCZV.d.mts.map +1 -0
  167. package/dist/{entity-kinds-D7vwoN_T-CCBwFJy0.mjs → entity-kinds-JR5SAm5h-DOH6VUtL.mjs} +31 -28
  168. package/dist/entity-kinds-JR5SAm5h-DOH6VUtL.mjs.map +1 -0
  169. package/dist/{errors-B5g0xWro-mWH2C07F.mjs → errors-B5g0xWro-C8plbqga.mjs} +2 -2
  170. package/dist/errors-B5g0xWro-C8plbqga.mjs.map +1 -0
  171. package/dist/errors.d.mts +1 -1
  172. package/dist/errors.d.mts.map +1 -1
  173. package/dist/errors.mjs +1 -1
  174. package/dist/exports-C3wGYtID-D65DEUTC.mjs +2389 -0
  175. package/dist/exports-C3wGYtID-D65DEUTC.mjs.map +1 -0
  176. package/dist/{expression-FJK6Ar-d.d.mts → expression-6ld_ZQL6-fOuazzzm.d.mts} +37 -16
  177. package/dist/expression-6ld_ZQL6-fOuazzzm.d.mts.map +1 -0
  178. package/dist/expression-CieaNuRM-B1uVqxwd.d.mts +22 -0
  179. package/dist/expression-CieaNuRM-B1uVqxwd.d.mts.map +1 -0
  180. package/dist/expression-D8HstQiB.d.mts +2 -0
  181. package/dist/{expression-CX5mTA-z.mjs → expression-impl-B-XNINxr-BhN2sysZ.mjs} +41 -18
  182. package/dist/expression-impl-B-XNINxr-BhN2sysZ.mjs.map +1 -0
  183. package/dist/{factories-SVor5xIT.mjs → factories-Crobuxwn.mjs} +27 -20
  184. package/dist/factories-Crobuxwn.mjs.map +1 -0
  185. package/dist/{factories-P3qBQhO-.d.mts → factories-DbNP9qfs.d.mts} +16 -10
  186. package/dist/factories-DbNP9qfs.d.mts.map +1 -0
  187. package/dist/family.d.mts +17 -13
  188. package/dist/family.mjs +17 -12
  189. package/dist/family__control-adapter.d.mts +3 -3
  190. package/dist/family__control-adapter.mjs +2 -1
  191. package/dist/family__control.d.mts +5 -4
  192. package/dist/family__control.mjs +4 -4
  193. package/dist/family__diff.d.mts +2 -3
  194. package/dist/family__diff.mjs +2 -2
  195. package/dist/family__ir.d.mts +1 -1
  196. package/dist/family__ir.mjs +2 -2
  197. package/dist/family__migration.d.mts +1 -1
  198. package/dist/family__migration.mjs +1 -1
  199. package/dist/family__pack.d.mts +2 -249
  200. package/dist/family__pack.mjs +3 -18
  201. package/dist/family__psl-build.d.mts +3 -0
  202. package/dist/family__psl-build.mjs +3 -0
  203. package/dist/family__psl-infer.d.mts +2 -2
  204. package/dist/family__psl-infer.mjs +2 -2
  205. package/dist/family__runtime.d.mts +2 -2
  206. package/dist/family__runtime.mjs +2 -2
  207. package/dist/family__verify.d.mts +1 -1
  208. package/dist/family__verify.mjs +1 -1
  209. package/dist/foreign-key-materialization-48P2V8on.d.mts +98 -0
  210. package/dist/foreign-key-materialization-48P2V8on.d.mts.map +1 -0
  211. package/dist/foreign-key-materialization-BM59w_Xg.mjs +287 -0
  212. package/dist/foreign-key-materialization-BM59w_Xg.mjs.map +1 -0
  213. package/dist/{foreign-key-C-iTPuRT-C9ip8zFx.d.mts → foreign-key-qkDFfG8t-TaK_GYWR.d.mts} +21 -5
  214. package/dist/foreign-key-qkDFfG8t-TaK_GYWR.d.mts.map +1 -0
  215. package/dist/functions-CsOoN7I3.mjs +88 -0
  216. package/dist/functions-CsOoN7I3.mjs.map +1 -0
  217. package/dist/functions-EW-RrRn3.d.mts +73 -0
  218. package/dist/functions-EW-RrRn3.d.mts.map +1 -0
  219. package/dist/generator-functions-D_qdqBV--Bq296cED.mjs +544 -0
  220. package/dist/generator-functions-D_qdqBV--Bq296cED.mjs.map +1 -0
  221. package/dist/index-7nHHQsAj.d.mts +606 -0
  222. package/dist/index-7nHHQsAj.d.mts.map +1 -0
  223. package/dist/{index-C5I8D-MB.d.mts → index-Nqc3OHR_.d.mts} +4 -5
  224. package/dist/index-Nqc3OHR_.d.mts.map +1 -0
  225. package/dist/index-equivalence-DswCiq5l-CGsyPP9B.mjs +109 -0
  226. package/dist/index-equivalence-DswCiq5l-CGsyPP9B.mjs.map +1 -0
  227. package/dist/{index-naming-DREt6js7-CRH27yUv.mjs → index-naming-BOcJT1B3-mG8Fd6KN.mjs} +35 -9
  228. package/dist/index-naming-BOcJT1B3-mG8Fd6KN.mjs.map +1 -0
  229. package/dist/{index-naming-Ct65z5Xk.d.mts → index-naming-Cs6wwia3.d.mts} +15 -5
  230. package/dist/index-naming-Cs6wwia3.d.mts.map +1 -0
  231. package/dist/index-reference-4wsdeB7v-DCwswK-q.d.mts +67 -0
  232. package/dist/index-reference-4wsdeB7v-DCwswK-q.d.mts.map +1 -0
  233. package/dist/index-reference-BQSrkRfT.mjs +55 -0
  234. package/dist/index-reference-BQSrkRfT.mjs.map +1 -0
  235. package/dist/index-reference-D8ewQRJr.d.mts +1 -0
  236. package/dist/index-type-validation-DJEMmmw0.mjs +42 -0
  237. package/dist/index-type-validation-DJEMmmw0.mjs.map +1 -0
  238. package/dist/index-type-validation-fGGwAHWc.d.mts +16 -0
  239. package/dist/index-type-validation-fGGwAHWc.d.mts.map +1 -0
  240. package/dist/index-types-H1O43iYT-BD0VwPqV.d.mts +66 -0
  241. package/dist/index-types-H1O43iYT-BD0VwPqV.d.mts.map +1 -0
  242. package/dist/index-types-pC_5vADQ-BOOBi14R.mjs +95 -0
  243. package/dist/index-types-pC_5vADQ-BOOBi14R.mjs.map +1 -0
  244. package/dist/index-types-snhtt_Fo.d.mts +1 -0
  245. package/dist/interpreter-D5qk4B---CG0C7kdx.mjs +2280 -0
  246. package/dist/interpreter-D5qk4B---CG0C7kdx.mjs.map +1 -0
  247. package/dist/{ir-Bghjt-FG.d.mts → ir-BvptQsFW.d.mts} +11 -5
  248. package/dist/ir-BvptQsFW.d.mts.map +1 -0
  249. package/dist/{ir-I-xciGUH.mjs → ir-DzsUDO8e.mjs} +2 -2
  250. package/dist/ir-DzsUDO8e.mjs.map +1 -0
  251. package/dist/{middleware-AhTz1BOW-th-Suxuf.d.mts → middleware-DHkW6pRr-DM6hd9iZ.d.mts} +5 -5
  252. package/dist/middleware-DHkW6pRr-DM6hd9iZ.d.mts.map +1 -0
  253. package/dist/middleware-gqy3l13N.d.mts +1 -0
  254. package/dist/{middleware-CMr4CHNz-DHIUdxlm.mjs → middleware-yBAfiVWn-DZO0vCRQ.mjs} +3 -3
  255. package/dist/middleware-yBAfiVWn-DZO0vCRQ.mjs.map +1 -0
  256. package/dist/{migration-CK4oePIo.mjs → migration-BJQjkqFz.mjs} +4 -4
  257. package/dist/migration-BJQjkqFz.mjs.map +1 -0
  258. package/dist/{migration-CjDRZNep.d.mts → migration-Cxmpzaz0.d.mts} +6 -6
  259. package/dist/migration-Cxmpzaz0.d.mts.map +1 -0
  260. package/dist/{naming-CV9j2pXl-KARaDReS.d.mts → naming-BcD36g9T-Mfe_xGGL.d.mts} +9 -14
  261. package/dist/naming-BcD36g9T-Mfe_xGGL.d.mts.map +1 -0
  262. package/dist/{naming-DKr4TJd7-Cszhq9RV.mjs → naming-bM5qm5PY-jOg3JFMb.mjs} +20 -31
  263. package/dist/naming-bM5qm5PY-jOg3JFMb.mjs.map +1 -0
  264. package/dist/{ddl-types-BGdnAbXo-DKPHPUGx.mjs → opaque-sql-Dset3kln-CtsPDTXn.mjs} +24 -11
  265. package/dist/opaque-sql-Dset3kln-CtsPDTXn.mjs.map +1 -0
  266. package/dist/operations.d.mts +1 -1
  267. package/dist/operations.mjs +1 -1
  268. package/dist/orm-client.d.mts +817 -267
  269. package/dist/orm-client.d.mts.map +1 -1
  270. package/dist/orm-client.mjs +4719 -2942
  271. package/dist/orm-client.mjs.map +1 -1
  272. package/dist/pack-DA8HZ2mo.d.mts +535 -0
  273. package/dist/pack-DA8HZ2mo.d.mts.map +1 -0
  274. package/dist/pack-gSvGQWqs.mjs +80 -0
  275. package/dist/pack-gSvGQWqs.mjs.map +1 -0
  276. package/dist/{plan-CDxduYaN-pLIyyJaB.d.mts → plan-Cr4azjnG-CuL8FqXC.d.mts} +12 -8
  277. package/dist/plan-Cr4azjnG-CuL8FqXC.d.mts.map +1 -0
  278. package/dist/{plan-Dh0LbYIv-Crx5-ThG.mjs → plan-Dh0LbYIv-ubBSdUgl.mjs} +2 -2
  279. package/dist/plan-Dh0LbYIv-ubBSdUgl.mjs.map +1 -0
  280. package/dist/plan-Di6Gs2JD.d.mts +2 -0
  281. package/dist/psl-attribute-parsing-BCsFWsSp-BJ-wGlY6.mjs +42 -0
  282. package/dist/psl-attribute-parsing-BCsFWsSp-BJ-wGlY6.mjs.map +1 -0
  283. package/dist/psl-build-DFBG6vhz.mjs +426 -0
  284. package/dist/psl-build-DFBG6vhz.mjs.map +1 -0
  285. package/dist/psl-build-RelubU2E.d.mts +112 -0
  286. package/dist/psl-build-RelubU2E.d.mts.map +1 -0
  287. package/dist/psl-column-resolution-ChZqioOc-BREg4J7d.d.mts +24 -0
  288. package/dist/psl-column-resolution-ChZqioOc-BREg4J7d.d.mts.map +1 -0
  289. package/dist/psl-field-resolution-C5KQ7kzP-B0NwuRWV.mjs +1960 -0
  290. package/dist/psl-field-resolution-C5KQ7kzP-B0NwuRWV.mjs.map +1 -0
  291. package/dist/psl-infer--g4i84Go.mjs +201 -0
  292. package/dist/psl-infer--g4i84Go.mjs.map +1 -0
  293. package/dist/psl-infer-DzoxPZGd.d.mts +80 -0
  294. package/dist/psl-infer-DzoxPZGd.d.mts.map +1 -0
  295. package/dist/psl-names-C3cwe0rg-D1CTmC3a.mjs +66 -0
  296. package/dist/psl-names-C3cwe0rg-D1CTmC3a.mjs.map +1 -0
  297. package/dist/{query-lane-context-Qa-eddrE-kuZ8Z86-.d.mts → query-lane-context-BCEoKy0_-CzmyavC9.d.mts} +20 -49
  298. package/dist/query-lane-context-BCEoKy0_-CzmyavC9.d.mts.map +1 -0
  299. package/dist/query-lane-context-VqH0mS9B.d.mts +1 -0
  300. package/dist/{referential-action-sql-DJ9ps6-S.d.mts → referential-action-sql-B2vKoUK6.d.mts} +3 -3
  301. package/dist/referential-action-sql-B2vKoUK6.d.mts.map +1 -0
  302. package/dist/{referential-action-sql-DSqkrySN.mjs → referential-action-sql-BLzCtTi8.mjs} +2 -2
  303. package/dist/referential-action-sql-BLzCtTi8.mjs.map +1 -0
  304. package/dist/relational-core.d.mts +14 -13
  305. package/dist/relational-core.mjs +8 -8
  306. package/dist/relational-core__aggregate-descriptor-registry.d.mts +2 -2
  307. package/dist/relational-core__aggregate-descriptor-registry.d.mts.map +1 -1
  308. package/dist/relational-core__aggregate-descriptor-registry.mjs +1 -1
  309. package/dist/relational-core__ast.d.mts +5 -5
  310. package/dist/relational-core__ast.mjs +5 -5
  311. package/dist/relational-core__codec-descriptor-registry.d.mts +7 -8
  312. package/dist/relational-core__codec-descriptor-registry.d.mts.map +1 -1
  313. package/dist/relational-core__codec-descriptor-registry.mjs +1 -1
  314. package/dist/relational-core__collection-methods.d.mts +3 -0
  315. package/dist/relational-core__contract-free.d.mts +18 -8
  316. package/dist/relational-core__contract-free.d.mts.map +1 -1
  317. package/dist/relational-core__contract-free.mjs +26 -10
  318. package/dist/relational-core__contract-free.mjs.map +1 -1
  319. package/dist/relational-core__expression.d.mts +4 -2
  320. package/dist/relational-core__expression.mjs +2 -2
  321. package/dist/relational-core__functions.d.mts +2 -0
  322. package/dist/relational-core__functions.mjs +2 -0
  323. package/dist/relational-core__index-reference.d.mts +3 -0
  324. package/dist/relational-core__index-reference.mjs +2 -0
  325. package/dist/relational-core__middleware.d.mts +2 -2
  326. package/dist/relational-core__middleware.mjs +1 -1
  327. package/dist/relational-core__plan.d.mts +4 -4
  328. package/dist/relational-core__plan.mjs +1 -1
  329. package/dist/relational-core__query-lane-context.d.mts +3 -3
  330. package/dist/relational-core__types.d.mts +2 -2
  331. package/dist/{resolve-storage-table-DZsfnzeW.mjs → resolve-storage-table-BHLQsOza.mjs} +3 -3
  332. package/dist/resolve-storage-table-BHLQsOza.mjs.map +1 -0
  333. package/dist/{resolve-storage-table-Nyrgk4h8.d.mts → resolve-storage-table-DCqtmnSU.d.mts} +4 -4
  334. package/dist/resolve-storage-table-DCqtmnSU.d.mts.map +1 -0
  335. package/dist/{runtime-tIHpGCcG.mjs → runtime-6tH1yOxK.mjs} +6 -6
  336. package/dist/runtime-6tH1yOxK.mjs.map +1 -0
  337. package/dist/{runtime-DpKF2Yu2.d.mts → runtime-CF6rAlE5.d.mts} +7 -8
  338. package/dist/runtime-CF6rAlE5.d.mts.map +1 -0
  339. package/dist/runtime.d.mts +5 -5
  340. package/dist/runtime.mjs +2 -1799
  341. package/dist/runtime__internal__prepared-query.d.mts +2 -2
  342. package/dist/runtime__internal__prepared-query.mjs +2 -2
  343. package/dist/{schema-differ-DpG_gnur-DFAtGezx.d.mts → schema-differ-DmP74bB8-tqHKiJ88.d.mts} +6 -6
  344. package/dist/schema-differ-DmP74bB8-tqHKiJ88.d.mts.map +1 -0
  345. package/dist/schema-ir.d.mts +2 -2
  346. package/dist/schema-ir.mjs +2 -2
  347. package/dist/schema-ir__naming.d.mts +1 -1
  348. package/dist/schema-ir__naming.mjs +1 -1
  349. package/dist/schema-ir__types.d.mts +3 -3
  350. package/dist/schema-ir__types.mjs +2 -2
  351. package/dist/{schema-verify-C_PEdlAr-Dxxjm6EM.mjs → schema-verify-C3wbdviw-DMjIubOr.mjs} +50 -8
  352. package/dist/schema-verify-C3wbdviw-DMjIubOr.mjs.map +1 -0
  353. package/dist/{serialized-index-CrgG8ct1-DG3JpHc7.d.mts → serialized-index-CrgG8ct1-DKVJ7TDX.d.mts} +4 -4
  354. package/dist/serialized-index-CrgG8ct1-DKVJ7TDX.d.mts.map +1 -0
  355. package/dist/{serialized-index-nBTwanKy-_ddEK4tk.mjs → serialized-index-DjCCnXB1-DMA7BtO2.mjs} +4 -4
  356. package/dist/serialized-index-DjCCnXB1-DMA7BtO2.mjs.map +1 -0
  357. package/dist/{sql-contract-serializer-2oBWuxTe-DKZTf2n8.mjs → sql-contract-serializer-sMY3prTx-D2BfrNxs.mjs} +41 -16
  358. package/dist/sql-contract-serializer-sMY3prTx-D2BfrNxs.mjs.map +1 -0
  359. package/dist/sql-data-type-D7M-YTTY-D2vRqDxn.mjs +400 -0
  360. package/dist/sql-data-type-D7M-YTTY-D2vRqDxn.mjs.map +1 -0
  361. package/dist/{sql-execution-plan--jKyLpe5-CMGhgO0M.d.mts → sql-execution-plan-3uxYjHyu-DLknM-Pj.d.mts} +3 -3
  362. package/dist/sql-execution-plan-3uxYjHyu-DLknM-Pj.d.mts.map +1 -0
  363. package/dist/sql-expression-B4BrhGPi.d.mts +62 -0
  364. package/dist/sql-expression-B4BrhGPi.d.mts.map +1 -0
  365. package/dist/sql-expression-CKgKznXS.mjs +137 -0
  366. package/dist/sql-expression-CKgKznXS.mjs.map +1 -0
  367. package/dist/{sql-index-ByAAE7K8-DKj2V86p.d.mts → sql-index-ByAAE7K8-Dqtn_vUL.d.mts} +4 -4
  368. package/dist/sql-index-ByAAE7K8-Dqtn_vUL.d.mts.map +1 -0
  369. package/dist/{sql-node-kEz6YFZo-v2F7delx.d.mts → sql-node-kEz6YFZo-1ogT6Cxt.d.mts} +2 -2
  370. package/dist/sql-node-kEz6YFZo-1ogT6Cxt.d.mts.map +1 -0
  371. package/dist/{sql-storage-8LqxeLAY-DH4DdUXx.d.mts → sql-storage-DeCAh5Hi-CEM-m8cs.d.mts} +19 -22
  372. package/dist/sql-storage-DeCAh5Hi-CEM-m8cs.d.mts.map +1 -0
  373. package/dist/{storage-table-DSeWszOL-CI-cItEK.d.mts → storage-table-Bf1ZjnxO-pUj6pyP0.d.mts} +17 -24
  374. package/dist/storage-table-Bf1ZjnxO-pUj6pyP0.d.mts.map +1 -0
  375. package/dist/{storage-table-ZzbR-xzQ-BRoTQE_2.mjs → storage-table-DDvN83mw-DkbBFmK9.mjs} +12 -9
  376. package/dist/storage-table-DDvN83mw-DkbBFmK9.mjs.map +1 -0
  377. package/dist/{storage-value-set-BGlj5Uus-CvZD--GG.d.mts → storage-value-set-BGlj5Uus-ny2k-0PA.d.mts} +3 -3
  378. package/dist/storage-value-set-BGlj5Uus-ny2k-0PA.d.mts.map +1 -0
  379. package/dist/transaction-state-BfXhs7D7-DhmbySW9.mjs +45 -0
  380. package/dist/transaction-state-BfXhs7D7-DhmbySW9.mjs.map +1 -0
  381. package/dist/transaction-state-DR3nKTmH-D29jmVE-.d.mts +115 -0
  382. package/dist/transaction-state-DR3nKTmH-D29jmVE-.d.mts.map +1 -0
  383. package/dist/types-B9wSEUsV.d.mts +1 -0
  384. package/dist/{types-CUsJrvEl.mjs → types-CTdSkl0s.mjs} +13 -6
  385. package/dist/types-CTdSkl0s.mjs.map +1 -0
  386. package/dist/types-CkAd8SWm.d.mts +57 -0
  387. package/dist/types-CkAd8SWm.d.mts.map +1 -0
  388. package/dist/{types-IqZMLrFC-DcH8v_u3.d.mts → types-Cq6ImLAB-RlU4jJAX.d.mts} +27 -41
  389. package/dist/types-Cq6ImLAB-RlU4jJAX.d.mts.map +1 -0
  390. package/dist/{types-YStFFkKs-D9UAmnON.d.mts → types-CuCxAQat-Dz8P4xyt.d.mts} +141 -86
  391. package/dist/types-CuCxAQat-Dz8P4xyt.d.mts.map +1 -0
  392. package/dist/types-DfKvtJwS-CrpWTGBJ.d.mts +273 -0
  393. package/dist/types-DfKvtJwS-CrpWTGBJ.d.mts.map +1 -0
  394. package/dist/{types-4YenawkP-CwaaZSid.mjs → types-DoyiTsjg-2YMhMJDA.mjs} +181 -80
  395. package/dist/types-DoyiTsjg-2YMhMJDA.mjs.map +1 -0
  396. package/dist/{types-v3qxLLxo-DCeKv7yY.d.mts → types-DriMIMNQ-BkbsW7w3.d.mts} +68 -34
  397. package/dist/types-DriMIMNQ-BkbsW7w3.d.mts.map +1 -0
  398. package/dist/{types-Dt4e_jC--COeP8xzN.mjs → types-NTQsD2MS-xcLtvKO9.mjs} +83 -17
  399. package/dist/types-NTQsD2MS-xcLtvKO9.mjs.map +1 -0
  400. package/dist/{types-CyxGtOOh-BggSa6Fe.d.mts → types-TXO7x1BA-CYYIY8NI.d.mts} +14 -14
  401. package/dist/types-TXO7x1BA-CYYIY8NI.d.mts.map +1 -0
  402. package/dist/types-ljUNyiWe.d.mts +1 -0
  403. package/dist/{unique-constraint-M5TlQnJQ-BiIHJ85k.d.mts → unique-constraint-M5TlQnJQ-qX-maNUV.d.mts} +3 -3
  404. package/dist/unique-constraint-M5TlQnJQ-qX-maNUV.d.mts.map +1 -0
  405. package/dist/{util-DQQgv2j1-D6INZaRG.mjs → util-BBgcP3gI-CpL-0VuC.mjs} +12 -3
  406. package/dist/util-BBgcP3gI-CpL-0VuC.mjs.map +1 -0
  407. package/dist/{validators-CrWD6bSP.mjs → validators-BwA7ttZM.mjs} +0 -0
  408. package/dist/validators-BwA7ttZM.mjs.map +1 -0
  409. package/dist/{validators-Belo8QqM.d.mts → validators-FJs8HvFr.d.mts} +54 -16
  410. package/dist/validators-FJs8HvFr.d.mts.map +1 -0
  411. package/dist/{value-set-derivation-hook-BhgGVtw0.d.mts → value-set-derivation-hook-3E437jPU.d.mts} +3 -3
  412. package/dist/value-set-derivation-hook-3E437jPU.d.mts.map +1 -0
  413. package/dist/{value-set-derivation-hook-Di9JZ0X7.mjs → value-set-derivation-hook-HVaxhALD.mjs} +2 -2
  414. package/dist/value-set-derivation-hook-HVaxhALD.mjs.map +1 -0
  415. package/dist/{verify-u0UTdZgD-DSAaz9rW.mjs → verify-BVk5bjdH-DhKm6hB3.mjs} +8 -7
  416. package/dist/verify-BVk5bjdH-DhKm6hB3.mjs.map +1 -0
  417. package/dist/{verify-zDRnw0Rn.d.mts → verify-DHXbuZPB.d.mts} +2 -2
  418. package/dist/verify-DHXbuZPB.d.mts.map +1 -0
  419. package/package.json +33 -22
  420. package/dist/aggregate-descriptor-registry-C7hel5O7.mjs.map +0 -1
  421. package/dist/ast-HFcfQZr-.d.mts +0 -206
  422. package/dist/ast-HFcfQZr-.d.mts.map +0 -1
  423. package/dist/ast-Lbl4VwqP.mjs +0 -325
  424. package/dist/ast-Lbl4VwqP.mjs.map +0 -1
  425. package/dist/authored-check-naming-BWBe-PVE.d.mts.map +0 -1
  426. package/dist/authored-check-naming-Hf9990DV.mjs.map +0 -1
  427. package/dist/authoring-type-constructors-Blqoa2Ua-DqvNCOb2.mjs +0 -316
  428. package/dist/authoring-type-constructors-Blqoa2Ua-DqvNCOb2.mjs.map +0 -1
  429. package/dist/canonicalization-hooks-CYnW_sGn.d.mts.map +0 -1
  430. package/dist/canonicalization-hooks-dmXkOR4a.mjs.map +0 -1
  431. package/dist/check-constraint-B7qGu6rc-HvQjjX82.d.mts.map +0 -1
  432. package/dist/codec-descriptor-registry-N0dhtKaH.mjs.map +0 -1
  433. package/dist/config-types-D9fdKG3g.d.mts.map +0 -1
  434. package/dist/config-types-gAm54C_v.mjs.map +0 -1
  435. package/dist/contract-builder-CG_tGDbB.d.mts +0 -1360
  436. package/dist/contract-builder-CG_tGDbB.d.mts.map +0 -1
  437. package/dist/contract-builder-D4a5dT7j.mjs.map +0 -1
  438. package/dist/contract-errors-BCN6RVI5-5IHBF_lg.mjs.map +0 -1
  439. package/dist/contract-view-BMR5IWk4.mjs.map +0 -1
  440. package/dist/contract-view-CPHxoAEX.d.mts.map +0 -1
  441. package/dist/contract__pack-types.d.mts +0 -2
  442. package/dist/control-D3cB5YQp.mjs +0 -1267
  443. package/dist/control-D3cB5YQp.mjs.map +0 -1
  444. package/dist/control-DTLJ1WtZ.d.mts +0 -945
  445. package/dist/control-DTLJ1WtZ.d.mts.map +0 -1
  446. package/dist/control-adapter-C99J7aEF-B7eQd7vD.d.mts.map +0 -1
  447. package/dist/control-adapter-MZJQiwcE.d.mts +0 -1
  448. package/dist/db-D18PrXKW-DvTv4JFn.d.mts.map +0 -1
  449. package/dist/ddl-types-BGdnAbXo-DKPHPUGx.mjs.map +0 -1
  450. package/dist/ddl-types-CXx4vPz6-BsgrnSUY.d.mts.map +0 -1
  451. package/dist/derived-checks-DFMRmiAu-DGfB8aS4.mjs +0 -1057
  452. package/dist/derived-checks-DFMRmiAu-DGfB8aS4.mjs.map +0 -1
  453. package/dist/derived-checks-DPdD01O0-DGqOFjs6.d.mts.map +0 -1
  454. package/dist/diff-B16bL_IR.mjs +0 -13
  455. package/dist/diff-B16bL_IR.mjs.map +0 -1
  456. package/dist/diff-DbTNVm2f.d.mts.map +0 -1
  457. package/dist/dist-C_q1_QR9.mjs.map +0 -1
  458. package/dist/dist-ZK6oeI5e.mjs.map +0 -1
  459. package/dist/dist-x6jvtkKM.mjs.map +0 -1
  460. package/dist/driver-types-BQtRkOJ0-Bv2RPSfr.d.mts.map +0 -1
  461. package/dist/entity-handle-lowering-hook-CIvRKBfa.d.mts.map +0 -1
  462. package/dist/entity-handle-lowering-hook-DwLIKNiS.mjs +0 -11
  463. package/dist/entity-handle-lowering-hook-DwLIKNiS.mjs.map +0 -1
  464. package/dist/entity-kinds-B5cUFU22.d.mts.map +0 -1
  465. package/dist/entity-kinds-D7vwoN_T-CCBwFJy0.mjs.map +0 -1
  466. package/dist/errors-B5g0xWro-mWH2C07F.mjs.map +0 -1
  467. package/dist/expression-CX5mTA-z.mjs.map +0 -1
  468. package/dist/expression-FJK6Ar-d.d.mts.map +0 -1
  469. package/dist/factories-P3qBQhO-.d.mts.map +0 -1
  470. package/dist/factories-SVor5xIT.mjs.map +0 -1
  471. package/dist/family__pack.d.mts.map +0 -1
  472. package/dist/family__pack.mjs.map +0 -1
  473. package/dist/foreign-key-C-iTPuRT-C9ip8zFx.d.mts.map +0 -1
  474. package/dist/foreign-key-materialization-CkvOzJWy.d.mts +0 -65
  475. package/dist/foreign-key-materialization-CkvOzJWy.d.mts.map +0 -1
  476. package/dist/foreign-key-materialization-Cu7-7LHl.mjs +0 -73
  477. package/dist/foreign-key-materialization-Cu7-7LHl.mjs.map +0 -1
  478. package/dist/index-C-vQOMY_.d.mts +0 -84
  479. package/dist/index-C-vQOMY_.d.mts.map +0 -1
  480. package/dist/index-C5I8D-MB.d.mts.map +0 -1
  481. package/dist/index-naming-Ct65z5Xk.d.mts.map +0 -1
  482. package/dist/index-naming-DREt6js7-CRH27yUv.mjs.map +0 -1
  483. package/dist/index-type-validation-COH4d78M.mjs +0 -17
  484. package/dist/index-type-validation-COH4d78M.mjs.map +0 -1
  485. package/dist/index-type-validation-CZ5L2lli.d.mts +0 -10
  486. package/dist/index-type-validation-CZ5L2lli.d.mts.map +0 -1
  487. package/dist/index-types-CNhHgKHi.d.mts +0 -1
  488. package/dist/index-types-DJQ_xwaE.mjs +0 -40
  489. package/dist/index-types-DJQ_xwaE.mjs.map +0 -1
  490. package/dist/index-types-DPVhsW0v-D-BikM4h.d.mts +0 -31
  491. package/dist/index-types-DPVhsW0v-D-BikM4h.d.mts.map +0 -1
  492. package/dist/interpreter-DyiUUAWh-DYdjIpiE.mjs +0 -3680
  493. package/dist/interpreter-DyiUUAWh-DYdjIpiE.mjs.map +0 -1
  494. package/dist/ir-Bghjt-FG.d.mts.map +0 -1
  495. package/dist/ir-I-xciGUH.mjs.map +0 -1
  496. package/dist/lane-query-builder.d.mts +0 -236
  497. package/dist/lane-query-builder.d.mts.map +0 -1
  498. package/dist/lane-query-builder.mjs +0 -67
  499. package/dist/lane-query-builder.mjs.map +0 -1
  500. package/dist/middleware--TtoxUiW.d.mts +0 -1
  501. package/dist/middleware-AhTz1BOW-th-Suxuf.d.mts.map +0 -1
  502. package/dist/middleware-CMr4CHNz-DHIUdxlm.mjs.map +0 -1
  503. package/dist/migration-CK4oePIo.mjs.map +0 -1
  504. package/dist/migration-CjDRZNep.d.mts.map +0 -1
  505. package/dist/naming-CV9j2pXl-KARaDReS.d.mts.map +0 -1
  506. package/dist/naming-DKr4TJd7-Cszhq9RV.mjs.map +0 -1
  507. package/dist/pack-types-BcLTpwbv.d.mts +0 -14
  508. package/dist/pack-types-BcLTpwbv.d.mts.map +0 -1
  509. package/dist/plan-BHLdb0Z7.d.mts +0 -2
  510. package/dist/plan-CDxduYaN-pLIyyJaB.d.mts.map +0 -1
  511. package/dist/plan-Dh0LbYIv-Crx5-ThG.mjs.map +0 -1
  512. package/dist/prepared-query-BJr50wPm-ChoqfJbX.mjs +0 -22
  513. package/dist/prepared-query-BJr50wPm-ChoqfJbX.mjs.map +0 -1
  514. package/dist/prepared-statement-9QpkE6JG-C430V3MO.d.mts +0 -529
  515. package/dist/prepared-statement-9QpkE6JG-C430V3MO.d.mts.map +0 -1
  516. package/dist/psl-infer-CCAD6FWA.d.mts +0 -119
  517. package/dist/psl-infer-CCAD6FWA.d.mts.map +0 -1
  518. package/dist/psl-infer-Dk5kgKre.mjs +0 -362
  519. package/dist/psl-infer-Dk5kgKre.mjs.map +0 -1
  520. package/dist/query-lane-context-Qa-eddrE-kuZ8Z86-.d.mts.map +0 -1
  521. package/dist/query-lane-context-XMvk7fmY.d.mts +0 -1
  522. package/dist/referential-action-sql-DJ9ps6-S.d.mts.map +0 -1
  523. package/dist/referential-action-sql-DSqkrySN.mjs.map +0 -1
  524. package/dist/resolve-storage-table-DZsfnzeW.mjs.map +0 -1
  525. package/dist/resolve-storage-table-Nyrgk4h8.d.mts.map +0 -1
  526. package/dist/runtime-DpKF2Yu2.d.mts.map +0 -1
  527. package/dist/runtime-tIHpGCcG.mjs.map +0 -1
  528. package/dist/runtime.mjs.map +0 -1
  529. package/dist/schema-differ-DpG_gnur-DFAtGezx.d.mts.map +0 -1
  530. package/dist/schema-verify-C_PEdlAr-Dxxjm6EM.mjs.map +0 -1
  531. package/dist/serialized-index-CrgG8ct1-DG3JpHc7.d.mts.map +0 -1
  532. package/dist/serialized-index-nBTwanKy-_ddEK4tk.mjs.map +0 -1
  533. package/dist/sql-contract-serializer-2oBWuxTe-DKZTf2n8.mjs.map +0 -1
  534. package/dist/sql-execution-plan--jKyLpe5-CMGhgO0M.d.mts.map +0 -1
  535. package/dist/sql-index-ByAAE7K8-DKj2V86p.d.mts.map +0 -1
  536. package/dist/sql-node-kEz6YFZo-v2F7delx.d.mts.map +0 -1
  537. package/dist/sql-storage-8LqxeLAY-DH4DdUXx.d.mts.map +0 -1
  538. package/dist/storage-table-DSeWszOL-CI-cItEK.d.mts.map +0 -1
  539. package/dist/storage-table-ZzbR-xzQ-BRoTQE_2.mjs.map +0 -1
  540. package/dist/storage-value-set-BGlj5Uus-CvZD--GG.d.mts.map +0 -1
  541. package/dist/timestamp-now-generator-DRXygu32-DN9Qb1uI.mjs +0 -173
  542. package/dist/timestamp-now-generator-DRXygu32-DN9Qb1uI.mjs.map +0 -1
  543. package/dist/types-4YenawkP-CwaaZSid.mjs.map +0 -1
  544. package/dist/types-B0msOnBM.d.mts +0 -1
  545. package/dist/types-BDUG29Df-LE85dIXP.d.mts +0 -161
  546. package/dist/types-BDUG29Df-LE85dIXP.d.mts.map +0 -1
  547. package/dist/types-CUsJrvEl.mjs.map +0 -1
  548. package/dist/types-CyxGtOOh-BggSa6Fe.d.mts.map +0 -1
  549. package/dist/types-Dt4e_jC--COeP8xzN.mjs.map +0 -1
  550. package/dist/types-Dwcw0F8X.d.mts +0 -1
  551. package/dist/types-IqZMLrFC-DcH8v_u3.d.mts.map +0 -1
  552. package/dist/types-UcHa2cTe.d.mts +0 -17
  553. package/dist/types-UcHa2cTe.d.mts.map +0 -1
  554. package/dist/types-YStFFkKs-D9UAmnON.d.mts.map +0 -1
  555. package/dist/types-v3qxLLxo-DCeKv7yY.d.mts.map +0 -1
  556. package/dist/unique-constraint-M5TlQnJQ-BiIHJ85k.d.mts.map +0 -1
  557. package/dist/util-DQQgv2j1-D6INZaRG.mjs.map +0 -1
  558. package/dist/validators-Belo8QqM.d.mts.map +0 -1
  559. package/dist/validators-CrWD6bSP.mjs.map +0 -1
  560. package/dist/value-set-derivation-hook-BhgGVtw0.d.mts.map +0 -1
  561. package/dist/value-set-derivation-hook-Di9JZ0X7.mjs.map +0 -1
  562. package/dist/verify-u0UTdZgD-DSAaz9rW.mjs.map +0 -1
  563. package/dist/verify-zDRnw0Rn.d.mts.map +0 -1
  564. /package/dist/{contract__pack-types.mjs → relational-core__collection-methods.mjs} +0 -0
@@ -0,0 +1,2389 @@
1
+ import { t as createSqlOperationRegistry } from "./dist-CHz1hF8M.mjs";
2
+ import { K as isQueryAst, j as PreparedParamRef } from "./types-NTQsD2MS-xcLtvKO9.mjs";
3
+ import { t as collectOrderedParamRefs } from "./util-BBgcP3gI-CpL-0VuC.mjs";
4
+ import { t as createSqlParamRefMutator } from "./middleware-yBAfiVWn-DZO0vCRQ.mjs";
5
+ import { t as buildSqlAggregateDescriptorRegistry } from "./aggregate-descriptor-registry-ZrKjxwQe.mjs";
6
+ import { t as buildCodecDescriptorRegistry } from "./codec-descriptor-registry-CiiFzMtb.mjs";
7
+ import { a as runPreparedQuery, c as transactionStart, i as runPreparedExecute, l as wasRefusedBeforeBegin, n as preparedStatementExecute, o as settlementOf, r as preparedStatementQuery, s as transactionSettlement, t as createTransactionStart } from "./transaction-state-BfXhs7D7-DhmbySW9.mjs";
8
+ import { isStructuredError, structuredError } from "@prisma/orm-framework/utils/structured-error";
9
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
10
+ import { createHash } from "node:crypto";
11
+ import { materializeCodec, resolveCodecDescriptorOrThrow } from "@prisma/orm-framework/components/codec";
12
+ import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
13
+ import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
14
+ import { assertNever, isInternalError } from "@prisma/orm-framework/utils/internal-error";
15
+ import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
16
+ import { checkContractComponentRequirements, mergeCapabilityMatrices } from "@prisma/orm-framework/components/components";
17
+ import { AsyncIterableResult, RuntimeCore, applyMutationDefaults, assertMutationDefaultGeneratorsAvailable, checkAborted, checkMiddlewareCompatibility, collectMutationDefaultGenerators, createContextBeneath, executeStatement, raceAgainstAbort, runtimeError as runtimeError$1, startClientActivity, startTransactionActivity, streamStatement } from "@prisma/orm-framework/components/runtime";
18
+ import { invariant } from "@prisma/orm-framework/utils/assertions";
19
+ import { createExecutionStack } from "@prisma/orm-framework/components/execution";
20
+ import { hashContent } from "@prisma/orm-framework/utils/hash-content";
21
+ //#region ../../../2-sql-family/5-runtime/dist/exports-C3wGYtID.mjs
22
+ /** The symbol-keyed member through which a runtime, connection, transaction, `withTransaction` context or activity handle starts activities; user-facing types do not show it. */
23
+ const activitySource = Symbol("activitySource");
24
+ function hasActivitySourceMember(target) {
25
+ return activitySource in target;
26
+ }
27
+ /** The `activitySource` member of a queryable; `undefined` for a queryable that cannot start activities, such as a test stub. */
28
+ function findActivitySource(target) {
29
+ return hasActivitySourceMember(target) ? target[activitySource] : void 0;
30
+ }
31
+ function activitySourceOf(target) {
32
+ const source = findActivitySource(target);
33
+ invariant(source !== void 0, "The queryable cannot start activities");
34
+ return source;
35
+ }
36
+ /** An activity source that calls `source()` each time it is used, for an object whose source is created later, such as on the first query. */
37
+ function lazyActivitySource(source) {
38
+ return {
39
+ startActivity: (activity) => source().startActivity(activity),
40
+ planContentHash: (plan) => source().planContentHash(plan)
41
+ };
42
+ }
43
+ /** An activity source that starts activities on whatever queryable `target()` returns when called, for an object that sends its statements to a queryable it looks up each time. */
44
+ function delegatingActivitySource(target) {
45
+ return lazyActivitySource(() => activitySourceOf(target()));
46
+ }
47
+ /** Starts an activity on a queryable through its `activitySource` member. */
48
+ function startActivityOn(target, activity) {
49
+ return activitySourceOf(target).startActivity(activity);
50
+ }
51
+ function planContentHashOn(target, plan) {
52
+ return activitySourceOf(target).planContentHash(plan);
53
+ }
54
+ /**
55
+ * Build an {@link AstCodecResolver} bound to a descriptor registry and a per-call instance-context factory.
56
+ *
57
+ * The instance-context factory lets callers control `name` / `usedAt` for refs the AST supplies (e.g. AST-embedded migration ops where the materialisation site is the AST node, not a contract column). The contract-walk pre-population path constructs its own contexts and invokes the resolver with those refs to seed the cache.
58
+ */
59
+ function createAstCodecResolver(descriptors, instanceContextFor) {
60
+ const cache = /* @__PURE__ */ new Map();
61
+ return { forCodecRef(ref) {
62
+ const key = `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;
63
+ const cached = cache.get(key);
64
+ if (cached) return cached;
65
+ const codec = materializeCodec(resolveCodecDescriptorOrThrow((id) => descriptors.descriptorFor(id), ref, "RUNTIME.CODEC_DESCRIPTOR_MISSING"), ref, instanceContextFor(ref));
66
+ cache.set(key, codec);
67
+ return codec;
68
+ } };
69
+ }
70
+ /**
71
+ * Build a contract-free {@link ContractCodecRegistry} that resolves codecs
72
+ * purely from AST-supplied {@link import('@internal/framework-components/codec').CodecRef}s
73
+ * against a target's descriptor registry.
74
+ *
75
+ * Dispatch is driven entirely by `CodecRef`s embedded in AST nodes; no
76
+ * contract walk is needed. `forColumn` always returns `undefined` — this
77
+ * registry carries no column-to-codec mappings.
78
+ */
79
+ function createAstCodecRegistry(descriptors) {
80
+ const resolver = createAstCodecResolver(descriptors, (ref) => ({
81
+ name: ref.codecId,
82
+ usedAt: []
83
+ }));
84
+ return {
85
+ forColumn: () => void 0,
86
+ forCodecRef: (ref) => resolver.forCodecRef(ref)
87
+ };
88
+ }
89
+ const NO_METADATA = Object.freeze({
90
+ codec: void 0,
91
+ name: void 0
92
+ });
93
+ function deriveParamMetadata(ast) {
94
+ return collectOrderedParamRefs(ast).map((ref) => {
95
+ return {
96
+ codec: ref.codec,
97
+ name: ref.name
98
+ };
99
+ });
100
+ }
101
+ function resolveParamCodec(metadata, contractCodecs) {
102
+ if (metadata.codec && contractCodecs) return contractCodecs.forCodecRef(metadata.codec);
103
+ }
104
+ function paramLabel(metadata, paramIndex) {
105
+ return metadata.name ?? `param[${paramIndex}]`;
106
+ }
107
+ function wrapEncodeFailure(error, metadata, paramIndex, codecId) {
108
+ if (isInternalError(error)) throw error;
109
+ const label = paramLabel(metadata, paramIndex);
110
+ const wrapped = runtimeError$1("RUNTIME.ENCODE_FAILED", `Failed to encode parameter ${label} with codec '${codecId}': ${error instanceof Error ? error.message : String(error)}`, {
111
+ label,
112
+ codec: codecId,
113
+ paramIndex
114
+ });
115
+ wrapped.cause = error;
116
+ throw wrapped;
117
+ }
118
+ async function encodeParamValue(value, metadata, paramIndex, ctx, contractCodecs) {
119
+ if (value === null || value === void 0) return null;
120
+ const codec = resolveParamCodec(metadata, contractCodecs);
121
+ if (!codec) return value;
122
+ if (metadata.codec?.many) {
123
+ if (!Array.isArray(value)) wrapEncodeFailure(/* @__PURE__ */ new TypeError(`expected an array for many-typed parameter, got ${typeof value}`), metadata, paramIndex, codec.id);
124
+ const encoded = [];
125
+ for (let i = 0; i < value.length; i++) {
126
+ const elem = value[i];
127
+ if (elem === null || elem === void 0) {
128
+ encoded.push(null);
129
+ continue;
130
+ }
131
+ try {
132
+ encoded.push(await codec.toWire(elem, ctx));
133
+ } catch (error) {
134
+ if (isStructuredError(error)) throw error;
135
+ wrapEncodeFailure(error, metadata, paramIndex, codec.id);
136
+ }
137
+ }
138
+ return encoded;
139
+ }
140
+ try {
141
+ return await codec.toWire(value, ctx);
142
+ } catch (error) {
143
+ if (isStructuredError(error)) throw error;
144
+ wrapEncodeFailure(error, metadata, paramIndex, codec.id);
145
+ }
146
+ }
147
+ /**
148
+ * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-and async-authored codecs share the same path: `codec.encode → await → return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.
149
+ *
150
+ * When `ctx.signal` is provided:
151
+ *
152
+ * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs can pin this with a per-call counter that stays at zero.
153
+ * - **Mid-flight abort** races the per-param `Promise.all` against `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly even if codec bodies ignore the signal; the in-flight bodies are abandoned and run to completion in the background (cooperative cancellation, see ADR 204).
154
+ * - Existing structured envelopes (any dotted-code error passing `isStructuredError`, e.g. `RUNTIME.ENCODE_FAILED`) that surface from a codec body before the runtime observes the abort pass through unchanged (no double wrap).
155
+ */
156
+ async function encodeParams(plan, ctx, contractCodecs) {
157
+ return encodeParamsWithMetadata(plan.params, deriveParamMetadata(plan.ast), ctx, contractCodecs);
158
+ }
159
+ async function encodeParamsWithMetadata(values, metadata, ctx, contractCodecs) {
160
+ checkAborted(ctx, "encode");
161
+ const signal = ctx.signal;
162
+ if (values.length === 0) return values;
163
+ const tasks = values.map((value, i) => encodeParamValue(value, metadata[i] ?? NO_METADATA, i, ctx, contractCodecs));
164
+ const settled = await raceAgainstAbort(Promise.all(tasks), signal, "encode");
165
+ return Object.freeze(settled);
166
+ }
167
+ function extractCodecIds(contract) {
168
+ const codecIds = /* @__PURE__ */ new Set();
169
+ for (const ns of Object.values(contract.storage.namespaces)) for (const table of Object.values(ns.entries.table ?? {})) for (const column of Object.values(table.columns)) {
170
+ const codecId = column.codecId;
171
+ codecIds.add(codecId);
172
+ }
173
+ return codecIds;
174
+ }
175
+ function extractColumnCodecRefs(contract) {
176
+ const refs = [];
177
+ for (const [namespaceId, ns] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.entries.table ?? {})) for (const [columnName, column] of Object.entries(table.columns)) refs.push({
178
+ namespaceId,
179
+ table: tableName,
180
+ column: columnName,
181
+ codecId: column.codecId
182
+ });
183
+ return refs;
184
+ }
185
+ function validateContractCodecMappings(registry, contract) {
186
+ const invalidCodecs = extractColumnCodecRefs(contract).filter((ref) => registry.descriptorFor(ref.codecId) === void 0);
187
+ if (invalidCodecs.length > 0) {
188
+ const details = {
189
+ contractTarget: contract.target,
190
+ invalidCodecs
191
+ };
192
+ throw runtimeError$1("RUNTIME.CODEC_MISSING", `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.namespaceId}.${c.table}.${c.column} (${c.codecId})`).join(", ")}`, details);
193
+ }
194
+ }
195
+ function validateCodecRegistryCompleteness(registry, contract) {
196
+ validateContractCodecMappings(registry, contract);
197
+ }
198
+ /**
199
+ * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.
200
+ *
201
+ * Ad-hoc lowerings produce only `{kind: 'literal'}` slots; this helper
202
+ * unwraps them into the bare-value array `SqlExecutionPlan` exposes.
203
+ * Encountering a `{kind: 'bind'}` slot here means the caller passed an
204
+ * AST containing `PreparedParamRef` to the ad-hoc execute path — that's a
205
+ * caller error, surfaced as `RUNTIME.PREPARE_BIND_ON_ADHOC`.
206
+ */
207
+ function lowerSqlPlan(adapter, contract, queryPlan) {
208
+ const lowered = adapter.lower(queryPlan.ast, {
209
+ contract,
210
+ params: queryPlan.params
211
+ });
212
+ const params = lowered.params.map((slot) => {
213
+ if (slot.kind === "literal") return slot.value;
214
+ throw runtimeError$1("RUNTIME.PREPARE_BIND_ON_ADHOC", `The plan has a bind site for '${slot.name}'. A plan built inside prepare(...) runs only as a prepared statement.`, { name: slot.name });
215
+ });
216
+ return Object.freeze({
217
+ sql: lowered.sql,
218
+ params,
219
+ ast: queryPlan.ast,
220
+ meta: queryPlan.meta
221
+ });
222
+ }
223
+ function hasAggregateWithoutGroupBy(ast) {
224
+ if (ast.groupBy !== void 0) return false;
225
+ return ast.projection.some((item) => item.expr.kind === "aggregate");
226
+ }
227
+ function primaryTableFromAst(ast) {
228
+ if (ast.from === void 0) return void 0;
229
+ switch (ast.from.kind) {
230
+ case "table-source": return ast.from.name;
231
+ case "derived-table-source": return ast.from.alias;
232
+ case "function-source": return ast.from.fn;
233
+ // v8 ignore next 4
234
+ default: return assertNever(ast.from, `Unsupported source kind: ${ast.from.kind}`);
235
+ }
236
+ }
237
+ function estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggregateWithoutGroup) {
238
+ if (hasAggregateWithoutGroup) return 1;
239
+ const primaryTable = primaryTableFromAst(ast);
240
+ const tableEstimate = (primaryTable !== void 0 ? tableRows[primaryTable] : void 0) ?? defaultTableRows;
241
+ if (typeof ast.limit === "number") return Math.min(ast.limit, tableEstimate);
242
+ return tableEstimate;
243
+ }
244
+ function emitBudgetViolation(error, shouldBlock, ctx) {
245
+ if (shouldBlock) throw error;
246
+ ctx.log.warn({
247
+ code: error.code,
248
+ message: error.message,
249
+ details: error.details
250
+ });
251
+ }
252
+ const observedRows = Symbol("budgets.observedRows");
253
+ function budgets(options) {
254
+ const maxRows = options?.maxRows ?? 1e4;
255
+ const defaultTableRows = options?.defaultTableRows ?? 1e4;
256
+ const tableRows = options?.tableRows ?? {};
257
+ const maxLatencyMs = options?.maxLatencyMs ?? 1e3;
258
+ const rowSeverity = options?.severities?.rowCount ?? "error";
259
+ const latencySeverity = options?.severities?.latency ?? "warn";
260
+ return Object.freeze({
261
+ name: "budgets",
262
+ familyId: "sql",
263
+ async beforeEncode(plan, ctx) {
264
+ if (isQueryAst(plan.ast) && plan.ast.kind === "select") evaluateSelectAst(plan.ast, ctx);
265
+ },
266
+ async onRow(_row, _plan, ctx) {
267
+ const observed = ctx.state(observedRows);
268
+ const count = (typeof observed["count"] === "number" ? observed["count"] : 0) + 1;
269
+ observed["count"] = count;
270
+ if (count <= maxRows || observed["warned"] === true) return;
271
+ const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
272
+ if (!shouldBlock) observed["warned"] = true;
273
+ emitBudgetViolation(runtimeError$1("BUDGET.ROWS_EXCEEDED", "Observed row count exceeds budget", {
274
+ source: "observed",
275
+ observedRows: count,
276
+ maxRows
277
+ }), shouldBlock, ctx);
278
+ },
279
+ async activityEnded(_activity, result, ctx) {
280
+ if (result.kind === "statement") checkLatency(result.latencyMs, ctx);
281
+ }
282
+ });
283
+ function checkLatency(latencyMs, ctx) {
284
+ if (latencyMs > maxLatencyMs) {
285
+ const shouldBlock = latencySeverity === "error" || ctx.mode === "strict";
286
+ emitBudgetViolation(runtimeError$1("BUDGET.TIME_EXCEEDED", "Query latency exceeds budget", {
287
+ latencyMs,
288
+ maxLatencyMs
289
+ }), shouldBlock, ctx);
290
+ }
291
+ }
292
+ function evaluateSelectAst(ast, ctx) {
293
+ const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);
294
+ const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);
295
+ const isUnbounded = ast.limit === void 0 && !hasAggNoGroup;
296
+ const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
297
+ if (isUnbounded) {
298
+ emitBudgetViolation(runtimeError$1("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", estimated >= maxRows ? {
299
+ source: "ast",
300
+ estimatedRows: estimated,
301
+ maxRows
302
+ } : {
303
+ source: "ast",
304
+ maxRows
305
+ }), shouldBlock, ctx);
306
+ return;
307
+ }
308
+ if (estimated > maxRows) emitBudgetViolation(runtimeError$1("BUDGET.ROWS_EXCEEDED", "Estimated row count exceeds budget", {
309
+ source: "ast",
310
+ estimatedRows: estimated,
311
+ maxRows
312
+ }), shouldBlock, ctx);
313
+ }
314
+ }
315
+ const SELECT_STAR_REGEX = /select\s+\*/i;
316
+ const LIMIT_REGEX = /\blimit\b/i;
317
+ const MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\b/i;
318
+ const READ_ONLY_INTENTS = /* @__PURE__ */ new Set([
319
+ "read",
320
+ "report",
321
+ "readonly"
322
+ ]);
323
+ function evaluateRawGuardrails(plan, config) {
324
+ const lints = [];
325
+ const budgets = [];
326
+ const normalized = normalizeWhitespace(plan.sql);
327
+ const statementType = classifyStatement(normalized);
328
+ if (statementType === "select") {
329
+ if (SELECT_STAR_REGEX.test(normalized)) lints.push(createLint("LINT.SELECT_STAR", "error", "Raw SQL plan selects all columns via *", { sql: snippet(plan.sql) }));
330
+ if (!LIMIT_REGEX.test(normalized)) {
331
+ const severity = config?.budgets?.unboundedSelectSeverity ?? "error";
332
+ lints.push(createLint("LINT.NO_LIMIT", "warn", "Raw SQL plan omits LIMIT clause", { sql: snippet(plan.sql) }));
333
+ budgets.push(createBudget("BUDGET.ROWS_EXCEEDED", severity, "Raw SQL plan is unbounded and may exceed row budget", {
334
+ sql: snippet(plan.sql),
335
+ ...config?.budgets?.estimatedRows !== void 0 ? { estimatedRows: config.budgets.estimatedRows } : {}
336
+ }));
337
+ }
338
+ }
339
+ if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) lints.push(createLint("LINT.READ_ONLY_MUTATION", "error", "Raw SQL plan mutates data despite read-only intent", {
340
+ sql: snippet(plan.sql),
341
+ intent: plan.meta.annotations?.["intent"]
342
+ }));
343
+ return {
344
+ lints,
345
+ budgets,
346
+ statement: statementType
347
+ };
348
+ }
349
+ function classifyStatement(sql) {
350
+ const trimmed = sql.trim();
351
+ const lower = trimmed.toLowerCase();
352
+ if (lower.startsWith("with")) {
353
+ if (lower.includes("select")) return "select";
354
+ }
355
+ if (lower.startsWith("select")) return "select";
356
+ if (MUTATION_PREFIX_REGEX.test(trimmed)) return "mutation";
357
+ return "other";
358
+ }
359
+ function isMutationStatement(statement) {
360
+ return statement === "mutation";
361
+ }
362
+ function isReadOnlyIntent(meta) {
363
+ const annotations = meta.annotations;
364
+ const intent = typeof annotations?.intent === "string" ? annotations.intent.toLowerCase() : void 0;
365
+ return intent !== void 0 && READ_ONLY_INTENTS.has(intent);
366
+ }
367
+ function normalizeWhitespace(value) {
368
+ return value.replace(/\s+/g, " ").trim();
369
+ }
370
+ function snippet(sql) {
371
+ return normalizeWhitespace(sql).slice(0, 200);
372
+ }
373
+ function createLint(code, severity, message, details) {
374
+ return {
375
+ code,
376
+ severity,
377
+ message,
378
+ ...details ? { details } : {}
379
+ };
380
+ }
381
+ function createBudget(code, severity, message, details) {
382
+ return {
383
+ code,
384
+ severity,
385
+ message,
386
+ ...details ? { details } : {}
387
+ };
388
+ }
389
+ function getFromSourceTableDetail(source) {
390
+ switch (source.kind) {
391
+ case "table-source": return source.name;
392
+ case "derived-table-source": return source.alias;
393
+ case "function-source": return source.fn;
394
+ // v8 ignore next 4
395
+ default: return assertNever(source, `Unsupported source kind: ${source.kind}`);
396
+ }
397
+ }
398
+ function evaluateAstLints(ast) {
399
+ const findings = [];
400
+ switch (ast.kind) {
401
+ case "delete":
402
+ if (ast.where === void 0) findings.push({
403
+ code: "LINT.DELETE_WITHOUT_WHERE",
404
+ severity: "error",
405
+ message: "DELETE without WHERE clause blocks execution to prevent accidental full-table deletion",
406
+ details: { table: ast.table.name }
407
+ });
408
+ break;
409
+ case "update":
410
+ if (ast.where === void 0) findings.push({
411
+ code: "LINT.UPDATE_WITHOUT_WHERE",
412
+ severity: "error",
413
+ message: "UPDATE without WHERE clause blocks execution to prevent accidental full-table update",
414
+ details: { table: ast.table.name }
415
+ });
416
+ break;
417
+ case "select":
418
+ if (ast.limit === void 0) {
419
+ const table = ast.from !== void 0 ? getFromSourceTableDetail(ast.from) : void 0;
420
+ findings.push({
421
+ code: "LINT.NO_LIMIT",
422
+ severity: "warn",
423
+ message: "Unbounded SELECT may return large result sets",
424
+ ...ifDefined("details", table !== void 0 ? { table } : void 0)
425
+ });
426
+ }
427
+ if (ast.selectAllIntent !== void 0) {
428
+ const table = ast.selectAllIntent.table;
429
+ findings.push({
430
+ code: "LINT.SELECT_STAR",
431
+ severity: "warn",
432
+ message: "Query selects all columns via selectAll intent",
433
+ ...ifDefined("details", table !== void 0 ? { table } : void 0)
434
+ });
435
+ }
436
+ break;
437
+ case "insert": break;
438
+ case "raw-query": break;
439
+ // v8 ignore next 2
440
+ default: assertNever(ast, `Unsupported AST kind: ${ast.kind}`);
441
+ }
442
+ return findings;
443
+ }
444
+ function getConfiguredSeverity(code, options) {
445
+ const severities = options?.severities;
446
+ if (!severities) return void 0;
447
+ switch (code) {
448
+ case "LINT.SELECT_STAR": return severities.selectStar;
449
+ case "LINT.NO_LIMIT": return severities.noLimit;
450
+ case "LINT.DELETE_WITHOUT_WHERE": return severities.deleteWithoutWhere;
451
+ case "LINT.UPDATE_WITHOUT_WHERE": return severities.updateWithoutWhere;
452
+ case "LINT.READ_ONLY_MUTATION": return severities.readOnlyMutation;
453
+ default: return;
454
+ }
455
+ }
456
+ /**
457
+ * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects
458
+ * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic
459
+ * guardrails or skips linting depending on `fallbackWhenAstMissing`.
460
+ *
461
+ * Rules (AST-based):
462
+ * - DELETE without WHERE: blocks execution (configurable severity, default error)
463
+ * - UPDATE without WHERE: blocks execution (configurable severity, default error)
464
+ * - Unbounded SELECT: warn/error (severity from noLimit)
465
+ * - SELECT * intent: warn/error (severity from selectStar)
466
+ *
467
+ * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic
468
+ * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.
469
+ */
470
+ function lints(options) {
471
+ const fallback = options?.fallbackWhenAstMissing ?? "raw";
472
+ const beforeOperation = async (plan, ctx) => {
473
+ const findings = [];
474
+ if (isQueryAst(plan.ast)) {
475
+ findings.push(...evaluateAstLints(plan.ast));
476
+ if (plan.ast.kind === "raw-query") findings.push(...evaluateRawGuardrails(plan).lints);
477
+ } else if (fallback !== "skip") findings.push(...evaluateRawGuardrails(plan).lints);
478
+ for (const lint of findings) {
479
+ const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
480
+ if (effectiveSeverity === "error") throw runtimeError$1(lint.code, lint.message, lint.details);
481
+ if (effectiveSeverity === "warn") ctx.log.warn({
482
+ code: lint.code,
483
+ message: lint.message,
484
+ details: lint.details
485
+ });
486
+ }
487
+ };
488
+ return Object.freeze({
489
+ name: "lints",
490
+ familyId: "sql",
491
+ beforeEncode: beforeOperation
492
+ });
493
+ }
494
+ var PreparedStatementImpl = class {
495
+ sql;
496
+ ast;
497
+ meta;
498
+ slots;
499
+ decodeContext;
500
+ paramMetadata;
501
+ constructor(internals) {
502
+ this.sql = internals.sql;
503
+ this.ast = internals.ast;
504
+ this.meta = internals.meta;
505
+ this.slots = internals.slots;
506
+ this.decodeContext = internals.decodeContext;
507
+ this.paramMetadata = internals.paramMetadata;
508
+ Object.freeze(this);
509
+ }
510
+ query(target, params, options) {
511
+ return runPreparedQuery(target, this, params, options);
512
+ }
513
+ };
514
+ /**
515
+ * The statistics-reporting sibling of {@link PreparedStatementImpl}. A plan
516
+ * declaring an affected-row count prepares into one of these, which carries
517
+ * the same lowered statement and bind slots and is consumed by executing it.
518
+ *
519
+ * The two classes are separate so the consumption a plan did not declare is
520
+ * absent from the value, not merely from its type.
521
+ */
522
+ var PreparedExecutionImpl = class {
523
+ sql;
524
+ ast;
525
+ meta;
526
+ slots;
527
+ decodeContext;
528
+ paramMetadata;
529
+ constructor(internals) {
530
+ this.sql = internals.sql;
531
+ this.ast = internals.ast;
532
+ this.meta = internals.meta;
533
+ this.slots = internals.slots;
534
+ this.decodeContext = internals.decodeContext;
535
+ this.paramMetadata = internals.paramMetadata;
536
+ Object.freeze(this);
537
+ }
538
+ execute(target, params, options) {
539
+ return runPreparedExecute(target, this, params, options);
540
+ }
541
+ };
542
+ function createSqlExecutionStack(options) {
543
+ return createExecutionStack({
544
+ target: options.target,
545
+ adapter: options.adapter,
546
+ driver: options.driver,
547
+ extensions: options.extensions
548
+ });
549
+ }
550
+ function assertExecutionStackContractRequirements(contract, stack) {
551
+ const providedComponentIds = /* @__PURE__ */ new Set([
552
+ stack.target.id,
553
+ stack.adapter.id,
554
+ ...stack.extensions.map((pack) => pack.id)
555
+ ]);
556
+ const result = checkContractComponentRequirements({
557
+ contract,
558
+ expectedTargetFamily: "sql",
559
+ expectedTargetId: stack.target.targetId,
560
+ providedComponentIds
561
+ });
562
+ if (result.familyMismatch) throw runtimeError$1("RUNTIME.CONTRACT_FAMILY_MISMATCH", `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`, {
563
+ actual: result.familyMismatch.actual,
564
+ expected: result.familyMismatch.expected
565
+ });
566
+ if (result.targetMismatch) throw runtimeError$1("RUNTIME.CONTRACT_TARGET_MISMATCH", `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`, {
567
+ actual: result.targetMismatch.actual,
568
+ expected: result.targetMismatch.expected
569
+ });
570
+ if (result.missingExtensionPackIds.length > 0) {
571
+ const packIds = result.missingExtensionPackIds;
572
+ throw runtimeError$1("RUNTIME.MISSING_EXTENSION_PACK", `Contract requires extension pack(s) ${packIds.map((id) => `'${id}'`).join(", ")}, but runtime descriptors do not provide matching component(s).`, { packIds });
573
+ }
574
+ }
575
+ function validateTypeParams(typeParams, descriptor, context) {
576
+ const result = descriptor.paramsSchema["~standard"].validate(typeParams);
577
+ if (result instanceof Promise) throw runtimeError$1("RUNTIME.TYPE_PARAMS_INVALID", `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`, {
578
+ ...context,
579
+ codecId: descriptor.codecId,
580
+ typeParams
581
+ });
582
+ if (result.issues) {
583
+ const messages = result.issues.map((issue) => issue.message).join("; ");
584
+ throw runtimeError$1("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for column '${context.tableName}.${context.columnName}' (codecId: ${descriptor.codecId}): ${messages}`, {
585
+ ...context,
586
+ codecId: descriptor.codecId,
587
+ typeParams
588
+ });
589
+ }
590
+ return blindCast(result.value);
591
+ }
592
+ /**
593
+ * Collect every {@link CodecDescriptor} contributed by the SQL stack and partition into "parameterized" vs "non-parameterized" via the descriptor's own {@link CodecDescriptorImpl.isParameterized} getter: a descriptor is parameterized when it has a `paramsSchema`.
594
+ *
595
+ * The unified descriptor list collapses the legacy split (a separate slot used to register parameterized codecs) — every codec id resolves through the same map (codec-registry-unification spec § Decision).
596
+ */
597
+ function collectCodecDescriptors(contributors) {
598
+ const all = [];
599
+ const parameterized = /* @__PURE__ */ new Map();
600
+ const seen = /* @__PURE__ */ new Set();
601
+ for (const contributor of contributors) for (const descriptor of contributor.codecs()) {
602
+ if (seen.has(descriptor.codecId)) throw runtimeError$1("RUNTIME.DUPLICATE_CODEC", `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`, { codecId: descriptor.codecId });
603
+ seen.add(descriptor.codecId);
604
+ all.push(descriptor);
605
+ if (descriptor.isParameterized) parameterized.set(descriptor.codecId, blindCast(descriptor));
606
+ }
607
+ return {
608
+ all,
609
+ parameterized
610
+ };
611
+ }
612
+ /**
613
+ * Flatten every aggregate descriptor the SQL stack contributes. Shape validation, single-ownership of each `(operation, input)` pair, and trait-overlap resolution all happen inside {@link buildSqlAggregateDescriptorRegistry}, so contributions reach it unchecked and fail there — at composition, never mid-query.
614
+ */
615
+ function collectAggregateDescriptorContributions(contributors) {
616
+ return contributors.flatMap((contributor) => contributor.types?.aggregateDescriptors ?? []);
617
+ }
618
+ function validateColumnTypeParams(storage, codecDescriptors) {
619
+ for (const ns of Object.values(storage.namespaces)) for (const [tableName, table] of Object.entries(ns.entries.table ?? {})) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeParams) {
620
+ const descriptor = codecDescriptors.get(column.codecId);
621
+ if (descriptor) validateTypeParams(column.typeParams, descriptor, {
622
+ tableName,
623
+ columnName
624
+ });
625
+ }
626
+ }
627
+ /**
628
+ * Build-time contract-integrity check: every `(table, column)` resolves to a {@link CodecRef} whose `codecId` is registered and whose `typeParams` presence matches the descriptor's `isParameterized` flag.
629
+ *
630
+ * Surfaces three classes of malformed contract that AST-bound codec resolution would otherwise mask silently:
631
+ *
632
+ * - column references a codecId no contributor registered → `RUNTIME.CODEC_DESCRIPTOR_MISSING`.
633
+ * - parameterized codec, no `typeParams` (legacy "tolerate refs without params" shape) → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.
634
+ * - non-parameterized codec, `typeParams` supplied → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.
635
+ *
636
+ * Runs unconditionally from `createExecutionContext` so contract bugs fail fast at construction time instead of silently skipping affected columns in the codec registry's pre-population walk.
637
+ */
638
+ function assertColumnCodecIntegrity(storage, codecDescriptors) {
639
+ for (const [namespaceId, ns] of Object.entries(storage.namespaces)) for (const [tableName, table] of Object.entries(ns.entries.table ?? {})) for (const columnName of Object.keys(table.columns)) {
640
+ const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
641
+ if (!ref) continue;
642
+ const descriptor = codecDescriptors.descriptorFor(ref.codecId);
643
+ if (!descriptor) throw runtimeError$1("RUNTIME.CODEC_DESCRIPTOR_MISSING", `Column '${tableName}.${columnName}' references codec '${ref.codecId}' but no contributor registered a codec descriptor for that codecId. Add the extension pack that owns the codec to the runtime stack.`, {
644
+ table: tableName,
645
+ column: columnName,
646
+ codecId: ref.codecId
647
+ });
648
+ const paramsSchema = descriptor.paramsSchema;
649
+ if (paramsSchema !== void 0 && ref.typeParams === void 0) {
650
+ const probe = paramsSchema["~standard"].validate({});
651
+ if (probe instanceof Promise) {
652
+ probe.catch(() => {});
653
+ throw runtimeError$1("RUNTIME.TYPE_PARAMS_INVALID", `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' whose paramsSchema returned a Promise; paramsSchema must be a synchronous Standard Schema validator. Return a value/issues result directly instead of a Promise.`, {
654
+ table: tableName,
655
+ column: columnName,
656
+ codecId: ref.codecId
657
+ });
658
+ }
659
+ if ("issues" in probe && !!probe.issues) throw runtimeError$1("RUNTIME.CODEC_PARAMETERIZATION_MISMATCH", `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' but no typeParams are supplied. Provide typeParams on the column.`, {
660
+ table: tableName,
661
+ column: columnName,
662
+ codecId: ref.codecId,
663
+ expected: "parameterized",
664
+ actual: "no typeParams"
665
+ });
666
+ }
667
+ const refTypeParams = ref.typeParams;
668
+ const refHasTypeParamKeys = refTypeParams !== void 0 && refTypeParams !== null && typeof refTypeParams === "object" && !Array.isArray(refTypeParams) && Object.keys(refTypeParams).length > 0;
669
+ if (!descriptor.isParameterized && refHasTypeParamKeys) throw runtimeError$1("RUNTIME.CODEC_PARAMETERIZATION_MISMATCH", `Column '${tableName}.${columnName}' supplies typeParams to non-parameterized codec '${ref.codecId}'. Remove the typeParams or switch to a parameterized codec id.`, {
670
+ table: tableName,
671
+ column: columnName,
672
+ codecId: ref.codecId,
673
+ expected: "non-parameterized",
674
+ actual: "has typeParams"
675
+ });
676
+ }
677
+ }
678
+ /**
679
+ * Build a {@link ContractCodecRegistry} that resolves codecs exclusively through the `forCodecRef` content-keyed cache.
680
+ *
681
+ * One pre-population pass walks `storage.tables[].columns[]` to seed the resolver's per-ref instance context with the *aggregated* `usedAt` set for each canonical `(codecId, typeParams)` key. The same codec materialised through `forColumn` or `forCodecRef` is therefore one instance with one `SqlCodecInstanceContext` — stateful codecs reading `usedAt` see the full column set regardless of which surface the caller used.
682
+ *
683
+ * Per-key instance-name policy:
684
+ *
685
+ * - columns with `typeParams` use `<col:Table.column>` (the first column observed at that key; additional columns sharing the key extend `usedAt`).
686
+ * - non-parameterized codec ids use `<codec:codecId>`, aggregating every column on that codec id into one `usedAt` set.
687
+ * - ad-hoc refs the contract walk did not pre-populate (e.g. AST-supplied refs from deserialised migration ops) fall back to the canonical cache key `${codecId}:${canonicalizeJson(typeParams)}` — the only structurally honest identity for an ad-hoc ref, distinct per `(codecId, typeParams)`.
688
+ *
689
+ * Contract integrity is enforced upstream by {@link assertColumnCodecIntegrity}: every column must reference a registered `codecId` whose `descriptor.isParameterized` flag matches the presence of `typeParams` (via `codecRefForColumn`). The pre-population walk and `forColumn` therefore make no defensive checks — malformed columns fail fast at `createExecutionContext` construction with `RUNTIME.CODEC_DESCRIPTOR_MISSING` or `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH` rather than being silently skipped here.
690
+ *
691
+ * `forColumn(ns, t, c)` is a thin delegate over `forCodecRef(codecRefForColumn(ns, t, c))`; encode/decode hot paths read the resolver directly via `forCodecRef`. The only `undefined` `forColumn` returns is the legitimate "no such column in the contract" case.
692
+ */
693
+ function buildContractCodecRegistry(contract, codecDescriptors) {
694
+ const refKeyOf = (ref) => `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;
695
+ const usedAtByKey = /* @__PURE__ */ new Map();
696
+ const nameByKey = /* @__PURE__ */ new Map();
697
+ for (const [namespaceId, ns] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.entries.table ?? {})) for (const columnName of Object.keys(table.columns)) {
698
+ const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
699
+ if (!ref) continue;
700
+ const key = refKeyOf(ref);
701
+ const site = {
702
+ table: tableName,
703
+ column: columnName
704
+ };
705
+ const existing = usedAtByKey.get(key);
706
+ if (existing) existing.push(site);
707
+ else {
708
+ usedAtByKey.set(key, [site]);
709
+ const name = ref.typeParams !== void 0 ? `<col:${tableName}.${columnName}>` : `<codec:${ref.codecId}>`;
710
+ nameByKey.set(key, name);
711
+ }
712
+ }
713
+ const resolver = createAstCodecResolver(codecDescriptors, (ref) => {
714
+ const key = refKeyOf(ref);
715
+ return {
716
+ name: nameByKey.get(key) ?? key,
717
+ usedAt: usedAtByKey.get(key) ?? []
718
+ };
719
+ });
720
+ for (const [namespaceId, ns] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.entries.table ?? {})) for (const columnName of Object.keys(table.columns)) {
721
+ const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
722
+ if (!ref) continue;
723
+ resolver.forCodecRef(ref);
724
+ }
725
+ return {
726
+ forColumn(namespaceId, table, column) {
727
+ const ref = codecDescriptors.codecRefForColumn(namespaceId, table, column);
728
+ return ref ? resolver.forCodecRef(ref) : void 0;
729
+ },
730
+ forCodecRef(ref) {
731
+ return resolver.forCodecRef(ref);
732
+ }
733
+ };
734
+ }
735
+ function createExecutionContext(options) {
736
+ const { stack, driver } = options;
737
+ assertExecutionStackContractRequirements(options.contract, stack);
738
+ const capabilityContributors = [
739
+ stack.target,
740
+ stack.adapter,
741
+ ...driver ? [driver] : [],
742
+ ...stack.extensions
743
+ ];
744
+ const mergedCapabilities = mergeCapabilityMatrices(options.contract.capabilities, capabilityContributors);
745
+ const contract = {
746
+ ...options.contract,
747
+ capabilities: mergedCapabilities
748
+ };
749
+ const contributors = [
750
+ stack.target,
751
+ stack.adapter,
752
+ ...stack.extensions
753
+ ];
754
+ const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } = collectCodecDescriptors(contributors);
755
+ const queryOperationRegistry = createSqlOperationRegistry();
756
+ for (const contributor of contributors) {
757
+ const ops = contributor.queryOperations?.() ?? {};
758
+ for (const [name, op] of Object.entries(ops)) queryOperationRegistry.register(name, op);
759
+ }
760
+ const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors, contract.storage);
761
+ assertColumnCodecIntegrity(contract.storage, codecDescriptors);
762
+ const aggregateDescriptors = buildSqlAggregateDescriptorRegistry(collectAggregateDescriptorContributions(contributors), codecDescriptors);
763
+ const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);
764
+ assertMutationDefaultGeneratorsAvailable(contract.execution, mutationDefaultGeneratorRegistry);
765
+ if (parameterizedCodecDescriptors.size > 0) validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);
766
+ return {
767
+ contract,
768
+ contractCodecs: buildContractCodecRegistry(contract, codecDescriptors),
769
+ codecDescriptors,
770
+ aggregateDescriptors,
771
+ queryOperations: queryOperationRegistry,
772
+ rawCodecInferer: stack.adapter.rawCodecInferer,
773
+ collectionMethods: contributors.flatMap((contributor) => contributor.collectionMethods?.() ?? []),
774
+ applyMutationDefaults: (options) => applyMutationDefaults(contract.execution, mutationDefaultGeneratorRegistry, options)
775
+ };
776
+ }
777
+ const sqlNativeArrayListDecoder = async (wireValue, decodeElement) => {
778
+ if (!Array.isArray(wireValue)) throw new TypeError(`expected an array from the driver for many-typed column, got ${typeof wireValue}`);
779
+ const decoded = [];
780
+ for (const elem of wireValue) decoded.push(await decodeElement(elem));
781
+ return decoded;
782
+ };
783
+ const WIRE_PREVIEW_LIMIT = 100;
784
+ const EMPTY_INCLUDE_ALIASES = /* @__PURE__ */ new Set();
785
+ function projectionListFromAst(ast) {
786
+ if (ast.kind === "select") return ast.projection;
787
+ return ast.returning;
788
+ }
789
+ function resolveProjectionCodec(item, contractCodecs) {
790
+ if (item.codec && contractCodecs) return contractCodecs.forCodecRef(item.codec);
791
+ }
792
+ const EMPTY_MANY_ALIASES = /* @__PURE__ */ new Set();
793
+ function undecodedContext() {
794
+ return {
795
+ aliases: void 0,
796
+ codecs: /* @__PURE__ */ new Map(),
797
+ columnRefs: /* @__PURE__ */ new Map(),
798
+ includeAliases: EMPTY_INCLUDE_ALIASES,
799
+ manyAliases: EMPTY_MANY_ALIASES,
800
+ aliasSource: "projection"
801
+ };
802
+ }
803
+ /**
804
+ * Decode context for a raw statement: the columns come from the row spec its
805
+ * author declared at the terminator, and each carries the codec that decodes
806
+ * it. A statement that reports an affected-row count declares no columns, so
807
+ * its single stats row passes through undecoded.
808
+ *
809
+ * The spec is the only description of the result — the runtime never parses
810
+ * the SQL — so it is also what a mismatched result set is measured against.
811
+ */
812
+ function rawQueryDecodeContext(ast, contractCodecs) {
813
+ if (ast.result.kind === "affected-count") return undecodedContext();
814
+ const aliases = [];
815
+ const codecs = /* @__PURE__ */ new Map();
816
+ for (const [name, column] of Object.entries(ast.result.columns)) {
817
+ aliases.push(name);
818
+ if (contractCodecs) codecs.set(name, contractCodecs.forCodecRef({ codecId: column.codecId }));
819
+ }
820
+ return {
821
+ aliases,
822
+ codecs,
823
+ columnRefs: /* @__PURE__ */ new Map(),
824
+ includeAliases: EMPTY_INCLUDE_ALIASES,
825
+ manyAliases: EMPTY_MANY_ALIASES,
826
+ aliasSource: "row-spec"
827
+ };
828
+ }
829
+ function buildDecodeContext(ast, contractCodecs) {
830
+ if (ast.kind === "raw-query") return rawQueryDecodeContext(ast, contractCodecs);
831
+ const projection = projectionListFromAst(ast);
832
+ if (!projection || projection.length === 0) return undecodedContext();
833
+ const aliases = [];
834
+ const codecs = /* @__PURE__ */ new Map();
835
+ const columnRefs = /* @__PURE__ */ new Map();
836
+ const includeAliases = /* @__PURE__ */ new Set();
837
+ const manyAliases = /* @__PURE__ */ new Set();
838
+ for (const item of projection) {
839
+ aliases.push(item.alias);
840
+ const codec = resolveProjectionCodec(item, contractCodecs);
841
+ if (codec) codecs.set(item.alias, codec);
842
+ if (item.codec?.many) manyAliases.add(item.alias);
843
+ if (item.expr.kind === "column-ref") columnRefs.set(item.alias, {
844
+ table: item.expr.table,
845
+ column: item.expr.column
846
+ });
847
+ else if (item.expr.kind === "subquery" || item.expr.kind === "json-array-agg") includeAliases.add(item.alias);
848
+ }
849
+ return {
850
+ aliases,
851
+ codecs,
852
+ columnRefs,
853
+ includeAliases,
854
+ manyAliases,
855
+ aliasSource: "projection"
856
+ };
857
+ }
858
+ function previewWireValue(wireValue) {
859
+ if (typeof wireValue === "string") return wireValue.length > WIRE_PREVIEW_LIMIT ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...` : wireValue;
860
+ return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
861
+ }
862
+ function wrapDecodeFailure(error, alias, ref, codec, wireValue) {
863
+ if (isInternalError(error)) throw error;
864
+ const message = error instanceof Error ? error.message : String(error);
865
+ const wrapped = runtimeError$1("RUNTIME.DECODE_FAILED", `Failed to decode column ${ref ? `${ref.table}.${ref.column}` : alias} with codec '${codec.id}': ${message}`, {
866
+ ...ref ? {
867
+ table: ref.table,
868
+ column: ref.column
869
+ } : { alias },
870
+ codec: codec.id,
871
+ wirePreview: previewWireValue(wireValue)
872
+ });
873
+ wrapped.cause = error;
874
+ throw wrapped;
875
+ }
876
+ function wrapIncludeAggregateFailure(error, alias, wireValue) {
877
+ const wrapped = runtimeError$1("RUNTIME.DECODE_FAILED", `Failed to parse JSON array for include alias '${alias}': ${error instanceof Error ? error.message : String(error)}`, {
878
+ alias,
879
+ wirePreview: previewWireValue(wireValue)
880
+ });
881
+ wrapped.cause = error;
882
+ throw wrapped;
883
+ }
884
+ function decodeIncludeAggregate(alias, wireValue) {
885
+ if (wireValue === null || wireValue === void 0) return [];
886
+ try {
887
+ if (typeof wireValue === "string") return JSON.parse(wireValue);
888
+ if (typeof wireValue === "object") return blindCast(wireValue);
889
+ return JSON.parse(String(wireValue));
890
+ } catch (error) {
891
+ wrapIncludeAggregateFailure(error, alias, wireValue);
892
+ }
893
+ }
894
+ /**
895
+ * Decodes a single field. Single-armed: every cell takes the same path — `codec.decode → await → return plain value` — so sync- and async-authored codecs are indistinguishable to callers. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (e.g. `arktype-json` validates against its rehydrated schema and throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` from `decode` directly); there is
896
+ * no separate validator-registry pass.
897
+ *
898
+ * The row-level `rowCtx` is repackaged into a per-cell `SqlCodecCallContext` whose `column = { table, name }` is a structural projection of the per-cell `ColumnRef = { table, column }` resolved from the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure` uses for envelope construction — one resolution per cell, two consumers). Cells the runtime cannot resolve to a single underlying column (aggregate
899
+ * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.
900
+ *
901
+ * For `many`-flagged aliases this function delegates frame traversal to the selected `ListDecoder`, passing `null` elements through unchanged and mapping the same element codec over every non-null element. SQL runtimes without a target-owned contribution select `sqlNativeArrayListDecoder` explicitly before row decoding. Element-level failures surface through the existing `RUNTIME.DECODE_FAILED` envelope with the column/codec context from the parent cell.
902
+ */
903
+ async function decodeField(alias, wireValue, decodeCtx, rowCtx, listDecoder) {
904
+ if (wireValue === null) return null;
905
+ const codec = decodeCtx.codecs.get(alias);
906
+ if (!codec) return wireValue;
907
+ const ref = decodeCtx.columnRefs.get(alias);
908
+ let cellCtx;
909
+ if (ref) cellCtx = {
910
+ ...rowCtx,
911
+ column: {
912
+ table: ref.table,
913
+ name: ref.column
914
+ }
915
+ };
916
+ else {
917
+ const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;
918
+ cellCtx = rowCtxWithoutColumn;
919
+ }
920
+ const decodeElement = async (elem) => {
921
+ if (elem === null || elem === void 0) return null;
922
+ try {
923
+ return await codec.fromWire(elem, cellCtx);
924
+ } catch (error) {
925
+ if (isStructuredError(error)) throw error;
926
+ wrapDecodeFailure(error, alias, ref, codec, elem);
927
+ }
928
+ };
929
+ if (decodeCtx.manyAliases.has(alias)) try {
930
+ return await listDecoder(wireValue, decodeElement);
931
+ } catch (error) {
932
+ if (isStructuredError(error)) throw error;
933
+ wrapDecodeFailure(error, alias, ref, codec, wireValue);
934
+ }
935
+ try {
936
+ return await codec.fromWire(wireValue, cellCtx);
937
+ } catch (error) {
938
+ if (isStructuredError(error)) throw error;
939
+ wrapDecodeFailure(error, alias, ref, codec, wireValue);
940
+ }
941
+ }
942
+ /**
943
+ * Decodes a row by dispatching all per-cell codec calls concurrently via `Promise.all`. Each cell follows the single-armed `decodeField` path. Structured envelopes thrown by codec bodies (anything passing `isStructuredError`) and an `InternalError` pass through unchanged; all other failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column, codec }` (or `{ alias, codec }` when no column ref is resolvable) and the original error attached on `cause`.
944
+ *
945
+ * When `rowCtx.signal` is provided:
946
+ *
947
+ * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.
948
+ * - **Mid-flight aborts** race the per-cell `Promise.all` against the signal so the runtime returns promptly even when codec bodies ignore it. In-flight bodies that ignore the signal complete in the background (cooperative cancellation).
949
+ * - Existing structured envelopes (any dotted-code error passing `isStructuredError`, e.g. `RUNTIME.DECODE_FAILED`) from codec bodies pass through unchanged (no double wrap).
950
+ */
951
+ async function decodeRow(row, decodeCtx, rowCtx, listDecoder) {
952
+ checkAborted(rowCtx, "decode");
953
+ const signal = rowCtx.signal;
954
+ const aliases = decodeCtx.aliases ?? Object.keys(row);
955
+ if (decodeCtx.aliases !== void 0) {
956
+ for (const alias of decodeCtx.aliases) if (!Object.hasOwn(row, alias)) throw decodeCtx.aliasSource === "row-spec" ? runtimeError$1("RUNTIME.RAW_ROW_COLUMN_MISSING", `Raw statement result has no column "${alias}", which its row spec declares`, {
957
+ column: alias,
958
+ declaredColumns: decodeCtx.aliases,
959
+ resultColumns: Object.keys(row)
960
+ }) : runtimeError$1("RUNTIME.DECODE_FAILED", `Row missing projection alias "${alias}"`, {
961
+ alias,
962
+ expectedAliases: decodeCtx.aliases,
963
+ presentKeys: Object.keys(row)
964
+ });
965
+ }
966
+ const tasks = [];
967
+ const includeIndices = [];
968
+ for (let i = 0; i < aliases.length; i++) {
969
+ const alias = blindCast(aliases[i]);
970
+ const wireValue = row[alias];
971
+ if (decodeCtx.includeAliases.has(alias)) {
972
+ includeIndices.push({
973
+ index: i,
974
+ alias,
975
+ value: wireValue
976
+ });
977
+ tasks.push(Promise.resolve(void 0));
978
+ continue;
979
+ }
980
+ tasks.push(decodeField(alias, wireValue, decodeCtx, rowCtx, listDecoder));
981
+ }
982
+ const settled = await raceAgainstAbort(Promise.all(tasks), signal, "decode");
983
+ for (const entry of includeIndices) settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);
984
+ const decoded = {};
985
+ for (let i = 0; i < aliases.length; i++) {
986
+ const alias = blindCast(aliases[i]);
987
+ decoded[alias] = settled[i];
988
+ }
989
+ return decoded;
990
+ }
991
+ /**
992
+ * Computes a stable content hash for a lowered SQL execution plan.
993
+ *
994
+ * Internally builds an unambiguous canonical-stringified preimage from
995
+ * three components:
996
+ *
997
+ * 1. `meta.storageHash` — discriminates by schema. A migration changes the
998
+ * storage hash, which invalidates cached entries automatically.
999
+ * 2. `exec.sql` — the raw lowered SQL text. Two queries with different
1000
+ * structure produce different keys. Note that we deliberately do **not**
1001
+ * use `computeSqlFingerprint` here: that helper strips literals to group
1002
+ * executions by statement shape (used by telemetry), which is the
1003
+ * opposite of what a content hash needs — we want per-execution
1004
+ * discrimination, not per-statement-shape grouping.
1005
+ * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a
1006
+ * deterministic serialization that is stable across object key
1007
+ * insertion order and that distinguishes types JSON would otherwise
1008
+ * conflate (e.g. `BigInt(1)` vs `1`).
1009
+ *
1010
+ * The components are wrapped in an object and canonicalized as a single
1011
+ * unit (rather than concatenated with a delimiter) so component
1012
+ * boundaries are unambiguous: any character appearing inside `sql` or
1013
+ * `storageHash` cannot bleed across components and produce a collision
1014
+ * with a different split of the same characters.
1015
+ *
1016
+ * The canonical string is then piped through `hashContent` to produce a
1017
+ * bounded, opaque digest. See `@internal/utils/hash-content` for the
1018
+ * rationale.
1019
+ *
1020
+ * @internal
1021
+ */
1022
+ function computeSqlContentHash(exec) {
1023
+ return hashContent(canonicalStringify({
1024
+ storageHash: exec.meta.storageHash,
1025
+ sql: exec.sql,
1026
+ params: exec.params
1027
+ }));
1028
+ }
1029
+ const STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;
1030
+ const NUMERIC_LITERAL_REGEX = /\b\d+(?:\.\d+)?\b/g;
1031
+ const WHITESPACE_REGEX = /\s+/g;
1032
+ /**
1033
+ * Computes a literal-stripped, normalized fingerprint of a SQL statement.
1034
+ *
1035
+ * The function strips string and numeric literals, collapses whitespace, and
1036
+ * lowercases the result before hashing — so two structurally equivalent
1037
+ * statements (with different parameter values) produce the same fingerprint.
1038
+ * Used by SQL telemetry to group queries.
1039
+ */
1040
+ function computeSqlFingerprint(sql) {
1041
+ const normalized = sql.replace(STRING_LITERAL_REGEX, "?").replace(NUMERIC_LITERAL_REGEX, "?").replace(WHITESPACE_REGEX, " ").trim().toLowerCase();
1042
+ return createHash("sha256").update(normalized).digest("hex");
1043
+ }
1044
+ var InFlightOperations = class {
1045
+ #count = 0;
1046
+ #started = 0;
1047
+ #drainWaiters = [];
1048
+ /** Records one operation as in flight; the returned callback ends it and ignores later calls. */
1049
+ begin() {
1050
+ this.#count += 1;
1051
+ this.#started += 1;
1052
+ let ended = false;
1053
+ return () => {
1054
+ if (ended) return;
1055
+ ended = true;
1056
+ this.#count -= 1;
1057
+ if (this.#count === 0) for (const wake of this.#drainWaiters.splice(0)) wake();
1058
+ };
1059
+ }
1060
+ /** How many operations have begun so far; a change between two reads means work started in between. */
1061
+ get started() {
1062
+ return this.#started;
1063
+ }
1064
+ /** How many operations are in flight. */
1065
+ get count() {
1066
+ return this.#count;
1067
+ }
1068
+ get active() {
1069
+ return this.#count > 0;
1070
+ }
1071
+ drained() {
1072
+ if (this.#count === 0) return Promise.resolve();
1073
+ return new Promise((resolve) => this.#drainWaiters.push(resolve));
1074
+ }
1075
+ /** Records `work` as in flight until it settles. */
1076
+ async track(work) {
1077
+ const end = this.begin();
1078
+ try {
1079
+ return await work();
1080
+ } finally {
1081
+ end();
1082
+ }
1083
+ }
1084
+ };
1085
+ async function runBeforeCompileChain(middleware, initial, ctx) {
1086
+ let current = initial;
1087
+ for (const mw of middleware) {
1088
+ if (!mw.beforeCompile) continue;
1089
+ const result = await mw.beforeCompile(current, ctx);
1090
+ if (result === void 0) continue;
1091
+ if (result.ast === current.ast) continue;
1092
+ ctx.log.debug?.({
1093
+ event: "middleware.rewrite",
1094
+ middleware: mw.name,
1095
+ lane: current.meta.lane
1096
+ });
1097
+ current = result;
1098
+ }
1099
+ return current;
1100
+ }
1101
+ /**
1102
+ * Begins a transaction on a connection the transaction owns. The connection is released once the transaction has committed or rolled back, and destroyed after a failed rollback or a failed start other than a refusal before `BEGIN`. After a failed commit it stays held for the rollback that follows. A release that fails after the transaction settled is passed to `log.error`, and `commit()` or `rollback()` keeps its own outcome.
1103
+ */
1104
+ async function beginOwnedTransaction(connection, begin, log) {
1105
+ let transaction;
1106
+ try {
1107
+ transaction = await begin();
1108
+ } catch (error) {
1109
+ if (wasRefusedBeforeBegin(connection)) await connection.release().catch(() => void 0);
1110
+ else await connection.destroy(error).catch(() => void 0);
1111
+ throw error;
1112
+ }
1113
+ let disposed = false;
1114
+ const dispose = async (destroyReason) => {
1115
+ if (disposed) return;
1116
+ disposed = true;
1117
+ if (destroyReason !== void 0) {
1118
+ await connection.destroy(destroyReason.reason).catch(() => void 0);
1119
+ return;
1120
+ }
1121
+ try {
1122
+ await connection.release();
1123
+ } catch (error) {
1124
+ try {
1125
+ log.error({
1126
+ event: "runtime.connection.release.error",
1127
+ error
1128
+ });
1129
+ } catch {}
1130
+ }
1131
+ };
1132
+ return Object.assign(castAs(Object.create(transaction)), {
1133
+ async commit() {
1134
+ try {
1135
+ await transaction.commit();
1136
+ } catch (error) {
1137
+ if (settlementOf(transaction)?.committed === true) await dispose();
1138
+ throw error;
1139
+ }
1140
+ await dispose();
1141
+ },
1142
+ async rollback() {
1143
+ try {
1144
+ await transaction.rollback();
1145
+ } catch (error) {
1146
+ const settlement = settlementOf(transaction);
1147
+ const settled = settlement?.rolledBack === true || settlement?.committed === true;
1148
+ await dispose(settled ? void 0 : { reason: error });
1149
+ throw error;
1150
+ }
1151
+ await dispose();
1152
+ }
1153
+ });
1154
+ }
1155
+ function normalizeSpec(spec) {
1156
+ if (typeof spec === "string") return {
1157
+ codec: { codecId: spec },
1158
+ nullable: false
1159
+ };
1160
+ return {
1161
+ codec: spec.typeParams !== void 0 ? {
1162
+ codecId: spec.codecId,
1163
+ typeParams: spec.typeParams
1164
+ } : { codecId: spec.codecId },
1165
+ nullable: spec.nullable === true
1166
+ };
1167
+ }
1168
+ var BindSiteExpression = class {
1169
+ returnType;
1170
+ #ast;
1171
+ constructor(ref, returnType) {
1172
+ this.#ast = ref;
1173
+ this.returnType = returnType;
1174
+ }
1175
+ buildAst() {
1176
+ return this.#ast;
1177
+ }
1178
+ };
1179
+ function buildBindSiteParams(declaration) {
1180
+ const params = {};
1181
+ for (const [name, spec] of Object.entries(declaration)) {
1182
+ const { codec, nullable } = normalizeSpec(spec);
1183
+ params[name] = new BindSiteExpression(PreparedParamRef.of(name, codec, nullable), {
1184
+ codecId: codec.codecId,
1185
+ nullable
1186
+ });
1187
+ }
1188
+ return blindCast(Object.freeze(params));
1189
+ }
1190
+ /**
1191
+ * Resolve a PreparedStatement's slot order to the unencoded values it
1192
+ * will carry into encode. Literal slots come from the lowered AST;
1193
+ * bind slots are looked up by name on `userParams`. Missing user params
1194
+ * surface `RUNTIME.PREPARE_MISSING_PARAM` so the caller cannot silently
1195
+ * bind `undefined`.
1196
+ */
1197
+ function isRecord(value) {
1198
+ return typeof value === "object" && value !== null;
1199
+ }
1200
+ function resolvePreparedSlotValues(ps, userParams) {
1201
+ if (!isRecord(userParams)) throw runtimeError$1("RUNTIME.PREPARE_MISSING_PARAM", "Prepared statement parameters must be an object");
1202
+ return ps.slots.map((slot) => {
1203
+ if (slot.kind === "literal") return slot.value;
1204
+ if (!Object.hasOwn(userParams, slot.name)) throw runtimeError$1("RUNTIME.PREPARE_MISSING_PARAM", `Prepared statement query is missing parameter '${slot.name}'`, { name: slot.name });
1205
+ return userParams[slot.name];
1206
+ });
1207
+ }
1208
+ async function encodePreparedParams(ps, userParams, ctx, contractCodecs) {
1209
+ return encodeParamsWithMetadata(resolvePreparedSlotValues(ps, userParams), ps.paramMetadata, ctx, contractCodecs);
1210
+ }
1211
+ var SqlFamilyAdapter = class {
1212
+ contract;
1213
+ markerReader;
1214
+ constructor(contract, adapterProfile) {
1215
+ this.contract = contract;
1216
+ this.markerReader = adapterProfile;
1217
+ }
1218
+ validatePlan(plan, contract) {
1219
+ validateSqlPlan(plan, contract);
1220
+ }
1221
+ };
1222
+ /** Rejects a plan built for another target or contract: `PLAN.TARGET_MISMATCH` or `PLAN.HASH_MISMATCH`. */
1223
+ function validateSqlPlan(plan, contract) {
1224
+ if (plan.meta.target !== contract.target) throw runtimeError$1("PLAN.TARGET_MISMATCH", "The plan was built for another target than the contract", {
1225
+ planTarget: plan.meta.target,
1226
+ contractTarget: contract.target
1227
+ });
1228
+ if (plan.meta.storageHash !== contract.storage.storageHash) throw runtimeError$1("PLAN.HASH_MISMATCH", "The plan was built for another contract", {
1229
+ planStorageHash: plan.meta.storageHash,
1230
+ contractStorageHash: contract.storage.storageHash
1231
+ });
1232
+ }
1233
+ function isExecutionPlan(plan) {
1234
+ return "sql" in plan;
1235
+ }
1236
+ function isBoundPreparedStatement(subject) {
1237
+ return "statement" in subject;
1238
+ }
1239
+ function isPreparedStatementInternals(statement) {
1240
+ return statement instanceof PreparedStatementImpl || statement instanceof PreparedExecutionImpl;
1241
+ }
1242
+ // v8 ignore next 2
1243
+ const noopLogSink = () => {};
1244
+ const noopLog = {
1245
+ info: noopLogSink,
1246
+ warn: noopLogSink,
1247
+ error: noopLogSink
1248
+ };
1249
+ const scheduleTimer = globalThis.setTimeout;
1250
+ function runtimeClosedError() {
1251
+ return structuredError("DRIVER.NOT_CONNECTED", "Runtime is closed", {
1252
+ why: "close() was called on this runtime, or on the client or connection that owns it. An await using scope calls close() when it ends.",
1253
+ fix: "Await every query, transaction and prepared statement before close(). The usual cause is a query returned without await from an await using scope."
1254
+ });
1255
+ }
1256
+ /**
1257
+ * Abstract family-layer base for SQL runtimes. Subclass to build a target runtime
1258
+ * (e.g. `PostgresRuntimeImpl`); app code should consume the `Runtime` interface returned
1259
+ * by the target factories, never this class directly.
1260
+ */
1261
+ var SqlRuntimeBase = class extends RuntimeCore {
1262
+ contract;
1263
+ adapter;
1264
+ driver;
1265
+ familyAdapter;
1266
+ contractCodecs;
1267
+ codecDescriptors;
1268
+ sqlCtx;
1269
+ verifyMarkerOption;
1270
+ verifyMarkerPromise;
1271
+ closePromise;
1272
+ ownsDriver;
1273
+ closeRefusal;
1274
+ #inFlight = new InFlightOperations();
1275
+ #openTransactionWork = new InFlightOperations();
1276
+ #transactionWorkOn = /* @__PURE__ */ new WeakMap();
1277
+ #openActivityHandles = 0;
1278
+ #refusing = false;
1279
+ #heldQueryables = /* @__PURE__ */ new WeakSet();
1280
+ #preparedStatementHandles = /* @__PURE__ */ new WeakMap();
1281
+ #holdFinishedChildren;
1282
+ #openTransactions = /* @__PURE__ */ new WeakMap();
1283
+ codecRegistryValidated;
1284
+ _telemetry;
1285
+ constructor(options) {
1286
+ const { context, adapter, driver, verifyMarker, middleware, mode, log, closeRefusal, ownsDriver } = options;
1287
+ if (middleware) for (const mw of middleware) checkMiddlewareCompatibility(mw, "sql", context.contract.target);
1288
+ const sqlCtx = {
1289
+ contract: context.contract,
1290
+ mode: mode ?? "strict",
1291
+ now: () => Date.now(),
1292
+ log: log ?? noopLog,
1293
+ contentHash: (exec) => computeSqlContentHash(blindCast(exec)),
1294
+ scope: "runtime"
1295
+ };
1296
+ super({
1297
+ middleware: middleware ?? [],
1298
+ ctx: sqlCtx
1299
+ });
1300
+ this.#holdFinishedChildren = this.middleware.some((mw) => mw.activityFinalized !== void 0);
1301
+ this.contract = context.contract;
1302
+ this.adapter = adapter;
1303
+ this.driver = driver;
1304
+ this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);
1305
+ this.contractCodecs = context.contractCodecs;
1306
+ this.codecDescriptors = context.codecDescriptors;
1307
+ this.sqlCtx = sqlCtx;
1308
+ this.verifyMarkerOption = verifyMarker ?? "onFirstUse";
1309
+ this.closeRefusal = closeRefusal ?? "when-idle";
1310
+ this.codecRegistryValidated = false;
1311
+ this.verifyMarkerPromise = this.verifyMarkerOption === false ? Promise.resolve() : null;
1312
+ this.closePromise = null;
1313
+ this.ownsDriver = ownsDriver ?? true;
1314
+ this._telemetry = null;
1315
+ }
1316
+ /**
1317
+ * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan`
1318
+ * with encoded parameters ready for the driver.
1319
+ *
1320
+ * Implementation note: SQL splits lower-then-encode across
1321
+ * {@link lowerToDraft} + {@link encodeDraftParams} so the selected
1322
+ * operation's middleware chain can run between them:
1323
+ * {@link prepareOperation} runs the statement's `beforeEncode` chain
1324
+ * between them (cipherstash bulk-encrypt, for example, mutates pre-encode
1325
+ * `ParamRef.value` slots). This protected hook composes the two back into
1326
+ * the cross-family `lower()` shape `RuntimeCore` expects. The production
1327
+ * operation methods use the matching split form before driver execution.
1328
+ *
1329
+ * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so
1330
+ * per-query cancellation reaches every codec body during parameter
1331
+ * encoding. SQL params do not populate `ctx.column` — encode-side
1332
+ * column metadata is the middleware's domain.
1333
+ */
1334
+ async lower(plan, ctx) {
1335
+ const draft = this.lowerToDraft(plan);
1336
+ return await this.encodeDraftParams(draft, ctx);
1337
+ }
1338
+ /**
1339
+ * AST → pre-encode draft for the selected `query()` or `execute()` operation.
1340
+ * The returned plan has `sql` rendered and `params` populated with the
1341
+ * user-domain values the lowering site collected from `ParamRef` nodes. No
1342
+ * codec encode has happened yet; consumers can mutate `params` via the
1343
+ * `SqlParamRefMutator` before {@link encodeDraftParams} runs.
1344
+ */
1345
+ lowerToDraft(plan) {
1346
+ return lowerSqlPlan(this.adapter, this.contract, plan);
1347
+ }
1348
+ /**
1349
+ * Encode a draft plan's params for the selected `query()` or `execute()`
1350
+ * operation through the per-column codecs and freeze the result into the
1351
+ * final `SqlExecutionPlan` the driver sees. Errors surface as
1352
+ * `RUNTIME.ENCODE_FAILED` envelopes from {@link encodeParams}.
1353
+ */
1354
+ async encodeDraftParams(draft, ctx) {
1355
+ return Object.freeze({
1356
+ ...draft,
1357
+ params: await encodeParams(draft, ctx, this.contractCodecs)
1358
+ });
1359
+ }
1360
+ /** Default query invocation required by the abstract `RuntimeCore` contract. */
1361
+ // v8 ignore next 6
1362
+ runDriver(exec) {
1363
+ return this.driver.query({
1364
+ sql: exec.sql,
1365
+ params: exec.params
1366
+ });
1367
+ }
1368
+ runExecute(exec) {
1369
+ return this.driver.execute({
1370
+ sql: exec.sql,
1371
+ params: exec.params
1372
+ });
1373
+ }
1374
+ /**
1375
+ * Runs the registered middleware `beforeCompile` chain over the plan's draft (AST + meta). Returns the original plan unchanged when no middleware rewrote the AST; otherwise returns a new plan carrying the rewritten AST and meta. The lowering adapter and the encoder both walk the rewritten AST directly.
1376
+ */
1377
+ async compilePlan(plan, middlewareCtx) {
1378
+ const rewrittenDraft = await runBeforeCompileChain(this.middleware, {
1379
+ ast: plan.ast,
1380
+ meta: plan.meta
1381
+ }, middlewareCtx);
1382
+ return rewrittenDraft.ast === plan.ast ? plan : {
1383
+ ...plan,
1384
+ ast: rewrittenDraft.ast,
1385
+ meta: rewrittenDraft.meta
1386
+ };
1387
+ }
1388
+ query(plan, options) {
1389
+ return this.queryAgainstQueryable(plan, this.driver, options);
1390
+ }
1391
+ execute(plan, options) {
1392
+ return this.executeStatisticsAgainstQueryable(plan, this.driver, options);
1393
+ }
1394
+ [preparedStatementQuery](ps, params, options) {
1395
+ return this.runPreparedQueryAgainstQueryable(blindCast(ps), params, this.driver, options);
1396
+ }
1397
+ [preparedStatementExecute](ps, params, options) {
1398
+ return this.runPreparedExecuteAgainstQueryable(blindCast(ps), params, this.driver, options);
1399
+ }
1400
+ #runtimeRoute;
1401
+ [activitySource] = {
1402
+ startActivity: (activity) => {
1403
+ this.#runtimeRoute ??= this.queryableRoute(this.driver, "runtime", () => void 0, {
1404
+ transaction: (parent) => this.beginOwnedTransactionBeneath(parent),
1405
+ runtimeWork: true
1406
+ });
1407
+ return this.startActivityOnRoute(this.#runtimeRoute, activity, void 0);
1408
+ },
1409
+ planContentHash: (plan) => this.planContentHashFor(plan, "runtime", void 0)
1410
+ };
1411
+ /**
1412
+ * Starts a client activity whose statements and transaction run on `route`, beneath `parent` or, without one, beneath `route.parent()`.
1413
+ */
1414
+ startActivityOnRoute(route, activity, parent) {
1415
+ let endWork = noWork;
1416
+ let started;
1417
+ try {
1418
+ endWork = route.runtimeWork ? this.beginActivityWork(parent) : noWork;
1419
+ started = startClientActivity(activity, {
1420
+ middleware: this.middleware,
1421
+ context: route.scope === "runtime" ? this.sqlCtx : {
1422
+ ...this.sqlCtx,
1423
+ scope: route.scope
1424
+ },
1425
+ parent: parent ?? route.parent(),
1426
+ holdFinishedChildren: this.#holdFinishedChildren
1427
+ });
1428
+ } catch (error) {
1429
+ endWork();
1430
+ return Promise.reject(error);
1431
+ }
1432
+ return started.then((run) => this.activityHandle(run, route, endWork), (error) => {
1433
+ endWork();
1434
+ throw error;
1435
+ });
1436
+ }
1437
+ /** The content hash of the statement `plan` would send on a queryable of `scope` beneath `parent`. */
1438
+ async planContentHashFor(plan, scope, parent) {
1439
+ this.ensureCodecRegistryValidated();
1440
+ if (isBoundPreparedStatement(plan)) {
1441
+ const { statement, params } = plan;
1442
+ invariant(isPreparedStatementInternals(statement), "The prepared statement was not prepared by a SQL runtime");
1443
+ return computeSqlContentHash({
1444
+ sql: statement.sql,
1445
+ ast: statement.ast,
1446
+ meta: statement.meta,
1447
+ params: await encodePreparedParams(statement, params, {}, this.contractCodecs)
1448
+ });
1449
+ }
1450
+ if (isExecutionPlan(plan)) return computeSqlContentHash(Object.freeze({
1451
+ ...plan,
1452
+ params: await encodeParams(plan, {}, this.contractCodecs)
1453
+ }));
1454
+ const compiled = await this.compilePlan(plan, createContextBeneath({
1455
+ ...this.sqlCtx,
1456
+ scope
1457
+ }, parent));
1458
+ return computeSqlContentHash(await this.encodeDraftParams(this.lowerToDraft(compiled), {}));
1459
+ }
1460
+ /** An activity route whose statements run on `queryable`. */
1461
+ queryableRoute(queryable, scope, parent, options) {
1462
+ return {
1463
+ scope,
1464
+ parent,
1465
+ ...options,
1466
+ query: (plan, executeOptions) => this.queryAgainstQueryable(plan, queryable, {
1467
+ ...executeOptions,
1468
+ scope
1469
+ }),
1470
+ execute: (plan, executeOptions) => this.executeStatisticsAgainstQueryable(plan, queryable, {
1471
+ ...executeOptions,
1472
+ scope
1473
+ }),
1474
+ preparedQuery: (statement, params, executeOptions) => this.runPreparedQueryAgainstQueryable(statement, params, queryable, {
1475
+ ...executeOptions,
1476
+ scope
1477
+ }),
1478
+ preparedExecute: (statement, params, executeOptions) => this.runPreparedExecuteAgainstQueryable(statement, params, queryable, {
1479
+ ...executeOptions,
1480
+ scope
1481
+ })
1482
+ };
1483
+ }
1484
+ /** The activity route of a held connection that `owner` wraps: its statements run on `connection`, and its transactions begin there. */
1485
+ connectionRoute(connection, owner) {
1486
+ const openTransaction = this.#openTransactions.get(connection);
1487
+ return this.queryableRoute(connection, "connection", () => openTransaction, {
1488
+ transaction: openTransaction === void 0 ? (parent) => this.beginTransactionBeneathOn(connection, owner, parent) : void 0,
1489
+ runtimeWork: false
1490
+ });
1491
+ }
1492
+ beginTransactionBeneathOn(connection, owner, parent) {
1493
+ const openTransaction = this.#openTransactions.get(connection);
1494
+ if (openTransaction !== void 0) return Promise.reject(transactionAlreadyOpenError(parent, openTransaction));
1495
+ return this.beginTransactionOn(connection, owner, parent);
1496
+ }
1497
+ /** The `activitySource` member of a held connection that `owner()` wraps. */
1498
+ connectionActivitySource(connection, owner) {
1499
+ return {
1500
+ startActivity: (activity) => this.startActivityOnRoute(this.connectionRoute(connection, owner()), activity, void 0),
1501
+ planContentHash: (plan) => this.planContentHashFor(plan, "connection", this.#openTransactions.get(connection))
1502
+ };
1503
+ }
1504
+ activityHandle(run, route, endWork) {
1505
+ const beneath = (options) => ({
1506
+ ...options,
1507
+ activityParent: run
1508
+ });
1509
+ const source = {
1510
+ startActivity: (activity) => {
1511
+ try {
1512
+ run.assertAcceptsChildren();
1513
+ } catch (error) {
1514
+ return Promise.reject(error);
1515
+ }
1516
+ return this.startActivityOnRoute(route, activity, run);
1517
+ },
1518
+ planContentHash: (plan) => this.planContentHashFor(plan, route.scope, run)
1519
+ };
1520
+ const handle = {
1521
+ [activitySource]: source,
1522
+ startActivity: source.startActivity,
1523
+ planContentHash: source.planContentHash,
1524
+ activity: run.activity,
1525
+ get intercepted() {
1526
+ return run.intercepted;
1527
+ },
1528
+ query(plan, options) {
1529
+ return rowsBeneath(run, () => route.query(plan, beneath(options)));
1530
+ },
1531
+ async execute(plan, options) {
1532
+ run.assertAcceptsChildren();
1533
+ return route.execute(plan, beneath(options));
1534
+ },
1535
+ [preparedStatementQuery](ps, params, options) {
1536
+ return rowsBeneath(run, () => route.preparedQuery(blindCast(ps), params, beneath(options)));
1537
+ },
1538
+ async [preparedStatementExecute](ps, params, options) {
1539
+ run.assertAcceptsChildren();
1540
+ return route.preparedExecute(blindCast(ps), params, beneath(options));
1541
+ },
1542
+ end(end) {
1543
+ let ending;
1544
+ try {
1545
+ ending = run.end(end);
1546
+ } catch (error) {
1547
+ endWork();
1548
+ return Promise.reject(error);
1549
+ }
1550
+ return ending.then(endWork, (error) => {
1551
+ endWork();
1552
+ throw error;
1553
+ });
1554
+ }
1555
+ };
1556
+ const beginTransaction = route.transaction;
1557
+ if (beginTransaction === void 0) return handle;
1558
+ return Object.assign(handle, { transaction: async () => {
1559
+ run.assertAcceptsChildren();
1560
+ return beginTransaction(run);
1561
+ } });
1562
+ }
1563
+ async beginOwnedTransactionBeneath(parent) {
1564
+ const { driverConnection, connection } = await this.openConnection({ activityParent: parent });
1565
+ return this.ownTransaction(connection, () => this.beginTransactionOn(driverConnection, connection, parent));
1566
+ }
1567
+ /** Begins a transaction with `begin` on a connection the transaction owns; see `beginOwnedTransaction`. */
1568
+ ownTransaction(connection, begin) {
1569
+ return beginOwnedTransaction(connection, begin, this.sqlCtx.log);
1570
+ }
1571
+ /**
1572
+ * Returns a raw driver connection. SQL issued on it runs below the middleware/codec/telemetry pipeline. It carries its own lifecycle (`release`/`destroy`/`beginTransaction`); the caller owns disposal. It follows the runtime's close rule for connections: see {@link Runtime.close}. Pass the `activityParent` of the activity it is acquired for, so it is admitted after `close()` while that activity is open.
1573
+ */
1574
+ async acquireRawConnection(options) {
1575
+ const endOperation = this.beginOperation(this.driver, options);
1576
+ let connection;
1577
+ try {
1578
+ connection = await this.driver.acquireConnection();
1579
+ } finally {
1580
+ endOperation();
1581
+ }
1582
+ const dispose = async (teardown) => {
1583
+ try {
1584
+ await this.#inFlight.track(teardown);
1585
+ } finally {
1586
+ this.#transactionWorkOn.get(held)?.();
1587
+ }
1588
+ };
1589
+ const held = {
1590
+ query: (request) => this.trackRows(connection.query(request)),
1591
+ execute: (request) => this.#inFlight.track(() => connection.execute(request)),
1592
+ beginTransaction: () => connection.beginTransaction(),
1593
+ ...ifDefined("explain", connection.explain?.bind(connection)),
1594
+ release: () => dispose(() => connection.release()),
1595
+ destroy: (reason) => dispose(() => connection.destroy(reason))
1596
+ };
1597
+ return held;
1598
+ }
1599
+ async *trackRows(rows) {
1600
+ const iterator = rows[Symbol.asyncIterator]();
1601
+ try {
1602
+ let next = await this.#inFlight.track(() => iterator.next());
1603
+ while (!next.done) {
1604
+ yield next.value;
1605
+ next = await iterator.next();
1606
+ }
1607
+ } finally {
1608
+ await iterator.return?.();
1609
+ }
1610
+ }
1611
+ async setupDriverExecution(exec, queryable) {
1612
+ this.familyAdapter.validatePlan(exec, this.contract);
1613
+ this._telemetry = null;
1614
+ if (this.verifyMarkerPromise === null) {
1615
+ const markerQueryable = this.#heldQueryables.has(queryable) ? queryable : this.driver;
1616
+ this.verifyMarkerPromise = this.verifyMarker(markerQueryable).catch((error) => {
1617
+ this.verifyMarkerPromise = null;
1618
+ throw error;
1619
+ });
1620
+ }
1621
+ await this.verifyMarkerPromise;
1622
+ }
1623
+ beginActivityWork(parent) {
1624
+ const endOperation = this.beginOperation(this.driver, { activityParent: parent });
1625
+ this.#openActivityHandles++;
1626
+ let ended = false;
1627
+ return () => {
1628
+ if (ended) return;
1629
+ ended = true;
1630
+ this.#openActivityHandles--;
1631
+ endOperation();
1632
+ };
1633
+ }
1634
+ warnWhenWaitingOnlyForUnendedWork(warned) {
1635
+ const openTransactions = this.#refusing ? this.#openTransactionWork.count : 0;
1636
+ if (warned.done || this.#openActivityHandles === 0 && openTransactions === 0) return;
1637
+ if (this.#inFlight.count !== this.#openActivityHandles) return;
1638
+ warned.done = true;
1639
+ this.sqlCtx.log.warn({
1640
+ event: "runtime.close.waiting-for-activities",
1641
+ openActivities: this.#openActivityHandles,
1642
+ openTransactions
1643
+ });
1644
+ }
1645
+ beginOperation(queryable, options) {
1646
+ const admittedParent = options?.activityParent?.acceptsChildren() === true;
1647
+ if (queryable === this.driver && this.#refusing && !admittedParent) throw runtimeClosedError();
1648
+ return this.#inFlight.begin();
1649
+ }
1650
+ parentOf(queryable, options) {
1651
+ const openTransaction = this.#openTransactions.get(queryable);
1652
+ const activityParent = options?.activityParent;
1653
+ if (activityParent === void 0) return openTransaction;
1654
+ if (openTransaction !== void 0 && !activityParent.ctx.inTransaction()) throw activityOutsideTransactionError(activityParent, openTransaction);
1655
+ return activityParent;
1656
+ }
1657
+ getListDecoder() {
1658
+ return sqlNativeArrayListDecoder;
1659
+ }
1660
+ async *streamDecodedRows(run, exec, createDecodeContext, driverCall, codecCtx, queryable, onDriverAnswered) {
1661
+ const rowDecodeContext = createDecodeContext();
1662
+ await this.setupDriverExecution(exec, queryable);
1663
+ const startedAt = Date.now();
1664
+ let telemetryOutcome = null;
1665
+ try {
1666
+ const iterator = run.runQuery(exec, driverCall)[Symbol.asyncIterator]();
1667
+ let answered = false;
1668
+ try {
1669
+ while (true) {
1670
+ checkAborted(codecCtx, "stream");
1671
+ const next = answered ? await iterator.next() : await iterator.next().finally(onDriverAnswered);
1672
+ answered = true;
1673
+ if (next.done) break;
1674
+ yield blindCast(await decodeRow(next.value, rowDecodeContext, codecCtx, this.getListDecoder()));
1675
+ }
1676
+ } finally {
1677
+ await iterator.return?.();
1678
+ }
1679
+ telemetryOutcome = "success";
1680
+ } catch (error) {
1681
+ telemetryOutcome = "runtime-error";
1682
+ throw error;
1683
+ } finally {
1684
+ if (telemetryOutcome !== null) this.recordTelemetry(exec, telemetryOutcome, Date.now() - startedAt);
1685
+ }
1686
+ }
1687
+ createQueryContexts(options) {
1688
+ const signal = options?.signal;
1689
+ const scope = options?.scope ?? "runtime";
1690
+ return {
1691
+ codecCtx: signal === void 0 ? {} : { signal },
1692
+ contextFields: {
1693
+ ...this.sqlCtx,
1694
+ ...ifDefined("signal", signal),
1695
+ ...scope !== "runtime" ? { scope } : {}
1696
+ }
1697
+ };
1698
+ }
1699
+ async prepareOperation(plan, codecCtx, run) {
1700
+ checkAborted(codecCtx, "stream");
1701
+ if (isExecutionPlan(plan)) {
1702
+ const mutator = createSqlParamRefMutator(plan);
1703
+ await run.beforeEncode(plan, mutator);
1704
+ return Object.freeze({
1705
+ ...plan,
1706
+ params: await encodeParams({
1707
+ ...plan,
1708
+ params: mutator.currentParams()
1709
+ }, codecCtx, this.contractCodecs)
1710
+ });
1711
+ }
1712
+ const compiled = await this.compilePlan(plan, run.ctx);
1713
+ const draft = this.lowerToDraft(compiled);
1714
+ const mutator = createSqlParamRefMutator(draft);
1715
+ await run.beforeEncode(draft, mutator);
1716
+ const draftWithMutations = Object.freeze({
1717
+ ...draft,
1718
+ params: mutator.currentParams()
1719
+ });
1720
+ return this.encodeDraftParams(draftWithMutations, codecCtx);
1721
+ }
1722
+ /** Query rows against a caller-supplied queryable through the shared preparation pipeline. */
1723
+ queryAgainstQueryable(plan, queryable, options) {
1724
+ this.ensureCodecRegistryValidated();
1725
+ const self = this;
1726
+ const { codecCtx, contextFields } = this.createQueryContexts(options);
1727
+ const generator = async function* () {
1728
+ const endOperation = self.beginOperation(queryable, options);
1729
+ try {
1730
+ yield* streamStatement({
1731
+ middleware: self.middleware,
1732
+ plan,
1733
+ context: contextFields,
1734
+ parent: self.parentOf(queryable, options)
1735
+ }, async function* (run) {
1736
+ const exec = await self.prepareOperation(plan, codecCtx, run);
1737
+ yield* self.streamDecodedRows(run, exec, () => buildDecodeContext(exec.ast, self.contractCodecs), () => queryable.query({
1738
+ sql: exec.sql,
1739
+ params: exec.params
1740
+ }), codecCtx, queryable, endOperation);
1741
+ });
1742
+ } finally {
1743
+ endOperation();
1744
+ }
1745
+ };
1746
+ return new AsyncIterableResult(generator());
1747
+ }
1748
+ /** Execute statistics against a caller-supplied queryable through the shared preparation pipeline. */
1749
+ async executeStatisticsAgainstQueryable(plan, queryable, options) {
1750
+ const endOperation = this.beginOperation(queryable, options);
1751
+ try {
1752
+ return await this.executeStatisticsInFlight(plan, queryable, options);
1753
+ } finally {
1754
+ endOperation();
1755
+ }
1756
+ }
1757
+ async executeStatisticsInFlight(plan, queryable, options) {
1758
+ this.ensureCodecRegistryValidated();
1759
+ const { codecCtx, contextFields } = this.createQueryContexts(options);
1760
+ return this.executeOn(queryable, options, plan, contextFields, async (run) => {
1761
+ const exec = await this.prepareOperation(plan, codecCtx, run);
1762
+ return this.executeEncodedPlan(run, exec, queryable, codecCtx, () => queryable.execute({
1763
+ sql: exec.sql,
1764
+ params: exec.params
1765
+ }));
1766
+ });
1767
+ }
1768
+ executeOn(queryable, options, plan, context, body) {
1769
+ return executeStatement({
1770
+ middleware: this.middleware,
1771
+ plan,
1772
+ context,
1773
+ parent: this.parentOf(queryable, options)
1774
+ }, body);
1775
+ }
1776
+ async executeEncodedPlan(run, exec, queryable, codecCtx, driverCall) {
1777
+ await this.setupDriverExecution(exec, queryable);
1778
+ checkAborted(codecCtx, "stream");
1779
+ const startedAt = Date.now();
1780
+ let telemetryOutcome = "success";
1781
+ try {
1782
+ return await run.runExecute(exec, driverCall);
1783
+ } catch (error) {
1784
+ telemetryOutcome = "runtime-error";
1785
+ throw error;
1786
+ } finally {
1787
+ this.recordTelemetry(exec, telemetryOutcome, Date.now() - startedAt);
1788
+ }
1789
+ }
1790
+ async prepare(declaration, callback) {
1791
+ this.ensureCodecRegistryValidated();
1792
+ const userPlan = callback(buildBindSiteParams(declaration));
1793
+ const finalPlan = await this.compilePlan(userPlan, createContextBeneath(this.sqlCtx, void 0));
1794
+ const orderedRefs = collectOrderedParamRefs(finalPlan.ast);
1795
+ const referencedNames = /* @__PURE__ */ new Set();
1796
+ for (const ref of orderedRefs) if (ref.kind === "prepared-param-ref") referencedNames.add(ref.name);
1797
+ const missing = Object.keys(declaration).filter((name) => !referencedNames.has(name));
1798
+ if (missing.length > 0) throw runtimeError$1("RUNTIME.PREPARE_UNUSED_PARAM", `Prepared statement declaration includes parameter${missing.length === 1 ? "" : "s"} not referenced by the callback's plan: ${missing.join(", ")}`, { unused: missing });
1799
+ const lowered = this.adapter.lower(finalPlan.ast, {
1800
+ contract: this.contract,
1801
+ params: orderedRefs.map((r) => r.kind === "param-ref" ? r.value : void 0)
1802
+ });
1803
+ const decodeContext = buildDecodeContext(finalPlan.ast, this.contractCodecs);
1804
+ const paramMetadata = deriveParamMetadata(finalPlan.ast);
1805
+ const internals = Object.freeze({
1806
+ sql: lowered.sql,
1807
+ ast: finalPlan.ast,
1808
+ meta: finalPlan.meta,
1809
+ slots: lowered.params,
1810
+ decodeContext,
1811
+ paramMetadata
1812
+ });
1813
+ return blindCast(finalPlan.ast.kind === "raw-query" && finalPlan.ast.result.kind === "affected-count" ? new PreparedExecutionImpl(internals) : new PreparedStatementImpl(internals));
1814
+ }
1815
+ /** Query prepared rows against a caller-supplied queryable through the full pipeline. */
1816
+ runPreparedQueryAgainstQueryable(ps, userParams, queryable, options) {
1817
+ this.ensureCodecRegistryValidated();
1818
+ const self = this;
1819
+ const { codecCtx, contextFields } = this.createQueryContexts(options);
1820
+ const generator = async function* () {
1821
+ const endOperation = self.beginOperation(queryable, options);
1822
+ try {
1823
+ yield* streamStatement({
1824
+ middleware: self.middleware,
1825
+ plan: ps,
1826
+ context: contextFields,
1827
+ parent: self.parentOf(queryable, options)
1828
+ }, (run) => self.streamPreparedRows(run, ps, userParams, queryable, codecCtx, endOperation));
1829
+ } finally {
1830
+ endOperation();
1831
+ }
1832
+ };
1833
+ return new AsyncIterableResult(generator());
1834
+ }
1835
+ async *streamPreparedRows(run, ps, userParams, queryable, codecCtx, onDriverAnswered) {
1836
+ checkAborted(codecCtx, "stream");
1837
+ const preEncodeValues = resolvePreparedSlotValues(ps, userParams);
1838
+ const preEncodeExec = {
1839
+ sql: ps.sql,
1840
+ params: preEncodeValues,
1841
+ ast: ps.ast,
1842
+ meta: ps.meta
1843
+ };
1844
+ const mutator = createSqlParamRefMutator(preEncodeExec);
1845
+ await run.beforeEncode(preEncodeExec, mutator);
1846
+ const encodedParams = await encodeParamsWithMetadata(mutator.currentParams(), ps.paramMetadata, codecCtx, this.contractCodecs);
1847
+ const exec = {
1848
+ sql: ps.sql,
1849
+ params: encodedParams,
1850
+ ast: ps.ast,
1851
+ meta: ps.meta
1852
+ };
1853
+ const handles = this.#preparedStatementHandles;
1854
+ const request = {
1855
+ sql: exec.sql,
1856
+ params: exec.params,
1857
+ preparedStatementHandle: {
1858
+ get: () => handles.get(ps),
1859
+ set: (value) => {
1860
+ handles.set(ps, value);
1861
+ }
1862
+ }
1863
+ };
1864
+ yield* this.streamDecodedRows(run, exec, () => ps.decodeContext, () => queryable.query(request), codecCtx, queryable, onDriverAnswered);
1865
+ }
1866
+ /** Execute a prepared statement's statistics against a caller-supplied queryable through the full pipeline. */
1867
+ async runPreparedExecuteAgainstQueryable(ps, userParams, queryable, options) {
1868
+ const endOperation = this.beginOperation(queryable, options);
1869
+ try {
1870
+ return await this.runPreparedExecuteInFlight(ps, userParams, queryable, options);
1871
+ } finally {
1872
+ endOperation();
1873
+ }
1874
+ }
1875
+ async runPreparedExecuteInFlight(ps, userParams, queryable, options) {
1876
+ this.ensureCodecRegistryValidated();
1877
+ const { codecCtx, contextFields } = this.createQueryContexts(options);
1878
+ return this.executeOn(queryable, options, ps, contextFields, (run) => this.executePrepared(run, ps, userParams, queryable, codecCtx));
1879
+ }
1880
+ async executePrepared(run, ps, userParams, queryable, codecCtx) {
1881
+ checkAborted(codecCtx, "stream");
1882
+ const preEncodeValues = resolvePreparedSlotValues(ps, userParams);
1883
+ const preEncodeExec = {
1884
+ sql: ps.sql,
1885
+ params: preEncodeValues,
1886
+ ast: ps.ast,
1887
+ meta: ps.meta
1888
+ };
1889
+ const mutator = createSqlParamRefMutator(preEncodeExec);
1890
+ await run.beforeEncode(preEncodeExec, mutator);
1891
+ const exec = {
1892
+ sql: ps.sql,
1893
+ params: await encodeParamsWithMetadata(mutator.currentParams(), ps.paramMetadata, codecCtx, this.contractCodecs),
1894
+ ast: ps.ast,
1895
+ meta: ps.meta
1896
+ };
1897
+ const handles = this.#preparedStatementHandles;
1898
+ const request = {
1899
+ sql: exec.sql,
1900
+ params: exec.params,
1901
+ preparedStatementHandle: {
1902
+ get: () => handles.get(ps),
1903
+ set: (value) => {
1904
+ handles.set(ps, value);
1905
+ }
1906
+ }
1907
+ };
1908
+ return this.executeEncodedPlan(run, exec, queryable, codecCtx, () => queryable.execute(request));
1909
+ }
1910
+ async connection() {
1911
+ return (await this.openConnection()).connection;
1912
+ }
1913
+ async openConnection(options) {
1914
+ const driverConn = await this.acquireRawConnection(options);
1915
+ this.#heldQueryables.add(driverConn);
1916
+ const self = this;
1917
+ const wrappedConnection = {
1918
+ [transactionStart]: createTransactionStart(),
1919
+ transaction() {
1920
+ return self.beginTransactionOn(driverConn, wrappedConnection, void 0);
1921
+ },
1922
+ [activitySource]: self.connectionActivitySource(driverConn, () => wrappedConnection),
1923
+ release: () => driverConn.release(),
1924
+ destroy: (reason) => driverConn.destroy(reason),
1925
+ query(plan, options) {
1926
+ return self.queryAgainstQueryable(plan, driverConn, {
1927
+ ...options,
1928
+ scope: "connection"
1929
+ });
1930
+ },
1931
+ execute(plan, options) {
1932
+ return self.executeStatisticsAgainstQueryable(plan, driverConn, {
1933
+ ...options,
1934
+ scope: "connection"
1935
+ });
1936
+ },
1937
+ [preparedStatementQuery](ps, params, options) {
1938
+ return self.runPreparedQueryAgainstQueryable(blindCast(ps), params, driverConn, {
1939
+ ...options,
1940
+ scope: "connection"
1941
+ });
1942
+ },
1943
+ [preparedStatementExecute](ps, params, options) {
1944
+ return self.runPreparedExecuteAgainstQueryable(blindCast(ps), params, driverConn, {
1945
+ ...options,
1946
+ scope: "connection"
1947
+ });
1948
+ }
1949
+ };
1950
+ return {
1951
+ driverConnection: driverConn,
1952
+ connection: wrappedConnection
1953
+ };
1954
+ }
1955
+ /**
1956
+ * Begins a transaction on `connection`, which `owner` wraps, as a transaction activity. When the transaction's `activityStarted` hooks refuse the start, no `BEGIN` is sent, `owner` is recorded as clean, and `withTransaction` releases it; after any other start failure it destroys it. The transaction's `activityStarted` hooks run before `BEGIN`. Every statement sent on the transaction, or on `connection`, from the end of `BEGIN` until `commit()` or `rollback()` is called is the transaction's child, and is finalized when the transaction ends, with its outcome. `commit()` and `rollback()` resolve after every finalization hook has run. A subclass that holds its own connection begins its transactions here.
1957
+ */
1958
+ async beginTransactionOn(connection, owner, parent) {
1959
+ owner[transactionStart].refusedBeforeBegin = false;
1960
+ const endTransactionWork = this.#openTransactionWork.begin();
1961
+ this.#transactionWorkOn.set(connection, endTransactionWork);
1962
+ let activity;
1963
+ try {
1964
+ activity = await startTransactionActivity({
1965
+ middleware: this.middleware,
1966
+ context: {
1967
+ ...this.sqlCtx,
1968
+ scope: "transaction"
1969
+ },
1970
+ parent,
1971
+ holdFinishedChildren: this.#holdFinishedChildren
1972
+ });
1973
+ } catch (error) {
1974
+ endTransactionWork();
1975
+ owner[transactionStart].refusedBeforeBegin = true;
1976
+ throw error;
1977
+ }
1978
+ let driverTx;
1979
+ try {
1980
+ driverTx = await connection.beginTransaction();
1981
+ } catch (error) {
1982
+ endTransactionWork();
1983
+ await activity.end({
1984
+ by: "rollback",
1985
+ outcome: "failed",
1986
+ commitAttempted: false
1987
+ });
1988
+ throw error;
1989
+ }
1990
+ if (this.#heldQueryables.has(connection)) this.#heldQueryables.add(driverTx);
1991
+ return this.wrapTransaction(driverTx, connection, activity, endTransactionWork);
1992
+ }
1993
+ wrapTransaction(driverTx, connection, activity, endTransactionWork) {
1994
+ this.#openTransactions.set(driverTx, activity);
1995
+ this.#openTransactions.set(connection, activity);
1996
+ const stopAcceptingChildren = () => {
1997
+ activity.stopAcceptingChildren();
1998
+ for (const queryable of [driverTx, connection]) if (this.#openTransactions.get(queryable) === activity) this.#openTransactions.delete(queryable);
1999
+ };
2000
+ let commitAttempted = false;
2001
+ const settlement = {
2002
+ committed: false,
2003
+ rolledBack: false,
2004
+ logDroppedError(error) {
2005
+ try {
2006
+ activity.ctx.log.error({
2007
+ event: "middleware.activityEnded.error",
2008
+ error
2009
+ });
2010
+ } catch {}
2011
+ }
2012
+ };
2013
+ let commitEnding;
2014
+ const self = this;
2015
+ return {
2016
+ [transactionSettlement]: settlement,
2017
+ async commit() {
2018
+ commitAttempted = true;
2019
+ stopAcceptingChildren();
2020
+ try {
2021
+ await self.#inFlight.track(() => driverTx.commit());
2022
+ } catch (error) {
2023
+ endTransactionWork();
2024
+ await activity.end({
2025
+ by: "commit",
2026
+ outcome: "failed"
2027
+ });
2028
+ throw error;
2029
+ }
2030
+ settlement.committed = true;
2031
+ commitEnding = activity.end({
2032
+ by: "commit",
2033
+ outcome: "succeeded"
2034
+ });
2035
+ try {
2036
+ await commitEnding;
2037
+ } finally {
2038
+ endTransactionWork();
2039
+ }
2040
+ },
2041
+ async rollback() {
2042
+ stopAcceptingChildren();
2043
+ if (settlement.committed) {
2044
+ await commitEnding?.catch(() => void 0);
2045
+ return;
2046
+ }
2047
+ if (settlement.rolledBack) return;
2048
+ try {
2049
+ await self.#inFlight.track(() => driverTx.rollback());
2050
+ } catch (error) {
2051
+ endTransactionWork();
2052
+ await activity.end({
2053
+ by: "rollback",
2054
+ outcome: "failed",
2055
+ commitAttempted
2056
+ });
2057
+ throw error;
2058
+ }
2059
+ settlement.rolledBack = true;
2060
+ try {
2061
+ await activity.end({
2062
+ by: "rollback",
2063
+ outcome: "succeeded",
2064
+ commitAttempted
2065
+ });
2066
+ } finally {
2067
+ endTransactionWork();
2068
+ }
2069
+ },
2070
+ [activitySource]: {
2071
+ startActivity: (clientActivity) => self.startActivityOnRoute(self.queryableRoute(driverTx, "transaction", () => activity, {
2072
+ transaction: void 0,
2073
+ runtimeWork: false
2074
+ }), clientActivity, void 0),
2075
+ planContentHash: (plan) => self.planContentHashFor(plan, "transaction", activity)
2076
+ },
2077
+ query(plan, options) {
2078
+ return self.queryAgainstQueryable(plan, driverTx, {
2079
+ ...options,
2080
+ scope: "transaction"
2081
+ });
2082
+ },
2083
+ execute(plan, options) {
2084
+ return self.executeStatisticsAgainstQueryable(plan, driverTx, {
2085
+ ...options,
2086
+ scope: "transaction"
2087
+ });
2088
+ },
2089
+ [preparedStatementQuery](ps, params, options) {
2090
+ return self.runPreparedQueryAgainstQueryable(blindCast(ps), params, driverTx, {
2091
+ ...options,
2092
+ scope: "transaction"
2093
+ });
2094
+ },
2095
+ [preparedStatementExecute](ps, params, options) {
2096
+ return self.runPreparedExecuteAgainstQueryable(blindCast(ps), params, driverTx, {
2097
+ ...options,
2098
+ scope: "transaction"
2099
+ });
2100
+ }
2101
+ };
2102
+ }
2103
+ telemetry() {
2104
+ return this._telemetry;
2105
+ }
2106
+ close() {
2107
+ this.closePromise ??= this.closeDriverAfterWork();
2108
+ return this.closePromise;
2109
+ }
2110
+ async closeDriverAfterWork() {
2111
+ await this.refuseAfterWork();
2112
+ if (this.ownsDriver) await this.driver.close();
2113
+ }
2114
+ async refuseAfterWork() {
2115
+ const warned = { done: false };
2116
+ if (this.closeRefusal === "when-idle") await this.waitForIdleTurn(warned);
2117
+ this.#refusing = true;
2118
+ this.warnWhenWaitingOnlyForUnendedWork(warned);
2119
+ while (this.#inFlight.active || this.#openTransactionWork.active) {
2120
+ await this.#inFlight.drained();
2121
+ this.warnWhenWaitingOnlyForUnendedWork(warned);
2122
+ await this.#openTransactionWork.drained();
2123
+ }
2124
+ }
2125
+ async waitForIdleTurn(warned) {
2126
+ for (;;) {
2127
+ const startedBefore = this.#inFlight.started;
2128
+ await new Promise((resolve) => scheduleTimer(resolve, 0));
2129
+ if (!this.#inFlight.active && this.#inFlight.started === startedBefore) return;
2130
+ this.warnWhenWaitingOnlyForUnendedWork(warned);
2131
+ await this.#inFlight.drained();
2132
+ }
2133
+ }
2134
+ ensureCodecRegistryValidated() {
2135
+ if (!this.codecRegistryValidated) {
2136
+ validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);
2137
+ this.codecRegistryValidated = true;
2138
+ }
2139
+ }
2140
+ async verifyMarker(queryable) {
2141
+ const readResult = await this.familyAdapter.markerReader.readMarker(queryable);
2142
+ const expectedStorageHash = this.contract.storage.storageHash;
2143
+ const expectedProfileHash = this.contract.profileHash ?? null;
2144
+ const expected = {
2145
+ storageHash: expectedStorageHash,
2146
+ profileHash: expectedProfileHash
2147
+ };
2148
+ if (readResult.kind !== "present") {
2149
+ this.sqlCtx.log.warn({
2150
+ code: "CONTRACT.MARKER_MISSING",
2151
+ scope: "marker-verification",
2152
+ expected,
2153
+ actual: null,
2154
+ message: "Contract marker not found in database"
2155
+ });
2156
+ return;
2157
+ }
2158
+ const marker = readResult.record;
2159
+ const storageHashMatch = marker.storageHash === expectedStorageHash;
2160
+ const profileHashMatch = expectedProfileHash === null || marker.profileHash === expectedProfileHash;
2161
+ if (!storageHashMatch || !profileHashMatch) this.sqlCtx.log.warn({
2162
+ code: "CONTRACT.MARKER_MISMATCH",
2163
+ scope: "marker-verification",
2164
+ expected,
2165
+ actual: {
2166
+ storageHash: marker.storageHash,
2167
+ profileHash: marker.profileHash ?? null
2168
+ },
2169
+ message: "Contract marker hash does not match runtime contract"
2170
+ });
2171
+ }
2172
+ recordTelemetry(plan, outcome, durationMs) {
2173
+ const contract = this.contract;
2174
+ this._telemetry = Object.freeze({
2175
+ lane: plan.meta.lane,
2176
+ target: contract.target,
2177
+ fingerprint: computeSqlFingerprint(plan.sql),
2178
+ outcome,
2179
+ ...durationMs !== void 0 ? { durationMs } : {}
2180
+ });
2181
+ }
2182
+ };
2183
+ function activityOutsideTransactionError(parent, openTransaction) {
2184
+ return runtimeError$1("RUNTIME.ACTIVITY_OUTSIDE_TRANSACTION", `Work was sent through a '${parent.activity.kind}' activity onto a connection whose open transaction the activity is not part of. Start the activity on the transaction instead.`, {
2185
+ kind: parent.activity.kind,
2186
+ id: parent.activity.id,
2187
+ transactionId: openTransaction.activity.id
2188
+ });
2189
+ }
2190
+ function transactionAlreadyOpenError(parent, openTransaction) {
2191
+ return runtimeError$1("RUNTIME.TRANSACTION_ALREADY_OPEN", `A transaction is already open on this connection; a '${parent.activity.kind}' activity cannot begin another until it commits or rolls back.`, {
2192
+ kind: parent.activity.kind,
2193
+ id: parent.activity.id,
2194
+ transactionId: openTransaction.activity.id
2195
+ });
2196
+ }
2197
+ function noWork() {}
2198
+ function rowsBeneath(run, rows) {
2199
+ return new AsyncIterableResult(new RowsBeneath(run, rows));
2200
+ }
2201
+ /** The rows of a statement started beneath `run`, checked against `run` on the first `next()`. It forwards to the statement's own iterator rather than adding an async generator, so each row costs no extra turn. */
2202
+ var RowsBeneath = class {
2203
+ #run;
2204
+ #rows;
2205
+ #inner;
2206
+ #done = false;
2207
+ constructor(run, rows) {
2208
+ this.#run = run;
2209
+ this.#rows = rows;
2210
+ }
2211
+ next() {
2212
+ if (this.#done) return Promise.resolve({
2213
+ done: true,
2214
+ value: void 0
2215
+ });
2216
+ if (this.#inner === void 0) try {
2217
+ this.#run.assertAcceptsChildren();
2218
+ this.#inner = this.#rows()[Symbol.asyncIterator]();
2219
+ } catch (error) {
2220
+ this.#done = true;
2221
+ return Promise.reject(error);
2222
+ }
2223
+ return this.#inner.next();
2224
+ }
2225
+ return() {
2226
+ const inner = this.#inner;
2227
+ this.#done = true;
2228
+ return inner?.return === void 0 ? Promise.resolve({
2229
+ done: true,
2230
+ value: void 0
2231
+ }) : inner.return();
2232
+ }
2233
+ throw(error) {
2234
+ const inner = this.#inner;
2235
+ if (inner?.throw === void 0) {
2236
+ this.#done = true;
2237
+ return Promise.reject(error);
2238
+ }
2239
+ return inner.throw(error);
2240
+ }
2241
+ [Symbol.asyncIterator]() {
2242
+ return this;
2243
+ }
2244
+ async [Symbol.asyncDispose]() {
2245
+ await this.return();
2246
+ }
2247
+ };
2248
+ function transactionClosedError() {
2249
+ return runtimeError$1("RUNTIME.TRANSACTION_CLOSED", "Cannot use a transaction operation after the transaction has ended. Consume query results and await execute calls inside the transaction callback.", {});
2250
+ }
2251
+ /**
2252
+ * Adds a client's members to the context `withTransaction` passes. The context is the prototype, not spread, so live accessors such as `invalidated` keep reading the transaction's state; spreading would copy their value once.
2253
+ */
2254
+ function withTransactionMembers(txCtx, members) {
2255
+ return Object.assign(castAs(Object.create(txCtx)), members);
2256
+ }
2257
+ async function withTransaction(runtime, fn) {
2258
+ const connection = await runtime.connection();
2259
+ let transaction;
2260
+ try {
2261
+ transaction = await connection.transaction();
2262
+ } catch (error) {
2263
+ if (wasRefusedBeforeBegin(connection)) await connection.release().catch(() => void 0);
2264
+ else await connection.destroy(error).catch(() => void 0);
2265
+ throw error;
2266
+ }
2267
+ let invalidated = false;
2268
+ async function* guardedStream(inner) {
2269
+ if (invalidated) throw transactionClosedError();
2270
+ for await (const row of inner) {
2271
+ yield row;
2272
+ if (invalidated) throw transactionClosedError();
2273
+ }
2274
+ }
2275
+ function guardedQueryable(target) {
2276
+ return {
2277
+ query(plan, options) {
2278
+ if (invalidated) throw transactionClosedError();
2279
+ return new AsyncIterableResult(guardedStream(target.query(plan, options)));
2280
+ },
2281
+ async execute(plan, options) {
2282
+ if (invalidated) throw transactionClosedError();
2283
+ return target.execute(plan, options);
2284
+ },
2285
+ [preparedStatementQuery](ps, params, options) {
2286
+ if (invalidated) throw transactionClosedError();
2287
+ return new AsyncIterableResult(guardedStream(runPreparedQuery(target, ps, params, options)));
2288
+ },
2289
+ [preparedStatementExecute](ps, params, options) {
2290
+ if (invalidated) throw transactionClosedError();
2291
+ return runPreparedExecute(target, ps, params, options);
2292
+ }
2293
+ };
2294
+ }
2295
+ function guardedSource(target) {
2296
+ return {
2297
+ async startActivity(activity) {
2298
+ if (invalidated) throw transactionClosedError();
2299
+ return guardedHandle(await startActivityOn(target, activity));
2300
+ },
2301
+ planContentHash(plan) {
2302
+ return planContentHashOn(target, plan);
2303
+ }
2304
+ };
2305
+ }
2306
+ function guardedHandle(handle) {
2307
+ const source = guardedSource(handle);
2308
+ return {
2309
+ ...source,
2310
+ ...guardedQueryable(handle),
2311
+ [activitySource]: source,
2312
+ activity: handle.activity,
2313
+ get intercepted() {
2314
+ return handle.intercepted;
2315
+ },
2316
+ end: (end) => handle.end(end)
2317
+ };
2318
+ }
2319
+ const txContext = {
2320
+ ...guardedQueryable(transaction),
2321
+ get invalidated() {
2322
+ return invalidated;
2323
+ },
2324
+ [activitySource]: guardedSource(transaction)
2325
+ };
2326
+ let connectionDisposed = false;
2327
+ const destroyConnection = async (reason) => {
2328
+ if (connectionDisposed) return;
2329
+ connectionDisposed = true;
2330
+ await connection.destroy(reason).catch(() => void 0);
2331
+ };
2332
+ try {
2333
+ let result;
2334
+ try {
2335
+ result = await fn(txContext);
2336
+ } catch (error) {
2337
+ try {
2338
+ await transaction.rollback();
2339
+ } catch (rollbackError) {
2340
+ const settlement = settlementOf(transaction);
2341
+ if (settlement?.rolledBack === true) {
2342
+ settlement.logDroppedError(rollbackError);
2343
+ throw error;
2344
+ }
2345
+ await destroyConnection(rollbackError);
2346
+ const wrapped = runtimeError$1("RUNTIME.TRANSACTION_ROLLBACK_FAILED", "Transaction rollback failed after callback error", { rollbackError });
2347
+ wrapped.cause = error;
2348
+ throw wrapped;
2349
+ }
2350
+ throw error;
2351
+ } finally {
2352
+ invalidated = true;
2353
+ }
2354
+ try {
2355
+ await transaction.commit();
2356
+ } catch (commitError) {
2357
+ if (settlementOf(transaction)?.committed === true) throw commitError;
2358
+ try {
2359
+ await transaction.rollback();
2360
+ } catch (rollbackError) {
2361
+ const settlement = settlementOf(transaction);
2362
+ if (settlement?.rolledBack === true) settlement.logDroppedError(rollbackError);
2363
+ else await destroyConnection(commitError);
2364
+ }
2365
+ const wrapped = runtimeError$1("RUNTIME.TRANSACTION_COMMIT_FAILED", "Transaction commit failed", { commitError });
2366
+ wrapped.cause = commitError;
2367
+ throw wrapped;
2368
+ }
2369
+ return result;
2370
+ } finally {
2371
+ if (!connectionDisposed) await connection.release();
2372
+ }
2373
+ }
2374
+ function createToSql(stack, contract) {
2375
+ let adapter;
2376
+ return (plan) => {
2377
+ validateSqlPlan(plan, contract);
2378
+ adapter ??= stack.adapter.create(stack);
2379
+ const { sql, params } = lowerSqlPlan(adapter, contract, plan);
2380
+ return {
2381
+ sql,
2382
+ params
2383
+ };
2384
+ };
2385
+ }
2386
+ //#endregion
2387
+ export { withTransactionMembers as C, withTransaction as S, lowerSqlPlan as _, budgets as a, validateCodecRegistryCompleteness as b, createSqlExecutionStack as c, deriveParamMetadata as d, encodeParamsWithMetadata as f, lints as g, lazyActivitySource as h, activitySource as i, createToSql as l, findActivitySource as m, PreparedStatementImpl as n, createAstCodecRegistry as o, extractCodecIds as p, SqlRuntimeBase as r, createExecutionContext as s, PreparedExecutionImpl as t, delegatingActivitySource as u, planContentHashOn as v, validateContractCodecMappings as x, startActivityOn as y };
2388
+
2389
+ //# sourceMappingURL=exports-C3wGYtID-D65DEUTC.mjs.map