drizzle-orm 0.28.3 → 0.28.4

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 (752) hide show
  1. package/{alias-d302772a.mjs → alias-e80df77c.mjs} +2302 -2299
  2. package/alias-e80df77c.mjs.map +1 -0
  3. package/alias.d.cts +31 -0
  4. package/alias.d.mts +31 -0
  5. package/alias.d.ts +7 -7
  6. package/aws-data-api/common/index.d.cts +9 -0
  7. package/aws-data-api/common/index.d.mts +9 -0
  8. package/aws-data-api/common/index.d.ts +1 -1
  9. package/aws-data-api/pg/driver.d.cts +23 -0
  10. package/aws-data-api/pg/driver.d.mts +23 -0
  11. package/aws-data-api/pg/driver.d.ts +6 -6
  12. package/aws-data-api/pg/index.cjs +17 -17
  13. package/aws-data-api/pg/index.d.cts +2 -0
  14. package/aws-data-api/pg/index.d.mts +2 -0
  15. package/aws-data-api/pg/index.d.ts +2 -2
  16. package/aws-data-api/pg/index.mjs +3 -2
  17. package/aws-data-api/pg/index.mjs.map +1 -1
  18. package/aws-data-api/pg/migrator.d.cts +3 -0
  19. package/aws-data-api/pg/migrator.d.mts +3 -0
  20. package/aws-data-api/pg/migrator.d.ts +2 -2
  21. package/aws-data-api/pg/session.d.cts +50 -0
  22. package/aws-data-api/pg/session.d.mts +50 -0
  23. package/aws-data-api/pg/session.d.ts +6 -6
  24. package/better-sqlite3/driver.d.cts +5 -0
  25. package/better-sqlite3/driver.d.mts +5 -0
  26. package/better-sqlite3/driver.d.ts +2 -2
  27. package/better-sqlite3/index.cjs +16 -16
  28. package/better-sqlite3/index.d.cts +2 -0
  29. package/better-sqlite3/index.d.mts +2 -0
  30. package/better-sqlite3/index.d.ts +2 -2
  31. package/better-sqlite3/index.mjs +3 -2
  32. package/better-sqlite3/index.mjs.map +1 -1
  33. package/better-sqlite3/migrator.d.cts +3 -0
  34. package/better-sqlite3/migrator.d.mts +3 -0
  35. package/better-sqlite3/migrator.d.ts +2 -2
  36. package/better-sqlite3/session.d.cts +48 -0
  37. package/better-sqlite3/session.d.mts +48 -0
  38. package/better-sqlite3/session.d.ts +8 -8
  39. package/bun-sqlite/driver.d.cts +6 -0
  40. package/bun-sqlite/driver.d.mts +6 -0
  41. package/bun-sqlite/driver.d.ts +2 -2
  42. package/bun-sqlite/index.cjs +16 -16
  43. package/bun-sqlite/index.d.cts +2 -0
  44. package/bun-sqlite/index.d.mts +2 -0
  45. package/bun-sqlite/index.d.ts +2 -2
  46. package/bun-sqlite/index.mjs +3 -2
  47. package/bun-sqlite/index.mjs.map +1 -1
  48. package/bun-sqlite/migrator.d.cts +3 -0
  49. package/bun-sqlite/migrator.d.mts +3 -0
  50. package/bun-sqlite/migrator.d.ts +2 -2
  51. package/bun-sqlite/session.d.cts +52 -0
  52. package/bun-sqlite/session.d.mts +52 -0
  53. package/bun-sqlite/session.d.ts +9 -9
  54. package/column-builder.d.cts +146 -0
  55. package/column-builder.d.mts +146 -0
  56. package/column-builder.d.ts +22 -20
  57. package/column.d.cts +56 -0
  58. package/column.d.mts +56 -0
  59. package/column.d.ts +5 -5
  60. package/d1/driver.d.cts +5 -0
  61. package/d1/driver.d.mts +5 -0
  62. package/d1/driver.d.ts +2 -2
  63. package/d1/index.cjs +19 -19
  64. package/d1/index.d.cts +2 -0
  65. package/d1/index.d.mts +2 -0
  66. package/d1/index.d.ts +2 -2
  67. package/d1/index.mjs +3 -2
  68. package/d1/index.mjs.map +1 -1
  69. package/d1/migrator.d.cts +3 -0
  70. package/d1/migrator.d.mts +3 -0
  71. package/d1/migrator.d.ts +2 -2
  72. package/d1/session.d.cts +50 -0
  73. package/d1/session.d.mts +50 -0
  74. package/d1/session.d.ts +9 -9
  75. package/entity.d.cts +7 -0
  76. package/entity.d.mts +7 -0
  77. package/errors.d.cts +10 -0
  78. package/errors.d.mts +10 -0
  79. package/errors.d.ts +1 -1
  80. package/expressions.d.cts +1 -0
  81. package/expressions.d.mts +1 -0
  82. package/expressions.d.ts +1 -1
  83. package/{alias-58b7b8c9.cjs → index-b1dbb7ec.cjs} +3071 -3030
  84. package/index-b1dbb7ec.cjs.map +1 -0
  85. package/index.cjs +100 -132
  86. package/index.cjs.map +1 -1
  87. package/index.d.cts +15 -0
  88. package/index.d.mts +15 -0
  89. package/index.d.ts +15 -15
  90. package/index.mjs +3 -2
  91. package/index.mjs.map +1 -1
  92. package/knex/index.d.cts +9 -0
  93. package/knex/index.d.mts +9 -0
  94. package/knex/index.d.ts +5 -5
  95. package/kysely/index.d.cts +16 -0
  96. package/kysely/index.d.mts +16 -0
  97. package/kysely/index.d.ts +7 -7
  98. package/libsql/driver.d.cts +5 -0
  99. package/libsql/driver.d.mts +5 -0
  100. package/libsql/driver.d.ts +2 -2
  101. package/libsql/index.cjs +17 -16
  102. package/libsql/index.cjs.map +1 -1
  103. package/libsql/index.d.cts +2 -0
  104. package/libsql/index.d.mts +2 -0
  105. package/libsql/index.d.ts +2 -2
  106. package/libsql/index.mjs +4 -2
  107. package/libsql/index.mjs.map +1 -1
  108. package/libsql/migrator.d.cts +3 -0
  109. package/libsql/migrator.d.mts +3 -0
  110. package/libsql/migrator.d.ts +2 -2
  111. package/libsql/session.d.cts +53 -0
  112. package/libsql/session.d.mts +53 -0
  113. package/libsql/session.d.ts +9 -9
  114. package/logger.d.cts +23 -0
  115. package/logger.d.mts +23 -0
  116. package/logger.d.ts +1 -1
  117. package/migrator.d.cts +15 -0
  118. package/migrator.d.mts +15 -0
  119. package/mysql-core/alias.d.cts +4 -0
  120. package/mysql-core/alias.d.mts +4 -0
  121. package/mysql-core/alias.d.ts +3 -3
  122. package/mysql-core/checks.d.cts +18 -0
  123. package/mysql-core/checks.d.mts +18 -0
  124. package/mysql-core/checks.d.ts +3 -3
  125. package/mysql-core/columns/bigint.d.cts +43 -0
  126. package/mysql-core/columns/bigint.d.mts +43 -0
  127. package/mysql-core/columns/bigint.d.ts +4 -4
  128. package/mysql-core/columns/binary.d.cts +25 -0
  129. package/mysql-core/columns/binary.d.mts +25 -0
  130. package/mysql-core/columns/binary.d.ts +4 -4
  131. package/mysql-core/columns/boolean.d.cts +22 -0
  132. package/mysql-core/columns/boolean.d.mts +22 -0
  133. package/mysql-core/columns/boolean.d.ts +4 -4
  134. package/mysql-core/columns/char.d.cts +28 -0
  135. package/mysql-core/columns/char.d.mts +28 -0
  136. package/mysql-core/columns/char.d.ts +5 -5
  137. package/mysql-core/columns/common.d.cts +49 -0
  138. package/mysql-core/columns/common.d.mts +49 -0
  139. package/mysql-core/columns/common.d.ts +13 -9
  140. package/mysql-core/columns/custom.d.cts +148 -0
  141. package/mysql-core/columns/custom.d.mts +148 -0
  142. package/mysql-core/columns/custom.d.ts +7 -7
  143. package/mysql-core/columns/date.common.d.cts +16 -0
  144. package/mysql-core/columns/date.common.d.mts +16 -0
  145. package/mysql-core/columns/date.common.d.ts +4 -4
  146. package/mysql-core/columns/date.d.cts +49 -0
  147. package/mysql-core/columns/date.d.mts +49 -0
  148. package/mysql-core/columns/date.d.ts +6 -6
  149. package/mysql-core/columns/datetime.d.cts +53 -0
  150. package/mysql-core/columns/datetime.d.mts +53 -0
  151. package/mysql-core/columns/datetime.d.ts +6 -6
  152. package/mysql-core/columns/decimal.d.cts +27 -0
  153. package/mysql-core/columns/decimal.d.mts +27 -0
  154. package/mysql-core/columns/decimal.d.ts +4 -4
  155. package/mysql-core/columns/double.d.cts +27 -0
  156. package/mysql-core/columns/double.d.mts +27 -0
  157. package/mysql-core/columns/double.d.ts +4 -4
  158. package/mysql-core/columns/enum.d.cts +27 -0
  159. package/mysql-core/columns/enum.d.mts +27 -0
  160. package/mysql-core/columns/enum.d.ts +5 -5
  161. package/mysql-core/columns/float.d.cts +21 -0
  162. package/mysql-core/columns/float.d.mts +21 -0
  163. package/mysql-core/columns/float.d.ts +4 -4
  164. package/mysql-core/columns/index.d.cts +25 -0
  165. package/mysql-core/columns/index.d.mts +25 -0
  166. package/mysql-core/columns/index.d.ts +25 -25
  167. package/mysql-core/columns/int.d.cts +22 -0
  168. package/mysql-core/columns/int.d.mts +22 -0
  169. package/mysql-core/columns/int.d.ts +4 -4
  170. package/mysql-core/columns/json.d.cts +22 -0
  171. package/mysql-core/columns/json.d.mts +22 -0
  172. package/mysql-core/columns/json.d.ts +4 -4
  173. package/mysql-core/columns/mediumint.d.cts +22 -0
  174. package/mysql-core/columns/mediumint.d.mts +22 -0
  175. package/mysql-core/columns/mediumint.d.ts +4 -4
  176. package/mysql-core/columns/real.d.cts +27 -0
  177. package/mysql-core/columns/real.d.mts +27 -0
  178. package/mysql-core/columns/real.d.ts +4 -4
  179. package/mysql-core/columns/serial.d.cts +22 -0
  180. package/mysql-core/columns/serial.d.mts +22 -0
  181. package/mysql-core/columns/serial.d.ts +4 -4
  182. package/mysql-core/columns/smallint.d.cts +22 -0
  183. package/mysql-core/columns/smallint.d.mts +22 -0
  184. package/mysql-core/columns/smallint.d.ts +4 -4
  185. package/mysql-core/columns/text.d.cts +37 -0
  186. package/mysql-core/columns/text.d.mts +37 -0
  187. package/mysql-core/columns/text.d.ts +5 -5
  188. package/mysql-core/columns/time.d.cts +25 -0
  189. package/mysql-core/columns/time.d.mts +25 -0
  190. package/mysql-core/columns/time.d.ts +4 -4
  191. package/mysql-core/columns/timestamp.d.cts +47 -0
  192. package/mysql-core/columns/timestamp.d.mts +47 -0
  193. package/mysql-core/columns/timestamp.d.ts +5 -5
  194. package/mysql-core/columns/tinyint.d.cts +22 -0
  195. package/mysql-core/columns/tinyint.d.mts +22 -0
  196. package/mysql-core/columns/tinyint.d.ts +4 -4
  197. package/mysql-core/columns/varbinary.d.cts +24 -0
  198. package/mysql-core/columns/varbinary.d.mts +24 -0
  199. package/mysql-core/columns/varbinary.d.ts +4 -4
  200. package/mysql-core/columns/varchar.d.cts +27 -0
  201. package/mysql-core/columns/varchar.d.mts +27 -0
  202. package/mysql-core/columns/varchar.d.ts +5 -5
  203. package/mysql-core/columns/year.d.cts +21 -0
  204. package/mysql-core/columns/year.d.mts +21 -0
  205. package/mysql-core/columns/year.d.ts +4 -4
  206. package/mysql-core/db.d.cts +55 -0
  207. package/mysql-core/db.d.mts +55 -0
  208. package/mysql-core/db.d.ts +14 -14
  209. package/mysql-core/dialect.d.cts +59 -0
  210. package/mysql-core/dialect.d.mts +59 -0
  211. package/mysql-core/dialect.d.ts +12 -12
  212. package/mysql-core/expressions.d.cts +8 -0
  213. package/mysql-core/expressions.d.mts +8 -0
  214. package/mysql-core/expressions.d.ts +3 -3
  215. package/mysql-core/foreign-keys.d.cts +48 -0
  216. package/mysql-core/foreign-keys.d.mts +48 -0
  217. package/mysql-core/foreign-keys.d.ts +3 -3
  218. package/mysql-core/index.cjs +156 -1028
  219. package/mysql-core/index.cjs.map +1 -1
  220. package/mysql-core/index.d.cts +16 -0
  221. package/mysql-core/index.d.mts +16 -0
  222. package/mysql-core/index.d.ts +16 -16
  223. package/mysql-core/index.mjs +37 -36
  224. package/mysql-core/index.mjs.map +1 -1
  225. package/mysql-core/indexes.d.cts +59 -0
  226. package/mysql-core/indexes.d.mts +59 -0
  227. package/mysql-core/indexes.d.ts +4 -4
  228. package/mysql-core/primary-keys.d.cts +17 -0
  229. package/mysql-core/primary-keys.d.mts +17 -0
  230. package/mysql-core/primary-keys.d.ts +3 -3
  231. package/mysql-core/query-builders/delete.d.cts +39 -0
  232. package/mysql-core/query-builders/delete.d.mts +39 -0
  233. package/mysql-core/query-builders/delete.d.ts +9 -9
  234. package/mysql-core/query-builders/index.d.cts +6 -0
  235. package/mysql-core/query-builders/index.d.mts +6 -0
  236. package/mysql-core/query-builders/index.d.ts +6 -6
  237. package/mysql-core/query-builders/insert.d.cts +59 -0
  238. package/mysql-core/query-builders/insert.d.mts +59 -0
  239. package/mysql-core/query-builders/insert.d.ts +11 -11
  240. package/mysql-core/query-builders/query-builder.d.cts +29 -0
  241. package/mysql-core/query-builders/query-builder.d.mts +29 -0
  242. package/mysql-core/query-builders/query-builder.d.ts +7 -7
  243. package/mysql-core/query-builders/query.d.cts +44 -0
  244. package/mysql-core/query-builders/query.d.mts +44 -0
  245. package/mysql-core/query-builders/query.d.ts +9 -9
  246. package/mysql-core/query-builders/select.d.cts +92 -0
  247. package/mysql-core/query-builders/select.d.mts +92 -0
  248. package/mysql-core/query-builders/select.d.ts +17 -17
  249. package/mysql-core/query-builders/select.types.d.cts +77 -0
  250. package/mysql-core/query-builders/select.types.d.mts +77 -0
  251. package/mysql-core/query-builders/select.types.d.ts +12 -12
  252. package/mysql-core/query-builders/update.d.cts +54 -0
  253. package/mysql-core/query-builders/update.d.mts +54 -0
  254. package/mysql-core/query-builders/update.d.ts +11 -11
  255. package/mysql-core/schema.d.cts +24 -0
  256. package/mysql-core/schema.d.mts +24 -0
  257. package/mysql-core/schema.d.ts +3 -3
  258. package/mysql-core/session.d.cts +63 -0
  259. package/mysql-core/session.d.mts +63 -0
  260. package/mysql-core/session.d.ts +7 -7
  261. package/mysql-core/subquery.d.cts +6 -0
  262. package/mysql-core/subquery.d.mts +6 -0
  263. package/mysql-core/subquery.d.ts +4 -4
  264. package/mysql-core/table.d.cts +35 -0
  265. package/mysql-core/table.d.mts +35 -0
  266. package/mysql-core/table.d.ts +11 -11
  267. package/mysql-core/unique-constraint.d.cts +24 -0
  268. package/mysql-core/unique-constraint.d.mts +24 -0
  269. package/mysql-core/unique-constraint.d.ts +3 -3
  270. package/mysql-core/utils.d.cts +32 -0
  271. package/mysql-core/utils.d.mts +32 -0
  272. package/mysql-core/utils.d.ts +11 -11
  273. package/mysql-core/view.d.cts +73 -0
  274. package/mysql-core/view.d.mts +73 -0
  275. package/mysql-core/view.d.ts +11 -11
  276. package/mysql2/driver.d.cts +31 -0
  277. package/mysql2/driver.d.mts +31 -0
  278. package/mysql2/driver.d.ts +10 -10
  279. package/mysql2/index.cjs +29 -27
  280. package/mysql2/index.cjs.map +1 -1
  281. package/mysql2/index.d.cts +2 -0
  282. package/mysql2/index.d.mts +2 -0
  283. package/mysql2/index.d.ts +2 -2
  284. package/mysql2/index.mjs +5 -2
  285. package/mysql2/index.mjs.map +1 -1
  286. package/mysql2/migrator.d.cts +3 -0
  287. package/mysql2/migrator.d.mts +3 -0
  288. package/mysql2/migrator.d.ts +2 -2
  289. package/mysql2/session.d.cts +52 -0
  290. package/mysql2/session.d.mts +52 -0
  291. package/mysql2/session.d.ts +8 -8
  292. package/neon-http/driver.d.cts +21 -0
  293. package/neon-http/driver.d.mts +21 -0
  294. package/neon-http/driver.d.ts +7 -7
  295. package/neon-http/index.cjs +16 -16
  296. package/neon-http/index.d.cts +2 -0
  297. package/neon-http/index.d.mts +2 -0
  298. package/neon-http/index.d.ts +2 -2
  299. package/neon-http/index.mjs +3 -2
  300. package/neon-http/index.mjs.map +1 -1
  301. package/neon-http/migrator.cjs +9 -6
  302. package/neon-http/migrator.cjs.map +1 -1
  303. package/neon-http/migrator.d.cts +11 -0
  304. package/neon-http/migrator.d.mts +11 -0
  305. package/neon-http/migrator.d.ts +2 -2
  306. package/neon-http/migrator.mjs +3 -1
  307. package/neon-http/migrator.mjs.map +1 -1
  308. package/neon-http/session.d.cts +55 -0
  309. package/neon-http/session.d.mts +55 -0
  310. package/neon-http/session.d.ts +10 -10
  311. package/neon-serverless/driver.d.cts +22 -0
  312. package/neon-serverless/driver.d.mts +22 -0
  313. package/neon-serverless/driver.d.ts +8 -8
  314. package/neon-serverless/index.cjs +22 -22
  315. package/neon-serverless/index.d.cts +2 -0
  316. package/neon-serverless/index.d.mts +2 -0
  317. package/neon-serverless/index.d.ts +2 -2
  318. package/neon-serverless/index.mjs +3 -2
  319. package/neon-serverless/index.mjs.map +1 -1
  320. package/neon-serverless/migrator.d.cts +3 -0
  321. package/neon-serverless/migrator.d.mts +3 -0
  322. package/neon-serverless/migrator.d.ts +2 -2
  323. package/neon-serverless/session.d.cts +48 -0
  324. package/neon-serverless/session.d.mts +48 -0
  325. package/neon-serverless/session.d.ts +10 -10
  326. package/node-postgres/driver.d.cts +22 -0
  327. package/node-postgres/driver.d.mts +22 -0
  328. package/node-postgres/driver.d.ts +8 -8
  329. package/node-postgres/index.cjs +27 -27
  330. package/node-postgres/index.d.cts +2 -0
  331. package/node-postgres/index.d.mts +2 -0
  332. package/node-postgres/index.d.ts +2 -2
  333. package/node-postgres/index.mjs +3 -2
  334. package/node-postgres/index.mjs.map +1 -1
  335. package/node-postgres/migrator.d.cts +3 -0
  336. package/node-postgres/migrator.d.mts +3 -0
  337. package/node-postgres/migrator.d.ts +2 -2
  338. package/node-postgres/session.d.cts +46 -0
  339. package/node-postgres/session.d.mts +46 -0
  340. package/node-postgres/session.d.ts +10 -10
  341. package/operations.d.cts +15 -0
  342. package/operations.d.mts +15 -0
  343. package/operations.d.ts +3 -3
  344. package/package.json +291 -74
  345. package/pg-core/alias.d.cts +4 -0
  346. package/pg-core/alias.d.mts +4 -0
  347. package/pg-core/alias.d.ts +3 -3
  348. package/pg-core/checks.d.cts +18 -0
  349. package/pg-core/checks.d.mts +18 -0
  350. package/pg-core/checks.d.ts +3 -3
  351. package/pg-core/columns/array.d.cts +26 -0
  352. package/pg-core/columns/array.d.mts +26 -0
  353. package/pg-core/columns/array.d.ts +5 -5
  354. package/pg-core/columns/bigint.d.cts +43 -0
  355. package/pg-core/columns/bigint.d.mts +43 -0
  356. package/pg-core/columns/bigint.d.ts +4 -4
  357. package/pg-core/columns/bigserial.d.cts +43 -0
  358. package/pg-core/columns/bigserial.d.mts +43 -0
  359. package/pg-core/columns/bigserial.d.ts +4 -4
  360. package/pg-core/columns/boolean.d.cts +21 -0
  361. package/pg-core/columns/boolean.d.mts +21 -0
  362. package/pg-core/columns/boolean.d.ts +4 -4
  363. package/pg-core/columns/char.d.cts +34 -0
  364. package/pg-core/columns/char.d.mts +34 -0
  365. package/pg-core/columns/char.d.ts +5 -5
  366. package/pg-core/columns/cidr.d.cts +21 -0
  367. package/pg-core/columns/cidr.d.mts +21 -0
  368. package/pg-core/columns/cidr.d.ts +4 -4
  369. package/pg-core/columns/common.d.cts +54 -0
  370. package/pg-core/columns/common.d.mts +54 -0
  371. package/pg-core/columns/common.d.ts +15 -13
  372. package/pg-core/columns/custom.d.cts +148 -0
  373. package/pg-core/columns/custom.d.mts +148 -0
  374. package/pg-core/columns/custom.d.ts +7 -7
  375. package/pg-core/columns/date.common.d.cts +7 -0
  376. package/pg-core/columns/date.common.d.mts +7 -0
  377. package/pg-core/columns/date.common.d.ts +4 -4
  378. package/pg-core/columns/date.d.cts +45 -0
  379. package/pg-core/columns/date.d.mts +45 -0
  380. package/pg-core/columns/date.d.ts +5 -5
  381. package/pg-core/columns/double-precision.d.cts +22 -0
  382. package/pg-core/columns/double-precision.d.mts +22 -0
  383. package/pg-core/columns/double-precision.d.ts +4 -4
  384. package/pg-core/columns/enum.d.cts +42 -0
  385. package/pg-core/columns/enum.d.mts +42 -0
  386. package/pg-core/columns/enum.d.ts +6 -6
  387. package/pg-core/columns/index.d.cts +28 -0
  388. package/pg-core/columns/index.d.mts +28 -0
  389. package/pg-core/columns/index.d.ts +28 -28
  390. package/pg-core/columns/inet.d.cts +21 -0
  391. package/pg-core/columns/inet.d.mts +21 -0
  392. package/pg-core/columns/inet.d.ts +4 -4
  393. package/pg-core/columns/integer.d.cts +23 -0
  394. package/pg-core/columns/integer.d.mts +23 -0
  395. package/pg-core/columns/integer.d.ts +4 -4
  396. package/pg-core/columns/interval.d.cts +32 -0
  397. package/pg-core/columns/interval.d.mts +32 -0
  398. package/pg-core/columns/interval.d.ts +5 -5
  399. package/pg-core/columns/json.d.cts +27 -0
  400. package/pg-core/columns/json.d.mts +27 -0
  401. package/pg-core/columns/json.d.ts +5 -5
  402. package/pg-core/columns/jsonb.d.cts +27 -0
  403. package/pg-core/columns/jsonb.d.mts +27 -0
  404. package/pg-core/columns/jsonb.d.ts +5 -5
  405. package/pg-core/columns/macaddr.d.cts +21 -0
  406. package/pg-core/columns/macaddr.d.mts +21 -0
  407. package/pg-core/columns/macaddr.d.ts +4 -4
  408. package/pg-core/columns/macaddr8.d.cts +21 -0
  409. package/pg-core/columns/macaddr8.d.mts +21 -0
  410. package/pg-core/columns/macaddr8.d.ts +4 -4
  411. package/pg-core/columns/numeric.d.cts +40 -0
  412. package/pg-core/columns/numeric.d.mts +40 -0
  413. package/pg-core/columns/numeric.d.ts +5 -5
  414. package/pg-core/columns/real.d.cts +28 -0
  415. package/pg-core/columns/real.d.mts +28 -0
  416. package/pg-core/columns/real.d.ts +5 -5
  417. package/pg-core/columns/serial.d.cts +21 -0
  418. package/pg-core/columns/serial.d.mts +21 -0
  419. package/pg-core/columns/serial.d.ts +4 -4
  420. package/pg-core/columns/smallint.d.cts +22 -0
  421. package/pg-core/columns/smallint.d.mts +22 -0
  422. package/pg-core/columns/smallint.d.ts +4 -4
  423. package/pg-core/columns/smallserial.d.cts +21 -0
  424. package/pg-core/columns/smallserial.d.mts +21 -0
  425. package/pg-core/columns/smallserial.d.ts +4 -4
  426. package/pg-core/columns/text.d.cts +31 -0
  427. package/pg-core/columns/text.d.mts +31 -0
  428. package/pg-core/columns/text.d.ts +5 -5
  429. package/pg-core/columns/time.d.cts +38 -0
  430. package/pg-core/columns/time.d.mts +38 -0
  431. package/pg-core/columns/time.d.ts +7 -7
  432. package/pg-core/columns/timestamp.d.cts +64 -0
  433. package/pg-core/columns/timestamp.d.mts +64 -0
  434. package/pg-core/columns/timestamp.d.ts +7 -7
  435. package/pg-core/columns/uuid.d.cts +25 -0
  436. package/pg-core/columns/uuid.d.mts +25 -0
  437. package/pg-core/columns/uuid.d.ts +4 -4
  438. package/pg-core/columns/varchar.d.cts +34 -0
  439. package/pg-core/columns/varchar.d.mts +34 -0
  440. package/pg-core/columns/varchar.d.ts +5 -5
  441. package/pg-core/db.d.cts +53 -0
  442. package/pg-core/db.d.mts +53 -0
  443. package/pg-core/db.d.ts +17 -17
  444. package/pg-core/dialect.d.cts +53 -0
  445. package/pg-core/dialect.d.mts +53 -0
  446. package/pg-core/dialect.d.ts +11 -11
  447. package/pg-core/expressions.d.cts +8 -0
  448. package/pg-core/expressions.d.mts +8 -0
  449. package/pg-core/expressions.d.ts +3 -3
  450. package/pg-core/foreign-keys.d.cts +45 -0
  451. package/pg-core/foreign-keys.d.mts +45 -0
  452. package/pg-core/foreign-keys.d.ts +3 -3
  453. package/pg-core/index.cjs +158 -157
  454. package/pg-core/index.cjs.map +1 -1
  455. package/pg-core/index.d.cts +16 -0
  456. package/pg-core/index.d.mts +16 -0
  457. package/pg-core/index.d.ts +16 -16
  458. package/pg-core/index.mjs +8 -7
  459. package/pg-core/index.mjs.map +1 -1
  460. package/pg-core/indexes.d.cts +72 -0
  461. package/pg-core/indexes.d.mts +72 -0
  462. package/pg-core/indexes.d.ts +4 -4
  463. package/pg-core/primary-keys.d.cts +17 -0
  464. package/pg-core/primary-keys.d.mts +17 -0
  465. package/pg-core/primary-keys.d.ts +3 -3
  466. package/pg-core/query-builders/delete.d.cts +35 -0
  467. package/pg-core/query-builders/delete.d.mts +35 -0
  468. package/pg-core/query-builders/delete.d.ts +9 -9
  469. package/pg-core/query-builders/index.d.cts +7 -0
  470. package/pg-core/query-builders/index.d.mts +7 -0
  471. package/pg-core/query-builders/index.d.ts +7 -7
  472. package/pg-core/query-builders/insert.d.cts +63 -0
  473. package/pg-core/query-builders/insert.d.mts +63 -0
  474. package/pg-core/query-builders/insert.d.ts +12 -12
  475. package/pg-core/query-builders/query-builder.d.cts +37 -0
  476. package/pg-core/query-builders/query-builder.d.mts +37 -0
  477. package/pg-core/query-builders/query-builder.d.ts +9 -9
  478. package/pg-core/query-builders/query.d.cts +39 -0
  479. package/pg-core/query-builders/query.d.mts +39 -0
  480. package/pg-core/query-builders/query.d.ts +7 -7
  481. package/pg-core/query-builders/refresh-materialized-view.d.cts +26 -0
  482. package/pg-core/query-builders/refresh-materialized-view.d.mts +26 -0
  483. package/pg-core/query-builders/refresh-materialized-view.d.ts +6 -6
  484. package/pg-core/query-builders/select.d.cts +211 -0
  485. package/pg-core/query-builders/select.d.mts +211 -0
  486. package/pg-core/query-builders/select.d.ts +15 -15
  487. package/pg-core/query-builders/select.types.d.cts +79 -0
  488. package/pg-core/query-builders/select.types.d.mts +79 -0
  489. package/pg-core/query-builders/select.types.d.ts +11 -11
  490. package/pg-core/query-builders/update.d.cts +53 -0
  491. package/pg-core/query-builders/update.d.mts +53 -0
  492. package/pg-core/query-builders/update.d.ts +11 -11
  493. package/pg-core/schema.d.cts +13 -0
  494. package/pg-core/schema.d.mts +13 -0
  495. package/pg-core/schema.d.ts +3 -3
  496. package/pg-core/session.d.cts +54 -0
  497. package/pg-core/session.d.mts +54 -0
  498. package/pg-core/session.d.ts +6 -6
  499. package/pg-core/subquery.d.cts +5 -0
  500. package/pg-core/subquery.d.mts +5 -0
  501. package/pg-core/subquery.d.ts +3 -3
  502. package/pg-core/table.d.cts +28 -0
  503. package/pg-core/table.d.mts +28 -0
  504. package/pg-core/table.d.ts +10 -10
  505. package/pg-core/unique-constraint.d.cts +25 -0
  506. package/pg-core/unique-constraint.d.mts +25 -0
  507. package/pg-core/unique-constraint.d.ts +3 -3
  508. package/pg-core/utils.d.cts +52 -0
  509. package/pg-core/utils.d.mts +52 -0
  510. package/pg-core/utils.d.ts +16 -16
  511. package/pg-core/view.d.cts +143 -0
  512. package/pg-core/view.d.mts +143 -0
  513. package/pg-core/view.d.ts +13 -13
  514. package/planetscale-serverless/driver.d.cts +10 -0
  515. package/planetscale-serverless/driver.d.mts +10 -0
  516. package/planetscale-serverless/driver.d.ts +4 -4
  517. package/planetscale-serverless/index.cjs +18 -18
  518. package/planetscale-serverless/index.cjs.map +1 -1
  519. package/planetscale-serverless/index.d.cts +2 -0
  520. package/planetscale-serverless/index.d.mts +2 -0
  521. package/planetscale-serverless/index.d.ts +2 -2
  522. package/planetscale-serverless/index.mjs +3 -2
  523. package/planetscale-serverless/index.mjs.map +1 -1
  524. package/planetscale-serverless/migrator.d.cts +3 -0
  525. package/planetscale-serverless/migrator.d.mts +3 -0
  526. package/planetscale-serverless/migrator.d.ts +2 -2
  527. package/planetscale-serverless/session.d.cts +52 -0
  528. package/planetscale-serverless/session.d.mts +52 -0
  529. package/planetscale-serverless/session.d.ts +8 -8
  530. package/postgres-js/driver.d.cts +6 -0
  531. package/postgres-js/driver.d.mts +6 -0
  532. package/postgres-js/driver.d.ts +3 -3
  533. package/postgres-js/index.cjs +20 -20
  534. package/postgres-js/index.d.cts +2 -0
  535. package/postgres-js/index.d.mts +2 -0
  536. package/postgres-js/index.d.ts +2 -2
  537. package/postgres-js/index.mjs +3 -2
  538. package/postgres-js/index.mjs.map +1 -1
  539. package/postgres-js/migrator.d.cts +3 -0
  540. package/postgres-js/migrator.d.mts +3 -0
  541. package/postgres-js/migrator.d.ts +2 -2
  542. package/postgres-js/session.d.cts +49 -0
  543. package/postgres-js/session.d.mts +49 -0
  544. package/postgres-js/session.d.ts +10 -10
  545. package/primary-key.d.cts +10 -0
  546. package/primary-key.d.mts +10 -0
  547. package/primary-key.d.ts +3 -3
  548. package/query-builders/query-builder.d.cts +10 -0
  549. package/query-builders/query-builder.d.mts +10 -0
  550. package/query-builders/query-builder.d.ts +2 -2
  551. package/query-builders/select.types.d.cts +56 -0
  552. package/query-builders/select.types.d.mts +56 -0
  553. package/query-builders/select.types.d.ts +8 -8
  554. package/query-promise.d.cts +9 -0
  555. package/query-promise.d.mts +9 -0
  556. package/query-promise.d.ts +1 -1
  557. package/relations.d.cts +189 -0
  558. package/relations.d.mts +189 -0
  559. package/relations.d.ts +10 -10
  560. package/{session-775da517.mjs → session-a0c900ab.mjs} +5 -3
  561. package/session-a0c900ab.mjs.map +1 -0
  562. package/{session-e7fcd577.mjs → session-a706e83f.mjs} +3 -2
  563. package/session-a706e83f.mjs.map +1 -0
  564. package/{session-f61b6e4d.cjs → session-fadbb086.cjs} +239 -239
  565. package/session-fadbb086.cjs.map +1 -0
  566. package/sql/expressions/conditions.d.cts +393 -0
  567. package/sql/expressions/conditions.d.mts +393 -0
  568. package/sql/expressions/conditions.d.ts +2 -2
  569. package/sql/expressions/index.d.cts +2 -0
  570. package/sql/expressions/index.d.mts +2 -0
  571. package/sql/expressions/index.d.ts +2 -2
  572. package/sql/expressions/select.d.cts +38 -0
  573. package/sql/expressions/select.d.mts +38 -0
  574. package/sql/expressions/select.d.ts +2 -2
  575. package/sql/index.d.cts +191 -0
  576. package/sql/index.d.mts +191 -0
  577. package/sql/index.d.ts +7 -7
  578. package/sql-js/driver.d.cts +5 -0
  579. package/sql-js/driver.d.mts +5 -0
  580. package/sql-js/driver.d.ts +2 -2
  581. package/sql-js/index.cjs +19 -19
  582. package/sql-js/index.d.cts +2 -0
  583. package/sql-js/index.d.mts +2 -0
  584. package/sql-js/index.d.ts +2 -2
  585. package/sql-js/index.mjs +3 -2
  586. package/sql-js/index.mjs.map +1 -1
  587. package/sql-js/migrator.d.cts +3 -0
  588. package/sql-js/migrator.d.mts +3 -0
  589. package/sql-js/migrator.d.ts +2 -2
  590. package/sql-js/session.d.cts +52 -0
  591. package/sql-js/session.d.mts +52 -0
  592. package/sql-js/session.d.ts +9 -9
  593. package/sqlite-core/alias.d.cts +4 -0
  594. package/sqlite-core/alias.d.mts +4 -0
  595. package/sqlite-core/alias.d.ts +3 -3
  596. package/sqlite-core/checks.d.cts +22 -0
  597. package/sqlite-core/checks.d.mts +22 -0
  598. package/sqlite-core/checks.d.ts +3 -3
  599. package/sqlite-core/columns/blob.d.cts +65 -0
  600. package/sqlite-core/columns/blob.d.mts +65 -0
  601. package/sqlite-core/columns/blob.d.ts +6 -6
  602. package/sqlite-core/columns/common.d.cts +35 -0
  603. package/sqlite-core/columns/common.d.mts +35 -0
  604. package/sqlite-core/columns/common.d.ts +14 -12
  605. package/sqlite-core/columns/custom.d.cts +148 -0
  606. package/sqlite-core/columns/custom.d.mts +148 -0
  607. package/sqlite-core/columns/custom.d.ts +7 -7
  608. package/sqlite-core/columns/index.d.cts +7 -0
  609. package/sqlite-core/columns/index.d.mts +7 -0
  610. package/sqlite-core/columns/index.d.ts +7 -7
  611. package/sqlite-core/columns/integer.d.cts +106 -0
  612. package/sqlite-core/columns/integer.d.mts +106 -0
  613. package/sqlite-core/columns/integer.d.ts +7 -7
  614. package/sqlite-core/columns/numeric.d.cts +21 -0
  615. package/sqlite-core/columns/numeric.d.mts +21 -0
  616. package/sqlite-core/columns/numeric.d.ts +4 -4
  617. package/sqlite-core/columns/real.d.cts +21 -0
  618. package/sqlite-core/columns/real.d.mts +21 -0
  619. package/sqlite-core/columns/real.d.ts +4 -4
  620. package/sqlite-core/columns/text.d.cts +38 -0
  621. package/sqlite-core/columns/text.d.mts +38 -0
  622. package/sqlite-core/columns/text.d.ts +6 -6
  623. package/sqlite-core/db.d.cts +57 -0
  624. package/sqlite-core/db.d.mts +57 -0
  625. package/sqlite-core/db.d.ts +14 -14
  626. package/sqlite-core/dialect.d.cts +53 -0
  627. package/sqlite-core/dialect.d.mts +53 -0
  628. package/sqlite-core/dialect.d.ts +10 -10
  629. package/sqlite-core/expressions.d.cts +9 -0
  630. package/sqlite-core/expressions.d.mts +9 -0
  631. package/sqlite-core/expressions.d.ts +3 -3
  632. package/sqlite-core/foreign-keys.d.cts +48 -0
  633. package/sqlite-core/foreign-keys.d.mts +48 -0
  634. package/sqlite-core/foreign-keys.d.ts +3 -3
  635. package/sqlite-core/index.cjs +11 -11
  636. package/sqlite-core/index.cjs.map +1 -1
  637. package/sqlite-core/index.d.cts +15 -0
  638. package/sqlite-core/index.d.mts +15 -0
  639. package/sqlite-core/index.d.ts +15 -15
  640. package/sqlite-core/index.mjs +4 -3
  641. package/sqlite-core/index.mjs.map +1 -1
  642. package/sqlite-core/indexes.d.cts +41 -0
  643. package/sqlite-core/indexes.d.mts +41 -0
  644. package/sqlite-core/indexes.d.ts +4 -4
  645. package/sqlite-core/primary-keys.d.cts +20 -0
  646. package/sqlite-core/primary-keys.d.mts +20 -0
  647. package/sqlite-core/primary-keys.d.ts +3 -3
  648. package/sqlite-core/query-builders/delete.d.cts +42 -0
  649. package/sqlite-core/query-builders/delete.d.mts +42 -0
  650. package/sqlite-core/query-builders/delete.d.ts +10 -10
  651. package/sqlite-core/query-builders/index.d.cts +6 -0
  652. package/sqlite-core/query-builders/index.d.mts +6 -0
  653. package/sqlite-core/query-builders/index.d.ts +6 -6
  654. package/sqlite-core/query-builders/insert.d.cts +74 -0
  655. package/sqlite-core/query-builders/insert.d.mts +74 -0
  656. package/sqlite-core/query-builders/insert.d.ts +13 -13
  657. package/sqlite-core/query-builders/query-builder.d.cts +29 -0
  658. package/sqlite-core/query-builders/query-builder.d.mts +29 -0
  659. package/sqlite-core/query-builders/query-builder.d.ts +7 -7
  660. package/sqlite-core/query-builders/query.d.cts +47 -0
  661. package/sqlite-core/query-builders/query.d.mts +47 -0
  662. package/sqlite-core/query-builders/query.d.ts +7 -7
  663. package/sqlite-core/query-builders/select.d.cts +94 -0
  664. package/sqlite-core/query-builders/select.d.mts +94 -0
  665. package/sqlite-core/query-builders/select.d.ts +15 -15
  666. package/sqlite-core/query-builders/select.types.d.cts +63 -0
  667. package/sqlite-core/query-builders/select.types.d.mts +63 -0
  668. package/sqlite-core/query-builders/select.types.d.ts +11 -11
  669. package/sqlite-core/query-builders/update.d.cts +63 -0
  670. package/sqlite-core/query-builders/update.d.mts +63 -0
  671. package/sqlite-core/query-builders/update.d.ts +11 -11
  672. package/sqlite-core/session.d.cts +91 -0
  673. package/sqlite-core/session.d.mts +91 -0
  674. package/sqlite-core/session.d.ts +7 -7
  675. package/sqlite-core/subquery.d.cts +5 -0
  676. package/sqlite-core/subquery.d.mts +5 -0
  677. package/sqlite-core/subquery.d.ts +3 -3
  678. package/sqlite-core/table.d.cts +28 -0
  679. package/sqlite-core/table.d.mts +28 -0
  680. package/sqlite-core/table.d.ts +10 -10
  681. package/sqlite-core/unique-constraint.d.cts +23 -0
  682. package/sqlite-core/unique-constraint.d.mts +23 -0
  683. package/sqlite-core/unique-constraint.d.ts +3 -3
  684. package/sqlite-core/utils.d.cts +31 -0
  685. package/sqlite-core/utils.d.mts +31 -0
  686. package/sqlite-core/utils.d.ts +11 -11
  687. package/sqlite-core/view.d.cts +67 -0
  688. package/sqlite-core/view.d.mts +67 -0
  689. package/sqlite-core/view.d.ts +11 -11
  690. package/sqlite-proxy/driver.d.cts +11 -0
  691. package/sqlite-proxy/driver.d.mts +11 -0
  692. package/sqlite-proxy/driver.d.ts +2 -2
  693. package/sqlite-proxy/index.cjs +19 -19
  694. package/sqlite-proxy/index.d.cts +2 -0
  695. package/sqlite-proxy/index.d.mts +2 -0
  696. package/sqlite-proxy/index.d.ts +2 -2
  697. package/sqlite-proxy/index.mjs +3 -2
  698. package/sqlite-proxy/index.mjs.map +1 -1
  699. package/sqlite-proxy/migrator.cjs +4 -3
  700. package/sqlite-proxy/migrator.cjs.map +1 -1
  701. package/sqlite-proxy/migrator.d.cts +4 -0
  702. package/sqlite-proxy/migrator.d.mts +4 -0
  703. package/sqlite-proxy/migrator.d.ts +2 -2
  704. package/sqlite-proxy/migrator.mjs +2 -1
  705. package/sqlite-proxy/migrator.mjs.map +1 -1
  706. package/sqlite-proxy/session.d.cts +48 -0
  707. package/sqlite-proxy/session.d.mts +48 -0
  708. package/sqlite-proxy/session.d.ts +10 -10
  709. package/subquery.d.cts +23 -0
  710. package/subquery.d.mts +23 -0
  711. package/subquery.d.ts +3 -3
  712. package/table.d.cts +63 -0
  713. package/table.d.mts +63 -0
  714. package/table.d.ts +8 -8
  715. package/tracing.d.cts +1 -0
  716. package/tracing.d.mts +1 -0
  717. package/utils.d.cts +45 -0
  718. package/utils.d.mts +45 -0
  719. package/utils.d.ts +4 -4
  720. package/vercel-postgres/driver.d.cts +21 -0
  721. package/vercel-postgres/driver.d.mts +21 -0
  722. package/vercel-postgres/driver.d.ts +7 -7
  723. package/vercel-postgres/index.cjs +22 -22
  724. package/vercel-postgres/index.d.cts +2 -0
  725. package/vercel-postgres/index.d.mts +2 -0
  726. package/vercel-postgres/index.d.ts +2 -2
  727. package/vercel-postgres/index.mjs +3 -2
  728. package/vercel-postgres/index.mjs.map +1 -1
  729. package/vercel-postgres/migrator.d.cts +3 -0
  730. package/vercel-postgres/migrator.d.mts +3 -0
  731. package/vercel-postgres/migrator.d.ts +2 -2
  732. package/vercel-postgres/session.d.cts +47 -0
  733. package/vercel-postgres/session.d.mts +47 -0
  734. package/vercel-postgres/session.d.ts +9 -9
  735. package/version.cjs +1 -1
  736. package/version.d.cts +2 -0
  737. package/version.d.mts +2 -0
  738. package/version.mjs +1 -1
  739. package/{session-9eb850c1.mjs → view-ba779eb7.mjs} +171 -169
  740. package/view-ba779eb7.mjs.map +1 -0
  741. package/{session-690cd067.cjs → view-e96fe3b6.cjs} +1400 -445
  742. package/view-e96fe3b6.cjs.map +1 -0
  743. package/view.d.cts +24 -0
  744. package/view.d.mts +24 -0
  745. package/view.d.ts +5 -5
  746. package/alias-58b7b8c9.cjs.map +0 -1
  747. package/alias-d302772a.mjs.map +0 -1
  748. package/session-690cd067.cjs.map +0 -1
  749. package/session-775da517.mjs.map +0 -1
  750. package/session-9eb850c1.mjs.map +0 -1
  751. package/session-e7fcd577.mjs.map +0 -1
  752. package/session-f61b6e4d.cjs.map +0 -1
