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

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
package/dist/runtime.mjs CHANGED
@@ -1,1799 +1,2 @@
1
- import { t as createSqlOperationRegistry } from "./dist-C_q1_QR9.mjs";
2
- import { A as PreparedParamRef, H as isQueryAst } from "./types-Dt4e_jC--COeP8xzN.mjs";
3
- import { t as collectOrderedParamRefs } from "./util-DQQgv2j1-D6INZaRG.mjs";
4
- import { t as createSqlParamRefMutator } from "./middleware-CMr4CHNz-DHIUdxlm.mjs";
5
- import { t as buildSqlAggregateDescriptorRegistry } from "./aggregate-descriptor-registry-C7hel5O7.mjs";
6
- import { t as buildCodecDescriptorRegistry } from "./codec-descriptor-registry-N0dhtKaH.mjs";
7
- import { i as runPreparedQuery, n as preparedStatementQuery, r as runPreparedExecute, t as preparedStatementExecute } from "./prepared-query-BJr50wPm-ChoqfJbX.mjs";
8
- import { isStructuredError } from "@prisma/orm-framework/utils/structured-error";
9
- import { createHash } from "node:crypto";
10
- import { assertNever } from "@prisma/orm-framework/utils/internal-error";
11
- import { ifDefined } from "@prisma/orm-framework/utils/defined";
12
- import { blindCast } from "@prisma/orm-framework/utils/casts";
13
- import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
14
- import { checkContractComponentRequirements, mergeCapabilityMatrices } from "@prisma/orm-framework/components/components";
15
- import { materializeCodec, resolveCodecDescriptorOrThrow } from "@prisma/orm-framework/components/codec";
16
- import { AsyncIterableResult, RuntimeCore, checkAborted, checkMiddlewareCompatibility, raceAgainstAbort, runBeforeExecuteChain, runBeforeQueryChain, runExecuteWithMiddleware, runQueryWithMiddleware, runtimeError } from "@prisma/orm-framework/components/runtime";
17
- import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
18
- import { createExecutionStack } from "@prisma/orm-framework/components/execution";
19
- import { hashContent } from "@prisma/orm-framework/utils/hash-content";
20
- //#region ../../../2-sql/5-runtime/dist/exports-BDzGy_bM.mjs
21
- /**
22
- * Build an {@link AstCodecResolver} bound to a descriptor registry and a per-call instance-context factory.
23
- *
24
- * 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.
25
- */
26
- function createAstCodecResolver(descriptors, instanceContextFor) {
27
- const cache = /* @__PURE__ */ new Map();
28
- return { forCodecRef(ref) {
29
- const key = `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;
30
- const cached = cache.get(key);
31
- if (cached) return cached;
32
- const codec = materializeCodec(resolveCodecDescriptorOrThrow((id) => descriptors.descriptorFor(id), ref, "RUNTIME.CODEC_DESCRIPTOR_MISSING"), ref, instanceContextFor(ref));
33
- cache.set(key, codec);
34
- return codec;
35
- } };
36
- }
37
- /**
38
- * Build a contract-free {@link ContractCodecRegistry} that resolves codecs
39
- * purely from AST-supplied {@link import('@internal/framework-components/codec').CodecRef}s
40
- * against a target's descriptor registry.
41
- *
42
- * Dispatch is driven entirely by `CodecRef`s embedded in AST nodes; no
43
- * contract walk is needed. `forColumn` always returns `undefined` — this
44
- * registry carries no column-to-codec mappings.
45
- */
46
- function createAstCodecRegistry(descriptors) {
47
- const resolver = createAstCodecResolver(descriptors, (ref) => ({
48
- name: ref.codecId,
49
- usedAt: []
50
- }));
51
- return {
52
- forColumn: () => void 0,
53
- forCodecRef: (ref) => resolver.forCodecRef(ref)
54
- };
55
- }
56
- const NO_METADATA = Object.freeze({
57
- codec: void 0,
58
- name: void 0
59
- });
60
- function deriveParamMetadata(ast) {
61
- return collectOrderedParamRefs(ast).map((ref) => {
62
- return {
63
- codec: ref.codec,
64
- name: ref.name
65
- };
66
- });
67
- }
68
- function resolveParamCodec(metadata, contractCodecs) {
69
- if (metadata.codec && contractCodecs) return contractCodecs.forCodecRef(metadata.codec);
70
- }
71
- function paramLabel(metadata, paramIndex) {
72
- return metadata.name ?? `param[${paramIndex}]`;
73
- }
74
- function wrapEncodeFailure(error, metadata, paramIndex, codecId) {
75
- const label = paramLabel(metadata, paramIndex);
76
- const wrapped = runtimeError("RUNTIME.ENCODE_FAILED", `Failed to encode parameter ${label} with codec '${codecId}': ${error instanceof Error ? error.message : String(error)}`, {
77
- label,
78
- codec: codecId,
79
- paramIndex
80
- });
81
- wrapped.cause = error;
82
- throw wrapped;
83
- }
84
- async function encodeParamValue(value, metadata, paramIndex, ctx, contractCodecs) {
85
- if (value === null || value === void 0) return null;
86
- const codec = resolveParamCodec(metadata, contractCodecs);
87
- if (!codec) return value;
88
- if (metadata.codec?.many) {
89
- if (!Array.isArray(value)) wrapEncodeFailure(/* @__PURE__ */ new TypeError(`expected an array for many-typed parameter, got ${typeof value}`), metadata, paramIndex, codec.id);
90
- const encoded = [];
91
- for (let i = 0; i < value.length; i++) {
92
- const elem = value[i];
93
- if (elem === null || elem === void 0) {
94
- encoded.push(null);
95
- continue;
96
- }
97
- try {
98
- encoded.push(await codec.encode(elem, ctx));
99
- } catch (error) {
100
- if (isStructuredError(error)) throw error;
101
- wrapEncodeFailure(error, metadata, paramIndex, codec.id);
102
- }
103
- }
104
- return encoded;
105
- }
106
- try {
107
- return await codec.encode(value, ctx);
108
- } catch (error) {
109
- if (isStructuredError(error)) throw error;
110
- wrapEncodeFailure(error, metadata, paramIndex, codec.id);
111
- }
112
- }
113
- /**
114
- * 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`.
115
- *
116
- * When `ctx.signal` is provided:
117
- *
118
- * - **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.
119
- * - **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).
120
- * - 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).
121
- */
122
- async function encodeParams(plan, ctx, contractCodecs) {
123
- return encodeParamsWithMetadata(plan.params, deriveParamMetadata(plan.ast), ctx, contractCodecs);
124
- }
125
- async function encodeParamsWithMetadata(values, metadata, ctx, contractCodecs) {
126
- checkAborted(ctx, "encode");
127
- const signal = ctx.signal;
128
- if (values.length === 0) return values;
129
- const tasks = values.map((value, i) => encodeParamValue(value, metadata[i] ?? NO_METADATA, i, ctx, contractCodecs));
130
- const settled = await raceAgainstAbort(Promise.all(tasks), signal, "encode");
131
- return Object.freeze(settled);
132
- }
133
- function extractCodecIds(contract) {
134
- const codecIds = /* @__PURE__ */ new Set();
135
- 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)) {
136
- const codecId = column.codecId;
137
- codecIds.add(codecId);
138
- }
139
- return codecIds;
140
- }
141
- function extractColumnCodecRefs(contract) {
142
- const refs = [];
143
- 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({
144
- namespaceId,
145
- table: tableName,
146
- column: columnName,
147
- codecId: column.codecId
148
- });
149
- return refs;
150
- }
151
- function validateContractCodecMappings(registry, contract) {
152
- const invalidCodecs = extractColumnCodecRefs(contract).filter((ref) => registry.descriptorFor(ref.codecId) === void 0);
153
- if (invalidCodecs.length > 0) {
154
- const details = {
155
- contractTarget: contract.target,
156
- invalidCodecs
157
- };
158
- throw runtimeError("RUNTIME.CODEC_MISSING", `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.namespaceId}.${c.table}.${c.column} (${c.codecId})`).join(", ")}`, details);
159
- }
160
- }
161
- function validateCodecRegistryCompleteness(registry, contract) {
162
- validateContractCodecMappings(registry, contract);
163
- }
164
- /**
165
- * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.
166
- *
167
- * Ad-hoc lowerings produce only `{kind: 'literal'}` slots; this helper
168
- * unwraps them into the bare-value array `SqlExecutionPlan` exposes.
169
- * Encountering a `{kind: 'bind'}` slot here means the caller passed an
170
- * AST containing `PreparedParamRef` to the ad-hoc execute path — that's a
171
- * caller error, surfaced as `RUNTIME.PREPARE_BIND_ON_ADHOC`.
172
- */
173
- function lowerSqlPlan(adapter, contract, queryPlan) {
174
- const lowered = adapter.lower(queryPlan.ast, {
175
- contract,
176
- params: queryPlan.params
177
- });
178
- const params = lowered.params.map((slot) => {
179
- if (slot.kind === "literal") return slot.value;
180
- throw runtimeError("RUNTIME.PREPARE_BIND_ON_ADHOC", `Ad-hoc execute received a bind-site slot for '${slot.name}' — bind-site references are only valid inside runtime.prepare(...).`, { name: slot.name });
181
- });
182
- return Object.freeze({
183
- sql: lowered.sql,
184
- params,
185
- ast: queryPlan.ast,
186
- meta: queryPlan.meta
187
- });
188
- }
189
- function hasAggregateWithoutGroupBy(ast) {
190
- if (ast.groupBy !== void 0) return false;
191
- return ast.projection.some((item) => item.expr.kind === "aggregate");
192
- }
193
- function primaryTableFromAst(ast) {
194
- if (ast.from === void 0) return void 0;
195
- switch (ast.from.kind) {
196
- case "table-source": return ast.from.name;
197
- case "derived-table-source": return ast.from.alias;
198
- case "function-source": return ast.from.fn;
199
- // v8 ignore next 4
200
- default: return assertNever(ast.from, `Unsupported source kind: ${ast.from.kind}`);
201
- }
202
- }
203
- function estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggregateWithoutGroup) {
204
- if (hasAggregateWithoutGroup) return 1;
205
- const primaryTable = primaryTableFromAst(ast);
206
- const tableEstimate = (primaryTable !== void 0 ? tableRows[primaryTable] : void 0) ?? defaultTableRows;
207
- if (typeof ast.limit === "number") return Math.min(ast.limit, tableEstimate);
208
- return tableEstimate;
209
- }
210
- function emitBudgetViolation(error, shouldBlock, ctx) {
211
- if (shouldBlock) throw error;
212
- ctx.log.warn({
213
- code: error.code,
214
- message: error.message,
215
- details: error.details
216
- });
217
- }
218
- function budgets(options) {
219
- const maxRows = options?.maxRows ?? 1e4;
220
- const defaultTableRows = options?.defaultTableRows ?? 1e4;
221
- const tableRows = options?.tableRows ?? {};
222
- const maxLatencyMs = options?.maxLatencyMs ?? 1e3;
223
- const rowSeverity = options?.severities?.rowCount ?? "error";
224
- const latencySeverity = options?.severities?.latency ?? "warn";
225
- const observedRowsByPlan = /* @__PURE__ */ new WeakMap();
226
- const beforeOperation = async (plan, ctx) => {
227
- observedRowsByPlan.set(plan, { count: 0 });
228
- if (isQueryAst(plan.ast) && plan.ast.kind === "select") evaluateSelectAst(plan.ast, ctx);
229
- };
230
- const afterOperation = async (_plan, result, ctx) => {
231
- const latencyMs = result.latencyMs;
232
- if (latencyMs > maxLatencyMs) {
233
- const shouldBlock = latencySeverity === "error" || ctx.mode === "strict";
234
- emitBudgetViolation(runtimeError("BUDGET.TIME_EXCEEDED", "Query latency exceeds budget", {
235
- latencyMs,
236
- maxLatencyMs
237
- }), shouldBlock, ctx);
238
- }
239
- };
240
- return Object.freeze({
241
- name: "budgets",
242
- familyId: "sql",
243
- beforeQuery: beforeOperation,
244
- beforeExecute: beforeOperation,
245
- async onRow(_row, plan, _ctx) {
246
- const state = observedRowsByPlan.get(plan);
247
- if (!state) return;
248
- state.count += 1;
249
- if (state.count > maxRows) throw runtimeError("BUDGET.ROWS_EXCEEDED", "Observed row count exceeds budget", {
250
- source: "observed",
251
- observedRows: state.count,
252
- maxRows
253
- });
254
- },
255
- afterQuery: afterOperation,
256
- afterExecute: afterOperation
257
- });
258
- function evaluateSelectAst(ast, ctx) {
259
- const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);
260
- const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);
261
- const isUnbounded = ast.limit === void 0 && !hasAggNoGroup;
262
- const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
263
- if (isUnbounded) {
264
- emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", estimated >= maxRows ? {
265
- source: "ast",
266
- estimatedRows: estimated,
267
- maxRows
268
- } : {
269
- source: "ast",
270
- maxRows
271
- }), shouldBlock, ctx);
272
- return;
273
- }
274
- if (estimated > maxRows) emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Estimated row count exceeds budget", {
275
- source: "ast",
276
- estimatedRows: estimated,
277
- maxRows
278
- }), shouldBlock, ctx);
279
- }
280
- }
281
- const SELECT_STAR_REGEX = /select\s+\*/i;
282
- const LIMIT_REGEX = /\blimit\b/i;
283
- const MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\b/i;
284
- const READ_ONLY_INTENTS = /* @__PURE__ */ new Set([
285
- "read",
286
- "report",
287
- "readonly"
288
- ]);
289
- function evaluateRawGuardrails(plan, config) {
290
- const lints = [];
291
- const budgets = [];
292
- const normalized = normalizeWhitespace(plan.sql);
293
- const statementType = classifyStatement(normalized);
294
- if (statementType === "select") {
295
- if (SELECT_STAR_REGEX.test(normalized)) lints.push(createLint("LINT.SELECT_STAR", "error", "Raw SQL plan selects all columns via *", { sql: snippet(plan.sql) }));
296
- if (!LIMIT_REGEX.test(normalized)) {
297
- const severity = config?.budgets?.unboundedSelectSeverity ?? "error";
298
- lints.push(createLint("LINT.NO_LIMIT", "warn", "Raw SQL plan omits LIMIT clause", { sql: snippet(plan.sql) }));
299
- budgets.push(createBudget("BUDGET.ROWS_EXCEEDED", severity, "Raw SQL plan is unbounded and may exceed row budget", {
300
- sql: snippet(plan.sql),
301
- ...config?.budgets?.estimatedRows !== void 0 ? { estimatedRows: config.budgets.estimatedRows } : {}
302
- }));
303
- }
304
- }
305
- if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) lints.push(createLint("LINT.READ_ONLY_MUTATION", "error", "Raw SQL plan mutates data despite read-only intent", {
306
- sql: snippet(plan.sql),
307
- intent: plan.meta.annotations?.["intent"]
308
- }));
309
- return {
310
- lints,
311
- budgets,
312
- statement: statementType
313
- };
314
- }
315
- function classifyStatement(sql) {
316
- const trimmed = sql.trim();
317
- const lower = trimmed.toLowerCase();
318
- if (lower.startsWith("with")) {
319
- if (lower.includes("select")) return "select";
320
- }
321
- if (lower.startsWith("select")) return "select";
322
- if (MUTATION_PREFIX_REGEX.test(trimmed)) return "mutation";
323
- return "other";
324
- }
325
- function isMutationStatement(statement) {
326
- return statement === "mutation";
327
- }
328
- function isReadOnlyIntent(meta) {
329
- const annotations = meta.annotations;
330
- const intent = typeof annotations?.intent === "string" ? annotations.intent.toLowerCase() : void 0;
331
- return intent !== void 0 && READ_ONLY_INTENTS.has(intent);
332
- }
333
- function normalizeWhitespace(value) {
334
- return value.replace(/\s+/g, " ").trim();
335
- }
336
- function snippet(sql) {
337
- return normalizeWhitespace(sql).slice(0, 200);
338
- }
339
- function createLint(code, severity, message, details) {
340
- return {
341
- code,
342
- severity,
343
- message,
344
- ...details ? { details } : {}
345
- };
346
- }
347
- function createBudget(code, severity, message, details) {
348
- return {
349
- code,
350
- severity,
351
- message,
352
- ...details ? { details } : {}
353
- };
354
- }
355
- function getFromSourceTableDetail(source) {
356
- switch (source.kind) {
357
- case "table-source": return source.name;
358
- case "derived-table-source": return source.alias;
359
- case "function-source": return source.fn;
360
- // v8 ignore next 4
361
- default: return assertNever(source, `Unsupported source kind: ${source.kind}`);
362
- }
363
- }
364
- function evaluateAstLints(ast) {
365
- const findings = [];
366
- switch (ast.kind) {
367
- case "delete":
368
- if (ast.where === void 0) findings.push({
369
- code: "LINT.DELETE_WITHOUT_WHERE",
370
- severity: "error",
371
- message: "DELETE without WHERE clause blocks execution to prevent accidental full-table deletion",
372
- details: { table: ast.table.name }
373
- });
374
- break;
375
- case "update":
376
- if (ast.where === void 0) findings.push({
377
- code: "LINT.UPDATE_WITHOUT_WHERE",
378
- severity: "error",
379
- message: "UPDATE without WHERE clause blocks execution to prevent accidental full-table update",
380
- details: { table: ast.table.name }
381
- });
382
- break;
383
- case "select":
384
- if (ast.limit === void 0) {
385
- const table = ast.from !== void 0 ? getFromSourceTableDetail(ast.from) : void 0;
386
- findings.push({
387
- code: "LINT.NO_LIMIT",
388
- severity: "warn",
389
- message: "Unbounded SELECT may return large result sets",
390
- ...ifDefined("details", table !== void 0 ? { table } : void 0)
391
- });
392
- }
393
- if (ast.selectAllIntent !== void 0) {
394
- const table = ast.selectAllIntent.table;
395
- findings.push({
396
- code: "LINT.SELECT_STAR",
397
- severity: "warn",
398
- message: "Query selects all columns via selectAll intent",
399
- ...ifDefined("details", table !== void 0 ? { table } : void 0)
400
- });
401
- }
402
- break;
403
- case "insert": break;
404
- case "raw-query": break;
405
- // v8 ignore next 2
406
- default: assertNever(ast, `Unsupported AST kind: ${ast.kind}`);
407
- }
408
- return findings;
409
- }
410
- function getConfiguredSeverity(code, options) {
411
- const severities = options?.severities;
412
- if (!severities) return void 0;
413
- switch (code) {
414
- case "LINT.SELECT_STAR": return severities.selectStar;
415
- case "LINT.NO_LIMIT": return severities.noLimit;
416
- case "LINT.DELETE_WITHOUT_WHERE": return severities.deleteWithoutWhere;
417
- case "LINT.UPDATE_WITHOUT_WHERE": return severities.updateWithoutWhere;
418
- case "LINT.READ_ONLY_MUTATION": return severities.readOnlyMutation;
419
- default: return;
420
- }
421
- }
422
- /**
423
- * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects
424
- * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic
425
- * guardrails or skips linting depending on `fallbackWhenAstMissing`.
426
- *
427
- * Rules (AST-based):
428
- * - DELETE without WHERE: blocks execution (configurable severity, default error)
429
- * - UPDATE without WHERE: blocks execution (configurable severity, default error)
430
- * - Unbounded SELECT: warn/error (severity from noLimit)
431
- * - SELECT * intent: warn/error (severity from selectStar)
432
- *
433
- * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic
434
- * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.
435
- */
436
- function lints(options) {
437
- const fallback = options?.fallbackWhenAstMissing ?? "raw";
438
- const beforeOperation = async (plan, ctx) => {
439
- const findings = [];
440
- if (isQueryAst(plan.ast)) {
441
- findings.push(...evaluateAstLints(plan.ast));
442
- if (plan.ast.kind === "raw-query") findings.push(...evaluateRawGuardrails(plan).lints);
443
- } else if (fallback !== "skip") findings.push(...evaluateRawGuardrails(plan).lints);
444
- for (const lint of findings) {
445
- const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
446
- if (effectiveSeverity === "error") throw runtimeError(lint.code, lint.message, lint.details);
447
- if (effectiveSeverity === "warn") ctx.log.warn({
448
- code: lint.code,
449
- message: lint.message,
450
- details: lint.details
451
- });
452
- }
453
- };
454
- return Object.freeze({
455
- name: "lints",
456
- familyId: "sql",
457
- beforeQuery: beforeOperation,
458
- beforeExecute: beforeOperation
459
- });
460
- }
461
- var PreparedStatementImpl = class {
462
- sql;
463
- ast;
464
- meta;
465
- slots;
466
- decodeContext;
467
- paramMetadata;
468
- constructor(internals) {
469
- this.sql = internals.sql;
470
- this.ast = internals.ast;
471
- this.meta = internals.meta;
472
- this.slots = internals.slots;
473
- this.decodeContext = internals.decodeContext;
474
- this.paramMetadata = internals.paramMetadata;
475
- Object.freeze(this);
476
- }
477
- query(target, params, options) {
478
- return runPreparedQuery(target, this, params, options);
479
- }
480
- };
481
- /**
482
- * The statistics-reporting sibling of {@link PreparedStatementImpl}. A plan
483
- * declaring an affected-row count prepares into one of these, which carries
484
- * the same lowered statement and bind slots and is consumed by executing it.
485
- *
486
- * The two classes are separate so the consumption a plan did not declare is
487
- * absent from the value, not merely from its type.
488
- */
489
- var PreparedExecutionImpl = class {
490
- sql;
491
- ast;
492
- meta;
493
- slots;
494
- decodeContext;
495
- paramMetadata;
496
- constructor(internals) {
497
- this.sql = internals.sql;
498
- this.ast = internals.ast;
499
- this.meta = internals.meta;
500
- this.slots = internals.slots;
501
- this.decodeContext = internals.decodeContext;
502
- this.paramMetadata = internals.paramMetadata;
503
- Object.freeze(this);
504
- }
505
- execute(target, params, options) {
506
- return runPreparedExecute(target, this, params, options);
507
- }
508
- };
509
- function documentScopedCodecTypes(contract) {
510
- return blindCast(contract.storage.types);
511
- }
512
- function createSqlExecutionStack(options) {
513
- return createExecutionStack({
514
- target: options.target,
515
- adapter: options.adapter,
516
- driver: options.driver,
517
- extensions: options.extensions
518
- });
519
- }
520
- function assertExecutionStackContractRequirements(contract, stack) {
521
- const providedComponentIds = /* @__PURE__ */ new Set([
522
- stack.target.id,
523
- stack.adapter.id,
524
- ...stack.extensions.map((pack) => pack.id)
525
- ]);
526
- const result = checkContractComponentRequirements({
527
- contract,
528
- expectedTargetFamily: "sql",
529
- expectedTargetId: stack.target.targetId,
530
- providedComponentIds
531
- });
532
- if (result.familyMismatch) throw runtimeError("RUNTIME.CONTRACT_FAMILY_MISMATCH", `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`, {
533
- actual: result.familyMismatch.actual,
534
- expected: result.familyMismatch.expected
535
- });
536
- if (result.targetMismatch) throw runtimeError("RUNTIME.CONTRACT_TARGET_MISMATCH", `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`, {
537
- actual: result.targetMismatch.actual,
538
- expected: result.targetMismatch.expected
539
- });
540
- if (result.missingExtensionPackIds.length > 0) {
541
- const packIds = result.missingExtensionPackIds;
542
- throw runtimeError("RUNTIME.MISSING_EXTENSION_PACK", `Contract requires extension pack(s) ${packIds.map((id) => `'${id}'`).join(", ")}, but runtime descriptors do not provide matching component(s).`, { packIds });
543
- }
544
- }
545
- function validateTypeParams(typeParams, descriptor, context) {
546
- const result = descriptor.paramsSchema["~standard"].validate(typeParams);
547
- if (result instanceof Promise) throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`, {
548
- ...context,
549
- codecId: descriptor.codecId,
550
- typeParams
551
- });
552
- if (result.issues) {
553
- const messages = result.issues.map((issue) => issue.message).join("; ");
554
- throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for ${context.typeName ? `type '${context.typeName}'` : `column '${context.tableName}.${context.columnName}'`} (codecId: ${descriptor.codecId}): ${messages}`, {
555
- ...context,
556
- codecId: descriptor.codecId,
557
- typeParams
558
- });
559
- }
560
- return result.value;
561
- }
562
- /**
563
- * 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. The getter is the canonical discriminator — a `paramsSchema` identity check would misroute any descriptor that doesn't reuse the exact `voidParamsSchema` singleton (e.g. a non-parameterized codec authoring its own no-op schema).
564
- *
565
- * 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).
566
- */
567
- function collectCodecDescriptors(contributors) {
568
- const all = [];
569
- const parameterized = /* @__PURE__ */ new Map();
570
- const seen = /* @__PURE__ */ new Set();
571
- for (const contributor of contributors) for (const descriptor of contributor.codecs()) {
572
- if (seen.has(descriptor.codecId)) throw runtimeError("RUNTIME.DUPLICATE_CODEC", `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`, { codecId: descriptor.codecId });
573
- seen.add(descriptor.codecId);
574
- all.push(descriptor);
575
- if (descriptor.isParameterized) parameterized.set(descriptor.codecId, descriptor);
576
- }
577
- return {
578
- all,
579
- parameterized
580
- };
581
- }
582
- /**
583
- * 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.
584
- */
585
- function collectAggregateDescriptorContributions(contributors) {
586
- return contributors.flatMap((contributor) => contributor.types?.aggregateDescriptors ?? []);
587
- }
588
- function collectTypeRefSites(storage) {
589
- const sites = /* @__PURE__ */ new Map();
590
- 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)) {
591
- if (typeof column.typeRef !== "string") continue;
592
- const list = sites.get(column.typeRef);
593
- const entry = {
594
- table: tableName,
595
- column: columnName
596
- };
597
- if (list) list.push(entry);
598
- else sites.set(column.typeRef, [entry]);
599
- }
600
- return sites;
601
- }
602
- function initializeTypeHelpers(storage, documentTypes, codecDescriptors) {
603
- const helpers = {};
604
- if (!documentTypes) return helpers;
605
- const typeRefSites = collectTypeRefSites(storage);
606
- for (const [typeName, typeInstance] of Object.entries(documentTypes)) {
607
- const codecId = typeInstance.codecId;
608
- const typeParams = typeInstance.typeParams;
609
- const descriptor = codecDescriptors.get(codecId);
610
- if (!descriptor) {
611
- helpers[typeName] = typeInstance;
612
- continue;
613
- }
614
- const validatedParams = validateTypeParams(typeParams ?? {}, descriptor, { typeName });
615
- const ctx = {
616
- name: typeName,
617
- usedAt: typeRefSites.get(typeName) ?? []
618
- };
619
- helpers[typeName] = descriptor.factory(validatedParams)(ctx);
620
- }
621
- return helpers;
622
- }
623
- function validateColumnTypeParams(storage, codecDescriptors) {
624
- 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) {
625
- const descriptor = codecDescriptors.get(column.codecId);
626
- if (descriptor) validateTypeParams(column.typeParams, descriptor, {
627
- tableName,
628
- columnName
629
- });
630
- }
631
- }
632
- /**
633
- * 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.
634
- *
635
- * Surfaces three classes of malformed contract that AST-bound codec resolution would otherwise mask silently:
636
- *
637
- * - column references a codecId no contributor registered → `RUNTIME.CODEC_DESCRIPTOR_MISSING`.
638
- * - parameterized codec, no `typeParams` (legacy "tolerate refs without params" shape) → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.
639
- * - non-parameterized codec, `typeParams` supplied → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.
640
- *
641
- * 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.
642
- */
643
- function assertColumnCodecIntegrity(storage, codecDescriptors) {
644
- 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)) {
645
- const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
646
- if (!ref) continue;
647
- const descriptor = codecDescriptors.descriptorFor(ref.codecId);
648
- if (!descriptor) throw runtimeError("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.`, {
649
- table: tableName,
650
- column: columnName,
651
- codecId: ref.codecId
652
- });
653
- if (descriptor.isParameterized && ref.typeParams === void 0) {
654
- const probe = descriptor.paramsSchema["~standard"].validate({});
655
- if (probe instanceof Promise) {
656
- probe.catch(() => {});
657
- throw runtimeError("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.`, {
658
- table: tableName,
659
- column: columnName,
660
- codecId: ref.codecId
661
- });
662
- }
663
- if ("issues" in probe && !!probe.issues) throw runtimeError("RUNTIME.CODEC_PARAMETERIZATION_MISMATCH", `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' but no typeParams are supplied. Provide typeParams on the column, or use a typeRef pointing at a storage.types entry that carries them.`, {
664
- table: tableName,
665
- column: columnName,
666
- codecId: ref.codecId,
667
- expected: "parameterized",
668
- actual: "no typeParams"
669
- });
670
- }
671
- const refTypeParams = ref.typeParams;
672
- const refHasTypeParamKeys = refTypeParams !== void 0 && refTypeParams !== null && typeof refTypeParams === "object" && !Array.isArray(refTypeParams) && Object.keys(refTypeParams).length > 0;
673
- if (!descriptor.isParameterized && refHasTypeParamKeys) throw runtimeError("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.`, {
674
- table: tableName,
675
- column: columnName,
676
- codecId: ref.codecId,
677
- expected: "non-parameterized",
678
- actual: "has typeParams"
679
- });
680
- }
681
- }
682
- /**
683
- * Build a {@link ContractCodecRegistry} that resolves codecs exclusively through the `forCodecRef` content-keyed cache.
684
- *
685
- * One pre-population pass walks `storage.types` and `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.
686
- *
687
- * Per-key instance-name policy:
688
- *
689
- * - typeRef-shared columns use the `storage.types[name]` name.
690
- * - inline-`typeParams` columns use `<col:Table.column>` (the first column observed at that key; additional columns sharing the key extend `usedAt`).
691
- * - non-parameterized codec ids use `<codec:codecId>`, aggregating every column on that codec id into one `usedAt` set.
692
- * - 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)`.
693
- *
694
- * 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.
695
- *
696
- * `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.
697
- */
698
- function buildContractCodecRegistry(contract, codecDescriptors) {
699
- const refKeyOf = (ref) => `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;
700
- const usedAtByKey = /* @__PURE__ */ new Map();
701
- const nameByKey = /* @__PURE__ */ new Map();
702
- const typeRefSites = collectTypeRefSites(contract.storage);
703
- for (const [typeName, typeInstance] of Object.entries(documentScopedCodecTypes(contract) ?? {})) {
704
- const instanceTypeParams = typeInstance.typeParams;
705
- const key = refKeyOf(instanceTypeParams !== void 0 && Object.keys(instanceTypeParams).length > 0 ? {
706
- codecId: typeInstance.codecId,
707
- typeParams: instanceTypeParams
708
- } : { codecId: typeInstance.codecId });
709
- const sites = typeRefSites.get(typeName) ?? [];
710
- const existing = usedAtByKey.get(key);
711
- if (existing) existing.push(...sites);
712
- else {
713
- usedAtByKey.set(key, [...sites]);
714
- nameByKey.set(key, typeName);
715
- }
716
- }
717
- 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)) {
718
- if (column.typeRef !== void 0) continue;
719
- const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
720
- if (!ref) continue;
721
- const key = refKeyOf(ref);
722
- const site = {
723
- table: tableName,
724
- column: columnName
725
- };
726
- const existing = usedAtByKey.get(key);
727
- if (existing) existing.push(site);
728
- else {
729
- usedAtByKey.set(key, [site]);
730
- const name = ref.typeParams !== void 0 ? `<col:${tableName}.${columnName}>` : `<codec:${ref.codecId}>`;
731
- nameByKey.set(key, name);
732
- }
733
- }
734
- const resolver = createAstCodecResolver(codecDescriptors, (ref) => {
735
- const key = refKeyOf(ref);
736
- return {
737
- name: nameByKey.get(key) ?? key,
738
- usedAt: usedAtByKey.get(key) ?? []
739
- };
740
- });
741
- 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)) {
742
- const ref = codecDescriptors.codecRefForColumn(namespaceId, tableName, columnName);
743
- if (!ref) continue;
744
- resolver.forCodecRef(ref);
745
- }
746
- return {
747
- forColumn(namespaceId, table, column) {
748
- const ref = codecDescriptors.codecRefForColumn(namespaceId, table, column);
749
- return ref ? resolver.forCodecRef(ref) : void 0;
750
- },
751
- forCodecRef(ref) {
752
- return resolver.forCodecRef(ref);
753
- }
754
- };
755
- }
756
- function assertMutationDefaultGeneratorsAvailable(contract, generatorRegistry) {
757
- const defaults = contract.execution?.mutations.defaults ?? [];
758
- if (defaults.length === 0) return;
759
- const missing = /* @__PURE__ */ new Set();
760
- for (const mutationDefault of defaults) for (const phase of [mutationDefault.onCreate, mutationDefault.onUpdate]) {
761
- if (!phase) continue;
762
- if (phase.kind === "generator" && !generatorRegistry.has(phase.id)) missing.add(phase.id);
763
- }
764
- if (missing.size === 0) return;
765
- const ids = Array.from(missing);
766
- throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `Contract requires mutation default generator(s) ${ids.map((id) => `'${id}'`).join(", ")}, but no runtime component provides them.`, { ids });
767
- }
768
- function collectMutationDefaultGenerators(contributors) {
769
- const generators = /* @__PURE__ */ new Map();
770
- const owners = /* @__PURE__ */ new Map();
771
- for (const contributor of contributors) {
772
- const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];
773
- for (const generator of nextGenerators) {
774
- const existingOwner = owners.get(generator.id);
775
- if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR", `Duplicate mutation default generator '${generator.id}'.`, {
776
- id: generator.id,
777
- existingOwner,
778
- incomingOwner: contributor.id
779
- });
780
- generators.set(generator.id, generator);
781
- owners.set(generator.id, contributor.id);
782
- }
783
- }
784
- return generators;
785
- }
786
- function computeExecutionDefaultValue(spec, generatorRegistry) {
787
- switch (spec.kind) {
788
- case "generator": {
789
- const generator = generatorRegistry.get(spec.id);
790
- if (!generator) throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`, { id: spec.id });
791
- return generator.generate(spec.params);
792
- }
793
- }
794
- }
795
- function applyMutationDefaults(contract, generatorRegistry, options) {
796
- const defaults = contract.execution?.mutations.defaults ?? [];
797
- if (defaults.length === 0) return [];
798
- const isEmptyUpdate = options.op === "update" && Object.keys(options.values).length === 0;
799
- const applied = [];
800
- const appliedColumns = /* @__PURE__ */ new Set();
801
- const rowCache = /* @__PURE__ */ new Map();
802
- for (const mutationDefault of defaults) {
803
- if (mutationDefault.ref.table !== options.table) continue;
804
- if (mutationDefault.ref.namespace !== options.namespace) continue;
805
- const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
806
- if (!defaultSpec) continue;
807
- if (isEmptyUpdate) continue;
808
- const columnName = mutationDefault.ref.column;
809
- if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) continue;
810
- applied.push({
811
- column: columnName,
812
- value: resolveScopedValue(defaultSpec, generatorRegistry, rowCache, options.defaultValueCache)
813
- });
814
- appliedColumns.add(columnName);
815
- }
816
- return applied;
817
- }
818
- function resolveScopedValue(spec, generatorRegistry, rowCache, queryCache) {
819
- if (spec.kind !== "generator") return computeExecutionDefaultValue(spec, generatorRegistry);
820
- const cache = scopedCache(generatorRegistry.get(spec.id)?.stability, rowCache, queryCache);
821
- if (!cache) return computeExecutionDefaultValue(spec, generatorRegistry);
822
- if (cache.has(spec.id)) return cache.get(spec.id);
823
- const value = computeExecutionDefaultValue(spec, generatorRegistry);
824
- cache.set(spec.id, value);
825
- return value;
826
- }
827
- function scopedCache(stability, rowCache, queryCache) {
828
- switch (stability) {
829
- case "row": return rowCache;
830
- case "query": return queryCache;
831
- default: return;
832
- }
833
- }
834
- function createExecutionContext(options) {
835
- const { stack, driver } = options;
836
- assertExecutionStackContractRequirements(options.contract, stack);
837
- const capabilityContributors = [
838
- stack.target,
839
- stack.adapter,
840
- ...driver ? [driver] : [],
841
- ...stack.extensions
842
- ];
843
- const mergedCapabilities = mergeCapabilityMatrices(options.contract.capabilities, capabilityContributors);
844
- const contract = {
845
- ...options.contract,
846
- capabilities: mergedCapabilities
847
- };
848
- const contributors = [
849
- stack.target,
850
- stack.adapter,
851
- ...stack.extensions
852
- ];
853
- const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } = collectCodecDescriptors(contributors);
854
- const queryOperationRegistry = createSqlOperationRegistry();
855
- for (const contributor of contributors) {
856
- const ops = contributor.queryOperations?.() ?? {};
857
- for (const [name, op] of Object.entries(ops)) queryOperationRegistry.register(name, op);
858
- }
859
- const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors, contract.storage);
860
- assertColumnCodecIntegrity(contract.storage, codecDescriptors);
861
- const aggregateDescriptors = buildSqlAggregateDescriptorRegistry(collectAggregateDescriptorContributions(contributors), codecDescriptors);
862
- const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);
863
- assertMutationDefaultGeneratorsAvailable(contract, mutationDefaultGeneratorRegistry);
864
- if (parameterizedCodecDescriptors.size > 0) validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);
865
- const types = initializeTypeHelpers(contract.storage, documentScopedCodecTypes(contract), parameterizedCodecDescriptors);
866
- return {
867
- contract,
868
- contractCodecs: buildContractCodecRegistry(contract, codecDescriptors),
869
- codecDescriptors,
870
- aggregateDescriptors,
871
- queryOperations: queryOperationRegistry,
872
- types,
873
- applyMutationDefaults: (options) => applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options)
874
- };
875
- }
876
- const WIRE_PREVIEW_LIMIT = 100;
877
- const EMPTY_INCLUDE_ALIASES = /* @__PURE__ */ new Set();
878
- function projectionListFromAst(ast) {
879
- if (ast.kind === "select") return ast.projection;
880
- return ast.returning;
881
- }
882
- function resolveProjectionCodec(item, contractCodecs) {
883
- if (item.codec && contractCodecs) return contractCodecs.forCodecRef(item.codec);
884
- }
885
- const EMPTY_MANY_ALIASES = /* @__PURE__ */ new Set();
886
- function undecodedContext() {
887
- return {
888
- aliases: void 0,
889
- codecs: /* @__PURE__ */ new Map(),
890
- columnRefs: /* @__PURE__ */ new Map(),
891
- includeAliases: EMPTY_INCLUDE_ALIASES,
892
- manyAliases: EMPTY_MANY_ALIASES,
893
- aliasSource: "projection"
894
- };
895
- }
896
- /**
897
- * Decode context for a raw statement: the columns come from the row spec its
898
- * author declared at the terminator, and each carries the codec that decodes
899
- * it. A statement that reports an affected-row count declares no columns, so
900
- * its single stats row passes through undecoded.
901
- *
902
- * The spec is the only description of the result — the runtime never parses
903
- * the SQL — so it is also what a mismatched result set is measured against.
904
- */
905
- function rawQueryDecodeContext(ast, contractCodecs) {
906
- if (ast.result.kind === "affected-count") return undecodedContext();
907
- const aliases = [];
908
- const codecs = /* @__PURE__ */ new Map();
909
- for (const [name, column] of Object.entries(ast.result.columns)) {
910
- aliases.push(name);
911
- if (contractCodecs) codecs.set(name, contractCodecs.forCodecRef({ codecId: column.codecId }));
912
- }
913
- return {
914
- aliases,
915
- codecs,
916
- columnRefs: /* @__PURE__ */ new Map(),
917
- includeAliases: EMPTY_INCLUDE_ALIASES,
918
- manyAliases: EMPTY_MANY_ALIASES,
919
- aliasSource: "row-spec"
920
- };
921
- }
922
- function buildDecodeContext(ast, contractCodecs) {
923
- if (ast.kind === "raw-query") return rawQueryDecodeContext(ast, contractCodecs);
924
- const projection = projectionListFromAst(ast);
925
- if (!projection || projection.length === 0) return undecodedContext();
926
- const aliases = [];
927
- const codecs = /* @__PURE__ */ new Map();
928
- const columnRefs = /* @__PURE__ */ new Map();
929
- const includeAliases = /* @__PURE__ */ new Set();
930
- const manyAliases = /* @__PURE__ */ new Set();
931
- for (const item of projection) {
932
- aliases.push(item.alias);
933
- const codec = resolveProjectionCodec(item, contractCodecs);
934
- if (codec) codecs.set(item.alias, codec);
935
- if (item.codec?.many) manyAliases.add(item.alias);
936
- if (item.expr.kind === "column-ref") columnRefs.set(item.alias, {
937
- table: item.expr.table,
938
- column: item.expr.column
939
- });
940
- else if (item.expr.kind === "subquery" || item.expr.kind === "json-array-agg") includeAliases.add(item.alias);
941
- }
942
- return {
943
- aliases,
944
- codecs,
945
- columnRefs,
946
- includeAliases,
947
- manyAliases,
948
- aliasSource: "projection"
949
- };
950
- }
951
- function previewWireValue(wireValue) {
952
- if (typeof wireValue === "string") return wireValue.length > WIRE_PREVIEW_LIMIT ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...` : wireValue;
953
- return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
954
- }
955
- function wrapDecodeFailure(error, alias, ref, codec, wireValue) {
956
- const message = error instanceof Error ? error.message : String(error);
957
- const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to decode column ${ref ? `${ref.table}.${ref.column}` : alias} with codec '${codec.id}': ${message}`, {
958
- ...ref ? {
959
- table: ref.table,
960
- column: ref.column
961
- } : { alias },
962
- codec: codec.id,
963
- wirePreview: previewWireValue(wireValue)
964
- });
965
- wrapped.cause = error;
966
- throw wrapped;
967
- }
968
- function wrapIncludeAggregateFailure(error, alias, wireValue) {
969
- const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to parse JSON array for include alias '${alias}': ${error instanceof Error ? error.message : String(error)}`, {
970
- alias,
971
- wirePreview: previewWireValue(wireValue)
972
- });
973
- wrapped.cause = error;
974
- throw wrapped;
975
- }
976
- function decodeIncludeAggregate(alias, wireValue) {
977
- if (wireValue === null || wireValue === void 0) return [];
978
- try {
979
- if (typeof wireValue === "string") return JSON.parse(wireValue);
980
- if (typeof wireValue === "object") return wireValue;
981
- return JSON.parse(String(wireValue));
982
- } catch (error) {
983
- wrapIncludeAggregateFailure(error, alias, wireValue);
984
- }
985
- }
986
- /**
987
- * 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
988
- * no separate validator-registry pass.
989
- *
990
- * 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
991
- * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.
992
- *
993
- * For `many`-flagged aliases the driver has already parsed the wire form into a JS array; this function maps the element codec over that array element-by-element, passing `null` elements through unchanged. Element-level failures surface through the existing `RUNTIME.DECODE_FAILED` envelope with the column/codec context from the parent cell.
994
- */
995
- async function decodeField(alias, wireValue, decodeCtx, rowCtx) {
996
- if (wireValue === null) return null;
997
- const codec = decodeCtx.codecs.get(alias);
998
- if (!codec) return wireValue;
999
- const ref = decodeCtx.columnRefs.get(alias);
1000
- let cellCtx;
1001
- if (ref) cellCtx = {
1002
- ...rowCtx,
1003
- column: {
1004
- table: ref.table,
1005
- name: ref.column
1006
- }
1007
- };
1008
- else {
1009
- const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;
1010
- cellCtx = rowCtxWithoutColumn;
1011
- }
1012
- if (decodeCtx.manyAliases.has(alias)) {
1013
- if (!Array.isArray(wireValue)) wrapDecodeFailure(/* @__PURE__ */ new TypeError(`expected an array from the driver for many-typed column, got ${typeof wireValue}`), alias, ref, codec, wireValue);
1014
- const decoded = [];
1015
- for (const elem of wireValue) {
1016
- if (elem === null || elem === void 0) {
1017
- decoded.push(null);
1018
- continue;
1019
- }
1020
- try {
1021
- decoded.push(await codec.decode(elem, cellCtx));
1022
- } catch (error) {
1023
- if (isStructuredError(error)) throw error;
1024
- wrapDecodeFailure(error, alias, ref, codec, elem);
1025
- }
1026
- }
1027
- return decoded;
1028
- }
1029
- try {
1030
- return await codec.decode(wireValue, cellCtx);
1031
- } catch (error) {
1032
- if (isStructuredError(error)) throw error;
1033
- wrapDecodeFailure(error, alias, ref, codec, wireValue);
1034
- }
1035
- }
1036
- /**
1037
- * 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`) 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`.
1038
- *
1039
- * When `rowCtx.signal` is provided:
1040
- *
1041
- * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.
1042
- * - **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).
1043
- * - Existing structured envelopes (any dotted-code error passing `isStructuredError`, e.g. `RUNTIME.DECODE_FAILED`) from codec bodies pass through unchanged (no double wrap).
1044
- */
1045
- async function decodeRow(row, decodeCtx, rowCtx) {
1046
- checkAborted(rowCtx, "decode");
1047
- const signal = rowCtx.signal;
1048
- const aliases = decodeCtx.aliases ?? Object.keys(row);
1049
- if (decodeCtx.aliases !== void 0) {
1050
- for (const alias of decodeCtx.aliases) if (!Object.hasOwn(row, alias)) throw decodeCtx.aliasSource === "row-spec" ? runtimeError("RUNTIME.RAW_ROW_COLUMN_MISSING", `Raw statement result has no column "${alias}", which its row spec declares`, {
1051
- column: alias,
1052
- declaredColumns: decodeCtx.aliases,
1053
- resultColumns: Object.keys(row)
1054
- }) : runtimeError("RUNTIME.DECODE_FAILED", `Row missing projection alias "${alias}"`, {
1055
- alias,
1056
- expectedAliases: decodeCtx.aliases,
1057
- presentKeys: Object.keys(row)
1058
- });
1059
- }
1060
- const tasks = [];
1061
- const includeIndices = [];
1062
- for (let i = 0; i < aliases.length; i++) {
1063
- const alias = aliases[i];
1064
- const wireValue = row[alias];
1065
- if (decodeCtx.includeAliases.has(alias)) {
1066
- includeIndices.push({
1067
- index: i,
1068
- alias,
1069
- value: wireValue
1070
- });
1071
- tasks.push(Promise.resolve(void 0));
1072
- continue;
1073
- }
1074
- tasks.push(decodeField(alias, wireValue, decodeCtx, rowCtx));
1075
- }
1076
- const settled = await raceAgainstAbort(Promise.all(tasks), signal, "decode");
1077
- for (const entry of includeIndices) settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);
1078
- const decoded = {};
1079
- for (let i = 0; i < aliases.length; i++) decoded[aliases[i]] = settled[i];
1080
- return decoded;
1081
- }
1082
- /**
1083
- * Computes a stable content hash for a lowered SQL execution plan.
1084
- *
1085
- * Internally builds an unambiguous canonical-stringified preimage from
1086
- * three components:
1087
- *
1088
- * 1. `meta.storageHash` — discriminates by schema. A migration changes the
1089
- * storage hash, which invalidates cached entries automatically.
1090
- * 2. `exec.sql` — the raw lowered SQL text. Two queries with different
1091
- * structure produce different keys. Note that we deliberately do **not**
1092
- * use `computeSqlFingerprint` here: that helper strips literals to group
1093
- * executions by statement shape (used by telemetry), which is the
1094
- * opposite of what a content hash needs — we want per-execution
1095
- * discrimination, not per-statement-shape grouping.
1096
- * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a
1097
- * deterministic serialization that is stable across object key
1098
- * insertion order and that distinguishes types JSON would otherwise
1099
- * conflate (e.g. `BigInt(1)` vs `1`).
1100
- *
1101
- * The components are wrapped in an object and canonicalized as a single
1102
- * unit (rather than concatenated with a delimiter) so component
1103
- * boundaries are unambiguous: any character appearing inside `sql` or
1104
- * `storageHash` cannot bleed across components and produce a collision
1105
- * with a different split of the same characters.
1106
- *
1107
- * The canonical string is then piped through `hashContent` to produce a
1108
- * bounded, opaque digest. See `@internal/utils/hash-content` for the
1109
- * rationale.
1110
- *
1111
- * @internal
1112
- */
1113
- function computeSqlContentHash(exec) {
1114
- return hashContent(canonicalStringify({
1115
- storageHash: exec.meta.storageHash,
1116
- sql: exec.sql,
1117
- params: exec.params
1118
- }));
1119
- }
1120
- const STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;
1121
- const NUMERIC_LITERAL_REGEX = /\b\d+(?:\.\d+)?\b/g;
1122
- const WHITESPACE_REGEX = /\s+/g;
1123
- /**
1124
- * Computes a literal-stripped, normalized fingerprint of a SQL statement.
1125
- *
1126
- * The function strips string and numeric literals, collapses whitespace, and
1127
- * lowercases the result before hashing — so two structurally equivalent
1128
- * statements (with different parameter values) produce the same fingerprint.
1129
- * Used by SQL telemetry to group queries.
1130
- */
1131
- function computeSqlFingerprint(sql) {
1132
- const normalized = sql.replace(STRING_LITERAL_REGEX, "?").replace(NUMERIC_LITERAL_REGEX, "?").replace(WHITESPACE_REGEX, " ").trim().toLowerCase();
1133
- return createHash("sha256").update(normalized).digest("hex");
1134
- }
1135
- async function runBeforeCompileChain(middleware, initial, ctx) {
1136
- let current = initial;
1137
- for (const mw of middleware) {
1138
- if (!mw.beforeCompile) continue;
1139
- const result = await mw.beforeCompile(current, ctx);
1140
- if (result === void 0) continue;
1141
- if (result.ast === current.ast) continue;
1142
- ctx.log.debug?.({
1143
- event: "middleware.rewrite",
1144
- middleware: mw.name,
1145
- lane: current.meta.lane
1146
- });
1147
- current = result;
1148
- }
1149
- return current;
1150
- }
1151
- function normalizeSpec(spec) {
1152
- if (typeof spec === "string") return {
1153
- codec: { codecId: spec },
1154
- nullable: false
1155
- };
1156
- return {
1157
- codec: spec.typeParams !== void 0 ? {
1158
- codecId: spec.codecId,
1159
- typeParams: spec.typeParams
1160
- } : { codecId: spec.codecId },
1161
- nullable: spec.nullable === true
1162
- };
1163
- }
1164
- var BindSiteExpression = class {
1165
- returnType;
1166
- #ast;
1167
- constructor(ref, returnType) {
1168
- this.#ast = ref;
1169
- this.returnType = returnType;
1170
- }
1171
- buildAst() {
1172
- return this.#ast;
1173
- }
1174
- };
1175
- function buildBindSiteParams(declaration) {
1176
- const params = {};
1177
- for (const [name, spec] of Object.entries(declaration)) {
1178
- const { codec, nullable } = normalizeSpec(spec);
1179
- params[name] = new BindSiteExpression(PreparedParamRef.of(name, codec), {
1180
- codecId: codec.codecId,
1181
- nullable
1182
- });
1183
- }
1184
- return Object.freeze(params);
1185
- }
1186
- /**
1187
- * Resolve a PreparedStatement's slot order to the unencoded values it
1188
- * will carry into encode. Literal slots come from the lowered AST;
1189
- * bind slots are looked up by name on `userParams`. Missing user params
1190
- * surface `RUNTIME.PREPARE_MISSING_PARAM` so the caller cannot silently
1191
- * bind `undefined`.
1192
- */
1193
- function isRecord(value) {
1194
- return typeof value === "object" && value !== null;
1195
- }
1196
- function resolvePreparedSlotValues(ps, userParams) {
1197
- if (!isRecord(userParams)) throw runtimeError("RUNTIME.PREPARE_MISSING_PARAM", "Prepared statement parameters must be an object");
1198
- return ps.slots.map((slot) => {
1199
- if (slot.kind === "literal") return slot.value;
1200
- if (!Object.hasOwn(userParams, slot.name)) throw runtimeError("RUNTIME.PREPARE_MISSING_PARAM", `Prepared statement query is missing parameter '${slot.name}'`, { name: slot.name });
1201
- return userParams[slot.name];
1202
- });
1203
- }
1204
- var SqlFamilyAdapter = class {
1205
- contract;
1206
- markerReader;
1207
- constructor(contract, adapterProfile) {
1208
- this.contract = contract;
1209
- this.markerReader = adapterProfile;
1210
- }
1211
- validatePlan(plan, contract) {
1212
- if (plan.meta.target !== contract.target) throw runtimeError("PLAN.TARGET_MISMATCH", "Plan target does not match runtime target", {
1213
- planTarget: plan.meta.target,
1214
- runtimeTarget: contract.target
1215
- });
1216
- if (plan.meta.storageHash !== contract.storage.storageHash) throw runtimeError("PLAN.HASH_MISMATCH", "Plan storage hash does not match runtime contract", {
1217
- planStorageHash: plan.meta.storageHash,
1218
- runtimeStorageHash: contract.storage.storageHash
1219
- });
1220
- }
1221
- };
1222
- function isExecutionPlan(plan) {
1223
- return "sql" in plan;
1224
- }
1225
- // v8 ignore next 2
1226
- const noopLogSink = () => {};
1227
- const noopLog = {
1228
- info: noopLogSink,
1229
- warn: noopLogSink,
1230
- error: noopLogSink
1231
- };
1232
- /**
1233
- * Abstract family-layer base for SQL runtimes. Subclass to build a target runtime
1234
- * (e.g. `PostgresRuntimeImpl`); app code should consume the `Runtime` interface returned
1235
- * by the target factories, never this class directly.
1236
- */
1237
- var SqlRuntimeBase = class extends RuntimeCore {
1238
- contract;
1239
- adapter;
1240
- driver;
1241
- familyAdapter;
1242
- contractCodecs;
1243
- codecDescriptors;
1244
- sqlCtx;
1245
- verifyMarkerOption;
1246
- verifyMarkerPromise;
1247
- #preparedStatementHandles = /* @__PURE__ */ new WeakMap();
1248
- codecRegistryValidated;
1249
- _telemetry;
1250
- constructor(options) {
1251
- const { context, adapter, driver, verifyMarker, middleware, mode, log } = options;
1252
- if (middleware) for (const mw of middleware) checkMiddlewareCompatibility(mw, "sql", context.contract.target);
1253
- const sqlCtx = {
1254
- contract: context.contract,
1255
- mode: mode ?? "strict",
1256
- now: () => Date.now(),
1257
- log: log ?? noopLog,
1258
- contentHash: (exec) => computeSqlContentHash(blindCast(exec)),
1259
- scope: "runtime",
1260
- planExecutionId: ""
1261
- };
1262
- super({
1263
- middleware: middleware ?? [],
1264
- ctx: sqlCtx
1265
- });
1266
- this.contract = context.contract;
1267
- this.adapter = adapter;
1268
- this.driver = driver;
1269
- this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);
1270
- this.contractCodecs = context.contractCodecs;
1271
- this.codecDescriptors = context.codecDescriptors;
1272
- this.sqlCtx = sqlCtx;
1273
- this.verifyMarkerOption = verifyMarker ?? "onFirstUse";
1274
- this.codecRegistryValidated = false;
1275
- this.verifyMarkerPromise = this.verifyMarkerOption === false ? Promise.resolve() : null;
1276
- this._telemetry = null;
1277
- }
1278
- /**
1279
- * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan`
1280
- * with encoded parameters ready for the driver.
1281
- *
1282
- * Implementation note: SQL splits lower-then-encode across
1283
- * {@link lowerToDraft} + {@link encodeDraftParams} so the selected
1284
- * operation's middleware chain can run between them:
1285
- * {@link prepareQueryExecution} uses `runBeforeQueryChain` for `query()`,
1286
- * while {@link prepareExecuteExecution} uses `runBeforeExecuteChain` for
1287
- * `execute()` (cipherstash bulk-encrypt, for example, mutates pre-encode
1288
- * `ParamRef.value` slots). This protected hook composes the two back into
1289
- * the cross-family `lower()` shape `RuntimeCore` expects. The production
1290
- * operation methods use the matching split form before driver execution.
1291
- *
1292
- * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so
1293
- * per-query cancellation reaches every codec body during parameter
1294
- * encoding. SQL params do not populate `ctx.column` — encode-side
1295
- * column metadata is the middleware's domain.
1296
- */
1297
- async lower(plan, ctx) {
1298
- const draft = this.lowerToDraft(plan);
1299
- return await this.encodeDraftParams(draft, ctx);
1300
- }
1301
- /**
1302
- * AST → pre-encode draft for the selected `query()` or `execute()` operation.
1303
- * The returned plan has `sql` rendered and `params` populated with the
1304
- * user-domain values the lowering site collected from `ParamRef` nodes. No
1305
- * codec encode has happened yet; consumers can mutate `params` via the
1306
- * `SqlParamRefMutator` before {@link encodeDraftParams} runs.
1307
- */
1308
- lowerToDraft(plan) {
1309
- return lowerSqlPlan(this.adapter, this.contract, plan);
1310
- }
1311
- /**
1312
- * Encode a draft plan's params for the selected `query()` or `execute()`
1313
- * operation through the per-column codecs and freeze the result into the
1314
- * final `SqlExecutionPlan` the driver sees. Errors surface as
1315
- * `RUNTIME.ENCODE_FAILED` envelopes from {@link encodeParams}.
1316
- */
1317
- async encodeDraftParams(draft, ctx) {
1318
- return Object.freeze({
1319
- ...draft,
1320
- params: await encodeParams(draft, ctx, this.contractCodecs)
1321
- });
1322
- }
1323
- /** Default query invocation required by the abstract `RuntimeCore` contract. */
1324
- // v8 ignore next 6
1325
- runDriver(exec) {
1326
- return this.driver.query({
1327
- sql: exec.sql,
1328
- params: exec.params
1329
- });
1330
- }
1331
- runExecute(exec) {
1332
- return this.driver.execute({
1333
- sql: exec.sql,
1334
- params: exec.params
1335
- });
1336
- }
1337
- /**
1338
- * SQL pre-compile hook. 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 AST is the authoritative source of execution metadata, so a rewrite needs no sidecar reconciliation here — the lowering adapter and the encoder both walk the rewritten
1339
- * AST directly.
1340
- */
1341
- runBeforeCompile(plan) {
1342
- return this.compilePlan(plan, this.sqlCtx);
1343
- }
1344
- async compilePlan(plan, middlewareCtx) {
1345
- const rewrittenDraft = await runBeforeCompileChain(this.middleware, {
1346
- ast: plan.ast,
1347
- meta: plan.meta
1348
- }, middlewareCtx);
1349
- return rewrittenDraft.ast === plan.ast ? plan : {
1350
- ...plan,
1351
- ast: rewrittenDraft.ast,
1352
- meta: rewrittenDraft.meta
1353
- };
1354
- }
1355
- query(plan, options) {
1356
- return this.queryAgainstQueryable(plan, this.driver, options);
1357
- }
1358
- execute(plan, options) {
1359
- return this.executeStatisticsAgainstQueryable(plan, this.driver, options);
1360
- }
1361
- [preparedStatementQuery](ps, params, options) {
1362
- return this.runPreparedQueryAgainstQueryable(blindCast(ps), params, this.driver, options);
1363
- }
1364
- [preparedStatementExecute](ps, params, options) {
1365
- return this.runPreparedExecuteAgainstQueryable(blindCast(ps), params, this.driver, options);
1366
- }
1367
- /**
1368
- * Returns the raw driver connection. The connection is a `SqlQueryable` — SQL
1369
- * issued on it runs below the middleware/codec/telemetry pipeline. It carries
1370
- * its own lifecycle (`release`/`destroy`/`beginTransaction`); the caller owns
1371
- * disposal.
1372
- */
1373
- acquireRawConnection() {
1374
- return this.driver.acquireConnection();
1375
- }
1376
- async setupDriverExecution(exec) {
1377
- this.familyAdapter.validatePlan(exec, this.contract);
1378
- this._telemetry = null;
1379
- if (this.verifyMarkerPromise === null) this.verifyMarkerPromise = this.verifyMarker();
1380
- await this.verifyMarkerPromise;
1381
- }
1382
- async *streamRows(exec, decodeContext, driverCall, codecCtx, execMiddlewareCtx) {
1383
- await this.setupDriverExecution(exec);
1384
- const startedAt = Date.now();
1385
- let outcome = null;
1386
- try {
1387
- const iterator = runQueryWithMiddleware(exec, this.middleware, execMiddlewareCtx, driverCall)[Symbol.asyncIterator]();
1388
- try {
1389
- while (true) {
1390
- checkAborted(codecCtx, "stream");
1391
- const next = await iterator.next();
1392
- if (next.done) break;
1393
- yield await decodeRow(next.value, decodeContext, codecCtx);
1394
- }
1395
- } finally {
1396
- await iterator.return?.();
1397
- }
1398
- outcome = "success";
1399
- } catch (error) {
1400
- outcome = "runtime-error";
1401
- throw error;
1402
- } finally {
1403
- if (outcome !== null) this.recordTelemetry(exec, outcome, Date.now() - startedAt);
1404
- }
1405
- }
1406
- createQueryContexts(options) {
1407
- const signal = options?.signal;
1408
- const scope = options?.scope ?? "runtime";
1409
- return {
1410
- codecCtx: signal === void 0 ? {} : { signal },
1411
- middlewareCtx: {
1412
- ...this.sqlCtx,
1413
- ...ifDefined("signal", signal),
1414
- ...scope !== "runtime" ? { scope } : {},
1415
- planExecutionId: crypto.randomUUID()
1416
- }
1417
- };
1418
- }
1419
- prepareQueryExecution(plan, codecCtx, middlewareCtx) {
1420
- return this.prepareOperation(plan, codecCtx, middlewareCtx, runBeforeQueryChain);
1421
- }
1422
- prepareExecuteExecution(plan, codecCtx, middlewareCtx) {
1423
- return this.prepareOperation(plan, codecCtx, middlewareCtx, runBeforeExecuteChain);
1424
- }
1425
- async prepareOperation(plan, codecCtx, middlewareCtx, runBefore) {
1426
- checkAborted(codecCtx, "stream");
1427
- if (isExecutionPlan(plan)) {
1428
- const mutator = createSqlParamRefMutator(plan);
1429
- await runBefore(plan, this.middleware, middlewareCtx, mutator);
1430
- return Object.freeze({
1431
- ...plan,
1432
- params: await encodeParams({
1433
- ...plan,
1434
- params: mutator.currentParams()
1435
- }, codecCtx, this.contractCodecs)
1436
- });
1437
- }
1438
- const compiled = await this.compilePlan(plan, middlewareCtx);
1439
- const draft = this.lowerToDraft(compiled);
1440
- const mutator = createSqlParamRefMutator(draft);
1441
- await runBefore(draft, this.middleware, middlewareCtx, mutator);
1442
- const draftWithMutations = Object.freeze({
1443
- ...draft,
1444
- params: mutator.currentParams()
1445
- });
1446
- return this.encodeDraftParams(draftWithMutations, codecCtx);
1447
- }
1448
- /** Query rows against a caller-supplied queryable through the shared preparation pipeline. */
1449
- queryAgainstQueryable(plan, queryable, options) {
1450
- this.ensureCodecRegistryValidated();
1451
- const self = this;
1452
- const { codecCtx, middlewareCtx } = this.createQueryContexts(options);
1453
- const generator = async function* () {
1454
- const exec = await self.prepareQueryExecution(plan, codecCtx, middlewareCtx);
1455
- const decodeContext = buildDecodeContext(exec.ast, self.contractCodecs);
1456
- yield* self.streamRows(exec, decodeContext, () => queryable.query({
1457
- sql: exec.sql,
1458
- params: exec.params
1459
- }), codecCtx, middlewareCtx);
1460
- };
1461
- return new AsyncIterableResult(generator());
1462
- }
1463
- /** Execute statistics against a caller-supplied queryable through the shared preparation pipeline. */
1464
- async executeStatisticsAgainstQueryable(plan, queryable, options) {
1465
- this.ensureCodecRegistryValidated();
1466
- const { codecCtx, middlewareCtx } = this.createQueryContexts(options);
1467
- const exec = await this.prepareExecuteExecution(plan, codecCtx, middlewareCtx);
1468
- await this.setupDriverExecution(exec);
1469
- checkAborted(codecCtx, "stream");
1470
- const startedAt = Date.now();
1471
- let outcome = "success";
1472
- try {
1473
- return await runExecuteWithMiddleware(exec, this.middleware, middlewareCtx, () => queryable.execute({
1474
- sql: exec.sql,
1475
- params: exec.params
1476
- }));
1477
- } catch (error) {
1478
- outcome = "runtime-error";
1479
- throw error;
1480
- } finally {
1481
- this.recordTelemetry(exec, outcome, Date.now() - startedAt);
1482
- }
1483
- }
1484
- async prepare(declaration, callback) {
1485
- this.ensureCodecRegistryValidated();
1486
- const userPlan = callback(buildBindSiteParams(declaration));
1487
- const finalPlan = await this.runBeforeCompile(userPlan);
1488
- const orderedRefs = collectOrderedParamRefs(finalPlan.ast);
1489
- const referencedNames = /* @__PURE__ */ new Set();
1490
- for (const ref of orderedRefs) if (ref.kind === "prepared-param-ref") referencedNames.add(ref.name);
1491
- const missing = Object.keys(declaration).filter((name) => !referencedNames.has(name));
1492
- if (missing.length > 0) throw runtimeError("RUNTIME.PREPARE_UNUSED_PARAM", `Prepared statement declaration includes parameter${missing.length === 1 ? "" : "s"} not referenced by the callback's plan: ${missing.join(", ")}`, { unused: missing });
1493
- const lowered = this.adapter.lower(finalPlan.ast, {
1494
- contract: this.contract,
1495
- params: orderedRefs.map((r) => r.kind === "param-ref" ? r.value : void 0)
1496
- });
1497
- const decodeContext = buildDecodeContext(finalPlan.ast, this.contractCodecs);
1498
- const paramMetadata = deriveParamMetadata(finalPlan.ast);
1499
- const internals = Object.freeze({
1500
- sql: lowered.sql,
1501
- ast: finalPlan.ast,
1502
- meta: finalPlan.meta,
1503
- slots: lowered.params,
1504
- decodeContext,
1505
- paramMetadata
1506
- });
1507
- return blindCast(finalPlan.ast.kind === "raw-query" && finalPlan.ast.result.kind === "affected-count" ? new PreparedExecutionImpl(internals) : new PreparedStatementImpl(internals));
1508
- }
1509
- /** Query prepared rows against a caller-supplied queryable through the full pipeline. */
1510
- runPreparedQueryAgainstQueryable(ps, userParams, queryable, options) {
1511
- this.ensureCodecRegistryValidated();
1512
- const self = this;
1513
- const { codecCtx, middlewareCtx: execMiddlewareCtx } = this.createQueryContexts(options);
1514
- const generator = async function* () {
1515
- checkAborted(codecCtx, "stream");
1516
- const preEncodeValues = resolvePreparedSlotValues(ps, userParams);
1517
- const preEncodeExec = {
1518
- sql: ps.sql,
1519
- params: preEncodeValues,
1520
- ast: ps.ast,
1521
- meta: ps.meta
1522
- };
1523
- const mutator = createSqlParamRefMutator(preEncodeExec);
1524
- await runBeforeQueryChain(preEncodeExec, self.middleware, execMiddlewareCtx, mutator);
1525
- const encodedParams = await encodeParamsWithMetadata(mutator.currentParams(), ps.paramMetadata, codecCtx, self.contractCodecs);
1526
- const exec = {
1527
- sql: ps.sql,
1528
- params: encodedParams,
1529
- ast: ps.ast,
1530
- meta: ps.meta
1531
- };
1532
- const handles = self.#preparedStatementHandles;
1533
- const request = {
1534
- sql: exec.sql,
1535
- params: exec.params,
1536
- preparedStatementHandle: {
1537
- get: () => handles.get(ps),
1538
- set: (value) => {
1539
- handles.set(ps, value);
1540
- }
1541
- }
1542
- };
1543
- yield* self.streamRows(exec, ps.decodeContext, () => queryable.query(request), codecCtx, execMiddlewareCtx);
1544
- };
1545
- return new AsyncIterableResult(generator());
1546
- }
1547
- /** Execute a prepared statement's statistics against a caller-supplied queryable through the full pipeline. */
1548
- async runPreparedExecuteAgainstQueryable(ps, userParams, queryable, options) {
1549
- this.ensureCodecRegistryValidated();
1550
- const { codecCtx, middlewareCtx } = this.createQueryContexts(options);
1551
- checkAborted(codecCtx, "stream");
1552
- const preEncodeValues = resolvePreparedSlotValues(ps, userParams);
1553
- const preEncodeExec = {
1554
- sql: ps.sql,
1555
- params: preEncodeValues,
1556
- ast: ps.ast,
1557
- meta: ps.meta
1558
- };
1559
- const mutator = createSqlParamRefMutator(preEncodeExec);
1560
- await runBeforeExecuteChain(preEncodeExec, this.middleware, middlewareCtx, mutator);
1561
- const exec = {
1562
- sql: ps.sql,
1563
- params: await encodeParamsWithMetadata(mutator.currentParams(), ps.paramMetadata, codecCtx, this.contractCodecs),
1564
- ast: ps.ast,
1565
- meta: ps.meta
1566
- };
1567
- await this.setupDriverExecution(exec);
1568
- checkAborted(codecCtx, "stream");
1569
- const handles = this.#preparedStatementHandles;
1570
- const request = {
1571
- sql: exec.sql,
1572
- params: exec.params,
1573
- preparedStatementHandle: {
1574
- get: () => handles.get(ps),
1575
- set: (value) => {
1576
- handles.set(ps, value);
1577
- }
1578
- }
1579
- };
1580
- const startedAt = Date.now();
1581
- let outcome = "success";
1582
- try {
1583
- return await runExecuteWithMiddleware(exec, this.middleware, middlewareCtx, () => queryable.execute(request));
1584
- } catch (error) {
1585
- outcome = "runtime-error";
1586
- throw error;
1587
- } finally {
1588
- this.recordTelemetry(exec, outcome, Date.now() - startedAt);
1589
- }
1590
- }
1591
- async connection() {
1592
- const driverConn = await this.driver.acquireConnection();
1593
- const self = this;
1594
- return {
1595
- async transaction() {
1596
- const driverTx = await driverConn.beginTransaction();
1597
- return self.wrapTransaction(driverTx);
1598
- },
1599
- async release() {
1600
- await driverConn.release();
1601
- },
1602
- async destroy(reason) {
1603
- await driverConn.destroy(reason);
1604
- },
1605
- query(plan, options) {
1606
- return self.queryAgainstQueryable(plan, driverConn, {
1607
- ...options,
1608
- scope: "connection"
1609
- });
1610
- },
1611
- execute(plan, options) {
1612
- return self.executeStatisticsAgainstQueryable(plan, driverConn, {
1613
- ...options,
1614
- scope: "connection"
1615
- });
1616
- },
1617
- [preparedStatementQuery](ps, params, options) {
1618
- return self.runPreparedQueryAgainstQueryable(blindCast(ps), params, driverConn, {
1619
- ...options,
1620
- scope: "connection"
1621
- });
1622
- },
1623
- [preparedStatementExecute](ps, params, options) {
1624
- return self.runPreparedExecuteAgainstQueryable(blindCast(ps), params, driverConn, {
1625
- ...options,
1626
- scope: "connection"
1627
- });
1628
- }
1629
- };
1630
- }
1631
- wrapTransaction(driverTx) {
1632
- const self = this;
1633
- return {
1634
- async commit() {
1635
- await driverTx.commit();
1636
- },
1637
- async rollback() {
1638
- await driverTx.rollback();
1639
- },
1640
- query(plan, options) {
1641
- return self.queryAgainstQueryable(plan, driverTx, {
1642
- ...options,
1643
- scope: "transaction"
1644
- });
1645
- },
1646
- execute(plan, options) {
1647
- return self.executeStatisticsAgainstQueryable(plan, driverTx, {
1648
- ...options,
1649
- scope: "transaction"
1650
- });
1651
- },
1652
- [preparedStatementQuery](ps, params, options) {
1653
- return self.runPreparedQueryAgainstQueryable(blindCast(ps), params, driverTx, {
1654
- ...options,
1655
- scope: "transaction"
1656
- });
1657
- },
1658
- [preparedStatementExecute](ps, params, options) {
1659
- return self.runPreparedExecuteAgainstQueryable(blindCast(ps), params, driverTx, {
1660
- ...options,
1661
- scope: "transaction"
1662
- });
1663
- }
1664
- };
1665
- }
1666
- telemetry() {
1667
- return this._telemetry;
1668
- }
1669
- async close() {
1670
- await this.driver.close();
1671
- }
1672
- ensureCodecRegistryValidated() {
1673
- if (!this.codecRegistryValidated) {
1674
- validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);
1675
- this.codecRegistryValidated = true;
1676
- }
1677
- }
1678
- async verifyMarker() {
1679
- const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);
1680
- const expectedStorageHash = this.contract.storage.storageHash;
1681
- const expectedProfileHash = this.contract.profileHash ?? null;
1682
- const expected = {
1683
- storageHash: expectedStorageHash,
1684
- profileHash: expectedProfileHash
1685
- };
1686
- if (readResult.kind !== "present") {
1687
- this.sqlCtx.log.warn({
1688
- code: "CONTRACT.MARKER_MISSING",
1689
- scope: "marker-verification",
1690
- expected,
1691
- actual: null,
1692
- message: "Contract marker not found in database"
1693
- });
1694
- return;
1695
- }
1696
- const marker = readResult.record;
1697
- const storageHashMatch = marker.storageHash === expectedStorageHash;
1698
- const profileHashMatch = expectedProfileHash === null || marker.profileHash === expectedProfileHash;
1699
- if (!storageHashMatch || !profileHashMatch) this.sqlCtx.log.warn({
1700
- code: "CONTRACT.MARKER_MISMATCH",
1701
- scope: "marker-verification",
1702
- expected,
1703
- actual: {
1704
- storageHash: marker.storageHash,
1705
- profileHash: marker.profileHash ?? null
1706
- },
1707
- message: "Contract marker hash does not match runtime contract"
1708
- });
1709
- }
1710
- recordTelemetry(plan, outcome, durationMs) {
1711
- const contract = this.contract;
1712
- this._telemetry = Object.freeze({
1713
- lane: plan.meta.lane,
1714
- target: contract.target,
1715
- fingerprint: computeSqlFingerprint(plan.sql),
1716
- outcome,
1717
- ...durationMs !== void 0 ? { durationMs } : {}
1718
- });
1719
- }
1720
- };
1721
- function transactionClosedError() {
1722
- return runtimeError("RUNTIME.TRANSACTION_CLOSED", "Cannot use a transaction operation after the transaction has ended. Consume query results and await execute calls inside the transaction callback.", {});
1723
- }
1724
- async function withTransaction(runtime, fn) {
1725
- const connection = await runtime.connection();
1726
- const transaction = await connection.transaction();
1727
- let invalidated = false;
1728
- async function* guardedStream(inner) {
1729
- if (invalidated) throw transactionClosedError();
1730
- for await (const row of inner) {
1731
- yield row;
1732
- if (invalidated) throw transactionClosedError();
1733
- }
1734
- }
1735
- const txContext = {
1736
- get invalidated() {
1737
- return invalidated;
1738
- },
1739
- query(plan, options) {
1740
- if (invalidated) throw transactionClosedError();
1741
- return new AsyncIterableResult(guardedStream(transaction.query(plan, options)));
1742
- },
1743
- async execute(plan, options) {
1744
- if (invalidated) throw transactionClosedError();
1745
- return transaction.execute(plan, options);
1746
- },
1747
- [preparedStatementQuery](ps, params, options) {
1748
- if (invalidated) throw transactionClosedError();
1749
- return new AsyncIterableResult(guardedStream(runPreparedQuery(transaction, ps, params, options)));
1750
- },
1751
- [preparedStatementExecute](ps, params, options) {
1752
- if (invalidated) throw transactionClosedError();
1753
- return runPreparedExecute(transaction, ps, params, options);
1754
- }
1755
- };
1756
- let connectionDisposed = false;
1757
- const destroyConnection = async (reason) => {
1758
- if (connectionDisposed) return;
1759
- connectionDisposed = true;
1760
- await connection.destroy(reason).catch(() => void 0);
1761
- };
1762
- try {
1763
- let result;
1764
- try {
1765
- result = await fn(txContext);
1766
- } catch (error) {
1767
- try {
1768
- await transaction.rollback();
1769
- } catch (rollbackError) {
1770
- await destroyConnection(rollbackError);
1771
- const wrapped = runtimeError("RUNTIME.TRANSACTION_ROLLBACK_FAILED", "Transaction rollback failed after callback error", { rollbackError });
1772
- wrapped.cause = error;
1773
- throw wrapped;
1774
- }
1775
- throw error;
1776
- } finally {
1777
- invalidated = true;
1778
- }
1779
- try {
1780
- await transaction.commit();
1781
- } catch (commitError) {
1782
- try {
1783
- await transaction.rollback();
1784
- } catch {
1785
- await destroyConnection(commitError);
1786
- }
1787
- const wrapped = runtimeError("RUNTIME.TRANSACTION_COMMIT_FAILED", "Transaction commit failed", { commitError });
1788
- wrapped.cause = commitError;
1789
- throw wrapped;
1790
- }
1791
- return result;
1792
- } finally {
1793
- if (!connectionDisposed) await connection.release();
1794
- }
1795
- }
1796
- //#endregion
1797
- export { PreparedExecutionImpl, PreparedStatementImpl, SqlRuntimeBase, budgets, createAstCodecRegistry, createExecutionContext, createSqlExecutionStack, deriveParamMetadata, encodeParamsWithMetadata, extractCodecIds, lints, lowerSqlPlan, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction };
1798
-
1799
- //# sourceMappingURL=runtime.mjs.map
1
+ import { C as withTransactionMembers, S as withTransaction, _ as lowerSqlPlan, a as budgets, b as validateCodecRegistryCompleteness, c as createSqlExecutionStack, d as deriveParamMetadata, f as encodeParamsWithMetadata, g as lints, h as lazyActivitySource, i as activitySource, l as createToSql, m as findActivitySource, n as PreparedStatementImpl, o as createAstCodecRegistry, p as extractCodecIds, r as SqlRuntimeBase, s as createExecutionContext, t as PreparedExecutionImpl, u as delegatingActivitySource, v as planContentHashOn, x as validateContractCodecMappings, y as startActivityOn } from "./exports-C3wGYtID-D65DEUTC.mjs";
2
+ export { PreparedExecutionImpl, PreparedStatementImpl, SqlRuntimeBase, activitySource, budgets, createAstCodecRegistry, createExecutionContext, createSqlExecutionStack, createToSql, delegatingActivitySource, deriveParamMetadata, encodeParamsWithMetadata, extractCodecIds, findActivitySource, lazyActivitySource, lints, lowerSqlPlan, planContentHashOn, startActivityOn, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, withTransactionMembers };