pqb 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/index.d.ts +3630 -0
  2. package/dist/index.esm.js +4587 -0
  3. package/dist/index.esm.js.map +1 -0
  4. package/dist/index.js +4691 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +59 -0
  7. package/rollup.config.js +35 -0
  8. package/src/adapter.test.ts +10 -0
  9. package/src/adapter.ts +171 -0
  10. package/src/columnSchema/array.ts +21 -0
  11. package/src/columnSchema/boolean.ts +10 -0
  12. package/src/columnSchema/columnType.test.ts +129 -0
  13. package/src/columnSchema/columnType.ts +77 -0
  14. package/src/columnSchema/columnTypes.ts +145 -0
  15. package/src/columnSchema/columnsSchema.test.ts +32 -0
  16. package/src/columnSchema/columnsSchema.ts +100 -0
  17. package/src/columnSchema/commonMethods.ts +130 -0
  18. package/src/columnSchema/dateTime.ts +104 -0
  19. package/src/columnSchema/enum.ts +13 -0
  20. package/src/columnSchema/index.ts +11 -0
  21. package/src/columnSchema/json/array.ts +55 -0
  22. package/src/columnSchema/json/discriminatedUnion.ts +91 -0
  23. package/src/columnSchema/json/enum.ts +29 -0
  24. package/src/columnSchema/json/instanceOf.ts +16 -0
  25. package/src/columnSchema/json/intersection.ts +23 -0
  26. package/src/columnSchema/json/lazy.ts +22 -0
  27. package/src/columnSchema/json/literal.ts +12 -0
  28. package/src/columnSchema/json/map.ts +29 -0
  29. package/src/columnSchema/json/nativeEnum.ts +30 -0
  30. package/src/columnSchema/json/nullable.ts +33 -0
  31. package/src/columnSchema/json/nullish.ts +30 -0
  32. package/src/columnSchema/json/object.ts +206 -0
  33. package/src/columnSchema/json/optional.ts +28 -0
  34. package/src/columnSchema/json/record.ts +40 -0
  35. package/src/columnSchema/json/scalarTypes.ts +117 -0
  36. package/src/columnSchema/json/set.ts +34 -0
  37. package/src/columnSchema/json/tuple.ts +40 -0
  38. package/src/columnSchema/json/typeBase.ts +202 -0
  39. package/src/columnSchema/json/union.ts +16 -0
  40. package/src/columnSchema/json.ts +64 -0
  41. package/src/columnSchema/number.ts +122 -0
  42. package/src/columnSchema/string.ts +222 -0
  43. package/src/columnSchema/utils.ts +27 -0
  44. package/src/common.ts +86 -0
  45. package/src/db.test.ts +67 -0
  46. package/src/db.ts +212 -0
  47. package/src/errors.ts +7 -0
  48. package/src/index.ts +18 -0
  49. package/src/operators.test.ts +608 -0
  50. package/src/operators.ts +177 -0
  51. package/src/query.ts +292 -0
  52. package/src/queryDataUtils.ts +50 -0
  53. package/src/queryMethods/aggregate.test.ts +583 -0
  54. package/src/queryMethods/aggregate.ts +878 -0
  55. package/src/queryMethods/callbacks.test.ts +69 -0
  56. package/src/queryMethods/callbacks.ts +55 -0
  57. package/src/queryMethods/clear.test.ts +64 -0
  58. package/src/queryMethods/clear.ts +58 -0
  59. package/src/queryMethods/columnInfo.test.ts +45 -0
  60. package/src/queryMethods/columnInfo.ts +67 -0
  61. package/src/queryMethods/delete.test.ts +135 -0
  62. package/src/queryMethods/delete.ts +50 -0
  63. package/src/queryMethods/for.test.ts +57 -0
  64. package/src/queryMethods/for.ts +99 -0
  65. package/src/queryMethods/from.test.ts +66 -0
  66. package/src/queryMethods/from.ts +58 -0
  67. package/src/queryMethods/get.test.ts +66 -0
  68. package/src/queryMethods/get.ts +88 -0
  69. package/src/queryMethods/having.test.ts +247 -0
  70. package/src/queryMethods/having.ts +99 -0
  71. package/src/queryMethods/insert.test.ts +555 -0
  72. package/src/queryMethods/insert.ts +453 -0
  73. package/src/queryMethods/join.test.ts +150 -0
  74. package/src/queryMethods/join.ts +508 -0
  75. package/src/queryMethods/json.test.ts +398 -0
  76. package/src/queryMethods/json.ts +259 -0
  77. package/src/queryMethods/log.test.ts +172 -0
  78. package/src/queryMethods/log.ts +123 -0
  79. package/src/queryMethods/queryMethods.test.ts +629 -0
  80. package/src/queryMethods/queryMethods.ts +428 -0
  81. package/src/queryMethods/select.test.ts +479 -0
  82. package/src/queryMethods/select.ts +249 -0
  83. package/src/queryMethods/then.ts +236 -0
  84. package/src/queryMethods/transaction.test.ts +66 -0
  85. package/src/queryMethods/transaction.ts +66 -0
  86. package/src/queryMethods/union.test.ts +59 -0
  87. package/src/queryMethods/union.ts +89 -0
  88. package/src/queryMethods/update.test.ts +417 -0
  89. package/src/queryMethods/update.ts +350 -0
  90. package/src/queryMethods/upsert.test.ts +56 -0
  91. package/src/queryMethods/upsert.ts +43 -0
  92. package/src/queryMethods/where.test.ts +1594 -0
  93. package/src/queryMethods/where.ts +450 -0
  94. package/src/queryMethods/window.test.ts +66 -0
  95. package/src/queryMethods/window.ts +108 -0
  96. package/src/queryMethods/with.test.ts +191 -0
  97. package/src/queryMethods/with.ts +92 -0
  98. package/src/quote.ts +36 -0
  99. package/src/relations.ts +194 -0
  100. package/src/sql/aggregate.ts +80 -0
  101. package/src/sql/columnInfo.ts +22 -0
  102. package/src/sql/common.ts +42 -0
  103. package/src/sql/delete.ts +41 -0
  104. package/src/sql/distinct.ts +19 -0
  105. package/src/sql/fromAndAs.ts +51 -0
  106. package/src/sql/having.ts +140 -0
  107. package/src/sql/index.ts +2 -0
  108. package/src/sql/insert.ts +102 -0
  109. package/src/sql/join.ts +242 -0
  110. package/src/sql/orderBy.ts +41 -0
  111. package/src/sql/select.ts +153 -0
  112. package/src/sql/toSql.ts +153 -0
  113. package/src/sql/truncate.ts +13 -0
  114. package/src/sql/types.ts +355 -0
  115. package/src/sql/update.ts +62 -0
  116. package/src/sql/where.ts +314 -0
  117. package/src/sql/window.ts +38 -0
  118. package/src/sql/with.ts +32 -0
  119. package/src/test-utils.ts +172 -0
  120. package/src/utils.ts +140 -0
  121. package/tsconfig.build.json +6 -0
  122. package/tsconfig.json +8 -0
