@madarco/agentbox 0.27.1 → 0.28.0-nightly.202607251721

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 (364) hide show
  1. package/CHANGELOG.md +87 -4
  2. package/README.md +7 -3
  3. package/dist/_cloud-attach-XZYF324R.js +26 -0
  4. package/dist/admin-client-NOZ5CCAH.js +15 -0
  5. package/dist/chunk-2VW37PW4.js +1694 -0
  6. package/dist/chunk-2VW37PW4.js.map +1 -0
  7. package/dist/{chunk-HR7NHH5J.js → chunk-3UMM4VJH.js} +808 -57
  8. package/dist/chunk-3UMM4VJH.js.map +1 -0
  9. package/dist/chunk-5U5QOFL5.js +20 -0
  10. package/dist/chunk-5U5QOFL5.js.map +1 -0
  11. package/dist/chunk-6P6D77QP.js +285 -0
  12. package/dist/chunk-6P6D77QP.js.map +1 -0
  13. package/dist/chunk-6V366IZC.js +2892 -0
  14. package/dist/chunk-6V366IZC.js.map +1 -0
  15. package/dist/{chunk-KWOEUFVA.js → chunk-7J6G526Q.js} +6 -14
  16. package/dist/{chunk-KWOEUFVA.js.map → chunk-7J6G526Q.js.map} +1 -1
  17. package/dist/{chunk-IDH5A4RR.js → chunk-AYPAYY5R.js} +17 -4
  18. package/dist/chunk-AYPAYY5R.js.map +1 -0
  19. package/dist/{chunk-JGZSA5ZI.js → chunk-BHJCMTHP.js} +58 -15
  20. package/dist/chunk-BHJCMTHP.js.map +1 -0
  21. package/dist/{chunk-26IKZRTT.js → chunk-BLWAWGFX.js} +297 -1217
  22. package/dist/chunk-BLWAWGFX.js.map +1 -0
  23. package/dist/chunk-CGPUFXET.js +95 -0
  24. package/dist/chunk-CGPUFXET.js.map +1 -0
  25. package/dist/{chunk-SJ75AIA2.js → chunk-D6AODRNA.js} +12 -9
  26. package/dist/{chunk-SJ75AIA2.js.map → chunk-D6AODRNA.js.map} +1 -1
  27. package/dist/chunk-DPJMEG7U.js +11 -0
  28. package/dist/chunk-DPJMEG7U.js.map +1 -0
  29. package/dist/chunk-E2ITEZAQ.js +148 -0
  30. package/dist/chunk-E2ITEZAQ.js.map +1 -0
  31. package/dist/{chunk-JE6UI5YR.js → chunk-NKVCIH6N.js} +89 -223
  32. package/dist/chunk-NKVCIH6N.js.map +1 -0
  33. package/dist/chunk-OEYAVBA6.js +120 -0
  34. package/dist/chunk-OEYAVBA6.js.map +1 -0
  35. package/dist/{chunk-UJEH2NJT.js → chunk-PXYPQ5BO.js} +64 -264
  36. package/dist/chunk-PXYPQ5BO.js.map +1 -0
  37. package/dist/chunk-QESXSSO6.js +670 -0
  38. package/dist/chunk-QESXSSO6.js.map +1 -0
  39. package/dist/{chunk-NEF6MDJO.js → chunk-QJCK2AFX.js} +128 -26
  40. package/dist/chunk-QJCK2AFX.js.map +1 -0
  41. package/dist/chunk-RUJJY23M.js +84 -0
  42. package/dist/chunk-RUJJY23M.js.map +1 -0
  43. package/dist/{chunk-LL7NCMUU.js → chunk-SKNJRYM5.js} +7 -13
  44. package/dist/chunk-SKNJRYM5.js.map +1 -0
  45. package/dist/chunk-WFGAMJ5Q.js +689 -0
  46. package/dist/chunk-WFGAMJ5Q.js.map +1 -0
  47. package/dist/chunk-ZJL56TJD.js +1444 -0
  48. package/dist/chunk-ZJL56TJD.js.map +1 -0
  49. package/dist/{chunk-V5XXJH63.js → chunk-ZXOP4LBG.js} +5 -8
  50. package/dist/chunk-ZXOP4LBG.js.map +1 -0
  51. package/dist/control-plane-2VEM2KCL.js +31 -0
  52. package/dist/custody-client-P6XIXHRG.js +16 -0
  53. package/dist/{dist-TSFVB7AI.js → dist-2SYQI5S2.js} +11 -7
  54. package/dist/dist-2SYQI5S2.js.map +1 -0
  55. package/dist/{dist-KQTMCVME.js → dist-6QZMZEL7.js} +18 -11
  56. package/dist/dist-6QZMZEL7.js.map +1 -0
  57. package/dist/{dist-FTKS2GI4.js → dist-JHMILJUT.js} +10 -6
  58. package/dist/{dist-OO52HARR.js → dist-JOFZOZCY.js} +41 -25
  59. package/dist/{dist-O3LKOIE7.js → dist-KZ2GEEEX.js} +11 -7
  60. package/dist/dist-KZ2GEEEX.js.map +1 -0
  61. package/dist/{dist-Z6L5MM5D.js → dist-Q5NY4CF6.js} +10 -6
  62. package/dist/{dist-U2SVLJUQ.js → dist-SKMNEDVW.js} +8 -2
  63. package/dist/dist-SKMNEDVW.js.map +1 -0
  64. package/dist/dist-SRCKO7ZV.js +197 -0
  65. package/dist/dist-SRCKO7ZV.js.map +1 -0
  66. package/dist/{dist-WVYAURMF.js → dist-UXZQWKY6.js} +10 -6
  67. package/dist/dist-UXZQWKY6.js.map +1 -0
  68. package/dist/env-file-UDUDQMP4.js +11 -0
  69. package/dist/env-file-UDUDQMP4.js.map +1 -0
  70. package/dist/hub-adopt-ZS5CREYF.js +21 -0
  71. package/dist/hub-adopt-ZS5CREYF.js.map +1 -0
  72. package/dist/index.js +2461 -1905
  73. package/dist/index.js.map +1 -1
  74. package/dist/node-postgres-6JUOVUN5.js +3584 -0
  75. package/dist/node-postgres-6JUOVUN5.js.map +1 -0
  76. package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js → prepared-state-75DIZ55S-P6LE4N64.js} +3 -2
  77. package/dist/prepared-state-75DIZ55S-P6LE4N64.js.map +1 -0
  78. package/dist/remote-hub-SJ4XWBA5.js +9 -0
  79. package/dist/remote-hub-SJ4XWBA5.js.map +1 -0
  80. package/dist/sqlite-proxy-53E5D2VM.js +2882 -0
  81. package/dist/sqlite-proxy-53E5D2VM.js.map +1 -0
  82. package/package.json +1 -1
  83. package/runtime/_shared/ctl.cjs +29199 -16813
  84. package/runtime/digitalocean/ctl.cjs +29199 -16813
  85. package/runtime/docker/packages/ctl/dist/bin.cjs +29199 -16813
  86. package/runtime/e2b/ctl.cjs +29199 -16813
  87. package/runtime/hetzner/ctl.cjs +29199 -16813
  88. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  89. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  90. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
  91. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
  92. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  93. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  94. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
  95. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  96. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
  97. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  98. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
  99. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  100. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
  101. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  102. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
  103. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  104. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  105. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  106. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  107. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  108. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
  109. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  110. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  111. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +4 -4
  113. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
  115. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
  117. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +2 -2
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +2 -2
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +2 -2
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +2 -2
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +2 -2
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  159. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -2
  160. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  161. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  162. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  163. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  164. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  165. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  166. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  167. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  168. package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +3 -0
  169. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0gvv4ct._.js +4 -0
  170. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0pn9b49._.js +4 -0
  171. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_145bz8z._.js +9 -0
  172. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_14y990b._.js +3 -0
  173. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_1nl4l3q._.js +3 -0
  174. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_sqlite-proxy_index_05v_j5r.js +15 -0
  175. package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__12m3qoa._.js → [externals]__0f3aqcx._.js} +2 -2
  176. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-9g1s8._.js +3 -0
  177. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-pvfxg._.js +3 -0
  178. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01amzh6._.js +3 -0
  179. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02q799_._.js +3 -0
  180. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__03k22rl._.js +3 -0
  181. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04tqk-j._.js +3 -0
  182. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05ovf1y._.js +3 -0
  183. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05s-_x7._.js +3 -0
  184. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07dnyfi._.js +3 -0
  185. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07zk6qo._.js +3 -0
  186. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_59yi6._.js +3 -0
  187. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ajlo3d._.js +3 -0
  188. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0b5s54n._.js +3 -0
  189. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c4fiez._.js +3 -0
  190. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c9iff1._.js +3 -0
  191. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +5 -5
  192. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dh6lzr._.js +3 -0
  193. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ey83ai._.js +3 -0
  194. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0h6vdvr._.js +3 -0
  195. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lup7p4._.js +3 -0
  196. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0luxuu4._.js +3 -0
  197. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nl2u6u._.js +3 -0
  198. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nonp-6._.js +3 -0
  199. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0oplozy._.js +3 -0
  200. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0p-6wgd._.js +3 -0
  201. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0rcnwbw._.js +3 -0
  202. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tuz1am._.js +3 -0
  203. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +1 -1
  204. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10ry4ss._.js +3 -0
  205. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11hv164._.js +3 -0
  206. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__154_i13._.js +3 -0
  207. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17676rc._.js +3 -0
  208. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bg1alc._.js +3 -0
  209. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cvqb1d._.js +3 -0
  210. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60gbz._.js +3 -0
  211. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dm0jmw._.js +6 -0
  212. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dv_b1t._.js +3 -0
  213. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fzxip4._.js +3 -0
  214. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4oj-e._.js +3 -0
  215. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i4gq_2._.js +3 -0
  216. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v1p7in._.js +3 -0
  217. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9_her._.js +4 -0
  218. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x1jkpb._.js +3 -0
  219. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1yd8n5l._.js +3 -0
  220. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20t_rs8._.js +3 -0
  221. package/runtime/hub/apps/hub/.next/server/chunks/_033w048._.js +1 -1
  222. package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +1 -1
  223. package/runtime/hub/apps/hub/.next/server/chunks/{_0760z6y._.js → _0907rw0._.js} +15 -15
  224. package/runtime/hub/apps/hub/.next/server/chunks/_0f3molr._.js +1 -1
  225. package/runtime/hub/apps/hub/.next/server/chunks/_0lgs9kd._.js +1 -1
  226. package/runtime/hub/apps/hub/.next/server/chunks/_0pyhcqe._.js +1 -1
  227. package/runtime/hub/apps/hub/.next/server/chunks/_1-42ili._.js +1 -1
  228. package/runtime/hub/apps/hub/.next/server/chunks/_11__3wi._.js +1 -1
  229. package/runtime/hub/apps/hub/.next/server/chunks/_12flzuh._.js +1 -1
  230. package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +1 -1
  231. package/runtime/hub/apps/hub/.next/server/chunks/_1rpkqst._.js +1 -1
  232. package/runtime/hub/apps/hub/.next/server/chunks/_1wt72m1._.js +1 -1
  233. package/runtime/hub/apps/hub/.next/server/chunks/_1x3l5t8._.js +1 -1
  234. package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +62 -31
  235. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +1 -1
  236. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_1uccfbf._.js +1 -1
  237. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +1 -1
  238. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +1 -1
  239. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +1 -1
  240. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +1 -1
  241. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +1 -1
  242. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +1 -1
  243. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +1 -1
  244. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +1 -1
  245. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0ebuy19._.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0wxhi0-._.js +3 -0
  247. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0xe4ick._.js +9 -0
  248. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_14oaveu._.js +4 -0
  249. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_sqlite-proxy_index_1a6wfdg.js +15 -0
  250. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0-pm2yl._.js +3 -0
  251. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +1 -1
  252. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +1 -1
  253. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +1 -1
  254. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +1 -1
  255. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +1 -1
  256. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0m1yf2b._.js +4 -0
  257. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0wv-3zo._.js +3 -0
  258. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +1 -1
  259. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +2 -2
  260. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +1 -1
  261. package/runtime/hub/apps/hub/.next/server/chunks/ssr/{_0ro6vh6._.js → _0r2xlss._.js} +3 -3
  262. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_components_1z1p98f._.js +1 -1
  263. package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +2 -25
  264. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  265. package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
  266. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  267. package/runtime/hub/apps/hub/.next/static/chunks/{2xc1sm79a6tsb.js → 2gsrna76i1d80.js} +1 -1
  268. package/runtime/hub/apps/hub/attach-helper.cjs +191 -0
  269. package/runtime/hub/apps/hub/{auth-DC44GQZY.js → auth-IRNNO3IK.js} +2 -2
  270. package/runtime/hub/apps/hub/{auth-config-LALRDYDO.js → auth-config-WJHIMGUE.js} +4 -2
  271. package/runtime/hub/apps/hub/{chunk-YJ5MJOXK.js → chunk-4LYVBRBC.js} +2094 -220
  272. package/runtime/hub/apps/hub/chunk-6AVSKCZJ.js +669 -0
  273. package/runtime/hub/apps/hub/{chunk-QSMPSV5Z.js → chunk-A5Y7LJMU.js} +57 -14
  274. package/runtime/hub/apps/hub/chunk-EDRFXO2M.js +35 -0
  275. package/runtime/hub/apps/hub/chunk-F2JI4GMX.js +2891 -0
  276. package/runtime/hub/apps/hub/{chunk-EHBJKZCL.js → chunk-O3K3ZGFF.js} +500 -35
  277. package/runtime/hub/apps/hub/chunk-RII6IKNJ.js +688 -0
  278. package/runtime/hub/apps/hub/{chunk-RXYOWSSN.js → chunk-RMEUA6PA.js} +120 -14
  279. package/runtime/hub/apps/hub/{chunk-3FJNKSNZ.js → chunk-SCHQR5KR.js} +3 -1
  280. package/runtime/hub/apps/hub/{dist-6FPPUSWZ.js → dist-2GEAA7QA.js} +15 -3
  281. package/runtime/hub/apps/hub/{dist-JG45OFT2.js → dist-36O6F6M3.js} +39 -24
  282. package/runtime/hub/apps/hub/{dist-3I7KUI6W.js → dist-IWLEL2TO.js} +21 -24
  283. package/runtime/hub/apps/hub/{dist-G6TXUSPZ.js → dist-NYKIT5W5.js} +10 -11
  284. package/runtime/hub/apps/hub/{dist-EQV4L7KP.js → dist-QB2IJ7OD.js} +7 -1
  285. package/runtime/hub/apps/hub/{dist-LYDHYTP2.js → dist-RBBXXGLI.js} +129 -26
  286. package/runtime/hub/apps/hub/{dist-GTVVXCBP.js → dist-RRJN2U5P.js} +10 -14
  287. package/runtime/hub/apps/hub/{dist-DX6IYMAH.js → dist-UWXGDCK4.js} +14 -11
  288. package/runtime/hub/apps/hub/{hub-token-COBZGSLS.js → hub-token-6USIMBPQ.js} +2 -2
  289. package/runtime/hub/apps/hub/hub-worker-SOFWVTWU.js +215 -0
  290. package/runtime/hub/apps/hub/node-postgres-DIU2H5VP.js +3583 -0
  291. package/runtime/hub/apps/hub/package.json +5 -2
  292. package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-2IFNUHHM.js → prepared-state-75DIZ55S-P5FHEORG.js} +1 -1
  293. package/runtime/hub/apps/hub/server.js +247 -66
  294. package/runtime/hub/apps/hub/sqlite-proxy-VJS3HIOV.js +2881 -0
  295. package/runtime/relay/bin.cjs +694 -13
  296. package/runtime/vercel/ctl.cjs +29199 -16813
  297. package/dist/_cloud-attach-WDGM6FL5.js +0 -19
  298. package/dist/chunk-26IKZRTT.js.map +0 -1
  299. package/dist/chunk-HR7NHH5J.js.map +0 -1
  300. package/dist/chunk-IDH5A4RR.js.map +0 -1
  301. package/dist/chunk-JE6UI5YR.js.map +0 -1
  302. package/dist/chunk-JGZSA5ZI.js.map +0 -1
  303. package/dist/chunk-LL7NCMUU.js.map +0 -1
  304. package/dist/chunk-NEF6MDJO.js.map +0 -1
  305. package/dist/chunk-UJEH2NJT.js.map +0 -1
  306. package/dist/chunk-V5XXJH63.js.map +0 -1
  307. package/dist/dist-KQTMCVME.js.map +0 -1
  308. package/dist/dist-O3LKOIE7.js.map +0 -1
  309. package/dist/dist-TSFVB7AI.js.map +0 -1
  310. package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +0 -3
  311. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04h15ml._.js +0 -3
  312. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04jgk9x._.js +0 -3
  313. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07ednlo._.js +0 -3
  314. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +0 -3
  315. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ig1bot._.js +0 -3
  316. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +0 -3
  317. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ql4fjo._.js +0 -3
  318. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0szd4sh._.js +0 -3
  319. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t7o5ed._.js +0 -3
  320. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vs8fma._.js +0 -3
  321. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w9ud8u._.js +0 -3
  322. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.js +0 -3
  323. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yhb0gc._.js +0 -3
  324. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-0flwc._.js +0 -3
  325. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13ioh5z._.js +0 -3
  326. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13jwk_k._.js +0 -3
  327. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16_uteg._.js +0 -3
  328. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16p2m-g._.js +0 -3
  329. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19pc87s._.js +0 -3
  330. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_gu2yk._.js +0 -3
  331. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1a50b07._.js +0 -3
  332. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ai-945._.js +0 -3
  333. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bu2zio._.js +0 -3
  334. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ctczev._.js +0 -3
  335. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d6mtlk._.js +0 -3
  336. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dn_3i1._.js +0 -3
  337. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1e4z_-v._.js +0 -3
  338. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f2sueq._.js +0 -3
  339. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f9zctr._.js +0 -3
  340. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +0 -3
  341. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +0 -3
  342. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1js2jdv._.js +0 -3
  343. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +0 -3
  344. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mttufy._.js +0 -3
  345. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1nepkp-._.js +0 -6
  346. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1pp5oib._.js +0 -3
  347. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q5bqse._.js +0 -3
  348. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qwhzmi._.js +0 -3
  349. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thipug._.js +0 -3
  350. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9om6g._.js +0 -3
  351. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xeczo7._.js +0 -3
  352. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20503l7._.js +0 -3
  353. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_20c820g._.js +0 -3
  354. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0j0tjwn._.js +0 -3
  355. /package/dist/{_cloud-attach-WDGM6FL5.js.map → _cloud-attach-XZYF324R.js.map} +0 -0
  356. /package/dist/{dist-FTKS2GI4.js.map → admin-client-NOZ5CCAH.js.map} +0 -0
  357. /package/dist/{dist-OO52HARR.js.map → control-plane-2VEM2KCL.js.map} +0 -0
  358. /package/dist/{dist-U2SVLJUQ.js.map → custody-client-P6XIXHRG.js.map} +0 -0
  359. /package/dist/{dist-WVYAURMF.js.map → dist-JHMILJUT.js.map} +0 -0
  360. /package/dist/{dist-Z6L5MM5D.js.map → dist-JOFZOZCY.js.map} +0 -0
  361. /package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js.map → dist-Q5NY4CF6.js.map} +0 -0
  362. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_buildManifest.js +0 -0
  363. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_clientMiddlewareManifest.js +0 -0
  364. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_ssgManifest.js +0 -0
