drizzle-orm 0.39.1 → 0.39.2-2fb137b

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 (387) hide show
  1. package/column-builder.cjs.map +1 -1
  2. package/column-builder.d.cts +6 -5
  3. package/column-builder.d.ts +6 -5
  4. package/column-builder.js.map +1 -1
  5. package/gel/driver.cjs +97 -0
  6. package/gel/driver.cjs.map +1 -0
  7. package/gel/driver.d.cts +38 -0
  8. package/gel/driver.d.ts +38 -0
  9. package/gel/driver.js +74 -0
  10. package/gel/driver.js.map +1 -0
  11. package/gel/index.cjs +25 -0
  12. package/gel/index.cjs.map +1 -0
  13. package/gel/index.d.cts +2 -0
  14. package/gel/index.d.ts +2 -0
  15. package/gel/index.js +3 -0
  16. package/gel/index.js.map +1 -0
  17. package/gel/migrator.cjs +5 -0
  18. package/gel/migrator.cjs.map +1 -0
  19. package/gel/migrator.d.cts +1 -0
  20. package/gel/migrator.d.ts +1 -0
  21. package/gel/migrator.js +4 -0
  22. package/gel/migrator.js.map +1 -0
  23. package/gel/session.cjs +139 -0
  24. package/gel/session.cjs.map +1 -0
  25. package/gel/session.d.cts +47 -0
  26. package/gel/session.d.ts +47 -0
  27. package/gel/session.js +113 -0
  28. package/gel/session.js.map +1 -0
  29. package/gel-core/alias.cjs +32 -0
  30. package/gel-core/alias.cjs.map +1 -0
  31. package/gel-core/alias.d.cts +4 -0
  32. package/gel-core/alias.d.ts +4 -0
  33. package/gel-core/alias.js +8 -0
  34. package/gel-core/alias.js.map +1 -0
  35. package/gel-core/checks.cjs +58 -0
  36. package/gel-core/checks.cjs.map +1 -0
  37. package/gel-core/checks.d.cts +18 -0
  38. package/gel-core/checks.d.ts +18 -0
  39. package/gel-core/checks.js +32 -0
  40. package/gel-core/checks.js.map +1 -0
  41. package/gel-core/columns/all.cjs +72 -0
  42. package/gel-core/columns/all.cjs.map +1 -0
  43. package/gel-core/columns/all.d.cts +43 -0
  44. package/gel-core/columns/all.d.ts +43 -0
  45. package/gel-core/columns/all.js +48 -0
  46. package/gel-core/columns/all.js.map +1 -0
  47. package/gel-core/columns/bigint.cjs +54 -0
  48. package/gel-core/columns/bigint.cjs.map +1 -0
  49. package/gel-core/columns/bigint.d.cts +23 -0
  50. package/gel-core/columns/bigint.d.ts +23 -0
  51. package/gel-core/columns/bigint.js +28 -0
  52. package/gel-core/columns/bigint.js.map +1 -0
  53. package/gel-core/columns/bigintT.cjs +60 -0
  54. package/gel-core/columns/bigintT.cjs.map +1 -0
  55. package/gel-core/columns/bigintT.d.cts +24 -0
  56. package/gel-core/columns/bigintT.d.ts +24 -0
  57. package/gel-core/columns/bigintT.js +34 -0
  58. package/gel-core/columns/bigintT.js.map +1 -0
  59. package/gel-core/columns/boolean.cjs +53 -0
  60. package/gel-core/columns/boolean.cjs.map +1 -0
  61. package/gel-core/columns/boolean.d.cts +22 -0
  62. package/gel-core/columns/boolean.d.ts +22 -0
  63. package/gel-core/columns/boolean.js +27 -0
  64. package/gel-core/columns/boolean.js.map +1 -0
  65. package/gel-core/columns/bytes.cjs +56 -0
  66. package/gel-core/columns/bytes.cjs.map +1 -0
  67. package/gel-core/columns/bytes.d.cts +22 -0
  68. package/gel-core/columns/bytes.d.ts +22 -0
  69. package/gel-core/columns/bytes.js +30 -0
  70. package/gel-core/columns/bytes.js.map +1 -0
  71. package/gel-core/columns/common.cjs +213 -0
  72. package/gel-core/columns/common.cjs.map +1 -0
  73. package/gel-core/columns/common.d.cts +147 -0
  74. package/gel-core/columns/common.d.ts +147 -0
  75. package/gel-core/columns/common.js +184 -0
  76. package/gel-core/columns/common.js.map +1 -0
  77. package/gel-core/columns/custom.cjs +77 -0
  78. package/gel-core/columns/custom.cjs.map +1 -0
  79. package/gel-core/columns/custom.d.cts +155 -0
  80. package/gel-core/columns/custom.d.ts +155 -0
  81. package/gel-core/columns/custom.js +51 -0
  82. package/gel-core/columns/custom.js.map +1 -0
  83. package/gel-core/columns/date-duration.cjs +56 -0
  84. package/gel-core/columns/date-duration.cjs.map +1 -0
  85. package/gel-core/columns/date-duration.d.cts +23 -0
  86. package/gel-core/columns/date-duration.d.ts +23 -0
  87. package/gel-core/columns/date-duration.js +30 -0
  88. package/gel-core/columns/date-duration.js.map +1 -0
  89. package/gel-core/columns/date.common.cjs +37 -0
  90. package/gel-core/columns/date.common.cjs.map +1 -0
  91. package/gel-core/columns/date.common.d.cts +7 -0
  92. package/gel-core/columns/date.common.d.ts +7 -0
  93. package/gel-core/columns/date.common.js +13 -0
  94. package/gel-core/columns/date.common.js.map +1 -0
  95. package/gel-core/columns/decimal.cjs +56 -0
  96. package/gel-core/columns/decimal.cjs.map +1 -0
  97. package/gel-core/columns/decimal.d.cts +26 -0
  98. package/gel-core/columns/decimal.d.ts +26 -0
  99. package/gel-core/columns/decimal.js +30 -0
  100. package/gel-core/columns/decimal.js.map +1 -0
  101. package/gel-core/columns/double-precision.cjs +62 -0
  102. package/gel-core/columns/double-precision.cjs.map +1 -0
  103. package/gel-core/columns/double-precision.d.cts +23 -0
  104. package/gel-core/columns/double-precision.d.ts +23 -0
  105. package/gel-core/columns/double-precision.js +36 -0
  106. package/gel-core/columns/double-precision.js.map +1 -0
  107. package/gel-core/columns/duration.cjs +53 -0
  108. package/gel-core/columns/duration.cjs.map +1 -0
  109. package/gel-core/columns/duration.d.cts +23 -0
  110. package/gel-core/columns/duration.d.ts +23 -0
  111. package/gel-core/columns/duration.js +27 -0
  112. package/gel-core/columns/duration.js.map +1 -0
  113. package/gel-core/columns/index.cjs +65 -0
  114. package/gel-core/columns/index.cjs.map +1 -0
  115. package/gel-core/columns/index.d.cts +22 -0
  116. package/gel-core/columns/index.d.ts +22 -0
  117. package/gel-core/columns/index.js +23 -0
  118. package/gel-core/columns/index.js.map +1 -0
  119. package/gel-core/columns/int.common.cjs +67 -0
  120. package/gel-core/columns/int.common.cjs.map +1 -0
  121. package/gel-core/columns/int.common.d.cts +15 -0
  122. package/gel-core/columns/int.common.d.ts +15 -0
  123. package/gel-core/columns/int.common.js +43 -0
  124. package/gel-core/columns/int.common.js.map +1 -0
  125. package/gel-core/columns/integer.cjs +54 -0
  126. package/gel-core/columns/integer.cjs.map +1 -0
  127. package/gel-core/columns/integer.d.cts +23 -0
  128. package/gel-core/columns/integer.d.ts +23 -0
  129. package/gel-core/columns/integer.js +28 -0
  130. package/gel-core/columns/integer.js.map +1 -0
  131. package/gel-core/columns/json.cjs +56 -0
  132. package/gel-core/columns/json.cjs.map +1 -0
  133. package/gel-core/columns/json.d.cts +26 -0
  134. package/gel-core/columns/json.d.ts +26 -0
  135. package/gel-core/columns/json.js +30 -0
  136. package/gel-core/columns/json.js.map +1 -0
  137. package/gel-core/columns/localdate.cjs +57 -0
  138. package/gel-core/columns/localdate.cjs.map +1 -0
  139. package/gel-core/columns/localdate.d.cts +24 -0
  140. package/gel-core/columns/localdate.d.ts +24 -0
  141. package/gel-core/columns/localdate.js +31 -0
  142. package/gel-core/columns/localdate.js.map +1 -0
  143. package/gel-core/columns/localtime.cjs +57 -0
  144. package/gel-core/columns/localtime.cjs.map +1 -0
  145. package/gel-core/columns/localtime.d.cts +24 -0
  146. package/gel-core/columns/localtime.d.ts +24 -0
  147. package/gel-core/columns/localtime.js +31 -0
  148. package/gel-core/columns/localtime.js.map +1 -0
  149. package/gel-core/columns/real.cjs +57 -0
  150. package/gel-core/columns/real.cjs.map +1 -0
  151. package/gel-core/columns/real.d.cts +28 -0
  152. package/gel-core/columns/real.d.ts +28 -0
  153. package/gel-core/columns/real.js +31 -0
  154. package/gel-core/columns/real.js.map +1 -0
  155. package/gel-core/columns/relative-duration.cjs +56 -0
  156. package/gel-core/columns/relative-duration.cjs.map +1 -0
  157. package/gel-core/columns/relative-duration.d.cts +23 -0
  158. package/gel-core/columns/relative-duration.d.ts +23 -0
  159. package/gel-core/columns/relative-duration.js +30 -0
  160. package/gel-core/columns/relative-duration.js.map +1 -0
  161. package/gel-core/columns/smallint.cjs +54 -0
  162. package/gel-core/columns/smallint.cjs.map +1 -0
  163. package/gel-core/columns/smallint.d.cts +23 -0
  164. package/gel-core/columns/smallint.d.ts +23 -0
  165. package/gel-core/columns/smallint.js +28 -0
  166. package/gel-core/columns/smallint.js.map +1 -0
  167. package/gel-core/columns/text.cjs +54 -0
  168. package/gel-core/columns/text.cjs.map +1 -0
  169. package/gel-core/columns/text.d.cts +26 -0
  170. package/gel-core/columns/text.d.ts +26 -0
  171. package/gel-core/columns/text.js +28 -0
  172. package/gel-core/columns/text.js.map +1 -0
  173. package/gel-core/columns/timestamp.cjs +60 -0
  174. package/gel-core/columns/timestamp.cjs.map +1 -0
  175. package/gel-core/columns/timestamp.d.cts +28 -0
  176. package/gel-core/columns/timestamp.d.ts +28 -0
  177. package/gel-core/columns/timestamp.js +34 -0
  178. package/gel-core/columns/timestamp.js.map +1 -0
  179. package/gel-core/columns/timestamptz.cjs +60 -0
  180. package/gel-core/columns/timestamptz.cjs.map +1 -0
  181. package/gel-core/columns/timestamptz.d.cts +27 -0
  182. package/gel-core/columns/timestamptz.d.ts +27 -0
  183. package/gel-core/columns/timestamptz.js +34 -0
  184. package/gel-core/columns/timestamptz.js.map +1 -0
  185. package/gel-core/columns/uuid.cjs +53 -0
  186. package/gel-core/columns/uuid.cjs.map +1 -0
  187. package/gel-core/columns/uuid.d.cts +22 -0
  188. package/gel-core/columns/uuid.d.ts +22 -0
  189. package/gel-core/columns/uuid.js +27 -0
  190. package/gel-core/columns/uuid.js.map +1 -0
  191. package/gel-core/db.cjs +338 -0
  192. package/gel-core/db.cjs.map +1 -0
  193. package/gel-core/db.d.cts +281 -0
  194. package/gel-core/db.d.ts +281 -0
  195. package/gel-core/db.js +319 -0
  196. package/gel-core/db.js.map +1 -0
  197. package/gel-core/dialect.cjs +1142 -0
  198. package/gel-core/dialect.cjs.map +1 -0
  199. package/gel-core/dialect.d.cts +62 -0
  200. package/gel-core/dialect.d.ts +62 -0
  201. package/gel-core/dialect.js +1128 -0
  202. package/gel-core/dialect.js.map +1 -0
  203. package/gel-core/expressions.cjs +49 -0
  204. package/gel-core/expressions.cjs.map +1 -0
  205. package/gel-core/expressions.d.cts +8 -0
  206. package/gel-core/expressions.d.ts +8 -0
  207. package/gel-core/expressions.js +22 -0
  208. package/gel-core/expressions.js.map +1 -0
  209. package/gel-core/foreign-keys.cjs +100 -0
  210. package/gel-core/foreign-keys.cjs.map +1 -0
  211. package/gel-core/foreign-keys.d.cts +48 -0
  212. package/gel-core/foreign-keys.d.ts +48 -0
  213. package/gel-core/foreign-keys.js +74 -0
  214. package/gel-core/foreign-keys.js.map +1 -0
  215. package/gel-core/index.cjs +61 -0
  216. package/gel-core/index.cjs.map +1 -0
  217. package/gel-core/index.d.cts +20 -0
  218. package/gel-core/index.d.ts +20 -0
  219. package/gel-core/index.js +21 -0
  220. package/gel-core/index.js.map +1 -0
  221. package/gel-core/indexes.cjs +149 -0
  222. package/gel-core/indexes.cjs.map +1 -0
  223. package/gel-core/indexes.d.cts +79 -0
  224. package/gel-core/indexes.d.ts +79 -0
  225. package/gel-core/indexes.js +121 -0
  226. package/gel-core/indexes.js.map +1 -0
  227. package/gel-core/policies.cjs +58 -0
  228. package/gel-core/policies.cjs.map +1 -0
  229. package/gel-core/policies.d.cts +24 -0
  230. package/gel-core/policies.d.ts +24 -0
  231. package/gel-core/policies.js +33 -0
  232. package/gel-core/policies.js.map +1 -0
  233. package/gel-core/primary-keys.cjs +68 -0
  234. package/gel-core/primary-keys.cjs.map +1 -0
  235. package/gel-core/primary-keys.d.cts +30 -0
  236. package/gel-core/primary-keys.d.ts +30 -0
  237. package/gel-core/primary-keys.js +42 -0
  238. package/gel-core/primary-keys.js.map +1 -0
  239. package/gel-core/query-builders/count.cjs +73 -0
  240. package/gel-core/query-builders/count.cjs.map +1 -0
  241. package/gel-core/query-builders/count.d.cts +25 -0
  242. package/gel-core/query-builders/count.d.ts +25 -0
  243. package/gel-core/query-builders/count.js +49 -0
  244. package/gel-core/query-builders/count.js.map +1 -0
  245. package/gel-core/query-builders/delete.cjs +105 -0
  246. package/gel-core/query-builders/delete.cjs.map +1 -0
  247. package/gel-core/query-builders/delete.d.cts +99 -0
  248. package/gel-core/query-builders/delete.d.ts +99 -0
  249. package/gel-core/query-builders/delete.js +81 -0
  250. package/gel-core/query-builders/delete.js.map +1 -0
  251. package/gel-core/query-builders/index.cjs +35 -0
  252. package/gel-core/query-builders/index.cjs.map +1 -0
  253. package/gel-core/query-builders/index.d.cts +7 -0
  254. package/gel-core/query-builders/index.d.ts +7 -0
  255. package/gel-core/query-builders/index.js +8 -0
  256. package/gel-core/query-builders/index.js.map +1 -0
  257. package/gel-core/query-builders/insert.cjs +218 -0
  258. package/gel-core/query-builders/insert.cjs.map +1 -0
  259. package/gel-core/query-builders/insert.d.cts +116 -0
  260. package/gel-core/query-builders/insert.d.ts +116 -0
  261. package/gel-core/query-builders/insert.js +193 -0
  262. package/gel-core/query-builders/insert.js.map +1 -0
  263. package/gel-core/query-builders/query-builder.cjs +114 -0
  264. package/gel-core/query-builders/query-builder.cjs.map +1 -0
  265. package/gel-core/query-builders/query-builder.d.cts +40 -0
  266. package/gel-core/query-builders/query-builder.d.ts +40 -0
  267. package/gel-core/query-builders/query-builder.js +90 -0
  268. package/gel-core/query-builders/query-builder.js.map +1 -0
  269. package/gel-core/query-builders/query.cjs +139 -0
  270. package/gel-core/query-builders/query.cjs.map +1 -0
  271. package/gel-core/query-builders/query.d.cts +46 -0
  272. package/gel-core/query-builders/query.d.ts +46 -0
  273. package/gel-core/query-builders/query.js +116 -0
  274. package/gel-core/query-builders/query.js.map +1 -0
  275. package/gel-core/query-builders/raw.cjs +57 -0
  276. package/gel-core/query-builders/raw.cjs.map +1 -0
  277. package/gel-core/query-builders/raw.d.cts +22 -0
  278. package/gel-core/query-builders/raw.d.ts +22 -0
  279. package/gel-core/query-builders/raw.js +33 -0
  280. package/gel-core/query-builders/raw.js.map +1 -0
  281. package/gel-core/query-builders/refresh-materialized-view.cjs +77 -0
  282. package/gel-core/query-builders/refresh-materialized-view.cjs.map +1 -0
  283. package/gel-core/query-builders/refresh-materialized-view.d.cts +27 -0
  284. package/gel-core/query-builders/refresh-materialized-view.d.ts +27 -0
  285. package/gel-core/query-builders/refresh-materialized-view.js +53 -0
  286. package/gel-core/query-builders/refresh-materialized-view.js.map +1 -0
  287. package/gel-core/query-builders/select.cjs +775 -0
  288. package/gel-core/query-builders/select.cjs.map +1 -0
  289. package/gel-core/query-builders/select.d.cts +721 -0
  290. package/gel-core/query-builders/select.d.ts +721 -0
  291. package/gel-core/query-builders/select.js +748 -0
  292. package/gel-core/query-builders/select.js.map +1 -0
  293. package/gel-core/query-builders/select.types.cjs +17 -0
  294. package/gel-core/query-builders/select.types.cjs.map +1 -0
  295. package/gel-core/query-builders/select.types.d.cts +138 -0
  296. package/gel-core/query-builders/select.types.d.ts +138 -0
  297. package/gel-core/query-builders/select.types.js +1 -0
  298. package/gel-core/query-builders/select.types.js.map +1 -0
  299. package/gel-core/query-builders/update.cjs +226 -0
  300. package/gel-core/query-builders/update.cjs.map +1 -0
  301. package/gel-core/query-builders/update.d.cts +166 -0
  302. package/gel-core/query-builders/update.d.ts +166 -0
  303. package/gel-core/query-builders/update.js +205 -0
  304. package/gel-core/query-builders/update.js.map +1 -0
  305. package/gel-core/roles.cjs +57 -0
  306. package/gel-core/roles.cjs.map +1 -0
  307. package/gel-core/roles.d.cts +13 -0
  308. package/gel-core/roles.d.ts +13 -0
  309. package/gel-core/roles.js +32 -0
  310. package/gel-core/roles.js.map +1 -0
  311. package/gel-core/schema.cjs +74 -0
  312. package/gel-core/schema.cjs.map +1 -0
  313. package/gel-core/schema.d.cts +15 -0
  314. package/gel-core/schema.d.ts +15 -0
  315. package/gel-core/schema.js +48 -0
  316. package/gel-core/schema.js.map +1 -0
  317. package/gel-core/sequence.cjs +52 -0
  318. package/gel-core/sequence.cjs.map +1 -0
  319. package/gel-core/sequence.d.cts +18 -0
  320. package/gel-core/sequence.d.ts +18 -0
  321. package/gel-core/sequence.js +25 -0
  322. package/gel-core/sequence.js.map +1 -0
  323. package/gel-core/session.cjs +94 -0
  324. package/gel-core/session.cjs.map +1 -0
  325. package/gel-core/session.d.cts +56 -0
  326. package/gel-core/session.d.ts +56 -0
  327. package/gel-core/session.js +68 -0
  328. package/gel-core/session.js.map +1 -0
  329. package/gel-core/subquery.cjs +17 -0
  330. package/gel-core/subquery.cjs.map +1 -0
  331. package/gel-core/subquery.d.cts +5 -0
  332. package/gel-core/subquery.d.ts +5 -0
  333. package/gel-core/subquery.js +1 -0
  334. package/gel-core/subquery.js.map +1 -0
  335. package/gel-core/table.cjs +100 -0
  336. package/gel-core/table.cjs.map +1 -0
  337. package/gel-core/table.d.cts +95 -0
  338. package/gel-core/table.d.ts +95 -0
  339. package/gel-core/table.js +71 -0
  340. package/gel-core/table.js.map +1 -0
  341. package/gel-core/unique-constraint.cjs +89 -0
  342. package/gel-core/unique-constraint.cjs.map +1 -0
  343. package/gel-core/unique-constraint.d.cts +25 -0
  344. package/gel-core/unique-constraint.d.ts +25 -0
  345. package/gel-core/unique-constraint.js +61 -0
  346. package/gel-core/unique-constraint.js.map +1 -0
  347. package/gel-core/utils.cjs +100 -0
  348. package/gel-core/utils.cjs.map +1 -0
  349. package/gel-core/utils.d.cts +51 -0
  350. package/gel-core/utils.d.ts +51 -0
  351. package/gel-core/utils.js +74 -0
  352. package/gel-core/utils.js.map +1 -0
  353. package/gel-core/view-base.cjs +33 -0
  354. package/gel-core/view-base.cjs.map +1 -0
  355. package/gel-core/view-base.d.cts +8 -0
  356. package/gel-core/view-base.d.ts +8 -0
  357. package/gel-core/view-base.js +9 -0
  358. package/gel-core/view-base.js.map +1 -0
  359. package/gel-core/view-common.cjs +29 -0
  360. package/gel-core/view-common.cjs.map +1 -0
  361. package/gel-core/view-common.d.cts +1 -0
  362. package/gel-core/view-common.d.ts +1 -0
  363. package/gel-core/view-common.js +5 -0
  364. package/gel-core/view-common.js.map +1 -0
  365. package/gel-core/view.cjs +302 -0
  366. package/gel-core/view.cjs.map +1 -0
  367. package/gel-core/view.d.cts +150 -0
  368. package/gel-core/view.d.ts +150 -0
  369. package/gel-core/view.js +268 -0
  370. package/gel-core/view.js.map +1 -0
  371. package/neon/neon-identity.cjs +2 -2
  372. package/neon/neon-identity.cjs.map +1 -1
  373. package/neon/neon-identity.d.cts +3 -3
  374. package/neon/neon-identity.d.ts +3 -3
  375. package/neon/neon-identity.js +2 -2
  376. package/neon/neon-identity.js.map +1 -1
  377. package/package.json +782 -49
  378. package/pg-core/table.cjs +2 -0
  379. package/pg-core/table.cjs.map +1 -1
  380. package/pg-core/table.js +2 -0
  381. package/pg-core/table.js.map +1 -1
  382. package/table.cjs.map +1 -1
  383. package/table.js.map +1 -1
  384. package/version.cjs +1 -1
  385. package/version.d.cts +1 -1
  386. package/version.d.ts +1 -1
  387. package/version.js +1 -1