@@ -0,0 +1,4587 @@
1
+ import { types, Pool } from 'pg';
2
+
3
+ class ColumnType {
4
+ constructor() {
5
+ this.data = {};
6
+ this.isPrimaryKey = false;
7
+ this.isHidden = false;
8
+ this.isNullable = false;
9
+ }
10
+ primaryKey() {
11
+ return Object.assign(this, { isPrimaryKey: true });
12
+ }
13
+ hidden() {
14
+ return Object.assign(this, { isHidden: true });
15
+ }
16
+ nullable() {
17
+ this.isNullable = true;
18
+ return this;
19
+ }
20
+ encode(fn) {
21
+ const self = this;
22
+ self.encodeFn = fn;
23
+ return self;
24
+ }
25
+ parse(fn) {
26
+ this.parseFn = fn;
27
+ return this;
28
+ }
29
+ toSQL() {
30
+ return this.dataType;
31
+ }
32
+ }
33
+
34
+ const raw = (sql, ...values) => ({
35
+ __raw: sql,
36
+ __values: values
37
+ });
38
+ const rawColumn = (column, sql, ...values) => ({
39
+ __column: column,
40
+ __raw: sql,
41
+ __values: values
42
+ });
43
+ const isRaw = (obj) => "__raw" in obj;
44
+ const getRaw = (raw2, values) => {
45
+ values.push(...raw2.__values);
46
+ return raw2.__raw;
47
+ };
48
+ const EMPTY_OBJECT = {};
49
+ const getQueryParsers = (q) => {
50
+ return q.query.parsers || q.columnsParsers;
51
+ };
52
+
53
+ const singleQuoteRegex = /'/g;
54
+ const doubleQuoteRegex = /"/g;
55
+ const quoteValue$1 = (value) => {
56
+ const type = typeof value;
57
+ if (type === "number")
58
+ return String(value);
59
+ else if (type === "string")
60
+ return `"${value.replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
61
+ else if (type === "boolean")
62
+ return value ? "true" : "false";
63
+ else if (value instanceof Date)
64
+ return `"${value.toISOString()}"`;
65
+ else if (Array.isArray(value))
66
+ return quoteArray(value);
67
+ else if (type === null || type === void 0)
68
+ return "NULL";
69
+ else
70
+ return `"${JSON.stringify(value).replace(doubleQuoteRegex, '\\"').replace(singleQuoteRegex, "''")}"`;
71
+ };
72
+ const quoteArray = (array) => `'{${array.map(quoteValue$1).join(",")}}'`;
73
+ const quote = (value) => {
74
+ const type = typeof value;
75
+ if (type === "number")
76
+ return `${value}`;
77
+ else if (type === "string")
78
+ return `'${value.replace(singleQuoteRegex, "''")}'`;
79
+ else if (type === "boolean")
80
+ return value ? "true" : "false";
81
+ else if (value instanceof Date)
82
+ return `'${value.toISOString()}'`;
83
+ else if (Array.isArray(value))
84
+ return quoteArray(value);
85
+ else if (value === null || value === void 0)
86
+ return "NULL";
87
+ else
88
+ return `'${JSON.stringify(value).replace(singleQuoteRegex, "''")}'`;
89
+ };
90
+
91
+ const q = (sql) => `"${sql}"`;
92
+ const qc = (column, quotedAs) => quotedAs ? `${quotedAs}.${q(column)}` : column;
93
+ const quoteFullColumn = (fullColumn, quotedAs) => {
94
+ const index = fullColumn.indexOf(".");
95
+ if (index !== -1) {
96
+ return `${q(fullColumn.slice(0, index))}.${q(fullColumn.slice(index + 1))}`;
97
+ } else if (quotedAs) {
98
+ return `${quotedAs}.${q(fullColumn)}`;
99
+ } else {
100
+ return q(fullColumn);
101
+ }
102
+ };
103
+ const expressionToSql = (expr, values, quotedAs) => {
104
+ return typeof expr === "object" && isRaw(expr) ? getRaw(expr, values) : quoteFullColumn(expr, quotedAs);
105
+ };
106
+ const quoteSchemaAndTable = (schema, table) => {
107
+ return schema ? `${q(schema)}.${q(table)}` : q(table);
108
+ };
109
+ const addValue = (values, value) => {
110
+ values.push(value);
111
+ return `$${values.length}`;
112
+ };
113
+
114
+ var __defProp$m = Object.defineProperty;
115
+ var __defProps$h = Object.defineProperties;
116
+ var __getOwnPropDescs$h = Object.getOwnPropertyDescriptors;
117
+ var __getOwnPropSymbols$n = Object.getOwnPropertySymbols;
118
+ var __hasOwnProp$n = Object.prototype.hasOwnProperty;
119
+ var __propIsEnum$n = Object.prototype.propertyIsEnumerable;
120
+ var __defNormalProp$m = (obj, key, value) => key in obj ? __defProp$m(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
121
+ var __spreadValues$m = (a, b) => {
122
+ for (var prop in b || (b = {}))
123
+ if (__hasOwnProp$n.call(b, prop))
124
+ __defNormalProp$m(a, prop, b[prop]);
125
+ if (__getOwnPropSymbols$n)
126
+ for (var prop of __getOwnPropSymbols$n(b)) {
127
+ if (__propIsEnum$n.call(b, prop))
128
+ __defNormalProp$m(a, prop, b[prop]);
129
+ }
130
+ return a;
131
+ };
132
+ var __spreadProps$h = (a, b) => __defProps$h(a, __getOwnPropDescs$h(b));
133
+ const createOperator = (fn) => {
134
+ return Object.assign(fn, { type: void 0 });
135
+ };
136
+ const quoteValue = (arg, values, jsonArray) => {
137
+ if (arg && typeof arg === "object") {
138
+ if (!jsonArray && Array.isArray(arg)) {
139
+ return `(${arg.map((value) => addValue(values, value)).join(", ")})`;
140
+ }
141
+ if ("toSql" in arg) {
142
+ const sql = arg.toSql(values);
143
+ return `(${sql.text})`;
144
+ }
145
+ if (isRaw(arg)) {
146
+ return getRaw(arg, values);
147
+ }
148
+ }
149
+ return addValue(values, arg);
150
+ };
151
+ const all = {
152
+ equals: () => createOperator((key, value, values) => value === null ? `${key} IS NULL` : `${key} = ${quoteValue(value, values)}`),
153
+ not: () => createOperator((key, value, values) => value === null ? `${key} IS NOT NULL` : `${key} <> ${quoteValue(value, values)}`),
154
+ in: () => createOperator((key, value, values) => `${key} IN ${quoteValue(value, values)}`),
155
+ notIn: () => createOperator((key, value, values) => `NOT ${key} IN ${quoteValue(value, values)}`),
156
+ lt: () => createOperator((key, value, values) => `${key} < ${quoteValue(value, values)}`),
157
+ lte: () => createOperator((key, value, values) => `${key} <= ${quoteValue(value, values)}`),
158
+ gt: () => createOperator((key, value, values) => `${key} > ${quoteValue(value, values)}`),
159
+ gte: () => createOperator((key, value, values) => `${key} >= ${quoteValue(value, values)}`),
160
+ contains: () => createOperator((key, value, values) => `${key} LIKE '%' || ${quoteValue(value, values)} || '%'`),
161
+ containsInsensitive: () => createOperator((key, value, values) => `${key} ILIKE '%' || ${quoteValue(value, values)} || '%'`),
162
+ startsWith: () => createOperator((key, value, values) => `${key} LIKE ${quoteValue(value, values)} || '%'`),
163
+ startsWithInsensitive: () => createOperator((key, value, values) => `${key} ILIKE ${quoteValue(value, values)} || '%'`),
164
+ endsWith: () => createOperator((key, value, values) => `${key} LIKE '%' || ${quoteValue(value, values)}`),
165
+ endsWithInsensitive: () => createOperator((key, value, values) => `${key} ILIKE '%' || ${quoteValue(value, values)}`),
166
+ between: () => createOperator((key, [from, to], values) => `${key} BETWEEN ${quoteValue(from, values)} AND ${quoteValue(to, values)}`),
167
+ jsonPath: () => createOperator((key, [path, op, value], values) => `jsonb_path_query_first(${key}, ${quote(path)}) #>> '{}' ${op} ${quoteValue(value, values, true)}`),
168
+ jsonSupersetOf: () => createOperator((key, value, values) => `${key} @> ${quoteValue(value, values, true)}`),
169
+ jsonSubsetOf: () => createOperator((key, value, values) => `${key} <@ ${quoteValue(value, values, true)}`)
170
+ };
171
+ const base = () => ({
172
+ equals: all.equals(),
173
+ not: all.not(),
174
+ in: all.in(),
175
+ notIn: all.notIn()
176
+ });
177
+ const numeric = () => __spreadProps$h(__spreadValues$m({}, base()), {
178
+ lt: all.lt(),
179
+ lte: all.lte(),
180
+ gt: all.gt(),
181
+ gte: all.gte(),
182
+ between: all.between()
183
+ });
184
+ const text = () => __spreadProps$h(__spreadValues$m({}, base()), {
185
+ contains: all.contains(),
186
+ containsInsensitive: all.containsInsensitive(),
187
+ startsWith: all.startsWith(),
188
+ startsWithInsensitive: all.startsWithInsensitive(),
189
+ endsWith: all.endsWith(),
190
+ endsWithInsensitive: all.endsWithInsensitive()
191
+ });
192
+ const json = () => __spreadProps$h(__spreadValues$m({}, base()), {
193
+ jsonPath: all.jsonPath(),
194
+ jsonSupersetOf: all.jsonSupersetOf(),
195
+ jsonSubsetOf: all.jsonSubsetOf()
196
+ });
197
+ const Operators = {
198
+ any: base(),
199
+ boolean: base(),
200
+ number: numeric(),
201
+ date: numeric(),
202
+ time: numeric(),
203
+ text: text(),
204
+ json: json(),
205
+ array: base()
206
+ };
207
+
208
+ var __defProp$l = Object.defineProperty;
209
+ var __getOwnPropSymbols$m = Object.getOwnPropertySymbols;
210
+ var __hasOwnProp$m = Object.prototype.hasOwnProperty;
211
+ var __propIsEnum$m = Object.prototype.propertyIsEnumerable;
212
+ var __defNormalProp$l = (obj, key, value) => key in obj ? __defProp$l(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
213
+ var __spreadValues$l = (a, b) => {
214
+ for (var prop in b || (b = {}))
215
+ if (__hasOwnProp$m.call(b, prop))
216
+ __defNormalProp$l(a, prop, b[prop]);
217
+ if (__getOwnPropSymbols$m)
218
+ for (var prop of __getOwnPropSymbols$m(b)) {
219
+ if (__propIsEnum$m.call(b, prop))
220
+ __defNormalProp$l(a, prop, b[prop]);
221
+ }
222
+ return a;
223
+ };
224
+ function applyMixins(derivedCtor, constructors) {
225
+ constructors.forEach((baseCtor) => {
226
+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
227
+ Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || /* @__PURE__ */ Object.create(null));
228
+ });
229
+ });
230
+ }
231
+ const joinTruthy = (...strings) => {
232
+ return strings.filter((string) => string).join("");
233
+ };
234
+ const getClonedQueryData = (query) => {
235
+ const cloned = __spreadValues$l({}, query);
236
+ for (const key in query) {
237
+ if (Array.isArray(query[key])) {
238
+ cloned[key] = [
239
+ ...query[key]
240
+ ];
241
+ }
242
+ }
243
+ return cloned;
244
+ };
245
+ const getQueryAs = (q) => {
246
+ return q.query.as || q.table;
247
+ };
248
+ const toArray = (item) => Array.isArray(item) ? item : [item];
249
+ const noop = () => {
250
+ };
251
+
252
+ const cloneInstance = (instance) => {
253
+ return Object.assign(Object.create(Object.getPrototypeOf(instance)), instance);
254
+ };
255
+ const assignMethodsToClass = (klass, methods) => {
256
+ for (const name in methods) {
257
+ Object.defineProperty(klass.prototype, name, {
258
+ configurable: true,
259
+ enumerable: false,
260
+ writable: true,
261
+ value(...args) {
262
+ const cloned = cloneInstance(this);
263
+ return methods[name].call(cloned, args);
264
+ }
265
+ });
266
+ }
267
+ };
268
+
269
+ var utils = /*#__PURE__*/Object.freeze({
270
+ __proto__: null,
271
+ cloneInstance: cloneInstance,
272
+ assignMethodsToClass: assignMethodsToClass
273
+ });
274
+
275
+ var __defProp$k = Object.defineProperty;
276
+ var __defProps$g = Object.defineProperties;
277
+ var __getOwnPropDescs$g = Object.getOwnPropertyDescriptors;
278
+ var __getOwnPropSymbols$l = Object.getOwnPropertySymbols;
279
+ var __hasOwnProp$l = Object.prototype.hasOwnProperty;
280
+ var __propIsEnum$l = Object.prototype.propertyIsEnumerable;
281
+ var __defNormalProp$k = (obj, key, value) => key in obj ? __defProp$k(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
282
+ var __spreadValues$k = (a, b) => {
283
+ for (var prop in b || (b = {}))
284
+ if (__hasOwnProp$l.call(b, prop))
285
+ __defNormalProp$k(a, prop, b[prop]);
286
+ if (__getOwnPropSymbols$l)
287
+ for (var prop of __getOwnPropSymbols$l(b)) {
288
+ if (__propIsEnum$l.call(b, prop))
289
+ __defNormalProp$k(a, prop, b[prop]);
290
+ }
291
+ return a;
292
+ };
293
+ var __spreadProps$g = (a, b) => __defProps$g(a, __getOwnPropDescs$g(b));
294
+ const arrayMethods = {
295
+ min(value) {
296
+ this.data.min = value;
297
+ return this;
298
+ },
299
+ max(value) {
300
+ this.data.max = value;
301
+ return this;
302
+ },
303
+ length(value) {
304
+ this.data.length = value;
305
+ return this;
306
+ }
307
+ };
308
+ const stringTypeMethods = () => __spreadProps$g(__spreadValues$k({}, arrayMethods), {
309
+ email() {
310
+ this.data.email = true;
311
+ return this;
312
+ },
313
+ url() {
314
+ this.data.url = true;
315
+ return this;
316
+ },
317
+ uuid() {
318
+ this.data.uuid = true;
319
+ return this;
320
+ },
321
+ cuid() {
322
+ this.data.cuid = true;
323
+ return this;
324
+ },
325
+ regex(value) {
326
+ this.data.regex = value;
327
+ return this;
328
+ },
329
+ trim() {
330
+ this.data.trim = true;
331
+ return this;
332
+ }
333
+ });
334
+ const numberTypeMethods = () => ({
335
+ lt(value) {
336
+ this.data.lt = value;
337
+ return this;
338
+ },
339
+ lte(value) {
340
+ this.data.lte = value;
341
+ return this;
342
+ },
343
+ max(value) {
344
+ this.data.lte = value;
345
+ return this;
346
+ },
347
+ gt(value) {
348
+ this.data.gt = value;
349
+ return this;
350
+ },
351
+ gte(value) {
352
+ this.data.gte = value;
353
+ return this;
354
+ },
355
+ min(value) {
356
+ this.data.gte = value;
357
+ return this;
358
+ },
359
+ positive() {
360
+ this.data.gt = 0;
361
+ return this;
362
+ },
363
+ nonNegative() {
364
+ this.data.gte = 0;
365
+ return this;
366
+ },
367
+ negative() {
368
+ this.data.lt = 0;
369
+ return this;
370
+ },
371
+ nonPositive() {
372
+ this.data.lte = 0;
373
+ return this;
374
+ },
375
+ multipleOf(value) {
376
+ this.data.multipleOf = value;
377
+ return this;
378
+ },
379
+ step(value) {
380
+ this.data.multipleOf = value;
381
+ return this;
382
+ }
383
+ });
384
+
385
+ const numberMethods$1 = numberTypeMethods();
386
+ class NumberBaseColumn extends ColumnType {
387
+ constructor() {
388
+ super(...arguments);
389
+ this.data = {};
390
+ this.operators = Operators.number;
391
+ }
392
+ }
393
+ assignMethodsToClass(NumberBaseColumn, numberMethods$1);
394
+ class DecimalBaseColumn extends NumberBaseColumn {
395
+ constructor(precision, scale) {
396
+ super();
397
+ this.dataType = "decimal";
398
+ this.data = {
399
+ precision,
400
+ scale
401
+ };
402
+ }
403
+ toSQL() {
404
+ const { precision, scale } = this.data;
405
+ return joinTruthy(this.dataType, precision ? scale ? `(${precision}, ${scale})` : `(${precision})` : void 0);
406
+ }
407
+ }
408
+ class SmallIntColumn extends NumberBaseColumn {
409
+ constructor() {
410
+ super(...arguments);
411
+ this.dataType = "smallint";
412
+ }
413
+ }
414
+ class IntegerColumn extends NumberBaseColumn {
415
+ constructor() {
416
+ super(...arguments);
417
+ this.dataType = "integer";
418
+ }
419
+ }
420
+ class BigIntColumn extends NumberBaseColumn {
421
+ constructor() {
422
+ super(...arguments);
423
+ this.dataType = "bigint";
424
+ }
425
+ }
426
+ class DecimalColumn extends DecimalBaseColumn {
427
+ }
428
+ class DecimalBigIntColumn extends DecimalBaseColumn {
429
+ }
430
+ class RealColumn extends NumberBaseColumn {
431
+ constructor() {
432
+ super(...arguments);
433
+ this.dataType = "real";
434
+ }
435
+ }
436
+ class DoublePrecisionColumn extends NumberBaseColumn {
437
+ constructor() {
438
+ super(...arguments);
439
+ this.dataType = "double precision";
440
+ }
441
+ }
442
+ class SmallSerialColumn extends NumberBaseColumn {
443
+ constructor() {
444
+ super(...arguments);
445
+ this.dataType = "smallserial";
446
+ }
447
+ }
448
+ class SerialColumn extends NumberBaseColumn {
449
+ constructor() {
450
+ super(...arguments);
451
+ this.dataType = "serial";
452
+ }
453
+ }
454
+ class BigSerialColumn extends NumberBaseColumn {
455
+ constructor() {
456
+ super(...arguments);
457
+ this.dataType = "bigserial";
458
+ }
459
+ }
460
+
461
+ const textMethods = stringTypeMethods();
462
+ class TextBaseColumn extends ColumnType {
463
+ constructor() {
464
+ super(...arguments);
465
+ this.data = {};
466
+ this.operators = Operators.text;
467
+ }
468
+ }
469
+ assignMethodsToClass(TextBaseColumn, textMethods);
470
+ class LimitedTextBaseColumn extends TextBaseColumn {
471
+ constructor(limit) {
472
+ super();
473
+ this.data = { max: limit };
474
+ }
475
+ toSQL() {
476
+ return joinTruthy(this.dataType, this.data.max !== void 0 && `(${this.data.max})`);
477
+ }
478
+ }
479
+ class VarCharColumn extends LimitedTextBaseColumn {
480
+ constructor() {
481
+ super(...arguments);
482
+ this.dataType = "varchar";
483
+ }
484
+ }
485
+ class CharColumn extends LimitedTextBaseColumn {
486
+ constructor() {
487
+ super(...arguments);
488
+ this.dataType = "char";
489
+ }
490
+ }
491
+ class TextColumn extends ColumnType {
492
+ constructor() {
493
+ super(...arguments);
494
+ this.dataType = "text";
495
+ this.operators = Operators.text;
496
+ }
497
+ }
498
+ class ByteaColumn extends NumberBaseColumn {
499
+ constructor() {
500
+ super(...arguments);
501
+ this.dataType = "bytea";
502
+ }
503
+ }
504
+ class PointColumn extends ColumnType {
505
+ constructor() {
506
+ super(...arguments);
507
+ this.dataType = "point";
508
+ this.operators = Operators.text;
509
+ }
510
+ }
511
+ class LineColumn extends ColumnType {
512
+ constructor() {
513
+ super(...arguments);
514
+ this.dataType = "point";
515
+ this.operators = Operators.text;
516
+ }
517
+ }
518
+ class LsegColumn extends ColumnType {
519
+ constructor() {
520
+ super(...arguments);
521
+ this.dataType = "point";
522
+ this.operators = Operators.text;
523
+ }
524
+ }
525
+ class BoxColumn extends ColumnType {
526
+ constructor() {
527
+ super(...arguments);
528
+ this.dataType = "point";
529
+ this.operators = Operators.text;
530
+ }
531
+ }
532
+ class PathColumn extends ColumnType {
533
+ constructor() {
534
+ super(...arguments);
535
+ this.dataType = "point";
536
+ this.operators = Operators.text;
537
+ }
538
+ }
539
+ class PolygonColumn extends ColumnType {
540
+ constructor() {
541
+ super(...arguments);
542
+ this.dataType = "point";
543
+ this.operators = Operators.text;
544
+ }
545
+ }
546
+ class CircleColumn extends ColumnType {
547
+ constructor() {
548
+ super(...arguments);
549
+ this.dataType = "point";
550
+ this.operators = Operators.text;
551
+ }
552
+ }
553
+ class MoneyColumn extends NumberBaseColumn {
554
+ constructor() {
555
+ super(...arguments);
556
+ this.dataType = "money";
557
+ }
558
+ }
559
+ class CidrColumn extends ColumnType {
560
+ constructor() {
561
+ super(...arguments);
562
+ this.dataType = "cidr";
563
+ this.operators = Operators.text;
564
+ }
565
+ }
566
+ class InetColumn extends ColumnType {
567
+ constructor() {
568
+ super(...arguments);
569
+ this.dataType = "inet";
570
+ this.operators = Operators.text;
571
+ }
572
+ }
573
+ class MacAddrColumn extends ColumnType {
574
+ constructor() {
575
+ super(...arguments);
576
+ this.dataType = "macaddr";
577
+ this.operators = Operators.text;
578
+ }
579
+ }
580
+ class MacAddr8Column extends ColumnType {
581
+ constructor() {
582
+ super(...arguments);
583
+ this.dataType = "macaddr8";
584
+ this.operators = Operators.text;
585
+ }
586
+ }
587
+ class BitColumn extends ColumnType {
588
+ constructor(length) {
589
+ super();
590
+ this.dataType = "bit";
591
+ this.operators = Operators.text;
592
+ this.data = { length };
593
+ }
594
+ toSQL() {
595
+ return joinTruthy(this.dataType, this.data.length && `(${this.data.length})`);
596
+ }
597
+ }
598
+ class BitVaryingColumn extends ColumnType {
599
+ constructor(length) {
600
+ super();
601
+ this.dataType = "bit varying";
602
+ this.operators = Operators.text;
603
+ this.data = { length };
604
+ }
605
+ toSQL() {
606
+ return joinTruthy(this.dataType, this.data.length && `(${this.data.length})`);
607
+ }
608
+ }
609
+ class TsVectorColumn extends ColumnType {
610
+ constructor() {
611
+ super(...arguments);
612
+ this.dataType = "tsvector";
613
+ this.operators = Operators.text;
614
+ }
615
+ }
616
+ class TsQueryColumn extends ColumnType {
617
+ constructor() {
618
+ super(...arguments);
619
+ this.dataType = "tsquery";
620
+ this.operators = Operators.text;
621
+ }
622
+ }
623
+ class UUIDColumn extends ColumnType {
624
+ constructor() {
625
+ super(...arguments);
626
+ this.dataType = "uuid";
627
+ this.operators = Operators.text;
628
+ }
629
+ }
630
+ class XMLColumn extends ColumnType {
631
+ constructor() {
632
+ super(...arguments);
633
+ this.dataType = "uuid";
634
+ this.operators = Operators.text;
635
+ }
636
+ }
637
+
638
+ class DateColumn extends ColumnType {
639
+ constructor() {
640
+ super(...arguments);
641
+ this.dataType = "date";
642
+ this.operators = Operators.date;
643
+ }
644
+ }
645
+ class DateTimeBaseClass extends ColumnType {
646
+ constructor(precision) {
647
+ super();
648
+ this.operators = Operators.date;
649
+ this.data = { precision };
650
+ }
651
+ toSQL() {
652
+ return joinTruthy(this.dataType, this.data.precision !== void 0 && `(${this.data.precision})`);
653
+ }
654
+ }
655
+ class DateTimeWithTimeZoneBaseClass extends DateTimeBaseClass {
656
+ toSQL() {
657
+ return joinTruthy(this.baseDataType, this.data.precision !== void 0 && `(${this.data.precision})`, " with time zone");
658
+ }
659
+ }
660
+ class TimestampColumn extends DateTimeBaseClass {
661
+ constructor() {
662
+ super(...arguments);
663
+ this.dataType = "timestamp";
664
+ }
665
+ }
666
+ class TimestampWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
667
+ constructor() {
668
+ super(...arguments);
669
+ this.dataType = "timestamp with time zone";
670
+ this.baseDataType = "timestamp";
671
+ }
672
+ }
673
+ class TimeColumn extends DateTimeBaseClass {
674
+ constructor() {
675
+ super(...arguments);
676
+ this.dataType = "time";
677
+ }
678
+ }
679
+ class TimeWithTimeZoneColumn extends DateTimeWithTimeZoneBaseClass {
680
+ constructor() {
681
+ super(...arguments);
682
+ this.dataType = "time with time zone";
683
+ this.baseDataType = "time";
684
+ }
685
+ }
686
+ class IntervalColumn extends ColumnType {
687
+ constructor(fields, precision) {
688
+ super();
689
+ this.dataType = "interval";
690
+ this.operators = Operators.date;
691
+ this.data = { fields, precision };
692
+ }
693
+ toSQL() {
694
+ return joinTruthy(this.dataType, this.data.fields && ` ${this.data.fields}`, this.data.precision !== void 0 && ` (${this.data.precision})`);
695
+ }
696
+ }
697
+
698
+ class BooleanColumn extends ColumnType {
699
+ constructor() {
700
+ super(...arguments);
701
+ this.dataType = "boolean";
702
+ this.operators = Operators.boolean;
703
+ }
704
+ }
705
+
706
+ class EnumColumn extends ColumnType {
707
+ constructor(dataType) {
708
+ super();
709
+ this.dataType = dataType;
710
+ this.operators = Operators.any;
711
+ }
712
+ }
713
+
714
+ var __defProp$j = Object.defineProperty;
715
+ var __defProps$f = Object.defineProperties;
716
+ var __getOwnPropDescs$f = Object.getOwnPropertyDescriptors;
717
+ var __getOwnPropSymbols$k = Object.getOwnPropertySymbols;
718
+ var __hasOwnProp$k = Object.prototype.hasOwnProperty;
719
+ var __propIsEnum$k = Object.prototype.propertyIsEnumerable;
720
+ var __defNormalProp$j = (obj, key, value) => key in obj ? __defProp$j(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
721
+ var __spreadValues$j = (a, b) => {
722
+ for (var prop in b || (b = {}))
723
+ if (__hasOwnProp$k.call(b, prop))
724
+ __defNormalProp$j(a, prop, b[prop]);
725
+ if (__getOwnPropSymbols$k)
726
+ for (var prop of __getOwnPropSymbols$k(b)) {
727
+ if (__propIsEnum$k.call(b, prop))
728
+ __defNormalProp$j(a, prop, b[prop]);
729
+ }
730
+ return a;
731
+ };
732
+ var __spreadProps$f = (a, b) => __defProps$f(a, __getOwnPropDescs$f(b));
733
+ var __objRest$4 = (source, exclude) => {
734
+ var target = {};
735
+ for (var prop in source)
736
+ if (__hasOwnProp$k.call(source, prop) && exclude.indexOf(prop) < 0)
737
+ target[prop] = source[prop];
738
+ if (source != null && __getOwnPropSymbols$k)
739
+ for (var prop of __getOwnPropSymbols$k(source)) {
740
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$k.call(source, prop))
741
+ target[prop] = source[prop];
742
+ }
743
+ return target;
744
+ };
745
+ const optional = (type) => {
746
+ return __spreadProps$f(__spreadValues$j({}, type), {
747
+ data: __spreadProps$f(__spreadValues$j({}, type.data), { optional: true })
748
+ });
749
+ };
750
+ const required = (type) => {
751
+ const _a = type.data, data = __objRest$4(_a, ["optional"]);
752
+ return __spreadProps$f(__spreadValues$j({}, type), {
753
+ data
754
+ });
755
+ };
756
+
757
+ var __defProp$i = Object.defineProperty;
758
+ var __defProps$e = Object.defineProperties;
759
+ var __getOwnPropDescs$e = Object.getOwnPropertyDescriptors;
760
+ var __getOwnPropSymbols$j = Object.getOwnPropertySymbols;
761
+ var __hasOwnProp$j = Object.prototype.hasOwnProperty;
762
+ var __propIsEnum$j = Object.prototype.propertyIsEnumerable;
763
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
764
+ var __spreadValues$i = (a, b) => {
765
+ for (var prop in b || (b = {}))
766
+ if (__hasOwnProp$j.call(b, prop))
767
+ __defNormalProp$i(a, prop, b[prop]);
768
+ if (__getOwnPropSymbols$j)
769
+ for (var prop of __getOwnPropSymbols$j(b)) {
770
+ if (__propIsEnum$j.call(b, prop))
771
+ __defNormalProp$i(a, prop, b[prop]);
772
+ }
773
+ return a;
774
+ };
775
+ var __spreadProps$e = (a, b) => __defProps$e(a, __getOwnPropDescs$e(b));
776
+ var __objRest$3 = (source, exclude) => {
777
+ var target = {};
778
+ for (var prop in source)
779
+ if (__hasOwnProp$j.call(source, prop) && exclude.indexOf(prop) < 0)
780
+ target[prop] = source[prop];
781
+ if (source != null && __getOwnPropSymbols$j)
782
+ for (var prop of __getOwnPropSymbols$j(source)) {
783
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$j.call(source, prop))
784
+ target[prop] = source[prop];
785
+ }
786
+ return target;
787
+ };
788
+ const nullable = (type) => {
789
+ return __spreadProps$e(__spreadValues$i({}, type), {
790
+ data: __spreadProps$e(__spreadValues$i({}, type.data), { nullable: true })
791
+ });
792
+ };
793
+ const notNullable = (type) => {
794
+ const _a = type.data, data = __objRest$3(_a, ["nullable"]);
795
+ return __spreadProps$e(__spreadValues$i({}, type), {
796
+ data
797
+ });
798
+ };
799
+
800
+ var __defProp$h = Object.defineProperty;
801
+ var __defProps$d = Object.defineProperties;
802
+ var __getOwnPropDescs$d = Object.getOwnPropertyDescriptors;
803
+ var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
804
+ var __hasOwnProp$i = Object.prototype.hasOwnProperty;
805
+ var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
806
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
807
+ var __spreadValues$h = (a, b) => {
808
+ for (var prop in b || (b = {}))
809
+ if (__hasOwnProp$i.call(b, prop))
810
+ __defNormalProp$h(a, prop, b[prop]);
811
+ if (__getOwnPropSymbols$i)
812
+ for (var prop of __getOwnPropSymbols$i(b)) {
813
+ if (__propIsEnum$i.call(b, prop))
814
+ __defNormalProp$h(a, prop, b[prop]);
815
+ }
816
+ return a;
817
+ };
818
+ var __spreadProps$d = (a, b) => __defProps$d(a, __getOwnPropDescs$d(b));
819
+ var __objRest$2 = (source, exclude) => {
820
+ var target = {};
821
+ for (var prop in source)
822
+ if (__hasOwnProp$i.call(source, prop) && exclude.indexOf(prop) < 0)
823
+ target[prop] = source[prop];
824
+ if (source != null && __getOwnPropSymbols$i)
825
+ for (var prop of __getOwnPropSymbols$i(source)) {
826
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$i.call(source, prop))
827
+ target[prop] = source[prop];
828
+ }
829
+ return target;
830
+ };
831
+ const nullish = (type) => {
832
+ return __spreadProps$d(__spreadValues$h({}, type), {
833
+ data: __spreadProps$d(__spreadValues$h({}, type.data), { nullable: true, optional: true })
834
+ });
835
+ };
836
+ const notNullish = (type) => {
837
+ const _a = type.data, data = __objRest$2(_a, ["nullable", "optional"]);
838
+ return __spreadProps$d(__spreadValues$h({}, type), {
839
+ data
840
+ });
841
+ };
842
+
843
+ const intersection = (left, right) => {
844
+ return constructType({
845
+ dataType: "intersection",
846
+ left,
847
+ right
848
+ });
849
+ };
850
+
851
+ var __defProp$g = Object.defineProperty;
852
+ var __defProps$c = Object.defineProperties;
853
+ var __getOwnPropDescs$c = Object.getOwnPropertyDescriptors;
854
+ var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
855
+ var __hasOwnProp$h = Object.prototype.hasOwnProperty;
856
+ var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
857
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
858
+ var __spreadValues$g = (a, b) => {
859
+ for (var prop in b || (b = {}))
860
+ if (__hasOwnProp$h.call(b, prop))
861
+ __defNormalProp$g(a, prop, b[prop]);
862
+ if (__getOwnPropSymbols$h)
863
+ for (var prop of __getOwnPropSymbols$h(b)) {
864
+ if (__propIsEnum$h.call(b, prop))
865
+ __defNormalProp$g(a, prop, b[prop]);
866
+ }
867
+ return a;
868
+ };
869
+ var __spreadProps$c = (a, b) => __defProps$c(a, __getOwnPropDescs$c(b));
870
+ const array = (element) => {
871
+ return constructType(__spreadValues$g({
872
+ dataType: "array",
873
+ element,
874
+ deepPartial() {
875
+ return __spreadProps$c(__spreadValues$g({}, this), {
876
+ element: this.element.deepPartial()
877
+ });
878
+ },
879
+ nonEmpty() {
880
+ return this.min(1);
881
+ }
882
+ }, arrayMethods));
883
+ };
884
+
885
+ const union = (types) => {
886
+ return constructType({
887
+ dataType: "union",
888
+ types
889
+ });
890
+ };
891
+
892
+ var __defProp$f = Object.defineProperty;
893
+ var __defProps$b = Object.defineProperties;
894
+ var __getOwnPropDescs$b = Object.getOwnPropertyDescriptors;
895
+ var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
896
+ var __hasOwnProp$g = Object.prototype.hasOwnProperty;
897
+ var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
898
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
899
+ var __spreadValues$f = (a, b) => {
900
+ for (var prop in b || (b = {}))
901
+ if (__hasOwnProp$g.call(b, prop))
902
+ __defNormalProp$f(a, prop, b[prop]);
903
+ if (__getOwnPropSymbols$g)
904
+ for (var prop of __getOwnPropSymbols$g(b)) {
905
+ if (__propIsEnum$g.call(b, prop))
906
+ __defNormalProp$f(a, prop, b[prop]);
907
+ }
908
+ return a;
909
+ };
910
+ var __spreadProps$b = (a, b) => __defProps$b(a, __getOwnPropDescs$b(b));
911
+ const baseTypeMethods = {
912
+ type: void 0,
913
+ data: {},
914
+ dataType: "any",
915
+ chain: [],
916
+ optional() {
917
+ return optional(this);
918
+ },
919
+ required() {
920
+ return required(this);
921
+ },
922
+ nullable() {
923
+ return nullable(this);
924
+ },
925
+ notNullable() {
926
+ return notNullable(this);
927
+ },
928
+ nullish() {
929
+ return nullish(this);
930
+ },
931
+ notNullish() {
932
+ return notNullish(this);
933
+ },
934
+ deepPartial() {
935
+ return this;
936
+ },
937
+ transform(fn) {
938
+ return __spreadProps$b(__spreadValues$f({}, this), {
939
+ chain: [...this.chain, ["transform", fn]]
940
+ });
941
+ },
942
+ to(fn, type) {
943
+ return __spreadProps$b(__spreadValues$f({}, type), {
944
+ chain: [...this.chain, ["to", fn, type], ...type.chain]
945
+ });
946
+ },
947
+ refine(check) {
948
+ return __spreadProps$b(__spreadValues$f({}, this), {
949
+ chain: [...this.chain, ["refine", check]]
950
+ });
951
+ },
952
+ superRefine(check) {
953
+ return __spreadProps$b(__spreadValues$f({}, this), {
954
+ chain: [...this.chain, ["superRefine", check]]
955
+ });
956
+ },
957
+ and(type) {
958
+ return intersection(this, type);
959
+ },
960
+ or(...args) {
961
+ const [type, ...types] = args;
962
+ return union([this, type, ...types]);
963
+ },
964
+ default(value) {
965
+ const defaultFn = typeof value === "function" ? (input) => input != null ? input : value() : (input) => input != null ? input : value;
966
+ return notNullish(__spreadProps$b(__spreadValues$f({}, this), {
967
+ chain: ["transform", defaultFn]
968
+ }));
969
+ },
970
+ array() {
971
+ return array(this);
972
+ }
973
+ };
974
+ const constructType = (type) => {
975
+ return __spreadValues$f(__spreadValues$f({}, baseTypeMethods), type);
976
+ };
977
+
978
+ var __defProp$e = Object.defineProperty;
979
+ var __defProps$a = Object.defineProperties;
980
+ var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
981
+ var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
982
+ var __hasOwnProp$f = Object.prototype.hasOwnProperty;
983
+ var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
984
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
985
+ var __spreadValues$e = (a, b) => {
986
+ for (var prop in b || (b = {}))
987
+ if (__hasOwnProp$f.call(b, prop))
988
+ __defNormalProp$e(a, prop, b[prop]);
989
+ if (__getOwnPropSymbols$f)
990
+ for (var prop of __getOwnPropSymbols$f(b)) {
991
+ if (__propIsEnum$f.call(b, prop))
992
+ __defNormalProp$e(a, prop, b[prop]);
993
+ }
994
+ return a;
995
+ };
996
+ var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
997
+ const any = () => {
998
+ return constructType({
999
+ dataType: "any"
1000
+ });
1001
+ };
1002
+ const bigIntMethods = __spreadValues$e({
1003
+ dataType: "bigint"
1004
+ }, numberTypeMethods());
1005
+ const bigint = () => {
1006
+ return constructType(bigIntMethods);
1007
+ };
1008
+ const boolean = () => {
1009
+ return constructType({
1010
+ dataType: "boolean"
1011
+ });
1012
+ };
1013
+ const nan = () => {
1014
+ return constructType({
1015
+ dataType: "nan"
1016
+ });
1017
+ };
1018
+ const never = () => {
1019
+ return constructType({
1020
+ dataType: "never"
1021
+ });
1022
+ };
1023
+ const nullType = () => {
1024
+ return constructType({
1025
+ dataType: "null"
1026
+ });
1027
+ };
1028
+ const numberMethods = __spreadProps$a(__spreadValues$e({}, numberTypeMethods()), {
1029
+ dataType: "number"
1030
+ });
1031
+ const number = () => {
1032
+ return constructType(numberMethods);
1033
+ };
1034
+ const date = () => {
1035
+ return constructType({
1036
+ dataType: "date"
1037
+ });
1038
+ };
1039
+ const stringMethods = __spreadProps$a(__spreadValues$e({}, stringTypeMethods()), {
1040
+ dataType: "string"
1041
+ });
1042
+ const string = () => {
1043
+ return constructType(stringMethods);
1044
+ };
1045
+ const undefinedType = () => {
1046
+ return constructType({
1047
+ dataType: "undefined"
1048
+ });
1049
+ };
1050
+ const unknown = () => {
1051
+ return constructType({
1052
+ dataType: "unknown"
1053
+ });
1054
+ };
1055
+ const voidType = () => {
1056
+ return constructType({
1057
+ dataType: "void"
1058
+ });
1059
+ };
1060
+ const scalarTypes = {
1061
+ any,
1062
+ bigint,
1063
+ boolean,
1064
+ date,
1065
+ nan,
1066
+ never,
1067
+ null: nullType,
1068
+ number,
1069
+ string,
1070
+ undefined: undefinedType,
1071
+ unknown,
1072
+ void: voidType
1073
+ };
1074
+
1075
+ var __defProp$d = Object.defineProperty;
1076
+ var __defProps$9 = Object.defineProperties;
1077
+ var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
1078
+ var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
1079
+ var __hasOwnProp$e = Object.prototype.hasOwnProperty;
1080
+ var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
1081
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1082
+ var __spreadValues$d = (a, b) => {
1083
+ for (var prop in b || (b = {}))
1084
+ if (__hasOwnProp$e.call(b, prop))
1085
+ __defNormalProp$d(a, prop, b[prop]);
1086
+ if (__getOwnPropSymbols$e)
1087
+ for (var prop of __getOwnPropSymbols$e(b)) {
1088
+ if (__propIsEnum$e.call(b, prop))
1089
+ __defNormalProp$d(a, prop, b[prop]);
1090
+ }
1091
+ return a;
1092
+ };
1093
+ var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
1094
+ const discriminatedUnion = (discriminator, options) => {
1095
+ const optionsMap = /* @__PURE__ */ new Map();
1096
+ options.forEach((option) => {
1097
+ const discriminatorValue = option.shape[discriminator].value;
1098
+ optionsMap.set(discriminatorValue, option);
1099
+ });
1100
+ return constructType({
1101
+ dataType: "discriminatedUnion",
1102
+ discriminator,
1103
+ options: optionsMap,
1104
+ deepPartial() {
1105
+ const newOptionsMap = /* @__PURE__ */ new Map();
1106
+ optionsMap.forEach((option, key) => {
1107
+ const partial = option.deepPartial();
1108
+ partial.shape[discriminator] = option.shape[discriminator];
1109
+ newOptionsMap.set(key, partial);
1110
+ });
1111
+ return __spreadProps$9(__spreadValues$d({}, this), {
1112
+ options: newOptionsMap
1113
+ });
1114
+ }
1115
+ });
1116
+ };
1117
+
1118
+ const arrayToEnum = (items) => {
1119
+ const obj = {};
1120
+ for (const item of items) {
1121
+ obj[item] = item;
1122
+ }
1123
+ return obj;
1124
+ };
1125
+ const enumType = (options) => {
1126
+ return constructType({
1127
+ dataType: "enum",
1128
+ enum: arrayToEnum(options),
1129
+ options
1130
+ });
1131
+ };
1132
+
1133
+ const instanceOf = (cls) => {
1134
+ return constructType({
1135
+ dataType: "instanceOf",
1136
+ class: cls
1137
+ });
1138
+ };
1139
+
1140
+ var __defProp$c = Object.defineProperty;
1141
+ var __defProps$8 = Object.defineProperties;
1142
+ var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
1143
+ var __getOwnPropSymbols$d = Object.getOwnPropertySymbols;
1144
+ var __hasOwnProp$d = Object.prototype.hasOwnProperty;
1145
+ var __propIsEnum$d = Object.prototype.propertyIsEnumerable;
1146
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1147
+ var __spreadValues$c = (a, b) => {
1148
+ for (var prop in b || (b = {}))
1149
+ if (__hasOwnProp$d.call(b, prop))
1150
+ __defNormalProp$c(a, prop, b[prop]);
1151
+ if (__getOwnPropSymbols$d)
1152
+ for (var prop of __getOwnPropSymbols$d(b)) {
1153
+ if (__propIsEnum$d.call(b, prop))
1154
+ __defNormalProp$c(a, prop, b[prop]);
1155
+ }
1156
+ return a;
1157
+ };
1158
+ var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
1159
+ const lazy = (fn) => {
1160
+ constructType({
1161
+ dataType: "lazy",
1162
+ getter: fn,
1163
+ deepPartial() {
1164
+ return __spreadProps$8(__spreadValues$c({}, this), {
1165
+ typeCache: void 0,
1166
+ getter: () => this.getter().deepPartial()
1167
+ });
1168
+ }
1169
+ });
1170
+ };
1171
+
1172
+ const literal = (value) => constructType({
1173
+ dataType: "literal",
1174
+ value
1175
+ });
1176
+
1177
+ var __defProp$b = Object.defineProperty;
1178
+ var __defProps$7 = Object.defineProperties;
1179
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
1180
+ var __getOwnPropSymbols$c = Object.getOwnPropertySymbols;
1181
+ var __hasOwnProp$c = Object.prototype.hasOwnProperty;
1182
+ var __propIsEnum$c = Object.prototype.propertyIsEnumerable;
1183
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1184
+ var __spreadValues$b = (a, b) => {
1185
+ for (var prop in b || (b = {}))
1186
+ if (__hasOwnProp$c.call(b, prop))
1187
+ __defNormalProp$b(a, prop, b[prop]);
1188
+ if (__getOwnPropSymbols$c)
1189
+ for (var prop of __getOwnPropSymbols$c(b)) {
1190
+ if (__propIsEnum$c.call(b, prop))
1191
+ __defNormalProp$b(a, prop, b[prop]);
1192
+ }
1193
+ return a;
1194
+ };
1195
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
1196
+ const map = (keyType, valueType) => {
1197
+ return constructType({
1198
+ dataType: "map",
1199
+ keyType,
1200
+ valueType,
1201
+ deepPartial() {
1202
+ return __spreadProps$7(__spreadValues$b({}, this), {
1203
+ keyType: this.keyType.deepPartial(),
1204
+ valueType: this.valueType.deepPartial()
1205
+ });
1206
+ }
1207
+ });
1208
+ };
1209
+
1210
+ const getValidEnumValues = (obj) => {
1211
+ const values = [];
1212
+ Object.keys(obj).forEach((k) => {
1213
+ if (typeof obj[obj[k]] !== "number" && !values.includes(obj[k])) {
1214
+ values.push(obj[k]);
1215
+ }
1216
+ });
1217
+ return values;
1218
+ };
1219
+ const nativeEnum = (givenEnum) => {
1220
+ const options = getValidEnumValues(givenEnum);
1221
+ return constructType({
1222
+ dataType: "nativeEnum",
1223
+ enum: givenEnum,
1224
+ options
1225
+ });
1226
+ };
1227
+
1228
+ var __defProp$a = Object.defineProperty;
1229
+ var __defProps$6 = Object.defineProperties;
1230
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1231
+ var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
1232
+ var __hasOwnProp$b = Object.prototype.hasOwnProperty;
1233
+ var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
1234
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1235
+ var __spreadValues$a = (a, b) => {
1236
+ for (var prop in b || (b = {}))
1237
+ if (__hasOwnProp$b.call(b, prop))
1238
+ __defNormalProp$a(a, prop, b[prop]);
1239
+ if (__getOwnPropSymbols$b)
1240
+ for (var prop of __getOwnPropSymbols$b(b)) {
1241
+ if (__propIsEnum$b.call(b, prop))
1242
+ __defNormalProp$a(a, prop, b[prop]);
1243
+ }
1244
+ return a;
1245
+ };
1246
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
1247
+ const object = (shape) => {
1248
+ return constructType({
1249
+ dataType: "object",
1250
+ shape,
1251
+ unknownKeys: "strip",
1252
+ catchAllType: void 0,
1253
+ extend(add) {
1254
+ return object(Object.assign(__spreadValues$a({}, this.shape), add));
1255
+ },
1256
+ merge(obj) {
1257
+ return object(Object.assign(__spreadValues$a({}, this.shape), obj.shape));
1258
+ },
1259
+ pick(...arr) {
1260
+ const picked = {};
1261
+ arr.forEach((key) => picked[key] = this.shape[key]);
1262
+ return object(picked);
1263
+ },
1264
+ omit(...arr) {
1265
+ const picked = {};
1266
+ for (const key in this.shape) {
1267
+ if (!arr.includes(key)) {
1268
+ picked[key] = this.shape[key];
1269
+ }
1270
+ }
1271
+ return object(picked);
1272
+ },
1273
+ partial(...arr) {
1274
+ const mapped = __spreadValues$a({}, this.shape);
1275
+ if (arr.length) {
1276
+ arr.forEach((key) => {
1277
+ mapped[key] = mapped[key].optional();
1278
+ });
1279
+ } else {
1280
+ for (const key in mapped) {
1281
+ mapped[key] = mapped[key].optional();
1282
+ }
1283
+ }
1284
+ return object(mapped);
1285
+ },
1286
+ deepPartial() {
1287
+ const newShape = {};
1288
+ for (const key in this.shape) {
1289
+ newShape[key] = optional(this.shape[key].deepPartial());
1290
+ }
1291
+ return __spreadProps$6(__spreadValues$a({}, this), {
1292
+ shape: newShape
1293
+ });
1294
+ },
1295
+ passthrough() {
1296
+ return __spreadProps$6(__spreadValues$a({}, this), {
1297
+ unknownKeys: "passthrough"
1298
+ });
1299
+ },
1300
+ strict() {
1301
+ return __spreadProps$6(__spreadValues$a({}, this), {
1302
+ unknownKeys: "strict"
1303
+ });
1304
+ },
1305
+ strip() {
1306
+ return __spreadProps$6(__spreadValues$a({}, this), {
1307
+ unknownKeys: "strip"
1308
+ });
1309
+ },
1310
+ catchAll(type) {
1311
+ return __spreadProps$6(__spreadValues$a({}, this), {
1312
+ catchAllType: type
1313
+ });
1314
+ }
1315
+ });
1316
+ };
1317
+
1318
+ var __defProp$9 = Object.defineProperty;
1319
+ var __defProps$5 = Object.defineProperties;
1320
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1321
+ var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
1322
+ var __hasOwnProp$a = Object.prototype.hasOwnProperty;
1323
+ var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
1324
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1325
+ var __spreadValues$9 = (a, b) => {
1326
+ for (var prop in b || (b = {}))
1327
+ if (__hasOwnProp$a.call(b, prop))
1328
+ __defNormalProp$9(a, prop, b[prop]);
1329
+ if (__getOwnPropSymbols$a)
1330
+ for (var prop of __getOwnPropSymbols$a(b)) {
1331
+ if (__propIsEnum$a.call(b, prop))
1332
+ __defNormalProp$9(a, prop, b[prop]);
1333
+ }
1334
+ return a;
1335
+ };
1336
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1337
+ function record(...args) {
1338
+ const [keyType, valueType] = args.length === 1 ? [scalarTypes.string(), args[0]] : args;
1339
+ return constructType({
1340
+ dataType: "record",
1341
+ keyType,
1342
+ valueType,
1343
+ deepPartial() {
1344
+ return __spreadProps$5(__spreadValues$9({}, this), {
1345
+ valueType: this.valueType.deepPartial()
1346
+ });
1347
+ }
1348
+ });
1349
+ }
1350
+
1351
+ var __defProp$8 = Object.defineProperty;
1352
+ var __defProps$4 = Object.defineProperties;
1353
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1354
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
1355
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
1356
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
1357
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1358
+ var __spreadValues$8 = (a, b) => {
1359
+ for (var prop in b || (b = {}))
1360
+ if (__hasOwnProp$9.call(b, prop))
1361
+ __defNormalProp$8(a, prop, b[prop]);
1362
+ if (__getOwnPropSymbols$9)
1363
+ for (var prop of __getOwnPropSymbols$9(b)) {
1364
+ if (__propIsEnum$9.call(b, prop))
1365
+ __defNormalProp$8(a, prop, b[prop]);
1366
+ }
1367
+ return a;
1368
+ };
1369
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1370
+ const set = (valueType) => {
1371
+ return constructType(__spreadValues$8({
1372
+ dataType: "set",
1373
+ valueType,
1374
+ deepPartial() {
1375
+ return __spreadProps$4(__spreadValues$8({}, this), {
1376
+ valueType: this.valueType.deepPartial()
1377
+ });
1378
+ },
1379
+ nonEmpty() {
1380
+ return this.min(1);
1381
+ }
1382
+ }, arrayMethods));
1383
+ };
1384
+
1385
+ var __defProp$7 = Object.defineProperty;
1386
+ var __defProps$3 = Object.defineProperties;
1387
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
1388
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
1389
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
1390
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
1391
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1392
+ var __spreadValues$7 = (a, b) => {
1393
+ for (var prop in b || (b = {}))
1394
+ if (__hasOwnProp$8.call(b, prop))
1395
+ __defNormalProp$7(a, prop, b[prop]);
1396
+ if (__getOwnPropSymbols$8)
1397
+ for (var prop of __getOwnPropSymbols$8(b)) {
1398
+ if (__propIsEnum$8.call(b, prop))
1399
+ __defNormalProp$7(a, prop, b[prop]);
1400
+ }
1401
+ return a;
1402
+ };
1403
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
1404
+ const tuple = (items) => {
1405
+ return constructType({
1406
+ dataType: "tuple",
1407
+ items,
1408
+ deepPartial() {
1409
+ return __spreadProps$3(__spreadValues$7({}, this), {
1410
+ items: this.items.map((item) => item.deepPartial())
1411
+ });
1412
+ }
1413
+ });
1414
+ };
1415
+
1416
+ var __defProp$6 = Object.defineProperty;
1417
+ var __defProps$2 = Object.defineProperties;
1418
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1419
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1420
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1421
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1422
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1423
+ var __spreadValues$6 = (a, b) => {
1424
+ for (var prop in b || (b = {}))
1425
+ if (__hasOwnProp$7.call(b, prop))
1426
+ __defNormalProp$6(a, prop, b[prop]);
1427
+ if (__getOwnPropSymbols$7)
1428
+ for (var prop of __getOwnPropSymbols$7(b)) {
1429
+ if (__propIsEnum$7.call(b, prop))
1430
+ __defNormalProp$6(a, prop, b[prop]);
1431
+ }
1432
+ return a;
1433
+ };
1434
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1435
+ const jsonTypes = __spreadProps$2(__spreadValues$6({
1436
+ array,
1437
+ discriminatedUnion,
1438
+ enum: enumType,
1439
+ instanceOf,
1440
+ intersection,
1441
+ lazy,
1442
+ literal,
1443
+ map,
1444
+ nativeEnum,
1445
+ nullable,
1446
+ nullish,
1447
+ object,
1448
+ optional,
1449
+ record
1450
+ }, scalarTypes), {
1451
+ set,
1452
+ tuple,
1453
+ union
1454
+ });
1455
+ class JSONColumn extends ColumnType {
1456
+ constructor(schemaOrFn) {
1457
+ super();
1458
+ this.dataType = "jsonb";
1459
+ this.operators = Operators.json;
1460
+ const schema = typeof schemaOrFn === "function" ? schemaOrFn(jsonTypes) : schemaOrFn;
1461
+ this.data = { schema };
1462
+ }
1463
+ }
1464
+ class JSONTextColumn extends ColumnType {
1465
+ constructor() {
1466
+ super(...arguments);
1467
+ this.dataType = "json";
1468
+ this.operators = Operators.text;
1469
+ }
1470
+ }
1471
+
1472
+ class ArrayColumn extends ColumnType {
1473
+ constructor(item) {
1474
+ super();
1475
+ this.dataType = "array";
1476
+ this.operators = Operators.array;
1477
+ this.data = { item };
1478
+ }
1479
+ toSQL() {
1480
+ return `${this.data.item.toSQL()}[]`;
1481
+ }
1482
+ }
1483
+
1484
+ const columnTypes = {
1485
+ smallint: () => new SmallIntColumn(),
1486
+ integer: () => new IntegerColumn(),
1487
+ bigint: () => new BigIntColumn(),
1488
+ numeric: (precision, scale) => new DecimalColumn(precision, scale),
1489
+ numericBigInt: (precision, scale) => new DecimalBigIntColumn(precision, scale),
1490
+ decimal: (precision, scale) => new DecimalColumn(precision, scale),
1491
+ decimalBigInt: (precision, scale) => new DecimalBigIntColumn(precision, scale),
1492
+ real: () => new RealColumn(),
1493
+ doublePrecision: () => new DoublePrecisionColumn(),
1494
+ smallSerial: () => new SmallSerialColumn(),
1495
+ serial: () => new SerialColumn(),
1496
+ bigserial: () => new BigSerialColumn(),
1497
+ money: () => new MoneyColumn(),
1498
+ varchar: (limit) => new VarCharColumn(limit),
1499
+ char: (limit) => new CharColumn(limit),
1500
+ text: () => new TextColumn(),
1501
+ bytea: () => new ByteaColumn(),
1502
+ date: () => new DateColumn(),
1503
+ timestamp: (precision) => new TimestampColumn(precision),
1504
+ timestampWithTimeZone: (precision) => new TimestampWithTimeZoneColumn(precision),
1505
+ time: (precision) => new TimeColumn(precision),
1506
+ timeWithTimeZone: (precision) => new TimeWithTimeZoneColumn(precision),
1507
+ interval: (fields, precision) => new IntervalColumn(fields, precision),
1508
+ boolean: () => new BooleanColumn(),
1509
+ enum: (dataType) => new EnumColumn(dataType),
1510
+ point: () => new PointColumn(),
1511
+ line: () => new LineColumn(),
1512
+ lseg: () => new LsegColumn(),
1513
+ box: () => new BoxColumn(),
1514
+ path: () => new PathColumn(),
1515
+ polygon: () => new PolygonColumn(),
1516
+ circle: () => new CircleColumn(),
1517
+ cidr() {
1518
+ return new CidrColumn();
1519
+ },
1520
+ inet: () => new InetColumn(),
1521
+ macaddr: () => new MacAddrColumn(),
1522
+ macaddr8: () => new MacAddr8Column(),
1523
+ bit: () => new BitColumn(),
1524
+ bitVarying: () => new BitVaryingColumn(),
1525
+ tsvector: () => new TsVectorColumn(),
1526
+ tsquery: () => new TsQueryColumn(),
1527
+ uuid: () => new UUIDColumn(),
1528
+ xml: () => new XMLColumn(),
1529
+ json: (schemaOrFn) => new JSONColumn(schemaOrFn),
1530
+ jsonText: () => new JSONTextColumn(),
1531
+ array: (item) => new ArrayColumn(item)
1532
+ };
1533
+
1534
+ class ColumnsObject extends ColumnType {
1535
+ constructor(shape) {
1536
+ super();
1537
+ this.shape = shape;
1538
+ this.dataType = "object";
1539
+ this.operators = Operators.any;
1540
+ }
1541
+ }
1542
+ class ArrayOfColumnsObjects extends ColumnType {
1543
+ constructor(shape) {
1544
+ super();
1545
+ this.shape = shape;
1546
+ this.dataType = "array";
1547
+ this.operators = Operators.any;
1548
+ }
1549
+ }
1550
+ class TableSchema {
1551
+ constructor(shape) {
1552
+ this.shape = shape;
1553
+ this.primaryKeys = Object.entries(this.shape).filter(([, column]) => {
1554
+ return column.isPrimaryKey;
1555
+ }).map(([key]) => key);
1556
+ }
1557
+ }
1558
+
1559
+ const pushDistinctSql = (sql, values, distinct, quotedAs) => {
1560
+ sql.push("DISTINCT");
1561
+ if (distinct.length) {
1562
+ const columns = [];
1563
+ distinct == null ? void 0 : distinct.forEach((item) => {
1564
+ columns.push(expressionToSql(item, values, quotedAs));
1565
+ });
1566
+ sql.push(`ON (${columns.join(", ")})`);
1567
+ }
1568
+ };
1569
+
1570
+ const pushOrderBySql = (sql, values, quotedAs, order) => {
1571
+ sql.push(`ORDER BY ${order.map((item) => orderByToSql(item, values, quotedAs)).join(", ")}`);
1572
+ };
1573
+ const orderByToSql = (order, values, quotedAs) => {
1574
+ if (typeof order === "string") {
1575
+ return `${qc(order, quotedAs)} ASC`;
1576
+ }
1577
+ if (isRaw(order)) {
1578
+ return getRaw(order, values);
1579
+ }
1580
+ const sql = [];
1581
+ for (const key in order) {
1582
+ const value = order[key];
1583
+ if (typeof value === "string") {
1584
+ sql.push(`${qc(key, quotedAs)} ${value}`);
1585
+ } else if (value) {
1586
+ sql.push(`${qc(key, quotedAs)} ${value.dir} NULLS ${value.nulls}`);
1587
+ }
1588
+ }
1589
+ return sql.join(", ");
1590
+ };
1591
+
1592
+ const windowToSql = (window, values, quotedAs) => {
1593
+ if (typeof window === "object") {
1594
+ if (isRaw(window)) {
1595
+ return `(${getRaw(window, values)})`;
1596
+ } else {
1597
+ const sql = [];
1598
+ if (window.partitionBy) {
1599
+ sql.push(`PARTITION BY ${Array.isArray(window.partitionBy) ? window.partitionBy.map((partitionBy) => expressionToSql(partitionBy, values, quotedAs)).join(", ") : expressionToSql(window.partitionBy, values, quotedAs)}`);
1600
+ }
1601
+ if (window.order) {
1602
+ sql.push(`ORDER BY ${orderByToSql(window.order, values, quotedAs)}`);
1603
+ }
1604
+ return `(${sql.join(" ")})`;
1605
+ }
1606
+ } else {
1607
+ return q(window);
1608
+ }
1609
+ };
1610
+
1611
+ const processJoinItem = (model, query, values, args, quotedAs) => {
1612
+ var _a;
1613
+ const [first] = args;
1614
+ if (typeof first === "string") {
1615
+ if (first in model.relations) {
1616
+ const { key, joinQuery: joinQuery2 } = model.relations[first];
1617
+ const table = typeof joinQuery2.query.from === "string" ? joinQuery2.query.from : joinQuery2.table;
1618
+ let target3 = quoteSchemaAndTable(joinQuery2.query.schema, table);
1619
+ const as = joinQuery2.query.as || key;
1620
+ if (as !== table) {
1621
+ target3 += ` AS ${q(as)}`;
1622
+ }
1623
+ const queryData = {
1624
+ and: [],
1625
+ or: []
1626
+ };
1627
+ if (joinQuery2.query.and)
1628
+ queryData.and.push(...joinQuery2.query.and);
1629
+ if (joinQuery2.query.or)
1630
+ queryData.or.push(...joinQuery2.query.or);
1631
+ const arg = (_a = args[1]) == null ? void 0 : _a.call(args, new model.onQueryBuilder({ table: model.table, query }, args[0])).query;
1632
+ if (arg) {
1633
+ if (arg.and)
1634
+ queryData.and.push(...arg.and);
1635
+ if (arg.or)
1636
+ queryData.or.push(...arg.or);
1637
+ }
1638
+ const joinAs2 = q(as);
1639
+ const onConditions = whereToSql(joinQuery2, queryData, values, quotedAs, joinAs2);
1640
+ const conditions3 = onConditions ? onConditions : void 0;
1641
+ return { target: target3, conditions: conditions3 };
1642
+ }
1643
+ const target2 = q(first);
1644
+ let conditions2;
1645
+ if (args.length === 2) {
1646
+ const arg = args[1];
1647
+ if (typeof arg === "function") {
1648
+ const joinQuery2 = arg(new model.onQueryBuilder({ table: model.table, query }, args[0]));
1649
+ const onConditions = whereToSql(model, joinQuery2.query, values, quotedAs, target2);
1650
+ if (onConditions)
1651
+ conditions2 = onConditions;
1652
+ } else {
1653
+ conditions2 = getObjectOrRawConditions(arg, values, quotedAs, target2);
1654
+ }
1655
+ } else if (args.length >= 3) {
1656
+ conditions2 = getConditionsFor3Or4LengthItem(target2, values, quotedAs, args);
1657
+ }
1658
+ return { target: target2, conditions: conditions2 };
1659
+ }
1660
+ const joinTarget = first;
1661
+ const joinQuery = joinTarget.query;
1662
+ const quotedFrom = typeof (joinQuery == null ? void 0 : joinQuery.from) === "string" ? q(joinQuery.from) : void 0;
1663
+ let target = quotedFrom || quoteSchemaAndTable(joinQuery == null ? void 0 : joinQuery.schema, joinTarget.table);
1664
+ let joinAs = quotedFrom || q(joinTarget.table);
1665
+ if (joinQuery == null ? void 0 : joinQuery.as) {
1666
+ const quoted = q(joinQuery.as);
1667
+ if (quoted !== joinAs) {
1668
+ joinAs = quoted;
1669
+ target += ` AS ${quoted}`;
1670
+ }
1671
+ }
1672
+ let conditions;
1673
+ if (args.length === 2) {
1674
+ const arg = args[1];
1675
+ if (typeof arg === "function") {
1676
+ const joinQuery2 = arg(new model.onQueryBuilder({ table: model.table, query }, args[0]));
1677
+ const onConditions = whereToSql(model, joinQuery2.query, values, quotedAs, joinAs);
1678
+ if (onConditions)
1679
+ conditions = onConditions;
1680
+ } else {
1681
+ conditions = getObjectOrRawConditions(arg, values, quotedAs, joinAs);
1682
+ }
1683
+ } else if (args.length >= 3) {
1684
+ conditions = getConditionsFor3Or4LengthItem(joinAs, values, quotedAs, args);
1685
+ }
1686
+ if (joinQuery) {
1687
+ const whereSql = whereToSql(model, joinQuery, values, joinAs, quotedAs);
1688
+ if (whereSql) {
1689
+ if (conditions)
1690
+ conditions += ` AND ${whereSql}`;
1691
+ else
1692
+ conditions = whereSql;
1693
+ }
1694
+ }
1695
+ return { target, conditions };
1696
+ };
1697
+ const getConditionsFor3Or4LengthItem = (target, values, quotedAs, args) => {
1698
+ const [, leftColumn, opOrRightColumn, maybeRightColumn] = args;
1699
+ const op = maybeRightColumn ? opOrRightColumn : "=";
1700
+ const rightColumn = maybeRightColumn ? maybeRightColumn : opOrRightColumn;
1701
+ return `${typeof leftColumn === "string" ? quoteFullColumn(leftColumn, target) : getRaw(leftColumn, values)} ${op} ${typeof rightColumn === "string" ? quoteFullColumn(rightColumn, quotedAs) : getRaw(rightColumn, values)}`;
1702
+ };
1703
+ const getObjectOrRawConditions = (data, values, quotedAs, joinAs) => {
1704
+ if (isRaw(data)) {
1705
+ return getRaw(data, values);
1706
+ } else {
1707
+ const pairs = [];
1708
+ for (const key in data) {
1709
+ const value = data[key];
1710
+ pairs.push(`${quoteFullColumn(key, joinAs)} = ${typeof value === "string" ? quoteFullColumn(value, quotedAs) : getRaw(value, values)}`);
1711
+ }
1712
+ return pairs.join(", ");
1713
+ }
1714
+ };
1715
+ const pushJoinSql = (sql, model, query, values, quotedAs) => {
1716
+ query.join.forEach((item) => {
1717
+ const { target, conditions } = processJoinItem(model, query, values, item.args, quotedAs);
1718
+ sql.push(item.type, target);
1719
+ if (conditions)
1720
+ sql.push("ON", conditions);
1721
+ });
1722
+ };
1723
+
1724
+ const pushWhereSql = (sql, model, query, values, quotedAs, otherTableQuotedAs) => {
1725
+ const whereConditions = whereToSql(model, query, values, quotedAs, otherTableQuotedAs);
1726
+ if (whereConditions) {
1727
+ sql.push("WHERE", whereConditions);
1728
+ }
1729
+ };
1730
+ const whereToSql = (model, query, values, quotedAs, otherTableQuotedAs, not) => {
1731
+ const or = query.and && query.or ? [query.and, ...query.or] : query.and ? [query.and] : query.or;
1732
+ if (!(or == null ? void 0 : or.length))
1733
+ return "";
1734
+ const ors = [];
1735
+ or.forEach((and) => {
1736
+ const ands = [];
1737
+ and.forEach((data) => {
1738
+ const prefix = not ? "NOT " : "";
1739
+ if (typeof data === "function") {
1740
+ const qb = data(new model.whereQueryBuilder(model.table, query.as));
1741
+ const sql = whereToSql(model, {
1742
+ as: query.as,
1743
+ and: qb.query.and,
1744
+ or: qb.query.or
1745
+ }, values, quotedAs, otherTableQuotedAs, not);
1746
+ if (sql)
1747
+ ands.push(sql);
1748
+ return;
1749
+ }
1750
+ if ("prototype" in data || "__model" in data) {
1751
+ const query2 = data;
1752
+ const sql = whereToSql(query2, query2.query || EMPTY_OBJECT, values, query2.table && q(query2.table));
1753
+ if (sql) {
1754
+ ands.push(`${prefix}(${sql})`);
1755
+ }
1756
+ return;
1757
+ }
1758
+ if (isRaw(data)) {
1759
+ ands.push(`${prefix}(${getRaw(data, values)})`);
1760
+ return;
1761
+ }
1762
+ for (const key in data) {
1763
+ const value = data[key];
1764
+ const handler = whereHandlers[key];
1765
+ if (handler) {
1766
+ handler(value, ands, prefix, model, query, values, quotedAs, otherTableQuotedAs, not);
1767
+ } else if (typeof value === "object" && value !== null && value !== void 0) {
1768
+ if (isRaw(value)) {
1769
+ ands.push(`${prefix}${quoteFullColumn(key, quotedAs)} = ${getRaw(value, values)}`);
1770
+ } else {
1771
+ const column = model.shape[key];
1772
+ if (!column) {
1773
+ throw new Error(`Unknown column ${key} provided to condition`);
1774
+ }
1775
+ for (const op in value) {
1776
+ const operator = column.operators[op];
1777
+ if (!operator) {
1778
+ throw new Error(`Unknown operator ${op} provided to condition`);
1779
+ }
1780
+ ands.push(`${prefix}${operator(qc(key, quotedAs), value[op], values)}`);
1781
+ }
1782
+ }
1783
+ } else {
1784
+ ands.push(`${prefix}${quoteFullColumn(key, quotedAs)} ${value === null ? "IS NULL" : `= ${addValue(values, value)}`}`);
1785
+ }
1786
+ }
1787
+ });
1788
+ ors.push(ands.join(" AND "));
1789
+ });
1790
+ return ors.join(" OR ");
1791
+ };
1792
+ const whereHandlers = {
1793
+ AND(value, ands, _, model, _q, values, quotedAs, otherTableQuotedAs, not) {
1794
+ const sql = whereToSql(model, {
1795
+ and: toArray(value)
1796
+ }, values, quotedAs, otherTableQuotedAs, not);
1797
+ if (sql)
1798
+ ands.push(sql);
1799
+ },
1800
+ OR(value, ands, _, model, _q, values, quotedAs, otherTableQuotedAs, not) {
1801
+ const sql = whereToSql(model, {
1802
+ or: value.map(toArray)
1803
+ }, values, quotedAs, otherTableQuotedAs, not);
1804
+ if (sql)
1805
+ ands.push(sql);
1806
+ },
1807
+ NOT(value, ands, _, model, _q, values, quotedAs, otherTableQuotedAs, not) {
1808
+ const sql = whereToSql(model, {
1809
+ and: toArray(value)
1810
+ }, values, quotedAs, otherTableQuotedAs, !not);
1811
+ if (sql)
1812
+ ands.push(sql);
1813
+ },
1814
+ ON(value, ands, prefix, _, _q, values, quotedAs, otherTableQuotedAs) {
1815
+ if (Array.isArray(value)) {
1816
+ const item = value;
1817
+ const leftColumn = quoteFullColumn(item[0], quotedAs);
1818
+ const leftPath = item[1];
1819
+ const rightColumn = quoteFullColumn(item[2], otherTableQuotedAs);
1820
+ const rightPath = item[3];
1821
+ ands.push(`${prefix}jsonb_path_query_first(${leftColumn}, ${addValue(values, leftPath)}) = jsonb_path_query_first(${rightColumn}, ${addValue(values, rightPath)})`);
1822
+ } else {
1823
+ const item = value;
1824
+ const leftColumn = quoteFullColumn(item.on[0], typeof item.joinTo === "string" ? q(item.joinTo) : q(getQueryAs(item.joinTo)));
1825
+ const joinTo = typeof item.joinFrom === "string" ? item.joinFrom : q(getQueryAs(item.joinFrom));
1826
+ const [op, rightColumn] = item.on.length === 2 ? ["=", quoteFullColumn(item.on[1], joinTo)] : [item.on[1], quoteFullColumn(item.on[2], joinTo)];
1827
+ ands.push(`${prefix}${leftColumn} ${op} ${rightColumn}`);
1828
+ }
1829
+ },
1830
+ IN(value, ands, prefix, _, _q, values, quotedAs) {
1831
+ toArray(value).forEach((item) => {
1832
+ pushIn(ands, prefix, quotedAs, values, item);
1833
+ });
1834
+ },
1835
+ EXISTS(value, ands, prefix, model, query, values, quotedAs) {
1836
+ const joinItems = Array.isArray(value[0]) ? value : [value];
1837
+ joinItems.forEach((item) => {
1838
+ const { target, conditions } = processJoinItem(model, query, values, item, quotedAs);
1839
+ ands.push(`${prefix}EXISTS (SELECT 1 FROM ${target} WHERE ${conditions} LIMIT 1)`);
1840
+ });
1841
+ }
1842
+ };
1843
+ const pushIn = (ands, prefix, quotedAs, values, arg) => {
1844
+ let value;
1845
+ if (Array.isArray(arg.values)) {
1846
+ value = `${arg.values.map((arr) => `(${arr.map((value2) => addValue(values, value2)).join(", ")})`).join(", ")}`;
1847
+ if (arg.columns.length > 1)
1848
+ value = `(${value})`;
1849
+ } else if (isRaw(arg.values)) {
1850
+ value = getRaw(arg.values, values);
1851
+ } else {
1852
+ const sql = arg.values.toSql(values);
1853
+ value = `(${sql.text})`;
1854
+ }
1855
+ const columnsSql = arg.columns.map((column) => quoteFullColumn(column, quotedAs)).join(", ");
1856
+ ands.push(`${prefix}${arg.columns.length > 1 ? `(${columnsSql})` : columnsSql} IN ${value}`);
1857
+ };
1858
+
1859
+ const aggregateToSql = (model, values, item, quotedAs) => {
1860
+ var _a;
1861
+ const sql = [`${item.function}(`];
1862
+ const options = item.options || EMPTY_OBJECT;
1863
+ if (options.distinct && !options.withinGroup)
1864
+ sql.push("DISTINCT ");
1865
+ if (typeof item.arg === "object") {
1866
+ if (Array.isArray(item.arg)) {
1867
+ sql.push(`${expressionToSql(item.arg[0], values, quotedAs)}, ${addValue(values, item.arg[1])}`);
1868
+ } else if (isRaw(item.arg)) {
1869
+ sql.push(getRaw(item.arg, values));
1870
+ } else {
1871
+ const args = [];
1872
+ for (const key in item.arg) {
1873
+ args.push(`${addValue(values, key)}::text, ${expressionToSql(item.arg[key], values, quotedAs)}`);
1874
+ }
1875
+ sql.push(args.join(", "));
1876
+ }
1877
+ } else if (item.arg) {
1878
+ sql.push(expressionToSql(item.arg, values, quotedAs));
1879
+ }
1880
+ if (options.withinGroup)
1881
+ sql.push(") WITHIN GROUP (");
1882
+ else if (options.order)
1883
+ sql.push(" ");
1884
+ if (options.order)
1885
+ pushOrderBySql(sql, values, quotedAs, options.order);
1886
+ sql.push(")");
1887
+ if (options.filter || options.filterOr) {
1888
+ const whereSql = whereToSql(model, {
1889
+ and: options.filter ? [options.filter] : void 0,
1890
+ or: (_a = options.filterOr) == null ? void 0 : _a.map((item2) => [item2])
1891
+ }, values, quotedAs);
1892
+ sql.push(` FILTER (WHERE ${whereSql})`);
1893
+ }
1894
+ if (options.over) {
1895
+ sql.push(` OVER ${windowToSql(options.over, values, quotedAs)}`);
1896
+ }
1897
+ if (options.as)
1898
+ sql.push(` AS ${q(options.as)}`);
1899
+ return sql.join("");
1900
+ };
1901
+
1902
+ const relationQueryKey = Symbol("relationQuery");
1903
+ const isRequiredRelationKey = Symbol("isRequiredRelation");
1904
+
1905
+ const jsonColumnOrMethodToSql = (column, values, quotedAs) => {
1906
+ return typeof column === "string" ? quoteFullColumn(column, quotedAs) : jsonToSql(column, values, quotedAs);
1907
+ };
1908
+ const jsonToSql = (item, values, quotedAs) => {
1909
+ const json = item.__json;
1910
+ if (json[0] === "pathQuery") {
1911
+ const [, , , column, path, options] = json;
1912
+ return `jsonb_path_query(${jsonColumnOrMethodToSql(column, values, quotedAs)}, ${addValue(values, path)}${(options == null ? void 0 : options.vars) ? `, ${addValue(values, options.vars)}` : ""}${(options == null ? void 0 : options.silent) ? ", true" : ""})`;
1913
+ } else if (json[0] === "set") {
1914
+ const [, , , column, path, value, options] = json;
1915
+ return `jsonb_set(${jsonColumnOrMethodToSql(column, values, quotedAs)}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.createIfMissing) ? ", true" : ""})`;
1916
+ } else if (json[0] === "insert") {
1917
+ const [, , , column, path, value, options] = json;
1918
+ return `jsonb_insert(${jsonColumnOrMethodToSql(column, values, quotedAs)}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.insertAfter) ? ", true" : ""})`;
1919
+ } else if (json[0] === "remove") {
1920
+ const [, , , column, path] = json;
1921
+ return `${jsonColumnOrMethodToSql(column, values, quotedAs)} #- '{${path.join(", ")}}'`;
1922
+ }
1923
+ return "";
1924
+ };
1925
+ const pushSelectSql = (sql, model, query, values, quotedAs) => {
1926
+ sql.push(selectToSql(model, query, values, quotedAs));
1927
+ };
1928
+ const selectToSql = (model, query, values, quotedAs) => {
1929
+ var _a;
1930
+ if (query.select) {
1931
+ const list = [];
1932
+ query.select.forEach((item) => {
1933
+ var _a2, _b;
1934
+ if (typeof item === "string") {
1935
+ list.push(item === "*" ? ((_a2 = query.join) == null ? void 0 : _a2.length) ? `${quotedAs}.*` : "*" : quoteFullColumn(item, quotedAs));
1936
+ } else if ((_b = item.query) == null ? void 0 : _b[relationQueryKey]) {
1937
+ let relationQuery = item.clone();
1938
+ const as = q(getQueryAs(relationQuery));
1939
+ relationQuery._as(relationQuery.query[relationQueryKey]);
1940
+ const { returnType } = relationQuery.query;
1941
+ if (returnType === "all" || returnType === "one" || returnType === "oneOrThrow") {
1942
+ relationQuery = relationQuery._json();
1943
+ }
1944
+ list.push(`(${relationQuery.toSql(values).text}) AS ${as}`);
1945
+ } else {
1946
+ if ("selectAs" in item) {
1947
+ const obj = item.selectAs;
1948
+ for (const as in obj) {
1949
+ const value = obj[as];
1950
+ if (typeof value === "object") {
1951
+ if (isRaw(value)) {
1952
+ list.push(`${getRaw(value, values)} AS ${q(as)}`);
1953
+ } else {
1954
+ const sql = value.json().toSql(values);
1955
+ list.push(`(${sql.text}) AS ${q(as)}`);
1956
+ }
1957
+ } else {
1958
+ list.push(`${quoteFullColumn(value, quotedAs)} AS ${q(as)}`);
1959
+ }
1960
+ }
1961
+ } else if ("__json" in item) {
1962
+ list.push(`${jsonToSql(item, values, quotedAs)} AS ${q(item.__json[1])}`);
1963
+ } else if (isRaw(item)) {
1964
+ list.push(getRaw(item, values));
1965
+ } else if ("arguments" in item) {
1966
+ list.push(`${item.function}(${selectToSql(model, { select: item.arguments }, values, quotedAs)})${item.as ? ` AS ${q(item.as)}` : ""}`);
1967
+ } else {
1968
+ list.push(aggregateToSql(model, values, item, quotedAs));
1969
+ }
1970
+ }
1971
+ });
1972
+ return list.join(", ");
1973
+ } else {
1974
+ return ((_a = query.join) == null ? void 0 : _a.length) ? `${quotedAs}.*` : "*";
1975
+ }
1976
+ };
1977
+
1978
+ const aggregateOptionNames = [
1979
+ "distinct",
1980
+ "order",
1981
+ "filter",
1982
+ "filterOr",
1983
+ "withinGroup"
1984
+ ];
1985
+ const pushHavingSql = (sql, model, query, values, quotedAs) => {
1986
+ const conditions = havingToSql(model, query, values, quotedAs);
1987
+ if (conditions.length)
1988
+ sql.push("HAVING", conditions);
1989
+ };
1990
+ const havingToSql = (model, query, values, quotedAs) => {
1991
+ const or = query.having && query.havingOr ? [query.having, ...query.havingOr] : query.having ? [query.having] : query.havingOr;
1992
+ if (!(or == null ? void 0 : or.length))
1993
+ return "";
1994
+ const ors = [];
1995
+ or.forEach((and) => {
1996
+ const ands = [];
1997
+ and.forEach((item) => {
1998
+ if ("prototype" in item || "__model" in item) {
1999
+ const query2 = item;
2000
+ const sql = havingToSql(query2, query2.query, values, query2.table && q(query2.table));
2001
+ if (sql.length)
2002
+ ands.push(`(${sql})`);
2003
+ return;
2004
+ }
2005
+ if (isRaw(item)) {
2006
+ ands.push(getRaw(item, values));
2007
+ return;
2008
+ }
2009
+ for (const key in item) {
2010
+ const columns = item[key];
2011
+ if (typeof columns === "object") {
2012
+ for (const column in columns) {
2013
+ const valueOrOptions = columns[column];
2014
+ if (typeof valueOrOptions === "object" && valueOrOptions !== null && valueOrOptions !== void 0) {
2015
+ for (const op in valueOrOptions) {
2016
+ if (!aggregateOptionNames.includes(op)) {
2017
+ const operator = model.shape[column].operators[op];
2018
+ if (!operator) {
2019
+ throw new Error(`Unknown operator ${op} provided to condition`);
2020
+ }
2021
+ const expression = aggregateToSql(model, values, {
2022
+ function: key,
2023
+ arg: column,
2024
+ options: valueOrOptions
2025
+ }, quotedAs);
2026
+ ands.push(operator(expression, valueOrOptions[op], values));
2027
+ }
2028
+ }
2029
+ } else {
2030
+ ands.push(`${aggregateToSql(model, values, {
2031
+ function: key,
2032
+ arg: column,
2033
+ options: EMPTY_OBJECT
2034
+ }, quotedAs)} = ${addValue(values, valueOrOptions)}`);
2035
+ }
2036
+ }
2037
+ } else {
2038
+ ands.push(`${key}(*) = ${columns}`);
2039
+ }
2040
+ }
2041
+ });
2042
+ ors.push(ands.join(" AND "));
2043
+ });
2044
+ return ors.join(" OR ");
2045
+ };
2046
+
2047
+ const pushWithSql = (sql, values, withData) => {
2048
+ withData.forEach((withItem) => {
2049
+ const [name, options, query] = withItem;
2050
+ let inner;
2051
+ if (isRaw(query)) {
2052
+ inner = getRaw(query, values);
2053
+ } else {
2054
+ inner = query.toSql(values).text;
2055
+ }
2056
+ sql.push(`WITH ${options.recursive ? "RECURSIVE " : ""}${q(name)}${options.columns ? `(${options.columns.map(q).join(", ")})` : ""} AS ${options.materialized ? "MATERIALIZED " : options.notMaterialized ? "NOT MATERIALIZED " : ""}(${inner})`);
2057
+ });
2058
+ };
2059
+
2060
+ const queryKeysOfNotSimpleQuery = [
2061
+ "take",
2062
+ "with",
2063
+ "as",
2064
+ "from",
2065
+ "and",
2066
+ "or",
2067
+ "select",
2068
+ "distinct",
2069
+ "fromOnly",
2070
+ "join",
2071
+ "group",
2072
+ "having",
2073
+ "havingOr",
2074
+ "window",
2075
+ "union",
2076
+ "order",
2077
+ "limit",
2078
+ "offset",
2079
+ "for"
2080
+ ];
2081
+
2082
+ const pushFromAndAs = (sql, model, query, values, quotedAs) => {
2083
+ sql.push("FROM");
2084
+ if (query.fromOnly)
2085
+ sql.push("ONLY");
2086
+ const from = getFrom(model, query, values);
2087
+ sql.push(from);
2088
+ if (query.as && quotedAs && quotedAs !== from) {
2089
+ sql.push("AS", quotedAs);
2090
+ }
2091
+ };
2092
+ const getFrom = (model, query, values) => {
2093
+ if (query.from) {
2094
+ if (typeof query.from === "object") {
2095
+ if (isRaw(query.from)) {
2096
+ return getRaw(query.from, values);
2097
+ }
2098
+ if (!query.from.table) {
2099
+ const sql = query.from.toSql(values);
2100
+ return `(${sql.text})`;
2101
+ }
2102
+ const q = query.from.query;
2103
+ const keys = Object.keys(q);
2104
+ if (keys.some((key) => queryKeysOfNotSimpleQuery.includes(key))) {
2105
+ const sql = query.from.toSql(values);
2106
+ return `(${sql.text})`;
2107
+ }
2108
+ return quoteSchemaAndTable(q.schema, query.from.table);
2109
+ }
2110
+ return quoteSchemaAndTable(query.schema, query.from);
2111
+ }
2112
+ return quoteSchemaAndTable(query.schema, model.table);
2113
+ };
2114
+
2115
+ const pushInsertSql = (sql, values, model, query, quotedAs) => {
2116
+ const quotedColumns = query.columns.map(q);
2117
+ sql.push(`INSERT INTO ${quotedAs}(${quotedColumns.join(", ")}) VALUES ${isRaw(query.values) ? getRaw(query.values, values) : query.values.map((row) => `(${row.map((value) => value === void 0 ? "DEFAULT" : addValue(values, value)).join(", ")})`).join(", ")}`);
2118
+ if (query.onConflict) {
2119
+ sql.push("ON CONFLICT");
2120
+ const { expr, type } = query.onConflict;
2121
+ if (expr) {
2122
+ if (typeof expr === "string") {
2123
+ sql.push(`(${q(expr)})`);
2124
+ } else if (Array.isArray(expr)) {
2125
+ sql.push(`(${expr.map(q).join(", ")})`);
2126
+ } else {
2127
+ sql.push(getRaw(expr, values));
2128
+ }
2129
+ } else {
2130
+ sql.push(`(${quotedColumns.join(", ")})`);
2131
+ }
2132
+ if (type === "ignore") {
2133
+ sql.push("DO NOTHING");
2134
+ } else if (type === "merge") {
2135
+ let set;
2136
+ const { update } = query.onConflict;
2137
+ if (update) {
2138
+ if (typeof update === "string") {
2139
+ set = `${q(update)} = excluded.${q(update)}`;
2140
+ } else if (Array.isArray(update)) {
2141
+ set = update.map((column) => `${q(column)} = excluded.${q(column)}`).join(", ");
2142
+ } else if (isRaw(update)) {
2143
+ set = getRaw(update, values);
2144
+ } else {
2145
+ const arr = [];
2146
+ for (const key in update) {
2147
+ arr.push(`${q(key)} = ${addValue(values, update[key])}`);
2148
+ }
2149
+ set = arr.join(", ");
2150
+ }
2151
+ } else {
2152
+ set = quotedColumns.map((column) => `${column} = excluded.${column}`).join(", ");
2153
+ }
2154
+ sql.push("DO UPDATE SET", set);
2155
+ }
2156
+ }
2157
+ pushWhereSql(sql, model, query, values, quotedAs);
2158
+ pushReturningSql(sql, model, query, values, quotedAs);
2159
+ };
2160
+ const pushReturningSql = (sql, model, query, values, quotedAs) => {
2161
+ if (query.select) {
2162
+ sql.push(`RETURNING ${selectToSql(model, query, values, quotedAs)}`);
2163
+ }
2164
+ };
2165
+
2166
+ const pushUpdateSql = (sql, values, model, query, quotedAs) => {
2167
+ const quotedTable = quoteSchemaAndTable(query.schema, model.table);
2168
+ sql.push(`UPDATE ${quotedTable}`);
2169
+ if (query.as && quotedTable !== quotedAs) {
2170
+ sql.push(`AS ${quotedAs}`);
2171
+ }
2172
+ sql.push("SET");
2173
+ query.data.forEach((item) => {
2174
+ if (isRaw(item)) {
2175
+ sql.push(getRaw(item, values));
2176
+ } else {
2177
+ const set = [];
2178
+ for (const key in item) {
2179
+ const value = item[key];
2180
+ if (value !== void 0) {
2181
+ set.push(`${q(key)} = ${processValue(values, key, value)}`);
2182
+ }
2183
+ }
2184
+ sql.push(set.join(", "));
2185
+ }
2186
+ });
2187
+ pushWhereSql(sql, model, query, values, quotedAs);
2188
+ pushReturningSql(sql, model, query, values, quotedAs);
2189
+ };
2190
+ const processValue = (values, key, value) => {
2191
+ if (value && typeof value === "object") {
2192
+ if (isRaw(value)) {
2193
+ return getRaw(value, values);
2194
+ } else if ("op" in value && "arg" in value) {
2195
+ return `${q(key)} ${value.op} ${addValue(values, value.arg)}`;
2196
+ }
2197
+ }
2198
+ return addValue(values, value);
2199
+ };
2200
+
2201
+ const pushDeleteSql = (sql, values, model, query, quotedAs) => {
2202
+ var _a, _b, _c;
2203
+ sql.push(`DELETE FROM ${quotedAs}`);
2204
+ let conditions;
2205
+ if ((_a = query.join) == null ? void 0 : _a.length) {
2206
+ const items = query.join.map((item) => processJoinItem(model, query, values, item.args, quotedAs));
2207
+ sql.push(`USING ${items.map((item) => item.target).join(", ")}`);
2208
+ conditions = items.map((item) => item.conditions).filter(Boolean).join(" AND ");
2209
+ }
2210
+ pushWhereSql(sql, model, query, values, quotedAs);
2211
+ if (conditions == null ? void 0 : conditions.length) {
2212
+ if (((_b = query.and) == null ? void 0 : _b.length) || ((_c = query.or) == null ? void 0 : _c.length)) {
2213
+ sql.push("AND", conditions);
2214
+ } else {
2215
+ sql.push("WHERE", conditions);
2216
+ }
2217
+ }
2218
+ pushReturningSql(sql, model, query, values, quotedAs);
2219
+ };
2220
+
2221
+ const pushTruncateSql = (sql, table, query) => {
2222
+ sql.push("TRUNCATE", quoteSchemaAndTable(query.schema, table));
2223
+ if (query.restartIdentity)
2224
+ sql.push("RESTART IDENTITY");
2225
+ if (query.cascade)
2226
+ sql.push("CASCADE");
2227
+ };
2228
+
2229
+ const pushColumnInfoSql = (sql, values, table, query) => {
2230
+ sql.push(`SELECT * FROM information_schema.columns WHERE table_name = ${addValue(values, table)} AND table_catalog = current_database() AND table_schema = ${query.schema || "current_schema()"}`);
2231
+ if (query.column) {
2232
+ sql.push(`AND column_name = ${addValue(values, query.column)}`);
2233
+ }
2234
+ };
2235
+
2236
+ const toSql = (model, values = []) => {
2237
+ const query = model.query;
2238
+ const sql = [];
2239
+ if (query.with) {
2240
+ pushWithSql(sql, values, query.with);
2241
+ }
2242
+ if (query.type) {
2243
+ if (query.type === "truncate") {
2244
+ if (!model.table)
2245
+ throw new Error("Table is missing for truncate");
2246
+ pushTruncateSql(sql, model.table, query);
2247
+ return { text: sql.join(" "), values };
2248
+ }
2249
+ if (query.type === "columnInfo") {
2250
+ if (!model.table)
2251
+ throw new Error("Table is missing for truncate");
2252
+ pushColumnInfoSql(sql, values, model.table, query);
2253
+ return { text: sql.join(" "), values };
2254
+ }
2255
+ if (!model.table)
2256
+ throw new Error(`Table is missing for ${query.type}`);
2257
+ const quotedAs2 = q(query.as || model.table);
2258
+ if (query.type === "insert") {
2259
+ pushInsertSql(sql, values, model, query, q(model.table));
2260
+ return { text: sql.join(" "), values };
2261
+ }
2262
+ if (query.type === "update") {
2263
+ pushUpdateSql(sql, values, model, query, quotedAs2);
2264
+ return { text: sql.join(" "), values };
2265
+ }
2266
+ if (query.type === "delete") {
2267
+ pushDeleteSql(sql, values, model, query, q(model.table));
2268
+ return { text: sql.join(" "), values };
2269
+ }
2270
+ }
2271
+ const quotedAs = model.table && q(query.as || model.table);
2272
+ sql.push("SELECT");
2273
+ if (query.distinct) {
2274
+ pushDistinctSql(sql, values, query.distinct, quotedAs);
2275
+ }
2276
+ pushSelectSql(sql, model, query, values, quotedAs);
2277
+ if (model.table || query.from) {
2278
+ pushFromAndAs(sql, model, query, values, quotedAs);
2279
+ }
2280
+ if (query.join) {
2281
+ pushJoinSql(sql, model, query, values, quotedAs);
2282
+ }
2283
+ if (query.and || query.or) {
2284
+ pushWhereSql(sql, model, query, values, quotedAs);
2285
+ }
2286
+ if (query.group) {
2287
+ const group = query.group.map((item) => typeof item === "object" && isRaw(item) ? getRaw(item, values) : qc(item, quotedAs));
2288
+ sql.push(`GROUP BY ${group.join(", ")}`);
2289
+ }
2290
+ if (query.having || query.havingOr) {
2291
+ pushHavingSql(sql, model, query, values, quotedAs);
2292
+ }
2293
+ if (query.window) {
2294
+ const window = [];
2295
+ query.window.forEach((item) => {
2296
+ for (const key in item) {
2297
+ window.push(`${q(key)} AS ${windowToSql(item[key], values, quotedAs)}`);
2298
+ }
2299
+ });
2300
+ sql.push(`WINDOW ${window.join(", ")}`);
2301
+ }
2302
+ if (query.union) {
2303
+ query.union.forEach((item) => {
2304
+ let itemSql;
2305
+ if (isRaw(item.arg)) {
2306
+ itemSql = getRaw(item.arg, values);
2307
+ } else {
2308
+ const argSql = item.arg.toSql(values);
2309
+ itemSql = argSql.text;
2310
+ }
2311
+ sql.push(`${item.kind} ${item.wrap ? `(${itemSql})` : itemSql}`);
2312
+ });
2313
+ }
2314
+ if (query.order) {
2315
+ pushOrderBySql(sql, values, quotedAs, query.order);
2316
+ }
2317
+ if (query.take || query.limit !== void 0) {
2318
+ sql.push(`LIMIT ${addValue(values, query.take ? 1 : query.limit)}`);
2319
+ }
2320
+ if (query.offset) {
2321
+ sql.push(`OFFSET ${addValue(values, query.offset)}`);
2322
+ }
2323
+ if (query.for) {
2324
+ sql.push("FOR", query.for.type);
2325
+ const { tableNames } = query.for;
2326
+ if (tableNames) {
2327
+ if (isRaw(tableNames)) {
2328
+ sql.push("OF", getRaw(tableNames, values));
2329
+ } else {
2330
+ sql.push("OF", tableNames.map(q).join(", "));
2331
+ }
2332
+ }
2333
+ if (query.for.mode)
2334
+ sql.push(query.for.mode);
2335
+ }
2336
+ return { text: sql.join(" "), values };
2337
+ };
2338
+
2339
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
2340
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
2341
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
2342
+ var __objRest$1 = (source, exclude) => {
2343
+ var target = {};
2344
+ for (var prop in source)
2345
+ if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)
2346
+ target[prop] = source[prop];
2347
+ if (source != null && __getOwnPropSymbols$6)
2348
+ for (var prop of __getOwnPropSymbols$6(source)) {
2349
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))
2350
+ target[prop] = source[prop];
2351
+ }
2352
+ return target;
2353
+ };
2354
+ const defaultTypeParsers = {};
2355
+ for (const key in types.builtins) {
2356
+ const id = types.builtins[key];
2357
+ defaultTypeParsers[id] = types.getTypeParser(id);
2358
+ }
2359
+ [
2360
+ types.builtins.DATE,
2361
+ types.builtins.TIMESTAMP,
2362
+ types.builtins.TIMESTAMPTZ,
2363
+ types.builtins.TIME
2364
+ ].forEach((id) => {
2365
+ delete defaultTypeParsers[id];
2366
+ });
2367
+ const returnArg = (arg) => arg;
2368
+ class Adapter {
2369
+ constructor(_a) {
2370
+ var _b = _a, { types: types2 = defaultTypeParsers } = _b, config = __objRest$1(_b, ["types"]);
2371
+ this.types = types2;
2372
+ this.pool = new Pool(config);
2373
+ }
2374
+ async query(query, types2 = this.types) {
2375
+ const client = await this.pool.connect();
2376
+ try {
2377
+ return await performQuery(client, query, types2);
2378
+ } finally {
2379
+ client.release();
2380
+ }
2381
+ }
2382
+ async arrays(query, types2 = this.types) {
2383
+ const client = await this.pool.connect();
2384
+ try {
2385
+ return await performQueryArrays(client, query, types2);
2386
+ } finally {
2387
+ client.release();
2388
+ }
2389
+ }
2390
+ async transaction(cb) {
2391
+ const client = await this.pool.connect();
2392
+ try {
2393
+ await performQuery(client, { text: "BEGIN" }, this.types);
2394
+ const result = await cb(new TransactionAdapter(this.pool, client, this.types));
2395
+ await performQuery(client, { text: "COMMIT" }, this.types);
2396
+ return result;
2397
+ } catch (err) {
2398
+ await performQuery(client, { text: "ROLLBACK" }, this.types);
2399
+ throw err;
2400
+ } finally {
2401
+ client.release();
2402
+ }
2403
+ }
2404
+ destroy() {
2405
+ return this.pool.end();
2406
+ }
2407
+ }
2408
+ const performQuery = (client, query, types2) => {
2409
+ return client.query({
2410
+ text: typeof query === "string" ? query : query.text,
2411
+ values: typeof query === "string" ? void 0 : query.values,
2412
+ types: types2 && {
2413
+ getTypeParser(id) {
2414
+ return types2[id] || returnArg;
2415
+ }
2416
+ }
2417
+ });
2418
+ };
2419
+ const performQueryArrays = (client, query, types2) => {
2420
+ return client.query({
2421
+ text: typeof query === "string" ? query : query.text,
2422
+ values: typeof query === "string" ? void 0 : query.values,
2423
+ rowMode: "array",
2424
+ types: types2 && {
2425
+ getTypeParser(id) {
2426
+ return types2[id] || returnArg;
2427
+ }
2428
+ }
2429
+ });
2430
+ };
2431
+ class TransactionAdapter {
2432
+ constructor(pool, client, types2) {
2433
+ this.pool = pool;
2434
+ this.client = client;
2435
+ this.types = types2;
2436
+ }
2437
+ async query(query, types2 = this.types) {
2438
+ return await performQuery(this.client, query, types2);
2439
+ }
2440
+ async arrays(query, types2 = this.types) {
2441
+ return await performQueryArrays(this.client, query, types2);
2442
+ }
2443
+ async transaction(cb) {
2444
+ return await cb(this);
2445
+ }
2446
+ destroy() {
2447
+ return this.pool.end();
2448
+ }
2449
+ }
2450
+
2451
+ const removeFromQuery = (q, key) => {
2452
+ if (q.query)
2453
+ delete q.query[key];
2454
+ return q;
2455
+ };
2456
+ const pushQueryArray = (q, key, value) => {
2457
+ if (!q.query[key])
2458
+ q.query[key] = value;
2459
+ else
2460
+ q.query[key].push(...value);
2461
+ return q;
2462
+ };
2463
+ const pushQueryValue = (q, key, value) => {
2464
+ if (!q.query[key])
2465
+ q.query[key] = [value];
2466
+ else
2467
+ q.query[key].push(value);
2468
+ return q;
2469
+ };
2470
+ const setQueryObjectValue = (q, object, key, value) => {
2471
+ if (!q.query[object])
2472
+ q.query[object] = {
2473
+ [key]: value
2474
+ };
2475
+ else
2476
+ q.query[object][key] = value;
2477
+ return q;
2478
+ };
2479
+
2480
+ class NotFoundError extends Error {
2481
+ constructor(message = "Record is not found") {
2482
+ super(message);
2483
+ }
2484
+ }
2485
+ class MoreThanOneRowError extends Error {
2486
+ }
2487
+
2488
+ const queryMethodByReturnType = {
2489
+ all: "query",
2490
+ one: "query",
2491
+ oneOrThrow: "query",
2492
+ rows: "arrays",
2493
+ pluck: "arrays",
2494
+ value: "arrays",
2495
+ valueOrThrow: "arrays",
2496
+ rowCount: "arrays",
2497
+ void: "arrays"
2498
+ };
2499
+ class Then {
2500
+ then(resolve, reject) {
2501
+ if (this.query.wrapInTransaction && !this.query.inTransaction) {
2502
+ return this.transaction((q) => then(q, resolve, reject));
2503
+ } else {
2504
+ return then(this, resolve, reject);
2505
+ }
2506
+ }
2507
+ }
2508
+ const handleResult = async (q, result) => {
2509
+ return parseResult(q, q.query.returnType, result);
2510
+ };
2511
+ const then = async (q, resolve, reject) => {
2512
+ var _a, _b, _c, _d;
2513
+ let sql;
2514
+ let logData;
2515
+ try {
2516
+ let beforeCallbacks;
2517
+ let afterCallbacks;
2518
+ if (q.query.type === "insert") {
2519
+ beforeCallbacks = q.query.beforeInsert;
2520
+ afterCallbacks = q.query.afterInsert;
2521
+ } else if (q.query.type === "update") {
2522
+ beforeCallbacks = q.query.beforeUpdate;
2523
+ afterCallbacks = q.query.afterUpdate;
2524
+ }
2525
+ if (beforeCallbacks) {
2526
+ await Promise.all(beforeCallbacks.map((cb) => cb(q)));
2527
+ }
2528
+ if (q.query.beforeQuery) {
2529
+ await Promise.all(q.query.beforeQuery.map((cb) => cb(q)));
2530
+ }
2531
+ sql = q.toSql();
2532
+ if (q.query.log) {
2533
+ logData = (_a = q.query.log) == null ? void 0 : _a.beforeQuery(q, sql);
2534
+ }
2535
+ const queryResult = await q.query.adapter[queryMethodByReturnType[q.query.returnType]](sql);
2536
+ if (q.query.log) {
2537
+ (_b = q.query.log) == null ? void 0 : _b.afterQuery(q, sql, logData);
2538
+ sql = void 0;
2539
+ }
2540
+ const result = await q.query.handleResult(q, queryResult);
2541
+ if ((afterCallbacks == null ? void 0 : afterCallbacks.length) || ((_c = q.query.afterQuery) == null ? void 0 : _c.length)) {
2542
+ if ((_d = q.query.afterQuery) == null ? void 0 : _d.length) {
2543
+ await Promise.all(q.query.afterQuery.map((query) => query(q, result)));
2544
+ }
2545
+ if (afterCallbacks == null ? void 0 : afterCallbacks.length) {
2546
+ await Promise.all(afterCallbacks.map((query) => query(q, result)));
2547
+ }
2548
+ }
2549
+ resolve == null ? void 0 : resolve(result);
2550
+ } catch (error) {
2551
+ if (q.query.log && sql && logData) {
2552
+ q.query.log.onError(error, q, sql, logData);
2553
+ }
2554
+ reject == null ? void 0 : reject(error);
2555
+ }
2556
+ };
2557
+ const parseResult = (q, returnType, result) => {
2558
+ var _a, _b;
2559
+ switch (returnType) {
2560
+ case "all": {
2561
+ if (q.query.throwOnNotFound && result.rows.length === 0)
2562
+ throw new NotFoundError();
2563
+ const parsers = getQueryParsers(q);
2564
+ return parsers ? result.rows.map((row) => parseRecord(parsers, row)) : result.rows;
2565
+ }
2566
+ case "one": {
2567
+ const row = result.rows[0];
2568
+ if (!row)
2569
+ return;
2570
+ const parsers = getQueryParsers(q);
2571
+ return parsers ? parseRecord(parsers, row) : row;
2572
+ }
2573
+ case "oneOrThrow": {
2574
+ const row = result.rows[0];
2575
+ if (!row)
2576
+ throw new NotFoundError();
2577
+ const parsers = getQueryParsers(q);
2578
+ return parsers ? parseRecord(parsers, row) : row;
2579
+ }
2580
+ case "rows": {
2581
+ const parsers = getQueryParsers(q);
2582
+ return parsers ? parseRows(parsers, result.fields, result.rows) : result.rows;
2583
+ }
2584
+ case "pluck": {
2585
+ const parsers = getQueryParsers(q);
2586
+ if (parsers == null ? void 0 : parsers.pluck) {
2587
+ return result.rows.map((row) => parsers.pluck(row[0]));
2588
+ }
2589
+ return result.rows.map((row) => row[0]);
2590
+ }
2591
+ case "value": {
2592
+ const value = (_a = result.rows[0]) == null ? void 0 : _a[0];
2593
+ return value !== void 0 ? parseValue(value, result.fields, q) : void 0;
2594
+ }
2595
+ case "valueOrThrow": {
2596
+ const value = (_b = result.rows[0]) == null ? void 0 : _b[0];
2597
+ if (value === void 0)
2598
+ throw new NotFoundError();
2599
+ return parseValue(value, result.fields, q);
2600
+ }
2601
+ case "rowCount": {
2602
+ if (q.query.throwOnNotFound && result.rowCount === 0) {
2603
+ throw new NotFoundError();
2604
+ }
2605
+ return result.rowCount;
2606
+ }
2607
+ case "void": {
2608
+ return;
2609
+ }
2610
+ }
2611
+ };
2612
+ const parseRecord = (parsers, row) => {
2613
+ for (const key in parsers) {
2614
+ if (row[key] !== null && row[key] !== void 0) {
2615
+ row[key] = parsers[key](row[key]);
2616
+ }
2617
+ }
2618
+ return row;
2619
+ };
2620
+ const parseRows = (parsers, fields, rows) => {
2621
+ fields.forEach((field, i) => {
2622
+ const parser = parsers[field.name];
2623
+ if (parser) {
2624
+ rows.forEach((row) => {
2625
+ row[i] = parser(row[i]);
2626
+ });
2627
+ }
2628
+ });
2629
+ return rows;
2630
+ };
2631
+ const parseValue = (value, fields, query) => {
2632
+ const field = fields[0];
2633
+ if (value !== null) {
2634
+ const parsers = getQueryParsers(query);
2635
+ const parser = parsers == null ? void 0 : parsers[field.name];
2636
+ if (parser) {
2637
+ return parser(value);
2638
+ }
2639
+ }
2640
+ return value;
2641
+ };
2642
+
2643
+ const addParserForRawExpression = (q, key, raw) => {
2644
+ var _a;
2645
+ const parser = (_a = raw.__column) == null ? void 0 : _a.parseFn;
2646
+ if (parser)
2647
+ addParserToQuery(q.query, key, parser);
2648
+ };
2649
+ const addParserForSelectItem = (q, as, key, item) => {
2650
+ var _a, _b, _c, _d;
2651
+ if (typeof item === "object") {
2652
+ if (isRaw(item)) {
2653
+ addParserForRawExpression(q, key, item);
2654
+ } else {
2655
+ const parsers = getQueryParsers(item);
2656
+ if (parsers) {
2657
+ if (item.query.take) {
2658
+ addParserToQuery(q.query, key, (item2) => parseRecord(parsers, item2));
2659
+ } else {
2660
+ addParserToQuery(q.query, key, (items) => items.map((item2) => parseRecord(parsers, item2)));
2661
+ }
2662
+ }
2663
+ }
2664
+ } else {
2665
+ const index = item.indexOf(".");
2666
+ if (index !== -1) {
2667
+ const table = item.slice(0, index);
2668
+ const column = item.slice(index + 1);
2669
+ if (table === as) {
2670
+ const parser = (_a = q.columnsParsers) == null ? void 0 : _a[column];
2671
+ if (parser)
2672
+ addParserToQuery(q.query, key, parser);
2673
+ } else {
2674
+ const parser = (_c = (_b = q.query.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
2675
+ if (parser)
2676
+ addParserToQuery(q.query, key, parser);
2677
+ }
2678
+ } else {
2679
+ const parser = (_d = q.columnsParsers) == null ? void 0 : _d[item];
2680
+ if (parser)
2681
+ addParserToQuery(q.query, key, parser);
2682
+ }
2683
+ }
2684
+ };
2685
+ const addParserToQuery = (query, key, parser) => {
2686
+ if (query.parsers)
2687
+ query.parsers[key] = parser;
2688
+ else
2689
+ query.parsers = { [key]: parser };
2690
+ };
2691
+ const processSelectArg = (q, as, item) => {
2692
+ var _a, _b, _c, _d, _e;
2693
+ if (typeof item === "string") {
2694
+ if (q.relations[item]) {
2695
+ item = q[item];
2696
+ } else {
2697
+ const index = item.indexOf(".");
2698
+ if (index !== -1) {
2699
+ const table = item.slice(0, index);
2700
+ const column = item.slice(index + 1);
2701
+ if (table === as) {
2702
+ const parser = (_a = q.columnsParsers) == null ? void 0 : _a[column];
2703
+ if (parser)
2704
+ addParserToQuery(q.query, column, parser);
2705
+ } else {
2706
+ const parser = (_c = (_b = q.query.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
2707
+ if (parser)
2708
+ addParserToQuery(q.query, column, parser);
2709
+ }
2710
+ } else {
2711
+ const parser = (_d = q.columnsParsers) == null ? void 0 : _d[item];
2712
+ if (parser)
2713
+ addParserToQuery(q.query, item, parser);
2714
+ }
2715
+ return item;
2716
+ }
2717
+ }
2718
+ if ((_e = item.query) == null ? void 0 : _e[relationQueryKey]) {
2719
+ const relation = item;
2720
+ const parsers = relation.query.parsers || relation.columnsParsers;
2721
+ if (parsers) {
2722
+ addParserToQuery(q.query, getQueryAs(relation), (input) => {
2723
+ if (Array.isArray(input)) {
2724
+ input.forEach((record) => {
2725
+ for (const key in parsers) {
2726
+ const value = record[key];
2727
+ if (value !== null) {
2728
+ record[key] = parsers[key](value);
2729
+ }
2730
+ }
2731
+ });
2732
+ } else {
2733
+ for (const key in parsers) {
2734
+ const value = input[key];
2735
+ if (value !== null) {
2736
+ input[key] = parsers[key](value);
2737
+ }
2738
+ }
2739
+ }
2740
+ return input;
2741
+ });
2742
+ }
2743
+ } else {
2744
+ for (const key in item) {
2745
+ addParserForSelectItem(q, as, key, item[key]);
2746
+ }
2747
+ return { selectAs: item };
2748
+ }
2749
+ return item;
2750
+ };
2751
+ class Select {
2752
+ select(...args) {
2753
+ return this.clone()._select(...args);
2754
+ }
2755
+ _select(...args) {
2756
+ if (!args.length) {
2757
+ return this;
2758
+ }
2759
+ const as = this.query.as || this.table;
2760
+ const selectArgs = args.map((item) => processSelectArg(this, as, item));
2761
+ return pushQueryArray(this, "select", selectArgs);
2762
+ }
2763
+ selectAll() {
2764
+ return this.clone()._selectAll();
2765
+ }
2766
+ _selectAll() {
2767
+ this.query.select = ["*"];
2768
+ return this;
2769
+ }
2770
+ }
2771
+
2772
+ var __defProp$5 = Object.defineProperty;
2773
+ var __defProps$1 = Object.defineProperties;
2774
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2775
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
2776
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
2777
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
2778
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2779
+ var __spreadValues$5 = (a, b) => {
2780
+ for (var prop in b || (b = {}))
2781
+ if (__hasOwnProp$5.call(b, prop))
2782
+ __defNormalProp$5(a, prop, b[prop]);
2783
+ if (__getOwnPropSymbols$5)
2784
+ for (var prop of __getOwnPropSymbols$5(b)) {
2785
+ if (__propIsEnum$5.call(b, prop))
2786
+ __defNormalProp$5(a, prop, b[prop]);
2787
+ }
2788
+ return a;
2789
+ };
2790
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2791
+ const allColumns = raw("*");
2792
+ const aggregate1FunctionNames = {
2793
+ count: "count",
2794
+ avg: "avg",
2795
+ min: "min",
2796
+ max: "max",
2797
+ sum: "sum",
2798
+ bitAnd: "bit_and",
2799
+ bitOr: "bit_or",
2800
+ boolAnd: "bool_and",
2801
+ boolOr: "bool_or",
2802
+ every: "every",
2803
+ jsonAgg: "json_agg",
2804
+ jsonbAgg: "jsonb_agg",
2805
+ xmlAgg: "xmlagg"
2806
+ };
2807
+ const buildAggregateSelectItem = (functionName, arg, options) => {
2808
+ return {
2809
+ function: functionName,
2810
+ arg,
2811
+ options: __spreadProps$1(__spreadValues$5({}, options), {
2812
+ order: (options == null ? void 0 : options.order) ? Array.isArray(options.order) ? options.order : [options.order] : void 0,
2813
+ filter: options == null ? void 0 : options.filter,
2814
+ filterOr: options == null ? void 0 : options.filterOr
2815
+ })
2816
+ };
2817
+ };
2818
+ const parseIntColumn = new IntegerColumn().parse((input) => parseInt(input));
2819
+ const parseIntOrNullColumn = new IntegerColumn().parse((input) => input === null ? null : parseInt(input));
2820
+ const get = (q) => {
2821
+ q.query.returnType = "valueOrThrow";
2822
+ removeFromQuery(q, "take");
2823
+ const select = q.query.select;
2824
+ if (select.length > 1) {
2825
+ select[0] = select[select.length - 1];
2826
+ select.length = 1;
2827
+ }
2828
+ return q;
2829
+ };
2830
+ class Aggregate {
2831
+ selectAgg(functionName, arg, options) {
2832
+ return this.clone()._selectAgg(functionName, arg, options);
2833
+ }
2834
+ _selectAgg(functionName, arg, options, columnType) {
2835
+ pushQueryValue(this, "select", buildAggregateSelectItem(functionName, arg, options));
2836
+ if (columnType == null ? void 0 : columnType.parseFn) {
2837
+ addParserToQuery(this.query, (options == null ? void 0 : options.as) || functionName, columnType.parseFn);
2838
+ }
2839
+ return this;
2840
+ }
2841
+ count(arg, options) {
2842
+ return this.clone()._count(arg, options);
2843
+ }
2844
+ _count(arg = "*", options) {
2845
+ return get(this._selectCount(arg, options));
2846
+ }
2847
+ selectCount(arg, options) {
2848
+ return this.clone()._selectCount(arg, options);
2849
+ }
2850
+ _selectCount(arg = "*", options) {
2851
+ return this._selectAgg(aggregate1FunctionNames.count, arg === "*" ? allColumns : arg, options, parseIntColumn);
2852
+ }
2853
+ avg(arg, options) {
2854
+ return this.clone()._avg(arg, options);
2855
+ }
2856
+ _avg(arg, options) {
2857
+ return get(this._selectAvg(arg, options));
2858
+ }
2859
+ selectAvg(arg, options) {
2860
+ return this.clone()._selectAvg(arg, options);
2861
+ }
2862
+ _selectAvg(arg, options) {
2863
+ return this._selectAgg(aggregate1FunctionNames.avg, arg, options, parseIntOrNullColumn);
2864
+ }
2865
+ min(arg, options) {
2866
+ return this.clone()._min(arg, options);
2867
+ }
2868
+ _min(arg, options) {
2869
+ return get(this._selectMin(arg, options));
2870
+ }
2871
+ selectMin(arg, options) {
2872
+ return this.clone()._selectMin(arg, options);
2873
+ }
2874
+ _selectMin(arg, options) {
2875
+ return this._selectAgg(aggregate1FunctionNames.min, arg, options, parseIntOrNullColumn);
2876
+ }
2877
+ max(arg, options) {
2878
+ return this.clone()._max(arg, options);
2879
+ }
2880
+ _max(arg, options) {
2881
+ return get(this._selectMax(arg, options));
2882
+ }
2883
+ selectMax(arg, options) {
2884
+ return this.clone()._selectMax(arg, options);
2885
+ }
2886
+ _selectMax(arg, options) {
2887
+ return this._selectAgg(aggregate1FunctionNames.max, arg, options, parseIntOrNullColumn);
2888
+ }
2889
+ sum(arg, options) {
2890
+ return this.clone()._sum(arg, options);
2891
+ }
2892
+ _sum(arg, options) {
2893
+ return get(this._selectSum(arg, options));
2894
+ }
2895
+ selectSum(arg, options) {
2896
+ return this.clone()._selectSum(arg, options);
2897
+ }
2898
+ _selectSum(arg, options) {
2899
+ return this._selectAgg(aggregate1FunctionNames.sum, arg, options, parseIntOrNullColumn);
2900
+ }
2901
+ bitAnd(arg, options) {
2902
+ return this.clone()._bitAnd(arg, options);
2903
+ }
2904
+ _bitAnd(arg, options) {
2905
+ return get(this._selectBitAnd(arg, options));
2906
+ }
2907
+ selectBitAnd(arg, options) {
2908
+ return this.clone()._selectBitAnd(arg, options);
2909
+ }
2910
+ _selectBitAnd(arg, options) {
2911
+ return this._selectAgg(aggregate1FunctionNames.bitAnd, arg, options);
2912
+ }
2913
+ bitOr(arg, options) {
2914
+ return this.clone()._bitOr(arg, options);
2915
+ }
2916
+ _bitOr(arg, options) {
2917
+ return get(this._selectBitOr(arg, options));
2918
+ }
2919
+ selectBitOr(arg, options) {
2920
+ return this.clone()._selectBitOr(arg, options);
2921
+ }
2922
+ _selectBitOr(arg, options) {
2923
+ return this._selectAgg(aggregate1FunctionNames.bitOr, arg, options);
2924
+ }
2925
+ boolAnd(arg, options) {
2926
+ return this.clone()._boolAnd(arg, options);
2927
+ }
2928
+ _boolAnd(arg, options) {
2929
+ return get(this._selectBoolAnd(arg, options));
2930
+ }
2931
+ selectBoolAnd(arg, options) {
2932
+ return this.clone()._selectBoolAnd(arg, options);
2933
+ }
2934
+ _selectBoolAnd(arg, options) {
2935
+ return this._selectAgg(aggregate1FunctionNames.boolAnd, arg, options);
2936
+ }
2937
+ boolOr(arg, options) {
2938
+ return this.clone()._boolOr(arg, options);
2939
+ }
2940
+ _boolOr(arg, options) {
2941
+ return get(this._selectBoolOr(arg, options));
2942
+ }
2943
+ selectBoolOr(arg, options) {
2944
+ return this.clone()._selectBoolOr(arg, options);
2945
+ }
2946
+ _selectBoolOr(arg, options) {
2947
+ return this._selectAgg(aggregate1FunctionNames.boolOr, arg, options);
2948
+ }
2949
+ every(arg, options) {
2950
+ return this.clone()._every(arg, options);
2951
+ }
2952
+ _every(arg, options) {
2953
+ return get(this._selectEvery(arg, options));
2954
+ }
2955
+ selectEvery(arg, options) {
2956
+ return this.clone()._selectEvery(arg, options);
2957
+ }
2958
+ _selectEvery(arg, options) {
2959
+ return this._selectAgg(aggregate1FunctionNames.every, arg, options);
2960
+ }
2961
+ jsonAgg(arg, options) {
2962
+ return this.clone()._jsonAgg(arg, options);
2963
+ }
2964
+ _jsonAgg(arg, options) {
2965
+ return get(this._selectJsonAgg(arg, options));
2966
+ }
2967
+ selectJsonAgg(arg, options) {
2968
+ return this.clone()._selectJsonAgg(arg, options);
2969
+ }
2970
+ _selectJsonAgg(arg, options) {
2971
+ return this._selectAgg(aggregate1FunctionNames.jsonAgg, arg, options);
2972
+ }
2973
+ jsonbAgg(arg, options) {
2974
+ return this.clone()._jsonbAgg(arg, options);
2975
+ }
2976
+ _jsonbAgg(arg, options) {
2977
+ return get(this._selectJsonbAgg(arg, options));
2978
+ }
2979
+ selectJsonbAgg(arg, options) {
2980
+ return this.clone()._selectJsonbAgg(arg, options);
2981
+ }
2982
+ _selectJsonbAgg(arg, options) {
2983
+ return this._selectAgg(aggregate1FunctionNames.jsonbAgg, arg, options);
2984
+ }
2985
+ xmlAgg(arg, options) {
2986
+ return this.clone()._xmlAgg(arg, options);
2987
+ }
2988
+ _xmlAgg(arg, options) {
2989
+ return get(this._selectXmlAgg(arg, options));
2990
+ }
2991
+ selectXmlAgg(arg, options) {
2992
+ return this.clone()._selectXmlAgg(arg, options);
2993
+ }
2994
+ _selectXmlAgg(arg, options) {
2995
+ return this._selectAgg(aggregate1FunctionNames.xmlAgg, arg, options);
2996
+ }
2997
+ jsonObjectAgg(obj, options) {
2998
+ return this.clone()._jsonObjectAgg(obj, options);
2999
+ }
3000
+ _jsonObjectAgg(obj, options) {
3001
+ return get(this._selectJsonObjectAgg(obj, options));
3002
+ }
3003
+ selectJsonObjectAgg(obj, options) {
3004
+ return this.clone()._selectJsonObjectAgg(obj, options);
3005
+ }
3006
+ _selectJsonObjectAgg(obj, options) {
3007
+ return this._selectAgg("json_object_agg", obj, options);
3008
+ }
3009
+ jsonbObjectAgg(obj, options) {
3010
+ return this.clone()._jsonbObjectAgg(obj, options);
3011
+ }
3012
+ _jsonbObjectAgg(obj, options) {
3013
+ return get(this._selectJsonbObjectAgg(obj, options));
3014
+ }
3015
+ selectJsonbObjectAgg(obj, options) {
3016
+ return this.clone()._selectJsonbObjectAgg(obj, options);
3017
+ }
3018
+ _selectJsonbObjectAgg(obj, options) {
3019
+ return this._selectAgg("jsonb_object_agg", obj, options);
3020
+ }
3021
+ stringAgg(arg, delimiter, options) {
3022
+ return this.clone()._stringAgg(arg, delimiter, options);
3023
+ }
3024
+ _stringAgg(arg, delimiter, options) {
3025
+ return get(this._selectStringAgg(arg, delimiter, options));
3026
+ }
3027
+ selectStringAgg(arg, delimiter, options) {
3028
+ return this.clone()._selectStringAgg(arg, delimiter, options);
3029
+ }
3030
+ _selectStringAgg(arg, delimiter, options) {
3031
+ return this._selectAgg("string_agg", [arg, delimiter], options);
3032
+ }
3033
+ }
3034
+
3035
+ class From {
3036
+ from(...args) {
3037
+ return this.clone()._from(...args);
3038
+ }
3039
+ _from(...args) {
3040
+ let as;
3041
+ if (typeof args[1] === "string") {
3042
+ as = args[1];
3043
+ } else if (typeof args[1] === "object" && args[1].as) {
3044
+ as = args[1].as;
3045
+ } else if (typeof args[0] === "string") {
3046
+ if (!this.query.as)
3047
+ as = args[0];
3048
+ } else if (!isRaw(args[0])) {
3049
+ as = args[0].query.as || args[0].table;
3050
+ }
3051
+ if (typeof args[1] === "object" && "only" in args[1]) {
3052
+ this.query.fromOnly = args[1].only;
3053
+ }
3054
+ const q = as ? this._as(as) : this;
3055
+ q.query.from = args[0];
3056
+ return q;
3057
+ }
3058
+ }
3059
+
3060
+ const addWhere = (q, args) => {
3061
+ return pushQueryArray(q, "and", args);
3062
+ };
3063
+ const addWhereNot = (q, args) => {
3064
+ return pushQueryValue(q, "and", {
3065
+ NOT: args
3066
+ });
3067
+ };
3068
+ const addOr = (q, args) => {
3069
+ return pushQueryArray(q, "or", args.map((item) => [item]));
3070
+ };
3071
+ const addOrNot = (q, args) => {
3072
+ return pushQueryArray(q, "or", args.map((item) => [{ NOT: item }]));
3073
+ };
3074
+ const addWhereIn = (q, and, arg, values, not) => {
3075
+ const op = not ? "notIn" : "in";
3076
+ let item;
3077
+ if (values) {
3078
+ if (Array.isArray(arg)) {
3079
+ item = {
3080
+ IN: {
3081
+ columns: arg,
3082
+ values
3083
+ }
3084
+ };
3085
+ if (not)
3086
+ item = { NOT: item };
3087
+ } else {
3088
+ item = { [arg]: { [op]: values } };
3089
+ }
3090
+ } else {
3091
+ item = {};
3092
+ for (const key in arg) {
3093
+ item[key] = { [op]: arg[key] };
3094
+ }
3095
+ }
3096
+ if (and) {
3097
+ pushQueryValue(q, "and", item);
3098
+ } else {
3099
+ pushQueryValue(q, "or", [item]);
3100
+ }
3101
+ return q;
3102
+ };
3103
+ class Where {
3104
+ constructor() {
3105
+ this.query = {};
3106
+ }
3107
+ where(...args) {
3108
+ return this.clone()._where(...args);
3109
+ }
3110
+ _where(...args) {
3111
+ return addWhere(this, args);
3112
+ }
3113
+ whereNot(...args) {
3114
+ return this.clone()._whereNot(...args);
3115
+ }
3116
+ _whereNot(...args) {
3117
+ return addWhereNot(this, args);
3118
+ }
3119
+ and(...args) {
3120
+ return this.where(...args);
3121
+ }
3122
+ _and(...args) {
3123
+ return this._where(...args);
3124
+ }
3125
+ andNot(...args) {
3126
+ return this.whereNot(...args);
3127
+ }
3128
+ _andNot(...args) {
3129
+ return this._whereNot(...args);
3130
+ }
3131
+ or(...args) {
3132
+ return this.clone()._or(...args);
3133
+ }
3134
+ _or(...args) {
3135
+ return addOr(this, args);
3136
+ }
3137
+ orNot(...args) {
3138
+ return this.clone()._orNot(...args);
3139
+ }
3140
+ _orNot(...args) {
3141
+ return addOrNot(this, args);
3142
+ }
3143
+ whereIn(arg, values) {
3144
+ return this.clone()._whereIn(arg, values);
3145
+ }
3146
+ _whereIn(arg, values) {
3147
+ return addWhereIn(this, true, arg, values);
3148
+ }
3149
+ orWhereIn(arg, values) {
3150
+ return this.clone()._orWhereIn(arg, values);
3151
+ }
3152
+ _orWhereIn(arg, values) {
3153
+ return addWhereIn(this, false, arg, values);
3154
+ }
3155
+ whereNotIn(arg, values) {
3156
+ return this.clone()._whereNotIn(arg, values);
3157
+ }
3158
+ _whereNotIn(arg, values) {
3159
+ return addWhereIn(this, true, arg, values, true);
3160
+ }
3161
+ orWhereNotIn(arg, values) {
3162
+ return this.clone()._orWhereNotIn(arg, values);
3163
+ }
3164
+ _orWhereNotIn(arg, values) {
3165
+ return addWhereIn(this, false, arg, values, true);
3166
+ }
3167
+ whereExists(...args) {
3168
+ return this.clone()._whereExists(...args);
3169
+ }
3170
+ _whereExists(...args) {
3171
+ return this._where({ EXISTS: args });
3172
+ }
3173
+ orWhereExists(...args) {
3174
+ return this.clone()._orWhereExists(...args);
3175
+ }
3176
+ _orWhereExists(...args) {
3177
+ return this._or({ EXISTS: args });
3178
+ }
3179
+ whereNotExists(...args) {
3180
+ return this.clone()._whereNotExists(...args);
3181
+ }
3182
+ _whereNotExists(...args) {
3183
+ return this._whereNot({ EXISTS: args });
3184
+ }
3185
+ orWhereNotExists(...args) {
3186
+ return this.clone()._orWhereNotExists(...args);
3187
+ }
3188
+ _orWhereNotExists(...args) {
3189
+ return this._orNot({ EXISTS: args });
3190
+ }
3191
+ }
3192
+ class WhereQueryBuilder extends Where {
3193
+ constructor(table, tableAlias) {
3194
+ super();
3195
+ this.table = table;
3196
+ this.tableAlias = tableAlias;
3197
+ this.query = {};
3198
+ this.relations = {};
3199
+ this.withData = {};
3200
+ this.__model = this;
3201
+ }
3202
+ clone() {
3203
+ const cloned = Object.create(this.__model);
3204
+ cloned.query = getClonedQueryData(this.query);
3205
+ return cloned;
3206
+ }
3207
+ }
3208
+
3209
+ const join = (q, type, args) => {
3210
+ return _join(q.clone(), type, args);
3211
+ };
3212
+ const _join = (q, type, args) => {
3213
+ var _a;
3214
+ const first = args[0];
3215
+ let joinKey;
3216
+ let parsers;
3217
+ if (typeof first === "object") {
3218
+ const as = first.tableAlias || first.table;
3219
+ if (as) {
3220
+ joinKey = as;
3221
+ parsers = first.query.parsers || first.columnsParsers;
3222
+ }
3223
+ } else {
3224
+ joinKey = first;
3225
+ const relation = q.relations[joinKey];
3226
+ if (relation) {
3227
+ parsers = relation.model.query.parsers || relation.model.columnsParsers;
3228
+ } else {
3229
+ const shape = (_a = q.query.withShapes) == null ? void 0 : _a[first];
3230
+ if (shape) {
3231
+ parsers = {};
3232
+ for (const key in shape) {
3233
+ const parser = shape[key].parseFn;
3234
+ if (parser) {
3235
+ parsers[key] = parser;
3236
+ }
3237
+ }
3238
+ }
3239
+ }
3240
+ }
3241
+ if (joinKey && parsers) {
3242
+ setQueryObjectValue(q, "joinedParsers", joinKey, parsers);
3243
+ }
3244
+ return pushQueryValue(q, "join", {
3245
+ type,
3246
+ args
3247
+ });
3248
+ };
3249
+ class Join {
3250
+ join(...args) {
3251
+ return join(this, "JOIN", args);
3252
+ }
3253
+ _join(...args) {
3254
+ return _join(this, "JOIN", args);
3255
+ }
3256
+ innerJoin(...args) {
3257
+ return join(this, "INNER JOIN", args);
3258
+ }
3259
+ _innerJoin(...args) {
3260
+ return _join(this, "INNER JOIN", args);
3261
+ }
3262
+ leftJoin(...args) {
3263
+ return join(this, "LEFT JOIN", args);
3264
+ }
3265
+ _leftJoin(...args) {
3266
+ return _join(this, "LEFT JOIN", args);
3267
+ }
3268
+ leftOuterJoin(...args) {
3269
+ return join(this, "LEFT OUTER JOIN", args);
3270
+ }
3271
+ _leftOuterJoin(...args) {
3272
+ return _join(this, "LEFT OUTER JOIN", args);
3273
+ }
3274
+ rightJoin(...args) {
3275
+ return join(this, "RIGHT JOIN", args);
3276
+ }
3277
+ _rightJoin(...args) {
3278
+ return _join(this, "RIGHT JOIN", args);
3279
+ }
3280
+ rightOuterJoin(...args) {
3281
+ return join(this, "RIGHT OUTER JOIN", args);
3282
+ }
3283
+ _rightOuterJoin(...args) {
3284
+ return _join(this, "RIGHT OUTER JOIN", args);
3285
+ }
3286
+ fullOuterJoin(...args) {
3287
+ return join(this, "FULL OUTER JOIN", args);
3288
+ }
3289
+ _fullOuterJoin(...args) {
3290
+ return _join(this, "FULL OUTER JOIN", args);
3291
+ }
3292
+ }
3293
+ const makeOnItem = (joinTo, joinFrom, args) => {
3294
+ return {
3295
+ ON: {
3296
+ joinTo,
3297
+ joinFrom,
3298
+ on: args
3299
+ }
3300
+ };
3301
+ };
3302
+ const pushQueryOn = (q, joinFrom, joinTo, ...on) => {
3303
+ return pushQueryValue(q, "and", makeOnItem(joinFrom, joinTo, on));
3304
+ };
3305
+ const pushQueryOrOn = (q, joinFrom, joinTo, ...on) => {
3306
+ return pushQueryValue(q, "or", [makeOnItem(joinFrom, joinTo, on)]);
3307
+ };
3308
+ const addQueryOn = (q, joinFrom, joinTo, ...args) => {
3309
+ return pushQueryOn(q.clone(), joinFrom, joinTo, ...args);
3310
+ };
3311
+ const addQueryOrOn = (q, joinFrom, joinTo, ...args) => {
3312
+ return pushQueryOrOn(q.clone(), joinFrom, joinTo, ...args);
3313
+ };
3314
+ class OnQueryBuilder extends WhereQueryBuilder {
3315
+ constructor(q, joinTo) {
3316
+ super(q.table, q.query.as);
3317
+ this.joinTo = joinTo;
3318
+ }
3319
+ on(...args) {
3320
+ return this.clone()._on(...args);
3321
+ }
3322
+ _on(...args) {
3323
+ return pushQueryOn(this, this.joinTo, this, ...args);
3324
+ }
3325
+ orOn(...args) {
3326
+ return this.clone()._orOn(...args);
3327
+ }
3328
+ _orOn(...args) {
3329
+ return pushQueryOrOn(this, this.joinTo, this, ...args);
3330
+ }
3331
+ onJsonPathEquals(...args) {
3332
+ return this.clone()._onJsonPathEquals(...args);
3333
+ }
3334
+ _onJsonPathEquals(...args) {
3335
+ return pushQueryValue(this, "and", { ON: args });
3336
+ }
3337
+ }
3338
+
3339
+ var __defProp$4 = Object.defineProperty;
3340
+ var __defProps = Object.defineProperties;
3341
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
3342
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
3343
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
3344
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
3345
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3346
+ var __spreadValues$4 = (a, b) => {
3347
+ for (var prop in b || (b = {}))
3348
+ if (__hasOwnProp$4.call(b, prop))
3349
+ __defNormalProp$4(a, prop, b[prop]);
3350
+ if (__getOwnPropSymbols$4)
3351
+ for (var prop of __getOwnPropSymbols$4(b)) {
3352
+ if (__propIsEnum$4.call(b, prop))
3353
+ __defNormalProp$4(a, prop, b[prop]);
3354
+ }
3355
+ return a;
3356
+ };
3357
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3358
+ class With {
3359
+ with(...args) {
3360
+ return this.clone()._with(...args);
3361
+ }
3362
+ _with(...args) {
3363
+ let options = args.length === 3 && !isRaw(args[2]) || args.length === 4 ? args[1] : void 0;
3364
+ const last = args[args.length - 1];
3365
+ const query = typeof last === "function" ? last(this.queryBuilder) : last;
3366
+ const shape = args.length === 4 ? args[2] : query.shape;
3367
+ if ((options == null ? void 0 : options.columns) === true) {
3368
+ options = __spreadProps(__spreadValues$4({}, options), {
3369
+ columns: Object.keys(shape)
3370
+ });
3371
+ }
3372
+ pushQueryValue(this, "with", [args[0], options || EMPTY_OBJECT, query]);
3373
+ return setQueryObjectValue(this, "withShapes", args[0], shape);
3374
+ }
3375
+ }
3376
+
3377
+ class Union {
3378
+ union(args, wrap) {
3379
+ return this._union(args, wrap);
3380
+ }
3381
+ _union(args, wrap) {
3382
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "UNION", wrap })));
3383
+ }
3384
+ unionAll(args, wrap) {
3385
+ return this._unionAll(args, wrap);
3386
+ }
3387
+ _unionAll(args, wrap) {
3388
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "UNION ALL", wrap })));
3389
+ }
3390
+ intersect(args, wrap) {
3391
+ return this._intersect(args, wrap);
3392
+ }
3393
+ _intersect(args, wrap) {
3394
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "INTERSECT", wrap })));
3395
+ }
3396
+ intersectAll(args, wrap) {
3397
+ return this._intersectAll(args, wrap);
3398
+ }
3399
+ _intersectAll(args, wrap) {
3400
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "INTERSECT ALL", wrap })));
3401
+ }
3402
+ except(args, wrap) {
3403
+ return this._except(args, wrap);
3404
+ }
3405
+ _except(args, wrap) {
3406
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "EXCEPT", wrap })));
3407
+ }
3408
+ exceptAll(args, wrap) {
3409
+ return this._exceptAll(args, wrap);
3410
+ }
3411
+ _exceptAll(args, wrap) {
3412
+ return pushQueryArray(this, "union", args.map((arg) => ({ arg, kind: "EXCEPT ALL", wrap })));
3413
+ }
3414
+ }
3415
+
3416
+ class Json {
3417
+ json() {
3418
+ return this.clone()._json();
3419
+ }
3420
+ _json() {
3421
+ const q = this._wrap(this.__model.clone());
3422
+ q._getOptional(raw(this.query.take ? `row_to_json("t".*)` : `COALESCE(json_agg(row_to_json("t".*)), '[]')`));
3423
+ delete q.query.take;
3424
+ return q;
3425
+ }
3426
+ jsonSet(column, path, value, options) {
3427
+ const q = this.clone();
3428
+ return q._jsonSet(column, path, value, options);
3429
+ }
3430
+ _jsonSet(column, path, value, options) {
3431
+ var _a;
3432
+ const json = {
3433
+ __json: [
3434
+ "set",
3435
+ (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
3436
+ typeof column === "string" ? this.shape[column] : column.__json[2],
3437
+ column,
3438
+ path,
3439
+ value,
3440
+ options
3441
+ ]
3442
+ };
3443
+ return Object.assign(pushQueryValue(this, "select", json), json);
3444
+ }
3445
+ jsonInsert(...args) {
3446
+ const q = this.clone();
3447
+ return q._jsonInsert(...args);
3448
+ }
3449
+ _jsonInsert(column, path, value, options) {
3450
+ var _a;
3451
+ const json = {
3452
+ __json: [
3453
+ "insert",
3454
+ (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
3455
+ typeof column === "string" ? this.shape[column] : column.__json[2],
3456
+ column,
3457
+ path,
3458
+ value,
3459
+ options
3460
+ ]
3461
+ };
3462
+ return Object.assign(pushQueryValue(this, "select", json), json);
3463
+ }
3464
+ jsonRemove(...args) {
3465
+ const q = this.clone();
3466
+ return q._jsonRemove(...args);
3467
+ }
3468
+ _jsonRemove(column, path, options) {
3469
+ var _a;
3470
+ const json = {
3471
+ __json: [
3472
+ "remove",
3473
+ (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
3474
+ typeof column === "string" ? this.shape[column] : column.__json[2],
3475
+ column,
3476
+ path
3477
+ ]
3478
+ };
3479
+ return Object.assign(pushQueryValue(this, "select", json), json);
3480
+ }
3481
+ jsonPathQuery(...args) {
3482
+ const q = this.clone();
3483
+ return q._jsonPathQuery(...args);
3484
+ }
3485
+ _jsonPathQuery(type, column, path, as, options) {
3486
+ const json = {
3487
+ __json: ["pathQuery", as, type, column, path, options]
3488
+ };
3489
+ return Object.assign(pushQueryValue(this, "select", json), json);
3490
+ }
3491
+ }
3492
+
3493
+ var __defProp$3 = Object.defineProperty;
3494
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
3495
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
3496
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
3497
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3498
+ var __spreadValues$3 = (a, b) => {
3499
+ for (var prop in b || (b = {}))
3500
+ if (__hasOwnProp$3.call(b, prop))
3501
+ __defNormalProp$3(a, prop, b[prop]);
3502
+ if (__getOwnPropSymbols$3)
3503
+ for (var prop of __getOwnPropSymbols$3(b)) {
3504
+ if (__propIsEnum$3.call(b, prop))
3505
+ __defNormalProp$3(a, prop, b[prop]);
3506
+ }
3507
+ return a;
3508
+ };
3509
+ const processInsertItem = (item, rowIndex, relations, prependRelations, appendRelations, requiredReturning, columns, columnsMap) => {
3510
+ Object.keys(item).forEach((key) => {
3511
+ if (relations[key]) {
3512
+ if (relations[key].type === "belongsTo") {
3513
+ const foreignKey = relations[key].options.foreignKey;
3514
+ let columnIndex = columnsMap[foreignKey];
3515
+ if (columnIndex === void 0) {
3516
+ columnsMap[foreignKey] = columnIndex = columns.length;
3517
+ columns.push(foreignKey);
3518
+ }
3519
+ if (!prependRelations[key])
3520
+ prependRelations[key] = [];
3521
+ prependRelations[key].push([
3522
+ rowIndex,
3523
+ columnIndex,
3524
+ item[key]
3525
+ ]);
3526
+ } else {
3527
+ requiredReturning[relations[key].primaryKey] = true;
3528
+ if (!appendRelations[key])
3529
+ appendRelations[key] = [];
3530
+ appendRelations[key].push([rowIndex, item[key]]);
3531
+ }
3532
+ } else if (columnsMap[key] === void 0) {
3533
+ columnsMap[key] = columns.length;
3534
+ columns.push(key);
3535
+ }
3536
+ });
3537
+ };
3538
+ class Insert {
3539
+ insert(data) {
3540
+ return this.clone()._insert(data);
3541
+ }
3542
+ _insert(data) {
3543
+ const q = this;
3544
+ const returning = q.query.select;
3545
+ delete q.query.and;
3546
+ delete q.query.or;
3547
+ let columns;
3548
+ const prependRelations = {};
3549
+ const appendRelations = {};
3550
+ const requiredReturning = {};
3551
+ const relations = this.relations;
3552
+ let values;
3553
+ let returnType = q.query.returnType;
3554
+ if (returning) {
3555
+ if (Array.isArray(data)) {
3556
+ if (returnType === "one" || returnType === "oneOrThrow") {
3557
+ returnType = "all";
3558
+ }
3559
+ } else {
3560
+ if (returnType === "all") {
3561
+ returnType = "one";
3562
+ }
3563
+ }
3564
+ } else {
3565
+ returnType = "rowCount";
3566
+ }
3567
+ if ("values" in data && typeof data.values === "object" && data.values && isRaw(data.values)) {
3568
+ columns = data.columns;
3569
+ values = data.values;
3570
+ } else {
3571
+ columns = [];
3572
+ const columnsMap = {};
3573
+ const defaults = q.query.defaults;
3574
+ if (Array.isArray(data)) {
3575
+ if (defaults) {
3576
+ data = data.map((item) => __spreadValues$3(__spreadValues$3({}, defaults), item));
3577
+ }
3578
+ data.forEach((item, i) => {
3579
+ processInsertItem(item, i, relations, prependRelations, appendRelations, requiredReturning, columns, columnsMap);
3580
+ });
3581
+ values = Array(data.length);
3582
+ data.forEach((item, i) => {
3583
+ values[i] = columns.map((key) => item[key]);
3584
+ });
3585
+ } else {
3586
+ if (defaults) {
3587
+ data = __spreadValues$3(__spreadValues$3({}, defaults), data);
3588
+ }
3589
+ processInsertItem(data, 0, relations, prependRelations, appendRelations, requiredReturning, columns, columnsMap);
3590
+ values = [columns.map((key) => data[key])];
3591
+ }
3592
+ }
3593
+ const prependRelationsKeys = Object.keys(prependRelations);
3594
+ if (prependRelationsKeys.length) {
3595
+ pushQueryArray(q, "beforeQuery", prependRelationsKeys.map((relationName) => {
3596
+ return async (q2) => {
3597
+ const relationData = prependRelations[relationName];
3598
+ const relation = relations[relationName];
3599
+ const inserted = await relation.nestedInsert(q2, relationData.map(([, , data2]) => data2));
3600
+ const primaryKey = relation.options.primaryKey;
3601
+ relationData.forEach(([rowIndex, columnIndex], index) => {
3602
+ values[rowIndex][columnIndex] = inserted[index][primaryKey];
3603
+ });
3604
+ };
3605
+ }));
3606
+ }
3607
+ const appendRelationsKeys = Object.keys(appendRelations);
3608
+ if (appendRelationsKeys.length) {
3609
+ if (!(returning == null ? void 0 : returning.includes("*"))) {
3610
+ const requiredColumns = Object.keys(requiredReturning);
3611
+ if (!returning) {
3612
+ q.query.select = requiredColumns;
3613
+ } else {
3614
+ q.query.select = [
3615
+ .../* @__PURE__ */ new Set([...returning, ...requiredColumns])
3616
+ ];
3617
+ }
3618
+ }
3619
+ let resultOfTypeAll;
3620
+ if (returnType !== "all") {
3621
+ const { handleResult } = q.query;
3622
+ q.query.handleResult = async (q2, queryResult) => {
3623
+ resultOfTypeAll = await handleResult(q2, queryResult);
3624
+ if (queryMethodByReturnType[returnType] === "arrays") {
3625
+ queryResult.rows.forEach((row, i) => queryResult.rows[i] = Object.values(row));
3626
+ }
3627
+ return parseResult(q2, returnType, queryResult);
3628
+ };
3629
+ }
3630
+ pushQueryArray(q, "afterQuery", appendRelationsKeys.map((relationName) => {
3631
+ return (q2, result) => {
3632
+ var _a, _b;
3633
+ const all = resultOfTypeAll || result;
3634
+ return (_b = (_a = relations[relationName]).nestedInsert) == null ? void 0 : _b.call(_a, q2, appendRelations[relationName].map(([rowIndex, data2]) => [
3635
+ all[rowIndex],
3636
+ data2
3637
+ ]));
3638
+ };
3639
+ }));
3640
+ }
3641
+ q.query.type = "insert";
3642
+ q.query.columns = columns;
3643
+ q.query.values = values;
3644
+ if (prependRelationsKeys.length || appendRelationsKeys.length) {
3645
+ q.query.wrapInTransaction = true;
3646
+ }
3647
+ q.query.returnType = appendRelationsKeys.length ? "all" : returnType;
3648
+ return q;
3649
+ }
3650
+ create(data) {
3651
+ return this.clone()._create(data);
3652
+ }
3653
+ _create(data) {
3654
+ if (!this.query.select) {
3655
+ this.query.select = ["*"];
3656
+ }
3657
+ return this.insert(data);
3658
+ }
3659
+ defaults(data) {
3660
+ return this.clone()._defaults(data);
3661
+ }
3662
+ _defaults(data) {
3663
+ this.query.defaults = data;
3664
+ return this;
3665
+ }
3666
+ onConflict(arg) {
3667
+ return this.clone()._onConflict(arg);
3668
+ }
3669
+ _onConflict(arg) {
3670
+ return new OnConflictQueryBuilder(this, arg);
3671
+ }
3672
+ }
3673
+ class OnConflictQueryBuilder {
3674
+ constructor(query, onConflict) {
3675
+ this.query = query;
3676
+ this.onConflict = onConflict;
3677
+ }
3678
+ ignore() {
3679
+ this.query.query.onConflict = {
3680
+ type: "ignore",
3681
+ expr: this.onConflict
3682
+ };
3683
+ return this.query;
3684
+ }
3685
+ merge(update) {
3686
+ this.query.query.onConflict = {
3687
+ type: "merge",
3688
+ expr: this.onConflict,
3689
+ update
3690
+ };
3691
+ return this.query;
3692
+ }
3693
+ }
3694
+
3695
+ var __defProp$2 = Object.defineProperty;
3696
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
3697
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
3698
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
3699
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3700
+ var __spreadValues$2 = (a, b) => {
3701
+ for (var prop in b || (b = {}))
3702
+ if (__hasOwnProp$2.call(b, prop))
3703
+ __defNormalProp$2(a, prop, b[prop]);
3704
+ if (__getOwnPropSymbols$2)
3705
+ for (var prop of __getOwnPropSymbols$2(b)) {
3706
+ if (__propIsEnum$2.call(b, prop))
3707
+ __defNormalProp$2(a, prop, b[prop]);
3708
+ }
3709
+ return a;
3710
+ };
3711
+ const applyCountChange = (self, op, data) => {
3712
+ self.query.type = "update";
3713
+ let map;
3714
+ if (typeof data === "object") {
3715
+ map = {};
3716
+ for (const key in data) {
3717
+ map[key] = { op, arg: data[key] };
3718
+ }
3719
+ } else {
3720
+ map = { [data]: { op, arg: 1 } };
3721
+ }
3722
+ pushQueryValue(self, "data", map);
3723
+ return self;
3724
+ };
3725
+ class Update {
3726
+ update(...args) {
3727
+ const q = this.clone();
3728
+ return q._update(...args);
3729
+ }
3730
+ _update(...args) {
3731
+ var _a, _b, _c, _d;
3732
+ const [data, forceAll] = args;
3733
+ const { query } = this;
3734
+ query.type = "update";
3735
+ if (!((_a = query.and) == null ? void 0 : _a.length) && !((_b = query.or) == null ? void 0 : _b.length) && !forceAll) {
3736
+ throw new Error("No where conditions or forceAll flag provided to update");
3737
+ }
3738
+ if (isRaw(data)) {
3739
+ pushQueryValue(this, "data", data);
3740
+ } else {
3741
+ const relations = this.relations;
3742
+ const prependRelations = {};
3743
+ const appendRelations = {};
3744
+ const originalReturnType = this.query.returnType;
3745
+ const update = __spreadValues$2({}, data);
3746
+ for (const key in data) {
3747
+ if (relations[key]) {
3748
+ delete update[key];
3749
+ if (relations[key].type === "belongsTo") {
3750
+ prependRelations[key] = data[key];
3751
+ } else {
3752
+ if (!((_c = query.select) == null ? void 0 : _c.includes("*"))) {
3753
+ const primaryKey = relations[key].primaryKey;
3754
+ if (!((_d = query.select) == null ? void 0 : _d.includes(primaryKey))) {
3755
+ this._select(primaryKey);
3756
+ }
3757
+ }
3758
+ appendRelations[key] = data[key];
3759
+ }
3760
+ }
3761
+ }
3762
+ const state = {};
3763
+ const prependRelationKeys = Object.keys(prependRelations);
3764
+ if (prependRelationKeys.length) {
3765
+ const willSetKeys = prependRelationKeys.some((relationName) => {
3766
+ const data2 = prependRelations[relationName];
3767
+ return relations[relationName].nestedUpdate(this, update, data2, state);
3768
+ });
3769
+ if (!willSetKeys && !Object.keys(update).length) {
3770
+ delete this.query.type;
3771
+ }
3772
+ } else if (!Object.keys(update).length) {
3773
+ delete this.query.type;
3774
+ }
3775
+ const appendRelationKeys = Object.keys(appendRelations);
3776
+ let resultOfTypeAll;
3777
+ if ((state == null ? void 0 : state.updateLater) || appendRelationKeys.length && originalReturnType !== "all") {
3778
+ this.query.returnType = "all";
3779
+ if (state == null ? void 0 : state.updateLater) {
3780
+ this.schema.primaryKeys.forEach((key) => {
3781
+ var _a2, _b2;
3782
+ if (!((_a2 = query.select) == null ? void 0 : _a2.includes("*")) && !((_b2 = query.select) == null ? void 0 : _b2.includes(key))) {
3783
+ this._select(key);
3784
+ }
3785
+ });
3786
+ }
3787
+ const { handleResult } = this.query;
3788
+ this.query.handleResult = async (q, queryResult) => {
3789
+ resultOfTypeAll = await handleResult(q, queryResult);
3790
+ if (state == null ? void 0 : state.updateLater) {
3791
+ await Promise.all(state.updateLaterPromises);
3792
+ const t = this.__model.clone().transacting(q);
3793
+ const keys = this.schema.primaryKeys;
3794
+ t._whereIn(keys, resultOfTypeAll.map((item) => keys.map((key) => item[key])));
3795
+ await t._update(state.updateLater);
3796
+ resultOfTypeAll.forEach((item) => Object.assign(item, state.updateLater));
3797
+ }
3798
+ if (queryMethodByReturnType[originalReturnType] === "arrays") {
3799
+ queryResult.rows.forEach((row, i) => queryResult.rows[i] = Object.values(row));
3800
+ }
3801
+ return parseResult(q, originalReturnType, queryResult);
3802
+ };
3803
+ }
3804
+ if (appendRelationKeys.length) {
3805
+ pushQueryArray(this, "afterQuery", appendRelationKeys.map((relationName) => {
3806
+ return (q, result) => {
3807
+ var _a2, _b2;
3808
+ const all = resultOfTypeAll || result;
3809
+ return (_b2 = (_a2 = relations[relationName]).nestedUpdate) == null ? void 0 : _b2.call(_a2, q, all, appendRelations[relationName]);
3810
+ };
3811
+ }));
3812
+ }
3813
+ if (prependRelationKeys.length || appendRelationKeys.length) {
3814
+ query.wrapInTransaction = true;
3815
+ }
3816
+ pushQueryValue(this, "data", update);
3817
+ }
3818
+ if (!query.select) {
3819
+ this.query.returnType = "rowCount";
3820
+ }
3821
+ return this;
3822
+ }
3823
+ updateOrThrow(...args) {
3824
+ const q = this.clone();
3825
+ return q._updateOrThrow(...args);
3826
+ }
3827
+ _updateOrThrow(...args) {
3828
+ this.query.throwOnNotFound = true;
3829
+ return this._update(...args);
3830
+ }
3831
+ increment(data) {
3832
+ return this.clone()._increment(data);
3833
+ }
3834
+ _increment(data) {
3835
+ return applyCountChange(this, "+", data);
3836
+ }
3837
+ decrement(data) {
3838
+ return this.clone()._decrement(data);
3839
+ }
3840
+ _decrement(data) {
3841
+ return applyCountChange(this, "-", data);
3842
+ }
3843
+ }
3844
+
3845
+ const del = (self, ...args) => {
3846
+ return self.clone()._del(...args);
3847
+ };
3848
+ const _del = (q, ...args) => {
3849
+ var _a, _b;
3850
+ if (!((_a = q.query.and) == null ? void 0 : _a.length) && !((_b = q.query.or) == null ? void 0 : _b.length) && !args[0]) {
3851
+ throw new Error("No where conditions or forceAll flag provided to delete");
3852
+ }
3853
+ if (!q.query.select) {
3854
+ q.query.returnType = "rowCount";
3855
+ }
3856
+ q.query.type = "delete";
3857
+ return q;
3858
+ };
3859
+ class Delete {
3860
+ del(...args) {
3861
+ return del(this, ...args);
3862
+ }
3863
+ _del(...args) {
3864
+ return _del(this, ...args);
3865
+ }
3866
+ delete(...args) {
3867
+ return del(this, ...args);
3868
+ }
3869
+ _delete(...args) {
3870
+ return _del(this, ...args);
3871
+ }
3872
+ }
3873
+
3874
+ const beginSql = {
3875
+ text: "BEGIN",
3876
+ values: []
3877
+ };
3878
+ const commitSql = {
3879
+ text: "COMMIT",
3880
+ values: []
3881
+ };
3882
+ const rollbackSql = {
3883
+ text: "ROLLBACK",
3884
+ values: []
3885
+ };
3886
+ class Transaction {
3887
+ async transaction(cb) {
3888
+ const log = this.query.log;
3889
+ let logData;
3890
+ if (log) {
3891
+ logData = log.beforeQuery(this, beginSql);
3892
+ }
3893
+ const t = this.query.adapter.transaction((adapter) => {
3894
+ if (log) {
3895
+ log.afterQuery(this, beginSql, logData);
3896
+ }
3897
+ const q = this.clone();
3898
+ q.query.adapter = adapter;
3899
+ q.query.inTransaction = true;
3900
+ if (log) {
3901
+ logData = log.beforeQuery(this, commitSql);
3902
+ }
3903
+ return cb(q);
3904
+ });
3905
+ if (log) {
3906
+ t.then(() => {
3907
+ log.afterQuery(this, commitSql, logData);
3908
+ }, () => {
3909
+ log.afterQuery(this, rollbackSql, logData);
3910
+ });
3911
+ }
3912
+ return t;
3913
+ }
3914
+ transacting(query) {
3915
+ return this.clone()._transacting(query);
3916
+ }
3917
+ _transacting(query) {
3918
+ this.query.adapter = query.query.adapter;
3919
+ this.query.inTransaction = true;
3920
+ return this;
3921
+ }
3922
+ }
3923
+
3924
+ const forQueryBuilder = (q, type, tableNames) => {
3925
+ q.query.for = { type, tableNames };
3926
+ q.__model = Object.create(q.__model);
3927
+ q.__model.__model = q.__model;
3928
+ Object.assign(q.__model, {
3929
+ noWait() {
3930
+ return this.clone()._noWait();
3931
+ },
3932
+ _noWait() {
3933
+ const q2 = this.query;
3934
+ if (q2 == null ? void 0 : q2.for)
3935
+ q2.for.mode = "NO WAIT";
3936
+ return this;
3937
+ },
3938
+ skipLocked() {
3939
+ return this.clone()._skipLocked();
3940
+ },
3941
+ _skipLocked() {
3942
+ const q2 = this.query;
3943
+ if (q2 == null ? void 0 : q2.for)
3944
+ q2.for.mode = "SKIP LOCKED";
3945
+ return this;
3946
+ }
3947
+ });
3948
+ return q.clone();
3949
+ };
3950
+ class For {
3951
+ forUpdate(tableNames) {
3952
+ return this.clone()._forUpdate(tableNames);
3953
+ }
3954
+ _forUpdate(tableNames) {
3955
+ return forQueryBuilder(this, "UPDATE", tableNames);
3956
+ }
3957
+ forNoKeyUpdate(tableNames) {
3958
+ return this.clone()._forNoKeyUpdate(tableNames);
3959
+ }
3960
+ _forNoKeyUpdate(tableNames) {
3961
+ return forQueryBuilder(this, "NO KEY UPDATE", tableNames);
3962
+ }
3963
+ forShare(tableNames) {
3964
+ return this.clone()._forShare(tableNames);
3965
+ }
3966
+ _forShare(tableNames) {
3967
+ return forQueryBuilder(this, "SHARE", tableNames);
3968
+ }
3969
+ forKeyShare(tableNames) {
3970
+ return this.clone()._forKeyShare(tableNames);
3971
+ }
3972
+ _forKeyShare(tableNames) {
3973
+ return forQueryBuilder(this, "KEY SHARE", tableNames);
3974
+ }
3975
+ }
3976
+
3977
+ const rowToColumnInfo = (row) => {
3978
+ const typed = row;
3979
+ return {
3980
+ defaultValue: typed.column_default,
3981
+ type: typed.data_type,
3982
+ maxLength: typed.character_maximum_length,
3983
+ nullable: typed.is_nullable === "YES"
3984
+ };
3985
+ };
3986
+ class ColumnInfoMethods {
3987
+ columnInfo(column) {
3988
+ return this.clone()._columnInfo(column);
3989
+ }
3990
+ _columnInfo(column) {
3991
+ this.query.type = "columnInfo";
3992
+ this.query.returnType = "all";
3993
+ if (column) {
3994
+ this.query.column = column;
3995
+ }
3996
+ this.then = function(resolve, reject) {
3997
+ new Then().then.call(this, (rows) => {
3998
+ if (column) {
3999
+ resolve == null ? void 0 : resolve(rowToColumnInfo(rows[0]));
4000
+ } else {
4001
+ const info = {};
4002
+ rows.forEach((row) => {
4003
+ info[row.column_name] = rowToColumnInfo(row);
4004
+ });
4005
+ resolve == null ? void 0 : resolve(info);
4006
+ }
4007
+ }, reject);
4008
+ };
4009
+ return this;
4010
+ }
4011
+ }
4012
+
4013
+ class Clear {
4014
+ clear(...clears) {
4015
+ return this.clone()._clear(...clears);
4016
+ }
4017
+ _clear(...clears) {
4018
+ clears.forEach((clear) => {
4019
+ if (clear === "where") {
4020
+ removeFromQuery(this, "and");
4021
+ removeFromQuery(this, "or");
4022
+ } else if (clear === "counters") {
4023
+ if ("type" in this.query && this.query.type === "update") {
4024
+ this.query.data = this.query.data.filter((item) => {
4025
+ if (!isRaw(item)) {
4026
+ let removed = false;
4027
+ for (const key in item) {
4028
+ const value = item[key];
4029
+ if (typeof value === "object" && (value.op === "+" || value.op === "-")) {
4030
+ delete item[key];
4031
+ removed = true;
4032
+ }
4033
+ }
4034
+ if (removed && !Object.keys(item).length) {
4035
+ return false;
4036
+ }
4037
+ }
4038
+ return true;
4039
+ });
4040
+ }
4041
+ } else {
4042
+ removeFromQuery(this, clear);
4043
+ }
4044
+ });
4045
+ return this;
4046
+ }
4047
+ }
4048
+
4049
+ var __defProp$1 = Object.defineProperty;
4050
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
4051
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
4052
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
4053
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4054
+ var __spreadValues$1 = (a, b) => {
4055
+ for (var prop in b || (b = {}))
4056
+ if (__hasOwnProp$1.call(b, prop))
4057
+ __defNormalProp$1(a, prop, b[prop]);
4058
+ if (__getOwnPropSymbols$1)
4059
+ for (var prop of __getOwnPropSymbols$1(b)) {
4060
+ if (__propIsEnum$1.call(b, prop))
4061
+ __defNormalProp$1(a, prop, b[prop]);
4062
+ }
4063
+ return a;
4064
+ };
4065
+ const processHavingArg = (arg) => {
4066
+ if ("__model" in arg || isRaw(arg)) {
4067
+ return arg;
4068
+ } else {
4069
+ const processed = __spreadValues$1({}, arg);
4070
+ for (const fn in arg) {
4071
+ const data = arg[fn];
4072
+ if (typeof data === "object") {
4073
+ processed[fn] = __spreadValues$1({}, data);
4074
+ for (const column in data) {
4075
+ const value = data[column];
4076
+ if (typeof value === "object") {
4077
+ processed[fn][column] = __spreadValues$1({}, value);
4078
+ const options = value;
4079
+ if ("order" in options && options.order && !Array.isArray(options.order)) {
4080
+ processed[fn][column].order = [options.order];
4081
+ }
4082
+ if ("filter" in options && options.filter) {
4083
+ processed[fn][column].filter = options.filter;
4084
+ }
4085
+ if ("filterOr" in options && options.filterOr) {
4086
+ processed[fn][column].filterOr = options.filterOr;
4087
+ }
4088
+ }
4089
+ }
4090
+ }
4091
+ }
4092
+ return processed;
4093
+ }
4094
+ };
4095
+ class Having {
4096
+ having(...args) {
4097
+ return this.clone()._having(...args);
4098
+ }
4099
+ _having(...args) {
4100
+ return pushQueryArray(this, "having", args.map((arg) => processHavingArg(arg)));
4101
+ }
4102
+ havingOr(...args) {
4103
+ return this.clone()._havingOr(...args);
4104
+ }
4105
+ _havingOr(...args) {
4106
+ return pushQueryArray(this, "havingOr", args.map((arg) => [processHavingArg(arg)]));
4107
+ }
4108
+ }
4109
+
4110
+ const selectWindowFunction = (self, functionName, options, parse) => {
4111
+ pushQueryValue(self, "select", {
4112
+ function: functionName,
4113
+ options: {
4114
+ as: options.as,
4115
+ over: options
4116
+ }
4117
+ });
4118
+ if (parse) {
4119
+ addParserToQuery(self.query, options.as || functionName, parse);
4120
+ }
4121
+ return self;
4122
+ };
4123
+ const toInt = (input) => parseInt(input);
4124
+ class Window {
4125
+ selectRowNumber(options) {
4126
+ return this.clone()._selectRowNumber(options);
4127
+ }
4128
+ _selectRowNumber(options) {
4129
+ return selectWindowFunction(this, "row_number", options, toInt);
4130
+ }
4131
+ selectRank(options) {
4132
+ return this.clone()._selectRank(options);
4133
+ }
4134
+ _selectRank(options) {
4135
+ return selectWindowFunction(this, "rank", options, toInt);
4136
+ }
4137
+ selectDenseRank(options) {
4138
+ return this.clone()._selectDenseRank(options);
4139
+ }
4140
+ _selectDenseRank(options) {
4141
+ return selectWindowFunction(this, "dense_rank", options, toInt);
4142
+ }
4143
+ selectPercentRank(options) {
4144
+ return this.clone()._selectPercentRank(options);
4145
+ }
4146
+ _selectPercentRank(options) {
4147
+ return selectWindowFunction(this, "percent_rank", options, toInt);
4148
+ }
4149
+ selectCumeDist(options) {
4150
+ return this.clone()._selectCumeDist(options);
4151
+ }
4152
+ _selectCumeDist(options) {
4153
+ return selectWindowFunction(this, "cume_dist", options, toInt);
4154
+ }
4155
+ }
4156
+
4157
+ const logColors = {
4158
+ boldCyanBright: (message) => `\x1B[1m\x1B[96m${message}\x1B[39m\x1B[22m`,
4159
+ boldBlue: (message) => `\x1B[1m\x1B[34m${message}\x1B[39m\x1B[22m`,
4160
+ boldYellow: (message) => `\x1B[1m\x1B[33m${message}\x1B[39m\x1B[22m`,
4161
+ boldMagenta: (message) => `\x1B[1m\x1B[33m${message}\x1B[39m\x1B[22m`,
4162
+ boldRed: (message) => `\x1B[1m\x1B[31m${message}\x1B[39m\x1B[22m`
4163
+ };
4164
+ const makeMessage = (colors, timeColor, time, sqlColor, sql, valuesColor, values) => {
4165
+ const elapsed = process.hrtime(time);
4166
+ const formattedTime = `(${elapsed[0] ? `${elapsed[0]}s ` : ""}${(elapsed[1] / 1e6).toFixed(1)}ms)`;
4167
+ const result = `${colors ? timeColor(formattedTime) : formattedTime} ${colors ? sqlColor(sql) : sql}`;
4168
+ if (!values.length) {
4169
+ return result;
4170
+ }
4171
+ const formattedValues = `[${values.map(quote).join(", ")}]`;
4172
+ return `${result} ${colors ? valuesColor(formattedValues) : formattedValues}`;
4173
+ };
4174
+ const logParamToLogObject = (logger, log) => {
4175
+ if (!log)
4176
+ return;
4177
+ const logObject = Object.assign({
4178
+ colors: true,
4179
+ beforeQuery() {
4180
+ return process.hrtime();
4181
+ },
4182
+ afterQuery(_, sql, time) {
4183
+ logger.log(makeMessage(colors, logColors.boldCyanBright, time, logColors.boldBlue, sql.text, logColors.boldYellow, sql.values));
4184
+ },
4185
+ onError(error, _, sql, time) {
4186
+ const message = `Error: ${error.message}`;
4187
+ logger.error(`${makeMessage(colors, logColors.boldMagenta, time, logColors.boldRed, sql.text, logColors.boldYellow, sql.values)} ${colors ? logColors.boldRed(message) : message}`);
4188
+ }
4189
+ }, log === true ? {} : log);
4190
+ const colors = logObject.colors;
4191
+ return logObject;
4192
+ };
4193
+ class QueryLog {
4194
+ log(log = true) {
4195
+ return this.clone()._log(log);
4196
+ }
4197
+ _log(log = true) {
4198
+ this.query.log = logParamToLogObject(this.query.logger, log);
4199
+ return this;
4200
+ }
4201
+ }
4202
+
4203
+ class QueryCallbacks {
4204
+ beforeQuery(cb) {
4205
+ return this.clone()._beforeQuery(cb);
4206
+ }
4207
+ _beforeQuery(cb) {
4208
+ return pushQueryValue(this, "beforeQuery", cb);
4209
+ }
4210
+ afterQuery(cb) {
4211
+ return this.clone()._afterQuery(cb);
4212
+ }
4213
+ _afterQuery(cb) {
4214
+ return pushQueryValue(this, "afterQuery", cb);
4215
+ }
4216
+ beforeInsert(cb) {
4217
+ return this.clone()._beforeInsert(cb);
4218
+ }
4219
+ _beforeInsert(cb) {
4220
+ return pushQueryValue(this, "beforeInsert", cb);
4221
+ }
4222
+ afterInsert(cb) {
4223
+ return this.clone()._afterInsert(cb);
4224
+ }
4225
+ _afterInsert(cb) {
4226
+ return pushQueryValue(this, "afterInsert", cb);
4227
+ }
4228
+ beforeUpdate(cb) {
4229
+ return this.clone()._beforeUpdate(cb);
4230
+ }
4231
+ _beforeUpdate(cb) {
4232
+ return pushQueryValue(this, "beforeUpdate", cb);
4233
+ }
4234
+ afterUpdate(cb) {
4235
+ return this.clone()._afterUpdate(cb);
4236
+ }
4237
+ _afterUpdate(cb) {
4238
+ return pushQueryValue(this, "afterUpdate", cb);
4239
+ }
4240
+ }
4241
+
4242
+ class QueryUpsert {
4243
+ upsert(data) {
4244
+ return this.clone()._upsert(data);
4245
+ }
4246
+ _upsert(data) {
4247
+ this._update(data.update);
4248
+ this.query.returnType = "one";
4249
+ this.query.wrapInTransaction = true;
4250
+ const { handleResult } = this.query;
4251
+ this.query.handleResult = async (q, queryResult) => {
4252
+ if (queryResult.rowCount === 0) {
4253
+ return q.insert(data.create);
4254
+ } else if (queryResult.rowCount > 1) {
4255
+ throw new MoreThanOneRowError(`Only one row was expected to find for upsert, found ${queryResult.rowCount} rows.`);
4256
+ }
4257
+ return handleResult(q, queryResult);
4258
+ };
4259
+ return this;
4260
+ }
4261
+ }
4262
+
4263
+ const _get = (q, returnType, arg) => {
4264
+ q.query.returnType = returnType;
4265
+ q.query.take = true;
4266
+ if (typeof arg === "object" && isRaw(arg)) {
4267
+ addParserForRawExpression(q, "value", arg);
4268
+ q.query.select = [arg];
4269
+ } else {
4270
+ q.query.select = [
4271
+ processSelectArg(q, getQueryAs(q), arg)
4272
+ ];
4273
+ }
4274
+ return q;
4275
+ };
4276
+ class QueryGet {
4277
+ get(arg) {
4278
+ return this.clone()._get(arg);
4279
+ }
4280
+ _get(arg) {
4281
+ return _get(this, "valueOrThrow", arg);
4282
+ }
4283
+ getOptional(arg) {
4284
+ return this.clone()._getOptional(arg);
4285
+ }
4286
+ _getOptional(arg) {
4287
+ return _get(this, "value", arg);
4288
+ }
4289
+ }
4290
+
4291
+ class QueryMethods {
4292
+ all() {
4293
+ return this.query.returnType === "all" ? this : this.clone()._all();
4294
+ }
4295
+ _all() {
4296
+ this.query.returnType = "all";
4297
+ removeFromQuery(this, "take");
4298
+ return this;
4299
+ }
4300
+ take() {
4301
+ return this.query.returnType === "oneOrThrow" ? this : this.clone()._take();
4302
+ }
4303
+ _take() {
4304
+ this.query.returnType = "oneOrThrow";
4305
+ this.query.take = true;
4306
+ return this;
4307
+ }
4308
+ takeOptional() {
4309
+ return this.query.returnType === "one" ? this : this.clone()._takeOptional();
4310
+ }
4311
+ _takeOptional() {
4312
+ this.query.returnType = "one";
4313
+ this.query.take = true;
4314
+ return this;
4315
+ }
4316
+ rows() {
4317
+ return this.query.returnType === "rows" ? this : this.clone()._rows();
4318
+ }
4319
+ _rows() {
4320
+ this.query.returnType = "rows";
4321
+ removeFromQuery(this, "take");
4322
+ return this;
4323
+ }
4324
+ pluck(select) {
4325
+ return this.query.returnType === "pluck" ? this : this.clone()._pluck(select);
4326
+ }
4327
+ _pluck(select) {
4328
+ this.query.returnType = "pluck";
4329
+ removeFromQuery(this, "take");
4330
+ this.query.select = [select];
4331
+ addParserForSelectItem(this, this.query.as || this.table, "pluck", select);
4332
+ return this;
4333
+ }
4334
+ exec() {
4335
+ return this.query.returnType === "void" ? this : this.clone()._exec();
4336
+ }
4337
+ _exec() {
4338
+ this.query.returnType = "void";
4339
+ removeFromQuery(this, "take");
4340
+ return this;
4341
+ }
4342
+ clone() {
4343
+ const cloned = Object.create(this.__model);
4344
+ cloned.query = getClonedQueryData(this.query);
4345
+ return cloned;
4346
+ }
4347
+ toSql(values) {
4348
+ return toSql(this, values);
4349
+ }
4350
+ distinct(...columns) {
4351
+ return this.clone()._distinct(...columns);
4352
+ }
4353
+ _distinct(...columns) {
4354
+ return pushQueryArray(this, "distinct", columns);
4355
+ }
4356
+ find(...args) {
4357
+ return this.clone()._find(...args);
4358
+ }
4359
+ _find(...args) {
4360
+ const conditions = {};
4361
+ this.schema.primaryKeys.forEach((key, i) => {
4362
+ conditions[key] = args[i];
4363
+ });
4364
+ return this._where(conditions)._take();
4365
+ }
4366
+ findOptional(...args) {
4367
+ return this.clone()._findOptional(...args);
4368
+ }
4369
+ _findOptional(...args) {
4370
+ return this._find(...args).takeOptional();
4371
+ }
4372
+ findBy(...args) {
4373
+ return this.clone()._findBy(...args);
4374
+ }
4375
+ _findBy(...args) {
4376
+ return addWhere(this, args).take();
4377
+ }
4378
+ findByOptional(...args) {
4379
+ return this.clone()._findByOptional(...args);
4380
+ }
4381
+ _findByOptional(...args) {
4382
+ return addWhere(this, args).takeOptional();
4383
+ }
4384
+ as(tableAlias) {
4385
+ return this.clone()._as(tableAlias);
4386
+ }
4387
+ _as(tableAlias) {
4388
+ this.query.as = tableAlias;
4389
+ return this;
4390
+ }
4391
+ withSchema(schema) {
4392
+ return this.clone()._withSchema(schema);
4393
+ }
4394
+ _withSchema(schema) {
4395
+ this.query.schema = schema;
4396
+ return this;
4397
+ }
4398
+ group(...columns) {
4399
+ return this.clone()._group(...columns);
4400
+ }
4401
+ _group(...columns) {
4402
+ return pushQueryArray(this, "group", columns);
4403
+ }
4404
+ window(arg) {
4405
+ return this.clone()._window(arg);
4406
+ }
4407
+ _window(arg) {
4408
+ return pushQueryValue(this, "window", arg);
4409
+ }
4410
+ wrap(query, as) {
4411
+ return this.clone()._wrap(query, as);
4412
+ }
4413
+ _wrap(query, as) {
4414
+ const sql = this.toSql();
4415
+ return query.as(as != null ? as : "t")._from(raw(`(${sql.text})`, ...sql.values));
4416
+ }
4417
+ order(...args) {
4418
+ return this.clone()._order(...args);
4419
+ }
4420
+ _order(...args) {
4421
+ return pushQueryArray(this, "order", args);
4422
+ }
4423
+ limit(arg) {
4424
+ return this.clone()._limit(arg);
4425
+ }
4426
+ _limit(arg) {
4427
+ this.query.limit = arg;
4428
+ return this;
4429
+ }
4430
+ offset(arg) {
4431
+ return this.clone()._offset(arg);
4432
+ }
4433
+ _offset(arg) {
4434
+ this.query.offset = arg;
4435
+ return this;
4436
+ }
4437
+ exists() {
4438
+ return this.clone()._exists();
4439
+ }
4440
+ _exists() {
4441
+ const q = this._getOptional(raw("1"));
4442
+ delete q.query.take;
4443
+ return q;
4444
+ }
4445
+ truncate(options) {
4446
+ return this.clone()._truncate(options);
4447
+ }
4448
+ _truncate(options) {
4449
+ const q = this.query;
4450
+ q.type = "truncate";
4451
+ if (options == null ? void 0 : options.restartIdentity) {
4452
+ q.restartIdentity = true;
4453
+ }
4454
+ if (options == null ? void 0 : options.cascade) {
4455
+ q.cascade = true;
4456
+ }
4457
+ return this._exec();
4458
+ }
4459
+ }
4460
+ applyMixins(QueryMethods, [
4461
+ Aggregate,
4462
+ Select,
4463
+ From,
4464
+ Join,
4465
+ With,
4466
+ Union,
4467
+ Json,
4468
+ Insert,
4469
+ Update,
4470
+ Delete,
4471
+ Transaction,
4472
+ For,
4473
+ ColumnInfoMethods,
4474
+ Where,
4475
+ Clear,
4476
+ Having,
4477
+ Window,
4478
+ Then,
4479
+ QueryLog,
4480
+ QueryCallbacks,
4481
+ QueryUpsert,
4482
+ QueryGet
4483
+ ]);
4484
+
4485
+ var __defProp = Object.defineProperty;
4486
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4487
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4488
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
4489
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4490
+ var __spreadValues = (a, b) => {
4491
+ for (var prop in b || (b = {}))
4492
+ if (__hasOwnProp.call(b, prop))
4493
+ __defNormalProp(a, prop, b[prop]);
4494
+ if (__getOwnPropSymbols)
4495
+ for (var prop of __getOwnPropSymbols(b)) {
4496
+ if (__propIsEnum.call(b, prop))
4497
+ __defNormalProp(a, prop, b[prop]);
4498
+ }
4499
+ return a;
4500
+ };
4501
+ var __objRest = (source, exclude) => {
4502
+ var target = {};
4503
+ for (var prop in source)
4504
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
4505
+ target[prop] = source[prop];
4506
+ if (source != null && __getOwnPropSymbols)
4507
+ for (var prop of __getOwnPropSymbols(source)) {
4508
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
4509
+ target[prop] = source[prop];
4510
+ }
4511
+ return target;
4512
+ };
4513
+ class Db {
4514
+ constructor(adapter, queryBuilder, table = void 0, shape = {}, options) {
4515
+ this.adapter = adapter;
4516
+ this.queryBuilder = queryBuilder;
4517
+ this.table = table;
4518
+ this.shape = shape;
4519
+ this.whereQueryBuilder = WhereQueryBuilder;
4520
+ this.onQueryBuilder = OnQueryBuilder;
4521
+ this.__model = this;
4522
+ const logger = options.logger || console;
4523
+ this.query = {
4524
+ adapter,
4525
+ handleResult,
4526
+ returnType: "all",
4527
+ logger,
4528
+ log: logParamToLogObject(logger, options.log)
4529
+ };
4530
+ if (options == null ? void 0 : options.schema) {
4531
+ this.query.schema = options.schema;
4532
+ }
4533
+ this.schema = new TableSchema(shape);
4534
+ const columns = Object.keys(shape);
4535
+ const { toSql } = this;
4536
+ this.columns = columns;
4537
+ this.defaultSelectColumns = columns.filter((column) => !shape[column].isHidden);
4538
+ const defaultSelect = this.defaultSelectColumns.length === columns.length ? void 0 : this.defaultSelectColumns;
4539
+ const columnsParsers = {};
4540
+ let hasParsers = false;
4541
+ for (const key in shape) {
4542
+ const column = shape[key];
4543
+ if (column.parseFn) {
4544
+ hasParsers = true;
4545
+ columnsParsers[key] = column.parseFn;
4546
+ }
4547
+ }
4548
+ this.columnsParsers = hasParsers ? columnsParsers : void 0;
4549
+ this.toSql = defaultSelect ? function(values) {
4550
+ const q = this.clone();
4551
+ if (!q.query.select) {
4552
+ q.query.select = defaultSelect;
4553
+ }
4554
+ return toSql.call(q, values);
4555
+ } : toSql;
4556
+ this.relations = {};
4557
+ }
4558
+ }
4559
+ applyMixins(Db, [QueryMethods]);
4560
+ Db.prototype.constructor = Db;
4561
+ const createDb = (_a) => {
4562
+ var _b = _a, {
4563
+ log,
4564
+ logger,
4565
+ columnTypes: ct = columnTypes
4566
+ } = _b, options = __objRest(_b, [
4567
+ "log",
4568
+ "logger",
4569
+ "columnTypes"
4570
+ ]);
4571
+ const adapter = "adapter" in options ? options.adapter : new Adapter(options);
4572
+ const commonOptions = { log, logger };
4573
+ const qb = new Db(adapter, void 0, void 0, {}, commonOptions);
4574
+ qb.queryBuilder = qb;
4575
+ const db = Object.assign((table, shape, options2) => {
4576
+ return new Db(adapter, qb, table, typeof shape === "function" ? shape(ct) : shape, __spreadValues(__spreadValues({}, commonOptions), options2));
4577
+ }, qb, { adapter, destroy: () => adapter.destroy() });
4578
+ Object.getOwnPropertyNames(Db.prototype).forEach((name) => {
4579
+ db[name] = Db.prototype[name];
4580
+ });
4581
+ return db;
4582
+ };
4583
+
4584
+ const defaultsKey = Symbol("defaults");
4585
+
4586
+ export { Adapter, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, ColumnInfoMethods, ColumnType, ColumnsObject, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalBigIntColumn, DecimalColumn, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, InetColumn, Insert, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PointColumn, PolygonColumn, QueryMethods, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, TableSchema, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, VarCharColumn, XMLColumn, addQueryOn, addQueryOrOn, applyMixins, columnTypes, utils as columnUtils, createDb, createOperator, defaultsKey, getClonedQueryData, getQueryAs, getQueryParsers, getRaw, handleResult, isRaw, isRequiredRelationKey, joinTruthy, noop, parseRecord, parseResult, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryKeysOfNotSimpleQuery, queryMethodByReturnType, quote, raw, rawColumn, relationQueryKey, removeFromQuery, setQueryObjectValue, toArray, toSql };
4587
+ //# sourceMappingURL=index.esm.js.map