@@ -0,0 +1,3584 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CasingCache,
4
+ DefaultLogger,
5
+ DrizzleError,
6
+ DrizzleQueryError,
7
+ Many,
8
+ NoopCache,
9
+ NoopLogger,
10
+ One,
11
+ QueryPromise,
12
+ SelectionProxyHandler,
13
+ TransactionRollbackError,
14
+ TypedQueryBuilder,
15
+ aliasedTable,
16
+ aliasedTableColumn,
17
+ createTableRelationsHelpers,
18
+ extractTablesRelationalConfig,
19
+ getOperators,
20
+ getOrderByOperators,
21
+ hashQuery,
22
+ mapColumnsInAliasedSQLToAlias,
23
+ mapColumnsInSQLToAlias,
24
+ mapRelationalRow,
25
+ normalizeRelation
26
+ } from "./chunk-WFGAMJ5Q.js";
27
+ import {
28
+ Column,
29
+ Columns,
30
+ Param,
31
+ PgColumn,
32
+ PgDate,
33
+ PgDateString,
34
+ PgJson,
35
+ PgJsonb,
36
+ PgNumeric,
37
+ PgTable,
38
+ PgTime,
39
+ PgTimestamp,
40
+ PgTimestampString,
41
+ PgUUID,
42
+ SQL,
43
+ Schema,
44
+ Subquery,
45
+ Table,
46
+ View,
47
+ ViewBaseConfig,
48
+ WithSubquery,
49
+ and,
50
+ applyMixins,
51
+ entityKind,
52
+ eq,
53
+ fillPlaceholders,
54
+ getTableColumns,
55
+ getTableLikeName,
56
+ getTableName,
57
+ getTableUniqueName,
58
+ haveSameKeys,
59
+ is,
60
+ isConfig,
61
+ mapResultRow,
62
+ mapUpdateSet,
63
+ orderSelectedFields,
64
+ sql,
65
+ tracer
66
+ } from "./chunk-6V366IZC.js";
67
+ import "./chunk-WJFZJZIM.js";
68
+
69
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/node-postgres/driver.js
70
+ import pg2 from "pg";
71
+
72
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/view-base.js
73
+ var PgViewBase = class extends View {
74
+ static [entityKind] = "PgViewBase";
75
+ };
76
+
77
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/dialect.js
78
+ var PgDialect = class {
79
+ static [entityKind] = "PgDialect";
80
+ /** @internal */
81
+ casing;
82
+ constructor(config) {
83
+ this.casing = new CasingCache(config?.casing);
84
+ }
85
+ async migrate(migrations, session, config) {
86
+ const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
87
+ const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
88
+ const migrationTableCreate = sql`
89
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
90
+ id SERIAL PRIMARY KEY,
91
+ hash text NOT NULL,
92
+ created_at bigint
93
+ )
94
+ `;
95
+ await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
96
+ await session.execute(migrationTableCreate);
97
+ const dbMigrations = await session.all(
98
+ sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
99
+ );
100
+ const lastDbMigration = dbMigrations[0];
101
+ await session.transaction(async (tx) => {
102
+ for await (const migration of migrations) {
103
+ if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
104
+ for (const stmt of migration.sql) {
105
+ await tx.execute(sql.raw(stmt));
106
+ }
107
+ await tx.execute(
108
+ sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
109
+ );
110
+ }
111
+ }
112
+ });
113
+ }
114
+ escapeName(name) {
115
+ return `"${name.replace(/"/g, '""')}"`;
116
+ }
117
+ escapeParam(num) {
118
+ return `$${num + 1}`;
119
+ }
120
+ escapeString(str) {
121
+ return `'${str.replace(/'/g, "''")}'`;
122
+ }
123
+ buildWithCTE(queries) {
124
+ if (!queries?.length) return void 0;
125
+ const withSqlChunks = [sql`with `];
126
+ for (const [i, w] of queries.entries()) {
127
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
128
+ if (i < queries.length - 1) {
129
+ withSqlChunks.push(sql`, `);
130
+ }
131
+ }
132
+ withSqlChunks.push(sql` `);
133
+ return sql.join(withSqlChunks);
134
+ }
135
+ buildDeleteQuery({ table, where, returning, withList }) {
136
+ const withSql = this.buildWithCTE(withList);
137
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
138
+ const whereSql = where ? sql` where ${where}` : void 0;
139
+ return sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
140
+ }
141
+ buildUpdateSet(table, set) {
142
+ const tableColumns = table[Table.Symbol.Columns];
143
+ const columnNames = Object.keys(tableColumns).filter(
144
+ (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
145
+ );
146
+ const setSize = columnNames.length;
147
+ return sql.join(columnNames.flatMap((colName, i) => {
148
+ const col = tableColumns[colName];
149
+ const onUpdateFnResult = col.onUpdateFn?.();
150
+ const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
151
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
152
+ if (i < setSize - 1) {
153
+ return [res, sql.raw(", ")];
154
+ }
155
+ return [res];
156
+ }));
157
+ }
158
+ buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
159
+ const withSql = this.buildWithCTE(withList);
160
+ const tableName = table[PgTable.Symbol.Name];
161
+ const tableSchema = table[PgTable.Symbol.Schema];
162
+ const origTableName = table[PgTable.Symbol.OriginalName];
163
+ const alias = tableName === origTableName ? void 0 : tableName;
164
+ const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
165
+ const setSql = this.buildUpdateSet(table, set);
166
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
167
+ const joinsSql = this.buildJoins(joins);
168
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
169
+ const whereSql = where ? sql` where ${where}` : void 0;
170
+ return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
171
+ }
172
+ /**
173
+ * Builds selection SQL with provided fields/expressions
174
+ *
175
+ * Examples:
176
+ *
177
+ * `select <selection> from`
178
+ *
179
+ * `insert ... returning <selection>`
180
+ *
181
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
182
+ */
183
+ buildSelection(fields, { isSingleTable = false } = {}) {
184
+ const columnsLen = fields.length;
185
+ const chunks = fields.flatMap(({ field }, i) => {
186
+ const chunk = [];
187
+ if (is(field, SQL.Aliased) && field.isSelectionField) {
188
+ chunk.push(sql.identifier(field.fieldAlias));
189
+ } else if (is(field, SQL.Aliased) || is(field, SQL)) {
190
+ const query = is(field, SQL.Aliased) ? field.sql : field;
191
+ if (isSingleTable) {
192
+ chunk.push(
193
+ new SQL(
194
+ query.queryChunks.map((c) => {
195
+ if (is(c, PgColumn)) {
196
+ return sql.identifier(this.casing.getColumnCasing(c));
197
+ }
198
+ return c;
199
+ })
200
+ )
201
+ );
202
+ } else {
203
+ chunk.push(query);
204
+ }
205
+ if (is(field, SQL.Aliased)) {
206
+ chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
207
+ }
208
+ } else if (is(field, Column)) {
209
+ if (isSingleTable) {
210
+ chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
211
+ } else {
212
+ chunk.push(field);
213
+ }
214
+ } else if (is(field, Subquery)) {
215
+ const entries = Object.entries(field._.selectedFields);
216
+ if (entries.length === 1) {
217
+ const entry = entries[0][1];
218
+ const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
219
+ if (fieldDecoder) {
220
+ field._.sql.decoder = fieldDecoder;
221
+ }
222
+ }
223
+ chunk.push(field);
224
+ }
225
+ if (i < columnsLen - 1) {
226
+ chunk.push(sql`, `);
227
+ }
228
+ return chunk;
229
+ });
230
+ return sql.join(chunks);
231
+ }
232
+ buildJoins(joins) {
233
+ if (!joins || joins.length === 0) {
234
+ return void 0;
235
+ }
236
+ const joinsArray = [];
237
+ for (const [index, joinMeta] of joins.entries()) {
238
+ if (index === 0) {
239
+ joinsArray.push(sql` `);
240
+ }
241
+ const table = joinMeta.table;
242
+ const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
243
+ const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
244
+ if (is(table, PgTable)) {
245
+ const tableName = table[PgTable.Symbol.Name];
246
+ const tableSchema = table[PgTable.Symbol.Schema];
247
+ const origTableName = table[PgTable.Symbol.OriginalName];
248
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
249
+ joinsArray.push(
250
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
251
+ );
252
+ } else if (is(table, View)) {
253
+ const viewName = table[ViewBaseConfig].name;
254
+ const viewSchema = table[ViewBaseConfig].schema;
255
+ const origViewName = table[ViewBaseConfig].originalName;
256
+ const alias = viewName === origViewName ? void 0 : joinMeta.alias;
257
+ joinsArray.push(
258
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
259
+ );
260
+ } else {
261
+ joinsArray.push(
262
+ sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`
263
+ );
264
+ }
265
+ if (index < joins.length - 1) {
266
+ joinsArray.push(sql` `);
267
+ }
268
+ }
269
+ return sql.join(joinsArray);
270
+ }
271
+ buildFromTable(table) {
272
+ if (is(table, Table) && table[Table.Symbol.IsAlias]) {
273
+ let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;
274
+ if (table[Table.Symbol.Schema]) {
275
+ fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
276
+ }
277
+ return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
278
+ }
279
+ return table;
280
+ }
281
+ buildSelectQuery({
282
+ withList,
283
+ fields,
284
+ fieldsFlat,
285
+ where,
286
+ having,
287
+ table,
288
+ joins,
289
+ orderBy,
290
+ groupBy,
291
+ limit,
292
+ offset,
293
+ lockingClause,
294
+ distinct,
295
+ setOperators
296
+ }) {
297
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
298
+ for (const f of fieldsList) {
299
+ if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(
300
+ ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])
301
+ ))(f.field.table)) {
302
+ const tableName = getTableName(f.field.table);
303
+ throw new Error(
304
+ `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
305
+ );
306
+ }
307
+ }
308
+ const isSingleTable = !joins || joins.length === 0;
309
+ const withSql = this.buildWithCTE(withList);
310
+ let distinctSql;
311
+ if (distinct) {
312
+ distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
313
+ }
314
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
315
+ const tableSql = this.buildFromTable(table);
316
+ const joinsSql = this.buildJoins(joins);
317
+ const whereSql = where ? sql` where ${where}` : void 0;
318
+ const havingSql = having ? sql` having ${having}` : void 0;
319
+ let orderBySql;
320
+ if (orderBy && orderBy.length > 0) {
321
+ orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
322
+ }
323
+ let groupBySql;
324
+ if (groupBy && groupBy.length > 0) {
325
+ groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
326
+ }
327
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
328
+ const offsetSql = offset ? sql` offset ${offset}` : void 0;
329
+ const lockingClauseSql = sql.empty();
330
+ if (lockingClause) {
331
+ const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
332
+ if (lockingClause.config.of) {
333
+ clauseSql.append(
334
+ sql` of ${sql.join(
335
+ Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
336
+ sql`, `
337
+ )}`
338
+ );
339
+ }
340
+ if (lockingClause.config.noWait) {
341
+ clauseSql.append(sql` nowait`);
342
+ } else if (lockingClause.config.skipLocked) {
343
+ clauseSql.append(sql` skip locked`);
344
+ }
345
+ lockingClauseSql.append(clauseSql);
346
+ }
347
+ const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
348
+ if (setOperators.length > 0) {
349
+ return this.buildSetOperations(finalQuery, setOperators);
350
+ }
351
+ return finalQuery;
352
+ }
353
+ buildSetOperations(leftSelect, setOperators) {
354
+ const [setOperator, ...rest] = setOperators;
355
+ if (!setOperator) {
356
+ throw new Error("Cannot pass undefined values to any set operator");
357
+ }
358
+ if (rest.length === 0) {
359
+ return this.buildSetOperationQuery({ leftSelect, setOperator });
360
+ }
361
+ return this.buildSetOperations(
362
+ this.buildSetOperationQuery({ leftSelect, setOperator }),
363
+ rest
364
+ );
365
+ }
366
+ buildSetOperationQuery({
367
+ leftSelect,
368
+ setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
369
+ }) {
370
+ const leftChunk = sql`(${leftSelect.getSQL()}) `;
371
+ const rightChunk = sql`(${rightSelect.getSQL()})`;
372
+ let orderBySql;
373
+ if (orderBy && orderBy.length > 0) {
374
+ const orderByValues = [];
375
+ for (const singleOrderBy of orderBy) {
376
+ if (is(singleOrderBy, PgColumn)) {
377
+ orderByValues.push(sql.identifier(singleOrderBy.name));
378
+ } else if (is(singleOrderBy, SQL)) {
379
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
380
+ const chunk = singleOrderBy.queryChunks[i];
381
+ if (is(chunk, PgColumn)) {
382
+ singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
383
+ }
384
+ }
385
+ orderByValues.push(sql`${singleOrderBy}`);
386
+ } else {
387
+ orderByValues.push(sql`${singleOrderBy}`);
388
+ }
389
+ }
390
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
391
+ }
392
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
393
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
394
+ const offsetSql = offset ? sql` offset ${offset}` : void 0;
395
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
396
+ }
397
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
398
+ const valuesSqlList = [];
399
+ const columns = table[Table.Symbol.Columns];
400
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
401
+ const insertOrder = colEntries.map(
402
+ ([, column]) => sql.identifier(this.casing.getColumnCasing(column))
403
+ );
404
+ if (select) {
405
+ const select2 = valuesOrSelect;
406
+ if (is(select2, SQL)) {
407
+ valuesSqlList.push(select2);
408
+ } else {
409
+ valuesSqlList.push(select2.getSQL());
410
+ }
411
+ } else {
412
+ const values = valuesOrSelect;
413
+ valuesSqlList.push(sql.raw("values "));
414
+ for (const [valueIndex, value] of values.entries()) {
415
+ const valueList = [];
416
+ for (const [fieldName, col] of colEntries) {
417
+ const colValue = value[fieldName];
418
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
419
+ if (col.defaultFn !== void 0) {
420
+ const defaultFnResult = col.defaultFn();
421
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
422
+ valueList.push(defaultValue);
423
+ } else if (!col.default && col.onUpdateFn !== void 0) {
424
+ const onUpdateFnResult = col.onUpdateFn();
425
+ const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
426
+ valueList.push(newValue);
427
+ } else {
428
+ valueList.push(sql`default`);
429
+ }
430
+ } else {
431
+ valueList.push(colValue);
432
+ }
433
+ }
434
+ valuesSqlList.push(valueList);
435
+ if (valueIndex < values.length - 1) {
436
+ valuesSqlList.push(sql`, `);
437
+ }
438
+ }
439
+ }
440
+ const withSql = this.buildWithCTE(withList);
441
+ const valuesSql = sql.join(valuesSqlList);
442
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
443
+ const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
444
+ const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
445
+ return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
446
+ }
447
+ buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
448
+ const concurrentlySql = concurrently ? sql` concurrently` : void 0;
449
+ const withNoDataSql = withNoData ? sql` with no data` : void 0;
450
+ return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
451
+ }
452
+ prepareTyping(encoder) {
453
+ if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
454
+ return "json";
455
+ } else if (is(encoder, PgNumeric)) {
456
+ return "decimal";
457
+ } else if (is(encoder, PgTime)) {
458
+ return "time";
459
+ } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
460
+ return "timestamp";
461
+ } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
462
+ return "date";
463
+ } else if (is(encoder, PgUUID)) {
464
+ return "uuid";
465
+ } else {
466
+ return "none";
467
+ }
468
+ }
469
+ sqlToQuery(sql2, invokeSource) {
470
+ return sql2.toQuery({
471
+ casing: this.casing,
472
+ escapeName: this.escapeName,
473
+ escapeParam: this.escapeParam,
474
+ escapeString: this.escapeString,
475
+ prepareTyping: this.prepareTyping,
476
+ invokeSource
477
+ });
478
+ }
479
+ // buildRelationalQueryWithPK({
480
+ // fullSchema,
481
+ // schema,
482
+ // tableNamesMap,
483
+ // table,
484
+ // tableConfig,
485
+ // queryConfig: config,
486
+ // tableAlias,
487
+ // isRoot = false,
488
+ // joinOn,
489
+ // }: {
490
+ // fullSchema: Record<string, unknown>;
491
+ // schema: TablesRelationalConfig;
492
+ // tableNamesMap: Record<string, string>;
493
+ // table: PgTable;
494
+ // tableConfig: TableRelationalConfig;
495
+ // queryConfig: true | DBQueryConfig<'many', true>;
496
+ // tableAlias: string;
497
+ // isRoot?: boolean;
498
+ // joinOn?: SQL;
499
+ // }): BuildRelationalQueryResult<PgTable, PgColumn> {
500
+ // // For { "<relation>": true }, return a table with selection of all columns
501
+ // if (config === true) {
502
+ // const selectionEntries = Object.entries(tableConfig.columns);
503
+ // const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
504
+ // [key, value],
505
+ // ) => ({
506
+ // dbKey: value.name,
507
+ // tsKey: key,
508
+ // field: value as PgColumn,
509
+ // relationTableTsKey: undefined,
510
+ // isJson: false,
511
+ // selection: [],
512
+ // }));
513
+ // return {
514
+ // tableTsKey: tableConfig.tsName,
515
+ // sql: table,
516
+ // selection,
517
+ // };
518
+ // }
519
+ // // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
520
+ // // let selectionForBuild = selection;
521
+ // const aliasedColumns = Object.fromEntries(
522
+ // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
523
+ // );
524
+ // const aliasedRelations = Object.fromEntries(
525
+ // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
526
+ // );
527
+ // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
528
+ // let where, hasUserDefinedWhere;
529
+ // if (config.where) {
530
+ // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
531
+ // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
532
+ // hasUserDefinedWhere = !!where;
533
+ // }
534
+ // where = and(joinOn, where);
535
+ // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
536
+ // let joins: Join[] = [];
537
+ // let selectedColumns: string[] = [];
538
+ // // Figure out which columns to select
539
+ // if (config.columns) {
540
+ // let isIncludeMode = false;
541
+ // for (const [field, value] of Object.entries(config.columns)) {
542
+ // if (value === undefined) {
543
+ // continue;
544
+ // }
545
+ // if (field in tableConfig.columns) {
546
+ // if (!isIncludeMode && value === true) {
547
+ // isIncludeMode = true;
548
+ // }
549
+ // selectedColumns.push(field);
550
+ // }
551
+ // }
552
+ // if (selectedColumns.length > 0) {
553
+ // selectedColumns = isIncludeMode
554
+ // ? selectedColumns.filter((c) => config.columns?.[c] === true)
555
+ // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
556
+ // }
557
+ // } else {
558
+ // // Select all columns if selection is not specified
559
+ // selectedColumns = Object.keys(tableConfig.columns);
560
+ // }
561
+ // // for (const field of selectedColumns) {
562
+ // // const column = tableConfig.columns[field]! as PgColumn;
563
+ // // fieldsSelection.push({ tsKey: field, value: column });
564
+ // // }
565
+ // let initiallySelectedRelations: {
566
+ // tsKey: string;
567
+ // queryConfig: true | DBQueryConfig<'many', false>;
568
+ // relation: Relation;
569
+ // }[] = [];
570
+ // // let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
571
+ // // Figure out which relations to select
572
+ // if (config.with) {
573
+ // initiallySelectedRelations = Object.entries(config.with)
574
+ // .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
575
+ // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
576
+ // }
577
+ // const manyRelations = initiallySelectedRelations.filter((r) =>
578
+ // is(r.relation, Many)
579
+ // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
580
+ // );
581
+ // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
582
+ // const isInnermostQuery = manyRelations.length < 2;
583
+ // const selectedExtras: {
584
+ // tsKey: string;
585
+ // value: SQL.Aliased;
586
+ // }[] = [];
587
+ // // Figure out which extras to select
588
+ // if (isInnermostQuery && config.extras) {
589
+ // const extras = typeof config.extras === 'function'
590
+ // ? config.extras(aliasedFields, { sql })
591
+ // : config.extras;
592
+ // for (const [tsKey, value] of Object.entries(extras)) {
593
+ // selectedExtras.push({
594
+ // tsKey,
595
+ // value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
596
+ // });
597
+ // }
598
+ // }
599
+ // // Transform `fieldsSelection` into `selection`
600
+ // // `fieldsSelection` shouldn't be used after this point
601
+ // // for (const { tsKey, value, isExtra } of fieldsSelection) {
602
+ // // selection.push({
603
+ // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
604
+ // // tsKey,
605
+ // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
606
+ // // relationTableTsKey: undefined,
607
+ // // isJson: false,
608
+ // // isExtra,
609
+ // // selection: [],
610
+ // // });
611
+ // // }
612
+ // let orderByOrig = typeof config.orderBy === 'function'
613
+ // ? config.orderBy(aliasedFields, orderByOperators)
614
+ // : config.orderBy ?? [];
615
+ // if (!Array.isArray(orderByOrig)) {
616
+ // orderByOrig = [orderByOrig];
617
+ // }
618
+ // const orderBy = orderByOrig.map((orderByValue) => {
619
+ // if (is(orderByValue, Column)) {
620
+ // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
621
+ // }
622
+ // return mapColumnsInSQLToAlias(orderByValue, tableAlias);
623
+ // });
624
+ // const limit = isInnermostQuery ? config.limit : undefined;
625
+ // const offset = isInnermostQuery ? config.offset : undefined;
626
+ // // For non-root queries without additional config except columns, return a table with selection
627
+ // if (
628
+ // !isRoot
629
+ // && initiallySelectedRelations.length === 0
630
+ // && selectedExtras.length === 0
631
+ // && !where
632
+ // && orderBy.length === 0
633
+ // && limit === undefined
634
+ // && offset === undefined
635
+ // ) {
636
+ // return {
637
+ // tableTsKey: tableConfig.tsName,
638
+ // sql: table,
639
+ // selection: selectedColumns.map((key) => ({
640
+ // dbKey: tableConfig.columns[key]!.name,
641
+ // tsKey: key,
642
+ // field: tableConfig.columns[key] as PgColumn,
643
+ // relationTableTsKey: undefined,
644
+ // isJson: false,
645
+ // selection: [],
646
+ // })),
647
+ // };
648
+ // }
649
+ // const selectedRelationsWithoutPK:
650
+ // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
651
+ // for (
652
+ // const {
653
+ // tsKey: selectedRelationTsKey,
654
+ // queryConfig: selectedRelationConfigValue,
655
+ // relation,
656
+ // } of initiallySelectedRelations
657
+ // ) {
658
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
659
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
660
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
661
+ // const relationTable = schema[relationTableTsName]!;
662
+ // if (relationTable.primaryKey.length > 0) {
663
+ // continue;
664
+ // }
665
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
666
+ // const joinOn = and(
667
+ // ...normalizedRelation.fields.map((field, i) =>
668
+ // eq(
669
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
670
+ // aliasedTableColumn(field, tableAlias),
671
+ // )
672
+ // ),
673
+ // );
674
+ // const builtRelation = this.buildRelationalQueryWithoutPK({
675
+ // fullSchema,
676
+ // schema,
677
+ // tableNamesMap,
678
+ // table: fullSchema[relationTableTsName] as PgTable,
679
+ // tableConfig: schema[relationTableTsName]!,
680
+ // queryConfig: selectedRelationConfigValue,
681
+ // tableAlias: relationTableAlias,
682
+ // joinOn,
683
+ // nestedQueryRelation: relation,
684
+ // });
685
+ // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
686
+ // joins.push({
687
+ // on: sql`true`,
688
+ // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
689
+ // alias: relationTableAlias,
690
+ // joinType: 'left',
691
+ // lateral: true,
692
+ // });
693
+ // selectedRelations.push({
694
+ // dbKey: selectedRelationTsKey,
695
+ // tsKey: selectedRelationTsKey,
696
+ // field,
697
+ // relationTableTsKey: relationTableTsName,
698
+ // isJson: true,
699
+ // selection: builtRelation.selection,
700
+ // });
701
+ // }
702
+ // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
703
+ // is(r.relation, One)
704
+ // );
705
+ // // Process all One relations with PKs, because they can all be joined on the same level
706
+ // for (
707
+ // const {
708
+ // tsKey: selectedRelationTsKey,
709
+ // queryConfig: selectedRelationConfigValue,
710
+ // relation,
711
+ // } of oneRelations
712
+ // ) {
713
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
714
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
715
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
716
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
717
+ // const relationTable = schema[relationTableTsName]!;
718
+ // if (relationTable.primaryKey.length === 0) {
719
+ // continue;
720
+ // }
721
+ // const joinOn = and(
722
+ // ...normalizedRelation.fields.map((field, i) =>
723
+ // eq(
724
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
725
+ // aliasedTableColumn(field, tableAlias),
726
+ // )
727
+ // ),
728
+ // );
729
+ // const builtRelation = this.buildRelationalQueryWithPK({
730
+ // fullSchema,
731
+ // schema,
732
+ // tableNamesMap,
733
+ // table: fullSchema[relationTableTsName] as PgTable,
734
+ // tableConfig: schema[relationTableTsName]!,
735
+ // queryConfig: selectedRelationConfigValue,
736
+ // tableAlias: relationTableAlias,
737
+ // joinOn,
738
+ // });
739
+ // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
740
+ // sql.join(
741
+ // builtRelation.selection.map(({ field }) =>
742
+ // is(field, SQL.Aliased)
743
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
744
+ // : is(field, Column)
745
+ // ? aliasedTableColumn(field, relationTableAlias)
746
+ // : field
747
+ // ),
748
+ // sql`, `,
749
+ // )
750
+ // }) end`.as(selectedRelationTsKey);
751
+ // const isLateralJoin = is(builtRelation.sql, SQL);
752
+ // joins.push({
753
+ // on: isLateralJoin ? sql`true` : joinOn,
754
+ // table: is(builtRelation.sql, SQL)
755
+ // ? new Subquery(builtRelation.sql, {}, relationTableAlias)
756
+ // : aliasedTable(builtRelation.sql, relationTableAlias),
757
+ // alias: relationTableAlias,
758
+ // joinType: 'left',
759
+ // lateral: is(builtRelation.sql, SQL),
760
+ // });
761
+ // selectedRelations.push({
762
+ // dbKey: selectedRelationTsKey,
763
+ // tsKey: selectedRelationTsKey,
764
+ // field,
765
+ // relationTableTsKey: relationTableTsName,
766
+ // isJson: true,
767
+ // selection: builtRelation.selection,
768
+ // });
769
+ // }
770
+ // let distinct: PgSelectConfig['distinct'];
771
+ // let tableFrom: PgTable | Subquery = table;
772
+ // // Process first Many relation - each one requires a nested subquery
773
+ // const manyRelation = manyRelations[0];
774
+ // if (manyRelation) {
775
+ // const {
776
+ // tsKey: selectedRelationTsKey,
777
+ // queryConfig: selectedRelationQueryConfig,
778
+ // relation,
779
+ // } = manyRelation;
780
+ // distinct = {
781
+ // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
782
+ // };
783
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
784
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
785
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
786
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
787
+ // const joinOn = and(
788
+ // ...normalizedRelation.fields.map((field, i) =>
789
+ // eq(
790
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
791
+ // aliasedTableColumn(field, tableAlias),
792
+ // )
793
+ // ),
794
+ // );
795
+ // const builtRelationJoin = this.buildRelationalQueryWithPK({
796
+ // fullSchema,
797
+ // schema,
798
+ // tableNamesMap,
799
+ // table: fullSchema[relationTableTsName] as PgTable,
800
+ // tableConfig: schema[relationTableTsName]!,
801
+ // queryConfig: selectedRelationQueryConfig,
802
+ // tableAlias: relationTableAlias,
803
+ // joinOn,
804
+ // });
805
+ // const builtRelationSelectionField = sql`case when ${
806
+ // sql.identifier(relationTableAlias)
807
+ // } is null then '[]' else json_agg(json_build_array(${
808
+ // sql.join(
809
+ // builtRelationJoin.selection.map(({ field }) =>
810
+ // is(field, SQL.Aliased)
811
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
812
+ // : is(field, Column)
813
+ // ? aliasedTableColumn(field, relationTableAlias)
814
+ // : field
815
+ // ),
816
+ // sql`, `,
817
+ // )
818
+ // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
819
+ // const isLateralJoin = is(builtRelationJoin.sql, SQL);
820
+ // joins.push({
821
+ // on: isLateralJoin ? sql`true` : joinOn,
822
+ // table: isLateralJoin
823
+ // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
824
+ // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
825
+ // alias: relationTableAlias,
826
+ // joinType: 'left',
827
+ // lateral: isLateralJoin,
828
+ // });
829
+ // // Build the "from" subquery with the remaining Many relations
830
+ // const builtTableFrom = this.buildRelationalQueryWithPK({
831
+ // fullSchema,
832
+ // schema,
833
+ // tableNamesMap,
834
+ // table,
835
+ // tableConfig,
836
+ // queryConfig: {
837
+ // ...config,
838
+ // where: undefined,
839
+ // orderBy: undefined,
840
+ // limit: undefined,
841
+ // offset: undefined,
842
+ // with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
843
+ // (result, { tsKey, queryConfig: configValue }) => {
844
+ // result[tsKey] = configValue;
845
+ // return result;
846
+ // },
847
+ // {},
848
+ // ),
849
+ // },
850
+ // tableAlias,
851
+ // });
852
+ // selectedRelations.push({
853
+ // dbKey: selectedRelationTsKey,
854
+ // tsKey: selectedRelationTsKey,
855
+ // field: builtRelationSelectionField,
856
+ // relationTableTsKey: relationTableTsName,
857
+ // isJson: true,
858
+ // selection: builtRelationJoin.selection,
859
+ // });
860
+ // // selection = builtTableFrom.selection.map((item) =>
861
+ // // is(item.field, SQL.Aliased)
862
+ // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
863
+ // // : item
864
+ // // );
865
+ // // selectionForBuild = [{
866
+ // // dbKey: '*',
867
+ // // tsKey: '*',
868
+ // // field: sql`${sql.identifier(tableAlias)}.*`,
869
+ // // selection: [],
870
+ // // isJson: false,
871
+ // // relationTableTsKey: undefined,
872
+ // // }];
873
+ // // const newSelectionItem: (typeof selection)[number] = {
874
+ // // dbKey: selectedRelationTsKey,
875
+ // // tsKey: selectedRelationTsKey,
876
+ // // field,
877
+ // // relationTableTsKey: relationTableTsName,
878
+ // // isJson: true,
879
+ // // selection: builtRelationJoin.selection,
880
+ // // };
881
+ // // selection.push(newSelectionItem);
882
+ // // selectionForBuild.push(newSelectionItem);
883
+ // tableFrom = is(builtTableFrom.sql, PgTable)
884
+ // ? builtTableFrom.sql
885
+ // : new Subquery(builtTableFrom.sql, {}, tableAlias);
886
+ // }
887
+ // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
888
+ // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
889
+ // }
890
+ // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
891
+ // function prepareSelectedColumns() {
892
+ // return selectedColumns.map((key) => ({
893
+ // dbKey: tableConfig.columns[key]!.name,
894
+ // tsKey: key,
895
+ // field: tableConfig.columns[key] as PgColumn,
896
+ // relationTableTsKey: undefined,
897
+ // isJson: false,
898
+ // selection: [],
899
+ // }));
900
+ // }
901
+ // function prepareSelectedExtras() {
902
+ // return selectedExtras.map((item) => ({
903
+ // dbKey: item.value.fieldAlias,
904
+ // tsKey: item.tsKey,
905
+ // field: item.value,
906
+ // relationTableTsKey: undefined,
907
+ // isJson: false,
908
+ // selection: [],
909
+ // }));
910
+ // }
911
+ // if (isRoot) {
912
+ // selection = [
913
+ // ...prepareSelectedColumns(),
914
+ // ...prepareSelectedExtras(),
915
+ // ];
916
+ // }
917
+ // if (hasUserDefinedWhere || orderBy.length > 0) {
918
+ // tableFrom = new Subquery(
919
+ // this.buildSelectQuery({
920
+ // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
921
+ // fields: {},
922
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
923
+ // path: [],
924
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
925
+ // })),
926
+ // joins,
927
+ // distinct,
928
+ // }),
929
+ // {},
930
+ // tableAlias,
931
+ // );
932
+ // selectionForBuild = selection.map((item) =>
933
+ // is(item.field, SQL.Aliased)
934
+ // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
935
+ // : item
936
+ // );
937
+ // joins = [];
938
+ // distinct = undefined;
939
+ // }
940
+ // const result = this.buildSelectQuery({
941
+ // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
942
+ // fields: {},
943
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
944
+ // path: [],
945
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
946
+ // })),
947
+ // where,
948
+ // limit,
949
+ // offset,
950
+ // joins,
951
+ // orderBy,
952
+ // distinct,
953
+ // });
954
+ // return {
955
+ // tableTsKey: tableConfig.tsName,
956
+ // sql: result,
957
+ // selection,
958
+ // };
959
+ // }
960
+ buildRelationalQueryWithoutPK({
961
+ fullSchema,
962
+ schema,
963
+ tableNamesMap,
964
+ table,
965
+ tableConfig,
966
+ queryConfig: config,
967
+ tableAlias,
968
+ nestedQueryRelation,
969
+ joinOn
970
+ }) {
971
+ let selection = [];
972
+ let limit, offset, orderBy = [], where;
973
+ const joins = [];
974
+ if (config === true) {
975
+ const selectionEntries = Object.entries(tableConfig.columns);
976
+ selection = selectionEntries.map(([key, value]) => ({
977
+ dbKey: value.name,
978
+ tsKey: key,
979
+ field: aliasedTableColumn(value, tableAlias),
980
+ relationTableTsKey: void 0,
981
+ isJson: false,
982
+ selection: []
983
+ }));
984
+ } else {
985
+ const aliasedColumns = Object.fromEntries(
986
+ Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
987
+ );
988
+ if (config.where) {
989
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
990
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
991
+ }
992
+ const fieldsSelection = [];
993
+ let selectedColumns = [];
994
+ if (config.columns) {
995
+ let isIncludeMode = false;
996
+ for (const [field, value] of Object.entries(config.columns)) {
997
+ if (value === void 0) {
998
+ continue;
999
+ }
1000
+ if (field in tableConfig.columns) {
1001
+ if (!isIncludeMode && value === true) {
1002
+ isIncludeMode = true;
1003
+ }
1004
+ selectedColumns.push(field);
1005
+ }
1006
+ }
1007
+ if (selectedColumns.length > 0) {
1008
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1009
+ }
1010
+ } else {
1011
+ selectedColumns = Object.keys(tableConfig.columns);
1012
+ }
1013
+ for (const field of selectedColumns) {
1014
+ const column = tableConfig.columns[field];
1015
+ fieldsSelection.push({ tsKey: field, value: column });
1016
+ }
1017
+ let selectedRelations = [];
1018
+ if (config.with) {
1019
+ selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
1020
+ }
1021
+ let extras;
1022
+ if (config.extras) {
1023
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
1024
+ for (const [tsKey, value] of Object.entries(extras)) {
1025
+ fieldsSelection.push({
1026
+ tsKey,
1027
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
1028
+ });
1029
+ }
1030
+ }
1031
+ for (const { tsKey, value } of fieldsSelection) {
1032
+ selection.push({
1033
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
1034
+ tsKey,
1035
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
1036
+ relationTableTsKey: void 0,
1037
+ isJson: false,
1038
+ selection: []
1039
+ });
1040
+ }
1041
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
1042
+ if (!Array.isArray(orderByOrig)) {
1043
+ orderByOrig = [orderByOrig];
1044
+ }
1045
+ orderBy = orderByOrig.map((orderByValue) => {
1046
+ if (is(orderByValue, Column)) {
1047
+ return aliasedTableColumn(orderByValue, tableAlias);
1048
+ }
1049
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1050
+ });
1051
+ limit = config.limit;
1052
+ offset = config.offset;
1053
+ for (const {
1054
+ tsKey: selectedRelationTsKey,
1055
+ queryConfig: selectedRelationConfigValue,
1056
+ relation
1057
+ } of selectedRelations) {
1058
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1059
+ const relationTableName = getTableUniqueName(relation.referencedTable);
1060
+ const relationTableTsName = tableNamesMap[relationTableName];
1061
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1062
+ const joinOn2 = and(
1063
+ ...normalizedRelation.fields.map(
1064
+ (field2, i) => eq(
1065
+ aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
1066
+ aliasedTableColumn(field2, tableAlias)
1067
+ )
1068
+ )
1069
+ );
1070
+ const builtRelation = this.buildRelationalQueryWithoutPK({
1071
+ fullSchema,
1072
+ schema,
1073
+ tableNamesMap,
1074
+ table: fullSchema[relationTableTsName],
1075
+ tableConfig: schema[relationTableTsName],
1076
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
1077
+ tableAlias: relationTableAlias,
1078
+ joinOn: joinOn2,
1079
+ nestedQueryRelation: relation
1080
+ });
1081
+ const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
1082
+ joins.push({
1083
+ on: sql`true`,
1084
+ table: new Subquery(builtRelation.sql, {}, relationTableAlias),
1085
+ alias: relationTableAlias,
1086
+ joinType: "left",
1087
+ lateral: true
1088
+ });
1089
+ selection.push({
1090
+ dbKey: selectedRelationTsKey,
1091
+ tsKey: selectedRelationTsKey,
1092
+ field,
1093
+ relationTableTsKey: relationTableTsName,
1094
+ isJson: true,
1095
+ selection: builtRelation.selection
1096
+ });
1097
+ }
1098
+ }
1099
+ if (selection.length === 0) {
1100
+ throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
1101
+ }
1102
+ let result;
1103
+ where = and(joinOn, where);
1104
+ if (nestedQueryRelation) {
1105
+ let field = sql`json_build_array(${sql.join(
1106
+ selection.map(
1107
+ ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
1108
+ ),
1109
+ sql`, `
1110
+ )})`;
1111
+ if (is(nestedQueryRelation, Many)) {
1112
+ field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
1113
+ }
1114
+ const nestedSelection = [{
1115
+ dbKey: "data",
1116
+ tsKey: "data",
1117
+ field: field.as("data"),
1118
+ isJson: true,
1119
+ relationTableTsKey: tableConfig.tsName,
1120
+ selection
1121
+ }];
1122
+ const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
1123
+ if (needsSubquery) {
1124
+ result = this.buildSelectQuery({
1125
+ table: aliasedTable(table, tableAlias),
1126
+ fields: {},
1127
+ fieldsFlat: [{
1128
+ path: [],
1129
+ field: sql.raw("*")
1130
+ }],
1131
+ where,
1132
+ limit,
1133
+ offset,
1134
+ orderBy,
1135
+ setOperators: []
1136
+ });
1137
+ where = void 0;
1138
+ limit = void 0;
1139
+ offset = void 0;
1140
+ orderBy = [];
1141
+ } else {
1142
+ result = aliasedTable(table, tableAlias);
1143
+ }
1144
+ result = this.buildSelectQuery({
1145
+ table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
1146
+ fields: {},
1147
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
1148
+ path: [],
1149
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
1150
+ })),
1151
+ joins,
1152
+ where,
1153
+ limit,
1154
+ offset,
1155
+ orderBy,
1156
+ setOperators: []
1157
+ });
1158
+ } else {
1159
+ result = this.buildSelectQuery({
1160
+ table: aliasedTable(table, tableAlias),
1161
+ fields: {},
1162
+ fieldsFlat: selection.map(({ field }) => ({
1163
+ path: [],
1164
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
1165
+ })),
1166
+ joins,
1167
+ where,
1168
+ limit,
1169
+ offset,
1170
+ orderBy,
1171
+ setOperators: []
1172
+ });
1173
+ }
1174
+ return {
1175
+ tableTsKey: tableConfig.tsName,
1176
+ sql: result,
1177
+ selection
1178
+ };
1179
+ }
1180
+ };
1181
+
1182
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/select.js
1183
+ var PgSelectBuilder = class {
1184
+ static [entityKind] = "PgSelectBuilder";
1185
+ fields;
1186
+ session;
1187
+ dialect;
1188
+ withList = [];
1189
+ distinct;
1190
+ constructor(config) {
1191
+ this.fields = config.fields;
1192
+ this.session = config.session;
1193
+ this.dialect = config.dialect;
1194
+ if (config.withList) {
1195
+ this.withList = config.withList;
1196
+ }
1197
+ this.distinct = config.distinct;
1198
+ }
1199
+ authToken;
1200
+ /** @internal */
1201
+ setToken(token) {
1202
+ this.authToken = token;
1203
+ return this;
1204
+ }
1205
+ /**
1206
+ * Specify the table, subquery, or other target that you're
1207
+ * building a select query against.
1208
+ *
1209
+ * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
1210
+ */
1211
+ from(source) {
1212
+ const isPartialSelect = !!this.fields;
1213
+ const src = source;
1214
+ let fields;
1215
+ if (this.fields) {
1216
+ fields = this.fields;
1217
+ } else if (is(src, Subquery)) {
1218
+ fields = Object.fromEntries(
1219
+ Object.keys(src._.selectedFields).map((key) => [key, src[key]])
1220
+ );
1221
+ } else if (is(src, PgViewBase)) {
1222
+ fields = src[ViewBaseConfig].selectedFields;
1223
+ } else if (is(src, SQL)) {
1224
+ fields = {};
1225
+ } else {
1226
+ fields = getTableColumns(src);
1227
+ }
1228
+ return new PgSelectBase({
1229
+ table: src,
1230
+ fields,
1231
+ isPartialSelect,
1232
+ session: this.session,
1233
+ dialect: this.dialect,
1234
+ withList: this.withList,
1235
+ distinct: this.distinct
1236
+ }).setToken(this.authToken);
1237
+ }
1238
+ };
1239
+ var PgSelectQueryBuilderBase = class extends TypedQueryBuilder {
1240
+ static [entityKind] = "PgSelectQueryBuilder";
1241
+ _;
1242
+ config;
1243
+ joinsNotNullableMap;
1244
+ tableName;
1245
+ isPartialSelect;
1246
+ session;
1247
+ dialect;
1248
+ cacheConfig = void 0;
1249
+ usedTables = /* @__PURE__ */ new Set();
1250
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
1251
+ super();
1252
+ this.config = {
1253
+ withList,
1254
+ table,
1255
+ fields: { ...fields },
1256
+ distinct,
1257
+ setOperators: []
1258
+ };
1259
+ this.isPartialSelect = isPartialSelect;
1260
+ this.session = session;
1261
+ this.dialect = dialect;
1262
+ this._ = {
1263
+ selectedFields: fields,
1264
+ config: this.config
1265
+ };
1266
+ this.tableName = getTableLikeName(table);
1267
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
1268
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
1269
+ }
1270
+ /** @internal */
1271
+ getUsedTables() {
1272
+ return [...this.usedTables];
1273
+ }
1274
+ createJoin(joinType, lateral) {
1275
+ return (table, on) => {
1276
+ const baseTableName = this.tableName;
1277
+ const tableName = getTableLikeName(table);
1278
+ for (const item of extractUsedTable(table)) this.usedTables.add(item);
1279
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
1280
+ throw new Error(`Alias "${tableName}" is already used in this query`);
1281
+ }
1282
+ if (!this.isPartialSelect) {
1283
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
1284
+ this.config.fields = {
1285
+ [baseTableName]: this.config.fields
1286
+ };
1287
+ }
1288
+ if (typeof tableName === "string" && !is(table, SQL)) {
1289
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
1290
+ this.config.fields[tableName] = selection;
1291
+ }
1292
+ }
1293
+ if (typeof on === "function") {
1294
+ on = on(
1295
+ new Proxy(
1296
+ this.config.fields,
1297
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1298
+ )
1299
+ );
1300
+ }
1301
+ if (!this.config.joins) {
1302
+ this.config.joins = [];
1303
+ }
1304
+ this.config.joins.push({ on, table, joinType, alias: tableName, lateral });
1305
+ if (typeof tableName === "string") {
1306
+ switch (joinType) {
1307
+ case "left": {
1308
+ this.joinsNotNullableMap[tableName] = false;
1309
+ break;
1310
+ }
1311
+ case "right": {
1312
+ this.joinsNotNullableMap = Object.fromEntries(
1313
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
1314
+ );
1315
+ this.joinsNotNullableMap[tableName] = true;
1316
+ break;
1317
+ }
1318
+ case "cross":
1319
+ case "inner": {
1320
+ this.joinsNotNullableMap[tableName] = true;
1321
+ break;
1322
+ }
1323
+ case "full": {
1324
+ this.joinsNotNullableMap = Object.fromEntries(
1325
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
1326
+ );
1327
+ this.joinsNotNullableMap[tableName] = false;
1328
+ break;
1329
+ }
1330
+ }
1331
+ }
1332
+ return this;
1333
+ };
1334
+ }
1335
+ /**
1336
+ * Executes a `left join` operation by adding another table to the current query.
1337
+ *
1338
+ * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
1339
+ *
1340
+ * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
1341
+ *
1342
+ * @param table the table to join.
1343
+ * @param on the `on` clause.
1344
+ *
1345
+ * @example
1346
+ *
1347
+ * ```ts
1348
+ * // Select all users and their pets
1349
+ * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
1350
+ * .from(users)
1351
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
1352
+ *
1353
+ * // Select userId and petId
1354
+ * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
1355
+ * userId: users.id,
1356
+ * petId: pets.id,
1357
+ * })
1358
+ * .from(users)
1359
+ * .leftJoin(pets, eq(users.id, pets.ownerId))
1360
+ * ```
1361
+ */
1362
+ leftJoin = this.createJoin("left", false);
1363
+ /**
1364
+ * Executes a `left join lateral` operation by adding subquery to the current query.
1365
+ *
1366
+ * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
1367
+ *
1368
+ * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
1369
+ *
1370
+ * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
1371
+ *
1372
+ * @param table the subquery to join.
1373
+ * @param on the `on` clause.
1374
+ */
1375
+ leftJoinLateral = this.createJoin("left", true);
1376
+ /**
1377
+ * Executes a `right join` operation by adding another table to the current query.
1378
+ *
1379
+ * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
1380
+ *
1381
+ * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
1382
+ *
1383
+ * @param table the table to join.
1384
+ * @param on the `on` clause.
1385
+ *
1386
+ * @example
1387
+ *
1388
+ * ```ts
1389
+ * // Select all users and their pets
1390
+ * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
1391
+ * .from(users)
1392
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
1393
+ *
1394
+ * // Select userId and petId
1395
+ * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
1396
+ * userId: users.id,
1397
+ * petId: pets.id,
1398
+ * })
1399
+ * .from(users)
1400
+ * .rightJoin(pets, eq(users.id, pets.ownerId))
1401
+ * ```
1402
+ */
1403
+ rightJoin = this.createJoin("right", false);
1404
+ /**
1405
+ * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
1406
+ *
1407
+ * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
1408
+ *
1409
+ * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
1410
+ *
1411
+ * @param table the table to join.
1412
+ * @param on the `on` clause.
1413
+ *
1414
+ * @example
1415
+ *
1416
+ * ```ts
1417
+ * // Select all users and their pets
1418
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
1419
+ * .from(users)
1420
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
1421
+ *
1422
+ * // Select userId and petId
1423
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
1424
+ * userId: users.id,
1425
+ * petId: pets.id,
1426
+ * })
1427
+ * .from(users)
1428
+ * .innerJoin(pets, eq(users.id, pets.ownerId))
1429
+ * ```
1430
+ */
1431
+ innerJoin = this.createJoin("inner", false);
1432
+ /**
1433
+ * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
1434
+ *
1435
+ * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
1436
+ *
1437
+ * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
1438
+ *
1439
+ * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
1440
+ *
1441
+ * @param table the subquery to join.
1442
+ * @param on the `on` clause.
1443
+ */
1444
+ innerJoinLateral = this.createJoin("inner", true);
1445
+ /**
1446
+ * Executes a `full join` operation by combining rows from two tables into a new table.
1447
+ *
1448
+ * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
1449
+ *
1450
+ * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
1451
+ *
1452
+ * @param table the table to join.
1453
+ * @param on the `on` clause.
1454
+ *
1455
+ * @example
1456
+ *
1457
+ * ```ts
1458
+ * // Select all users and their pets
1459
+ * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
1460
+ * .from(users)
1461
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
1462
+ *
1463
+ * // Select userId and petId
1464
+ * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
1465
+ * userId: users.id,
1466
+ * petId: pets.id,
1467
+ * })
1468
+ * .from(users)
1469
+ * .fullJoin(pets, eq(users.id, pets.ownerId))
1470
+ * ```
1471
+ */
1472
+ fullJoin = this.createJoin("full", false);
1473
+ /**
1474
+ * Executes a `cross join` operation by combining rows from two tables into a new table.
1475
+ *
1476
+ * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
1477
+ *
1478
+ * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
1479
+ *
1480
+ * @param table the table to join.
1481
+ *
1482
+ * @example
1483
+ *
1484
+ * ```ts
1485
+ * // Select all users, each user with every pet
1486
+ * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
1487
+ * .from(users)
1488
+ * .crossJoin(pets)
1489
+ *
1490
+ * // Select userId and petId
1491
+ * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
1492
+ * userId: users.id,
1493
+ * petId: pets.id,
1494
+ * })
1495
+ * .from(users)
1496
+ * .crossJoin(pets)
1497
+ * ```
1498
+ */
1499
+ crossJoin = this.createJoin("cross", false);
1500
+ /**
1501
+ * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
1502
+ *
1503
+ * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
1504
+ *
1505
+ * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
1506
+ *
1507
+ * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
1508
+ *
1509
+ * @param table the query to join.
1510
+ */
1511
+ crossJoinLateral = this.createJoin("cross", true);
1512
+ createSetOperator(type, isAll) {
1513
+ return (rightSelection) => {
1514
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
1515
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
1516
+ throw new Error(
1517
+ "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
1518
+ );
1519
+ }
1520
+ this.config.setOperators.push({ type, isAll, rightSelect });
1521
+ return this;
1522
+ };
1523
+ }
1524
+ /**
1525
+ * Adds `union` set operator to the query.
1526
+ *
1527
+ * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
1528
+ *
1529
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
1530
+ *
1531
+ * @example
1532
+ *
1533
+ * ```ts
1534
+ * // Select all unique names from customers and users tables
1535
+ * await db.select({ name: users.name })
1536
+ * .from(users)
1537
+ * .union(
1538
+ * db.select({ name: customers.name }).from(customers)
1539
+ * );
1540
+ * // or
1541
+ * import { union } from 'drizzle-orm/pg-core'
1542
+ *
1543
+ * await union(
1544
+ * db.select({ name: users.name }).from(users),
1545
+ * db.select({ name: customers.name }).from(customers)
1546
+ * );
1547
+ * ```
1548
+ */
1549
+ union = this.createSetOperator("union", false);
1550
+ /**
1551
+ * Adds `union all` set operator to the query.
1552
+ *
1553
+ * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
1554
+ *
1555
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
1556
+ *
1557
+ * @example
1558
+ *
1559
+ * ```ts
1560
+ * // Select all transaction ids from both online and in-store sales
1561
+ * await db.select({ transaction: onlineSales.transactionId })
1562
+ * .from(onlineSales)
1563
+ * .unionAll(
1564
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
1565
+ * );
1566
+ * // or
1567
+ * import { unionAll } from 'drizzle-orm/pg-core'
1568
+ *
1569
+ * await unionAll(
1570
+ * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
1571
+ * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
1572
+ * );
1573
+ * ```
1574
+ */
1575
+ unionAll = this.createSetOperator("union", true);
1576
+ /**
1577
+ * Adds `intersect` set operator to the query.
1578
+ *
1579
+ * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
1580
+ *
1581
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
1582
+ *
1583
+ * @example
1584
+ *
1585
+ * ```ts
1586
+ * // Select course names that are offered in both departments A and B
1587
+ * await db.select({ courseName: depA.courseName })
1588
+ * .from(depA)
1589
+ * .intersect(
1590
+ * db.select({ courseName: depB.courseName }).from(depB)
1591
+ * );
1592
+ * // or
1593
+ * import { intersect } from 'drizzle-orm/pg-core'
1594
+ *
1595
+ * await intersect(
1596
+ * db.select({ courseName: depA.courseName }).from(depA),
1597
+ * db.select({ courseName: depB.courseName }).from(depB)
1598
+ * );
1599
+ * ```
1600
+ */
1601
+ intersect = this.createSetOperator("intersect", false);
1602
+ /**
1603
+ * Adds `intersect all` set operator to the query.
1604
+ *
1605
+ * Calling this method will retain only the rows that are present in both result sets including all duplicates.
1606
+ *
1607
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
1608
+ *
1609
+ * @example
1610
+ *
1611
+ * ```ts
1612
+ * // Select all products and quantities that are ordered by both regular and VIP customers
1613
+ * await db.select({
1614
+ * productId: regularCustomerOrders.productId,
1615
+ * quantityOrdered: regularCustomerOrders.quantityOrdered
1616
+ * })
1617
+ * .from(regularCustomerOrders)
1618
+ * .intersectAll(
1619
+ * db.select({
1620
+ * productId: vipCustomerOrders.productId,
1621
+ * quantityOrdered: vipCustomerOrders.quantityOrdered
1622
+ * })
1623
+ * .from(vipCustomerOrders)
1624
+ * );
1625
+ * // or
1626
+ * import { intersectAll } from 'drizzle-orm/pg-core'
1627
+ *
1628
+ * await intersectAll(
1629
+ * db.select({
1630
+ * productId: regularCustomerOrders.productId,
1631
+ * quantityOrdered: regularCustomerOrders.quantityOrdered
1632
+ * })
1633
+ * .from(regularCustomerOrders),
1634
+ * db.select({
1635
+ * productId: vipCustomerOrders.productId,
1636
+ * quantityOrdered: vipCustomerOrders.quantityOrdered
1637
+ * })
1638
+ * .from(vipCustomerOrders)
1639
+ * );
1640
+ * ```
1641
+ */
1642
+ intersectAll = this.createSetOperator("intersect", true);
1643
+ /**
1644
+ * Adds `except` set operator to the query.
1645
+ *
1646
+ * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
1647
+ *
1648
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
1649
+ *
1650
+ * @example
1651
+ *
1652
+ * ```ts
1653
+ * // Select all courses offered in department A but not in department B
1654
+ * await db.select({ courseName: depA.courseName })
1655
+ * .from(depA)
1656
+ * .except(
1657
+ * db.select({ courseName: depB.courseName }).from(depB)
1658
+ * );
1659
+ * // or
1660
+ * import { except } from 'drizzle-orm/pg-core'
1661
+ *
1662
+ * await except(
1663
+ * db.select({ courseName: depA.courseName }).from(depA),
1664
+ * db.select({ courseName: depB.courseName }).from(depB)
1665
+ * );
1666
+ * ```
1667
+ */
1668
+ except = this.createSetOperator("except", false);
1669
+ /**
1670
+ * Adds `except all` set operator to the query.
1671
+ *
1672
+ * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
1673
+ *
1674
+ * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
1675
+ *
1676
+ * @example
1677
+ *
1678
+ * ```ts
1679
+ * // Select all products that are ordered by regular customers but not by VIP customers
1680
+ * await db.select({
1681
+ * productId: regularCustomerOrders.productId,
1682
+ * quantityOrdered: regularCustomerOrders.quantityOrdered,
1683
+ * })
1684
+ * .from(regularCustomerOrders)
1685
+ * .exceptAll(
1686
+ * db.select({
1687
+ * productId: vipCustomerOrders.productId,
1688
+ * quantityOrdered: vipCustomerOrders.quantityOrdered,
1689
+ * })
1690
+ * .from(vipCustomerOrders)
1691
+ * );
1692
+ * // or
1693
+ * import { exceptAll } from 'drizzle-orm/pg-core'
1694
+ *
1695
+ * await exceptAll(
1696
+ * db.select({
1697
+ * productId: regularCustomerOrders.productId,
1698
+ * quantityOrdered: regularCustomerOrders.quantityOrdered
1699
+ * })
1700
+ * .from(regularCustomerOrders),
1701
+ * db.select({
1702
+ * productId: vipCustomerOrders.productId,
1703
+ * quantityOrdered: vipCustomerOrders.quantityOrdered
1704
+ * })
1705
+ * .from(vipCustomerOrders)
1706
+ * );
1707
+ * ```
1708
+ */
1709
+ exceptAll = this.createSetOperator("except", true);
1710
+ /** @internal */
1711
+ addSetOperators(setOperators) {
1712
+ this.config.setOperators.push(...setOperators);
1713
+ return this;
1714
+ }
1715
+ /**
1716
+ * Adds a `where` clause to the query.
1717
+ *
1718
+ * Calling this method will select only those rows that fulfill a specified condition.
1719
+ *
1720
+ * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
1721
+ *
1722
+ * @param where the `where` clause.
1723
+ *
1724
+ * @example
1725
+ * You can use conditional operators and `sql function` to filter the rows to be selected.
1726
+ *
1727
+ * ```ts
1728
+ * // Select all cars with green color
1729
+ * await db.select().from(cars).where(eq(cars.color, 'green'));
1730
+ * // or
1731
+ * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
1732
+ * ```
1733
+ *
1734
+ * You can logically combine conditional operators with `and()` and `or()` operators:
1735
+ *
1736
+ * ```ts
1737
+ * // Select all BMW cars with a green color
1738
+ * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
1739
+ *
1740
+ * // Select all cars with the green or blue color
1741
+ * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
1742
+ * ```
1743
+ */
1744
+ where(where) {
1745
+ if (typeof where === "function") {
1746
+ where = where(
1747
+ new Proxy(
1748
+ this.config.fields,
1749
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1750
+ )
1751
+ );
1752
+ }
1753
+ this.config.where = where;
1754
+ return this;
1755
+ }
1756
+ /**
1757
+ * Adds a `having` clause to the query.
1758
+ *
1759
+ * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
1760
+ *
1761
+ * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
1762
+ *
1763
+ * @param having the `having` clause.
1764
+ *
1765
+ * @example
1766
+ *
1767
+ * ```ts
1768
+ * // Select all brands with more than one car
1769
+ * await db.select({
1770
+ * brand: cars.brand,
1771
+ * count: sql<number>`cast(count(${cars.id}) as int)`,
1772
+ * })
1773
+ * .from(cars)
1774
+ * .groupBy(cars.brand)
1775
+ * .having(({ count }) => gt(count, 1));
1776
+ * ```
1777
+ */
1778
+ having(having) {
1779
+ if (typeof having === "function") {
1780
+ having = having(
1781
+ new Proxy(
1782
+ this.config.fields,
1783
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1784
+ )
1785
+ );
1786
+ }
1787
+ this.config.having = having;
1788
+ return this;
1789
+ }
1790
+ groupBy(...columns) {
1791
+ if (typeof columns[0] === "function") {
1792
+ const groupBy = columns[0](
1793
+ new Proxy(
1794
+ this.config.fields,
1795
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
1796
+ )
1797
+ );
1798
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
1799
+ } else {
1800
+ this.config.groupBy = columns;
1801
+ }
1802
+ return this;
1803
+ }
1804
+ orderBy(...columns) {
1805
+ if (typeof columns[0] === "function") {
1806
+ const orderBy = columns[0](
1807
+ new Proxy(
1808
+ this.config.fields,
1809
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
1810
+ )
1811
+ );
1812
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
1813
+ if (this.config.setOperators.length > 0) {
1814
+ this.config.setOperators.at(-1).orderBy = orderByArray;
1815
+ } else {
1816
+ this.config.orderBy = orderByArray;
1817
+ }
1818
+ } else {
1819
+ const orderByArray = columns;
1820
+ if (this.config.setOperators.length > 0) {
1821
+ this.config.setOperators.at(-1).orderBy = orderByArray;
1822
+ } else {
1823
+ this.config.orderBy = orderByArray;
1824
+ }
1825
+ }
1826
+ return this;
1827
+ }
1828
+ /**
1829
+ * Adds a `limit` clause to the query.
1830
+ *
1831
+ * Calling this method will set the maximum number of rows that will be returned by this query.
1832
+ *
1833
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1834
+ *
1835
+ * @param limit the `limit` clause.
1836
+ *
1837
+ * @example
1838
+ *
1839
+ * ```ts
1840
+ * // Get the first 10 people from this query.
1841
+ * await db.select().from(people).limit(10);
1842
+ * ```
1843
+ */
1844
+ limit(limit) {
1845
+ if (this.config.setOperators.length > 0) {
1846
+ this.config.setOperators.at(-1).limit = limit;
1847
+ } else {
1848
+ this.config.limit = limit;
1849
+ }
1850
+ return this;
1851
+ }
1852
+ /**
1853
+ * Adds an `offset` clause to the query.
1854
+ *
1855
+ * Calling this method will skip a number of rows when returning results from this query.
1856
+ *
1857
+ * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
1858
+ *
1859
+ * @param offset the `offset` clause.
1860
+ *
1861
+ * @example
1862
+ *
1863
+ * ```ts
1864
+ * // Get the 10th-20th people from this query.
1865
+ * await db.select().from(people).offset(10).limit(10);
1866
+ * ```
1867
+ */
1868
+ offset(offset) {
1869
+ if (this.config.setOperators.length > 0) {
1870
+ this.config.setOperators.at(-1).offset = offset;
1871
+ } else {
1872
+ this.config.offset = offset;
1873
+ }
1874
+ return this;
1875
+ }
1876
+ /**
1877
+ * Adds a `for` clause to the query.
1878
+ *
1879
+ * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
1880
+ *
1881
+ * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
1882
+ *
1883
+ * @param strength the lock strength.
1884
+ * @param config the lock configuration.
1885
+ */
1886
+ for(strength, config = {}) {
1887
+ this.config.lockingClause = { strength, config };
1888
+ return this;
1889
+ }
1890
+ /** @internal */
1891
+ getSQL() {
1892
+ return this.dialect.buildSelectQuery(this.config);
1893
+ }
1894
+ toSQL() {
1895
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1896
+ return rest;
1897
+ }
1898
+ as(alias) {
1899
+ const usedTables = [];
1900
+ usedTables.push(...extractUsedTable(this.config.table));
1901
+ if (this.config.joins) {
1902
+ for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
1903
+ }
1904
+ return new Proxy(
1905
+ new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
1906
+ new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
1907
+ );
1908
+ }
1909
+ /** @internal */
1910
+ getSelectedFields() {
1911
+ return new Proxy(
1912
+ this.config.fields,
1913
+ new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
1914
+ );
1915
+ }
1916
+ $dynamic() {
1917
+ return this;
1918
+ }
1919
+ $withCache(config) {
1920
+ this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
1921
+ return this;
1922
+ }
1923
+ };
1924
+ var PgSelectBase = class extends PgSelectQueryBuilderBase {
1925
+ static [entityKind] = "PgSelect";
1926
+ /** @internal */
1927
+ _prepare(name) {
1928
+ const { session, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
1929
+ if (!session) {
1930
+ throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
1931
+ }
1932
+ const { fields } = config;
1933
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
1934
+ const fieldsList = orderSelectedFields(fields);
1935
+ const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, void 0, {
1936
+ type: "select",
1937
+ tables: [...usedTables]
1938
+ }, cacheConfig);
1939
+ query.joinsNotNullableMap = joinsNotNullableMap;
1940
+ return query.setToken(authToken);
1941
+ });
1942
+ }
1943
+ /**
1944
+ * Create a prepared statement for this query. This allows
1945
+ * the database to remember this query for the given session
1946
+ * and call it by name, rather than specifying the full query.
1947
+ *
1948
+ * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
1949
+ */
1950
+ prepare(name) {
1951
+ return this._prepare(name);
1952
+ }
1953
+ authToken;
1954
+ /** @internal */
1955
+ setToken(token) {
1956
+ this.authToken = token;
1957
+ return this;
1958
+ }
1959
+ execute = (placeholderValues) => {
1960
+ return tracer.startActiveSpan("drizzle.operation", () => {
1961
+ return this._prepare().execute(placeholderValues, this.authToken);
1962
+ });
1963
+ };
1964
+ };
1965
+ applyMixins(PgSelectBase, [QueryPromise]);
1966
+ function createSetOperator(type, isAll) {
1967
+ return (leftSelect, rightSelect, ...restSelects) => {
1968
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
1969
+ type,
1970
+ isAll,
1971
+ rightSelect: select
1972
+ }));
1973
+ for (const setOperator of setOperators) {
1974
+ if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
1975
+ throw new Error(
1976
+ "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
1977
+ );
1978
+ }
1979
+ }
1980
+ return leftSelect.addSetOperators(setOperators);
1981
+ };
1982
+ }
1983
+ var getPgSetOperators = () => ({
1984
+ union,
1985
+ unionAll,
1986
+ intersect,
1987
+ intersectAll,
1988
+ except,
1989
+ exceptAll
1990
+ });
1991
+ var union = createSetOperator("union", false);
1992
+ var unionAll = createSetOperator("union", true);
1993
+ var intersect = createSetOperator("intersect", false);
1994
+ var intersectAll = createSetOperator("intersect", true);
1995
+ var except = createSetOperator("except", false);
1996
+ var exceptAll = createSetOperator("except", true);
1997
+
1998
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js
1999
+ var QueryBuilder = class {
2000
+ static [entityKind] = "PgQueryBuilder";
2001
+ dialect;
2002
+ dialectConfig;
2003
+ constructor(dialect) {
2004
+ this.dialect = is(dialect, PgDialect) ? dialect : void 0;
2005
+ this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
2006
+ }
2007
+ $with = (alias, selection) => {
2008
+ const queryBuilder = this;
2009
+ const as = (qb) => {
2010
+ if (typeof qb === "function") {
2011
+ qb = qb(queryBuilder);
2012
+ }
2013
+ return new Proxy(
2014
+ new WithSubquery(
2015
+ qb.getSQL(),
2016
+ selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
2017
+ alias,
2018
+ true
2019
+ ),
2020
+ new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
2021
+ );
2022
+ };
2023
+ return { as };
2024
+ };
2025
+ with(...queries) {
2026
+ const self = this;
2027
+ function select(fields) {
2028
+ return new PgSelectBuilder({
2029
+ fields: fields ?? void 0,
2030
+ session: void 0,
2031
+ dialect: self.getDialect(),
2032
+ withList: queries
2033
+ });
2034
+ }
2035
+ function selectDistinct(fields) {
2036
+ return new PgSelectBuilder({
2037
+ fields: fields ?? void 0,
2038
+ session: void 0,
2039
+ dialect: self.getDialect(),
2040
+ distinct: true
2041
+ });
2042
+ }
2043
+ function selectDistinctOn(on, fields) {
2044
+ return new PgSelectBuilder({
2045
+ fields: fields ?? void 0,
2046
+ session: void 0,
2047
+ dialect: self.getDialect(),
2048
+ distinct: { on }
2049
+ });
2050
+ }
2051
+ return { select, selectDistinct, selectDistinctOn };
2052
+ }
2053
+ select(fields) {
2054
+ return new PgSelectBuilder({
2055
+ fields: fields ?? void 0,
2056
+ session: void 0,
2057
+ dialect: this.getDialect()
2058
+ });
2059
+ }
2060
+ selectDistinct(fields) {
2061
+ return new PgSelectBuilder({
2062
+ fields: fields ?? void 0,
2063
+ session: void 0,
2064
+ dialect: this.getDialect(),
2065
+ distinct: true
2066
+ });
2067
+ }
2068
+ selectDistinctOn(on, fields) {
2069
+ return new PgSelectBuilder({
2070
+ fields: fields ?? void 0,
2071
+ session: void 0,
2072
+ dialect: this.getDialect(),
2073
+ distinct: { on }
2074
+ });
2075
+ }
2076
+ // Lazy load dialect to avoid circular dependency
2077
+ getDialect() {
2078
+ if (!this.dialect) {
2079
+ this.dialect = new PgDialect(this.dialectConfig);
2080
+ }
2081
+ return this.dialect;
2082
+ }
2083
+ };
2084
+
2085
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/utils.js
2086
+ function extractUsedTable(table) {
2087
+ if (is(table, PgTable)) {
2088
+ return [table[Schema] ? `${table[Schema]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]];
2089
+ }
2090
+ if (is(table, Subquery)) {
2091
+ return table._.usedTables ?? [];
2092
+ }
2093
+ if (is(table, SQL)) {
2094
+ return table.usedTables ?? [];
2095
+ }
2096
+ return [];
2097
+ }
2098
+
2099
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/delete.js
2100
+ var PgDeleteBase = class extends QueryPromise {
2101
+ constructor(table, session, dialect, withList) {
2102
+ super();
2103
+ this.session = session;
2104
+ this.dialect = dialect;
2105
+ this.config = { table, withList };
2106
+ }
2107
+ static [entityKind] = "PgDelete";
2108
+ config;
2109
+ cacheConfig;
2110
+ /**
2111
+ * Adds a `where` clause to the query.
2112
+ *
2113
+ * Calling this method will delete only those rows that fulfill a specified condition.
2114
+ *
2115
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
2116
+ *
2117
+ * @param where the `where` clause.
2118
+ *
2119
+ * @example
2120
+ * You can use conditional operators and `sql function` to filter the rows to be deleted.
2121
+ *
2122
+ * ```ts
2123
+ * // Delete all cars with green color
2124
+ * await db.delete(cars).where(eq(cars.color, 'green'));
2125
+ * // or
2126
+ * await db.delete(cars).where(sql`${cars.color} = 'green'`)
2127
+ * ```
2128
+ *
2129
+ * You can logically combine conditional operators with `and()` and `or()` operators:
2130
+ *
2131
+ * ```ts
2132
+ * // Delete all BMW cars with a green color
2133
+ * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
2134
+ *
2135
+ * // Delete all cars with the green or blue color
2136
+ * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
2137
+ * ```
2138
+ */
2139
+ where(where) {
2140
+ this.config.where = where;
2141
+ return this;
2142
+ }
2143
+ returning(fields = this.config.table[Table.Symbol.Columns]) {
2144
+ this.config.returningFields = fields;
2145
+ this.config.returning = orderSelectedFields(fields);
2146
+ return this;
2147
+ }
2148
+ /** @internal */
2149
+ getSQL() {
2150
+ return this.dialect.buildDeleteQuery(this.config);
2151
+ }
2152
+ toSQL() {
2153
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2154
+ return rest;
2155
+ }
2156
+ /** @internal */
2157
+ _prepare(name) {
2158
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2159
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
2160
+ type: "delete",
2161
+ tables: extractUsedTable(this.config.table)
2162
+ }, this.cacheConfig);
2163
+ });
2164
+ }
2165
+ prepare(name) {
2166
+ return this._prepare(name);
2167
+ }
2168
+ authToken;
2169
+ /** @internal */
2170
+ setToken(token) {
2171
+ this.authToken = token;
2172
+ return this;
2173
+ }
2174
+ execute = (placeholderValues) => {
2175
+ return tracer.startActiveSpan("drizzle.operation", () => {
2176
+ return this._prepare().execute(placeholderValues, this.authToken);
2177
+ });
2178
+ };
2179
+ /** @internal */
2180
+ getSelectedFields() {
2181
+ return this.config.returningFields ? new Proxy(
2182
+ this.config.returningFields,
2183
+ new SelectionProxyHandler({
2184
+ alias: getTableName(this.config.table),
2185
+ sqlAliasedBehavior: "alias",
2186
+ sqlBehavior: "error"
2187
+ })
2188
+ ) : void 0;
2189
+ }
2190
+ $dynamic() {
2191
+ return this;
2192
+ }
2193
+ };
2194
+
2195
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/insert.js
2196
+ var PgInsertBuilder = class {
2197
+ constructor(table, session, dialect, withList, overridingSystemValue_) {
2198
+ this.table = table;
2199
+ this.session = session;
2200
+ this.dialect = dialect;
2201
+ this.withList = withList;
2202
+ this.overridingSystemValue_ = overridingSystemValue_;
2203
+ }
2204
+ static [entityKind] = "PgInsertBuilder";
2205
+ authToken;
2206
+ /** @internal */
2207
+ setToken(token) {
2208
+ this.authToken = token;
2209
+ return this;
2210
+ }
2211
+ overridingSystemValue() {
2212
+ this.overridingSystemValue_ = true;
2213
+ return this;
2214
+ }
2215
+ values(values) {
2216
+ values = Array.isArray(values) ? values : [values];
2217
+ if (values.length === 0) {
2218
+ throw new Error("values() must be called with at least one value");
2219
+ }
2220
+ const mappedValues = values.map((entry) => {
2221
+ const result = {};
2222
+ const cols = this.table[Table.Symbol.Columns];
2223
+ for (const colKey of Object.keys(entry)) {
2224
+ const colValue = entry[colKey];
2225
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
2226
+ }
2227
+ return result;
2228
+ });
2229
+ return new PgInsertBase(
2230
+ this.table,
2231
+ mappedValues,
2232
+ this.session,
2233
+ this.dialect,
2234
+ this.withList,
2235
+ false,
2236
+ this.overridingSystemValue_
2237
+ ).setToken(this.authToken);
2238
+ }
2239
+ select(selectQuery) {
2240
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
2241
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
2242
+ throw new Error(
2243
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
2244
+ );
2245
+ }
2246
+ return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
2247
+ }
2248
+ };
2249
+ var PgInsertBase = class extends QueryPromise {
2250
+ constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
2251
+ super();
2252
+ this.session = session;
2253
+ this.dialect = dialect;
2254
+ this.config = { table, values, withList, select, overridingSystemValue_ };
2255
+ }
2256
+ static [entityKind] = "PgInsert";
2257
+ config;
2258
+ cacheConfig;
2259
+ returning(fields = this.config.table[Table.Symbol.Columns]) {
2260
+ this.config.returningFields = fields;
2261
+ this.config.returning = orderSelectedFields(fields);
2262
+ return this;
2263
+ }
2264
+ /**
2265
+ * Adds an `on conflict do nothing` clause to the query.
2266
+ *
2267
+ * Calling this method simply avoids inserting a row as its alternative action.
2268
+ *
2269
+ * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
2270
+ *
2271
+ * @param config The `target` and `where` clauses.
2272
+ *
2273
+ * @example
2274
+ * ```ts
2275
+ * // Insert one row and cancel the insert if there's a conflict
2276
+ * await db.insert(cars)
2277
+ * .values({ id: 1, brand: 'BMW' })
2278
+ * .onConflictDoNothing();
2279
+ *
2280
+ * // Explicitly specify conflict target
2281
+ * await db.insert(cars)
2282
+ * .values({ id: 1, brand: 'BMW' })
2283
+ * .onConflictDoNothing({ target: cars.id });
2284
+ * ```
2285
+ */
2286
+ onConflictDoNothing(config = {}) {
2287
+ if (config.target === void 0) {
2288
+ this.config.onConflict = sql`do nothing`;
2289
+ } else {
2290
+ let targetColumn = "";
2291
+ targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
2292
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
2293
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
2294
+ }
2295
+ return this;
2296
+ }
2297
+ /**
2298
+ * Adds an `on conflict do update` clause to the query.
2299
+ *
2300
+ * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
2301
+ *
2302
+ * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
2303
+ *
2304
+ * @param config The `target`, `set` and `where` clauses.
2305
+ *
2306
+ * @example
2307
+ * ```ts
2308
+ * // Update the row if there's a conflict
2309
+ * await db.insert(cars)
2310
+ * .values({ id: 1, brand: 'BMW' })
2311
+ * .onConflictDoUpdate({
2312
+ * target: cars.id,
2313
+ * set: { brand: 'Porsche' }
2314
+ * });
2315
+ *
2316
+ * // Upsert with 'where' clause
2317
+ * await db.insert(cars)
2318
+ * .values({ id: 1, brand: 'BMW' })
2319
+ * .onConflictDoUpdate({
2320
+ * target: cars.id,
2321
+ * set: { brand: 'newBMW' },
2322
+ * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
2323
+ * });
2324
+ * ```
2325
+ */
2326
+ onConflictDoUpdate(config) {
2327
+ if (config.where && (config.targetWhere || config.setWhere)) {
2328
+ throw new Error(
2329
+ 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
2330
+ );
2331
+ }
2332
+ const whereSql = config.where ? sql` where ${config.where}` : void 0;
2333
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
2334
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
2335
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
2336
+ let targetColumn = "";
2337
+ targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
2338
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
2339
+ return this;
2340
+ }
2341
+ /** @internal */
2342
+ getSQL() {
2343
+ return this.dialect.buildInsertQuery(this.config);
2344
+ }
2345
+ toSQL() {
2346
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2347
+ return rest;
2348
+ }
2349
+ /** @internal */
2350
+ _prepare(name) {
2351
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2352
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
2353
+ type: "insert",
2354
+ tables: extractUsedTable(this.config.table)
2355
+ }, this.cacheConfig);
2356
+ });
2357
+ }
2358
+ prepare(name) {
2359
+ return this._prepare(name);
2360
+ }
2361
+ authToken;
2362
+ /** @internal */
2363
+ setToken(token) {
2364
+ this.authToken = token;
2365
+ return this;
2366
+ }
2367
+ execute = (placeholderValues) => {
2368
+ return tracer.startActiveSpan("drizzle.operation", () => {
2369
+ return this._prepare().execute(placeholderValues, this.authToken);
2370
+ });
2371
+ };
2372
+ /** @internal */
2373
+ getSelectedFields() {
2374
+ return this.config.returningFields ? new Proxy(
2375
+ this.config.returningFields,
2376
+ new SelectionProxyHandler({
2377
+ alias: getTableName(this.config.table),
2378
+ sqlAliasedBehavior: "alias",
2379
+ sqlBehavior: "error"
2380
+ })
2381
+ ) : void 0;
2382
+ }
2383
+ $dynamic() {
2384
+ return this;
2385
+ }
2386
+ };
2387
+
2388
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js
2389
+ var PgRefreshMaterializedView = class extends QueryPromise {
2390
+ constructor(view, session, dialect) {
2391
+ super();
2392
+ this.session = session;
2393
+ this.dialect = dialect;
2394
+ this.config = { view };
2395
+ }
2396
+ static [entityKind] = "PgRefreshMaterializedView";
2397
+ config;
2398
+ concurrently() {
2399
+ if (this.config.withNoData !== void 0) {
2400
+ throw new Error("Cannot use concurrently and withNoData together");
2401
+ }
2402
+ this.config.concurrently = true;
2403
+ return this;
2404
+ }
2405
+ withNoData() {
2406
+ if (this.config.concurrently !== void 0) {
2407
+ throw new Error("Cannot use concurrently and withNoData together");
2408
+ }
2409
+ this.config.withNoData = true;
2410
+ return this;
2411
+ }
2412
+ /** @internal */
2413
+ getSQL() {
2414
+ return this.dialect.buildRefreshMaterializedViewQuery(this.config);
2415
+ }
2416
+ toSQL() {
2417
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2418
+ return rest;
2419
+ }
2420
+ /** @internal */
2421
+ _prepare(name) {
2422
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2423
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
2424
+ });
2425
+ }
2426
+ prepare(name) {
2427
+ return this._prepare(name);
2428
+ }
2429
+ authToken;
2430
+ /** @internal */
2431
+ setToken(token) {
2432
+ this.authToken = token;
2433
+ return this;
2434
+ }
2435
+ execute = (placeholderValues) => {
2436
+ return tracer.startActiveSpan("drizzle.operation", () => {
2437
+ return this._prepare().execute(placeholderValues, this.authToken);
2438
+ });
2439
+ };
2440
+ };
2441
+
2442
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/update.js
2443
+ var PgUpdateBuilder = class {
2444
+ constructor(table, session, dialect, withList) {
2445
+ this.table = table;
2446
+ this.session = session;
2447
+ this.dialect = dialect;
2448
+ this.withList = withList;
2449
+ }
2450
+ static [entityKind] = "PgUpdateBuilder";
2451
+ authToken;
2452
+ setToken(token) {
2453
+ this.authToken = token;
2454
+ return this;
2455
+ }
2456
+ set(values) {
2457
+ return new PgUpdateBase(
2458
+ this.table,
2459
+ mapUpdateSet(this.table, values),
2460
+ this.session,
2461
+ this.dialect,
2462
+ this.withList
2463
+ ).setToken(this.authToken);
2464
+ }
2465
+ };
2466
+ var PgUpdateBase = class extends QueryPromise {
2467
+ constructor(table, set, session, dialect, withList) {
2468
+ super();
2469
+ this.session = session;
2470
+ this.dialect = dialect;
2471
+ this.config = { set, table, withList, joins: [] };
2472
+ this.tableName = getTableLikeName(table);
2473
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
2474
+ }
2475
+ static [entityKind] = "PgUpdate";
2476
+ config;
2477
+ tableName;
2478
+ joinsNotNullableMap;
2479
+ cacheConfig;
2480
+ from(source) {
2481
+ const src = source;
2482
+ const tableName = getTableLikeName(src);
2483
+ if (typeof tableName === "string") {
2484
+ this.joinsNotNullableMap[tableName] = true;
2485
+ }
2486
+ this.config.from = src;
2487
+ return this;
2488
+ }
2489
+ getTableLikeFields(table) {
2490
+ if (is(table, PgTable)) {
2491
+ return table[Table.Symbol.Columns];
2492
+ } else if (is(table, Subquery)) {
2493
+ return table._.selectedFields;
2494
+ }
2495
+ return table[ViewBaseConfig].selectedFields;
2496
+ }
2497
+ createJoin(joinType) {
2498
+ return (table, on) => {
2499
+ const tableName = getTableLikeName(table);
2500
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
2501
+ throw new Error(`Alias "${tableName}" is already used in this query`);
2502
+ }
2503
+ if (typeof on === "function") {
2504
+ const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
2505
+ on = on(
2506
+ new Proxy(
2507
+ this.config.table[Table.Symbol.Columns],
2508
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
2509
+ ),
2510
+ from && new Proxy(
2511
+ from,
2512
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
2513
+ )
2514
+ );
2515
+ }
2516
+ this.config.joins.push({ on, table, joinType, alias: tableName });
2517
+ if (typeof tableName === "string") {
2518
+ switch (joinType) {
2519
+ case "left": {
2520
+ this.joinsNotNullableMap[tableName] = false;
2521
+ break;
2522
+ }
2523
+ case "right": {
2524
+ this.joinsNotNullableMap = Object.fromEntries(
2525
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
2526
+ );
2527
+ this.joinsNotNullableMap[tableName] = true;
2528
+ break;
2529
+ }
2530
+ case "inner": {
2531
+ this.joinsNotNullableMap[tableName] = true;
2532
+ break;
2533
+ }
2534
+ case "full": {
2535
+ this.joinsNotNullableMap = Object.fromEntries(
2536
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
2537
+ );
2538
+ this.joinsNotNullableMap[tableName] = false;
2539
+ break;
2540
+ }
2541
+ }
2542
+ }
2543
+ return this;
2544
+ };
2545
+ }
2546
+ leftJoin = this.createJoin("left");
2547
+ rightJoin = this.createJoin("right");
2548
+ innerJoin = this.createJoin("inner");
2549
+ fullJoin = this.createJoin("full");
2550
+ /**
2551
+ * Adds a 'where' clause to the query.
2552
+ *
2553
+ * Calling this method will update only those rows that fulfill a specified condition.
2554
+ *
2555
+ * See docs: {@link https://orm.drizzle.team/docs/update}
2556
+ *
2557
+ * @param where the 'where' clause.
2558
+ *
2559
+ * @example
2560
+ * You can use conditional operators and `sql function` to filter the rows to be updated.
2561
+ *
2562
+ * ```ts
2563
+ * // Update all cars with green color
2564
+ * await db.update(cars).set({ color: 'red' })
2565
+ * .where(eq(cars.color, 'green'));
2566
+ * // or
2567
+ * await db.update(cars).set({ color: 'red' })
2568
+ * .where(sql`${cars.color} = 'green'`)
2569
+ * ```
2570
+ *
2571
+ * You can logically combine conditional operators with `and()` and `or()` operators:
2572
+ *
2573
+ * ```ts
2574
+ * // Update all BMW cars with a green color
2575
+ * await db.update(cars).set({ color: 'red' })
2576
+ * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
2577
+ *
2578
+ * // Update all cars with the green or blue color
2579
+ * await db.update(cars).set({ color: 'red' })
2580
+ * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
2581
+ * ```
2582
+ */
2583
+ where(where) {
2584
+ this.config.where = where;
2585
+ return this;
2586
+ }
2587
+ returning(fields) {
2588
+ if (!fields) {
2589
+ fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
2590
+ if (this.config.from) {
2591
+ const tableName = getTableLikeName(this.config.from);
2592
+ if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
2593
+ const fromFields = this.getTableLikeFields(this.config.from);
2594
+ fields[tableName] = fromFields;
2595
+ }
2596
+ for (const join of this.config.joins) {
2597
+ const tableName2 = getTableLikeName(join.table);
2598
+ if (typeof tableName2 === "string" && !is(join.table, SQL)) {
2599
+ const fromFields = this.getTableLikeFields(join.table);
2600
+ fields[tableName2] = fromFields;
2601
+ }
2602
+ }
2603
+ }
2604
+ }
2605
+ this.config.returningFields = fields;
2606
+ this.config.returning = orderSelectedFields(fields);
2607
+ return this;
2608
+ }
2609
+ /** @internal */
2610
+ getSQL() {
2611
+ return this.dialect.buildUpdateQuery(this.config);
2612
+ }
2613
+ toSQL() {
2614
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2615
+ return rest;
2616
+ }
2617
+ /** @internal */
2618
+ _prepare(name) {
2619
+ const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
2620
+ type: "insert",
2621
+ tables: extractUsedTable(this.config.table)
2622
+ }, this.cacheConfig);
2623
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
2624
+ return query;
2625
+ }
2626
+ prepare(name) {
2627
+ return this._prepare(name);
2628
+ }
2629
+ authToken;
2630
+ /** @internal */
2631
+ setToken(token) {
2632
+ this.authToken = token;
2633
+ return this;
2634
+ }
2635
+ execute = (placeholderValues) => {
2636
+ return this._prepare().execute(placeholderValues, this.authToken);
2637
+ };
2638
+ /** @internal */
2639
+ getSelectedFields() {
2640
+ return this.config.returningFields ? new Proxy(
2641
+ this.config.returningFields,
2642
+ new SelectionProxyHandler({
2643
+ alias: getTableName(this.config.table),
2644
+ sqlAliasedBehavior: "alias",
2645
+ sqlBehavior: "error"
2646
+ })
2647
+ ) : void 0;
2648
+ }
2649
+ $dynamic() {
2650
+ return this;
2651
+ }
2652
+ };
2653
+
2654
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/count.js
2655
+ var PgCountBuilder = class _PgCountBuilder extends SQL {
2656
+ constructor(params) {
2657
+ super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
2658
+ this.params = params;
2659
+ this.mapWith(Number);
2660
+ this.session = params.session;
2661
+ this.sql = _PgCountBuilder.buildCount(
2662
+ params.source,
2663
+ params.filters
2664
+ );
2665
+ }
2666
+ sql;
2667
+ token;
2668
+ static [entityKind] = "PgCountBuilder";
2669
+ [Symbol.toStringTag] = "PgCountBuilder";
2670
+ session;
2671
+ static buildEmbeddedCount(source, filters) {
2672
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
2673
+ }
2674
+ static buildCount(source, filters) {
2675
+ return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
2676
+ }
2677
+ /** @intrnal */
2678
+ setToken(token) {
2679
+ this.token = token;
2680
+ return this;
2681
+ }
2682
+ then(onfulfilled, onrejected) {
2683
+ return Promise.resolve(this.session.count(this.sql, this.token)).then(
2684
+ onfulfilled,
2685
+ onrejected
2686
+ );
2687
+ }
2688
+ catch(onRejected) {
2689
+ return this.then(void 0, onRejected);
2690
+ }
2691
+ finally(onFinally) {
2692
+ return this.then(
2693
+ (value) => {
2694
+ onFinally?.();
2695
+ return value;
2696
+ },
2697
+ (reason) => {
2698
+ onFinally?.();
2699
+ throw reason;
2700
+ }
2701
+ );
2702
+ }
2703
+ };
2704
+
2705
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/query.js
2706
+ var RelationalQueryBuilder = class {
2707
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
2708
+ this.fullSchema = fullSchema;
2709
+ this.schema = schema;
2710
+ this.tableNamesMap = tableNamesMap;
2711
+ this.table = table;
2712
+ this.tableConfig = tableConfig;
2713
+ this.dialect = dialect;
2714
+ this.session = session;
2715
+ }
2716
+ static [entityKind] = "PgRelationalQueryBuilder";
2717
+ findMany(config) {
2718
+ return new PgRelationalQuery(
2719
+ this.fullSchema,
2720
+ this.schema,
2721
+ this.tableNamesMap,
2722
+ this.table,
2723
+ this.tableConfig,
2724
+ this.dialect,
2725
+ this.session,
2726
+ config ? config : {},
2727
+ "many"
2728
+ );
2729
+ }
2730
+ findFirst(config) {
2731
+ return new PgRelationalQuery(
2732
+ this.fullSchema,
2733
+ this.schema,
2734
+ this.tableNamesMap,
2735
+ this.table,
2736
+ this.tableConfig,
2737
+ this.dialect,
2738
+ this.session,
2739
+ config ? { ...config, limit: 1 } : { limit: 1 },
2740
+ "first"
2741
+ );
2742
+ }
2743
+ };
2744
+ var PgRelationalQuery = class extends QueryPromise {
2745
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
2746
+ super();
2747
+ this.fullSchema = fullSchema;
2748
+ this.schema = schema;
2749
+ this.tableNamesMap = tableNamesMap;
2750
+ this.table = table;
2751
+ this.tableConfig = tableConfig;
2752
+ this.dialect = dialect;
2753
+ this.session = session;
2754
+ this.config = config;
2755
+ this.mode = mode;
2756
+ }
2757
+ static [entityKind] = "PgRelationalQuery";
2758
+ /** @internal */
2759
+ _prepare(name) {
2760
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2761
+ const { query, builtQuery } = this._toSQL();
2762
+ return this.session.prepareQuery(
2763
+ builtQuery,
2764
+ void 0,
2765
+ name,
2766
+ true,
2767
+ (rawRows, mapColumnValue) => {
2768
+ const rows = rawRows.map(
2769
+ (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
2770
+ );
2771
+ if (this.mode === "first") {
2772
+ return rows[0];
2773
+ }
2774
+ return rows;
2775
+ }
2776
+ );
2777
+ });
2778
+ }
2779
+ prepare(name) {
2780
+ return this._prepare(name);
2781
+ }
2782
+ _getQuery() {
2783
+ return this.dialect.buildRelationalQueryWithoutPK({
2784
+ fullSchema: this.fullSchema,
2785
+ schema: this.schema,
2786
+ tableNamesMap: this.tableNamesMap,
2787
+ table: this.table,
2788
+ tableConfig: this.tableConfig,
2789
+ queryConfig: this.config,
2790
+ tableAlias: this.tableConfig.tsName
2791
+ });
2792
+ }
2793
+ /** @internal */
2794
+ getSQL() {
2795
+ return this._getQuery().sql;
2796
+ }
2797
+ _toSQL() {
2798
+ const query = this._getQuery();
2799
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
2800
+ return { query, builtQuery };
2801
+ }
2802
+ toSQL() {
2803
+ return this._toSQL().builtQuery;
2804
+ }
2805
+ authToken;
2806
+ /** @internal */
2807
+ setToken(token) {
2808
+ this.authToken = token;
2809
+ return this;
2810
+ }
2811
+ execute() {
2812
+ return tracer.startActiveSpan("drizzle.operation", () => {
2813
+ return this._prepare().execute(void 0, this.authToken);
2814
+ });
2815
+ }
2816
+ };
2817
+
2818
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/query-builders/raw.js
2819
+ var PgRaw = class extends QueryPromise {
2820
+ constructor(execute, sql2, query, mapBatchResult) {
2821
+ super();
2822
+ this.execute = execute;
2823
+ this.sql = sql2;
2824
+ this.query = query;
2825
+ this.mapBatchResult = mapBatchResult;
2826
+ }
2827
+ static [entityKind] = "PgRaw";
2828
+ /** @internal */
2829
+ getSQL() {
2830
+ return this.sql;
2831
+ }
2832
+ getQuery() {
2833
+ return this.query;
2834
+ }
2835
+ mapResult(result, isFromBatch) {
2836
+ return isFromBatch ? this.mapBatchResult(result) : result;
2837
+ }
2838
+ _prepare() {
2839
+ return this;
2840
+ }
2841
+ /** @internal */
2842
+ isResponseInArrayMode() {
2843
+ return false;
2844
+ }
2845
+ };
2846
+
2847
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/db.js
2848
+ var PgDatabase = class {
2849
+ constructor(dialect, session, schema) {
2850
+ this.dialect = dialect;
2851
+ this.session = session;
2852
+ this._ = schema ? {
2853
+ schema: schema.schema,
2854
+ fullSchema: schema.fullSchema,
2855
+ tableNamesMap: schema.tableNamesMap,
2856
+ session
2857
+ } : {
2858
+ schema: void 0,
2859
+ fullSchema: {},
2860
+ tableNamesMap: {},
2861
+ session
2862
+ };
2863
+ this.query = {};
2864
+ if (this._.schema) {
2865
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
2866
+ this.query[tableName] = new RelationalQueryBuilder(
2867
+ schema.fullSchema,
2868
+ this._.schema,
2869
+ this._.tableNamesMap,
2870
+ schema.fullSchema[tableName],
2871
+ columns,
2872
+ dialect,
2873
+ session
2874
+ );
2875
+ }
2876
+ }
2877
+ this.$cache = { invalidate: async (_params) => {
2878
+ } };
2879
+ }
2880
+ static [entityKind] = "PgDatabase";
2881
+ query;
2882
+ /**
2883
+ * Creates a subquery that defines a temporary named result set as a CTE.
2884
+ *
2885
+ * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
2886
+ *
2887
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
2888
+ *
2889
+ * @param alias The alias for the subquery.
2890
+ *
2891
+ * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
2892
+ *
2893
+ * @example
2894
+ *
2895
+ * ```ts
2896
+ * // Create a subquery with alias 'sq' and use it in the select query
2897
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
2898
+ *
2899
+ * const result = await db.with(sq).select().from(sq);
2900
+ * ```
2901
+ *
2902
+ * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
2903
+ *
2904
+ * ```ts
2905
+ * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
2906
+ * const sq = db.$with('sq').as(db.select({
2907
+ * name: sql<string>`upper(${users.name})`.as('name'),
2908
+ * })
2909
+ * .from(users));
2910
+ *
2911
+ * const result = await db.with(sq).select({ name: sq.name }).from(sq);
2912
+ * ```
2913
+ */
2914
+ $with = (alias, selection) => {
2915
+ const self = this;
2916
+ const as = (qb) => {
2917
+ if (typeof qb === "function") {
2918
+ qb = qb(new QueryBuilder(self.dialect));
2919
+ }
2920
+ return new Proxy(
2921
+ new WithSubquery(
2922
+ qb.getSQL(),
2923
+ selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
2924
+ alias,
2925
+ true
2926
+ ),
2927
+ new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
2928
+ );
2929
+ };
2930
+ return { as };
2931
+ };
2932
+ $count(source, filters) {
2933
+ return new PgCountBuilder({ source, filters, session: this.session });
2934
+ }
2935
+ $cache;
2936
+ /**
2937
+ * Incorporates a previously defined CTE (using `$with`) into the main query.
2938
+ *
2939
+ * This method allows the main query to reference a temporary named result set.
2940
+ *
2941
+ * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
2942
+ *
2943
+ * @param queries The CTEs to incorporate into the main query.
2944
+ *
2945
+ * @example
2946
+ *
2947
+ * ```ts
2948
+ * // Define a subquery 'sq' as a CTE using $with
2949
+ * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
2950
+ *
2951
+ * // Incorporate the CTE 'sq' into the main query and select from it
2952
+ * const result = await db.with(sq).select().from(sq);
2953
+ * ```
2954
+ */
2955
+ with(...queries) {
2956
+ const self = this;
2957
+ function select(fields) {
2958
+ return new PgSelectBuilder({
2959
+ fields: fields ?? void 0,
2960
+ session: self.session,
2961
+ dialect: self.dialect,
2962
+ withList: queries
2963
+ });
2964
+ }
2965
+ function selectDistinct(fields) {
2966
+ return new PgSelectBuilder({
2967
+ fields: fields ?? void 0,
2968
+ session: self.session,
2969
+ dialect: self.dialect,
2970
+ withList: queries,
2971
+ distinct: true
2972
+ });
2973
+ }
2974
+ function selectDistinctOn(on, fields) {
2975
+ return new PgSelectBuilder({
2976
+ fields: fields ?? void 0,
2977
+ session: self.session,
2978
+ dialect: self.dialect,
2979
+ withList: queries,
2980
+ distinct: { on }
2981
+ });
2982
+ }
2983
+ function update(table) {
2984
+ return new PgUpdateBuilder(table, self.session, self.dialect, queries);
2985
+ }
2986
+ function insert(table) {
2987
+ return new PgInsertBuilder(table, self.session, self.dialect, queries);
2988
+ }
2989
+ function delete_(table) {
2990
+ return new PgDeleteBase(table, self.session, self.dialect, queries);
2991
+ }
2992
+ return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
2993
+ }
2994
+ select(fields) {
2995
+ return new PgSelectBuilder({
2996
+ fields: fields ?? void 0,
2997
+ session: this.session,
2998
+ dialect: this.dialect
2999
+ });
3000
+ }
3001
+ selectDistinct(fields) {
3002
+ return new PgSelectBuilder({
3003
+ fields: fields ?? void 0,
3004
+ session: this.session,
3005
+ dialect: this.dialect,
3006
+ distinct: true
3007
+ });
3008
+ }
3009
+ selectDistinctOn(on, fields) {
3010
+ return new PgSelectBuilder({
3011
+ fields: fields ?? void 0,
3012
+ session: this.session,
3013
+ dialect: this.dialect,
3014
+ distinct: { on }
3015
+ });
3016
+ }
3017
+ /**
3018
+ * Creates an update query.
3019
+ *
3020
+ * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
3021
+ *
3022
+ * Use `.set()` method to specify which values to update.
3023
+ *
3024
+ * See docs: {@link https://orm.drizzle.team/docs/update}
3025
+ *
3026
+ * @param table The table to update.
3027
+ *
3028
+ * @example
3029
+ *
3030
+ * ```ts
3031
+ * // Update all rows in the 'cars' table
3032
+ * await db.update(cars).set({ color: 'red' });
3033
+ *
3034
+ * // Update rows with filters and conditions
3035
+ * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
3036
+ *
3037
+ * // Update with returning clause
3038
+ * const updatedCar: Car[] = await db.update(cars)
3039
+ * .set({ color: 'red' })
3040
+ * .where(eq(cars.id, 1))
3041
+ * .returning();
3042
+ * ```
3043
+ */
3044
+ update(table) {
3045
+ return new PgUpdateBuilder(table, this.session, this.dialect);
3046
+ }
3047
+ /**
3048
+ * Creates an insert query.
3049
+ *
3050
+ * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
3051
+ *
3052
+ * See docs: {@link https://orm.drizzle.team/docs/insert}
3053
+ *
3054
+ * @param table The table to insert into.
3055
+ *
3056
+ * @example
3057
+ *
3058
+ * ```ts
3059
+ * // Insert one row
3060
+ * await db.insert(cars).values({ brand: 'BMW' });
3061
+ *
3062
+ * // Insert multiple rows
3063
+ * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
3064
+ *
3065
+ * // Insert with returning clause
3066
+ * const insertedCar: Car[] = await db.insert(cars)
3067
+ * .values({ brand: 'BMW' })
3068
+ * .returning();
3069
+ * ```
3070
+ */
3071
+ insert(table) {
3072
+ return new PgInsertBuilder(table, this.session, this.dialect);
3073
+ }
3074
+ /**
3075
+ * Creates a delete query.
3076
+ *
3077
+ * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
3078
+ *
3079
+ * See docs: {@link https://orm.drizzle.team/docs/delete}
3080
+ *
3081
+ * @param table The table to delete from.
3082
+ *
3083
+ * @example
3084
+ *
3085
+ * ```ts
3086
+ * // Delete all rows in the 'cars' table
3087
+ * await db.delete(cars);
3088
+ *
3089
+ * // Delete rows with filters and conditions
3090
+ * await db.delete(cars).where(eq(cars.color, 'green'));
3091
+ *
3092
+ * // Delete with returning clause
3093
+ * const deletedCar: Car[] = await db.delete(cars)
3094
+ * .where(eq(cars.id, 1))
3095
+ * .returning();
3096
+ * ```
3097
+ */
3098
+ delete(table) {
3099
+ return new PgDeleteBase(table, this.session, this.dialect);
3100
+ }
3101
+ refreshMaterializedView(view) {
3102
+ return new PgRefreshMaterializedView(view, this.session, this.dialect);
3103
+ }
3104
+ authToken;
3105
+ execute(query) {
3106
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3107
+ const builtQuery = this.dialect.sqlToQuery(sequel);
3108
+ const prepared = this.session.prepareQuery(
3109
+ builtQuery,
3110
+ void 0,
3111
+ void 0,
3112
+ false
3113
+ );
3114
+ return new PgRaw(
3115
+ () => prepared.execute(void 0, this.authToken),
3116
+ sequel,
3117
+ builtQuery,
3118
+ (result) => prepared.mapResult(result, true)
3119
+ );
3120
+ }
3121
+ transaction(transaction, config) {
3122
+ return this.session.transaction(transaction, config);
3123
+ }
3124
+ };
3125
+
3126
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/node-postgres/session.js
3127
+ import pg from "pg";
3128
+
3129
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/pg-core/session.js
3130
+ var PgPreparedQuery = class {
3131
+ constructor(query, cache, queryMetadata, cacheConfig) {
3132
+ this.query = query;
3133
+ this.cache = cache;
3134
+ this.queryMetadata = queryMetadata;
3135
+ this.cacheConfig = cacheConfig;
3136
+ if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
3137
+ this.cacheConfig = { enable: true, autoInvalidate: true };
3138
+ }
3139
+ if (!this.cacheConfig?.enable) {
3140
+ this.cacheConfig = void 0;
3141
+ }
3142
+ }
3143
+ authToken;
3144
+ getQuery() {
3145
+ return this.query;
3146
+ }
3147
+ mapResult(response, _isFromBatch) {
3148
+ return response;
3149
+ }
3150
+ /** @internal */
3151
+ setToken(token) {
3152
+ this.authToken = token;
3153
+ return this;
3154
+ }
3155
+ static [entityKind] = "PgPreparedQuery";
3156
+ /** @internal */
3157
+ joinsNotNullableMap;
3158
+ /** @internal */
3159
+ async queryWithCache(queryString, params, query) {
3160
+ if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
3161
+ try {
3162
+ return await query();
3163
+ } catch (e) {
3164
+ throw new DrizzleQueryError(queryString, params, e);
3165
+ }
3166
+ }
3167
+ if (this.cacheConfig && !this.cacheConfig.enable) {
3168
+ try {
3169
+ return await query();
3170
+ } catch (e) {
3171
+ throw new DrizzleQueryError(queryString, params, e);
3172
+ }
3173
+ }
3174
+ if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
3175
+ try {
3176
+ const [res] = await Promise.all([
3177
+ query(),
3178
+ this.cache.onMutate({ tables: this.queryMetadata.tables })
3179
+ ]);
3180
+ return res;
3181
+ } catch (e) {
3182
+ throw new DrizzleQueryError(queryString, params, e);
3183
+ }
3184
+ }
3185
+ if (!this.cacheConfig) {
3186
+ try {
3187
+ return await query();
3188
+ } catch (e) {
3189
+ throw new DrizzleQueryError(queryString, params, e);
3190
+ }
3191
+ }
3192
+ if (this.queryMetadata.type === "select") {
3193
+ const fromCache = await this.cache.get(
3194
+ this.cacheConfig.tag ?? await hashQuery(queryString, params),
3195
+ this.queryMetadata.tables,
3196
+ this.cacheConfig.tag !== void 0,
3197
+ this.cacheConfig.autoInvalidate
3198
+ );
3199
+ if (fromCache === void 0) {
3200
+ let result;
3201
+ try {
3202
+ result = await query();
3203
+ } catch (e) {
3204
+ throw new DrizzleQueryError(queryString, params, e);
3205
+ }
3206
+ await this.cache.put(
3207
+ this.cacheConfig.tag ?? await hashQuery(queryString, params),
3208
+ result,
3209
+ // make sure we send tables that were used in a query only if user wants to invalidate it on each write
3210
+ this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
3211
+ this.cacheConfig.tag !== void 0,
3212
+ this.cacheConfig.config
3213
+ );
3214
+ return result;
3215
+ }
3216
+ return fromCache;
3217
+ }
3218
+ try {
3219
+ return await query();
3220
+ } catch (e) {
3221
+ throw new DrizzleQueryError(queryString, params, e);
3222
+ }
3223
+ }
3224
+ };
3225
+ var PgSession = class {
3226
+ constructor(dialect) {
3227
+ this.dialect = dialect;
3228
+ }
3229
+ static [entityKind] = "PgSession";
3230
+ /** @internal */
3231
+ execute(query, token) {
3232
+ return tracer.startActiveSpan("drizzle.operation", () => {
3233
+ const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
3234
+ return this.prepareQuery(
3235
+ this.dialect.sqlToQuery(query),
3236
+ void 0,
3237
+ void 0,
3238
+ false
3239
+ );
3240
+ });
3241
+ return prepared.setToken(token).execute(void 0, token);
3242
+ });
3243
+ }
3244
+ all(query) {
3245
+ return this.prepareQuery(
3246
+ this.dialect.sqlToQuery(query),
3247
+ void 0,
3248
+ void 0,
3249
+ false
3250
+ ).all();
3251
+ }
3252
+ /** @internal */
3253
+ async count(sql2, token) {
3254
+ const res = await this.execute(sql2, token);
3255
+ return Number(
3256
+ res[0]["count"]
3257
+ );
3258
+ }
3259
+ };
3260
+ var PgTransaction = class extends PgDatabase {
3261
+ constructor(dialect, session, schema, nestedIndex = 0) {
3262
+ super(dialect, session, schema);
3263
+ this.schema = schema;
3264
+ this.nestedIndex = nestedIndex;
3265
+ }
3266
+ static [entityKind] = "PgTransaction";
3267
+ rollback() {
3268
+ throw new TransactionRollbackError();
3269
+ }
3270
+ /** @internal */
3271
+ getTransactionConfigSQL(config) {
3272
+ const chunks = [];
3273
+ if (config.isolationLevel) {
3274
+ chunks.push(`isolation level ${config.isolationLevel}`);
3275
+ }
3276
+ if (config.accessMode) {
3277
+ chunks.push(config.accessMode);
3278
+ }
3279
+ if (typeof config.deferrable === "boolean") {
3280
+ chunks.push(config.deferrable ? "deferrable" : "not deferrable");
3281
+ }
3282
+ return sql.raw(chunks.join(" "));
3283
+ }
3284
+ setTransaction(config) {
3285
+ return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
3286
+ }
3287
+ };
3288
+
3289
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/node-postgres/session.js
3290
+ var { Pool, types } = pg;
3291
+ var NodePgPreparedQuery = class extends PgPreparedQuery {
3292
+ constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) {
3293
+ super({ sql: queryString, params }, cache, queryMetadata, cacheConfig);
3294
+ this.client = client;
3295
+ this.queryString = queryString;
3296
+ this.params = params;
3297
+ this.logger = logger;
3298
+ this.fields = fields;
3299
+ this._isResponseInArrayMode = _isResponseInArrayMode;
3300
+ this.customResultMapper = customResultMapper;
3301
+ this.rawQueryConfig = {
3302
+ name,
3303
+ text: queryString,
3304
+ types: {
3305
+ // @ts-ignore
3306
+ getTypeParser: (typeId, format) => {
3307
+ if (typeId === types.builtins.TIMESTAMPTZ) {
3308
+ return (val) => val;
3309
+ }
3310
+ if (typeId === types.builtins.TIMESTAMP) {
3311
+ return (val) => val;
3312
+ }
3313
+ if (typeId === types.builtins.DATE) {
3314
+ return (val) => val;
3315
+ }
3316
+ if (typeId === types.builtins.INTERVAL) {
3317
+ return (val) => val;
3318
+ }
3319
+ if (typeId === 1231) {
3320
+ return (val) => val;
3321
+ }
3322
+ if (typeId === 1115) {
3323
+ return (val) => val;
3324
+ }
3325
+ if (typeId === 1185) {
3326
+ return (val) => val;
3327
+ }
3328
+ if (typeId === 1187) {
3329
+ return (val) => val;
3330
+ }
3331
+ if (typeId === 1182) {
3332
+ return (val) => val;
3333
+ }
3334
+ return types.getTypeParser(typeId, format);
3335
+ }
3336
+ }
3337
+ };
3338
+ this.queryConfig = {
3339
+ name,
3340
+ text: queryString,
3341
+ rowMode: "array",
3342
+ types: {
3343
+ // @ts-ignore
3344
+ getTypeParser: (typeId, format) => {
3345
+ if (typeId === types.builtins.TIMESTAMPTZ) {
3346
+ return (val) => val;
3347
+ }
3348
+ if (typeId === types.builtins.TIMESTAMP) {
3349
+ return (val) => val;
3350
+ }
3351
+ if (typeId === types.builtins.DATE) {
3352
+ return (val) => val;
3353
+ }
3354
+ if (typeId === types.builtins.INTERVAL) {
3355
+ return (val) => val;
3356
+ }
3357
+ if (typeId === 1231) {
3358
+ return (val) => val;
3359
+ }
3360
+ if (typeId === 1115) {
3361
+ return (val) => val;
3362
+ }
3363
+ if (typeId === 1185) {
3364
+ return (val) => val;
3365
+ }
3366
+ if (typeId === 1187) {
3367
+ return (val) => val;
3368
+ }
3369
+ if (typeId === 1182) {
3370
+ return (val) => val;
3371
+ }
3372
+ return types.getTypeParser(typeId, format);
3373
+ }
3374
+ }
3375
+ };
3376
+ }
3377
+ static [entityKind] = "NodePgPreparedQuery";
3378
+ rawQueryConfig;
3379
+ queryConfig;
3380
+ async execute(placeholderValues = {}) {
3381
+ return tracer.startActiveSpan("drizzle.execute", async () => {
3382
+ const params = fillPlaceholders(this.params, placeholderValues);
3383
+ this.logger.logQuery(this.rawQueryConfig.text, params);
3384
+ const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this;
3385
+ if (!fields && !customResultMapper) {
3386
+ return tracer.startActiveSpan("drizzle.driver.execute", async (span) => {
3387
+ span?.setAttributes({
3388
+ "drizzle.query.name": rawQuery.name,
3389
+ "drizzle.query.text": rawQuery.text,
3390
+ "drizzle.query.params": JSON.stringify(params)
3391
+ });
3392
+ return this.queryWithCache(rawQuery.text, params, async () => {
3393
+ return await client.query(rawQuery, params);
3394
+ });
3395
+ });
3396
+ }
3397
+ const result = await tracer.startActiveSpan("drizzle.driver.execute", (span) => {
3398
+ span?.setAttributes({
3399
+ "drizzle.query.name": query.name,
3400
+ "drizzle.query.text": query.text,
3401
+ "drizzle.query.params": JSON.stringify(params)
3402
+ });
3403
+ return this.queryWithCache(query.text, params, async () => {
3404
+ return await client.query(query, params);
3405
+ });
3406
+ });
3407
+ return tracer.startActiveSpan("drizzle.mapResponse", () => {
3408
+ return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
3409
+ });
3410
+ });
3411
+ }
3412
+ all(placeholderValues = {}) {
3413
+ return tracer.startActiveSpan("drizzle.execute", () => {
3414
+ const params = fillPlaceholders(this.params, placeholderValues);
3415
+ this.logger.logQuery(this.rawQueryConfig.text, params);
3416
+ return tracer.startActiveSpan("drizzle.driver.execute", (span) => {
3417
+ span?.setAttributes({
3418
+ "drizzle.query.name": this.rawQueryConfig.name,
3419
+ "drizzle.query.text": this.rawQueryConfig.text,
3420
+ "drizzle.query.params": JSON.stringify(params)
3421
+ });
3422
+ return this.queryWithCache(this.rawQueryConfig.text, params, async () => {
3423
+ return this.client.query(this.rawQueryConfig, params);
3424
+ }).then((result) => result.rows);
3425
+ });
3426
+ });
3427
+ }
3428
+ /** @internal */
3429
+ isResponseInArrayMode() {
3430
+ return this._isResponseInArrayMode;
3431
+ }
3432
+ };
3433
+ var NodePgSession = class _NodePgSession extends PgSession {
3434
+ constructor(client, dialect, schema, options = {}) {
3435
+ super(dialect);
3436
+ this.client = client;
3437
+ this.schema = schema;
3438
+ this.options = options;
3439
+ this.logger = options.logger ?? new NoopLogger();
3440
+ this.cache = options.cache ?? new NoopCache();
3441
+ }
3442
+ static [entityKind] = "NodePgSession";
3443
+ logger;
3444
+ cache;
3445
+ prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
3446
+ return new NodePgPreparedQuery(
3447
+ this.client,
3448
+ query.sql,
3449
+ query.params,
3450
+ this.logger,
3451
+ this.cache,
3452
+ queryMetadata,
3453
+ cacheConfig,
3454
+ fields,
3455
+ name,
3456
+ isResponseInArrayMode,
3457
+ customResultMapper
3458
+ );
3459
+ }
3460
+ async transaction(transaction, config) {
3461
+ const isPool = this.client instanceof Pool || Object.getPrototypeOf(this.client).constructor.name.includes("Pool");
3462
+ const session = isPool ? new _NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this;
3463
+ const tx = new NodePgTransaction(this.dialect, session, this.schema);
3464
+ await tx.execute(sql`begin${config ? sql` ${tx.getTransactionConfigSQL(config)}` : void 0}`);
3465
+ try {
3466
+ const result = await transaction(tx);
3467
+ await tx.execute(sql`commit`);
3468
+ return result;
3469
+ } catch (error) {
3470
+ await tx.execute(sql`rollback`);
3471
+ throw error;
3472
+ } finally {
3473
+ if (isPool) session.client.release();
3474
+ }
3475
+ }
3476
+ async count(sql2) {
3477
+ const res = await this.execute(sql2);
3478
+ return Number(
3479
+ res["rows"][0]["count"]
3480
+ );
3481
+ }
3482
+ };
3483
+ var NodePgTransaction = class _NodePgTransaction extends PgTransaction {
3484
+ static [entityKind] = "NodePgTransaction";
3485
+ async transaction(transaction) {
3486
+ const savepointName = `sp${this.nestedIndex + 1}`;
3487
+ const tx = new _NodePgTransaction(
3488
+ this.dialect,
3489
+ this.session,
3490
+ this.schema,
3491
+ this.nestedIndex + 1
3492
+ );
3493
+ await tx.execute(sql.raw(`savepoint ${savepointName}`));
3494
+ try {
3495
+ const result = await transaction(tx);
3496
+ await tx.execute(sql.raw(`release savepoint ${savepointName}`));
3497
+ return result;
3498
+ } catch (err) {
3499
+ await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
3500
+ throw err;
3501
+ }
3502
+ }
3503
+ };
3504
+
3505
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+pg@8.20.0_kysely@0.29.2_pg@8.22.0/node_modules/drizzle-orm/node-postgres/driver.js
3506
+ var NodePgDriver = class {
3507
+ constructor(client, dialect, options = {}) {
3508
+ this.client = client;
3509
+ this.dialect = dialect;
3510
+ this.options = options;
3511
+ }
3512
+ static [entityKind] = "NodePgDriver";
3513
+ createSession(schema) {
3514
+ return new NodePgSession(this.client, this.dialect, schema, {
3515
+ logger: this.options.logger,
3516
+ cache: this.options.cache
3517
+ });
3518
+ }
3519
+ };
3520
+ var NodePgDatabase = class extends PgDatabase {
3521
+ static [entityKind] = "NodePgDatabase";
3522
+ };
3523
+ function construct(client, config = {}) {
3524
+ const dialect = new PgDialect({ casing: config.casing });
3525
+ let logger;
3526
+ if (config.logger === true) {
3527
+ logger = new DefaultLogger();
3528
+ } else if (config.logger !== false) {
3529
+ logger = config.logger;
3530
+ }
3531
+ let schema;
3532
+ if (config.schema) {
3533
+ const tablesConfig = extractTablesRelationalConfig(
3534
+ config.schema,
3535
+ createTableRelationsHelpers
3536
+ );
3537
+ schema = {
3538
+ fullSchema: config.schema,
3539
+ schema: tablesConfig.tables,
3540
+ tableNamesMap: tablesConfig.tableNamesMap
3541
+ };
3542
+ }
3543
+ const driver = new NodePgDriver(client, dialect, { logger, cache: config.cache });
3544
+ const session = driver.createSession(schema);
3545
+ const db = new NodePgDatabase(dialect, session, schema);
3546
+ db.$client = client;
3547
+ db.$cache = config.cache;
3548
+ if (db.$cache) {
3549
+ db.$cache["invalidate"] = config.cache?.onMutate;
3550
+ }
3551
+ return db;
3552
+ }
3553
+ function drizzle(...params) {
3554
+ if (typeof params[0] === "string") {
3555
+ const instance = new pg2.Pool({
3556
+ connectionString: params[0]
3557
+ });
3558
+ return construct(instance, params[1]);
3559
+ }
3560
+ if (isConfig(params[0])) {
3561
+ const { connection, client, ...drizzleConfig } = params[0];
3562
+ if (client) return construct(client, drizzleConfig);
3563
+ const instance = typeof connection === "string" ? new pg2.Pool({
3564
+ connectionString: connection
3565
+ }) : new pg2.Pool(connection);
3566
+ return construct(instance, drizzleConfig);
3567
+ }
3568
+ return construct(params[0], params[1]);
3569
+ }
3570
+ ((drizzle2) => {
3571
+ function mock(config) {
3572
+ return construct({}, config);
3573
+ }
3574
+ drizzle2.mock = mock;
3575
+ })(drizzle || (drizzle = {}));
3576
+ export {
3577
+ NodePgDatabase,
3578
+ NodePgDriver,
3579
+ NodePgPreparedQuery,
3580
+ NodePgSession,
3581
+ NodePgTransaction,
3582
+ drizzle
3583
+ };
3584
+ //# sourceMappingURL=node-postgres-6JUOVUN5.js.map