@@ -1,3 +1,5 @@
1
+ import '@opentelemetry/api';
2
+
1
3
  const entityKind = Symbol.for('drizzle:entityKind');
2
4
  const hasOwnEntityKind = Symbol.for('drizzle:hasOwnEntityKind');
3
5
  function is(value, type) {
@@ -67,6 +69,216 @@ class Column {
67
69
  }
68
70
  }
69
71
 
72
+ const ViewBaseConfig = Symbol.for('drizzle:ViewBaseConfig');
73
+ class View {
74
+ static [entityKind] = 'View';
75
+ /** @internal */
76
+ [ViewBaseConfig];
77
+ constructor({ name, schema, selectedFields, query }) {
78
+ this[ViewBaseConfig] = {
79
+ name,
80
+ originalName: name,
81
+ schema,
82
+ selectedFields,
83
+ query: query,
84
+ isExisting: !query,
85
+ isAlias: false,
86
+ };
87
+ }
88
+ getSQL() {
89
+ return new SQL([this]);
90
+ }
91
+ }
92
+
93
+ const SubqueryConfig = Symbol.for('drizzle:SubqueryConfig');
94
+ class Subquery {
95
+ static [entityKind] = 'Subquery';
96
+ /** @internal */
97
+ [SubqueryConfig];
98
+ constructor(sql, selection, alias, isWith = false) {
99
+ this[SubqueryConfig] = {
100
+ sql,
101
+ selection,
102
+ alias,
103
+ isWith,
104
+ };
105
+ }
106
+ getSQL() {
107
+ return new SQL([this]);
108
+ }
109
+ }
110
+ class WithSubquery extends Subquery {
111
+ static [entityKind] = 'WithSubquery';
112
+ }
113
+ class SelectionProxyHandler {
114
+ static [entityKind] = 'SelectionProxyHandler';
115
+ config;
116
+ constructor(config) {
117
+ this.config = { ...config };
118
+ }
119
+ get(subquery, prop) {
120
+ if (prop === SubqueryConfig) {
121
+ return {
122
+ ...subquery[SubqueryConfig],
123
+ selection: new Proxy(subquery[SubqueryConfig].selection, this),
124
+ };
125
+ }
126
+ if (prop === ViewBaseConfig) {
127
+ return {
128
+ ...subquery[ViewBaseConfig],
129
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this),
130
+ };
131
+ }
132
+ if (typeof prop === 'symbol') {
133
+ return subquery[prop];
134
+ }
135
+ const columns = is(subquery, Subquery)
136
+ ? subquery[SubqueryConfig].selection
137
+ : is(subquery, View)
138
+ ? subquery[ViewBaseConfig].selectedFields
139
+ : subquery;
140
+ const value = columns[prop];
141
+ if (is(value, SQL.Aliased)) {
142
+ // Never return the underlying SQL expression for a field previously selected in a subquery
143
+ if (this.config.sqlAliasedBehavior === 'sql' && !value.isSelectionField) {
144
+ return value.sql;
145
+ }
146
+ const newValue = value.clone();
147
+ newValue.isSelectionField = true;
148
+ return newValue;
149
+ }
150
+ if (is(value, SQL)) {
151
+ if (this.config.sqlBehavior === 'sql') {
152
+ return value;
153
+ }
154
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
155
+ }
156
+ if (is(value, Column)) {
157
+ if (this.config.alias) {
158
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
159
+ }
160
+ return value;
161
+ }
162
+ if (typeof value !== 'object' || value === null) {
163
+ return value;
164
+ }
165
+ return new Proxy(value, new SelectionProxyHandler(this.config));
166
+ }
167
+ }
168
+
169
+ /** @internal */
170
+ function mapResultRow(columns, row, joinsNotNullableMap) {
171
+ // Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise
172
+ const nullifyMap = {};
173
+ const result = columns.reduce((result, { path, field }, columnIndex) => {
174
+ let decoder;
175
+ if (is(field, Column)) {
176
+ decoder = field;
177
+ }
178
+ else if (is(field, SQL)) {
179
+ decoder = field.decoder;
180
+ }
181
+ else {
182
+ decoder = field.sql.decoder;
183
+ }
184
+ let node = result;
185
+ for (const [pathChunkIndex, pathChunk] of path.entries()) {
186
+ if (pathChunkIndex < path.length - 1) {
187
+ if (!(pathChunk in node)) {
188
+ node[pathChunk] = {};
189
+ }
190
+ node = node[pathChunk];
191
+ }
192
+ else {
193
+ const rawValue = row[columnIndex];
194
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
195
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
196
+ const objectName = path[0];
197
+ if (!(objectName in nullifyMap)) {
198
+ nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
199
+ }
200
+ else if (typeof nullifyMap[objectName] === 'string' && nullifyMap[objectName] !== getTableName(field.table)) {
201
+ nullifyMap[objectName] = false;
202
+ }
203
+ }
204
+ }
205
+ }
206
+ return result;
207
+ }, {});
208
+ // Nullify all nested objects from nullifyMap that are nullable
209
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
210
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) {
211
+ if (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {
212
+ result[objectName] = null;
213
+ }
214
+ }
215
+ }
216
+ return result;
217
+ }
218
+ /** @internal */
219
+ function orderSelectedFields(fields, pathPrefix) {
220
+ return Object.entries(fields).reduce((result, [name, field]) => {
221
+ if (typeof name !== 'string') {
222
+ return result;
223
+ }
224
+ const newPath = pathPrefix ? [...pathPrefix, name] : [name];
225
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
226
+ result.push({ path: newPath, field });
227
+ }
228
+ else if (is(field, Table)) {
229
+ result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
230
+ }
231
+ else {
232
+ result.push(...orderSelectedFields(field, newPath));
233
+ }
234
+ return result;
235
+ }, []);
236
+ }
237
+ /** @internal */
238
+ function mapUpdateSet(table, values) {
239
+ const entries = Object.entries(values)
240
+ .filter(([, value]) => value !== undefined)
241
+ .map(([key, value]) => {
242
+ // eslint-disable-next-line unicorn/prefer-ternary
243
+ if (is(value, SQL)) {
244
+ return [key, value];
245
+ }
246
+ else {
247
+ return [key, new Param(value, table[Table.Symbol.Columns][key])];
248
+ }
249
+ });
250
+ if (entries.length === 0) {
251
+ throw new Error('No values to set');
252
+ }
253
+ return Object.fromEntries(entries);
254
+ }
255
+ /** @internal */
256
+ function applyMixins(baseClass, extendedClasses) {
257
+ for (const extendedClass of extendedClasses) {
258
+ for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
259
+ Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null));
260
+ }
261
+ }
262
+ }
263
+ function getTableColumns(table) {
264
+ return table[Table.Symbol.Columns];
265
+ }
266
+ /** @internal */
267
+ function getTableLikeName(table) {
268
+ return is(table, Subquery)
269
+ ? table[SubqueryConfig].alias
270
+ : is(table, View)
271
+ ? table[ViewBaseConfig].name
272
+ : is(table, SQL)
273
+ ? undefined
274
+ : table[Table.Symbol.IsAlias]
275
+ ? table[Table.Symbol.Name]
276
+ : table[Table.Symbol.BaseName];
277
+ }
278
+ function iife(fn, ...args) {
279
+ return fn(...args);
280
+ }
281
+
70
282
  /** @internal */
71
283
  const TableName = Symbol.for('drizzle:Name');
72
284
  /** @internal */
@@ -134,42 +346,61 @@ function getTableName(table) {
134
346
  return table[TableName];
135
347
  }
136
348
 