@@ -0,0 +1,1142 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var dialect_exports = {};
20
+ __export(dialect_exports, {
21
+ GelDialect: () => GelDialect
22
+ });
23
+ module.exports = __toCommonJS(dialect_exports);
24
+ var import_alias = require("../alias.cjs");
25
+ var import_casing = require("../casing.cjs");
26
+ var import_column = require("../column.cjs");
27
+ var import_entity = require("../entity.cjs");
28
+ var import_errors = require("../errors.cjs");
29
+ var import_columns = require("./columns/index.cjs");
30
+ var import_table = require("./table.cjs");
31
+ var import_relations = require("../relations.cjs");
32
+ var import_sql = require("../sql/index.cjs");
33
+ var import_sql2 = require("../sql/sql.cjs");
34
+ var import_subquery = require("../subquery.cjs");
35
+ var import_table2 = require("../table.cjs");
36
+ var import_utils = require("../utils.cjs");
37
+ var import_view_common = require("../view-common.cjs");
38
+ var import_timestamp = require("./columns/timestamp.cjs");
39
+ var import_view_base = require("./view-base.cjs");
40
+ class GelDialect {
41
+ static [import_entity.entityKind] = "GelDialect";
42
+ /** @internal */
43
+ casing;
44
+ constructor(config) {
45
+ this.casing = new import_casing.CasingCache(config?.casing);
46
+ }
47
+ // TODO can not migrate gel with drizzle
48
+ // async migrate(migrations: MigrationMeta[], session: GelSession, config: string | MigrationConfig): Promise<void> {
49
+ // const migrationsTable = typeof config === 'string'
50
+ // ? '__drizzle_migrations'
51
+ // : config.migrationsTable ?? '__drizzle_migrations';
52
+ // const migrationsSchema = typeof config === 'string' ? 'drizzle' : config.migrationsSchema ?? 'drizzle';
53
+ // const migrationTableCreate = sql`
54
+ // CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
55
+ // id SERIAL PRIMARY KEY,
56
+ // hash text NOT NULL,
57
+ // created_at bigint
58
+ // )
59
+ // `;
60
+ // await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
61
+ // await session.execute(migrationTableCreate);
62
+ // const dbMigrations = await session.all<{ id: number; hash: string; created_at: string }>(
63
+ // sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${
64
+ // sql.identifier(migrationsTable)
65
+ // } order by created_at desc limit 1`,
66
+ // );
67
+ // const lastDbMigration = dbMigrations[0];
68
+ // await session.transaction(async (tx) => {
69
+ // for await (const migration of migrations) {
70
+ // if (
71
+ // !lastDbMigration
72
+ // || Number(lastDbMigration.created_at) < migration.folderMillis
73
+ // ) {
74
+ // for (const stmt of migration.sql) {
75
+ // await tx.execute(sql.raw(stmt));
76
+ // }
77
+ // await tx.execute(
78
+ // sql`insert into ${sql.identifier(migrationsSchema)}.${
79
+ // sql.identifier(migrationsTable)
80
+ // } ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`,
81
+ // );
82
+ // }
83
+ // }
84
+ // });
85
+ // }
86
+ escapeName(name) {
87
+ return `"${name}"`;
88
+ }
89
+ escapeParam(num) {
90
+ return `$${num + 1}`;
91
+ }
92
+ escapeString(str) {
93
+ return `'${str.replace(/'/g, "''")}'`;
94
+ }
95
+ buildWithCTE(queries) {
96
+ if (!queries?.length)
97
+ return void 0;
98
+ const withSqlChunks = [import_sql2.sql`with `];
99
+ for (const [i, w] of queries.entries()) {
100
+ withSqlChunks.push(import_sql2.sql`${import_sql2.sql.identifier(w._.alias)} as (${w._.sql})`);
101
+ if (i < queries.length - 1) {
102
+ withSqlChunks.push(import_sql2.sql`, `);
103
+ }
104
+ }
105
+ withSqlChunks.push(import_sql2.sql` `);
106
+ return import_sql2.sql.join(withSqlChunks);
107
+ }
108
+ buildDeleteQuery({ table, where, returning, withList }) {
109
+ const withSql = this.buildWithCTE(withList);
110
+ const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
111
+ const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
112
+ return import_sql2.sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
113
+ }
114
+ buildUpdateSet(table, set) {
115
+ const tableColumns = table[import_table2.Table.Symbol.Columns];
116
+ const columnNames = Object.keys(tableColumns).filter(
117
+ (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
118
+ );
119
+ const setSize = columnNames.length;
120
+ return import_sql2.sql.join(columnNames.flatMap((colName, i) => {
121
+ const col = tableColumns[colName];
122
+ const value = set[colName] ?? import_sql2.sql.param(col.onUpdateFn(), col);
123
+ const res = import_sql2.sql`${import_sql2.sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
124
+ if (i < setSize - 1) {
125
+ return [res, import_sql2.sql.raw(", ")];
126
+ }
127
+ return [res];
128
+ }));
129
+ }
130
+ buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
131
+ const withSql = this.buildWithCTE(withList);
132
+ const tableName = table[import_table.GelTable.Symbol.Name];
133
+ const tableSchema = table[import_table.GelTable.Symbol.Schema];
134
+ const origTableName = table[import_table.GelTable.Symbol.OriginalName];
135
+ const alias = tableName === origTableName ? void 0 : tableName;
136
+ const tableSql = import_sql2.sql`${tableSchema ? import_sql2.sql`${import_sql2.sql.identifier(tableSchema)}.` : void 0}${import_sql2.sql.identifier(origTableName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`}`;
137
+ const setSql = this.buildUpdateSet(table, set);
138
+ const fromSql = from && import_sql2.sql.join([import_sql2.sql.raw(" from "), this.buildFromTable(from)]);
139
+ const joinsSql = this.buildJoins(joins);
140
+ const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
141
+ const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
142
+ return import_sql2.sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
143
+ }
144
+ /**
145
+ * Builds selection SQL with provided fields/expressions
146
+ *
147
+ * Examples:
148
+ *
149
+ * `select <selection> from`
150
+ *
151
+ * `insert ... returning <selection>`
152
+ *
153
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
154
+ */
155
+ buildSelection(fields, { isSingleTable = false } = {}) {
156
+ const columnsLen = fields.length;
157
+ const chunks = fields.flatMap(({ field }, i) => {
158
+ const chunk = [];
159
+ if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) && field.isSelectionField) {
160
+ chunk.push(import_sql2.sql.identifier(field.fieldAlias));
161
+ } else if ((0, import_entity.is)(field, import_sql2.SQL.Aliased) || (0, import_entity.is)(field, import_sql2.SQL)) {
162
+ const query = (0, import_entity.is)(field, import_sql2.SQL.Aliased) ? field.sql : field;
163
+ if (isSingleTable) {
164
+ chunk.push(
165
+ new import_sql2.SQL(
166
+ query.queryChunks.map((c) => {
167
+ if ((0, import_entity.is)(c, import_columns.GelColumn)) {
168
+ return import_sql2.sql.identifier(this.casing.getColumnCasing(c));
169
+ }
170
+ return c;
171
+ })
172
+ )
173
+ );
174
+ } else {
175
+ chunk.push(query);
176
+ }
177
+ if ((0, import_entity.is)(field, import_sql2.SQL.Aliased)) {
178
+ chunk.push(import_sql2.sql` as ${import_sql2.sql.identifier(field.fieldAlias)}`);
179
+ }
180
+ } else if ((0, import_entity.is)(field, import_column.Column)) {
181
+ if (isSingleTable) {
182
+ chunk.push(import_sql2.sql.identifier(this.casing.getColumnCasing(field)));
183
+ } else {
184
+ chunk.push(field);
185
+ }
186
+ }
187
+ if (i < columnsLen - 1) {
188
+ chunk.push(import_sql2.sql`, `);
189
+ }
190
+ return chunk;
191
+ });
192
+ return import_sql2.sql.join(chunks);
193
+ }
194
+ buildJoins(joins) {
195
+ if (!joins || joins.length === 0) {
196
+ return void 0;
197
+ }
198
+ const joinsArray = [];
199
+ for (const [index, joinMeta] of joins.entries()) {
200
+ if (index === 0) {
201
+ joinsArray.push(import_sql2.sql` `);
202
+ }
203
+ const table = joinMeta.table;
204
+ const lateralSql = joinMeta.lateral ? import_sql2.sql` lateral` : void 0;
205
+ if ((0, import_entity.is)(table, import_table.GelTable)) {
206
+ const tableName = table[import_table.GelTable.Symbol.Name];
207
+ const tableSchema = table[import_table.GelTable.Symbol.Schema];
208
+ const origTableName = table[import_table.GelTable.Symbol.OriginalName];
209
+ const alias = tableName === origTableName ? void 0 : joinMeta.alias;
210
+ joinsArray.push(
211
+ import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? import_sql2.sql`${import_sql2.sql.identifier(tableSchema)}.` : void 0}${import_sql2.sql.identifier(origTableName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`} on ${joinMeta.on}`
212
+ );
213
+ } else if ((0, import_entity.is)(table, import_sql.View)) {
214
+ const viewName = table[import_view_common.ViewBaseConfig].name;
215
+ const viewSchema = table[import_view_common.ViewBaseConfig].schema;
216
+ const origViewName = table[import_view_common.ViewBaseConfig].originalName;
217
+ const alias = viewName === origViewName ? void 0 : joinMeta.alias;
218
+ joinsArray.push(
219
+ import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? import_sql2.sql`${import_sql2.sql.identifier(viewSchema)}.` : void 0}${import_sql2.sql.identifier(origViewName)}${alias && import_sql2.sql` ${import_sql2.sql.identifier(alias)}`} on ${joinMeta.on}`
220
+ );
221
+ } else {
222
+ joinsArray.push(
223
+ import_sql2.sql`${import_sql2.sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}`
224
+ );
225
+ }
226
+ if (index < joins.length - 1) {
227
+ joinsArray.push(import_sql2.sql` `);
228
+ }
229
+ }
230
+ return import_sql2.sql.join(joinsArray);
231
+ }
232
+ buildFromTable(table) {
233
+ if ((0, import_entity.is)(table, import_table2.Table) && table[import_table2.Table.Symbol.OriginalName] !== table[import_table2.Table.Symbol.Name]) {
234
+ let fullName = import_sql2.sql`${import_sql2.sql.identifier(table[import_table2.Table.Symbol.OriginalName])}`;
235
+ if (table[import_table2.Table.Symbol.Schema]) {
236
+ fullName = import_sql2.sql`${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Schema])}.${fullName}`;
237
+ }
238
+ return import_sql2.sql`${fullName} ${import_sql2.sql.identifier(table[import_table2.Table.Symbol.Name])}`;
239
+ }
240
+ return table;
241
+ }
242
+ buildSelectQuery({
243
+ withList,
244
+ fields,
245
+ fieldsFlat,
246
+ where,
247
+ having,
248
+ table,
249
+ joins,
250
+ orderBy,
251
+ groupBy,
252
+ limit,
253
+ offset,
254
+ lockingClause,
255
+ distinct,
256
+ setOperators
257
+ }) {
258
+ const fieldsList = fieldsFlat ?? (0, import_utils.orderSelectedFields)(fields);
259
+ for (const f of fieldsList) {
260
+ if ((0, import_entity.is)(f.field, import_column.Column) && (0, import_table2.getTableName)(f.field.table) !== ((0, import_entity.is)(table, import_subquery.Subquery) ? table._.alias : (0, import_entity.is)(table, import_view_base.GelViewBase) ? table[import_view_common.ViewBaseConfig].name : (0, import_entity.is)(table, import_sql2.SQL) ? void 0 : (0, import_table2.getTableName)(table)) && !((table2) => joins?.some(
261
+ ({ alias }) => alias === (table2[import_table2.Table.Symbol.IsAlias] ? (0, import_table2.getTableName)(table2) : table2[import_table2.Table.Symbol.BaseName])
262
+ ))(f.field.table)) {
263
+ const tableName = (0, import_table2.getTableName)(f.field.table);
264
+ throw new Error(
265
+ `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?`
266
+ );
267
+ }
268
+ }
269
+ const isSingleTable = !joins || joins.length === 0;
270
+ const withSql = this.buildWithCTE(withList);
271
+ let distinctSql;
272
+ if (distinct) {
273
+ distinctSql = distinct === true ? import_sql2.sql` distinct` : import_sql2.sql` distinct on (${import_sql2.sql.join(distinct.on, import_sql2.sql`, `)})`;
274
+ }
275
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
276
+ const tableSql = this.buildFromTable(table);
277
+ const joinsSql = this.buildJoins(joins);
278
+ const whereSql = where ? import_sql2.sql` where ${where}` : void 0;
279
+ const havingSql = having ? import_sql2.sql` having ${having}` : void 0;
280
+ let orderBySql;
281
+ if (orderBy && orderBy.length > 0) {
282
+ orderBySql = import_sql2.sql` order by ${import_sql2.sql.join(orderBy, import_sql2.sql`, `)}`;
283
+ }
284
+ let groupBySql;
285
+ if (groupBy && groupBy.length > 0) {
286
+ groupBySql = import_sql2.sql` group by ${import_sql2.sql.join(groupBy, import_sql2.sql`, `)}`;
287
+ }
288
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
289
+ const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
290
+ const lockingClauseSql = import_sql2.sql.empty();
291
+ if (lockingClause) {
292
+ const clauseSql = import_sql2.sql` for ${import_sql2.sql.raw(lockingClause.strength)}`;
293
+ if (lockingClause.config.of) {
294
+ clauseSql.append(
295
+ import_sql2.sql` of ${import_sql2.sql.join(
296
+ Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
297
+ import_sql2.sql`, `
298
+ )}`
299
+ );
300
+ }
301
+ if (lockingClause.config.noWait) {
302
+ clauseSql.append(import_sql2.sql` no wait`);
303
+ } else if (lockingClause.config.skipLocked) {
304
+ clauseSql.append(import_sql2.sql` skip locked`);
305
+ }
306
+ lockingClauseSql.append(clauseSql);
307
+ }
308
+ const finalQuery = import_sql2.sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
309
+ if (setOperators.length > 0) {
310
+ return this.buildSetOperations(finalQuery, setOperators);
311
+ }
312
+ return finalQuery;
313
+ }
314
+ buildSetOperations(leftSelect, setOperators) {
315
+ const [setOperator, ...rest] = setOperators;
316
+ if (!setOperator) {
317
+ throw new Error("Cannot pass undefined values to any set operator");
318
+ }
319
+ if (rest.length === 0) {
320
+ return this.buildSetOperationQuery({ leftSelect, setOperator });
321
+ }
322
+ return this.buildSetOperations(
323
+ this.buildSetOperationQuery({ leftSelect, setOperator }),
324
+ rest
325
+ );
326
+ }
327
+ buildSetOperationQuery({
328
+ leftSelect,
329
+ setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
330
+ }) {
331
+ const leftChunk = import_sql2.sql`(${leftSelect.getSQL()}) `;
332
+ const rightChunk = import_sql2.sql`(${rightSelect.getSQL()})`;
333
+ let orderBySql;
334
+ if (orderBy && orderBy.length > 0) {
335
+ const orderByValues = [];
336
+ for (const singleOrderBy of orderBy) {
337
+ if ((0, import_entity.is)(singleOrderBy, import_columns.GelColumn)) {
338
+ orderByValues.push(import_sql2.sql.identifier(singleOrderBy.name));
339
+ } else if ((0, import_entity.is)(singleOrderBy, import_sql2.SQL)) {
340
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
341
+ const chunk = singleOrderBy.queryChunks[i];
342
+ if ((0, import_entity.is)(chunk, import_columns.GelColumn)) {
343
+ singleOrderBy.queryChunks[i] = import_sql2.sql.identifier(chunk.name);
344
+ }
345
+ }
346
+ orderByValues.push(import_sql2.sql`${singleOrderBy}`);
347
+ } else {
348
+ orderByValues.push(import_sql2.sql`${singleOrderBy}`);
349
+ }
350
+ }
351
+ orderBySql = import_sql2.sql` order by ${import_sql2.sql.join(orderByValues, import_sql2.sql`, `)} `;
352
+ }
353
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql2.sql` limit ${limit}` : void 0;
354
+ const operatorChunk = import_sql2.sql.raw(`${type} ${isAll ? "all " : ""}`);
355
+ const offsetSql = offset ? import_sql2.sql` offset ${offset}` : void 0;
356
+ return import_sql2.sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
357
+ }
358
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
359
+ const valuesSqlList = [];
360
+ const columns = table[import_table2.Table.Symbol.Columns];
361
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
362
+ const insertOrder = colEntries.map(
363
+ ([, column]) => import_sql2.sql.identifier(this.casing.getColumnCasing(column))
364
+ );
365
+ if (select) {
366
+ const select2 = valuesOrSelect;
367
+ if ((0, import_entity.is)(select2, import_sql2.SQL)) {
368
+ valuesSqlList.push(select2);
369
+ } else {
370
+ valuesSqlList.push(select2.getSQL());
371
+ }
372
+ } else {
373
+ const values = valuesOrSelect;
374
+ valuesSqlList.push(import_sql2.sql.raw("values "));
375
+ for (const [valueIndex, value] of values.entries()) {
376
+ const valueList = [];
377
+ for (const [fieldName, col] of colEntries) {
378
+ const colValue = value[fieldName];
379
+ if (colValue === void 0 || (0, import_entity.is)(colValue, import_sql2.Param) && colValue.value === void 0) {
380
+ if (col.defaultFn !== void 0) {
381
+ const defaultFnResult = col.defaultFn();
382
+ const defaultValue = (0, import_entity.is)(defaultFnResult, import_sql2.SQL) ? defaultFnResult : import_sql2.sql.param(defaultFnResult, col);
383
+ valueList.push(defaultValue);
384
+ } else if (!col.default && col.onUpdateFn !== void 0) {
385
+ const onUpdateFnResult = col.onUpdateFn();
386
+ const newValue = (0, import_entity.is)(onUpdateFnResult, import_sql2.SQL) ? onUpdateFnResult : import_sql2.sql.param(onUpdateFnResult, col);
387
+ valueList.push(newValue);
388
+ } else {
389
+ valueList.push(import_sql2.sql`default`);
390
+ }
391
+ } else {
392
+ valueList.push(colValue);
393
+ }
394
+ }
395
+ valuesSqlList.push(valueList);
396
+ if (valueIndex < values.length - 1) {
397
+ valuesSqlList.push(import_sql2.sql`, `);
398
+ }
399
+ }
400
+ }
401
+ const withSql = this.buildWithCTE(withList);
402
+ const valuesSql = import_sql2.sql.join(valuesSqlList);
403
+ const returningSql = returning ? import_sql2.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
404
+ const onConflictSql = onConflict ? import_sql2.sql` on conflict ${onConflict}` : void 0;
405
+ const overridingSql = overridingSystemValue_ === true ? import_sql2.sql`overriding system value ` : void 0;
406
+ return import_sql2.sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
407
+ }
408
+ buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
409
+ const concurrentlySql = concurrently ? import_sql2.sql` concurrently` : void 0;
410
+ const withNoDataSql = withNoData ? import_sql2.sql` with no data` : void 0;
411
+ return import_sql2.sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
412
+ }
413
+ prepareTyping(encoder) {
414
+ if ((0, import_entity.is)(encoder, import_columns.GelJson)) {
415
+ return "json";
416
+ } else if ((0, import_entity.is)(encoder, import_columns.GelDecimal)) {
417
+ return "decimal";
418
+ } else if ((0, import_entity.is)(encoder, import_timestamp.GelTimestamp)) {
419
+ return "timestamp";
420
+ } else if ((0, import_entity.is)(encoder, import_columns.GelUUID)) {
421
+ return "uuid";
422
+ } else {
423
+ return "none";
424
+ }
425
+ }
426
+ sqlToQuery(sql2, invokeSource) {
427
+ return sql2.toQuery({
428
+ casing: this.casing,
429
+ escapeName: this.escapeName,
430
+ escapeParam: this.escapeParam,
431
+ escapeString: this.escapeString,
432
+ prepareTyping: this.prepareTyping,
433
+ invokeSource
434
+ });
435
+ }
436
+ // buildRelationalQueryWithPK({
437
+ // fullSchema,
438
+ // schema,
439
+ // tableNamesMap,
440
+ // table,
441
+ // tableConfig,
442
+ // queryConfig: config,
443
+ // tableAlias,
444
+ // isRoot = false,
445
+ // joinOn,
446
+ // }: {
447
+ // fullSchema: Record<string, unknown>;
448
+ // schema: TablesRelationalConfig;
449
+ // tableNamesMap: Record<string, string>;
450
+ // table: GelTable;
451
+ // tableConfig: TableRelationalConfig;
452
+ // queryConfig: true | DBQueryConfig<'many', true>;
453
+ // tableAlias: string;
454
+ // isRoot?: boolean;
455
+ // joinOn?: SQL;
456
+ // }): BuildRelationalQueryResult<GelTable, GelColumn> {
457
+ // // For { "<relation>": true }, return a table with selection of all columns
458
+ // if (config === true) {
459
+ // const selectionEntries = Object.entries(tableConfig.columns);
460
+ // const selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = selectionEntries.map((
461
+ // [key, value],
462
+ // ) => ({
463
+ // dbKey: value.name,
464
+ // tsKey: key,
465
+ // field: value as GelColumn,
466
+ // relationTableTsKey: undefined,
467
+ // isJson: false,
468
+ // selection: [],
469
+ // }));
470
+ // return {
471
+ // tableTsKey: tableConfig.tsName,
472
+ // sql: table,
473
+ // selection,
474
+ // };
475
+ // }
476
+ // // let selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = [];
477
+ // // let selectionForBuild = selection;
478
+ // const aliasedColumns = Object.fromEntries(
479
+ // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
480
+ // );
481
+ // const aliasedRelations = Object.fromEntries(
482
+ // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
483
+ // );
484
+ // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
485
+ // let where, hasUserDefinedWhere;
486
+ // if (config.where) {
487
+ // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
488
+ // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
489
+ // hasUserDefinedWhere = !!where;
490
+ // }
491
+ // where = and(joinOn, where);
492
+ // // const fieldsSelection: { tsKey: string; value: GelColumn | SQL.Aliased; isExtra?: boolean }[] = [];
493
+ // let joins: Join[] = [];
494
+ // let selectedColumns: string[] = [];
495
+ // // Figure out which columns to select
496
+ // if (config.columns) {
497
+ // let isIncludeMode = false;
498
+ // for (const [field, value] of Object.entries(config.columns)) {
499
+ // if (value === undefined) {
500
+ // continue;
501
+ // }
502
+ // if (field in tableConfig.columns) {
503
+ // if (!isIncludeMode && value === true) {
504
+ // isIncludeMode = true;
505
+ // }
506
+ // selectedColumns.push(field);
507
+ // }
508
+ // }
509
+ // if (selectedColumns.length > 0) {
510
+ // selectedColumns = isIncludeMode
511
+ // ? selectedColumns.filter((c) => config.columns?.[c] === true)
512
+ // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
513
+ // }
514
+ // } else {
515
+ // // Select all columns if selection is not specified
516
+ // selectedColumns = Object.keys(tableConfig.columns);
517
+ // }
518
+ // // for (const field of selectedColumns) {
519
+ // // const column = tableConfig.columns[field]! as GelColumn;
520
+ // // fieldsSelection.push({ tsKey: field, value: column });
521
+ // // }
522
+ // let initiallySelectedRelations: {
523
+ // tsKey: string;
524
+ // queryConfig: true | DBQueryConfig<'many', false>;
525
+ // relation: Relation;
526
+ // }[] = [];
527
+ // // let selectedRelations: BuildRelationalQueryResult<GelTable, GelColumn>['selection'] = [];
528
+ // // Figure out which relations to select
529
+ // if (config.with) {
530
+ // initiallySelectedRelations = Object.entries(config.with)
531
+ // .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
532
+ // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
533
+ // }
534
+ // const manyRelations = initiallySelectedRelations.filter((r) =>
535
+ // is(r.relation, Many)
536
+ // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
537
+ // );
538
+ // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
539
+ // const isInnermostQuery = manyRelations.length < 2;
540
+ // const selectedExtras: {
541
+ // tsKey: string;
542
+ // value: SQL.Aliased;
543
+ // }[] = [];
544
+ // // Figure out which extras to select
545
+ // if (isInnermostQuery && config.extras) {
546
+ // const extras = typeof config.extras === 'function'
547
+ // ? config.extras(aliasedFields, { sql })
548
+ // : config.extras;
549
+ // for (const [tsKey, value] of Object.entries(extras)) {
550
+ // selectedExtras.push({
551
+ // tsKey,
552
+ // value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
553
+ // });
554
+ // }
555
+ // }
556
+ // // Transform `fieldsSelection` into `selection`
557
+ // // `fieldsSelection` shouldn't be used after this point
558
+ // // for (const { tsKey, value, isExtra } of fieldsSelection) {
559
+ // // selection.push({
560
+ // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
561
+ // // tsKey,
562
+ // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
563
+ // // relationTableTsKey: undefined,
564
+ // // isJson: false,
565
+ // // isExtra,
566
+ // // selection: [],
567
+ // // });
568
+ // // }
569
+ // let orderByOrig = typeof config.orderBy === 'function'
570
+ // ? config.orderBy(aliasedFields, orderByOperators)
571
+ // : config.orderBy ?? [];
572
+ // if (!Array.isArray(orderByOrig)) {
573
+ // orderByOrig = [orderByOrig];
574
+ // }
575
+ // const orderBy = orderByOrig.map((orderByValue) => {
576
+ // if (is(orderByValue, Column)) {
577
+ // return aliasedTableColumn(orderByValue, tableAlias) as GelColumn;
578
+ // }
579
+ // return mapColumnsInSQLToAlias(orderByValue, tableAlias);
580
+ // });
581
+ // const limit = isInnermostQuery ? config.limit : undefined;
582
+ // const offset = isInnermostQuery ? config.offset : undefined;
583
+ // // For non-root queries without additional config except columns, return a table with selection
584
+ // if (
585
+ // !isRoot
586
+ // && initiallySelectedRelations.length === 0
587
+ // && selectedExtras.length === 0
588
+ // && !where
589
+ // && orderBy.length === 0
590
+ // && limit === undefined
591
+ // && offset === undefined
592
+ // ) {
593
+ // return {
594
+ // tableTsKey: tableConfig.tsName,
595
+ // sql: table,
596
+ // selection: selectedColumns.map((key) => ({
597
+ // dbKey: tableConfig.columns[key]!.name,
598
+ // tsKey: key,
599
+ // field: tableConfig.columns[key] as GelColumn,
600
+ // relationTableTsKey: undefined,
601
+ // isJson: false,
602
+ // selection: [],
603
+ // })),
604
+ // };
605
+ // }
606
+ // const selectedRelationsWithoutPK:
607
+ // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
608
+ // for (
609
+ // const {
610
+ // tsKey: selectedRelationTsKey,
611
+ // queryConfig: selectedRelationConfigValue,
612
+ // relation,
613
+ // } of initiallySelectedRelations
614
+ // ) {
615
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
616
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
617
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
618
+ // const relationTable = schema[relationTableTsName]!;
619
+ // if (relationTable.primaryKey.length > 0) {
620
+ // continue;
621
+ // }
622
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
623
+ // const joinOn = and(
624
+ // ...normalizedRelation.fields.map((field, i) =>
625
+ // eq(
626
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
627
+ // aliasedTableColumn(field, tableAlias),
628
+ // )
629
+ // ),
630
+ // );
631
+ // const builtRelation = this.buildRelationalQueryWithoutPK({
632
+ // fullSchema,
633
+ // schema,
634
+ // tableNamesMap,
635
+ // table: fullSchema[relationTableTsName] as GelTable,
636
+ // tableConfig: schema[relationTableTsName]!,
637
+ // queryConfig: selectedRelationConfigValue,
638
+ // tableAlias: relationTableAlias,
639
+ // joinOn,
640
+ // nestedQueryRelation: relation,
641
+ // });
642
+ // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
643
+ // joins.push({
644
+ // on: sql`true`,
645
+ // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
646
+ // alias: relationTableAlias,
647
+ // joinType: 'left',
648
+ // lateral: true,
649
+ // });
650
+ // selectedRelations.push({
651
+ // dbKey: selectedRelationTsKey,
652
+ // tsKey: selectedRelationTsKey,
653
+ // field,
654
+ // relationTableTsKey: relationTableTsName,
655
+ // isJson: true,
656
+ // selection: builtRelation.selection,
657
+ // });
658
+ // }
659
+ // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
660
+ // is(r.relation, One)
661
+ // );
662
+ // // Process all One relations with PKs, because they can all be joined on the same level
663
+ // for (
664
+ // const {
665
+ // tsKey: selectedRelationTsKey,
666
+ // queryConfig: selectedRelationConfigValue,
667
+ // relation,
668
+ // } of oneRelations
669
+ // ) {
670
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
671
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
672
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
673
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
674
+ // const relationTable = schema[relationTableTsName]!;
675
+ // if (relationTable.primaryKey.length === 0) {
676
+ // continue;
677
+ // }
678
+ // const joinOn = and(
679
+ // ...normalizedRelation.fields.map((field, i) =>
680
+ // eq(
681
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
682
+ // aliasedTableColumn(field, tableAlias),
683
+ // )
684
+ // ),
685
+ // );
686
+ // const builtRelation = this.buildRelationalQueryWithPK({
687
+ // fullSchema,
688
+ // schema,
689
+ // tableNamesMap,
690
+ // table: fullSchema[relationTableTsName] as GelTable,
691
+ // tableConfig: schema[relationTableTsName]!,
692
+ // queryConfig: selectedRelationConfigValue,
693
+ // tableAlias: relationTableAlias,
694
+ // joinOn,
695
+ // });
696
+ // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
697
+ // sql.join(
698
+ // builtRelation.selection.map(({ field }) =>
699
+ // is(field, SQL.Aliased)
700
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
701
+ // : is(field, Column)
702
+ // ? aliasedTableColumn(field, relationTableAlias)
703
+ // : field
704
+ // ),
705
+ // sql`, `,
706
+ // )
707
+ // }) end`.as(selectedRelationTsKey);
708
+ // const isLateralJoin = is(builtRelation.sql, SQL);
709
+ // joins.push({
710
+ // on: isLateralJoin ? sql`true` : joinOn,
711
+ // table: is(builtRelation.sql, SQL)
712
+ // ? new Subquery(builtRelation.sql, {}, relationTableAlias)
713
+ // : aliasedTable(builtRelation.sql, relationTableAlias),
714
+ // alias: relationTableAlias,
715
+ // joinType: 'left',
716
+ // lateral: is(builtRelation.sql, SQL),
717
+ // });
718
+ // selectedRelations.push({
719
+ // dbKey: selectedRelationTsKey,
720
+ // tsKey: selectedRelationTsKey,
721
+ // field,
722
+ // relationTableTsKey: relationTableTsName,
723
+ // isJson: true,
724
+ // selection: builtRelation.selection,
725
+ // });
726
+ // }
727
+ // let distinct: GelSelectConfig['distinct'];
728
+ // let tableFrom: GelTable | Subquery = table;
729
+ // // Process first Many relation - each one requires a nested subquery
730
+ // const manyRelation = manyRelations[0];
731
+ // if (manyRelation) {
732
+ // const {
733
+ // tsKey: selectedRelationTsKey,
734
+ // queryConfig: selectedRelationQueryConfig,
735
+ // relation,
736
+ // } = manyRelation;
737
+ // distinct = {
738
+ // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as GelColumn, tableAlias)),
739
+ // };
740
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
741
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
742
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
743
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
744
+ // const joinOn = and(
745
+ // ...normalizedRelation.fields.map((field, i) =>
746
+ // eq(
747
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
748
+ // aliasedTableColumn(field, tableAlias),
749
+ // )
750
+ // ),
751
+ // );
752
+ // const builtRelationJoin = this.buildRelationalQueryWithPK({
753
+ // fullSchema,
754
+ // schema,
755
+ // tableNamesMap,
756
+ // table: fullSchema[relationTableTsName] as GelTable,
757
+ // tableConfig: schema[relationTableTsName]!,
758
+ // queryConfig: selectedRelationQueryConfig,
759
+ // tableAlias: relationTableAlias,
760
+ // joinOn,
761
+ // });
762
+ // const builtRelationSelectionField = sql`case when ${
763
+ // sql.identifier(relationTableAlias)
764
+ // } is null then '[]' else json_agg(json_build_array(${
765
+ // sql.join(
766
+ // builtRelationJoin.selection.map(({ field }) =>
767
+ // is(field, SQL.Aliased)
768
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
769
+ // : is(field, Column)
770
+ // ? aliasedTableColumn(field, relationTableAlias)
771
+ // : field
772
+ // ),
773
+ // sql`, `,
774
+ // )
775
+ // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
776
+ // const isLateralJoin = is(builtRelationJoin.sql, SQL);
777
+ // joins.push({
778
+ // on: isLateralJoin ? sql`true` : joinOn,
779
+ // table: isLateralJoin
780
+ // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
781
+ // : aliasedTable(builtRelationJoin.sql as GelTable, relationTableAlias),
782
+ // alias: relationTableAlias,
783
+ // joinType: 'left',
784
+ // lateral: isLateralJoin,
785
+ // });
786
+ // // Build the "from" subquery with the remaining Many relations
787
+ // const builtTableFrom = this.buildRelationalQueryWithPK({
788
+ // fullSchema,
789
+ // schema,
790
+ // tableNamesMap,
791
+ // table,
792
+ // tableConfig,
793
+ // queryConfig: {
794
+ // ...config,
795
+ // where: undefined,
796
+ // orderBy: undefined,
797
+ // limit: undefined,
798
+ // offset: undefined,
799
+ // with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
800
+ // (result, { tsKey, queryConfig: configValue }) => {
801
+ // result[tsKey] = configValue;
802
+ // return result;
803
+ // },
804
+ // {},
805
+ // ),
806
+ // },
807
+ // tableAlias,
808
+ // });
809
+ // selectedRelations.push({
810
+ // dbKey: selectedRelationTsKey,
811
+ // tsKey: selectedRelationTsKey,
812
+ // field: builtRelationSelectionField,
813
+ // relationTableTsKey: relationTableTsName,
814
+ // isJson: true,
815
+ // selection: builtRelationJoin.selection,
816
+ // });
817
+ // // selection = builtTableFrom.selection.map((item) =>
818
+ // // is(item.field, SQL.Aliased)
819
+ // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
820
+ // // : item
821
+ // // );
822
+ // // selectionForBuild = [{
823
+ // // dbKey: '*',
824
+ // // tsKey: '*',
825
+ // // field: sql`${sql.identifier(tableAlias)}.*`,
826
+ // // selection: [],
827
+ // // isJson: false,
828
+ // // relationTableTsKey: undefined,
829
+ // // }];
830
+ // // const newSelectionItem: (typeof selection)[number] = {
831
+ // // dbKey: selectedRelationTsKey,
832
+ // // tsKey: selectedRelationTsKey,
833
+ // // field,
834
+ // // relationTableTsKey: relationTableTsName,
835
+ // // isJson: true,
836
+ // // selection: builtRelationJoin.selection,
837
+ // // };
838
+ // // selection.push(newSelectionItem);
839
+ // // selectionForBuild.push(newSelectionItem);
840
+ // tableFrom = is(builtTableFrom.sql, GelTable)
841
+ // ? builtTableFrom.sql
842
+ // : new Subquery(builtTableFrom.sql, {}, tableAlias);
843
+ // }
844
+ // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
845
+ // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
846
+ // }
847
+ // let selection: BuildRelationalQueryResult<GelTable, GelColumn>['selection'];
848
+ // function prepareSelectedColumns() {
849
+ // return selectedColumns.map((key) => ({
850
+ // dbKey: tableConfig.columns[key]!.name,
851
+ // tsKey: key,
852
+ // field: tableConfig.columns[key] as GelColumn,
853
+ // relationTableTsKey: undefined,
854
+ // isJson: false,
855
+ // selection: [],
856
+ // }));
857
+ // }
858
+ // function prepareSelectedExtras() {
859
+ // return selectedExtras.map((item) => ({
860
+ // dbKey: item.value.fieldAlias,
861
+ // tsKey: item.tsKey,
862
+ // field: item.value,
863
+ // relationTableTsKey: undefined,
864
+ // isJson: false,
865
+ // selection: [],
866
+ // }));
867
+ // }
868
+ // if (isRoot) {
869
+ // selection = [
870
+ // ...prepareSelectedColumns(),
871
+ // ...prepareSelectedExtras(),
872
+ // ];
873
+ // }
874
+ // if (hasUserDefinedWhere || orderBy.length > 0) {
875
+ // tableFrom = new Subquery(
876
+ // this.buildSelectQuery({
877
+ // table: is(tableFrom, GelTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
878
+ // fields: {},
879
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
880
+ // path: [],
881
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
882
+ // })),
883
+ // joins,
884
+ // distinct,
885
+ // }),
886
+ // {},
887
+ // tableAlias,
888
+ // );
889
+ // selectionForBuild = selection.map((item) =>
890
+ // is(item.field, SQL.Aliased)
891
+ // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
892
+ // : item
893
+ // );
894
+ // joins = [];
895
+ // distinct = undefined;
896
+ // }
897
+ // const result = this.buildSelectQuery({
898
+ // table: is(tableFrom, GelTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
899
+ // fields: {},
900
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
901
+ // path: [],
902
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
903
+ // })),
904
+ // where,
905
+ // limit,
906
+ // offset,
907
+ // joins,
908
+ // orderBy,
909
+ // distinct,
910
+ // });
911
+ // return {
912
+ // tableTsKey: tableConfig.tsName,
913
+ // sql: result,
914
+ // selection,
915
+ // };
916
+ // }
917
+ buildRelationalQueryWithoutPK({
918
+ fullSchema,
919
+ schema,
920
+ tableNamesMap,
921
+ table,
922
+ tableConfig,
923
+ queryConfig: config,
924
+ tableAlias,
925
+ nestedQueryRelation,
926
+ joinOn
927
+ }) {
928
+ let selection = [];
929
+ let limit, offset, orderBy = [], where;
930
+ const joins = [];
931
+ if (config === true) {
932
+ const selectionEntries = Object.entries(tableConfig.columns);
933
+ selection = selectionEntries.map(([key, value]) => ({
934
+ dbKey: value.name,
935
+ tsKey: key,
936
+ field: (0, import_alias.aliasedTableColumn)(value, tableAlias),
937
+ relationTableTsKey: void 0,
938
+ isJson: false,
939
+ selection: []
940
+ }));
941
+ } else {
942
+ const aliasedColumns = Object.fromEntries(
943
+ Object.entries(tableConfig.columns).map(([key, value]) => [key, (0, import_alias.aliasedTableColumn)(value, tableAlias)])
944
+ );
945
+ if (config.where) {
946
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0, import_relations.getOperators)()) : config.where;
947
+ where = whereSql && (0, import_alias.mapColumnsInSQLToAlias)(whereSql, tableAlias);
948
+ }
949
+ const fieldsSelection = [];
950
+ let selectedColumns = [];
951
+ if (config.columns) {
952
+ let isIncludeMode = false;
953
+ for (const [field, value] of Object.entries(config.columns)) {
954
+ if (value === void 0) {
955
+ continue;
956
+ }
957
+ if (field in tableConfig.columns) {
958
+ if (!isIncludeMode && value === true) {
959
+ isIncludeMode = true;
960
+ }
961
+ selectedColumns.push(field);
962
+ }
963
+ }
964
+ if (selectedColumns.length > 0) {
965
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
966
+ }
967
+ } else {
968
+ selectedColumns = Object.keys(tableConfig.columns);
969
+ }
970
+ for (const field of selectedColumns) {
971
+ const column = tableConfig.columns[field];
972
+ fieldsSelection.push({ tsKey: field, value: column });
973
+ }
974
+ let selectedRelations = [];
975
+ if (config.with) {
976
+ selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
977
+ }
978
+ let extras;
979
+ if (config.extras) {
980
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: import_sql2.sql }) : config.extras;
981
+ for (const [tsKey, value] of Object.entries(extras)) {
982
+ fieldsSelection.push({
983
+ tsKey,
984
+ value: (0, import_alias.mapColumnsInAliasedSQLToAlias)(value, tableAlias)
985
+ });
986
+ }
987
+ }
988
+ for (const { tsKey, value } of fieldsSelection) {
989
+ selection.push({
990
+ dbKey: (0, import_entity.is)(value, import_sql2.SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
991
+ tsKey,
992
+ field: (0, import_entity.is)(value, import_column.Column) ? (0, import_alias.aliasedTableColumn)(value, tableAlias) : value,
993
+ relationTableTsKey: void 0,
994
+ isJson: false,
995
+ selection: []
996
+ });
997
+ }
998
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0, import_relations.getOrderByOperators)()) : config.orderBy ?? [];
999
+ if (!Array.isArray(orderByOrig)) {
1000
+ orderByOrig = [orderByOrig];
1001
+ }
1002
+ orderBy = orderByOrig.map((orderByValue) => {
1003
+ if ((0, import_entity.is)(orderByValue, import_column.Column)) {
1004
+ return (0, import_alias.aliasedTableColumn)(orderByValue, tableAlias);
1005
+ }
1006
+ return (0, import_alias.mapColumnsInSQLToAlias)(orderByValue, tableAlias);
1007
+ });
1008
+ limit = config.limit;
1009
+ offset = config.offset;
1010
+ for (const {
1011
+ tsKey: selectedRelationTsKey,
1012
+ queryConfig: selectedRelationConfigValue,
1013
+ relation
1014
+ } of selectedRelations) {
1015
+ const normalizedRelation = (0, import_relations.normalizeRelation)(schema, tableNamesMap, relation);
1016
+ const relationTableName = (0, import_table2.getTableUniqueName)(relation.referencedTable);
1017
+ const relationTableTsName = tableNamesMap[relationTableName];
1018
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1019
+ const joinOn2 = (0, import_sql.and)(
1020
+ ...normalizedRelation.fields.map(
1021
+ (field2, i) => (0, import_sql.eq)(
1022
+ (0, import_alias.aliasedTableColumn)(normalizedRelation.references[i], relationTableAlias),
1023
+ (0, import_alias.aliasedTableColumn)(field2, tableAlias)
1024
+ )
1025
+ )
1026
+ );
1027
+ const builtRelation = this.buildRelationalQueryWithoutPK({
1028
+ fullSchema,
1029
+ schema,
1030
+ tableNamesMap,
1031
+ table: fullSchema[relationTableTsName],
1032
+ tableConfig: schema[relationTableTsName],
1033
+ queryConfig: (0, import_entity.is)(relation, import_relations.One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
1034
+ tableAlias: relationTableAlias,
1035
+ joinOn: joinOn2,
1036
+ nestedQueryRelation: relation
1037
+ });
1038
+ const field = import_sql2.sql`${import_sql2.sql.identifier(relationTableAlias)}.${import_sql2.sql.identifier("data")}`.as(selectedRelationTsKey);
1039
+ joins.push({
1040
+ on: import_sql2.sql`true`,
1041
+ table: new import_subquery.Subquery(builtRelation.sql, {}, relationTableAlias),
1042
+ alias: relationTableAlias,
1043
+ joinType: "left",
1044
+ lateral: true
1045
+ });
1046
+ selection.push({
1047
+ dbKey: selectedRelationTsKey,
1048
+ tsKey: selectedRelationTsKey,
1049
+ field,
1050
+ relationTableTsKey: relationTableTsName,
1051
+ isJson: true,
1052
+ selection: builtRelation.selection
1053
+ });
1054
+ }
1055
+ }
1056
+ if (selection.length === 0) {
1057
+ throw new import_errors.DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
1058
+ }
1059
+ let result;
1060
+ where = (0, import_sql.and)(joinOn, where);
1061
+ if (nestedQueryRelation) {
1062
+ let field = import_sql2.sql`json_build_array(${import_sql2.sql.join(
1063
+ selection.map(
1064
+ ({ field: field2, tsKey, isJson }) => isJson ? import_sql2.sql`${import_sql2.sql.identifier(`${tableAlias}_${tsKey}`)}.${import_sql2.sql.identifier("data")}` : (0, import_entity.is)(field2, import_sql2.SQL.Aliased) ? field2.sql : field2
1065
+ ),
1066
+ import_sql2.sql`, `
1067
+ )})`;
1068
+ if ((0, import_entity.is)(nestedQueryRelation, import_relations.Many)) {
1069
+ field = import_sql2.sql`coalesce(json_agg(${field}${orderBy.length > 0 ? import_sql2.sql` order by ${import_sql2.sql.join(orderBy, import_sql2.sql`, `)}` : void 0}), '[]'::json)`;
1070
+ }
1071
+ const nestedSelection = [{
1072
+ dbKey: "data",
1073
+ tsKey: "data",
1074
+ field: field.as("data"),
1075
+ isJson: true,
1076
+ relationTableTsKey: tableConfig.tsName,
1077
+ selection
1078
+ }];
1079
+ const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
1080
+ if (needsSubquery) {
1081
+ result = this.buildSelectQuery({
1082
+ table: (0, import_alias.aliasedTable)(table, tableAlias),
1083
+ fields: {},
1084
+ fieldsFlat: [{
1085
+ path: [],
1086
+ field: import_sql2.sql.raw("*")
1087
+ }],
1088
+ where,
1089
+ limit,
1090
+ offset,
1091
+ orderBy,
1092
+ setOperators: []
1093
+ });
1094
+ where = void 0;
1095
+ limit = void 0;
1096
+ offset = void 0;
1097
+ orderBy = [];
1098
+ } else {
1099
+ result = (0, import_alias.aliasedTable)(table, tableAlias);
1100
+ }
1101
+ result = this.buildSelectQuery({
1102
+ table: (0, import_entity.is)(result, import_table.GelTable) ? result : new import_subquery.Subquery(result, {}, tableAlias),
1103
+ fields: {},
1104
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
1105
+ path: [],
1106
+ field: (0, import_entity.is)(field2, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field2, tableAlias) : field2
1107
+ })),
1108
+ joins,
1109
+ where,
1110
+ limit,
1111
+ offset,
1112
+ orderBy,
1113
+ setOperators: []
1114
+ });
1115
+ } else {
1116
+ result = this.buildSelectQuery({
1117
+ table: (0, import_alias.aliasedTable)(table, tableAlias),
1118
+ fields: {},
1119
+ fieldsFlat: selection.map(({ field }) => ({
1120
+ path: [],
1121
+ field: (0, import_entity.is)(field, import_column.Column) ? (0, import_alias.aliasedTableColumn)(field, tableAlias) : field
1122
+ })),
1123
+ joins,
1124
+ where,
1125
+ limit,
1126
+ offset,
1127
+ orderBy,
1128
+ setOperators: []
1129
+ });
1130
+ }
1131
+ return {
1132
+ tableTsKey: tableConfig.tsName,
1133
+ sql: result,
1134
+ selection
1135
+ };
1136
+ }
1137
+ }
1138
+ // Annotate the CommonJS export names for ESM import in node:
1139
+ 0 && (module.exports = {
1140
+ GelDialect
1141
+ });
1142
+ //# sourceMappingURL=dialect.cjs.map