drizzle-orm 0.25.2 → 0.25.3-4cc2d87

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