137
- class CheckBuilder {
138
- name;
139
- value;
140
- static [entityKind] = 'PgCheckBuilder';
141
- brand;
142
- constructor(name, value) {
143
- this.name = name;
144
- this.value = value;
349
+ class QueryPromise {
350
+ static [entityKind] = 'QueryPromise';
351
+ [Symbol.toStringTag] = 'QueryPromise';
352
+ catch(onRejected) {
353
+ return this.then(undefined, onRejected);
145
354
  }
146
- /** @internal */
147
- build(table) {
148
- return new Check(table, this);
355
+ finally(onFinally) {
356
+ return this.then((value) => {
357
+ onFinally?.();
358
+ return value;
359
+ }, (reason) => {
360
+ onFinally?.();
361
+ throw reason;
362
+ });
149
363
  }
150
- }
151
- class Check {
152
- table;
153
- static [entityKind] = 'PgCheck';
154
- name;
155
- value;
156
- constructor(table, builder) {
157
- this.table = table;
158
- this.name = builder.name;
159
- this.value = builder.value;
364
+ then(onFulfilled, onRejected) {
365
+ return this.execute().then(onFulfilled, onRejected);
160
366
  }
161
367
  }
162
- function check(name, value) {
163
- return new CheckBuilder(name, value);
164
- }
165
368
 
166
369
  /** @internal */
167
- const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');
168
- class PgTable extends Table {
169
- static [entityKind] = 'PgTable';
170
- /** @internal */
171
- static Symbol = Object.assign({}, Table.Symbol, {
172
- InlineForeignKeys: InlineForeignKeys,
370
+ const tracer = {
371
+ startActiveSpan(name, fn) {
372
+ {
373
+ return fn();
374
+ }
375
+ },
376
+ };
377
+
378
+ class DrizzleError extends Error {
379
+ static [entityKind] = 'DrizzleError';
380
+ constructor(message) {
381
+ super(message);
382
+ this.name = 'DrizzleError';
383
+ }
384
+ static wrap(error, message) {
385
+ return error instanceof Error // eslint-disable-line no-instanceof/no-instanceof
386
+ ? new DrizzleError(message ? `${message}: ${error.message}` : error.message)
387
+ : new DrizzleError(message ?? String(error));
388
+ }
389
+ }
390
+ class TransactionRollbackError extends DrizzleError {
391
+ static [entityKind] = 'TransactionRollbackError';
392
+ constructor() {
393
+ super('Rollback');
394
+ }
395
+ }
396
+
397
+ /** @internal */
398
+ const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');
399
+ class PgTable extends Table {
400
+ static [entityKind] = 'PgTable';
401
+ /** @internal */
402
+ static Symbol = Object.assign({}, Table.Symbol, {
403
+ InlineForeignKeys: InlineForeignKeys,
173
404
  });
174
405
  /**@internal */
175
406
  [InlineForeignKeys] = [];
@@ -179,7 +410,8 @@ class PgTable extends Table {
179
410
  /** @internal */
180
411
  function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) {
181
412
  const rawTable = new PgTable(name, schema, baseName);
182
- const builtColumns = Object.fromEntries(Object.entries(columns).map(([name, colBuilder]) => {
413
+ const builtColumns = Object.fromEntries(Object.entries(columns).map(([name, colBuilderBase]) => {
414
+ const colBuilder = colBuilderBase;
183
415
  const column = colBuilder.build(rawTable);
184
416
  rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
185
417
  return [name, column];
@@ -200,26 +432,34 @@ function pgTableCreator(customizeTableName) {
200
432
  };
201
433
  }
202
434
 
203
- const ViewBaseConfig = Symbol.for('drizzle:ViewBaseConfig');
204
- class View {
205
- static [entityKind] = 'View';
435
+ class CheckBuilder {
436
+ name;
437
+ value;
438
+ static [entityKind] = 'PgCheckBuilder';
439
+ brand;
440
+ constructor(name, value) {
441
+ this.name = name;
442
+ this.value = value;
443
+ }
206
444
  /** @internal */
207
- [ViewBaseConfig];
208
- constructor({ name, schema, selectedFields, query }) {
209
- this[ViewBaseConfig] = {
210
- name,
211
- originalName: name,
212
- schema,
213
- selectedFields,
214
- query: query,
215
- isExisting: !query,
216
- isAlias: false,
217
- };
445
+ build(table) {
446
+ return new Check(table, this);
218
447
  }
219
- getSQL() {
220
- return new SQL([this]);
448
+ }
449
+ class Check {
450
+ table;
451
+ static [entityKind] = 'PgCheck';
452
+ name;
453
+ value;
454
+ constructor(table, builder) {
455
+ this.table = table;
456
+ this.name = builder.name;
457
+ this.value = builder.value;
221
458
  }
222
459
  }
460
+ function check(name, value) {
461
+ return new CheckBuilder(name, value);
462
+ }
223
463
 
224
464
  class ForeignKeyBuilder {
225
465
  static [entityKind] = 'PgForeignKeyBuilder';
@@ -444,2437 +684,2200 @@ class UniqueConstraint {
444
684
  }
445
685
  }
446
686
 
447
- const SubqueryConfig = Symbol.for('drizzle:SubqueryConfig');
448
- class Subquery {
449
- static [entityKind] = 'Subquery';
450
- /** @internal */
451
- [SubqueryConfig];
452
- constructor(sql, selection, alias, isWith = false) {
453
- this[SubqueryConfig] = {
454
- sql,
455
- selection,
456
- alias,
457
- isWith,
458
- };
459
- }
460
- getSQL() {
461
- return new SQL([this]);
687
+ function getTableConfig(table) {
688
+ const columns = Object.values(table[Table.Symbol.Columns]);
689
+ const indexes = [];
690
+ const checks = [];
691
+ const primaryKeys = [];
692
+ const foreignKeys = Object.values(table[PgTable.Symbol.InlineForeignKeys]);
693
+ const uniqueConstraints = [];
694
+ const name = table[Table.Symbol.Name];
695
+ const schema = table[Table.Symbol.Schema];
696
+ const extraConfigBuilder = table[PgTable.Symbol.ExtraConfigBuilder];
697
+ if (extraConfigBuilder !== undefined) {
698
+ const extraConfig = extraConfigBuilder(table[Table.Symbol.Columns]);
699
+ for (const builder of Object.values(extraConfig)) {
700
+ if (is(builder, IndexBuilder)) {
701
+ indexes.push(builder.build(table));
702
+ }
703
+ else if (is(builder, CheckBuilder)) {
704
+ checks.push(builder.build(table));
705
+ }
706
+ else if (is(builder, UniqueConstraintBuilder)) {
707
+ uniqueConstraints.push(builder.build(table));
708
+ }
709
+ else if (is(builder, PrimaryKeyBuilder)) {
710
+ primaryKeys.push(builder.build(table));
711
+ }
712
+ else if (is(builder, ForeignKeyBuilder)) {
713
+ foreignKeys.push(builder.build(table));
714
+ }
715
+ }
462
716
  }
717
+ return {
718
+ columns,
719
+ indexes,
720
+ foreignKeys,
721
+ checks,
722
+ primaryKeys,
723
+ uniqueConstraints,
724
+ name,
725
+ schema,
726
+ };
463
727
  }
464
- class WithSubquery extends Subquery {
465
- static [entityKind] = 'WithSubquery';
728
+ function getViewConfig(view) {
729
+ return {
730
+ ...view[ViewBaseConfig],
731
+ ...view[PgViewConfig],
732
+ };
466
733
  }
467
- class SelectionProxyHandler {
468
- static [entityKind] = 'SelectionProxyHandler';
469
- config;
470
- constructor(config) {
471
- this.config = { ...config };
472
- }
473
- get(subquery, prop) {
474
- if (prop === SubqueryConfig) {
475
- return {
476
- ...subquery[SubqueryConfig],
477
- selection: new Proxy(subquery[SubqueryConfig].selection, this),
478
- };
734
+ function getMaterializedViewConfig(view) {
735
+ return {
736
+ ...view[ViewBaseConfig],
737
+ ...view[PgMaterializedViewConfig],
738
+ };
739
+ }
740
+ function parsePgArrayValue(arrayString, startFrom, inQuotes) {
741
+ for (let i = startFrom; i < arrayString.length; i++) {
742
+ const char = arrayString[i];
743
+ if (char === '\\') {
744
+ i++;
745
+ continue;
479
746
  }
480
- if (prop === ViewBaseConfig) {
481
- return {
482
- ...subquery[ViewBaseConfig],
483
- selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this),
484
- };
747
+ if (char === '"') {
748
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ''), i + 1];
485
749
  }
486
- if (typeof prop === 'symbol') {
487
- return subquery[prop];
750
+ if (inQuotes) {
751
+ continue;
488
752
  }
489
- const columns = is(subquery, Subquery)
490
- ? subquery[SubqueryConfig].selection
491
- : is(subquery, View)
492
- ? subquery[ViewBaseConfig].selectedFields
493
- : subquery;
494
- const value = columns[prop];
495
- if (is(value, SQL.Aliased)) {
496
- // Never return the underlying SQL expression for a field previously selected in a subquery
497
- if (this.config.sqlAliasedBehavior === 'sql' && !value.isSelectionField) {
498
- return value.sql;
499
- }
500
- const newValue = value.clone();
501
- newValue.isSelectionField = true;
502
- return newValue;
753
+ if (char === ',' || char === '}') {
754
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ''), i];
503
755
  }
504
- if (is(value, SQL)) {
505
- if (this.config.sqlBehavior === 'sql') {
506
- return value;
756
+ }
757
+ return [arrayString.slice(startFrom).replace(/\\/g, ''), arrayString.length];
758
+ }
759
+ function parsePgNestedArray(arrayString, startFrom = 0) {
760
+ const result = [];
761
+ let i = startFrom;
762
+ let lastCharIsComma = false;
763
+ while (i < arrayString.length) {
764
+ const char = arrayString[i];
765
+ if (char === ',') {
766
+ if (lastCharIsComma || i === startFrom) {
767
+ result.push('');
507
768
  }
508
- throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
769
+ lastCharIsComma = true;
770
+ i++;
771
+ continue;
509
772
  }
510
- if (is(value, Column)) {
511
- if (this.config.alias) {
512
- return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
513
- }
514
- return value;
773
+ lastCharIsComma = false;
774
+ if (char === '\\') {
775
+ i += 2;
776
+ continue;
515
777
  }
516
- if (typeof value !== 'object' || value === null) {
517
- return value;
778
+ if (char === '"') {
779
+ const [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);
780
+ result.push(value);
781
+ i = startFrom;
782
+ continue;
518
783
  }
519
- return new Proxy(value, new SelectionProxyHandler(this.config));
784
+ if (char === '}') {
785
+ return [result, i + 1];
786
+ }
787
+ if (char === '{') {
788
+ const [value, startFrom] = parsePgNestedArray(arrayString, i + 1);
789
+ result.push(value);
790
+ i = startFrom;
791
+ continue;
792
+ }
793
+ const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
794
+ result.push(value);
795
+ i = newStartFrom;
520
796
  }
797
+ return [result, i];
521
798
  }
522
-
523
- /** @internal */
524
- function mapResultRow(columns, row, joinsNotNullableMap) {
525
- // Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise
526
- const nullifyMap = {};
527
- const result = columns.reduce((result, { path, field }, columnIndex) => {
528
- let decoder;
529
- if (is(field, Column)) {
530
- decoder = field;
799
+ function parsePgArray(arrayString) {
800
+ const [result] = parsePgNestedArray(arrayString, 1);
801
+ return result;
802
+ }
803
+ function makePgArray(array) {
804
+ return `{${array.map((item) => {
805
+ if (Array.isArray(item)) {
806
+ return makePgArray(item);
531
807
  }
532
- else if (is(field, SQL)) {
533
- decoder = field.decoder;
808
+ if (typeof item === 'string' && item.includes(',')) {
809
+ return `"${item.replace(/"/g, '\\"')}"`;
534
810
  }
535
- else {
536
- decoder = field.sql.decoder;
537
- }
538
- let node = result;
539
- for (const [pathChunkIndex, pathChunk] of path.entries()) {
540
- if (pathChunkIndex < path.length - 1) {
541
- if (!(pathChunk in node)) {
542
- node[pathChunk] = {};
543
- }
544
- node = node[pathChunk];
545
- }
546
- else {
547
- const rawValue = row[columnIndex];
548
- const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
549
- if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
550
- const objectName = path[0];
551
- if (!(objectName in nullifyMap)) {
552
- nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
553
- }
554
- else if (typeof nullifyMap[objectName] === 'string' && nullifyMap[objectName] !== getTableName(field.table)) {
555
- nullifyMap[objectName] = false;
556
- }
557
- }
558
- }
559
- }
560
- return result;
561
- }, {});
562
- // Nullify all nested objects from nullifyMap that are nullable
563
- if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
564
- for (const [objectName, tableName] of Object.entries(nullifyMap)) {
565
- if (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {
566
- result[objectName] = null;
567
- }
568
- }
569
- }
570
- return result;
571
- }
572
- /** @internal */
573
- function orderSelectedFields(fields, pathPrefix) {
574
- return Object.entries(fields).reduce((result, [name, field]) => {
575
- if (typeof name !== 'string') {
576
- return result;
577
- }
578
- const newPath = pathPrefix ? [...pathPrefix, name] : [name];
579
- if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
580
- result.push({ path: newPath, field });
581
- }
582
- else if (is(field, Table)) {
583
- result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
584
- }
585
- else {
586
- result.push(...orderSelectedFields(field, newPath));
587
- }
588
- return result;
589
- }, []);
811
+ return `${item}`;
812
+ }).join(',')}}`;
590
813
  }
591
- /** @internal */
592
- function mapUpdateSet(table, values) {
593
- const entries = Object.entries(values)
594
- .filter(([, value]) => value !== undefined)
595
- .map(([key, value]) => {
596
- // eslint-disable-next-line unicorn/prefer-ternary
597
- if (is(value, SQL)) {
598
- return [key, value];
599
- }
600
- else {
601
- return [key, new Param(value, table[Table.Symbol.Columns][key])];
602
- }
603
- });
604
- if (entries.length === 0) {
605
- throw new Error('No values to set');
814
+
815
+ // To understand how to use `ColumnBuilder` and `AnyColumnBuilder`, see `Column` and `AnyColumn` documentation.
816
+ class ColumnBuilder {
817
+ static [entityKind] = 'ColumnBuilder';
818
+ config;
819
+ constructor(name, dataType, columnType) {
820
+ this.config = {
821
+ name,
822
+ notNull: false,
823
+ default: undefined,
824
+ hasDefault: false,
825
+ primaryKey: false,
826
+ isUnique: false,
827
+ uniqueName: undefined,
828
+ uniqueType: undefined,
829
+ dataType,
830
+ columnType,
831
+ };
606
832
  }
607
- return Object.fromEntries(entries);
608
- }
609
- /** @internal */
610
- function applyMixins(baseClass, extendedClasses) {
611
- for (const extendedClass of extendedClasses) {
612
- for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
613
- Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null));
614
- }
833
+ /**
834
+ * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
835
+ *
836
+ * @example
837
+ * ```ts
838
+ * const users = pgTable('users', {
839
+ * id: integer('id').$type<UserId>().primaryKey(),
840
+ * details: json('details').$type<UserDetails>().notNull(),
841
+ * });
842
+ * ```
843
+ */
844
+ $type() {
845
+ return this;
615
846
  }
616
- }
617
- function getTableColumns(table) {
618
- return table[Table.Symbol.Columns];
619
- }
620
- /** @internal */
621
- function getTableLikeName(table) {
622
- return is(table, Subquery)
623
- ? table[SubqueryConfig].alias
624
- : is(table, View)
625
- ? table[ViewBaseConfig].name
626
- : is(table, SQL)
627
- ? undefined
628
- : table[Table.Symbol.IsAlias]
629
- ? table[Table.Symbol.Name]
630
- : table[Table.Symbol.BaseName];
631
- }
632
- function iife(fn, ...args) {
633
- return fn(...args);
634
- }
635
-
636
- class QueryPromise {
637
- static [entityKind] = 'QueryPromise';
638
- [Symbol.toStringTag] = 'QueryPromise';
639
- catch(onRejected) {
640
- return this.then(undefined, onRejected);
847
+ /**
848
+ * Adds a `not null` clause to the column definition.
849
+ *
850
+ * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
851
+ */
852
+ notNull() {
853
+ this.config.notNull = true;
854
+ return this;
641
855
  }
642
- finally(onFinally) {
643
- return this.then((value) => {
644
- onFinally?.();
645
- return value;
646
- }, (reason) => {
647
- onFinally?.();
648
- throw reason;
649
- });
856
+ /**
857
+ * Adds a `default <value>` clause to the column definition.
858
+ *
859
+ * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
860
+ *
861
+ * If you need to set a dynamic default value, use {@link $defaultFn} instead.
862
+ */
863
+ default(value) {
864
+ this.config.default = value;
865
+ this.config.hasDefault = true;
866
+ return this;
650
867
  }
651
- then(onFulfilled, onRejected) {
652
- return this.execute().then(onFulfilled, onRejected);
868
+ /**
869
+ * Adds a dynamic default value to the column.
870
+ * The function will be called when the row is inserted, and the returned value will be used as the column value.
871
+ *
872
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
873
+ */
874
+ $defaultFn(fn) {
875
+ this.config.defaultFn = fn;
876
+ this.config.hasDefault = true;
877
+ return this;
878
+ }
879
+ /**
880
+ * Alias for {@link $defaultFn}.
881
+ */
882
+ $default = this.$defaultFn;
883
+ /**
884
+ * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
885
+ *
886
+ * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
887
+ */
888
+ primaryKey() {
889
+ this.config.primaryKey = true;
890
+ this.config.notNull = true;
891
+ return this;
653
892
  }
654
893
  }
655
894
 
656
- /** @internal */
657
- const tracer = {
658
- startActiveSpan(name, fn) {
659
- {
660
- return fn();
661
- }
662
- },
663
- };
664
-
665
- class DrizzleError extends Error {
666
- static [entityKind] = 'DrizzleError';
667
- constructor(message) {
668
- super(message);
669
- this.name = 'DrizzleError';
895
+ class PgColumnBuilder extends ColumnBuilder {
896
+ foreignKeyConfigs = [];
897
+ static [entityKind] = 'PgColumnBuilder';
898
+ array(size) {
899
+ return new PgArrayBuilder(this.config.name, this, size);
670
900
  }
671
- static wrap(error, message) {
672
- return error instanceof Error // eslint-disable-line no-instanceof/no-instanceof
673
- ? new DrizzleError(message ? `${message}: ${error.message}` : error.message)
674
- : new DrizzleError(message ?? String(error));
901
+ references(ref, actions = {}) {
902
+ this.foreignKeyConfigs.push({ ref, actions });
903
+ return this;
904
+ }
905
+ unique(name, config) {
906
+ this.config.isUnique = true;
907
+ this.config.uniqueName = name;
908
+ this.config.uniqueType = config?.nulls;
909
+ return this;
910
+ }
911
+ /** @internal */
912
+ buildForeignKeys(column, table) {
913
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
914
+ return iife((ref, actions) => {
915
+ const builder = new ForeignKeyBuilder(() => {
916
+ const foreignColumn = ref();
917
+ return { columns: [column], foreignColumns: [foreignColumn] };
918
+ });
919
+ if (actions.onUpdate) {
920
+ builder.onUpdate(actions.onUpdate);
921
+ }
922
+ if (actions.onDelete) {
923
+ builder.onDelete(actions.onDelete);
924
+ }
925
+ return builder.build(table);
926
+ }, ref, actions);
927
+ });
675
928
  }
676
929
  }
677
- class TransactionRollbackError extends DrizzleError {
678
- static [entityKind] = 'TransactionRollbackError';
679
- constructor() {
680
- super('Rollback');
930
+ // To understand how to use `PgColumn` and `PgColumn`, see `Column` and `AnyColumn` documentation.
931
+ class PgColumn extends Column {
932
+ table;
933
+ static [entityKind] = 'PgColumn';
934
+ constructor(table, config) {
935
+ if (!config.uniqueName) {
936
+ config.uniqueName = uniqueKeyName(table, [config.name]);
937
+ }
938
+ super(table, config);
939
+ this.table = table;
681
940
  }
682
941
  }
683
942
 
684
- class PgDialect {
685
- static [entityKind] = 'PgDialect';
686
- async migrate(migrations, session) {
687
- const migrationTableCreate = sql `
688
- CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (
689
- id SERIAL PRIMARY KEY,
690
- hash text NOT NULL,
691
- created_at bigint
692
- )
693
- `;
694
- await session.execute(sql `CREATE SCHEMA IF NOT EXISTS "drizzle"`);
695
- await session.execute(migrationTableCreate);
696
- const dbMigrations = await session.all(sql `select id, hash, created_at from "drizzle"."__drizzle_migrations" order by created_at desc limit 1`);
697
- const lastDbMigration = dbMigrations[0];
698
- await session.transaction(async (tx) => {
699
- for await (const migration of migrations) {
700
- if (!lastDbMigration
701
- || Number(lastDbMigration.created_at) < migration.folderMillis) {
702
- for (const stmt of migration.sql) {
703
- await tx.execute(sql.raw(stmt));
704
- }
705
- await tx.execute(sql `insert into "drizzle"."__drizzle_migrations" ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`);
706
- }
707
- }
708
- });
943
+ class PgArrayBuilder extends PgColumnBuilder {
944
+ static [entityKind] = 'PgArrayBuilder';
945
+ constructor(name, baseBuilder, size) {
946
+ super(name, 'array', 'PgArray');
947
+ this.config.baseBuilder = baseBuilder;
948
+ this.config.size = size;
709
949
  }
710
- escapeName(name) {
711
- return `"${name}"`;
950
+ /** @internal */
951
+ build(table) {
952
+ const baseColumn = this.config.baseBuilder.build(table);
953
+ return new PgArray(table, this.config, baseColumn);
712
954
  }
713
- escapeParam(num) {
714
- return `$${num + 1}`;
955
+ }
956
+ class PgArray extends PgColumn {
957
+ baseColumn;
958
+ range;
959
+ size;
960
+ static [entityKind] = 'PgArray';
961
+ constructor(table, config, baseColumn, range) {
962
+ super(table, config);
963
+ this.baseColumn = baseColumn;
964
+ this.range = range;
965
+ this.size = config.size;
715
966
  }
716
- escapeString(str) {
717
- return `'${str.replace(/'/g, "''")}'`;
967
+ getSQLType() {
968
+ return `${this.baseColumn.getSQLType()}[${typeof this.size === 'number' ? this.size : ''}]`;
718
969
  }
719
- buildDeleteQuery({ table, where, returning }) {
720
- const returningSql = returning
721
- ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
722
- : undefined;
723
- const whereSql = where ? sql ` where ${where}` : undefined;
724
- return sql `delete from ${table}${whereSql}${returningSql}`;
970
+ mapFromDriverValue(value) {
971
+ if (typeof value === 'string') {
972
+ // Thank you node-postgres for not parsing enum arrays
973
+ value = parsePgArray(value);
974
+ }
975
+ return value.map((v) => this.baseColumn.mapFromDriverValue(v));
725
976
  }
726
- buildUpdateSet(table, set) {
727
- const setEntries = Object.entries(set);
728
- const setSize = setEntries.length;
729
- return sql.join(setEntries
730
- .flatMap(([colName, value], i) => {
731
- const col = table[Table.Symbol.Columns][colName];
732
- const res = sql `${sql.identifier(col.name)} = ${value}`;
733
- if (i < setSize - 1) {
734
- return [res, sql.raw(', ')];
735
- }
736
- return [res];
737
- }));
977
+ mapToDriverValue(value, isNestedArray = false) {
978
+ const a = value.map((v) => v === null
979
+ ? null
980
+ : is(this.baseColumn, PgArray)
981
+ ? this.baseColumn.mapToDriverValue(v, true)
982
+ : this.baseColumn.mapToDriverValue(v));
983
+ if (isNestedArray)
984
+ return a;
985
+ return makePgArray(a);
738
986
  }
739
- buildUpdateQuery({ table, set, where, returning }) {
740
- const setSql = this.buildUpdateSet(table, set);
741
- const returningSql = returning
742
- ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
743
- : undefined;
744
- const whereSql = where ? sql ` where ${where}` : undefined;
745
- return sql `update ${table} set ${setSql}${whereSql}${returningSql}`;
987
+ }
988
+
989
+ class PgDateColumnBaseBuilder extends PgColumnBuilder {
990
+ static [entityKind] = 'PgDateColumnBaseBuilder';
991
+ defaultNow() {
992
+ return this.default(sql `now()`);
746
993
  }
747
- /**
748
- * Builds selection SQL with provided fields/expressions
749
- *
750
- * Examples:
751
- *
752
- * `select <selection> from`
753
- *
754
- * `insert ... returning <selection>`
755
- *
756
- * If `isSingleTable` is true, then columns won't be prefixed with table name
757
- */
758
- buildSelection(fields, { isSingleTable = false } = {}) {
759
- const columnsLen = fields.length;
760
- const chunks = fields
761
- .flatMap(({ field }, i) => {
762
- const chunk = [];
763
- if (is(field, SQL.Aliased) && field.isSelectionField) {
764
- chunk.push(sql.identifier(field.fieldAlias));
994
+ }
995
+
996
+ class PgDateBuilder extends PgDateColumnBaseBuilder {
997
+ static [entityKind] = 'PgDateBuilder';
998
+ constructor(name) {
999
+ super(name, 'date', 'PgDate');
1000
+ }
1001
+ /** @internal */
1002
+ build(table) {
1003
+ return new PgDate(table, this.config);
1004
+ }
1005
+ }
1006
+ class PgDate extends PgColumn {
1007
+ static [entityKind] = 'PgDate';
1008
+ getSQLType() {
1009
+ return 'date';
1010
+ }
1011
+ mapFromDriverValue(value) {
1012
+ return new Date(value);
1013
+ }
1014
+ mapToDriverValue(value) {
1015
+ return value.toISOString();
1016
+ }
1017
+ }
1018
+ class PgDateStringBuilder extends PgDateColumnBaseBuilder {
1019
+ static [entityKind] = 'PgDateStringBuilder';
1020
+ constructor(name) {
1021
+ super(name, 'string', 'PgDateString');
1022
+ }
1023
+ /** @internal */
1024
+ build(table) {
1025
+ return new PgDateString(table, this.config);
1026
+ }
1027
+ }
1028
+ class PgDateString extends PgColumn {
1029
+ static [entityKind] = 'PgDateString';
1030
+ getSQLType() {
1031
+ return 'date';
1032
+ }
1033
+ }
1034
+ function date(name, config) {
1035
+ if (config?.mode === 'date') {
1036
+ return new PgDateBuilder(name);
1037
+ }
1038
+ return new PgDateStringBuilder(name);
1039
+ }
1040
+
1041
+ class PgJsonBuilder extends PgColumnBuilder {
1042
+ static [entityKind] = 'PgJsonBuilder';
1043
+ constructor(name) {
1044
+ super(name, 'json', 'PgJson');
1045
+ }
1046
+ /** @internal */
1047
+ build(table) {
1048
+ return new PgJson(table, this.config);
1049
+ }
1050
+ }
1051
+ class PgJson extends PgColumn {
1052
+ static [entityKind] = 'PgJson';
1053
+ constructor(table, config) {
1054
+ super(table, config);
1055
+ }
1056
+ getSQLType() {
1057
+ return 'json';
1058
+ }
1059
+ mapToDriverValue(value) {
1060
+ return JSON.stringify(value);
1061
+ }
1062
+ mapFromDriverValue(value) {
1063
+ if (typeof value === 'string') {
1064
+ try {
1065
+ return JSON.parse(value);
765
1066
  }
766
- else if (is(field, SQL.Aliased) || is(field, SQL)) {
767
- const query = is(field, SQL.Aliased) ? field.sql : field;
768
- if (isSingleTable) {
769
- chunk.push(new SQL(query.queryChunks.map((c) => {
770
- if (is(c, PgColumn)) {
771
- return sql.identifier(c.name);
772
- }
773
- return c;
774
- })));
775
- }
776
- else {
777
- chunk.push(query);
778
- }
779
- if (is(field, SQL.Aliased)) {
780
- chunk.push(sql ` as ${sql.identifier(field.fieldAlias)}`);
781
- }
1067
+ catch {
1068
+ return value;
782
1069
  }
783
- else if (is(field, Column)) {
784
- if (isSingleTable) {
785
- chunk.push(sql.identifier(field.name));
786
- }
787
- else {
788
- chunk.push(field);
789
- }
1070
+ }
1071
+ return value;
1072
+ }
1073
+ }
1074
+ function json(name) {
1075
+ return new PgJsonBuilder(name);
1076
+ }
1077
+
1078
+ class PgJsonbBuilder extends PgColumnBuilder {
1079
+ static [entityKind] = 'PgJsonbBuilder';
1080
+ constructor(name) {
1081
+ super(name, 'json', 'PgJsonb');
1082
+ }
1083
+ /** @internal */
1084
+ build(table) {
1085
+ return new PgJsonb(table, this.config);
1086
+ }
1087
+ }
1088
+ class PgJsonb extends PgColumn {
1089
+ static [entityKind] = 'PgJsonb';
1090
+ constructor(table, config) {
1091
+ super(table, config);
1092
+ }
1093
+ getSQLType() {
1094
+ return 'jsonb';
1095
+ }
1096
+ mapToDriverValue(value) {
1097
+ return JSON.stringify(value);
1098
+ }
1099
+ mapFromDriverValue(value) {
1100
+ if (typeof value === 'string') {
1101
+ try {
1102
+ return JSON.parse(value);
790
1103
  }
791
- if (i < columnsLen - 1) {
792
- chunk.push(sql `, `);
1104
+ catch {
1105
+ return value;
793
1106
  }
794
- return chunk;
795
- });
796
- return sql.join(chunks);
1107
+ }
1108
+ return value;
797
1109
  }
798
- buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, lockingClauses, distinct, }) {
799
- const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
800
- for (const f of fieldsList) {
801
- if (is(f.field, Column)
802
- && getTableName(f.field.table)
803
- !== (is(table, Subquery)
804
- ? table[SubqueryConfig].alias
805
- : is(table, PgViewBase)
806
- ? table[ViewBaseConfig].name
807
- : is(table, SQL)
808
- ? undefined
809
- : getTableName(table))
810
- && !((table) => joins?.some(({ alias }) => alias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])))(f.field.table)) {
811
- const tableName = getTableName(f.field.table);
812
- throw new Error(`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?`);
813
- }
814
- }
815
- const isSingleTable = !joins || joins.length === 0;
816
- let withSql;
817
- if (withList?.length) {
818
- const withSqlChunks = [sql `with `];
819
- for (const [i, w] of withList.entries()) {
820
- withSqlChunks.push(sql `${sql.identifier(w[SubqueryConfig].alias)} as (${w[SubqueryConfig].sql})`);
821
- if (i < withList.length - 1) {
822
- withSqlChunks.push(sql `, `);
823
- }
824
- }
825
- withSqlChunks.push(sql ` `);
826
- withSql = sql.join(withSqlChunks);
827
- }
828
- let distinctSql;
829
- if (distinct) {
830
- distinctSql = distinct === true ? sql ` distinct` : sql ` distinct on (${sql.join(distinct.on, ', ')})`;
831
- }
832
- const selection = this.buildSelection(fieldsList, { isSingleTable });
833
- const tableSql = (() => {
834
- if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {
835
- let fullName = sql `${sql.identifier(table[Table.Symbol.OriginalName])}`;
836
- if (table[Table.Symbol.Schema]) {
837
- fullName = sql `${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
838
- }
839
- return sql `${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
840
- }
841
- return table;
842
- })();
843
- const joinsArray = [];
844
- if (joins) {
845
- for (const [index, joinMeta] of joins.entries()) {
846
- if (index === 0) {
847
- joinsArray.push(sql ` `);
848
- }
849
- const table = joinMeta.table;
850
- const lateralSql = joinMeta.lateral ? sql ` lateral` : undefined;
851
- if (is(table, PgTable)) {
852
- const tableName = table[PgTable.Symbol.Name];
853
- const tableSchema = table[PgTable.Symbol.Schema];
854
- const origTableName = table[PgTable.Symbol.OriginalName];
855
- const alias = tableName === origTableName ? undefined : joinMeta.alias;
856
- joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql `${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql ` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
857
- }
858
- else if (is(table, View)) {
859
- const viewName = table[ViewBaseConfig].name;
860
- const viewSchema = table[ViewBaseConfig].schema;
861
- const origViewName = table[ViewBaseConfig].originalName;
862
- const alias = viewName === origViewName ? undefined : joinMeta.alias;
863
- joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql `${sql.identifier(viewSchema)}.` : undefined}${sql.identifier(origViewName)}${alias && sql ` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
864
- }
865
- else {
866
- joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}`);
867
- }
868
- if (index < joins.length - 1) {
869
- joinsArray.push(sql ` `);
870
- }
871
- }
872
- }
873
- const joinsSql = sql.join(joinsArray);
874
- const whereSql = where ? sql ` where ${where}` : undefined;
875
- const havingSql = having ? sql ` having ${having}` : undefined;
876
- let orderBySql;
877
- if (orderBy && orderBy.length > 0) {
878
- orderBySql = sql ` order by ${sql.join(orderBy, sql `, `)}`;
879
- }
880
- let groupBySql;
881
- if (groupBy && groupBy.length > 0) {
882
- groupBySql = sql ` group by ${sql.join(groupBy, sql `, `)}`;
883
- }
884
- const limitSql = limit ? sql ` limit ${limit}` : undefined;
885
- const offsetSql = offset ? sql ` offset ${offset}` : undefined;
886
- const lockingClausesSql = sql.empty();
887
- if (lockingClauses) {
888
- for (const { strength, config } of lockingClauses) {
889
- const clauseSql = sql ` for ${sql.raw(strength)}`;
890
- if (config.of) {
891
- clauseSql.append(sql ` of ${config.of}`);
892
- }
893
- if (config.noWait) {
894
- clauseSql.append(sql ` no wait`);
895
- }
896
- else if (config.skipLocked) {
897
- clauseSql.append(sql ` skip locked`);
898
- }
899
- lockingClausesSql.append(clauseSql);
900
- }
901
- }
902
- return sql `${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
1110
+ }
1111
+ function jsonb(name) {
1112
+ return new PgJsonbBuilder(name);
1113
+ }
1114
+
1115
+ class PgNumericBuilder extends PgColumnBuilder {
1116
+ static [entityKind] = 'PgNumericBuilder';
1117
+ constructor(name, precision, scale) {
1118
+ super(name, 'string', 'PgNumeric');
1119
+ this.config.precision = precision;
1120
+ this.config.scale = scale;
903
1121
  }
904
- buildInsertQuery({ table, values, onConflict, returning }) {
905
- const valuesSqlList = [];
906
- const columns = table[Table.Symbol.Columns];
907
- const colEntries = Object.entries(columns);
908
- const insertOrder = colEntries.map(([, column]) => sql.identifier(column.name));
909
- for (const [valueIndex, value] of values.entries()) {
910
- const valueList = [];
911
- for (const [fieldName, col] of colEntries) {
912
- const colValue = value[fieldName];
913
- if (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {
914
- // eslint-disable-next-line unicorn/no-negated-condition
915
- if (col.defaultFn !== undefined) {
916
- const defaultFnResult = col.defaultFn();
917
- const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
918
- valueList.push(defaultValue);
919
- }
920
- else {
921
- valueList.push(sql `default`);
922
- }
923
- }
924
- else {
925
- valueList.push(colValue);
926
- }
927
- }
928
- valuesSqlList.push(valueList);
929
- if (valueIndex < values.length - 1) {
930
- valuesSqlList.push(sql `, `);
931
- }
932
- }
933
- const valuesSql = sql.join(valuesSqlList);
934
- const returningSql = returning
935
- ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
936
- : undefined;
937
- const onConflictSql = onConflict ? sql ` on conflict ${onConflict}` : undefined;
938
- return sql `insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
1122
+ /** @internal */
1123
+ build(table) {
1124
+ return new PgNumeric(table, this.config);
939
1125
  }
940
- buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
941
- const concurrentlySql = concurrently ? sql ` concurrently` : undefined;
942
- const withNoDataSql = withNoData ? sql ` with no data` : undefined;
943
- return sql `refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
1126
+ }
1127
+ class PgNumeric extends PgColumn {
1128
+ static [entityKind] = 'PgNumeric';
1129
+ precision;
1130
+ scale;
1131
+ constructor(table, config) {
1132
+ super(table, config);
1133
+ this.precision = config.precision;
1134
+ this.scale = config.scale;
944
1135
  }
945
- prepareTyping(encoder) {
946
- if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
947
- return 'json';
948
- }
949
- else if (is(encoder, PgNumeric)) {
950
- return 'decimal';
951
- }
952
- else if (is(encoder, PgTime)) {
953
- return 'time';
954
- }
955
- else if (is(encoder, PgTimestamp)) {
956
- return 'timestamp';
957
- }
958
- else if (is(encoder, PgDate)) {
959
- return 'date';
1136
+ getSQLType() {
1137
+ if (this.precision !== undefined && this.scale !== undefined) {
1138
+ return `numeric(${this.precision}, ${this.scale})`;
960
1139
  }
961
- else if (is(encoder, PgUUID)) {
962
- return 'uuid';
1140
+ else if (this.precision === undefined) {
1141
+ return 'numeric';
963
1142
  }
964
1143
  else {
965
- return 'none';
1144
+ return `numeric(${this.precision})`;
966
1145
  }
967
1146
  }
968
- sqlToQuery(sql) {
969
- return sql.toQuery({
970
- escapeName: this.escapeName,
971
- escapeParam: this.escapeParam,
972
- escapeString: this.escapeString,
973
- prepareTyping: this.prepareTyping,
974
- });
1147
+ }
1148
+ function numeric(name, config) {
1149
+ return new PgNumericBuilder(name, config?.precision, config?.scale);
1150
+ }
1151
+ const decimal = numeric;
1152
+
1153
+ class PgTimeBuilder extends PgDateColumnBaseBuilder {
1154
+ withTimezone;
1155
+ precision;
1156
+ static [entityKind] = 'PgTimeBuilder';
1157
+ constructor(name, withTimezone, precision) {
1158
+ super(name, 'string', 'PgTime');
1159
+ this.withTimezone = withTimezone;
1160
+ this.precision = precision;
1161
+ this.config.withTimezone = withTimezone;
1162
+ this.config.precision = precision;
975
1163
  }
976
- // buildRelationalQueryWithPK({
977
- // fullSchema,
978
- // schema,
979
- // tableNamesMap,
980
- // table,
981
- // tableConfig,
982
- // queryConfig: config,
983
- // tableAlias,
984
- // isRoot = false,
985
- // joinOn,
986
- // }: {
987
- // fullSchema: Record<string, unknown>;
988
- // schema: TablesRelationalConfig;
989
- // tableNamesMap: Record<string, string>;
990
- // table: PgTable;
991
- // tableConfig: TableRelationalConfig;
992
- // queryConfig: true | DBQueryConfig<'many', true>;
993
- // tableAlias: string;
994
- // isRoot?: boolean;
995
- // joinOn?: SQL;
996
- // }): BuildRelationalQueryResult<PgTable, PgColumn> {
997
- // // For { "<relation>": true }, return a table with selection of all columns
998
- // if (config === true) {
999
- // const selectionEntries = Object.entries(tableConfig.columns);
1000
- // const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
1001
- // [key, value],
1002
- // ) => ({
1003
- // dbKey: value.name,
1004
- // tsKey: key,
1005
- // field: value as PgColumn,
1006
- // relationTableTsKey: undefined,
1007
- // isJson: false,
1008
- // selection: [],
1009
- // }));
1010
- // return {
1011
- // tableTsKey: tableConfig.tsName,
1012
- // sql: table,
1013
- // selection,
1014
- // };
1015
- // }
1016
- // // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
1017
- // // let selectionForBuild = selection;
1018
- // const aliasedColumns = Object.fromEntries(
1019
- // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
1020
- // );
1021
- // const aliasedRelations = Object.fromEntries(
1022
- // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
1023
- // );
1024
- // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
1025
- // let where, hasUserDefinedWhere;
1026
- // if (config.where) {
1027
- // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
1028
- // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
1029
- // hasUserDefinedWhere = !!where;
1030
- // }
1031
- // where = and(joinOn, where);
1032
- // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
1033
- // let joins: Join[] = [];
1034
- // let selectedColumns: string[] = [];
1035
- // // Figure out which columns to select
1036
- // if (config.columns) {
1037
- // let isIncludeMode = false;
1038
- // for (const [field, value] of Object.entries(config.columns)) {
1039
- // if (value === undefined) {
1040
- // continue;
1041
- // }
1042
- // if (field in tableConfig.columns) {
1043
- // if (!isIncludeMode && value === true) {
1044
- // isIncludeMode = true;
1045
- // }
1046
- // selectedColumns.push(field);
1047
- // }
1048
- // }
1049
- // if (selectedColumns.length > 0) {
1050
- // selectedColumns = isIncludeMode
1051
- // ? selectedColumns.filter((c) => config.columns?.[c] === true)
1052
- // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1053
- // }
1054
- // } else {
1055
- // // Select all columns if selection is not specified
1056
- // selectedColumns = Object.keys(tableConfig.columns);
1057
- // }
1058
- // // for (const field of selectedColumns) {
1059
- // // const column = tableConfig.columns[field]! as PgColumn;
1060
- // // fieldsSelection.push({ tsKey: field, value: column });
1061
- // // }
1062
- // let initiallySelectedRelations: {
1063
- // tsKey: string;
1064
- // queryConfig: true | DBQueryConfig<'many', false>;
1065
- // relation: Relation;
1066
- // }[] = [];
1067
- // // let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
1068
- // // Figure out which relations to select
1069
- // if (config.with) {
1070
- // initiallySelectedRelations = Object.entries(config.with)
1071
- // .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
1072
- // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
1073
- // }
1074
- // const manyRelations = initiallySelectedRelations.filter((r) =>
1075
- // is(r.relation, Many)
1076
- // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
1077
- // );
1078
- // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
1079
- // const isInnermostQuery = manyRelations.length < 2;
1080
- // const selectedExtras: {
1081
- // tsKey: string;
1082
- // value: SQL.Aliased;
1083
- // }[] = [];
1084
- // // Figure out which extras to select
1085
- // if (isInnermostQuery && config.extras) {
1086
- // const extras = typeof config.extras === 'function'
1087
- // ? config.extras(aliasedFields, { sql })
1088
- // : config.extras;
1089
- // for (const [tsKey, value] of Object.entries(extras)) {
1090
- // selectedExtras.push({
1091
- // tsKey,
1092
- // value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
1093
- // });
1094
- // }
1095
- // }
1096
- // // Transform `fieldsSelection` into `selection`
1097
- // // `fieldsSelection` shouldn't be used after this point
1098
- // // for (const { tsKey, value, isExtra } of fieldsSelection) {
1099
- // // selection.push({
1100
- // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
1101
- // // tsKey,
1102
- // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
1103
- // // relationTableTsKey: undefined,
1104
- // // isJson: false,
1105
- // // isExtra,
1106
- // // selection: [],
1107
- // // });
1108
- // // }
1109
- // let orderByOrig = typeof config.orderBy === 'function'
1110
- // ? config.orderBy(aliasedFields, orderByOperators)
1111
- // : config.orderBy ?? [];
1112
- // if (!Array.isArray(orderByOrig)) {
1113
- // orderByOrig = [orderByOrig];
1114
- // }
1115
- // const orderBy = orderByOrig.map((orderByValue) => {
1116
- // if (is(orderByValue, Column)) {
1117
- // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
1118
- // }
1119
- // return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1120
- // });
1121
- // const limit = isInnermostQuery ? config.limit : undefined;
1122
- // const offset = isInnermostQuery ? config.offset : undefined;
1123
- // // For non-root queries without additional config except columns, return a table with selection
1124
- // if (
1125
- // !isRoot
1126
- // && initiallySelectedRelations.length === 0
1127
- // && selectedExtras.length === 0
1128
- // && !where
1129
- // && orderBy.length === 0
1130
- // && limit === undefined
1131
- // && offset === undefined
1132
- // ) {
1133
- // return {
1134
- // tableTsKey: tableConfig.tsName,
1135
- // sql: table,
1136
- // selection: selectedColumns.map((key) => ({
1137
- // dbKey: tableConfig.columns[key]!.name,
1138
- // tsKey: key,
1139
- // field: tableConfig.columns[key] as PgColumn,
1140
- // relationTableTsKey: undefined,
1141
- // isJson: false,
1142
- // selection: [],
1143
- // })),
1144
- // };
1145
- // }
1146
- // const selectedRelationsWithoutPK:
1147
- // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
1148
- // for (
1149
- // const {
1150
- // tsKey: selectedRelationTsKey,
1151
- // queryConfig: selectedRelationConfigValue,
1152
- // relation,
1153
- // } of initiallySelectedRelations
1154
- // ) {
1155
- // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1156
- // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1157
- // const relationTableTsName = tableNamesMap[relationTableName]!;
1158
- // const relationTable = schema[relationTableTsName]!;
1159
- // if (relationTable.primaryKey.length > 0) {
1160
- // continue;
1161
- // }
1162
- // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1163
- // const joinOn = and(
1164
- // ...normalizedRelation.fields.map((field, i) =>
1165
- // eq(
1166
- // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1167
- // aliasedTableColumn(field, tableAlias),
1168
- // )
1169
- // ),
1170
- // );
1171
- // const builtRelation = this.buildRelationalQueryWithoutPK({
1172
- // fullSchema,
1173
- // schema,
1174
- // tableNamesMap,
1175
- // table: fullSchema[relationTableTsName] as PgTable,
1176
- // tableConfig: schema[relationTableTsName]!,
1177
- // queryConfig: selectedRelationConfigValue,
1178
- // tableAlias: relationTableAlias,
1179
- // joinOn,
1180
- // nestedQueryRelation: relation,
1181
- // });
1182
- // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
1183
- // joins.push({
1184
- // on: sql`true`,
1185
- // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
1186
- // alias: relationTableAlias,
1187
- // joinType: 'left',
1188
- // lateral: true,
1189
- // });
1190
- // selectedRelations.push({
1191
- // dbKey: selectedRelationTsKey,
1192
- // tsKey: selectedRelationTsKey,
1193
- // field,
1194
- // relationTableTsKey: relationTableTsName,
1195
- // isJson: true,
1196
- // selection: builtRelation.selection,
1197
- // });
1198
- // }
1199
- // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
1200
- // is(r.relation, One)
1201
- // );
1202
- // // Process all One relations with PKs, because they can all be joined on the same level
1203
- // for (
1204
- // const {
1205
- // tsKey: selectedRelationTsKey,
1206
- // queryConfig: selectedRelationConfigValue,
1207
- // relation,
1208
- // } of oneRelations
1209
- // ) {
1210
- // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1211
- // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1212
- // const relationTableTsName = tableNamesMap[relationTableName]!;
1213
- // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1214
- // const relationTable = schema[relationTableTsName]!;
1215
- // if (relationTable.primaryKey.length === 0) {
1216
- // continue;
1217
- // }
1218
- // const joinOn = and(
1219
- // ...normalizedRelation.fields.map((field, i) =>
1220
- // eq(
1221
- // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1222
- // aliasedTableColumn(field, tableAlias),
1223
- // )
1224
- // ),
1225
- // );
1226
- // const builtRelation = this.buildRelationalQueryWithPK({
1227
- // fullSchema,
1228
- // schema,
1229
- // tableNamesMap,
1230
- // table: fullSchema[relationTableTsName] as PgTable,
1231
- // tableConfig: schema[relationTableTsName]!,
1232
- // queryConfig: selectedRelationConfigValue,
1233
- // tableAlias: relationTableAlias,
1234
- // joinOn,
1235
- // });
1236
- // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
1237
- // sql.join(
1238
- // builtRelation.selection.map(({ field }) =>
1239
- // is(field, SQL.Aliased)
1240
- // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
1241
- // : is(field, Column)
1242
- // ? aliasedTableColumn(field, relationTableAlias)
1243
- // : field
1244
- // ),
1245
- // sql`, `,
1246
- // )
1247
- // }) end`.as(selectedRelationTsKey);
1248
- // const isLateralJoin = is(builtRelation.sql, SQL);
1249
- // joins.push({
1250
- // on: isLateralJoin ? sql`true` : joinOn,
1251
- // table: is(builtRelation.sql, SQL)
1252
- // ? new Subquery(builtRelation.sql, {}, relationTableAlias)
1253
- // : aliasedTable(builtRelation.sql, relationTableAlias),
1254
- // alias: relationTableAlias,
1255
- // joinType: 'left',
1256
- // lateral: is(builtRelation.sql, SQL),
1257
- // });
1258
- // selectedRelations.push({
1259
- // dbKey: selectedRelationTsKey,
1260
- // tsKey: selectedRelationTsKey,
1261
- // field,
1262
- // relationTableTsKey: relationTableTsName,
1263
- // isJson: true,
1264
- // selection: builtRelation.selection,
1265
- // });
1266
- // }
1267
- // let distinct: PgSelectConfig['distinct'];
1268
- // let tableFrom: PgTable | Subquery = table;
1269
- // // Process first Many relation - each one requires a nested subquery
1270
- // const manyRelation = manyRelations[0];
1271
- // if (manyRelation) {
1272
- // const {
1273
- // tsKey: selectedRelationTsKey,
1274
- // queryConfig: selectedRelationQueryConfig,
1275
- // relation,
1276
- // } = manyRelation;
1277
- // distinct = {
1278
- // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
1279
- // };
1280
- // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1281
- // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1282
- // const relationTableTsName = tableNamesMap[relationTableName]!;
1283
- // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1284
- // const joinOn = and(
1285
- // ...normalizedRelation.fields.map((field, i) =>
1286
- // eq(
1287
- // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1288
- // aliasedTableColumn(field, tableAlias),
1289
- // )
1290
- // ),
1291
- // );
1292
- // const builtRelationJoin = this.buildRelationalQueryWithPK({
1293
- // fullSchema,
1294
- // schema,
1295
- // tableNamesMap,
1296
- // table: fullSchema[relationTableTsName] as PgTable,
1297
- // tableConfig: schema[relationTableTsName]!,
1298
- // queryConfig: selectedRelationQueryConfig,
1299
- // tableAlias: relationTableAlias,
1300
- // joinOn,
1301
- // });
1302
- // const builtRelationSelectionField = sql`case when ${
1303
- // sql.identifier(relationTableAlias)
1304
- // } is null then '[]' else json_agg(json_build_array(${
1305
- // sql.join(
1306
- // builtRelationJoin.selection.map(({ field }) =>
1307
- // is(field, SQL.Aliased)
1308
- // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
1309
- // : is(field, Column)
1310
- // ? aliasedTableColumn(field, relationTableAlias)
1311
- // : field
1312
- // ),
1313
- // sql`, `,
1314
- // )
1315
- // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
1316
- // const isLateralJoin = is(builtRelationJoin.sql, SQL);
1317
- // joins.push({
1318
- // on: isLateralJoin ? sql`true` : joinOn,
1319
- // table: isLateralJoin
1320
- // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
1321
- // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
1322
- // alias: relationTableAlias,
1323
- // joinType: 'left',
1324
- // lateral: isLateralJoin,
1325
- // });
1326
- // // Build the "from" subquery with the remaining Many relations
1327
- // const builtTableFrom = this.buildRelationalQueryWithPK({
1328
- // fullSchema,
1329
- // schema,
1330
- // tableNamesMap,
1331
- // table,
1332
- // tableConfig,
1333
- // queryConfig: {
1334
- // ...config,
1335
- // where: undefined,
1336
- // orderBy: undefined,
1337
- // limit: undefined,
1338
- // offset: undefined,
1339
- // with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
1340
- // (result, { tsKey, queryConfig: configValue }) => {
1341
- // result[tsKey] = configValue;
1342
- // return result;
1343
- // },
1344
- // {},
1345
- // ),
1346
- // },
1347
- // tableAlias,
1348
- // });
1349
- // selectedRelations.push({
1350
- // dbKey: selectedRelationTsKey,
1351
- // tsKey: selectedRelationTsKey,
1352
- // field: builtRelationSelectionField,
1353
- // relationTableTsKey: relationTableTsName,
1354
- // isJson: true,
1355
- // selection: builtRelationJoin.selection,
1356
- // });
1357
- // // selection = builtTableFrom.selection.map((item) =>
1358
- // // is(item.field, SQL.Aliased)
1359
- // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
1360
- // // : item
1361
- // // );
1362
- // // selectionForBuild = [{
1363
- // // dbKey: '*',
1364
- // // tsKey: '*',
1365
- // // field: sql`${sql.identifier(tableAlias)}.*`,
1366
- // // selection: [],
1367
- // // isJson: false,
1368
- // // relationTableTsKey: undefined,
1369
- // // }];
1370
- // // const newSelectionItem: (typeof selection)[number] = {
1371
- // // dbKey: selectedRelationTsKey,
1372
- // // tsKey: selectedRelationTsKey,
1373
- // // field,
1374
- // // relationTableTsKey: relationTableTsName,
1375
- // // isJson: true,
1376
- // // selection: builtRelationJoin.selection,
1377
- // // };
1378
- // // selection.push(newSelectionItem);
1379
- // // selectionForBuild.push(newSelectionItem);
1380
- // tableFrom = is(builtTableFrom.sql, PgTable)
1381
- // ? builtTableFrom.sql
1382
- // : new Subquery(builtTableFrom.sql, {}, tableAlias);
1383
- // }
1384
- // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
1385
- // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
1386
- // }
1387
- // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
1388
- // function prepareSelectedColumns() {
1389
- // return selectedColumns.map((key) => ({
1390
- // dbKey: tableConfig.columns[key]!.name,
1391
- // tsKey: key,
1392
- // field: tableConfig.columns[key] as PgColumn,
1393
- // relationTableTsKey: undefined,
1394
- // isJson: false,
1395
- // selection: [],
1396
- // }));
1397
- // }
1398
- // function prepareSelectedExtras() {
1399
- // return selectedExtras.map((item) => ({
1400
- // dbKey: item.value.fieldAlias,
1401
- // tsKey: item.tsKey,
1402
- // field: item.value,
1403
- // relationTableTsKey: undefined,
1404
- // isJson: false,
1405
- // selection: [],
1406
- // }));
1407
- // }
1408
- // if (isRoot) {
1409
- // selection = [
1410
- // ...prepareSelectedColumns(),
1411
- // ...prepareSelectedExtras(),
1412
- // ];
1413
- // }
1414
- // if (hasUserDefinedWhere || orderBy.length > 0) {
1415
- // tableFrom = new Subquery(
1416
- // this.buildSelectQuery({
1417
- // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
1418
- // fields: {},
1419
- // fieldsFlat: selectionForBuild.map(({ field }) => ({
1420
- // path: [],
1421
- // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
1422
- // })),
1423
- // joins,
1424
- // distinct,
1425
- // }),
1426
- // {},
1427
- // tableAlias,
1428
- // );
1429
- // selectionForBuild = selection.map((item) =>
1430
- // is(item.field, SQL.Aliased)
1431
- // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
1432
- // : item
1433
- // );
1434
- // joins = [];
1435
- // distinct = undefined;
1436
- // }
1437
- // const result = this.buildSelectQuery({
1438
- // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
1439
- // fields: {},
1440
- // fieldsFlat: selectionForBuild.map(({ field }) => ({
1441
- // path: [],
1442
- // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
1443
- // })),
1444
- // where,
1445
- // limit,
1446
- // offset,
1447
- // joins,
1448
- // orderBy,
1449
- // distinct,
1450
- // });
1451
- // return {
1452
- // tableTsKey: tableConfig.tsName,
1453
- // sql: result,
1454
- // selection,
1455
- // };
1456
- // }
1457
- buildRelationalQueryWithoutPK({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn, }) {
1458
- let selection = [];
1459
- let limit, offset, orderBy = [], where;
1460
- const joins = [];
1461
- if (config === true) {
1462
- const selectionEntries = Object.entries(tableConfig.columns);
1463
- selection = selectionEntries.map(([key, value]) => ({
1464
- dbKey: value.name,
1465
- tsKey: key,
1466
- field: aliasedTableColumn(value, tableAlias),
1467
- relationTableTsKey: undefined,
1468
- isJson: false,
1469
- selection: [],
1470
- }));
1471
- }
1472
- else {
1473
- const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
1474
- if (config.where) {
1475
- const whereSql = typeof config.where === 'function'
1476
- ? config.where(aliasedColumns, getOperators())
1477
- : config.where;
1478
- where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
1479
- }
1480
- const fieldsSelection = [];
1481
- let selectedColumns = [];
1482
- // Figure out which columns to select
1483
- if (config.columns) {
1484
- let isIncludeMode = false;
1485
- for (const [field, value] of Object.entries(config.columns)) {
1486
- if (value === undefined) {
1487
- continue;
1488
- }
1489
- if (field in tableConfig.columns) {
1490
- if (!isIncludeMode && value === true) {
1491
- isIncludeMode = true;
1492
- }
1493
- selectedColumns.push(field);
1494
- }
1495
- }
1496
- if (selectedColumns.length > 0) {
1497
- selectedColumns = isIncludeMode
1498
- ? selectedColumns.filter((c) => config.columns?.[c] === true)
1499
- : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1500
- }
1501
- }
1502
- else {
1503
- // Select all columns if selection is not specified
1504
- selectedColumns = Object.keys(tableConfig.columns);
1505
- }
1506
- for (const field of selectedColumns) {
1507
- const column = tableConfig.columns[field];
1508
- fieldsSelection.push({ tsKey: field, value: column });
1509
- }
1510
- let selectedRelations = [];
1511
- // Figure out which relations to select
1512
- if (config.with) {
1513
- selectedRelations = Object.entries(config.with)
1514
- .filter((entry) => !!entry[1])
1515
- .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
1516
- }
1517
- let extras;
1518
- // Figure out which extras to select
1519
- if (config.extras) {
1520
- extras = typeof config.extras === 'function'
1521
- ? config.extras(aliasedColumns, { sql })
1522
- : config.extras;
1523
- for (const [tsKey, value] of Object.entries(extras)) {
1524
- fieldsSelection.push({
1525
- tsKey,
1526
- value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
1527
- });
1528
- }
1529
- }
1530
- // Transform `fieldsSelection` into `selection`
1531
- // `fieldsSelection` shouldn't be used after this point
1532
- for (const { tsKey, value } of fieldsSelection) {
1533
- selection.push({
1534
- dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
1535
- tsKey,
1536
- field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
1537
- relationTableTsKey: undefined,
1538
- isJson: false,
1539
- selection: [],
1540
- });
1541
- }
1542
- let orderByOrig = typeof config.orderBy === 'function'
1543
- ? config.orderBy(aliasedColumns, getOrderByOperators())
1544
- : config.orderBy ?? [];
1545
- if (!Array.isArray(orderByOrig)) {
1546
- orderByOrig = [orderByOrig];
1547
- }
1548
- orderBy = orderByOrig.map((orderByValue) => {
1549
- if (is(orderByValue, Column)) {
1550
- return aliasedTableColumn(orderByValue, tableAlias);
1551
- }
1552
- return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1553
- });
1554
- limit = config.limit;
1555
- offset = config.offset;
1556
- // Process all relations
1557
- for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation, } of selectedRelations) {
1558
- const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1559
- const relationTableName = relation.referencedTable[Table.Symbol.Name];
1560
- const relationTableTsName = tableNamesMap[relationTableName];
1561
- const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1562
- const joinOn = and(...normalizedRelation.fields.map((field, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field, tableAlias))));
1563
- const builtRelation = this.buildRelationalQueryWithoutPK({
1564
- fullSchema,
1565
- schema,
1566
- tableNamesMap,
1567
- table: fullSchema[relationTableTsName],
1568
- tableConfig: schema[relationTableTsName],
1569
- queryConfig: is(relation, One)
1570
- ? (selectedRelationConfigValue === true
1571
- ? { limit: 1 }
1572
- : { ...selectedRelationConfigValue, limit: 1 })
1573
- : selectedRelationConfigValue,
1574
- tableAlias: relationTableAlias,
1575
- joinOn,
1576
- nestedQueryRelation: relation,
1577
- });
1578
- const field = sql `${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
1579
- joins.push({
1580
- on: sql `true`,
1581
- table: new Subquery(builtRelation.sql, {}, relationTableAlias),
1582
- alias: relationTableAlias,
1583
- joinType: 'left',
1584
- lateral: true,
1585
- });
1586
- selection.push({
1587
- dbKey: selectedRelationTsKey,
1588
- tsKey: selectedRelationTsKey,
1589
- field,
1590
- relationTableTsKey: relationTableTsName,
1591
- isJson: true,
1592
- selection: builtRelation.selection,
1593
- });
1594
- }
1595
- }
1596
- if (selection.length === 0) {
1597
- throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
1598
- }
1599
- let result;
1600
- where = and(joinOn, where);
1601
- if (nestedQueryRelation) {
1602
- let field = sql `json_build_array(${sql.join(selection.map(({ field, tsKey, isJson }) => isJson
1603
- ? sql `${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier('data')}`
1604
- : is(field, SQL.Aliased)
1605
- ? field.sql
1606
- : field), sql `, `)})`;
1607
- if (is(nestedQueryRelation, Many)) {
1608
- field = sql `coalesce(json_agg(${field}${orderBy.length > 0 ? sql ` order by ${sql.join(orderBy, sql `, `)}` : undefined}), '[]'::json)`;
1609
- // orderBy = [];
1610
- }
1611
- const nestedSelection = [{
1612
- dbKey: 'data',
1613
- tsKey: 'data',
1614
- field: field.as('data'),
1615
- isJson: true,
1616
- relationTableTsKey: tableConfig.tsName,
1617
- selection,
1618
- }];
1619
- const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
1620
- if (needsSubquery) {
1621
- result = this.buildSelectQuery({
1622
- table: aliasedTable(table, tableAlias),
1623
- fields: {},
1624
- fieldsFlat: [{
1625
- path: [],
1626
- field: sql.raw('*'),
1627
- }],
1628
- where,
1629
- limit,
1630
- offset,
1631
- orderBy,
1632
- });
1633
- where = undefined;
1634
- limit = undefined;
1635
- offset = undefined;
1636
- orderBy = [];
1637
- }
1638
- else {
1639
- result = aliasedTable(table, tableAlias);
1640
- }
1641
- result = this.buildSelectQuery({
1642
- table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
1643
- fields: {},
1644
- fieldsFlat: nestedSelection.map(({ field }) => ({
1645
- path: [],
1646
- field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
1647
- })),
1648
- joins,
1649
- where,
1650
- limit,
1651
- offset,
1652
- orderBy,
1653
- });
1654
- }
1655
- else {
1656
- result = this.buildSelectQuery({
1657
- table: aliasedTable(table, tableAlias),
1658
- fields: {},
1659
- fieldsFlat: selection.map(({ field }) => ({
1660
- path: [],
1661
- field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
1662
- })),
1663
- joins,
1664
- where,
1665
- limit,
1666
- offset,
1667
- orderBy,
1668
- });
1669
- }
1670
- return {
1671
- tableTsKey: tableConfig.tsName,
1672
- sql: result,
1673
- selection,
1674
- };
1164
+ /** @internal */
1165
+ build(table) {
1166
+ return new PgTime(table, this.config);
1167
+ }
1168
+ }
1169
+ class PgTime extends PgColumn {
1170
+ static [entityKind] = 'PgTime';
1171
+ withTimezone;
1172
+ precision;
1173
+ constructor(table, config) {
1174
+ super(table, config);
1175
+ this.withTimezone = config.withTimezone;
1176
+ this.precision = config.precision;
1177
+ }
1178
+ getSQLType() {
1179
+ const precision = this.precision === undefined ? '' : `(${this.precision})`;
1180
+ return `time${precision}${this.withTimezone ? ' with time zone' : ''}`;
1675
1181
  }
1676
1182
  }
1183
+ function time(name, config = {}) {
1184
+ return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);
1185
+ }
1677
1186
 
1678
- class TypedQueryBuilder {
1679
- static [entityKind] = 'TypedQueryBuilder';
1187
+ class PgTimestampBuilder extends PgDateColumnBaseBuilder {
1188
+ static [entityKind] = 'PgTimestampBuilder';
1189
+ constructor(name, withTimezone, precision) {
1190
+ super(name, 'date', 'PgTimestamp');
1191
+ this.config.withTimezone = withTimezone;
1192
+ this.config.precision = precision;
1193
+ }
1680
1194
  /** @internal */
1681
- getSelectedFields() {
1682
- return this._.selectedFields;
1195
+ build(table) {
1196
+ return new PgTimestamp(table, this.config);
1683
1197
  }
1684
1198
  }
1685
-
1686
- class PgSelectBuilder {
1687
- static [entityKind] = 'PgSelectBuilder';
1688
- fields;
1689
- session;
1690
- dialect;
1691
- withList = [];
1692
- distinct;
1693
- constructor(config) {
1694
- this.fields = config.fields;
1695
- this.session = config.session;
1696
- this.dialect = config.dialect;
1697
- if (config.withList) {
1698
- this.withList = config.withList;
1699
- }
1700
- this.distinct = config.distinct;
1199
+ class PgTimestamp extends PgColumn {
1200
+ static [entityKind] = 'PgTimestamp';
1201
+ withTimezone;
1202
+ precision;
1203
+ constructor(table, config) {
1204
+ super(table, config);
1205
+ this.withTimezone = config.withTimezone;
1206
+ this.precision = config.precision;
1207
+ }
1208
+ getSQLType() {
1209
+ const precision = this.precision === undefined ? '' : ` (${this.precision})`;
1210
+ return `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;
1211
+ }
1212
+ mapFromDriverValue = (value) => {
1213
+ return new Date(this.withTimezone ? value : value + '+0000');
1214
+ };
1215
+ mapToDriverValue = (value) => {
1216
+ return this.withTimezone ? value.toUTCString() : value.toISOString();
1217
+ };
1218
+ }
1219
+ class PgTimestampStringBuilder extends PgDateColumnBaseBuilder {
1220
+ static [entityKind] = 'PgTimestampStringBuilder';
1221
+ constructor(name, withTimezone, precision) {
1222
+ super(name, 'string', 'PgTimestampString');
1223
+ this.config.withTimezone = withTimezone;
1224
+ this.config.precision = precision;
1225
+ }
1226
+ /** @internal */
1227
+ build(table) {
1228
+ return new PgTimestampString(table, this.config);
1229
+ }
1230
+ }
1231
+ class PgTimestampString extends PgColumn {
1232
+ static [entityKind] = 'PgTimestampString';
1233
+ withTimezone;
1234
+ precision;
1235
+ constructor(table, config) {
1236
+ super(table, config);
1237
+ this.withTimezone = config.withTimezone;
1238
+ this.precision = config.precision;
1239
+ }
1240
+ getSQLType() {
1241
+ const precision = this.precision === undefined ? '' : `(${this.precision})`;
1242
+ return `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;
1243
+ }
1244
+ }
1245
+ function timestamp(name, config = {}) {
1246
+ if (config.mode === 'string') {
1247
+ return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);
1248
+ }
1249
+ return new PgTimestampBuilder(name, config.withTimezone ?? false, config.precision);
1250
+ }
1251
+
1252
+ class PgUUIDBuilder extends PgColumnBuilder {
1253
+ static [entityKind] = 'PgUUIDBuilder';
1254
+ constructor(name) {
1255
+ super(name, 'string', 'PgUUID');
1701
1256
  }
1702
1257
  /**
1703
- * Specify the table, subquery, or other target that you're
1704
- * building a select query against.
1705
- *
1706
- * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM|Postgres from documentation}
1258
+ * Adds `default gen_random_uuid()` to the column definition.
1707
1259
  */
1708
- from(source) {
1709
- const isPartialSelect = !!this.fields;
1710
- let fields;
1711
- if (this.fields) {
1712
- fields = this.fields;
1713
- }
1714
- else if (is(source, Subquery)) {
1715
- // This is required to use the proxy handler to get the correct field values from the subquery
1716
- fields = Object.fromEntries(Object.keys(source[SubqueryConfig].selection).map((key) => [key, source[key]]));
1717
- }
1718
- else if (is(source, PgViewBase)) {
1719
- fields = source[ViewBaseConfig].selectedFields;
1720
- }
1721
- else if (is(source, SQL)) {
1722
- fields = {};
1723
- }
1724
- else {
1725
- fields = getTableColumns(source);
1726
- }
1727
- return new PgSelect({
1728
- table: source,
1729
- fields,
1730
- isPartialSelect,
1731
- session: this.session,
1732
- dialect: this.dialect,
1733
- withList: this.withList,
1734
- distinct: this.distinct,
1735
- });
1260
+ defaultRandom() {
1261
+ return this.default(sql `gen_random_uuid()`);
1262
+ }
1263
+ /** @internal */
1264
+ build(table) {
1265
+ return new PgUUID(table, this.config);
1736
1266
  }
1737
1267
  }
1738
- class PgSelectQueryBuilder extends TypedQueryBuilder {
1739
- static [entityKind] = 'PgSelectQueryBuilder';
1740
- _;
1741
- config;
1742
- joinsNotNullableMap;
1743
- tableName;
1744
- isPartialSelect;
1745
- session;
1746
- dialect;
1747
- constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
1748
- super();
1749
- this.config = {
1750
- withList,
1751
- table,
1752
- fields: { ...fields },
1753
- distinct,
1754
- };
1755
- this.isPartialSelect = isPartialSelect;
1756
- this.session = session;
1757
- this.dialect = dialect;
1758
- this._ = {
1759
- selectedFields: fields,
1760
- };
1761
- this.tableName = getTableLikeName(table);
1762
- this.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};
1268
+ class PgUUID extends PgColumn {
1269
+ static [entityKind] = 'PgUUID';
1270
+ getSQLType() {
1271
+ return 'uuid';
1763
1272
  }
1764
- createJoin(joinType) {
1765
- return (table, on) => {
1766
- const baseTableName = this.tableName;
1767
- const tableName = getTableLikeName(table);
1768
- if (typeof tableName === 'string' && this.config.joins?.some((join) => join.alias === tableName)) {
1769
- throw new Error(`Alias "${tableName}" is already used in this query`);
1770
- }
1771
- if (!this.isPartialSelect) {
1772
- // If this is the first join and this is not a partial select and we're not selecting from raw SQL, "move" the fields from the main table to the nested object
1773
- if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {
1774
- this.config.fields = {
1775
- [baseTableName]: this.config.fields,
1776
- };
1777
- }
1778
- if (typeof tableName === 'string' && !is(table, SQL)) {
1779
- const selection = is(table, Subquery)
1780
- ? table[SubqueryConfig].selection
1781
- : is(table, View)
1782
- ? table[ViewBaseConfig].selectedFields
1783
- : table[Table.Symbol.Columns];
1784
- this.config.fields[tableName] = selection;
1785
- }
1786
- }
1787
- if (typeof on === 'function') {
1788
- on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
1789
- }
1790
- if (!this.config.joins) {
1791
- this.config.joins = [];
1792
- }
1793
- this.config.joins.push({ on, table, joinType, alias: tableName });
1794
- if (typeof tableName === 'string') {
1795
- switch (joinType) {
1796
- case 'left': {
1797
- this.joinsNotNullableMap[tableName] = false;
1798
- break;
1799
- }
1800
- case 'right': {
1801
- this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
1802
- this.joinsNotNullableMap[tableName] = true;
1803
- break;
1804
- }
1805
- case 'inner': {
1806
- this.joinsNotNullableMap[tableName] = true;
1807
- break;
1808
- }
1809
- case 'full': {
1810
- this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
1811
- this.joinsNotNullableMap[tableName] = false;
1812
- break;
1273
+ }
1274
+ function uuid(name) {
1275
+ return new PgUUIDBuilder(name);
1276
+ }
1277
+
1278
+ class PgDialect {
1279
+ static [entityKind] = 'PgDialect';
1280
+ async migrate(migrations, session) {
1281
+ const migrationTableCreate = sql `
1282
+ CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (
1283
+ id SERIAL PRIMARY KEY,
1284
+ hash text NOT NULL,
1285
+ created_at bigint
1286
+ )
1287
+ `;
1288
+ await session.execute(sql `CREATE SCHEMA IF NOT EXISTS "drizzle"`);
1289
+ await session.execute(migrationTableCreate);
1290
+ const dbMigrations = await session.all(sql `select id, hash, created_at from "drizzle"."__drizzle_migrations" order by created_at desc limit 1`);
1291
+ const lastDbMigration = dbMigrations[0];
1292
+ await session.transaction(async (tx) => {
1293
+ for await (const migration of migrations) {
1294
+ if (!lastDbMigration
1295
+ || Number(lastDbMigration.created_at) < migration.folderMillis) {
1296
+ for (const stmt of migration.sql) {
1297
+ await tx.execute(sql.raw(stmt));
1813
1298
  }
1299
+ await tx.execute(sql `insert into "drizzle"."__drizzle_migrations" ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`);
1814
1300
  }
1815
1301
  }
1816
- return this;
1817
- };
1302
+ });
1818
1303
  }
1819
- /**
1820
- * For each row of the table, include
1821
- * values from a matching row of the joined
1822
- * table, if there is a matching row. If not,
1823
- * all of the columns of the joined table
1824
- * will be set to null.
1825
- */
1826
- leftJoin = this.createJoin('left');
1827
- /**
1828
- * Includes all of the rows of the joined table.
1829
- * If there is no matching row in the main table,
1830
- * all the columns of the main table will be
1831
- * set to null.
1832
- */
1833
- rightJoin = this.createJoin('right');
1834
- /**
1835
- * This is the default type of join.
1836
- *
1837
- * For each row of the table, the joined table
1838
- * needs to have a matching row, or it will
1839
- * be excluded from results.
1840
- */
1841
- innerJoin = this.createJoin('inner');
1842
- /**
1843
- * Rows from both the main & joined are included,
1844
- * regardless of whether or not they have matching
1845
- * rows in the other table.
1846
- */
1847
- fullJoin = this.createJoin('full');
1848
- /**
1849
- * Specify a condition to narrow the result set. Multiple
1850
- * conditions can be combined with the `and` and `or`
1851
- * functions.
1852
- *
1853
- * ## Examples
1854
- *
1855
- * ```ts
1856
- * // Find cars made in the year 2000
1857
- * db.select().from(cars).where(eq(cars.year, 2000));
1858
- * ```
1859
- */
1860
- where(where) {
1861
- if (typeof where === 'function') {
1862
- where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
1863
- }
1864
- this.config.where = where;
1865
- return this;
1304
+ escapeName(name) {
1305
+ return `"${name}"`;
1866
1306
  }
1867
- /**
1868
- * Sets the HAVING clause of this query, which often
1869
- * used with GROUP BY and filters rows after they've been
1870
- * grouped together and combined.
1871
- *
1872
- * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-HAVING|Postgres having clause documentation}
1873
- */
1874
- having(having) {
1875
- if (typeof having === 'function') {
1876
- having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
1877
- }
1878
- this.config.having = having;
1879
- return this;
1307
+ escapeParam(num) {
1308
+ return `$${num + 1}`;
1880
1309
  }
1881
- groupBy(...columns) {
1882
- if (typeof columns[0] === 'function') {
1883
- const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
1884
- this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
1885
- }
1886
- else {
1887
- this.config.groupBy = columns;
1888
- }
1889
- return this;
1310
+ escapeString(str) {
1311
+ return `'${str.replace(/'/g, "''")}'`;
1890
1312
  }
1891
- orderBy(...columns) {
1892
- if (typeof columns[0] === 'function') {
1893
- const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
1894
- this.config.orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
1895
- }
1896
- else {
1897
- this.config.orderBy = columns;
1898
- }
1899
- return this;
1313
+ buildDeleteQuery({ table, where, returning }) {
1314
+ const returningSql = returning
1315
+ ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
1316
+ : undefined;
1317
+ const whereSql = where ? sql ` where ${where}` : undefined;
1318
+ return sql `delete from ${table}${whereSql}${returningSql}`;
1319
+ }
1320
+ buildUpdateSet(table, set) {
1321
+ const setEntries = Object.entries(set);
1322
+ const setSize = setEntries.length;
1323
+ return sql.join(setEntries
1324
+ .flatMap(([colName, value], i) => {
1325
+ const col = table[Table.Symbol.Columns][colName];
1326
+ const res = sql `${sql.identifier(col.name)} = ${value}`;
1327
+ if (i < setSize - 1) {
1328
+ return [res, sql.raw(', ')];
1329
+ }
1330
+ return [res];
1331
+ }));
1332
+ }
1333
+ buildUpdateQuery({ table, set, where, returning }) {
1334
+ const setSql = this.buildUpdateSet(table, set);
1335
+ const returningSql = returning
1336
+ ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
1337
+ : undefined;
1338
+ const whereSql = where ? sql ` where ${where}` : undefined;
1339
+ return sql `update ${table} set ${setSql}${whereSql}${returningSql}`;
1900
1340
  }
1901
1341
  /**
1902
- * Set the maximum number of rows that will be
1903
- * returned by this query.
1904
- *
1905
- * ## Examples
1342
+ * Builds selection SQL with provided fields/expressions
1906
1343
  *
1907
- * ```ts
1908
- * // Get the first 10 people from this query.
1909
- * db.select().from(people).limit(10);
1910
- * ```
1344
+ * Examples:
1911
1345
  *
1912
- * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-LIMIT|Postgres LIMIT documentation}
1913
- */
1914
- limit(limit) {
1915
- this.config.limit = limit;
1916
- return this;
1917
- }
1918
- /**
1919
- * Skip a number of rows when returning results
1920
- * from this query.
1346
+ * `select <selection> from`
1921
1347
  *
1922
- * ## Examples
1348
+ * `insert ... returning <selection>`
1923
1349
  *
1924
- * ```ts
1925
- * // Get the 10th-20th people from this query.
1926
- * db.select().from(people).offset(10).limit(10);
1927
- * ```
1350
+ * If `isSingleTable` is true, then columns won't be prefixed with table name
1928
1351
  */
1929
- offset(offset) {
1930
- this.config.offset = offset;
1931
- return this;
1352
+ buildSelection(fields, { isSingleTable = false } = {}) {
1353
+ const columnsLen = fields.length;
1354
+ const chunks = fields
1355
+ .flatMap(({ field }, i) => {
1356
+ const chunk = [];
1357
+ if (is(field, SQL.Aliased) && field.isSelectionField) {
1358
+ chunk.push(sql.identifier(field.fieldAlias));
1359
+ }
1360
+ else if (is(field, SQL.Aliased) || is(field, SQL)) {
1361
+ const query = is(field, SQL.Aliased) ? field.sql : field;
1362
+ if (isSingleTable) {
1363
+ chunk.push(new SQL(query.queryChunks.map((c) => {
1364
+ if (is(c, PgColumn)) {
1365
+ return sql.identifier(c.name);
1366
+ }
1367
+ return c;
1368
+ })));
1369
+ }
1370
+ else {
1371
+ chunk.push(query);
1372
+ }
1373
+ if (is(field, SQL.Aliased)) {
1374
+ chunk.push(sql ` as ${sql.identifier(field.fieldAlias)}`);
1375
+ }
1376
+ }
1377
+ else if (is(field, Column)) {
1378
+ if (isSingleTable) {
1379
+ chunk.push(sql.identifier(field.name));
1380
+ }
1381
+ else {
1382
+ chunk.push(field);
1383
+ }
1384
+ }
1385
+ if (i < columnsLen - 1) {
1386
+ chunk.push(sql `, `);
1387
+ }
1388
+ return chunk;
1389
+ });
1390
+ return sql.join(chunks);
1932
1391
  }
1933
- /**
1934
- * The FOR clause specifies a lock strength for this query
1935
- * that controls how strictly it acquires exclusive access to
1936
- * the rows being queried.
1937
- *
1938
- * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE|Postgres locking clause documentation}
1939
- */
1940
- for(strength, config = {}) {
1941
- if (!this.config.lockingClauses) {
1942
- this.config.lockingClauses = [];
1392
+ buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, lockingClauses, distinct, }) {
1393
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
1394
+ for (const f of fieldsList) {
1395
+ if (is(f.field, Column)
1396
+ && getTableName(f.field.table)
1397
+ !== (is(table, Subquery)
1398
+ ? table[SubqueryConfig].alias
1399
+ : is(table, PgViewBase)
1400
+ ? table[ViewBaseConfig].name
1401
+ : is(table, SQL)
1402
+ ? undefined
1403
+ : getTableName(table))
1404
+ && !((table) => joins?.some(({ alias }) => alias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])))(f.field.table)) {
1405
+ const tableName = getTableName(f.field.table);
1406
+ throw new Error(`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?`);
1407
+ }
1943
1408
  }
1944
- this.config.lockingClauses.push({ strength, config });
1945
- return this;
1946
- }
1947
- /** @internal */
1948
- getSQL() {
1949
- return this.dialect.buildSelectQuery(this.config);
1950
- }
1951
- toSQL() {
1952
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1953
- return rest;
1954
- }
1955
- as(alias) {
1956
- return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias), new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
1957
- }
1958
- }
1959
- class PgSelect extends PgSelectQueryBuilder {
1960
- static [entityKind] = 'PgSelect';
1961
- _prepare(name) {
1962
- const { session, config, dialect, joinsNotNullableMap } = this;
1963
- if (!session) {
1964
- throw new Error('Cannot execute a query on a query builder. Please use a database instance instead.');
1409
+ const isSingleTable = !joins || joins.length === 0;
1410
+ let withSql;
1411
+ if (withList?.length) {
1412
+ const withSqlChunks = [sql `with `];
1413
+ for (const [i, w] of withList.entries()) {
1414
+ withSqlChunks.push(sql `${sql.identifier(w[SubqueryConfig].alias)} as (${w[SubqueryConfig].sql})`);
1415
+ if (i < withList.length - 1) {
1416
+ withSqlChunks.push(sql `, `);
1417
+ }
1418
+ }
1419
+ withSqlChunks.push(sql ` `);
1420
+ withSql = sql.join(withSqlChunks);
1965
1421
  }
1966
- return tracer.startActiveSpan('drizzle.prepareQuery', () => {
1967
- const fieldsList = orderSelectedFields(config.fields);
1968
- const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name);
1969
- query.joinsNotNullableMap = joinsNotNullableMap;
1970
- return query;
1971
- });
1972
- }
1973
- /**
1974
- * Create a prepared statement for this query. This allows
1975
- * the database to remember this query for the given session
1976
- * and call it by name, rather than specifying the full query.
1977
- *
1978
- * {@link https://www.postgresql.org/docs/current/sql-prepare.html|Postgres prepare documentation}
1979
- */
1980
- prepare(name) {
1981
- return this._prepare(name);
1422
+ let distinctSql;
1423
+ if (distinct) {
1424
+ distinctSql = distinct === true ? sql ` distinct` : sql ` distinct on (${sql.join(distinct.on, ', ')})`;
1425
+ }
1426
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
1427
+ const tableSql = (() => {
1428
+ if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {
1429
+ let fullName = sql `${sql.identifier(table[Table.Symbol.OriginalName])}`;
1430
+ if (table[Table.Symbol.Schema]) {
1431
+ fullName = sql `${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
1432
+ }
1433
+ return sql `${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
1434
+ }
1435
+ return table;
1436
+ })();
1437
+ const joinsArray = [];
1438
+ if (joins) {
1439
+ for (const [index, joinMeta] of joins.entries()) {
1440
+ if (index === 0) {
1441
+ joinsArray.push(sql ` `);
1442
+ }
1443
+ const table = joinMeta.table;
1444
+ const lateralSql = joinMeta.lateral ? sql ` lateral` : undefined;
1445
+ if (is(table, PgTable)) {
1446
+ const tableName = table[PgTable.Symbol.Name];
1447
+ const tableSchema = table[PgTable.Symbol.Schema];
1448
+ const origTableName = table[PgTable.Symbol.OriginalName];
1449
+ const alias = tableName === origTableName ? undefined : joinMeta.alias;
1450
+ joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql `${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql ` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
1451
+ }
1452
+ else if (is(table, View)) {
1453
+ const viewName = table[ViewBaseConfig].name;
1454
+ const viewSchema = table[ViewBaseConfig].schema;
1455
+ const origViewName = table[ViewBaseConfig].originalName;
1456
+ const alias = viewName === origViewName ? undefined : joinMeta.alias;
1457
+ joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql `${sql.identifier(viewSchema)}.` : undefined}${sql.identifier(origViewName)}${alias && sql ` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
1458
+ }
1459
+ else {
1460
+ joinsArray.push(sql `${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}`);
1461
+ }
1462
+ if (index < joins.length - 1) {
1463
+ joinsArray.push(sql ` `);
1464
+ }
1465
+ }
1466
+ }
1467
+ const joinsSql = sql.join(joinsArray);
1468
+ const whereSql = where ? sql ` where ${where}` : undefined;
1469
+ const havingSql = having ? sql ` having ${having}` : undefined;
1470
+ let orderBySql;
1471
+ if (orderBy && orderBy.length > 0) {
1472
+ orderBySql = sql ` order by ${sql.join(orderBy, sql `, `)}`;
1473
+ }
1474
+ let groupBySql;
1475
+ if (groupBy && groupBy.length > 0) {
1476
+ groupBySql = sql ` group by ${sql.join(groupBy, sql `, `)}`;
1477
+ }
1478
+ const limitSql = limit ? sql ` limit ${limit}` : undefined;
1479
+ const offsetSql = offset ? sql ` offset ${offset}` : undefined;
1480
+ const lockingClausesSql = sql.empty();
1481
+ if (lockingClauses) {
1482
+ for (const { strength, config } of lockingClauses) {
1483
+ const clauseSql = sql ` for ${sql.raw(strength)}`;
1484
+ if (config.of) {
1485
+ clauseSql.append(sql ` of ${config.of}`);
1486
+ }
1487
+ if (config.noWait) {
1488
+ clauseSql.append(sql ` no wait`);
1489
+ }
1490
+ else if (config.skipLocked) {
1491
+ clauseSql.append(sql ` skip locked`);
1492
+ }
1493
+ lockingClausesSql.append(clauseSql);
1494
+ }
1495
+ }
1496
+ return sql `${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
1982
1497
  }
1983
- execute = (placeholderValues) => {
1984
- return tracer.startActiveSpan('drizzle.operation', () => {
1985
- return this._prepare().execute(placeholderValues);
1986
- });
1987
- };
1988
- }
1989
- applyMixins(PgSelect, [QueryPromise]);
1990
-
1991
- class QueryBuilder {
1992
- static [entityKind] = 'PgQueryBuilder';
1993
- dialect;
1994
- $with(alias) {
1995
- const queryBuilder = this;
1996
- return {
1997
- as(qb) {
1998
- if (typeof qb === 'function') {
1999
- qb = qb(queryBuilder);
1498
+ buildInsertQuery({ table, values, onConflict, returning }) {
1499
+ const valuesSqlList = [];
1500
+ const columns = table[Table.Symbol.Columns];
1501
+ const colEntries = Object.entries(columns);
1502
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(column.name));
1503
+ for (const [valueIndex, value] of values.entries()) {
1504
+ const valueList = [];
1505
+ for (const [fieldName, col] of colEntries) {
1506
+ const colValue = value[fieldName];
1507
+ if (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {
1508
+ // eslint-disable-next-line unicorn/no-negated-condition
1509
+ if (col.defaultFn !== undefined) {
1510
+ const defaultFnResult = col.defaultFn();
1511
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
1512
+ valueList.push(defaultValue);
1513
+ }
1514
+ else {
1515
+ valueList.push(sql `default`);
1516
+ }
2000
1517
  }
2001
- return new Proxy(new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
2002
- },
2003
- };
1518
+ else {
1519
+ valueList.push(colValue);
1520
+ }
1521
+ }
1522
+ valuesSqlList.push(valueList);
1523
+ if (valueIndex < values.length - 1) {
1524
+ valuesSqlList.push(sql `, `);
1525
+ }
1526
+ }
1527
+ const valuesSql = sql.join(valuesSqlList);
1528
+ const returningSql = returning
1529
+ ? sql ` returning ${this.buildSelection(returning, { isSingleTable: true })}`
1530
+ : undefined;
1531
+ const onConflictSql = onConflict ? sql ` on conflict ${onConflict}` : undefined;
1532
+ return sql `insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
2004
1533
  }
2005
- with(...queries) {
2006
- const self = this;
2007
- function select(fields) {
2008
- return new PgSelectBuilder({
2009
- fields: fields ?? undefined,
2010
- session: undefined,
2011
- dialect: self.getDialect(),
2012
- withList: queries,
2013
- });
1534
+ buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
1535
+ const concurrentlySql = concurrently ? sql ` concurrently` : undefined;
1536
+ const withNoDataSql = withNoData ? sql ` with no data` : undefined;
1537
+ return sql `refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
1538
+ }
1539
+ prepareTyping(encoder) {
1540
+ if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
1541
+ return 'json';
2014
1542
  }
2015
- function selectDistinct(fields) {
2016
- return new PgSelectBuilder({
2017
- fields: fields ?? undefined,
2018
- session: undefined,
2019
- dialect: self.getDialect(),
2020
- distinct: true,
2021
- });
1543
+ else if (is(encoder, PgNumeric)) {
1544
+ return 'decimal';
2022
1545
  }
2023
- function selectDistinctOn(on, fields) {
2024
- return new PgSelectBuilder({
2025
- fields: fields ?? undefined,
2026
- session: undefined,
2027
- dialect: self.getDialect(),
2028
- distinct: { on },
2029
- });
1546
+ else if (is(encoder, PgTime)) {
1547
+ return 'time';
2030
1548
  }
2031
- return { select, selectDistinct, selectDistinctOn };
2032
- }
2033
- select(fields) {
2034
- return new PgSelectBuilder({
2035
- fields: fields ?? undefined,
2036
- session: undefined,
2037
- dialect: this.getDialect(),
2038
- });
2039
- }
2040
- selectDistinct(fields) {
2041
- return new PgSelectBuilder({
2042
- fields: fields ?? undefined,
2043
- session: undefined,
2044
- dialect: this.getDialect(),
2045
- distinct: true,
2046
- });
2047
- }
2048
- selectDistinctOn(on, fields) {
2049
- return new PgSelectBuilder({
2050
- fields: fields ?? undefined,
2051
- session: undefined,
2052
- dialect: this.getDialect(),
2053
- distinct: { on },
2054
- });
2055
- }
2056
- // Lazy load dialect to avoid circular dependency
2057
- getDialect() {
2058
- if (!this.dialect) {
2059
- this.dialect = new PgDialect();
1549
+ else if (is(encoder, PgTimestamp)) {
1550
+ return 'timestamp';
2060
1551
  }
2061
- return this.dialect;
2062
- }
2063
- }
2064
-
2065
- class DefaultViewBuilderCore {
2066
- name;
2067
- schema;
2068
- static [entityKind] = 'PgDefaultViewBuilderCore';
2069
- constructor(name, schema) {
2070
- this.name = name;
2071
- this.schema = schema;
2072
- }
2073
- config = {};
2074
- with(config) {
2075
- this.config.with = config;
2076
- return this;
2077
- }
2078
- }
2079
- class ViewBuilder extends DefaultViewBuilderCore {
2080
- static [entityKind] = 'PgViewBuilder';
2081
- as(qb) {
2082
- if (typeof qb === 'function') {
2083
- qb = qb(new QueryBuilder());
1552
+ else if (is(encoder, PgDate)) {
1553
+ return 'date';
2084
1554
  }
2085
- const selectionProxy = new SelectionProxyHandler({
2086
- alias: this.name,
2087
- sqlBehavior: 'error',
2088
- sqlAliasedBehavior: 'alias',
2089
- replaceOriginalName: true,
2090
- });
2091
- const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
2092
- return new Proxy(new PgView({
2093
- pgConfig: this.config,
2094
- config: {
2095
- name: this.name,
2096
- schema: this.schema,
2097
- selectedFields: aliasedSelection,
2098
- query: qb.getSQL().inlineParams(),
2099
- },
2100
- }), selectionProxy);
2101
- }
2102
- }
2103
- class ManualViewBuilder extends DefaultViewBuilderCore {
2104
- static [entityKind] = 'PgManualViewBuilder';
2105
- columns;
2106
- constructor(name, columns, schema) {
2107
- super(name, schema);
2108
- this.columns = getTableColumns(pgTable(name, columns));
2109
- }
2110
- existing() {
2111
- return new Proxy(new PgView({
2112
- pgConfig: undefined,
2113
- config: {
2114
- name: this.name,
2115
- schema: this.schema,
2116
- selectedFields: this.columns,
2117
- query: undefined,
2118
- },
2119
- }), new SelectionProxyHandler({
2120
- alias: this.name,
2121
- sqlBehavior: 'error',
2122
- sqlAliasedBehavior: 'alias',
2123
- replaceOriginalName: true,
2124
- }));
2125
- }
2126
- as(query) {
2127
- return new Proxy(new PgView({
2128
- pgConfig: this.config,
2129
- config: {
2130
- name: this.name,
2131
- schema: this.schema,
2132
- selectedFields: this.columns,
2133
- query: query.inlineParams(),
2134
- },
2135
- }), new SelectionProxyHandler({
2136
- alias: this.name,
2137
- sqlBehavior: 'error',
2138
- sqlAliasedBehavior: 'alias',
2139
- replaceOriginalName: true,
2140
- }));
2141
- }
2142
- }
2143
- class MaterializedViewBuilderCore {
2144
- name;
2145
- schema;
2146
- static [entityKind] = 'PgMaterializedViewBuilderCore';
2147
- constructor(name, schema) {
2148
- this.name = name;
2149
- this.schema = schema;
2150
- }
2151
- config = {};
2152
- using(using) {
2153
- this.config.using = using;
2154
- return this;
2155
- }
2156
- with(config) {
2157
- this.config.with = config;
2158
- return this;
2159
- }
2160
- tablespace(tablespace) {
2161
- this.config.tablespace = tablespace;
2162
- return this;
2163
- }
2164
- withNoData() {
2165
- this.config.withNoData = true;
2166
- return this;
2167
- }
2168
- }
2169
- class MaterializedViewBuilder extends MaterializedViewBuilderCore {
2170
- static [entityKind] = 'PgMaterializedViewBuilder';
2171
- as(qb) {
2172
- if (typeof qb === 'function') {
2173
- qb = qb(new QueryBuilder());
1555
+ else if (is(encoder, PgUUID)) {
1556
+ return 'uuid';
1557
+ }
1558
+ else {
1559
+ return 'none';
2174
1560
  }
2175
- const selectionProxy = new SelectionProxyHandler({
2176
- alias: this.name,
2177
- sqlBehavior: 'error',
2178
- sqlAliasedBehavior: 'alias',
2179
- replaceOriginalName: true,
2180
- });
2181
- const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
2182
- return new Proxy(new PgMaterializedView({
2183
- pgConfig: {
2184
- with: this.config.with,
2185
- using: this.config.using,
2186
- tablespace: this.config.tablespace,
2187
- withNoData: this.config.withNoData,
2188
- },
2189
- config: {
2190
- name: this.name,
2191
- schema: this.schema,
2192
- selectedFields: aliasedSelection,
2193
- query: qb.getSQL().inlineParams(),
2194
- },
2195
- }), selectionProxy);
2196
- }
2197
- }
2198
- class ManualMaterializedViewBuilder extends MaterializedViewBuilderCore {
2199
- static [entityKind] = 'PgManualMaterializedViewBuilder';
2200
- columns;
2201
- constructor(name, columns, schema) {
2202
- super(name, schema);
2203
- this.columns = getTableColumns(pgTable(name, columns));
2204
- }
2205
- existing() {
2206
- return new Proxy(new PgMaterializedView({
2207
- pgConfig: undefined,
2208
- config: {
2209
- name: this.name,
2210
- schema: this.schema,
2211
- selectedFields: this.columns,
2212
- query: undefined,
2213
- },
2214
- }), new SelectionProxyHandler({
2215
- alias: this.name,
2216
- sqlBehavior: 'error',
2217
- sqlAliasedBehavior: 'alias',
2218
- replaceOriginalName: true,
2219
- }));
2220
1561
  }
2221
- as(query) {
2222
- return new Proxy(new PgMaterializedView({
2223
- pgConfig: undefined,
2224
- config: {
2225
- name: this.name,
2226
- schema: this.schema,
2227
- selectedFields: this.columns,
2228
- query: query.inlineParams(),
2229
- },
2230
- }), new SelectionProxyHandler({
2231
- alias: this.name,
2232
- sqlBehavior: 'error',
2233
- sqlAliasedBehavior: 'alias',
2234
- replaceOriginalName: true,
2235
- }));
1562
+ sqlToQuery(sql) {
1563
+ return sql.toQuery({
1564
+ escapeName: this.escapeName,
1565
+ escapeParam: this.escapeParam,
1566
+ escapeString: this.escapeString,
1567
+ prepareTyping: this.prepareTyping,
1568
+ });
2236
1569
  }
2237
- }
2238
- class PgViewBase extends View {
2239
- static [entityKind] = 'PgViewBase';
2240
- }
2241
- const PgViewConfig = Symbol.for('drizzle:PgViewConfig');
2242
- class PgView extends PgViewBase {
2243
- static [entityKind] = 'PgView';
2244
- [PgViewConfig];
2245
- constructor({ pgConfig, config }) {
2246
- super(config);
2247
- if (pgConfig) {
2248
- this[PgViewConfig] = {
2249
- with: pgConfig.with,
2250
- };
1570
+ // buildRelationalQueryWithPK({
1571
+ // fullSchema,
1572
+ // schema,
1573
+ // tableNamesMap,
1574
+ // table,
1575
+ // tableConfig,
1576
+ // queryConfig: config,
1577
+ // tableAlias,
1578
+ // isRoot = false,
1579
+ // joinOn,
1580
+ // }: {
1581
+ // fullSchema: Record<string, unknown>;
1582
+ // schema: TablesRelationalConfig;
1583
+ // tableNamesMap: Record<string, string>;
1584
+ // table: PgTable;
1585
+ // tableConfig: TableRelationalConfig;
1586
+ // queryConfig: true | DBQueryConfig<'many', true>;
1587
+ // tableAlias: string;
1588
+ // isRoot?: boolean;
1589
+ // joinOn?: SQL;
1590
+ // }): BuildRelationalQueryResult<PgTable, PgColumn> {
1591
+ // // For { "<relation>": true }, return a table with selection of all columns
1592
+ // if (config === true) {
1593
+ // const selectionEntries = Object.entries(tableConfig.columns);
1594
+ // const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
1595
+ // [key, value],
1596
+ // ) => ({
1597
+ // dbKey: value.name,
1598
+ // tsKey: key,
1599
+ // field: value as PgColumn,
1600
+ // relationTableTsKey: undefined,
1601
+ // isJson: false,
1602
+ // selection: [],
1603
+ // }));
1604
+ // return {
1605
+ // tableTsKey: tableConfig.tsName,
1606
+ // sql: table,
1607
+ // selection,
1608
+ // };
1609
+ // }
1610
+ // // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
1611
+ // // let selectionForBuild = selection;
1612
+ // const aliasedColumns = Object.fromEntries(
1613
+ // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
1614
+ // );
1615
+ // const aliasedRelations = Object.fromEntries(
1616
+ // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
1617
+ // );
1618
+ // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
1619
+ // let where, hasUserDefinedWhere;
1620
+ // if (config.where) {
1621
+ // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
1622
+ // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
1623
+ // hasUserDefinedWhere = !!where;
1624
+ // }
1625
+ // where = and(joinOn, where);
1626
+ // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
1627
+ // let joins: Join[] = [];
1628
+ // let selectedColumns: string[] = [];
1629
+ // // Figure out which columns to select
1630
+ // if (config.columns) {
1631
+ // let isIncludeMode = false;
1632
+ // for (const [field, value] of Object.entries(config.columns)) {
1633
+ // if (value === undefined) {
1634
+ // continue;
1635
+ // }
1636
+ // if (field in tableConfig.columns) {
1637
+ // if (!isIncludeMode && value === true) {
1638
+ // isIncludeMode = true;
1639
+ // }
1640
+ // selectedColumns.push(field);
1641
+ // }
1642
+ // }
1643
+ // if (selectedColumns.length > 0) {
1644
+ // selectedColumns = isIncludeMode
1645
+ // ? selectedColumns.filter((c) => config.columns?.[c] === true)
1646
+ // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1647
+ // }
1648
+ // } else {
1649
+ // // Select all columns if selection is not specified
1650
+ // selectedColumns = Object.keys(tableConfig.columns);
1651
+ // }
1652
+ // // for (const field of selectedColumns) {
1653
+ // // const column = tableConfig.columns[field]! as PgColumn;
1654
+ // // fieldsSelection.push({ tsKey: field, value: column });
1655
+ // // }
1656
+ // let initiallySelectedRelations: {
1657
+ // tsKey: string;
1658
+ // queryConfig: true | DBQueryConfig<'many', false>;
1659
+ // relation: Relation;
1660
+ // }[] = [];
1661
+ // // let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
1662
+ // // Figure out which relations to select
1663
+ // if (config.with) {
1664
+ // initiallySelectedRelations = Object.entries(config.with)
1665
+ // .filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
1666
+ // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
1667
+ // }
1668
+ // const manyRelations = initiallySelectedRelations.filter((r) =>
1669
+ // is(r.relation, Many)
1670
+ // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
1671
+ // );
1672
+ // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
1673
+ // const isInnermostQuery = manyRelations.length < 2;
1674
+ // const selectedExtras: {
1675
+ // tsKey: string;
1676
+ // value: SQL.Aliased;
1677
+ // }[] = [];
1678
+ // // Figure out which extras to select
1679
+ // if (isInnermostQuery && config.extras) {
1680
+ // const extras = typeof config.extras === 'function'
1681
+ // ? config.extras(aliasedFields, { sql })
1682
+ // : config.extras;
1683
+ // for (const [tsKey, value] of Object.entries(extras)) {
1684
+ // selectedExtras.push({
1685
+ // tsKey,
1686
+ // value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
1687
+ // });
1688
+ // }
1689
+ // }
1690
+ // // Transform `fieldsSelection` into `selection`
1691
+ // // `fieldsSelection` shouldn't be used after this point
1692
+ // // for (const { tsKey, value, isExtra } of fieldsSelection) {
1693
+ // // selection.push({
1694
+ // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
1695
+ // // tsKey,
1696
+ // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
1697
+ // // relationTableTsKey: undefined,
1698
+ // // isJson: false,
1699
+ // // isExtra,
1700
+ // // selection: [],
1701
+ // // });
1702
+ // // }
1703
+ // let orderByOrig = typeof config.orderBy === 'function'
1704
+ // ? config.orderBy(aliasedFields, orderByOperators)
1705
+ // : config.orderBy ?? [];
1706
+ // if (!Array.isArray(orderByOrig)) {
1707
+ // orderByOrig = [orderByOrig];
1708
+ // }
1709
+ // const orderBy = orderByOrig.map((orderByValue) => {
1710
+ // if (is(orderByValue, Column)) {
1711
+ // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
1712
+ // }
1713
+ // return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1714
+ // });
1715
+ // const limit = isInnermostQuery ? config.limit : undefined;
1716
+ // const offset = isInnermostQuery ? config.offset : undefined;
1717
+ // // For non-root queries without additional config except columns, return a table with selection
1718
+ // if (
1719
+ // !isRoot
1720
+ // && initiallySelectedRelations.length === 0
1721
+ // && selectedExtras.length === 0
1722
+ // && !where
1723
+ // && orderBy.length === 0
1724
+ // && limit === undefined
1725
+ // && offset === undefined
1726
+ // ) {
1727
+ // return {
1728
+ // tableTsKey: tableConfig.tsName,
1729
+ // sql: table,
1730
+ // selection: selectedColumns.map((key) => ({
1731
+ // dbKey: tableConfig.columns[key]!.name,
1732
+ // tsKey: key,
1733
+ // field: tableConfig.columns[key] as PgColumn,
1734
+ // relationTableTsKey: undefined,
1735
+ // isJson: false,
1736
+ // selection: [],
1737
+ // })),
1738
+ // };
1739
+ // }
1740
+ // const selectedRelationsWithoutPK:
1741
+ // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
1742
+ // for (
1743
+ // const {
1744
+ // tsKey: selectedRelationTsKey,
1745
+ // queryConfig: selectedRelationConfigValue,
1746
+ // relation,
1747
+ // } of initiallySelectedRelations
1748
+ // ) {
1749
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1750
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1751
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
1752
+ // const relationTable = schema[relationTableTsName]!;
1753
+ // if (relationTable.primaryKey.length > 0) {
1754
+ // continue;
1755
+ // }
1756
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1757
+ // const joinOn = and(
1758
+ // ...normalizedRelation.fields.map((field, i) =>
1759
+ // eq(
1760
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1761
+ // aliasedTableColumn(field, tableAlias),
1762
+ // )
1763
+ // ),
1764
+ // );
1765
+ // const builtRelation = this.buildRelationalQueryWithoutPK({
1766
+ // fullSchema,
1767
+ // schema,
1768
+ // tableNamesMap,
1769
+ // table: fullSchema[relationTableTsName] as PgTable,
1770
+ // tableConfig: schema[relationTableTsName]!,
1771
+ // queryConfig: selectedRelationConfigValue,
1772
+ // tableAlias: relationTableAlias,
1773
+ // joinOn,
1774
+ // nestedQueryRelation: relation,
1775
+ // });
1776
+ // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
1777
+ // joins.push({
1778
+ // on: sql`true`,
1779
+ // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
1780
+ // alias: relationTableAlias,
1781
+ // joinType: 'left',
1782
+ // lateral: true,
1783
+ // });
1784
+ // selectedRelations.push({
1785
+ // dbKey: selectedRelationTsKey,
1786
+ // tsKey: selectedRelationTsKey,
1787
+ // field,
1788
+ // relationTableTsKey: relationTableTsName,
1789
+ // isJson: true,
1790
+ // selection: builtRelation.selection,
1791
+ // });
1792
+ // }
1793
+ // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
1794
+ // is(r.relation, One)
1795
+ // );
1796
+ // // Process all One relations with PKs, because they can all be joined on the same level
1797
+ // for (
1798
+ // const {
1799
+ // tsKey: selectedRelationTsKey,
1800
+ // queryConfig: selectedRelationConfigValue,
1801
+ // relation,
1802
+ // } of oneRelations
1803
+ // ) {
1804
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1805
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1806
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
1807
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1808
+ // const relationTable = schema[relationTableTsName]!;
1809
+ // if (relationTable.primaryKey.length === 0) {
1810
+ // continue;
1811
+ // }
1812
+ // const joinOn = and(
1813
+ // ...normalizedRelation.fields.map((field, i) =>
1814
+ // eq(
1815
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1816
+ // aliasedTableColumn(field, tableAlias),
1817
+ // )
1818
+ // ),
1819
+ // );
1820
+ // const builtRelation = this.buildRelationalQueryWithPK({
1821
+ // fullSchema,
1822
+ // schema,
1823
+ // tableNamesMap,
1824
+ // table: fullSchema[relationTableTsName] as PgTable,
1825
+ // tableConfig: schema[relationTableTsName]!,
1826
+ // queryConfig: selectedRelationConfigValue,
1827
+ // tableAlias: relationTableAlias,
1828
+ // joinOn,
1829
+ // });
1830
+ // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
1831
+ // sql.join(
1832
+ // builtRelation.selection.map(({ field }) =>
1833
+ // is(field, SQL.Aliased)
1834
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
1835
+ // : is(field, Column)
1836
+ // ? aliasedTableColumn(field, relationTableAlias)
1837
+ // : field
1838
+ // ),
1839
+ // sql`, `,
1840
+ // )
1841
+ // }) end`.as(selectedRelationTsKey);
1842
+ // const isLateralJoin = is(builtRelation.sql, SQL);
1843
+ // joins.push({
1844
+ // on: isLateralJoin ? sql`true` : joinOn,
1845
+ // table: is(builtRelation.sql, SQL)
1846
+ // ? new Subquery(builtRelation.sql, {}, relationTableAlias)
1847
+ // : aliasedTable(builtRelation.sql, relationTableAlias),
1848
+ // alias: relationTableAlias,
1849
+ // joinType: 'left',
1850
+ // lateral: is(builtRelation.sql, SQL),
1851
+ // });
1852
+ // selectedRelations.push({
1853
+ // dbKey: selectedRelationTsKey,
1854
+ // tsKey: selectedRelationTsKey,
1855
+ // field,
1856
+ // relationTableTsKey: relationTableTsName,
1857
+ // isJson: true,
1858
+ // selection: builtRelation.selection,
1859
+ // });
1860
+ // }
1861
+ // let distinct: PgSelectConfig['distinct'];
1862
+ // let tableFrom: PgTable | Subquery = table;
1863
+ // // Process first Many relation - each one requires a nested subquery
1864
+ // const manyRelation = manyRelations[0];
1865
+ // if (manyRelation) {
1866
+ // const {
1867
+ // tsKey: selectedRelationTsKey,
1868
+ // queryConfig: selectedRelationQueryConfig,
1869
+ // relation,
1870
+ // } = manyRelation;
1871
+ // distinct = {
1872
+ // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
1873
+ // };
1874
+ // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1875
+ // const relationTableName = relation.referencedTable[Table.Symbol.Name];
1876
+ // const relationTableTsName = tableNamesMap[relationTableName]!;
1877
+ // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1878
+ // const joinOn = and(
1879
+ // ...normalizedRelation.fields.map((field, i) =>
1880
+ // eq(
1881
+ // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
1882
+ // aliasedTableColumn(field, tableAlias),
1883
+ // )
1884
+ // ),
1885
+ // );
1886
+ // const builtRelationJoin = this.buildRelationalQueryWithPK({
1887
+ // fullSchema,
1888
+ // schema,
1889
+ // tableNamesMap,
1890
+ // table: fullSchema[relationTableTsName] as PgTable,
1891
+ // tableConfig: schema[relationTableTsName]!,
1892
+ // queryConfig: selectedRelationQueryConfig,
1893
+ // tableAlias: relationTableAlias,
1894
+ // joinOn,
1895
+ // });
1896
+ // const builtRelationSelectionField = sql`case when ${
1897
+ // sql.identifier(relationTableAlias)
1898
+ // } is null then '[]' else json_agg(json_build_array(${
1899
+ // sql.join(
1900
+ // builtRelationJoin.selection.map(({ field }) =>
1901
+ // is(field, SQL.Aliased)
1902
+ // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
1903
+ // : is(field, Column)
1904
+ // ? aliasedTableColumn(field, relationTableAlias)
1905
+ // : field
1906
+ // ),
1907
+ // sql`, `,
1908
+ // )
1909
+ // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
1910
+ // const isLateralJoin = is(builtRelationJoin.sql, SQL);
1911
+ // joins.push({
1912
+ // on: isLateralJoin ? sql`true` : joinOn,
1913
+ // table: isLateralJoin
1914
+ // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
1915
+ // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
1916
+ // alias: relationTableAlias,
1917
+ // joinType: 'left',
1918
+ // lateral: isLateralJoin,
1919
+ // });
1920
+ // // Build the "from" subquery with the remaining Many relations
1921
+ // const builtTableFrom = this.buildRelationalQueryWithPK({
1922
+ // fullSchema,
1923
+ // schema,
1924
+ // tableNamesMap,
1925
+ // table,
1926
+ // tableConfig,
1927
+ // queryConfig: {
1928
+ // ...config,
1929
+ // where: undefined,
1930
+ // orderBy: undefined,
1931
+ // limit: undefined,
1932
+ // offset: undefined,
1933
+ // with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
1934
+ // (result, { tsKey, queryConfig: configValue }) => {
1935
+ // result[tsKey] = configValue;
1936
+ // return result;
1937
+ // },
1938
+ // {},
1939
+ // ),
1940
+ // },
1941
+ // tableAlias,
1942
+ // });
1943
+ // selectedRelations.push({
1944
+ // dbKey: selectedRelationTsKey,
1945
+ // tsKey: selectedRelationTsKey,
1946
+ // field: builtRelationSelectionField,
1947
+ // relationTableTsKey: relationTableTsName,
1948
+ // isJson: true,
1949
+ // selection: builtRelationJoin.selection,
1950
+ // });
1951
+ // // selection = builtTableFrom.selection.map((item) =>
1952
+ // // is(item.field, SQL.Aliased)
1953
+ // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
1954
+ // // : item
1955
+ // // );
1956
+ // // selectionForBuild = [{
1957
+ // // dbKey: '*',
1958
+ // // tsKey: '*',
1959
+ // // field: sql`${sql.identifier(tableAlias)}.*`,
1960
+ // // selection: [],
1961
+ // // isJson: false,
1962
+ // // relationTableTsKey: undefined,
1963
+ // // }];
1964
+ // // const newSelectionItem: (typeof selection)[number] = {
1965
+ // // dbKey: selectedRelationTsKey,
1966
+ // // tsKey: selectedRelationTsKey,
1967
+ // // field,
1968
+ // // relationTableTsKey: relationTableTsName,
1969
+ // // isJson: true,
1970
+ // // selection: builtRelationJoin.selection,
1971
+ // // };
1972
+ // // selection.push(newSelectionItem);
1973
+ // // selectionForBuild.push(newSelectionItem);
1974
+ // tableFrom = is(builtTableFrom.sql, PgTable)
1975
+ // ? builtTableFrom.sql
1976
+ // : new Subquery(builtTableFrom.sql, {}, tableAlias);
1977
+ // }
1978
+ // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
1979
+ // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
1980
+ // }
1981
+ // let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
1982
+ // function prepareSelectedColumns() {
1983
+ // return selectedColumns.map((key) => ({
1984
+ // dbKey: tableConfig.columns[key]!.name,
1985
+ // tsKey: key,
1986
+ // field: tableConfig.columns[key] as PgColumn,
1987
+ // relationTableTsKey: undefined,
1988
+ // isJson: false,
1989
+ // selection: [],
1990
+ // }));
1991
+ // }
1992
+ // function prepareSelectedExtras() {
1993
+ // return selectedExtras.map((item) => ({
1994
+ // dbKey: item.value.fieldAlias,
1995
+ // tsKey: item.tsKey,
1996
+ // field: item.value,
1997
+ // relationTableTsKey: undefined,
1998
+ // isJson: false,
1999
+ // selection: [],
2000
+ // }));
2001
+ // }
2002
+ // if (isRoot) {
2003
+ // selection = [
2004
+ // ...prepareSelectedColumns(),
2005
+ // ...prepareSelectedExtras(),
2006
+ // ];
2007
+ // }
2008
+ // if (hasUserDefinedWhere || orderBy.length > 0) {
2009
+ // tableFrom = new Subquery(
2010
+ // this.buildSelectQuery({
2011
+ // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
2012
+ // fields: {},
2013
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
2014
+ // path: [],
2015
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
2016
+ // })),
2017
+ // joins,
2018
+ // distinct,
2019
+ // }),
2020
+ // {},
2021
+ // tableAlias,
2022
+ // );
2023
+ // selectionForBuild = selection.map((item) =>
2024
+ // is(item.field, SQL.Aliased)
2025
+ // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
2026
+ // : item
2027
+ // );
2028
+ // joins = [];
2029
+ // distinct = undefined;
2030
+ // }
2031
+ // const result = this.buildSelectQuery({
2032
+ // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
2033
+ // fields: {},
2034
+ // fieldsFlat: selectionForBuild.map(({ field }) => ({
2035
+ // path: [],
2036
+ // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
2037
+ // })),
2038
+ // where,
2039
+ // limit,
2040
+ // offset,
2041
+ // joins,
2042
+ // orderBy,
2043
+ // distinct,
2044
+ // });
2045
+ // return {
2046
+ // tableTsKey: tableConfig.tsName,
2047
+ // sql: result,
2048
+ // selection,
2049
+ // };
2050
+ // }
2051
+ buildRelationalQueryWithoutPK({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn, }) {
2052
+ let selection = [];
2053
+ let limit, offset, orderBy = [], where;
2054
+ const joins = [];
2055
+ if (config === true) {
2056
+ const selectionEntries = Object.entries(tableConfig.columns);
2057
+ selection = selectionEntries.map(([key, value]) => ({
2058
+ dbKey: value.name,
2059
+ tsKey: key,
2060
+ field: aliasedTableColumn(value, tableAlias),
2061
+ relationTableTsKey: undefined,
2062
+ isJson: false,
2063
+ selection: [],
2064
+ }));
2251
2065
  }
2252
- }
2253
- }
2254
- const PgMaterializedViewConfig = Symbol.for('drizzle:PgMaterializedViewConfig');
2255
- class PgMaterializedView extends PgViewBase {
2256
- static [entityKind] = 'PgMaterializedView';
2257
- [PgMaterializedViewConfig];
2258
- constructor({ pgConfig, config }) {
2259
- super(config);
2260
- this[PgMaterializedViewConfig] = {
2261
- with: pgConfig?.with,
2262
- using: pgConfig?.using,
2263
- tablespace: pgConfig?.tablespace,
2264
- withNoData: pgConfig?.withNoData,
2265
- };
2266
- }
2267
- }
2268
- /** @internal */
2269
- function pgViewWithSchema(name, selection, schema) {
2270
- if (selection) {
2271
- return new ManualViewBuilder(name, selection, schema);
2272
- }
2273
- return new ViewBuilder(name, schema);
2274
- }
2275
- /** @internal */
2276
- function pgMaterializedViewWithSchema(name, selection, schema) {
2277
- if (selection) {
2278
- return new ManualMaterializedViewBuilder(name, selection, schema);
2279
- }
2280
- return new MaterializedViewBuilder(name, schema);
2281
- }
2282
- function pgView(name, columns) {
2283
- return pgViewWithSchema(name, columns, undefined);
2284
- }
2285
- function pgMaterializedView(name, columns) {
2286
- return pgMaterializedViewWithSchema(name, columns, undefined);
2287
- }
2288
-
2289
- function getTableConfig(table) {
2290
- const columns = Object.values(table[Table.Symbol.Columns]);
2291
- const indexes = [];
2292
- const checks = [];
2293
- const primaryKeys = [];
2294
- const foreignKeys = Object.values(table[PgTable.Symbol.InlineForeignKeys]);
2295
- const uniqueConstraints = [];
2296
- const name = table[Table.Symbol.Name];
2297
- const schema = table[Table.Symbol.Schema];
2298
- const extraConfigBuilder = table[PgTable.Symbol.ExtraConfigBuilder];
2299
- if (extraConfigBuilder !== undefined) {
2300
- const extraConfig = extraConfigBuilder(table[Table.Symbol.Columns]);
2301
- for (const builder of Object.values(extraConfig)) {
2302
- if (is(builder, IndexBuilder)) {
2303
- indexes.push(builder.build(table));
2066
+ else {
2067
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
2068
+ if (config.where) {
2069
+ const whereSql = typeof config.where === 'function'
2070
+ ? config.where(aliasedColumns, getOperators())
2071
+ : config.where;
2072
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
2304
2073
  }
2305
- else if (is(builder, CheckBuilder)) {
2306
- checks.push(builder.build(table));
2074
+ const fieldsSelection = [];
2075
+ let selectedColumns = [];
2076
+ // Figure out which columns to select
2077
+ if (config.columns) {
2078
+ let isIncludeMode = false;
2079
+ for (const [field, value] of Object.entries(config.columns)) {
2080
+ if (value === undefined) {
2081
+ continue;
2082
+ }
2083
+ if (field in tableConfig.columns) {
2084
+ if (!isIncludeMode && value === true) {
2085
+ isIncludeMode = true;
2086
+ }
2087
+ selectedColumns.push(field);
2088
+ }
2089
+ }
2090
+ if (selectedColumns.length > 0) {
2091
+ selectedColumns = isIncludeMode
2092
+ ? selectedColumns.filter((c) => config.columns?.[c] === true)
2093
+ : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
2094
+ }
2307
2095
  }
2308
- else if (is(builder, UniqueConstraintBuilder)) {
2309
- uniqueConstraints.push(builder.build(table));
2096
+ else {
2097
+ // Select all columns if selection is not specified
2098
+ selectedColumns = Object.keys(tableConfig.columns);
2310
2099
  }
2311
- else if (is(builder, PrimaryKeyBuilder)) {
2312
- primaryKeys.push(builder.build(table));
2100
+ for (const field of selectedColumns) {
2101
+ const column = tableConfig.columns[field];
2102
+ fieldsSelection.push({ tsKey: field, value: column });
2313
2103
  }
2314
- else if (is(builder, ForeignKeyBuilder)) {
2315
- foreignKeys.push(builder.build(table));
2104
+ let selectedRelations = [];
2105
+ // Figure out which relations to select
2106
+ if (config.with) {
2107
+ selectedRelations = Object.entries(config.with)
2108
+ .filter((entry) => !!entry[1])
2109
+ .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
2110
+ }
2111
+ let extras;
2112
+ // Figure out which extras to select
2113
+ if (config.extras) {
2114
+ extras = typeof config.extras === 'function'
2115
+ ? config.extras(aliasedColumns, { sql })
2116
+ : config.extras;
2117
+ for (const [tsKey, value] of Object.entries(extras)) {
2118
+ fieldsSelection.push({
2119
+ tsKey,
2120
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
2121
+ });
2122
+ }
2123
+ }
2124
+ // Transform `fieldsSelection` into `selection`
2125
+ // `fieldsSelection` shouldn't be used after this point
2126
+ for (const { tsKey, value } of fieldsSelection) {
2127
+ selection.push({
2128
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
2129
+ tsKey,
2130
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
2131
+ relationTableTsKey: undefined,
2132
+ isJson: false,
2133
+ selection: [],
2134
+ });
2135
+ }
2136
+ let orderByOrig = typeof config.orderBy === 'function'
2137
+ ? config.orderBy(aliasedColumns, getOrderByOperators())
2138
+ : config.orderBy ?? [];
2139
+ if (!Array.isArray(orderByOrig)) {
2140
+ orderByOrig = [orderByOrig];
2141
+ }
2142
+ orderBy = orderByOrig.map((orderByValue) => {
2143
+ if (is(orderByValue, Column)) {
2144
+ return aliasedTableColumn(orderByValue, tableAlias);
2145
+ }
2146
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
2147
+ });
2148
+ limit = config.limit;
2149
+ offset = config.offset;
2150
+ // Process all relations
2151
+ for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation, } of selectedRelations) {
2152
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
2153
+ const relationTableName = relation.referencedTable[Table.Symbol.Name];
2154
+ const relationTableTsName = tableNamesMap[relationTableName];
2155
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
2156
+ const joinOn = and(...normalizedRelation.fields.map((field, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field, tableAlias))));
2157
+ const builtRelation = this.buildRelationalQueryWithoutPK({
2158
+ fullSchema,
2159
+ schema,
2160
+ tableNamesMap,
2161
+ table: fullSchema[relationTableTsName],
2162
+ tableConfig: schema[relationTableTsName],
2163
+ queryConfig: is(relation, One)
2164
+ ? (selectedRelationConfigValue === true
2165
+ ? { limit: 1 }
2166
+ : { ...selectedRelationConfigValue, limit: 1 })
2167
+ : selectedRelationConfigValue,
2168
+ tableAlias: relationTableAlias,
2169
+ joinOn,
2170
+ nestedQueryRelation: relation,
2171
+ });
2172
+ const field = sql `${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
2173
+ joins.push({
2174
+ on: sql `true`,
2175
+ table: new Subquery(builtRelation.sql, {}, relationTableAlias),
2176
+ alias: relationTableAlias,
2177
+ joinType: 'left',
2178
+ lateral: true,
2179
+ });
2180
+ selection.push({
2181
+ dbKey: selectedRelationTsKey,
2182
+ tsKey: selectedRelationTsKey,
2183
+ field,
2184
+ relationTableTsKey: relationTableTsName,
2185
+ isJson: true,
2186
+ selection: builtRelation.selection,
2187
+ });
2188
+ }
2189
+ }
2190
+ if (selection.length === 0) {
2191
+ throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
2192
+ }
2193
+ let result;
2194
+ where = and(joinOn, where);
2195
+ if (nestedQueryRelation) {
2196
+ let field = sql `json_build_array(${sql.join(selection.map(({ field, tsKey, isJson }) => isJson
2197
+ ? sql `${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier('data')}`
2198
+ : is(field, SQL.Aliased)
2199
+ ? field.sql
2200
+ : field), sql `, `)})`;
2201
+ if (is(nestedQueryRelation, Many)) {
2202
+ field = sql `coalesce(json_agg(${field}${orderBy.length > 0 ? sql ` order by ${sql.join(orderBy, sql `, `)}` : undefined}), '[]'::json)`;
2203
+ // orderBy = [];
2204
+ }
2205
+ const nestedSelection = [{
2206
+ dbKey: 'data',
2207
+ tsKey: 'data',
2208
+ field: field.as('data'),
2209
+ isJson: true,
2210
+ relationTableTsKey: tableConfig.tsName,
2211
+ selection,
2212
+ }];
2213
+ const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
2214
+ if (needsSubquery) {
2215
+ result = this.buildSelectQuery({
2216
+ table: aliasedTable(table, tableAlias),
2217
+ fields: {},
2218
+ fieldsFlat: [{
2219
+ path: [],
2220
+ field: sql.raw('*'),
2221
+ }],
2222
+ where,
2223
+ limit,
2224
+ offset,
2225
+ orderBy,
2226
+ });
2227
+ where = undefined;
2228
+ limit = undefined;
2229
+ offset = undefined;
2230
+ orderBy = [];
2316
2231
  }
2232
+ else {
2233
+ result = aliasedTable(table, tableAlias);
2234
+ }
2235
+ result = this.buildSelectQuery({
2236
+ table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
2237
+ fields: {},
2238
+ fieldsFlat: nestedSelection.map(({ field }) => ({
2239
+ path: [],
2240
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
2241
+ })),
2242
+ joins,
2243
+ where,
2244
+ limit,
2245
+ offset,
2246
+ orderBy,
2247
+ });
2317
2248
  }
2249
+ else {
2250
+ result = this.buildSelectQuery({
2251
+ table: aliasedTable(table, tableAlias),
2252
+ fields: {},
2253
+ fieldsFlat: selection.map(({ field }) => ({
2254
+ path: [],
2255
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
2256
+ })),
2257
+ joins,
2258
+ where,
2259
+ limit,
2260
+ offset,
2261
+ orderBy,
2262
+ });
2263
+ }
2264
+ return {
2265
+ tableTsKey: tableConfig.tsName,
2266
+ sql: result,
2267
+ selection,
2268
+ };
2318
2269
  }
2319
- return {
2320
- columns,
2321
- indexes,
2322
- foreignKeys,
2323
- checks,
2324
- primaryKeys,
2325
- uniqueConstraints,
2326
- name,
2327
- schema,
2328
- };
2329
- }
2330
- function getViewConfig(view) {
2331
- return {
2332
- ...view[ViewBaseConfig],
2333
- ...view[PgViewConfig],
2334
- };
2335
2270
  }
2336
- function getMaterializedViewConfig(view) {
2337
- return {
2338
- ...view[ViewBaseConfig],
2339
- ...view[PgMaterializedViewConfig],
2340
- };
2271
+
2272
+ class TypedQueryBuilder {
2273
+ static [entityKind] = 'TypedQueryBuilder';
2274
+ /** @internal */
2275
+ getSelectedFields() {
2276
+ return this._.selectedFields;
2277
+ }
2341
2278
  }
2342
- function parsePgArrayValue(arrayString, startFrom, inQuotes) {
2343
- for (let i = startFrom; i < arrayString.length; i++) {
2344
- const char = arrayString[i];
2345
- if (char === '\\') {
2346
- i++;
2347
- continue;
2348
- }
2349
- if (char === '"') {
2350
- return [arrayString.slice(startFrom, i).replace(/\\/g, ''), i + 1];
2351
- }
2352
- if (inQuotes) {
2353
- continue;
2354
- }
2355
- if (char === ',' || char === '}') {
2356
- return [arrayString.slice(startFrom, i).replace(/\\/g, ''), i];
2279
+
2280
+ class PgSelectBuilder {
2281
+ static [entityKind] = 'PgSelectBuilder';
2282
+ fields;
2283
+ session;
2284
+ dialect;
2285
+ withList = [];
2286
+ distinct;
2287
+ constructor(config) {
2288
+ this.fields = config.fields;
2289
+ this.session = config.session;
2290
+ this.dialect = config.dialect;
2291
+ if (config.withList) {
2292
+ this.withList = config.withList;
2357
2293
  }
2294
+ this.distinct = config.distinct;
2358
2295
  }
2359
- return [arrayString.slice(startFrom).replace(/\\/g, ''), arrayString.length];
2360
- }
2361
- function parsePgNestedArray(arrayString, startFrom = 0) {
2362
- const result = [];
2363
- let i = startFrom;
2364
- let lastCharIsComma = false;
2365
- while (i < arrayString.length) {
2366
- const char = arrayString[i];
2367
- if (char === ',') {
2368
- if (lastCharIsComma || i === startFrom) {
2369
- result.push('');
2370
- }
2371
- lastCharIsComma = true;
2372
- i++;
2373
- continue;
2296
+ /**
2297
+ * Specify the table, subquery, or other target that you're
2298
+ * building a select query against.
2299
+ *
2300
+ * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM|Postgres from documentation}
2301
+ */
2302
+ from(source) {
2303
+ const isPartialSelect = !!this.fields;
2304
+ let fields;
2305
+ if (this.fields) {
2306
+ fields = this.fields;
2374
2307
  }
2375
- lastCharIsComma = false;
2376
- if (char === '\\') {
2377
- i += 2;
2378
- continue;
2308
+ else if (is(source, Subquery)) {
2309
+ // This is required to use the proxy handler to get the correct field values from the subquery
2310
+ fields = Object.fromEntries(Object.keys(source[SubqueryConfig].selection).map((key) => [key, source[key]]));
2379
2311
  }
2380
- if (char === '"') {
2381
- const [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);
2382
- result.push(value);
2383
- i = startFrom;
2384
- continue;
2312
+ else if (is(source, PgViewBase)) {
2313
+ fields = source[ViewBaseConfig].selectedFields;
2385
2314
  }
2386
- if (char === '}') {
2387
- return [result, i + 1];
2315
+ else if (is(source, SQL)) {
2316
+ fields = {};
2388
2317
  }
2389
- if (char === '{') {
2390
- const [value, startFrom] = parsePgNestedArray(arrayString, i + 1);
2391
- result.push(value);
2392
- i = startFrom;
2393
- continue;
2318
+ else {
2319
+ fields = getTableColumns(source);
2394
2320
  }
2395
- const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
2396
- result.push(value);
2397
- i = newStartFrom;
2321
+ return new PgSelect({
2322
+ table: source,
2323
+ fields,
2324
+ isPartialSelect,
2325
+ session: this.session,
2326
+ dialect: this.dialect,
2327
+ withList: this.withList,
2328
+ distinct: this.distinct,
2329
+ });
2398
2330
  }
2399
- return [result, i];
2400
- }
2401
- function parsePgArray(arrayString) {
2402
- const [result] = parsePgNestedArray(arrayString, 1);
2403
- return result;
2404
- }
2405
- function makePgArray(array) {
2406
- return `{${array.map((item) => {
2407
- if (Array.isArray(item)) {
2408
- return makePgArray(item);
2409
- }
2410
- if (typeof item === 'string' && item.includes(',')) {
2411
- return `"${item.replace(/"/g, '\\"')}"`;
2412
- }
2413
- return `${item}`;
2414
- }).join(',')}}`;
2415
2331
  }
2416
-
2417
- // To understand how to use `ColumnBuilder` and `AnyColumnBuilder`, see `Column` and `AnyColumn` documentation.
2418
- class ColumnBuilder {
2419
- static [entityKind] = 'ColumnBuilder';
2332
+ class PgSelectQueryBuilder extends TypedQueryBuilder {
2333
+ static [entityKind] = 'PgSelectQueryBuilder';
2334
+ _;
2420
2335
  config;
2421
- constructor(name, dataType, columnType) {
2336
+ joinsNotNullableMap;
2337
+ tableName;
2338
+ isPartialSelect;
2339
+ session;
2340
+ dialect;
2341
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
2342
+ super();
2422
2343
  this.config = {
2423
- name,
2424
- notNull: false,
2425
- default: undefined,
2426
- hasDefault: false,
2427
- primaryKey: false,
2428
- isUnique: false,
2429
- uniqueName: undefined,
2430
- uniqueType: undefined,
2431
- dataType,
2432
- columnType,
2344
+ withList,
2345
+ table,
2346
+ fields: { ...fields },
2347
+ distinct,
2348
+ };
2349
+ this.isPartialSelect = isPartialSelect;
2350
+ this.session = session;
2351
+ this.dialect = dialect;
2352
+ this._ = {
2353
+ selectedFields: fields,
2433
2354
  };
2355
+ this.tableName = getTableLikeName(table);
2356
+ this.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};
2434
2357
  }
2435
- /**
2436
- * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
2437
- *
2438
- * @example
2439
- * ```ts
2440
- * const users = pgTable('users', {
2441
- * id: integer('id').$type<UserId>().primaryKey(),
2442
- * details: json('details').$type<UserDetails>().notNull(),
2443
- * });
2444
- * ```
2445
- */
2446
- $type() {
2447
- return this;
2358
+ createJoin(joinType) {
2359
+ return (table, on) => {
2360
+ const baseTableName = this.tableName;
2361
+ const tableName = getTableLikeName(table);
2362
+ if (typeof tableName === 'string' && this.config.joins?.some((join) => join.alias === tableName)) {
2363
+ throw new Error(`Alias "${tableName}" is already used in this query`);
2364
+ }
2365
+ if (!this.isPartialSelect) {
2366
+ // If this is the first join and this is not a partial select and we're not selecting from raw SQL, "move" the fields from the main table to the nested object
2367
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {
2368
+ this.config.fields = {
2369
+ [baseTableName]: this.config.fields,
2370
+ };
2371
+ }
2372
+ if (typeof tableName === 'string' && !is(table, SQL)) {
2373
+ const selection = is(table, Subquery)
2374
+ ? table[SubqueryConfig].selection
2375
+ : is(table, View)
2376
+ ? table[ViewBaseConfig].selectedFields
2377
+ : table[Table.Symbol.Columns];
2378
+ this.config.fields[tableName] = selection;
2379
+ }
2380
+ }
2381
+ if (typeof on === 'function') {
2382
+ on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
2383
+ }
2384
+ if (!this.config.joins) {
2385
+ this.config.joins = [];
2386
+ }
2387
+ this.config.joins.push({ on, table, joinType, alias: tableName });
2388
+ if (typeof tableName === 'string') {
2389
+ switch (joinType) {
2390
+ case 'left': {
2391
+ this.joinsNotNullableMap[tableName] = false;
2392
+ break;
2393
+ }
2394
+ case 'right': {
2395
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2396
+ this.joinsNotNullableMap[tableName] = true;
2397
+ break;
2398
+ }
2399
+ case 'inner': {
2400
+ this.joinsNotNullableMap[tableName] = true;
2401
+ break;
2402
+ }
2403
+ case 'full': {
2404
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2405
+ this.joinsNotNullableMap[tableName] = false;
2406
+ break;
2407
+ }
2408
+ }
2409
+ }
2410
+ return this;
2411
+ };
2448
2412
  }
2449
2413
  /**
2450
- * Adds a `not null` clause to the column definition.
2451
- *
2452
- * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
2414
+ * For each row of the table, include
2415
+ * values from a matching row of the joined
2416
+ * table, if there is a matching row. If not,
2417
+ * all of the columns of the joined table
2418
+ * will be set to null.
2453
2419
  */
2454
- notNull() {
2455
- this.config.notNull = true;
2456
- return this;
2457
- }
2420
+ leftJoin = this.createJoin('left');
2458
2421
  /**
2459
- * Adds a `default <value>` clause to the column definition.
2460
- *
2461
- * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
2462
- *
2463
- * If you need to set a dynamic default value, use {@link $defaultFn} instead.
2422
+ * Includes all of the rows of the joined table.
2423
+ * If there is no matching row in the main table,
2424
+ * all the columns of the main table will be
2425
+ * set to null.
2464
2426
  */
2465
- default(value) {
2466
- this.config.default = value;
2467
- this.config.hasDefault = true;
2468
- return this;
2469
- }
2427
+ rightJoin = this.createJoin('right');
2470
2428
  /**
2471
- * Adds a dynamic default value to the column.
2472
- * The function will be called when the row is inserted, and the returned value will be used as the column value.
2429
+ * This is the default type of join.
2473
2430
  *
2474
- * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
2431
+ * For each row of the table, the joined table
2432
+ * needs to have a matching row, or it will
2433
+ * be excluded from results.
2475
2434
  */
2476
- $defaultFn(fn) {
2477
- this.config.defaultFn = fn;
2478
- this.config.hasDefault = true;
2479
- return this;
2480
- }
2435
+ innerJoin = this.createJoin('inner');
2481
2436
  /**
2482
- * Alias for {@link $defaultFn}.
2437
+ * Rows from both the main & joined are included,
2438
+ * regardless of whether or not they have matching
2439
+ * rows in the other table.
2483
2440
  */
2484
- $default = this.$defaultFn;
2441
+ fullJoin = this.createJoin('full');
2485
2442
  /**
2486
- * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
2443
+ * Specify a condition to narrow the result set. Multiple
2444
+ * conditions can be combined with the `and` and `or`
2445
+ * functions.
2487
2446
  *
2488
- * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
2447
+ * ## Examples
2448
+ *
2449
+ * ```ts
2450
+ * // Find cars made in the year 2000
2451
+ * db.select().from(cars).where(eq(cars.year, 2000));
2452
+ * ```
2489
2453
  */
2490
- primaryKey() {
2491
- this.config.primaryKey = true;
2492
- this.config.notNull = true;
2454
+ where(where) {
2455
+ if (typeof where === 'function') {
2456
+ where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
2457
+ }
2458
+ this.config.where = where;
2493
2459
  return this;
2494
2460
  }
2495
- }
2496
-
2497
- class PgColumnBuilder extends ColumnBuilder {
2498
- foreignKeyConfigs = [];
2499
- static [entityKind] = 'PgColumnBuilder';
2500
- array(size) {
2501
- return new PgArrayBuilder(this.config.name, this, size);
2502
- }
2503
- references(ref, actions = {}) {
2504
- this.foreignKeyConfigs.push({ ref, actions });
2461
+ /**
2462
+ * Sets the HAVING clause of this query, which often
2463
+ * used with GROUP BY and filters rows after they've been
2464
+ * grouped together and combined.
2465
+ *
2466
+ * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-HAVING|Postgres having clause documentation}
2467
+ */
2468
+ having(having) {
2469
+ if (typeof having === 'function') {
2470
+ having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' })));
2471
+ }
2472
+ this.config.having = having;
2505
2473
  return this;
2506
2474
  }
2507
- unique(name, config) {
2508
- this.config.isUnique = true;
2509
- this.config.uniqueName = name;
2510
- this.config.uniqueType = config?.nulls;
2475
+ groupBy(...columns) {
2476
+ if (typeof columns[0] === 'function') {
2477
+ const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
2478
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
2479
+ }
2480
+ else {
2481
+ this.config.groupBy = columns;
2482
+ }
2511
2483
  return this;
2512
2484
  }
2513
- /** @internal */
2514
- buildForeignKeys(column, table) {
2515
- return this.foreignKeyConfigs.map(({ ref, actions }) => {
2516
- return iife((ref, actions) => {
2517
- const builder = new ForeignKeyBuilder(() => {
2518
- const foreignColumn = ref();
2519
- return { columns: [column], foreignColumns: [foreignColumn] };
2520
- });
2521
- if (actions.onUpdate) {
2522
- builder.onUpdate(actions.onUpdate);
2523
- }
2524
- if (actions.onDelete) {
2525
- builder.onDelete(actions.onDelete);
2526
- }
2527
- return builder.build(table);
2528
- }, ref, actions);
2529
- });
2530
- }
2531
- }
2532
- // To understand how to use `PgColumn` and `PgColumn`, see `Column` and `AnyColumn` documentation.
2533
- class PgColumn extends Column {
2534
- table;
2535
- static [entityKind] = 'PgColumn';
2536
- constructor(table, config) {
2537
- if (!config.uniqueName) {
2538
- config.uniqueName = uniqueKeyName(table, [config.name]);
2485
+ orderBy(...columns) {
2486
+ if (typeof columns[0] === 'function') {
2487
+ const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' })));
2488
+ this.config.orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
2539
2489
  }
2540
- super(table, config);
2541
- this.table = table;
2542
- }
2543
- }
2544
-
2545
- class PgArrayBuilder extends PgColumnBuilder {
2546
- static [entityKind] = 'PgArrayBuilder';
2547
- constructor(name, baseBuilder, size) {
2548
- super(name, 'array', 'PgArray');
2549
- this.config.baseBuilder = baseBuilder;
2550
- this.config.size = size;
2551
- }
2552
- /** @internal */
2553
- build(table) {
2554
- const baseColumn = this.config.baseBuilder.build(table);
2555
- return new PgArray(table, this.config, baseColumn);
2556
- }
2557
- }
2558
- class PgArray extends PgColumn {
2559
- baseColumn;
2560
- range;
2561
- size;
2562
- static [entityKind] = 'PgArray';
2563
- constructor(table, config, baseColumn, range) {
2564
- super(table, config);
2565
- this.baseColumn = baseColumn;
2566
- this.range = range;
2567
- this.size = config.size;
2568
- }
2569
- getSQLType() {
2570
- return `${this.baseColumn.getSQLType()}[${typeof this.size === 'number' ? this.size : ''}]`;
2571
- }
2572
- mapFromDriverValue(value) {
2573
- if (typeof value === 'string') {
2574
- // Thank you node-postgres for not parsing enum arrays
2575
- value = parsePgArray(value);
2490
+ else {
2491
+ this.config.orderBy = columns;
2576
2492
  }
2577
- return value.map((v) => this.baseColumn.mapFromDriverValue(v));
2578
- }
2579
- mapToDriverValue(value, isNestedArray = false) {
2580
- const a = value.map((v) => v === null
2581
- ? null
2582
- : is(this.baseColumn, PgArray)
2583
- ? this.baseColumn.mapToDriverValue(v, true)
2584
- : this.baseColumn.mapToDriverValue(v));
2585
- if (isNestedArray)
2586
- return a;
2587
- return makePgArray(a);
2588
- }
2589
- }
2590
-
2591
- class PgDateColumnBaseBuilder extends PgColumnBuilder {
2592
- static [entityKind] = 'PgDateColumnBaseBuilder';
2593
- defaultNow() {
2594
- return this.default(sql `now()`);
2595
- }
2596
- }
2597
-
2598
- class PgDateBuilder extends PgDateColumnBaseBuilder {
2599
- static [entityKind] = 'PgDateBuilder';
2600
- constructor(name) {
2601
- super(name, 'date', 'PgDate');
2602
- }
2603
- /** @internal */
2604
- build(table) {
2605
- return new PgDate(table, this.config);
2606
- }
2607
- }
2608
- class PgDate extends PgColumn {
2609
- static [entityKind] = 'PgDate';
2610
- getSQLType() {
2611
- return 'date';
2612
- }
2613
- mapFromDriverValue(value) {
2614
- return new Date(value);
2615
- }
2616
- mapToDriverValue(value) {
2617
- return value.toISOString();
2618
- }
2619
- }
2620
- class PgDateStringBuilder extends PgDateColumnBaseBuilder {
2621
- static [entityKind] = 'PgDateStringBuilder';
2622
- constructor(name) {
2623
- super(name, 'string', 'PgDateString');
2624
- }
2625
- /** @internal */
2626
- build(table) {
2627
- return new PgDateString(table, this.config);
2493
+ return this;
2628
2494
  }
2629
- }
2630
- class PgDateString extends PgColumn {
2631
- static [entityKind] = 'PgDateString';
2632
- getSQLType() {
2633
- return 'date';
2495
+ /**
2496
+ * Set the maximum number of rows that will be
2497
+ * returned by this query.
2498
+ *
2499
+ * ## Examples
2500
+ *
2501
+ * ```ts
2502
+ * // Get the first 10 people from this query.
2503
+ * db.select().from(people).limit(10);
2504
+ * ```
2505
+ *
2506
+ * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-LIMIT|Postgres LIMIT documentation}
2507
+ */
2508
+ limit(limit) {
2509
+ this.config.limit = limit;
2510
+ return this;
2634
2511
  }
2635
- }
2636
- function date(name, config) {
2637
- if (config?.mode === 'date') {
2638
- return new PgDateBuilder(name);
2512
+ /**
2513
+ * Skip a number of rows when returning results
2514
+ * from this query.
2515
+ *
2516
+ * ## Examples
2517
+ *
2518
+ * ```ts
2519
+ * // Get the 10th-20th people from this query.
2520
+ * db.select().from(people).offset(10).limit(10);
2521
+ * ```
2522
+ */
2523
+ offset(offset) {
2524
+ this.config.offset = offset;
2525
+ return this;
2639
2526
  }
2640
- return new PgDateStringBuilder(name);
2641
- }
2642
-
2643
- class PgJsonBuilder extends PgColumnBuilder {
2644
- static [entityKind] = 'PgJsonBuilder';
2645
- constructor(name) {
2646
- super(name, 'json', 'PgJson');
2527
+ /**
2528
+ * The FOR clause specifies a lock strength for this query
2529
+ * that controls how strictly it acquires exclusive access to
2530
+ * the rows being queried.
2531
+ *
2532
+ * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE|Postgres locking clause documentation}
2533
+ */
2534
+ for(strength, config = {}) {
2535
+ if (!this.config.lockingClauses) {
2536
+ this.config.lockingClauses = [];
2537
+ }
2538
+ this.config.lockingClauses.push({ strength, config });
2539
+ return this;
2647
2540
  }
2648
2541
  /** @internal */
2649
- build(table) {
2650
- return new PgJson(table, this.config);
2651
- }
2652
- }
2653
- class PgJson extends PgColumn {
2654
- static [entityKind] = 'PgJson';
2655
- constructor(table, config) {
2656
- super(table, config);
2542
+ getSQL() {
2543
+ return this.dialect.buildSelectQuery(this.config);
2657
2544
  }
2658
- getSQLType() {
2659
- return 'json';
2545
+ toSQL() {
2546
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2547
+ return rest;
2660
2548
  }
2661
- mapToDriverValue(value) {
2662
- return JSON.stringify(value);
2549
+ as(alias) {
2550
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias), new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
2663
2551
  }
2664
- mapFromDriverValue(value) {
2665
- if (typeof value === 'string') {
2666
- try {
2667
- return JSON.parse(value);
2668
- }
2669
- catch {
2670
- return value;
2671
- }
2552
+ }
2553
+ class PgSelect extends PgSelectQueryBuilder {
2554
+ static [entityKind] = 'PgSelect';
2555
+ _prepare(name) {
2556
+ const { session, config, dialect, joinsNotNullableMap } = this;
2557
+ if (!session) {
2558
+ throw new Error('Cannot execute a query on a query builder. Please use a database instance instead.');
2672
2559
  }
2673
- return value;
2560
+ return tracer.startActiveSpan('drizzle.prepareQuery', () => {
2561
+ const fieldsList = orderSelectedFields(config.fields);
2562
+ const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name);
2563
+ query.joinsNotNullableMap = joinsNotNullableMap;
2564
+ return query;
2565
+ });
2674
2566
  }
2567
+ /**
2568
+ * Create a prepared statement for this query. This allows
2569
+ * the database to remember this query for the given session
2570
+ * and call it by name, rather than specifying the full query.
2571
+ *
2572
+ * {@link https://www.postgresql.org/docs/current/sql-prepare.html|Postgres prepare documentation}
2573
+ */
2574
+ prepare(name) {
2575
+ return this._prepare(name);
2576
+ }
2577
+ execute = (placeholderValues) => {
2578
+ return tracer.startActiveSpan('drizzle.operation', () => {
2579
+ return this._prepare().execute(placeholderValues);
2580
+ });
2581
+ };
2675
2582
  }
2676
- function json(name) {
2677
- return new PgJsonBuilder(name);
2678
- }
2583
+ applyMixins(PgSelect, [QueryPromise]);
2679
2584
 
2680
- class PgJsonbBuilder extends PgColumnBuilder {
2681
- static [entityKind] = 'PgJsonbBuilder';
2682
- constructor(name) {
2683
- super(name, 'json', 'PgJsonb');
2585
+ class QueryBuilder {
2586
+ static [entityKind] = 'PgQueryBuilder';
2587
+ dialect;
2588
+ $with(alias) {
2589
+ const queryBuilder = this;
2590
+ return {
2591
+ as(qb) {
2592
+ if (typeof qb === 'function') {
2593
+ qb = qb(queryBuilder);
2594
+ }
2595
+ return new Proxy(new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }));
2596
+ },
2597
+ };
2684
2598
  }
2685
- /** @internal */
2686
- build(table) {
2687
- return new PgJsonb(table, this.config);
2599
+ with(...queries) {
2600
+ const self = this;
2601
+ function select(fields) {
2602
+ return new PgSelectBuilder({
2603
+ fields: fields ?? undefined,
2604
+ session: undefined,
2605
+ dialect: self.getDialect(),
2606
+ withList: queries,
2607
+ });
2608
+ }
2609
+ function selectDistinct(fields) {
2610
+ return new PgSelectBuilder({
2611
+ fields: fields ?? undefined,
2612
+ session: undefined,
2613
+ dialect: self.getDialect(),
2614
+ distinct: true,
2615
+ });
2616
+ }
2617
+ function selectDistinctOn(on, fields) {
2618
+ return new PgSelectBuilder({
2619
+ fields: fields ?? undefined,
2620
+ session: undefined,
2621
+ dialect: self.getDialect(),
2622
+ distinct: { on },
2623
+ });
2624
+ }
2625
+ return { select, selectDistinct, selectDistinctOn };
2688
2626
  }
2689
- }
2690
- class PgJsonb extends PgColumn {
2691
- static [entityKind] = 'PgJsonb';
2692
- constructor(table, config) {
2693
- super(table, config);
2627
+ select(fields) {
2628
+ return new PgSelectBuilder({
2629
+ fields: fields ?? undefined,
2630
+ session: undefined,
2631
+ dialect: this.getDialect(),
2632
+ });
2694
2633
  }
2695
- getSQLType() {
2696
- return 'jsonb';
2634
+ selectDistinct(fields) {
2635
+ return new PgSelectBuilder({
2636
+ fields: fields ?? undefined,
2637
+ session: undefined,
2638
+ dialect: this.getDialect(),
2639
+ distinct: true,
2640
+ });
2697
2641
  }
2698
- mapToDriverValue(value) {
2699
- return JSON.stringify(value);
2642
+ selectDistinctOn(on, fields) {
2643
+ return new PgSelectBuilder({
2644
+ fields: fields ?? undefined,
2645
+ session: undefined,
2646
+ dialect: this.getDialect(),
2647
+ distinct: { on },
2648
+ });
2700
2649
  }
2701
- mapFromDriverValue(value) {
2702
- if (typeof value === 'string') {
2703
- try {
2704
- return JSON.parse(value);
2705
- }
2706
- catch {
2707
- return value;
2708
- }
2650
+ // Lazy load dialect to avoid circular dependency
2651
+ getDialect() {
2652
+ if (!this.dialect) {
2653
+ this.dialect = new PgDialect();
2709
2654
  }
2710
- return value;
2655
+ return this.dialect;
2711
2656
  }
2712
2657
  }
2713
- function jsonb(name) {
2714
- return new PgJsonbBuilder(name);
2715
- }
2716
2658
 
2717
- class PgNumericBuilder extends PgColumnBuilder {
2718
- static [entityKind] = 'PgNumericBuilder';
2719
- constructor(name, precision, scale) {
2720
- super(name, 'string', 'PgNumeric');
2721
- this.config.precision = precision;
2722
- this.config.scale = scale;
2659
+ class DefaultViewBuilderCore {
2660
+ name;
2661
+ schema;
2662
+ static [entityKind] = 'PgDefaultViewBuilderCore';
2663
+ constructor(name, schema) {
2664
+ this.name = name;
2665
+ this.schema = schema;
2723
2666
  }
2724
- /** @internal */
2725
- build(table) {
2726
- return new PgNumeric(table, this.config);
2667
+ config = {};
2668
+ with(config) {
2669
+ this.config.with = config;
2670
+ return this;
2727
2671
  }
2728
2672
  }
2729
- class PgNumeric extends PgColumn {
2730
- static [entityKind] = 'PgNumeric';
2731
- precision;
2732
- scale;
2733
- constructor(table, config) {
2734
- super(table, config);
2735
- this.precision = config.precision;
2736
- this.scale = config.scale;
2737
- }
2738
- getSQLType() {
2739
- if (this.precision !== undefined && this.scale !== undefined) {
2740
- return `numeric(${this.precision}, ${this.scale})`;
2741
- }
2742
- else if (this.precision === undefined) {
2743
- return 'numeric';
2744
- }
2745
- else {
2746
- return `numeric(${this.precision})`;
2673
+ class ViewBuilder extends DefaultViewBuilderCore {
2674
+ static [entityKind] = 'PgViewBuilder';
2675
+ as(qb) {
2676
+ if (typeof qb === 'function') {
2677
+ qb = qb(new QueryBuilder());
2747
2678
  }
2679
+ const selectionProxy = new SelectionProxyHandler({
2680
+ alias: this.name,
2681
+ sqlBehavior: 'error',
2682
+ sqlAliasedBehavior: 'alias',
2683
+ replaceOriginalName: true,
2684
+ });
2685
+ const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
2686
+ return new Proxy(new PgView({
2687
+ pgConfig: this.config,
2688
+ config: {
2689
+ name: this.name,
2690
+ schema: this.schema,
2691
+ selectedFields: aliasedSelection,
2692
+ query: qb.getSQL().inlineParams(),
2693
+ },
2694
+ }), selectionProxy);
2748
2695
  }
2749
2696
  }
2750
- function numeric(name, config) {
2751
- return new PgNumericBuilder(name, config?.precision, config?.scale);
2752
- }
2753
- const decimal = numeric;
2754
-
2755
- class PgTimeBuilder extends PgDateColumnBaseBuilder {
2756
- withTimezone;
2757
- precision;
2758
- static [entityKind] = 'PgTimeBuilder';
2759
- constructor(name, withTimezone, precision) {
2760
- super(name, 'string', 'PgTime');
2761
- this.withTimezone = withTimezone;
2762
- this.precision = precision;
2763
- this.config.withTimezone = withTimezone;
2764
- this.config.precision = precision;
2765
- }
2766
- /** @internal */
2767
- build(table) {
2768
- return new PgTime(table, this.config);
2769
- }
2770
- }
2771
- class PgTime extends PgColumn {
2772
- static [entityKind] = 'PgTime';
2773
- withTimezone;
2774
- precision;
2775
- constructor(table, config) {
2776
- super(table, config);
2777
- this.withTimezone = config.withTimezone;
2778
- this.precision = config.precision;
2697
+ class ManualViewBuilder extends DefaultViewBuilderCore {
2698
+ static [entityKind] = 'PgManualViewBuilder';
2699
+ columns;
2700
+ constructor(name, columns, schema) {
2701
+ super(name, schema);
2702
+ this.columns = getTableColumns(pgTable(name, columns));
2779
2703
  }
2780
- getSQLType() {
2781
- const precision = this.precision === undefined ? '' : `(${this.precision})`;
2782
- return `time${precision}${this.withTimezone ? ' with time zone' : ''}`;
2704
+ existing() {
2705
+ return new Proxy(new PgView({
2706
+ pgConfig: undefined,
2707
+ config: {
2708
+ name: this.name,
2709
+ schema: this.schema,
2710
+ selectedFields: this.columns,
2711
+ query: undefined,
2712
+ },
2713
+ }), new SelectionProxyHandler({
2714
+ alias: this.name,
2715
+ sqlBehavior: 'error',
2716
+ sqlAliasedBehavior: 'alias',
2717
+ replaceOriginalName: true,
2718
+ }));
2719
+ }
2720
+ as(query) {
2721
+ return new Proxy(new PgView({
2722
+ pgConfig: this.config,
2723
+ config: {
2724
+ name: this.name,
2725
+ schema: this.schema,
2726
+ selectedFields: this.columns,
2727
+ query: query.inlineParams(),
2728
+ },
2729
+ }), new SelectionProxyHandler({
2730
+ alias: this.name,
2731
+ sqlBehavior: 'error',
2732
+ sqlAliasedBehavior: 'alias',
2733
+ replaceOriginalName: true,
2734
+ }));
2783
2735
  }
2784
2736
  }
2785
- function time(name, config = {}) {
2786
- return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);
2787
- }
2788
-
2789
- class PgTimestampBuilder extends PgDateColumnBaseBuilder {
2790
- static [entityKind] = 'PgTimestampBuilder';
2791
- constructor(name, withTimezone, precision) {
2792
- super(name, 'date', 'PgTimestamp');
2793
- this.config.withTimezone = withTimezone;
2794
- this.config.precision = precision;
2737
+ class MaterializedViewBuilderCore {
2738
+ name;
2739
+ schema;
2740
+ static [entityKind] = 'PgMaterializedViewBuilderCore';
2741
+ constructor(name, schema) {
2742
+ this.name = name;
2743
+ this.schema = schema;
2795
2744
  }
2796
- /** @internal */
2797
- build(table) {
2798
- return new PgTimestamp(table, this.config);
2745
+ config = {};
2746
+ using(using) {
2747
+ this.config.using = using;
2748
+ return this;
2799
2749
  }
2800
- }
2801
- class PgTimestamp extends PgColumn {
2802
- static [entityKind] = 'PgTimestamp';
2803
- withTimezone;
2804
- precision;
2805
- constructor(table, config) {
2806
- super(table, config);
2807
- this.withTimezone = config.withTimezone;
2808
- this.precision = config.precision;
2750
+ with(config) {
2751
+ this.config.with = config;
2752
+ return this;
2809
2753
  }
2810
- getSQLType() {
2811
- const precision = this.precision === undefined ? '' : ` (${this.precision})`;
2812
- return `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;
2754
+ tablespace(tablespace) {
2755
+ this.config.tablespace = tablespace;
2756
+ return this;
2813
2757
  }
2814
- mapFromDriverValue = (value) => {
2815
- return new Date(this.withTimezone ? value : value + '+0000');
2816
- };
2817
- mapToDriverValue = (value) => {
2818
- return this.withTimezone ? value.toUTCString() : value.toISOString();
2819
- };
2820
- }
2821
- class PgTimestampStringBuilder extends PgDateColumnBaseBuilder {
2822
- static [entityKind] = 'PgTimestampStringBuilder';
2823
- constructor(name, withTimezone, precision) {
2824
- super(name, 'string', 'PgTimestampString');
2825
- this.config.withTimezone = withTimezone;
2826
- this.config.precision = precision;
2758
+ withNoData() {
2759
+ this.config.withNoData = true;
2760
+ return this;
2827
2761
  }
2828
- /** @internal */
2829
- build(table) {
2830
- return new PgTimestampString(table, this.config);
2762
+ }
2763
+ class MaterializedViewBuilder extends MaterializedViewBuilderCore {
2764
+ static [entityKind] = 'PgMaterializedViewBuilder';
2765
+ as(qb) {
2766
+ if (typeof qb === 'function') {
2767
+ qb = qb(new QueryBuilder());
2768
+ }
2769
+ const selectionProxy = new SelectionProxyHandler({
2770
+ alias: this.name,
2771
+ sqlBehavior: 'error',
2772
+ sqlAliasedBehavior: 'alias',
2773
+ replaceOriginalName: true,
2774
+ });
2775
+ const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
2776
+ return new Proxy(new PgMaterializedView({
2777
+ pgConfig: {
2778
+ with: this.config.with,
2779
+ using: this.config.using,
2780
+ tablespace: this.config.tablespace,
2781
+ withNoData: this.config.withNoData,
2782
+ },
2783
+ config: {
2784
+ name: this.name,
2785
+ schema: this.schema,
2786
+ selectedFields: aliasedSelection,
2787
+ query: qb.getSQL().inlineParams(),
2788
+ },
2789
+ }), selectionProxy);
2831
2790
  }
2832
2791
  }
2833
- class PgTimestampString extends PgColumn {
2834
- static [entityKind] = 'PgTimestampString';
2835
- withTimezone;
2836
- precision;
2837
- constructor(table, config) {
2838
- super(table, config);
2839
- this.withTimezone = config.withTimezone;
2840
- this.precision = config.precision;
2792
+ class ManualMaterializedViewBuilder extends MaterializedViewBuilderCore {
2793
+ static [entityKind] = 'PgManualMaterializedViewBuilder';
2794
+ columns;
2795
+ constructor(name, columns, schema) {
2796
+ super(name, schema);
2797
+ this.columns = getTableColumns(pgTable(name, columns));
2841
2798
  }
2842
- getSQLType() {
2843
- const precision = this.precision === undefined ? '' : `(${this.precision})`;
2844
- return `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;
2799
+ existing() {
2800
+ return new Proxy(new PgMaterializedView({
2801
+ pgConfig: undefined,
2802
+ config: {
2803
+ name: this.name,
2804
+ schema: this.schema,
2805
+ selectedFields: this.columns,
2806
+ query: undefined,
2807
+ },
2808
+ }), new SelectionProxyHandler({
2809
+ alias: this.name,
2810
+ sqlBehavior: 'error',
2811
+ sqlAliasedBehavior: 'alias',
2812
+ replaceOriginalName: true,
2813
+ }));
2845
2814
  }
2846
- }
2847
- function timestamp(name, config = {}) {
2848
- if (config.mode === 'string') {
2849
- return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);
2815
+ as(query) {
2816
+ return new Proxy(new PgMaterializedView({
2817
+ pgConfig: undefined,
2818
+ config: {
2819
+ name: this.name,
2820
+ schema: this.schema,
2821
+ selectedFields: this.columns,
2822
+ query: query.inlineParams(),
2823
+ },
2824
+ }), new SelectionProxyHandler({
2825
+ alias: this.name,
2826
+ sqlBehavior: 'error',
2827
+ sqlAliasedBehavior: 'alias',
2828
+ replaceOriginalName: true,
2829
+ }));
2850
2830
  }
2851
- return new PgTimestampBuilder(name, config.withTimezone ?? false, config.precision);
2852
2831
  }
2853
-
2854
- class PgUUIDBuilder extends PgColumnBuilder {
2855
- static [entityKind] = 'PgUUIDBuilder';
2856
- constructor(name) {
2857
- super(name, 'string', 'PgUUID');
2832
+ class PgViewBase extends View {
2833
+ static [entityKind] = 'PgViewBase';
2834
+ }
2835
+ const PgViewConfig = Symbol.for('drizzle:PgViewConfig');
2836
+ class PgView extends PgViewBase {
2837
+ static [entityKind] = 'PgView';
2838
+ [PgViewConfig];
2839
+ constructor({ pgConfig, config }) {
2840
+ super(config);
2841
+ if (pgConfig) {
2842
+ this[PgViewConfig] = {
2843
+ with: pgConfig.with,
2844
+ };
2845
+ }
2858
2846
  }
2859
- /**
2860
- * Adds `default gen_random_uuid()` to the column definition.
2861
- */
2862
- defaultRandom() {
2863
- return this.default(sql `gen_random_uuid()`);
2847
+ }
2848
+ const PgMaterializedViewConfig = Symbol.for('drizzle:PgMaterializedViewConfig');
2849
+ class PgMaterializedView extends PgViewBase {
2850
+ static [entityKind] = 'PgMaterializedView';
2851
+ [PgMaterializedViewConfig];
2852
+ constructor({ pgConfig, config }) {
2853
+ super(config);
2854
+ this[PgMaterializedViewConfig] = {
2855
+ with: pgConfig?.with,
2856
+ using: pgConfig?.using,
2857
+ tablespace: pgConfig?.tablespace,
2858
+ withNoData: pgConfig?.withNoData,
2859
+ };
2864
2860
  }
2865
- /** @internal */
2866
- build(table) {
2867
- return new PgUUID(table, this.config);
2861
+ }
2862
+ /** @internal */
2863
+ function pgViewWithSchema(name, selection, schema) {
2864
+ if (selection) {
2865
+ return new ManualViewBuilder(name, selection, schema);
2868
2866
  }
2867
+ return new ViewBuilder(name, schema);
2869
2868
  }
2870
- class PgUUID extends PgColumn {
2871
- static [entityKind] = 'PgUUID';
2872
- getSQLType() {
2873
- return 'uuid';
2869
+ /** @internal */
2870
+ function pgMaterializedViewWithSchema(name, selection, schema) {
2871
+ if (selection) {
2872
+ return new ManualMaterializedViewBuilder(name, selection, schema);
2874
2873
  }
2874
+ return new MaterializedViewBuilder(name, schema);
2875
2875
  }
2876
- function uuid(name) {
2877
- return new PgUUIDBuilder(name);
2876
+ function pgView(name, columns) {
2877
+ return pgViewWithSchema(name, columns, undefined);
2878
+ }
2879
+ function pgMaterializedView(name, columns) {
2880
+ return pgMaterializedViewWithSchema(name, columns, undefined);
2878
2881
  }
2879
2882
 
2880
2883
  class Relation {
@@ -3977,5 +3980,5 @@ function mapColumnsInSQLToAlias(query, alias) {
3977
3980
  }));
3978
3981
  }
3979
3982
 
3980
- export { PgArrayBuilder as $, mapColumnsInAliasedSQLToAlias as A, getOrderByOperators as B, ColumnBuilder as C, DrizzleError as D, normalizeRelation as E, and as F, eq as G, aliasedTable as H, applyMixins as I, TypedQueryBuilder as J, getTableLikeName as K, PgColumnBuilder as L, Many as M, PgColumn as N, One as O, PgDialect as P, QueryPromise as Q, pgTableWithSchema as R, SQL as S, Table as T, pgViewWithSchema as U, ViewBaseConfig as V, WithSubquery as W, pgMaterializedViewWithSchema as X, CheckBuilder as Y, Check as Z, check as _, extractTablesRelationalConfig as a, PgView as a$, PgArray as a0, PgDateBuilder as a1, PgDate as a2, PgDateStringBuilder as a3, PgDateString as a4, date as a5, PgJsonBuilder as a6, PgJson as a7, json as a8, PgJsonbBuilder as a9, PrimaryKeyBuilder as aA, PrimaryKey as aB, unique as aC, uniqueKeyName as aD, UniqueConstraintBuilder as aE, UniqueOnConstraintBuilder as aF, UniqueConstraint as aG, PgSelectQueryBuilder as aH, PgSelect as aI, InlineForeignKeys as aJ, PgTable as aK, pgTable as aL, pgTableCreator as aM, getTableConfig as aN, getViewConfig as aO, getMaterializedViewConfig as aP, parsePgNestedArray as aQ, parsePgArray as aR, makePgArray as aS, DefaultViewBuilderCore as aT, ViewBuilder as aU, ManualViewBuilder as aV, MaterializedViewBuilderCore as aW, MaterializedViewBuilder as aX, ManualMaterializedViewBuilder as aY, PgViewBase as aZ, PgViewConfig as a_, PgJsonb as aa, jsonb as ab, PgNumericBuilder as ac, PgNumeric as ad, numeric as ae, decimal as af, PgTimeBuilder as ag, PgTime as ah, time as ai, PgTimestampBuilder as aj, PgTimestamp as ak, PgTimestampStringBuilder as al, PgTimestampString as am, timestamp as an, PgUUIDBuilder as ao, PgUUID as ap, uuid as aq, ForeignKeyBuilder as ar, ForeignKey as as, foreignKey as at, IndexBuilderOn as au, IndexBuilder as av, Index as aw, index as ax, uniqueIndex as ay, primaryKey as az, Param as b, PgMaterializedViewConfig as b0, PgMaterializedView as b1, pgView as b2, pgMaterializedView as b3, ColumnAliasProxyHandler as b4, RelationTableAliasProxyHandler as b5, aliasedRelation as b6, hasOwnEntityKind as b7, bindIfParam as b8, ne as b9, isSQLWrapper as bA, StringChunk as bB, Name as bC, name as bD, isDriverValueEncoder as bE, noopDecoder as bF, noopEncoder as bG, noopMapper as bH, param as bI, Placeholder as bJ, placeholder as bK, TableName as bL, Schema as bM, Columns as bN, OriginalName as bO, BaseName as bP, IsAlias as bQ, ExtraConfigBuilder as bR, isTable as bS, iife as bT, or as ba, not as bb, gt as bc, gte as bd, lt as be, lte as bf, inArray as bg, notInArray as bh, isNull as bi, isNotNull as bj, exists as bk, notExists as bl, between as bm, notBetween as bn, like as bo, notLike as bp, ilike as bq, notIlike as br, asc as bs, desc as bt, Relation as bu, Relations as bv, relations as bw, createOne as bx, createMany as by, FakePrimitiveParam as bz, createTableRelationsHelpers as c, mapUpdateSet as d, entityKind as e, fillPlaceholders as f, mapRelationalRow as g, QueryBuilder as h, is as i, SelectionProxyHandler as j, PgSelectBuilder as k, TransactionRollbackError as l, mapResultRow as m, TableAliasProxyHandler as n, orderSelectedFields as o, Column as p, getTableColumns as q, View as r, sql as s, tracer as t, getTableName as u, Subquery as v, SubqueryConfig as w, aliasedTableColumn as x, getOperators as y, mapColumnsInSQLToAlias as z };
3981
- //# sourceMappingURL=alias-d302772a.mjs.map
3983
+ export { PgArrayBuilder as $, getOrderByOperators as A, normalizeRelation as B, ColumnBuilder as C, DrizzleError as D, and as E, eq as F, aliasedTable as G, applyMixins as H, getTableColumns as I, TypedQueryBuilder as J, getTableLikeName as K, PgColumnBuilder as L, Many as M, PgColumn as N, One as O, PgDialect as P, QueryPromise as Q, pgTableWithSchema as R, SQL as S, Table as T, pgViewWithSchema as U, ViewBaseConfig as V, WithSubquery as W, pgMaterializedViewWithSchema as X, CheckBuilder as Y, Check as Z, check as _, extractTablesRelationalConfig as a, PgView as a$, PgArray as a0, PgDateBuilder as a1, PgDate as a2, PgDateStringBuilder as a3, PgDateString as a4, date as a5, PgJsonBuilder as a6, PgJson as a7, json as a8, PgJsonbBuilder as a9, PrimaryKeyBuilder as aA, PrimaryKey as aB, PgSelectQueryBuilder as aC, PgSelect as aD, InlineForeignKeys as aE, PgTable as aF, pgTable as aG, pgTableCreator as aH, unique as aI, uniqueKeyName as aJ, UniqueConstraintBuilder as aK, UniqueOnConstraintBuilder as aL, UniqueConstraint as aM, getTableConfig as aN, getViewConfig as aO, getMaterializedViewConfig as aP, parsePgNestedArray as aQ, parsePgArray as aR, makePgArray as aS, DefaultViewBuilderCore as aT, ViewBuilder as aU, ManualViewBuilder as aV, MaterializedViewBuilderCore as aW, MaterializedViewBuilder as aX, ManualMaterializedViewBuilder as aY, PgViewBase as aZ, PgViewConfig as a_, PgJsonb as aa, jsonb as ab, PgNumericBuilder as ac, PgNumeric as ad, numeric as ae, decimal as af, PgTimeBuilder as ag, PgTime as ah, time as ai, PgTimestampBuilder as aj, PgTimestamp as ak, PgTimestampStringBuilder as al, PgTimestampString as am, timestamp as an, PgUUIDBuilder as ao, PgUUID as ap, uuid as aq, ForeignKeyBuilder as ar, ForeignKey as as, foreignKey as at, IndexBuilderOn as au, IndexBuilder as av, Index as aw, index as ax, uniqueIndex as ay, primaryKey as az, Param as b, PgMaterializedViewConfig as b0, PgMaterializedView as b1, pgView as b2, pgMaterializedView as b3, ColumnAliasProxyHandler as b4, RelationTableAliasProxyHandler as b5, aliasedRelation as b6, hasOwnEntityKind as b7, bindIfParam as b8, ne as b9, isSQLWrapper as bA, StringChunk as bB, Name as bC, name as bD, isDriverValueEncoder as bE, noopDecoder as bF, noopEncoder as bG, noopMapper as bH, param as bI, Placeholder as bJ, placeholder as bK, TableName as bL, Schema as bM, Columns as bN, OriginalName as bO, BaseName as bP, IsAlias as bQ, ExtraConfigBuilder as bR, isTable as bS, iife as bT, or as ba, not as bb, gt as bc, gte as bd, lt as be, lte as bf, inArray as bg, notInArray as bh, isNull as bi, isNotNull as bj, exists as bk, notExists as bl, between as bm, notBetween as bn, like as bo, notLike as bp, ilike as bq, notIlike as br, asc as bs, desc as bt, Relation as bu, Relations as bv, relations as bw, createOne as bx, createMany as by, FakePrimitiveParam as bz, createTableRelationsHelpers as c, mapUpdateSet as d, entityKind as e, fillPlaceholders as f, mapRelationalRow as g, QueryBuilder as h, is as i, SelectionProxyHandler as j, PgSelectBuilder as k, TransactionRollbackError as l, mapResultRow as m, TableAliasProxyHandler as n, orderSelectedFields as o, Column as p, getTableName as q, Subquery as r, sql as s, tracer as t, SubqueryConfig as u, View as v, aliasedTableColumn as w, getOperators as x, mapColumnsInSQLToAlias as y, mapColumnsInAliasedSQLToAlias as z };
3984
+ //# sourceMappingURL=alias-e80df77c.mjs.map