@duckdbfan/drizzle-duckdb 0.0.1 → 0.0.2

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.
package/dist/index.js ADDED
@@ -0,0 +1,3497 @@
1
+ // node_modules/drizzle-orm/entity.js
2
+ var entityKind = Symbol.for("drizzle:entityKind");
3
+ var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
4
+ function is(value, type) {
5
+ if (!value || typeof value !== "object") {
6
+ return false;
7
+ }
8
+ if (value instanceof type) {
9
+ return true;
10
+ }
11
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
12
+ throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
13
+ }
14
+ let cls = Object.getPrototypeOf(value).constructor;
15
+ if (cls) {
16
+ while (cls) {
17
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
18
+ return true;
19
+ }
20
+ cls = Object.getPrototypeOf(cls);
21
+ }
22
+ }
23
+ return false;
24
+ }
25
+
26
+ // node_modules/drizzle-orm/logger.js
27
+ class ConsoleLogWriter {
28
+ static [entityKind] = "ConsoleLogWriter";
29
+ write(message) {
30
+ console.log(message);
31
+ }
32
+ }
33
+
34
+ class DefaultLogger {
35
+ static [entityKind] = "DefaultLogger";
36
+ writer;
37
+ constructor(config) {
38
+ this.writer = config?.writer ?? new ConsoleLogWriter;
39
+ }
40
+ logQuery(query, params) {
41
+ const stringifiedParams = params.map((p) => {
42
+ try {
43
+ return JSON.stringify(p);
44
+ } catch {
45
+ return String(p);
46
+ }
47
+ });
48
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
49
+ this.writer.write(`Query: ${query}${paramsStr}`);
50
+ }
51
+ }
52
+
53
+ class NoopLogger {
54
+ static [entityKind] = "NoopLogger";
55
+ logQuery() {}
56
+ }
57
+
58
+ // node_modules/drizzle-orm/query-promise.js
59
+ class QueryPromise {
60
+ static [entityKind] = "QueryPromise";
61
+ [Symbol.toStringTag] = "QueryPromise";
62
+ catch(onRejected) {
63
+ return this.then(undefined, onRejected);
64
+ }
65
+ finally(onFinally) {
66
+ return this.then((value) => {
67
+ onFinally?.();
68
+ return value;
69
+ }, (reason) => {
70
+ onFinally?.();
71
+ throw reason;
72
+ });
73
+ }
74
+ then(onFulfilled, onRejected) {
75
+ return this.execute().then(onFulfilled, onRejected);
76
+ }
77
+ }
78
+
79
+ // node_modules/drizzle-orm/column.js
80
+ class Column {
81
+ constructor(table, config) {
82
+ this.table = table;
83
+ this.config = config;
84
+ this.name = config.name;
85
+ this.keyAsName = config.keyAsName;
86
+ this.notNull = config.notNull;
87
+ this.default = config.default;
88
+ this.defaultFn = config.defaultFn;
89
+ this.onUpdateFn = config.onUpdateFn;
90
+ this.hasDefault = config.hasDefault;
91
+ this.primary = config.primaryKey;
92
+ this.isUnique = config.isUnique;
93
+ this.uniqueName = config.uniqueName;
94
+ this.uniqueType = config.uniqueType;
95
+ this.dataType = config.dataType;
96
+ this.columnType = config.columnType;
97
+ this.generated = config.generated;
98
+ this.generatedIdentity = config.generatedIdentity;
99
+ }
100
+ static [entityKind] = "Column";
101
+ name;
102
+ keyAsName;
103
+ primary;
104
+ notNull;
105
+ default;
106
+ defaultFn;
107
+ onUpdateFn;
108
+ hasDefault;
109
+ isUnique;
110
+ uniqueName;
111
+ uniqueType;
112
+ dataType;
113
+ columnType;
114
+ enumValues = undefined;
115
+ generated = undefined;
116
+ generatedIdentity = undefined;
117
+ config;
118
+ mapFromDriverValue(value) {
119
+ return value;
120
+ }
121
+ mapToDriverValue(value) {
122
+ return value;
123
+ }
124
+ shouldDisableInsert() {
125
+ return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
126
+ }
127
+ }
128
+
129
+ // node_modules/drizzle-orm/table.utils.js
130
+ var TableName = Symbol.for("drizzle:Name");
131
+
132
+ // node_modules/drizzle-orm/tracing-utils.js
133
+ function iife(fn, ...args) {
134
+ return fn(...args);
135
+ }
136
+
137
+ // node_modules/drizzle-orm/pg-core/unique-constraint.js
138
+ function uniqueKeyName(table, columns) {
139
+ return `${table[TableName]}_${columns.join("_")}_unique`;
140
+ }
141
+
142
+ // node_modules/drizzle-orm/pg-core/columns/common.js
143
+ class PgColumn extends Column {
144
+ constructor(table, config) {
145
+ if (!config.uniqueName) {
146
+ config.uniqueName = uniqueKeyName(table, [config.name]);
147
+ }
148
+ super(table, config);
149
+ this.table = table;
150
+ }
151
+ static [entityKind] = "PgColumn";
152
+ }
153
+
154
+ class ExtraConfigColumn extends PgColumn {
155
+ static [entityKind] = "ExtraConfigColumn";
156
+ getSQLType() {
157
+ return this.getSQLType();
158
+ }
159
+ indexConfig = {
160
+ order: this.config.order ?? "asc",
161
+ nulls: this.config.nulls ?? "last",
162
+ opClass: this.config.opClass
163
+ };
164
+ defaultConfig = {
165
+ order: "asc",
166
+ nulls: "last",
167
+ opClass: undefined
168
+ };
169
+ asc() {
170
+ this.indexConfig.order = "asc";
171
+ return this;
172
+ }
173
+ desc() {
174
+ this.indexConfig.order = "desc";
175
+ return this;
176
+ }
177
+ nullsFirst() {
178
+ this.indexConfig.nulls = "first";
179
+ return this;
180
+ }
181
+ nullsLast() {
182
+ this.indexConfig.nulls = "last";
183
+ return this;
184
+ }
185
+ op(opClass) {
186
+ this.indexConfig.opClass = opClass;
187
+ return this;
188
+ }
189
+ }
190
+
191
+ // node_modules/drizzle-orm/pg-core/columns/enum.js
192
+ var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
193
+ function isPgEnum(obj) {
194
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
195
+ }
196
+ class PgEnumColumn extends PgColumn {
197
+ static [entityKind] = "PgEnumColumn";
198
+ enum = this.config.enum;
199
+ enumValues = this.config.enum.enumValues;
200
+ constructor(table, config) {
201
+ super(table, config);
202
+ this.enum = config.enum;
203
+ }
204
+ getSQLType() {
205
+ return this.enum.enumName;
206
+ }
207
+ }
208
+
209
+ // node_modules/drizzle-orm/subquery.js
210
+ class Subquery {
211
+ static [entityKind] = "Subquery";
212
+ constructor(sql, selection, alias, isWith = false) {
213
+ this._ = {
214
+ brand: "Subquery",
215
+ sql,
216
+ selectedFields: selection,
217
+ alias,
218
+ isWith
219
+ };
220
+ }
221
+ }
222
+
223
+ class WithSubquery extends Subquery {
224
+ static [entityKind] = "WithSubquery";
225
+ }
226
+
227
+ // node_modules/drizzle-orm/version.js
228
+ var version = "0.40.0";
229
+
230
+ // node_modules/drizzle-orm/tracing.js
231
+ var otel;
232
+ var rawTracer;
233
+ var tracer = {
234
+ startActiveSpan(name, fn) {
235
+ if (!otel) {
236
+ return fn();
237
+ }
238
+ if (!rawTracer) {
239
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
240
+ }
241
+ return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
242
+ try {
243
+ return fn(span);
244
+ } catch (e) {
245
+ span.setStatus({
246
+ code: otel2.SpanStatusCode.ERROR,
247
+ message: e instanceof Error ? e.message : "Unknown error"
248
+ });
249
+ throw e;
250
+ } finally {
251
+ span.end();
252
+ }
253
+ }), otel, rawTracer);
254
+ }
255
+ };
256
+
257
+ // node_modules/drizzle-orm/view-common.js
258
+ var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
259
+
260
+ // node_modules/drizzle-orm/table.js
261
+ var Schema = Symbol.for("drizzle:Schema");
262
+ var Columns = Symbol.for("drizzle:Columns");
263
+ var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
264
+ var OriginalName = Symbol.for("drizzle:OriginalName");
265
+ var BaseName = Symbol.for("drizzle:BaseName");
266
+ var IsAlias = Symbol.for("drizzle:IsAlias");
267
+ var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
268
+ var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
269
+
270
+ class Table {
271
+ static [entityKind] = "Table";
272
+ static Symbol = {
273
+ Name: TableName,
274
+ Schema,
275
+ OriginalName,
276
+ Columns,
277
+ ExtraConfigColumns,
278
+ BaseName,
279
+ IsAlias,
280
+ ExtraConfigBuilder
281
+ };
282
+ [TableName];
283
+ [OriginalName];
284
+ [Schema];
285
+ [Columns];
286
+ [ExtraConfigColumns];
287
+ [BaseName];
288
+ [IsAlias] = false;
289
+ [IsDrizzleTable] = true;
290
+ [ExtraConfigBuilder] = undefined;
291
+ constructor(name, schema, baseName) {
292
+ this[TableName] = this[OriginalName] = name;
293
+ this[Schema] = schema;
294
+ this[BaseName] = baseName;
295
+ }
296
+ }
297
+ function getTableName(table) {
298
+ return table[TableName];
299
+ }
300
+ function getTableUniqueName(table) {
301
+ return `${table[Schema] ?? "public"}.${table[TableName]}`;
302
+ }
303
+
304
+ // node_modules/drizzle-orm/sql/sql.js
305
+ function isSQLWrapper(value) {
306
+ return value !== null && value !== undefined && typeof value.getSQL === "function";
307
+ }
308
+ function mergeQueries(queries) {
309
+ const result = { sql: "", params: [] };
310
+ for (const query of queries) {
311
+ result.sql += query.sql;
312
+ result.params.push(...query.params);
313
+ if (query.typings?.length) {
314
+ if (!result.typings) {
315
+ result.typings = [];
316
+ }
317
+ result.typings.push(...query.typings);
318
+ }
319
+ }
320
+ return result;
321
+ }
322
+
323
+ class StringChunk {
324
+ static [entityKind] = "StringChunk";
325
+ value;
326
+ constructor(value) {
327
+ this.value = Array.isArray(value) ? value : [value];
328
+ }
329
+ getSQL() {
330
+ return new SQL([this]);
331
+ }
332
+ }
333
+
334
+ class SQL {
335
+ constructor(queryChunks) {
336
+ this.queryChunks = queryChunks;
337
+ }
338
+ static [entityKind] = "SQL";
339
+ decoder = noopDecoder;
340
+ shouldInlineParams = false;
341
+ append(query) {
342
+ this.queryChunks.push(...query.queryChunks);
343
+ return this;
344
+ }
345
+ toQuery(config) {
346
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
347
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
348
+ span?.setAttributes({
349
+ "drizzle.query.text": query.sql,
350
+ "drizzle.query.params": JSON.stringify(query.params)
351
+ });
352
+ return query;
353
+ });
354
+ }
355
+ buildQueryFromSourceParams(chunks, _config) {
356
+ const config = Object.assign({}, _config, {
357
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
358
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
359
+ });
360
+ const {
361
+ casing,
362
+ escapeName,
363
+ escapeParam,
364
+ prepareTyping,
365
+ inlineParams,
366
+ paramStartIndex
367
+ } = config;
368
+ return mergeQueries(chunks.map((chunk) => {
369
+ if (is(chunk, StringChunk)) {
370
+ return { sql: chunk.value.join(""), params: [] };
371
+ }
372
+ if (is(chunk, Name)) {
373
+ return { sql: escapeName(chunk.value), params: [] };
374
+ }
375
+ if (chunk === undefined) {
376
+ return { sql: "", params: [] };
377
+ }
378
+ if (Array.isArray(chunk)) {
379
+ const result = [new StringChunk("(")];
380
+ for (const [i, p] of chunk.entries()) {
381
+ result.push(p);
382
+ if (i < chunk.length - 1) {
383
+ result.push(new StringChunk(", "));
384
+ }
385
+ }
386
+ result.push(new StringChunk(")"));
387
+ return this.buildQueryFromSourceParams(result, config);
388
+ }
389
+ if (is(chunk, SQL)) {
390
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
391
+ ...config,
392
+ inlineParams: inlineParams || chunk.shouldInlineParams
393
+ });
394
+ }
395
+ if (is(chunk, Table)) {
396
+ const schemaName = chunk[Table.Symbol.Schema];
397
+ const tableName = chunk[Table.Symbol.Name];
398
+ return {
399
+ sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
400
+ params: []
401
+ };
402
+ }
403
+ if (is(chunk, Column)) {
404
+ const columnName = casing.getColumnCasing(chunk);
405
+ if (_config.invokeSource === "indexes") {
406
+ return { sql: escapeName(columnName), params: [] };
407
+ }
408
+ const schemaName = chunk.table[Table.Symbol.Schema];
409
+ return {
410
+ sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
411
+ params: []
412
+ };
413
+ }
414
+ if (is(chunk, View)) {
415
+ const schemaName = chunk[ViewBaseConfig].schema;
416
+ const viewName = chunk[ViewBaseConfig].name;
417
+ return {
418
+ sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
419
+ params: []
420
+ };
421
+ }
422
+ if (is(chunk, Param)) {
423
+ if (is(chunk.value, Placeholder)) {
424
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
425
+ }
426
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
427
+ if (is(mappedValue, SQL)) {
428
+ return this.buildQueryFromSourceParams([mappedValue], config);
429
+ }
430
+ if (inlineParams) {
431
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
432
+ }
433
+ let typings = ["none"];
434
+ if (prepareTyping) {
435
+ typings = [prepareTyping(chunk.encoder)];
436
+ }
437
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
438
+ }
439
+ if (is(chunk, Placeholder)) {
440
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
441
+ }
442
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
443
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
444
+ }
445
+ if (is(chunk, Subquery)) {
446
+ if (chunk._.isWith) {
447
+ return { sql: escapeName(chunk._.alias), params: [] };
448
+ }
449
+ return this.buildQueryFromSourceParams([
450
+ new StringChunk("("),
451
+ chunk._.sql,
452
+ new StringChunk(") "),
453
+ new Name(chunk._.alias)
454
+ ], config);
455
+ }
456
+ if (isPgEnum(chunk)) {
457
+ if (chunk.schema) {
458
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
459
+ }
460
+ return { sql: escapeName(chunk.enumName), params: [] };
461
+ }
462
+ if (isSQLWrapper(chunk)) {
463
+ if (chunk.shouldOmitSQLParens?.()) {
464
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
465
+ }
466
+ return this.buildQueryFromSourceParams([
467
+ new StringChunk("("),
468
+ chunk.getSQL(),
469
+ new StringChunk(")")
470
+ ], config);
471
+ }
472
+ if (inlineParams) {
473
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
474
+ }
475
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
476
+ }));
477
+ }
478
+ mapInlineParam(chunk, { escapeString }) {
479
+ if (chunk === null) {
480
+ return "null";
481
+ }
482
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
483
+ return chunk.toString();
484
+ }
485
+ if (typeof chunk === "string") {
486
+ return escapeString(chunk);
487
+ }
488
+ if (typeof chunk === "object") {
489
+ const mappedValueAsString = chunk.toString();
490
+ if (mappedValueAsString === "[object Object]") {
491
+ return escapeString(JSON.stringify(chunk));
492
+ }
493
+ return escapeString(mappedValueAsString);
494
+ }
495
+ throw new Error("Unexpected param value: " + chunk);
496
+ }
497
+ getSQL() {
498
+ return this;
499
+ }
500
+ as(alias) {
501
+ if (alias === undefined) {
502
+ return this;
503
+ }
504
+ return new SQL.Aliased(this, alias);
505
+ }
506
+ mapWith(decoder) {
507
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
508
+ return this;
509
+ }
510
+ inlineParams() {
511
+ this.shouldInlineParams = true;
512
+ return this;
513
+ }
514
+ if(condition) {
515
+ return condition ? this : undefined;
516
+ }
517
+ }
518
+
519
+ class Name {
520
+ constructor(value) {
521
+ this.value = value;
522
+ }
523
+ static [entityKind] = "Name";
524
+ brand;
525
+ getSQL() {
526
+ return new SQL([this]);
527
+ }
528
+ }
529
+ function isDriverValueEncoder(value) {
530
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
531
+ }
532
+ var noopDecoder = {
533
+ mapFromDriverValue: (value) => value
534
+ };
535
+ var noopEncoder = {
536
+ mapToDriverValue: (value) => value
537
+ };
538
+ var noopMapper = {
539
+ ...noopDecoder,
540
+ ...noopEncoder
541
+ };
542
+
543
+ class Param {
544
+ constructor(value, encoder = noopEncoder) {
545
+ this.value = value;
546
+ this.encoder = encoder;
547
+ }
548
+ static [entityKind] = "Param";
549
+ brand;
550
+ getSQL() {
551
+ return new SQL([this]);
552
+ }
553
+ }
554
+ function sql(strings, ...params) {
555
+ const queryChunks = [];
556
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
557
+ queryChunks.push(new StringChunk(strings[0]));
558
+ }
559
+ for (const [paramIndex, param2] of params.entries()) {
560
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
561
+ }
562
+ return new SQL(queryChunks);
563
+ }
564
+ ((sql2) => {
565
+ function empty() {
566
+ return new SQL([]);
567
+ }
568
+ sql2.empty = empty;
569
+ function fromList(list) {
570
+ return new SQL(list);
571
+ }
572
+ sql2.fromList = fromList;
573
+ function raw(str) {
574
+ return new SQL([new StringChunk(str)]);
575
+ }
576
+ sql2.raw = raw;
577
+ function join(chunks, separator) {
578
+ const result = [];
579
+ for (const [i, chunk] of chunks.entries()) {
580
+ if (i > 0 && separator !== undefined) {
581
+ result.push(separator);
582
+ }
583
+ result.push(chunk);
584
+ }
585
+ return new SQL(result);
586
+ }
587
+ sql2.join = join;
588
+ function identifier(value) {
589
+ return new Name(value);
590
+ }
591
+ sql2.identifier = identifier;
592
+ function placeholder2(name2) {
593
+ return new Placeholder(name2);
594
+ }
595
+ sql2.placeholder = placeholder2;
596
+ function param2(value, encoder) {
597
+ return new Param(value, encoder);
598
+ }
599
+ sql2.param = param2;
600
+ })(sql || (sql = {}));
601
+ ((SQL2) => {
602
+
603
+ class Aliased {
604
+ constructor(sql2, fieldAlias) {
605
+ this.sql = sql2;
606
+ this.fieldAlias = fieldAlias;
607
+ }
608
+ static [entityKind] = "SQL.Aliased";
609
+ isSelectionField = false;
610
+ getSQL() {
611
+ return this.sql;
612
+ }
613
+ clone() {
614
+ return new Aliased(this.sql, this.fieldAlias);
615
+ }
616
+ }
617
+ SQL2.Aliased = Aliased;
618
+ })(SQL || (SQL = {}));
619
+
620
+ class Placeholder {
621
+ constructor(name2) {
622
+ this.name = name2;
623
+ }
624
+ static [entityKind] = "Placeholder";
625
+ getSQL() {
626
+ return new SQL([this]);
627
+ }
628
+ }
629
+ function fillPlaceholders(params, values) {
630
+ return params.map((p) => {
631
+ if (is(p, Placeholder)) {
632
+ if (!(p.name in values)) {
633
+ throw new Error(`No value for placeholder "${p.name}" was provided`);
634
+ }
635
+ return values[p.name];
636
+ }
637
+ if (is(p, Param) && is(p.value, Placeholder)) {
638
+ if (!(p.value.name in values)) {
639
+ throw new Error(`No value for placeholder "${p.value.name}" was provided`);
640
+ }
641
+ return p.encoder.mapToDriverValue(values[p.value.name]);
642
+ }
643
+ return p;
644
+ });
645
+ }
646
+ var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
647
+
648
+ class View {
649
+ static [entityKind] = "View";
650
+ [ViewBaseConfig];
651
+ [IsDrizzleView] = true;
652
+ constructor({ name: name2, schema, selectedFields, query }) {
653
+ this[ViewBaseConfig] = {
654
+ name: name2,
655
+ originalName: name2,
656
+ schema,
657
+ selectedFields,
658
+ query,
659
+ isExisting: !query,
660
+ isAlias: false
661
+ };
662
+ }
663
+ getSQL() {
664
+ return new SQL([this]);
665
+ }
666
+ }
667
+ Column.prototype.getSQL = function() {
668
+ return new SQL([this]);
669
+ };
670
+ Table.prototype.getSQL = function() {
671
+ return new SQL([this]);
672
+ };
673
+ Subquery.prototype.getSQL = function() {
674
+ return new SQL([this]);
675
+ };
676
+
677
+ // node_modules/drizzle-orm/alias.js
678
+ class ColumnAliasProxyHandler {
679
+ constructor(table) {
680
+ this.table = table;
681
+ }
682
+ static [entityKind] = "ColumnAliasProxyHandler";
683
+ get(columnObj, prop) {
684
+ if (prop === "table") {
685
+ return this.table;
686
+ }
687
+ return columnObj[prop];
688
+ }
689
+ }
690
+
691
+ class TableAliasProxyHandler {
692
+ constructor(alias, replaceOriginalName) {
693
+ this.alias = alias;
694
+ this.replaceOriginalName = replaceOriginalName;
695
+ }
696
+ static [entityKind] = "TableAliasProxyHandler";
697
+ get(target, prop) {
698
+ if (prop === Table.Symbol.IsAlias) {
699
+ return true;
700
+ }
701
+ if (prop === Table.Symbol.Name) {
702
+ return this.alias;
703
+ }
704
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
705
+ return this.alias;
706
+ }
707
+ if (prop === ViewBaseConfig) {
708
+ return {
709
+ ...target[ViewBaseConfig],
710
+ name: this.alias,
711
+ isAlias: true
712
+ };
713
+ }
714
+ if (prop === Table.Symbol.Columns) {
715
+ const columns = target[Table.Symbol.Columns];
716
+ if (!columns) {
717
+ return columns;
718
+ }
719
+ const proxiedColumns = {};
720
+ Object.keys(columns).map((key) => {
721
+ proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
722
+ });
723
+ return proxiedColumns;
724
+ }
725
+ const value = target[prop];
726
+ if (is(value, Column)) {
727
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
728
+ }
729
+ return value;
730
+ }
731
+ }
732
+ function aliasedTable(table, tableAlias) {
733
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
734
+ }
735
+ function aliasedTableColumn(column, tableAlias) {
736
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
737
+ }
738
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
739
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
740
+ }
741
+ function mapColumnsInSQLToAlias(query, alias) {
742
+ return sql.join(query.queryChunks.map((c) => {
743
+ if (is(c, Column)) {
744
+ return aliasedTableColumn(c, alias);
745
+ }
746
+ if (is(c, SQL)) {
747
+ return mapColumnsInSQLToAlias(c, alias);
748
+ }
749
+ if (is(c, SQL.Aliased)) {
750
+ return mapColumnsInAliasedSQLToAlias(c, alias);
751
+ }
752
+ return c;
753
+ }));
754
+ }
755
+
756
+ // node_modules/drizzle-orm/selection-proxy.js
757
+ class SelectionProxyHandler {
758
+ static [entityKind] = "SelectionProxyHandler";
759
+ config;
760
+ constructor(config) {
761
+ this.config = { ...config };
762
+ }
763
+ get(subquery, prop) {
764
+ if (prop === "_") {
765
+ return {
766
+ ...subquery["_"],
767
+ selectedFields: new Proxy(subquery._.selectedFields, this)
768
+ };
769
+ }
770
+ if (prop === ViewBaseConfig) {
771
+ return {
772
+ ...subquery[ViewBaseConfig],
773
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
774
+ };
775
+ }
776
+ if (typeof prop === "symbol") {
777
+ return subquery[prop];
778
+ }
779
+ const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
780
+ const value = columns[prop];
781
+ if (is(value, SQL.Aliased)) {
782
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
783
+ return value.sql;
784
+ }
785
+ const newValue = value.clone();
786
+ newValue.isSelectionField = true;
787
+ return newValue;
788
+ }
789
+ if (is(value, SQL)) {
790
+ if (this.config.sqlBehavior === "sql") {
791
+ return value;
792
+ }
793
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
794
+ }
795
+ if (is(value, Column)) {
796
+ if (this.config.alias) {
797
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
798
+ }
799
+ return value;
800
+ }
801
+ if (typeof value !== "object" || value === null) {
802
+ return value;
803
+ }
804
+ return new Proxy(value, new SelectionProxyHandler(this.config));
805
+ }
806
+ }
807
+
808
+ // node_modules/drizzle-orm/utils.js
809
+ function orderSelectedFields(fields, pathPrefix) {
810
+ return Object.entries(fields).reduce((result, [name, field]) => {
811
+ if (typeof name !== "string") {
812
+ return result;
813
+ }
814
+ const newPath = pathPrefix ? [...pathPrefix, name] : [name];
815
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
816
+ result.push({ path: newPath, field });
817
+ } else if (is(field, Table)) {
818
+ result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
819
+ } else {
820
+ result.push(...orderSelectedFields(field, newPath));
821
+ }
822
+ return result;
823
+ }, []);
824
+ }
825
+ function haveSameKeys(left, right) {
826
+ const leftKeys = Object.keys(left);
827
+ const rightKeys = Object.keys(right);
828
+ if (leftKeys.length !== rightKeys.length) {
829
+ return false;
830
+ }
831
+ for (const [index, key] of leftKeys.entries()) {
832
+ if (key !== rightKeys[index]) {
833
+ return false;
834
+ }
835
+ }
836
+ return true;
837
+ }
838
+ function mapUpdateSet(table, values) {
839
+ const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
840
+ if (is(value, SQL) || is(value, Column)) {
841
+ return [key, value];
842
+ } else {
843
+ return [key, new Param(value, table[Table.Symbol.Columns][key])];
844
+ }
845
+ });
846
+ if (entries.length === 0) {
847
+ throw new Error("No values to set");
848
+ }
849
+ return Object.fromEntries(entries);
850
+ }
851
+ function applyMixins(baseClass, extendedClasses) {
852
+ for (const extendedClass of extendedClasses) {
853
+ for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
854
+ if (name === "constructor")
855
+ continue;
856
+ Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null));
857
+ }
858
+ }
859
+ }
860
+ function getTableColumns(table) {
861
+ return table[Table.Symbol.Columns];
862
+ }
863
+ function getTableLikeName(table) {
864
+ return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
865
+ }
866
+
867
+ // node_modules/drizzle-orm/pg-core/query-builders/delete.js
868
+ class PgDeleteBase extends QueryPromise {
869
+ constructor(table, session, dialect, withList) {
870
+ super();
871
+ this.session = session;
872
+ this.dialect = dialect;
873
+ this.config = { table, withList };
874
+ }
875
+ static [entityKind] = "PgDelete";
876
+ config;
877
+ where(where) {
878
+ this.config.where = where;
879
+ return this;
880
+ }
881
+ returning(fields = this.config.table[Table.Symbol.Columns]) {
882
+ this.config.returningFields = fields;
883
+ this.config.returning = orderSelectedFields(fields);
884
+ return this;
885
+ }
886
+ getSQL() {
887
+ return this.dialect.buildDeleteQuery(this.config);
888
+ }
889
+ toSQL() {
890
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
891
+ return rest;
892
+ }
893
+ _prepare(name) {
894
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
895
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
896
+ });
897
+ }
898
+ prepare(name) {
899
+ return this._prepare(name);
900
+ }
901
+ authToken;
902
+ setToken(token) {
903
+ this.authToken = token;
904
+ return this;
905
+ }
906
+ execute = (placeholderValues) => {
907
+ return tracer.startActiveSpan("drizzle.operation", () => {
908
+ return this._prepare().execute(placeholderValues, this.authToken);
909
+ });
910
+ };
911
+ getSelectedFields() {
912
+ return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
913
+ alias: getTableName(this.config.table),
914
+ sqlAliasedBehavior: "alias",
915
+ sqlBehavior: "error"
916
+ })) : undefined;
917
+ }
918
+ $dynamic() {
919
+ return this;
920
+ }
921
+ }
922
+
923
+ // node_modules/drizzle-orm/casing.js
924
+ function toSnakeCase(input) {
925
+ const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
926
+ return words.map((word) => word.toLowerCase()).join("_");
927
+ }
928
+ function toCamelCase(input) {
929
+ const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
930
+ return words.reduce((acc, word, i) => {
931
+ const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
932
+ return acc + formattedWord;
933
+ }, "");
934
+ }
935
+ function noopCase(input) {
936
+ return input;
937
+ }
938
+
939
+ class CasingCache {
940
+ static [entityKind] = "CasingCache";
941
+ cache = {};
942
+ cachedTables = {};
943
+ convert;
944
+ constructor(casing) {
945
+ this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
946
+ }
947
+ getColumnCasing(column) {
948
+ if (!column.keyAsName)
949
+ return column.name;
950
+ const schema = column.table[Table.Symbol.Schema] ?? "public";
951
+ const tableName = column.table[Table.Symbol.OriginalName];
952
+ const key = `${schema}.${tableName}.${column.name}`;
953
+ if (!this.cache[key]) {
954
+ this.cacheTable(column.table);
955
+ }
956
+ return this.cache[key];
957
+ }
958
+ cacheTable(table) {
959
+ const schema = table[Table.Symbol.Schema] ?? "public";
960
+ const tableName = table[Table.Symbol.OriginalName];
961
+ const tableKey = `${schema}.${tableName}`;
962
+ if (!this.cachedTables[tableKey]) {
963
+ for (const column of Object.values(table[Table.Symbol.Columns])) {
964
+ const columnKey = `${tableKey}.${column.name}`;
965
+ this.cache[columnKey] = this.convert(column.name);
966
+ }
967
+ this.cachedTables[tableKey] = true;
968
+ }
969
+ }
970
+ clearCache() {
971
+ this.cache = {};
972
+ this.cachedTables = {};
973
+ }
974
+ }
975
+
976
+ // node_modules/drizzle-orm/errors.js
977
+ class DrizzleError extends Error {
978
+ static [entityKind] = "DrizzleError";
979
+ constructor({ message, cause }) {
980
+ super(message);
981
+ this.name = "DrizzleError";
982
+ this.cause = cause;
983
+ }
984
+ }
985
+
986
+ class TransactionRollbackError extends DrizzleError {
987
+ static [entityKind] = "TransactionRollbackError";
988
+ constructor() {
989
+ super({ message: "Rollback" });
990
+ }
991
+ }
992
+
993
+ // node_modules/drizzle-orm/pg-core/columns/date.js
994
+ class PgDate extends PgColumn {
995
+ static [entityKind] = "PgDate";
996
+ getSQLType() {
997
+ return "date";
998
+ }
999
+ mapFromDriverValue(value) {
1000
+ return new Date(value);
1001
+ }
1002
+ mapToDriverValue(value) {
1003
+ return value.toISOString();
1004
+ }
1005
+ }
1006
+ class PgDateString extends PgColumn {
1007
+ static [entityKind] = "PgDateString";
1008
+ getSQLType() {
1009
+ return "date";
1010
+ }
1011
+ }
1012
+
1013
+ // node_modules/drizzle-orm/pg-core/columns/json.js
1014
+ class PgJson extends PgColumn {
1015
+ static [entityKind] = "PgJson";
1016
+ constructor(table, config) {
1017
+ super(table, config);
1018
+ }
1019
+ getSQLType() {
1020
+ return "json";
1021
+ }
1022
+ mapToDriverValue(value) {
1023
+ return JSON.stringify(value);
1024
+ }
1025
+ mapFromDriverValue(value) {
1026
+ if (typeof value === "string") {
1027
+ try {
1028
+ return JSON.parse(value);
1029
+ } catch {
1030
+ return value;
1031
+ }
1032
+ }
1033
+ return value;
1034
+ }
1035
+ }
1036
+
1037
+ // node_modules/drizzle-orm/pg-core/columns/jsonb.js
1038
+ class PgJsonb extends PgColumn {
1039
+ static [entityKind] = "PgJsonb";
1040
+ constructor(table, config) {
1041
+ super(table, config);
1042
+ }
1043
+ getSQLType() {
1044
+ return "jsonb";
1045
+ }
1046
+ mapToDriverValue(value) {
1047
+ return JSON.stringify(value);
1048
+ }
1049
+ mapFromDriverValue(value) {
1050
+ if (typeof value === "string") {
1051
+ try {
1052
+ return JSON.parse(value);
1053
+ } catch {
1054
+ return value;
1055
+ }
1056
+ }
1057
+ return value;
1058
+ }
1059
+ }
1060
+
1061
+ // node_modules/drizzle-orm/pg-core/columns/numeric.js
1062
+ class PgNumeric extends PgColumn {
1063
+ static [entityKind] = "PgNumeric";
1064
+ precision;
1065
+ scale;
1066
+ constructor(table, config) {
1067
+ super(table, config);
1068
+ this.precision = config.precision;
1069
+ this.scale = config.scale;
1070
+ }
1071
+ getSQLType() {
1072
+ if (this.precision !== undefined && this.scale !== undefined) {
1073
+ return `numeric(${this.precision}, ${this.scale})`;
1074
+ } else if (this.precision === undefined) {
1075
+ return "numeric";
1076
+ } else {
1077
+ return `numeric(${this.precision})`;
1078
+ }
1079
+ }
1080
+ }
1081
+
1082
+ // node_modules/drizzle-orm/pg-core/columns/time.js
1083
+ class PgTime extends PgColumn {
1084
+ static [entityKind] = "PgTime";
1085
+ withTimezone;
1086
+ precision;
1087
+ constructor(table, config) {
1088
+ super(table, config);
1089
+ this.withTimezone = config.withTimezone;
1090
+ this.precision = config.precision;
1091
+ }
1092
+ getSQLType() {
1093
+ const precision = this.precision === undefined ? "" : `(${this.precision})`;
1094
+ return `time${precision}${this.withTimezone ? " with time zone" : ""}`;
1095
+ }
1096
+ }
1097
+
1098
+ // node_modules/drizzle-orm/pg-core/columns/timestamp.js
1099
+ class PgTimestamp extends PgColumn {
1100
+ static [entityKind] = "PgTimestamp";
1101
+ withTimezone;
1102
+ precision;
1103
+ constructor(table, config) {
1104
+ super(table, config);
1105
+ this.withTimezone = config.withTimezone;
1106
+ this.precision = config.precision;
1107
+ }
1108
+ getSQLType() {
1109
+ const precision = this.precision === undefined ? "" : ` (${this.precision})`;
1110
+ return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
1111
+ }
1112
+ mapFromDriverValue = (value) => {
1113
+ return new Date(this.withTimezone ? value : value + "+0000");
1114
+ };
1115
+ mapToDriverValue = (value) => {
1116
+ return value.toISOString();
1117
+ };
1118
+ }
1119
+ class PgTimestampString extends PgColumn {
1120
+ static [entityKind] = "PgTimestampString";
1121
+ withTimezone;
1122
+ precision;
1123
+ constructor(table, config) {
1124
+ super(table, config);
1125
+ this.withTimezone = config.withTimezone;
1126
+ this.precision = config.precision;
1127
+ }
1128
+ getSQLType() {
1129
+ const precision = this.precision === undefined ? "" : `(${this.precision})`;
1130
+ return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
1131
+ }
1132
+ }
1133
+
1134
+ // node_modules/drizzle-orm/pg-core/columns/uuid.js
1135
+ class PgUUID extends PgColumn {
1136
+ static [entityKind] = "PgUUID";
1137
+ getSQLType() {
1138
+ return "uuid";
1139
+ }
1140
+ }
1141
+
1142
+ // node_modules/drizzle-orm/pg-core/table.js
1143
+ var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
1144
+ var EnableRLS = Symbol.for("drizzle:EnableRLS");
1145
+
1146
+ class PgTable extends Table {
1147
+ static [entityKind] = "PgTable";
1148
+ static Symbol = Object.assign({}, Table.Symbol, {
1149
+ InlineForeignKeys,
1150
+ EnableRLS
1151
+ });
1152
+ [InlineForeignKeys] = [];
1153
+ [EnableRLS] = false;
1154
+ [Table.Symbol.ExtraConfigBuilder] = undefined;
1155
+ [Table.Symbol.ExtraConfigColumns] = {};
1156
+ }
1157
+
1158
+ // node_modules/drizzle-orm/pg-core/primary-keys.js
1159
+ class PrimaryKeyBuilder {
1160
+ static [entityKind] = "PgPrimaryKeyBuilder";
1161
+ columns;
1162
+ name;
1163
+ constructor(columns, name) {
1164
+ this.columns = columns;
1165
+ this.name = name;
1166
+ }
1167
+ build(table) {
1168
+ return new PrimaryKey(table, this.columns, this.name);
1169
+ }
1170
+ }
1171
+
1172
+ class PrimaryKey {
1173
+ constructor(table, columns, name) {
1174
+ this.table = table;
1175
+ this.columns = columns;
1176
+ this.name = name;
1177
+ }
1178
+ static [entityKind] = "PgPrimaryKey";
1179
+ columns;
1180
+ name;
1181
+ getName() {
1182
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1183
+ }
1184
+ }
1185
+
1186
+ // node_modules/drizzle-orm/sql/expressions/conditions.js
1187
+ function bindIfParam(value, column) {
1188
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
1189
+ return new Param(value, column);
1190
+ }
1191
+ return value;
1192
+ }
1193
+ var eq = (left, right) => {
1194
+ return sql`${left} = ${bindIfParam(right, left)}`;
1195
+ };
1196
+ var ne = (left, right) => {
1197
+ return sql`${left} <> ${bindIfParam(right, left)}`;
1198
+ };
1199
+ function and(...unfilteredConditions) {
1200
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1201
+ if (conditions.length === 0) {
1202
+ return;
1203
+ }
1204
+ if (conditions.length === 1) {
1205
+ return new SQL(conditions);
1206
+ }
1207
+ return new SQL([
1208
+ new StringChunk("("),
1209
+ sql.join(conditions, new StringChunk(" and ")),
1210
+ new StringChunk(")")
1211
+ ]);
1212
+ }
1213
+ function or(...unfilteredConditions) {
1214
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1215
+ if (conditions.length === 0) {
1216
+ return;
1217
+ }
1218
+ if (conditions.length === 1) {
1219
+ return new SQL(conditions);
1220
+ }
1221
+ return new SQL([
1222
+ new StringChunk("("),
1223
+ sql.join(conditions, new StringChunk(" or ")),
1224
+ new StringChunk(")")
1225
+ ]);
1226
+ }
1227
+ function not(condition) {
1228
+ return sql`not ${condition}`;
1229
+ }
1230
+ var gt = (left, right) => {
1231
+ return sql`${left} > ${bindIfParam(right, left)}`;
1232
+ };
1233
+ var gte = (left, right) => {
1234
+ return sql`${left} >= ${bindIfParam(right, left)}`;
1235
+ };
1236
+ var lt = (left, right) => {
1237
+ return sql`${left} < ${bindIfParam(right, left)}`;
1238
+ };
1239
+ var lte = (left, right) => {
1240
+ return sql`${left} <= ${bindIfParam(right, left)}`;
1241
+ };
1242
+ function inArray(column, values) {
1243
+ if (Array.isArray(values)) {
1244
+ if (values.length === 0) {
1245
+ return sql`false`;
1246
+ }
1247
+ return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
1248
+ }
1249
+ return sql`${column} in ${bindIfParam(values, column)}`;
1250
+ }
1251
+ function notInArray(column, values) {
1252
+ if (Array.isArray(values)) {
1253
+ if (values.length === 0) {
1254
+ return sql`true`;
1255
+ }
1256
+ return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
1257
+ }
1258
+ return sql`${column} not in ${bindIfParam(values, column)}`;
1259
+ }
1260
+ function isNull(value) {
1261
+ return sql`${value} is null`;
1262
+ }
1263
+ function isNotNull(value) {
1264
+ return sql`${value} is not null`;
1265
+ }
1266
+ function exists(subquery) {
1267
+ return sql`exists ${subquery}`;
1268
+ }
1269
+ function notExists(subquery) {
1270
+ return sql`not exists ${subquery}`;
1271
+ }
1272
+ function between(column, min, max) {
1273
+ return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1274
+ }
1275
+ function notBetween(column, min, max) {
1276
+ return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1277
+ }
1278
+ function like(column, value) {
1279
+ return sql`${column} like ${value}`;
1280
+ }
1281
+ function notLike(column, value) {
1282
+ return sql`${column} not like ${value}`;
1283
+ }
1284
+ function ilike(column, value) {
1285
+ return sql`${column} ilike ${value}`;
1286
+ }
1287
+ function notIlike(column, value) {
1288
+ return sql`${column} not ilike ${value}`;
1289
+ }
1290
+
1291
+ // node_modules/drizzle-orm/sql/expressions/select.js
1292
+ function asc(column) {
1293
+ return sql`${column} asc`;
1294
+ }
1295
+ function desc(column) {
1296
+ return sql`${column} desc`;
1297
+ }
1298
+
1299
+ // node_modules/drizzle-orm/relations.js
1300
+ class Relation {
1301
+ constructor(sourceTable, referencedTable, relationName) {
1302
+ this.sourceTable = sourceTable;
1303
+ this.referencedTable = referencedTable;
1304
+ this.relationName = relationName;
1305
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
1306
+ }
1307
+ static [entityKind] = "Relation";
1308
+ referencedTableName;
1309
+ fieldName;
1310
+ }
1311
+
1312
+ class Relations {
1313
+ constructor(table, config) {
1314
+ this.table = table;
1315
+ this.config = config;
1316
+ }
1317
+ static [entityKind] = "Relations";
1318
+ }
1319
+
1320
+ class One extends Relation {
1321
+ constructor(sourceTable, referencedTable, config, isNullable) {
1322
+ super(sourceTable, referencedTable, config?.relationName);
1323
+ this.config = config;
1324
+ this.isNullable = isNullable;
1325
+ }
1326
+ static [entityKind] = "One";
1327
+ withFieldName(fieldName) {
1328
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1329
+ relation.fieldName = fieldName;
1330
+ return relation;
1331
+ }
1332
+ }
1333
+
1334
+ class Many extends Relation {
1335
+ constructor(sourceTable, referencedTable, config) {
1336
+ super(sourceTable, referencedTable, config?.relationName);
1337
+ this.config = config;
1338
+ }
1339
+ static [entityKind] = "Many";
1340
+ withFieldName(fieldName) {
1341
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1342
+ relation.fieldName = fieldName;
1343
+ return relation;
1344
+ }
1345
+ }
1346
+ function getOperators() {
1347
+ return {
1348
+ and,
1349
+ between,
1350
+ eq,
1351
+ exists,
1352
+ gt,
1353
+ gte,
1354
+ ilike,
1355
+ inArray,
1356
+ isNull,
1357
+ isNotNull,
1358
+ like,
1359
+ lt,
1360
+ lte,
1361
+ ne,
1362
+ not,
1363
+ notBetween,
1364
+ notExists,
1365
+ notLike,
1366
+ notIlike,
1367
+ notInArray,
1368
+ or,
1369
+ sql
1370
+ };
1371
+ }
1372
+ function getOrderByOperators() {
1373
+ return {
1374
+ sql,
1375
+ asc,
1376
+ desc
1377
+ };
1378
+ }
1379
+ function extractTablesRelationalConfig(schema, configHelpers) {
1380
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
1381
+ schema = schema["default"];
1382
+ }
1383
+ const tableNamesMap = {};
1384
+ const relationsBuffer = {};
1385
+ const tablesConfig = {};
1386
+ for (const [key, value] of Object.entries(schema)) {
1387
+ if (is(value, Table)) {
1388
+ const dbName = getTableUniqueName(value);
1389
+ const bufferedRelations = relationsBuffer[dbName];
1390
+ tableNamesMap[dbName] = key;
1391
+ tablesConfig[key] = {
1392
+ tsName: key,
1393
+ dbName: value[Table.Symbol.Name],
1394
+ schema: value[Table.Symbol.Schema],
1395
+ columns: value[Table.Symbol.Columns],
1396
+ relations: bufferedRelations?.relations ?? {},
1397
+ primaryKey: bufferedRelations?.primaryKey ?? []
1398
+ };
1399
+ for (const column of Object.values(value[Table.Symbol.Columns])) {
1400
+ if (column.primary) {
1401
+ tablesConfig[key].primaryKey.push(column);
1402
+ }
1403
+ }
1404
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1405
+ if (extraConfig) {
1406
+ for (const configEntry of Object.values(extraConfig)) {
1407
+ if (is(configEntry, PrimaryKeyBuilder)) {
1408
+ tablesConfig[key].primaryKey.push(...configEntry.columns);
1409
+ }
1410
+ }
1411
+ }
1412
+ } else if (is(value, Relations)) {
1413
+ const dbName = getTableUniqueName(value.table);
1414
+ const tableName = tableNamesMap[dbName];
1415
+ const relations2 = value.config(configHelpers(value.table));
1416
+ let primaryKey;
1417
+ for (const [relationName, relation] of Object.entries(relations2)) {
1418
+ if (tableName) {
1419
+ const tableConfig = tablesConfig[tableName];
1420
+ tableConfig.relations[relationName] = relation;
1421
+ if (primaryKey) {
1422
+ tableConfig.primaryKey.push(...primaryKey);
1423
+ }
1424
+ } else {
1425
+ if (!(dbName in relationsBuffer)) {
1426
+ relationsBuffer[dbName] = {
1427
+ relations: {},
1428
+ primaryKey
1429
+ };
1430
+ }
1431
+ relationsBuffer[dbName].relations[relationName] = relation;
1432
+ }
1433
+ }
1434
+ }
1435
+ }
1436
+ return { tables: tablesConfig, tableNamesMap };
1437
+ }
1438
+ function createOne(sourceTable) {
1439
+ return function one(table, config) {
1440
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
1441
+ };
1442
+ }
1443
+ function createMany(sourceTable) {
1444
+ return function many(referencedTable, config) {
1445
+ return new Many(sourceTable, referencedTable, config);
1446
+ };
1447
+ }
1448
+ function normalizeRelation(schema, tableNamesMap, relation) {
1449
+ if (is(relation, One) && relation.config) {
1450
+ return {
1451
+ fields: relation.config.fields,
1452
+ references: relation.config.references
1453
+ };
1454
+ }
1455
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1456
+ if (!referencedTableTsName) {
1457
+ throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1458
+ }
1459
+ const referencedTableConfig = schema[referencedTableTsName];
1460
+ if (!referencedTableConfig) {
1461
+ throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1462
+ }
1463
+ const sourceTable = relation.sourceTable;
1464
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1465
+ if (!sourceTableTsName) {
1466
+ throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1467
+ }
1468
+ const reverseRelations = [];
1469
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
1470
+ if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
1471
+ reverseRelations.push(referencedTableRelation);
1472
+ }
1473
+ }
1474
+ if (reverseRelations.length > 1) {
1475
+ throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
1476
+ }
1477
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
1478
+ return {
1479
+ fields: reverseRelations[0].config.references,
1480
+ references: reverseRelations[0].config.fields
1481
+ };
1482
+ }
1483
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1484
+ }
1485
+ function createTableRelationsHelpers(sourceTable) {
1486
+ return {
1487
+ one: createOne(sourceTable),
1488
+ many: createMany(sourceTable)
1489
+ };
1490
+ }
1491
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1492
+ const result = {};
1493
+ for (const [
1494
+ selectionItemIndex,
1495
+ selectionItem
1496
+ ] of buildQueryResultSelection.entries()) {
1497
+ if (selectionItem.isJson) {
1498
+ const relation = tableConfig.relations[selectionItem.tsKey];
1499
+ const rawSubRows = row[selectionItemIndex];
1500
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1501
+ result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
1502
+ } else {
1503
+ const value = mapColumnValue(row[selectionItemIndex]);
1504
+ const field = selectionItem.field;
1505
+ let decoder;
1506
+ if (is(field, Column)) {
1507
+ decoder = field;
1508
+ } else if (is(field, SQL)) {
1509
+ decoder = field.decoder;
1510
+ } else {
1511
+ decoder = field.sql.decoder;
1512
+ }
1513
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1514
+ }
1515
+ }
1516
+ return result;
1517
+ }
1518
+
1519
+ // node_modules/drizzle-orm/pg-core/view-base.js
1520
+ class PgViewBase extends View {
1521
+ static [entityKind] = "PgViewBase";
1522
+ }
1523
+
1524
+ // node_modules/drizzle-orm/pg-core/dialect.js
1525
+ class PgDialect {
1526
+ static [entityKind] = "PgDialect";
1527
+ casing;
1528
+ constructor(config) {
1529
+ this.casing = new CasingCache(config?.casing);
1530
+ }
1531
+ async migrate(migrations, session, config) {
1532
+ const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
1533
+ const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
1534
+ const migrationTableCreate = sql`
1535
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
1536
+ id SERIAL PRIMARY KEY,
1537
+ hash text NOT NULL,
1538
+ created_at bigint
1539
+ )
1540
+ `;
1541
+ await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
1542
+ await session.execute(migrationTableCreate);
1543
+ const dbMigrations = await session.all(sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`);
1544
+ const lastDbMigration = dbMigrations[0];
1545
+ await session.transaction(async (tx) => {
1546
+ for await (const migration of migrations) {
1547
+ if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
1548
+ for (const stmt of migration.sql) {
1549
+ await tx.execute(sql.raw(stmt));
1550
+ }
1551
+ await tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`);
1552
+ }
1553
+ }
1554
+ });
1555
+ }
1556
+ escapeName(name) {
1557
+ return `"${name}"`;
1558
+ }
1559
+ escapeParam(num) {
1560
+ return `$${num + 1}`;
1561
+ }
1562
+ escapeString(str) {
1563
+ return `'${str.replace(/'/g, "''")}'`;
1564
+ }
1565
+ buildWithCTE(queries) {
1566
+ if (!queries?.length)
1567
+ return;
1568
+ const withSqlChunks = [sql`with `];
1569
+ for (const [i, w] of queries.entries()) {
1570
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
1571
+ if (i < queries.length - 1) {
1572
+ withSqlChunks.push(sql`, `);
1573
+ }
1574
+ }
1575
+ withSqlChunks.push(sql` `);
1576
+ return sql.join(withSqlChunks);
1577
+ }
1578
+ buildDeleteQuery({ table, where, returning, withList }) {
1579
+ const withSql = this.buildWithCTE(withList);
1580
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
1581
+ const whereSql = where ? sql` where ${where}` : undefined;
1582
+ return sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
1583
+ }
1584
+ buildUpdateSet(table, set) {
1585
+ const tableColumns = table[Table.Symbol.Columns];
1586
+ const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined);
1587
+ const setSize = columnNames.length;
1588
+ return sql.join(columnNames.flatMap((colName, i) => {
1589
+ const col = tableColumns[colName];
1590
+ const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
1591
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
1592
+ if (i < setSize - 1) {
1593
+ return [res, sql.raw(", ")];
1594
+ }
1595
+ return [res];
1596
+ }));
1597
+ }
1598
+ buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
1599
+ const withSql = this.buildWithCTE(withList);
1600
+ const tableName = table[PgTable.Symbol.Name];
1601
+ const tableSchema = table[PgTable.Symbol.Schema];
1602
+ const origTableName = table[PgTable.Symbol.OriginalName];
1603
+ const alias = tableName === origTableName ? undefined : tableName;
1604
+ const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
1605
+ const setSql = this.buildUpdateSet(table, set);
1606
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
1607
+ const joinsSql = this.buildJoins(joins);
1608
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : undefined;
1609
+ const whereSql = where ? sql` where ${where}` : undefined;
1610
+ return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
1611
+ }
1612
+ buildSelection(fields, { isSingleTable = false } = {}) {
1613
+ const columnsLen = fields.length;
1614
+ const chunks = fields.flatMap(({ field }, i) => {
1615
+ const chunk = [];
1616
+ if (is(field, SQL.Aliased) && field.isSelectionField) {
1617
+ chunk.push(sql.identifier(field.fieldAlias));
1618
+ } else if (is(field, SQL.Aliased) || is(field, SQL)) {
1619
+ const query = is(field, SQL.Aliased) ? field.sql : field;
1620
+ if (isSingleTable) {
1621
+ chunk.push(new SQL(query.queryChunks.map((c) => {
1622
+ if (is(c, PgColumn)) {
1623
+ return sql.identifier(this.casing.getColumnCasing(c));
1624
+ }
1625
+ return c;
1626
+ })));
1627
+ } else {
1628
+ chunk.push(query);
1629
+ }
1630
+ if (is(field, SQL.Aliased)) {
1631
+ chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
1632
+ }
1633
+ } else if (is(field, Column)) {
1634
+ if (isSingleTable) {
1635
+ chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
1636
+ } else {
1637
+ chunk.push(field);
1638
+ }
1639
+ }
1640
+ if (i < columnsLen - 1) {
1641
+ chunk.push(sql`, `);
1642
+ }
1643
+ return chunk;
1644
+ });
1645
+ return sql.join(chunks);
1646
+ }
1647
+ buildJoins(joins) {
1648
+ if (!joins || joins.length === 0) {
1649
+ return;
1650
+ }
1651
+ const joinsArray = [];
1652
+ for (const [index, joinMeta] of joins.entries()) {
1653
+ if (index === 0) {
1654
+ joinsArray.push(sql` `);
1655
+ }
1656
+ const table = joinMeta.table;
1657
+ const lateralSql = joinMeta.lateral ? sql` lateral` : undefined;
1658
+ if (is(table, PgTable)) {
1659
+ const tableName = table[PgTable.Symbol.Name];
1660
+ const tableSchema = table[PgTable.Symbol.Schema];
1661
+ const origTableName = table[PgTable.Symbol.OriginalName];
1662
+ const alias = tableName === origTableName ? undefined : joinMeta.alias;
1663
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
1664
+ } else if (is(table, View)) {
1665
+ const viewName = table[ViewBaseConfig].name;
1666
+ const viewSchema = table[ViewBaseConfig].schema;
1667
+ const origViewName = table[ViewBaseConfig].originalName;
1668
+ const alias = viewName === origViewName ? undefined : joinMeta.alias;
1669
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : undefined}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
1670
+ } else {
1671
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}`);
1672
+ }
1673
+ if (index < joins.length - 1) {
1674
+ joinsArray.push(sql` `);
1675
+ }
1676
+ }
1677
+ return sql.join(joinsArray);
1678
+ }
1679
+ buildFromTable(table) {
1680
+ if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {
1681
+ let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;
1682
+ if (table[Table.Symbol.Schema]) {
1683
+ fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
1684
+ }
1685
+ return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
1686
+ }
1687
+ return table;
1688
+ }
1689
+ buildSelectQuery({
1690
+ withList,
1691
+ fields,
1692
+ fieldsFlat,
1693
+ where,
1694
+ having,
1695
+ table,
1696
+ joins,
1697
+ orderBy,
1698
+ groupBy,
1699
+ limit,
1700
+ offset,
1701
+ lockingClause,
1702
+ distinct,
1703
+ setOperators
1704
+ }) {
1705
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
1706
+ for (const f of fieldsList) {
1707
+ if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) {
1708
+ const tableName = getTableName(f.field.table);
1709
+ throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
1710
+ }
1711
+ }
1712
+ const isSingleTable = !joins || joins.length === 0;
1713
+ const withSql = this.buildWithCTE(withList);
1714
+ let distinctSql;
1715
+ if (distinct) {
1716
+ distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
1717
+ }
1718
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
1719
+ const tableSql = this.buildFromTable(table);
1720
+ const joinsSql = this.buildJoins(joins);
1721
+ const whereSql = where ? sql` where ${where}` : undefined;
1722
+ const havingSql = having ? sql` having ${having}` : undefined;
1723
+ let orderBySql;
1724
+ if (orderBy && orderBy.length > 0) {
1725
+ orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
1726
+ }
1727
+ let groupBySql;
1728
+ if (groupBy && groupBy.length > 0) {
1729
+ groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
1730
+ }
1731
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
1732
+ const offsetSql = offset ? sql` offset ${offset}` : undefined;
1733
+ const lockingClauseSql = sql.empty();
1734
+ if (lockingClause) {
1735
+ const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
1736
+ if (lockingClause.config.of) {
1737
+ clauseSql.append(sql` of ${sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], sql`, `)}`);
1738
+ }
1739
+ if (lockingClause.config.noWait) {
1740
+ clauseSql.append(sql` no wait`);
1741
+ } else if (lockingClause.config.skipLocked) {
1742
+ clauseSql.append(sql` skip locked`);
1743
+ }
1744
+ lockingClauseSql.append(clauseSql);
1745
+ }
1746
+ const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
1747
+ if (setOperators.length > 0) {
1748
+ return this.buildSetOperations(finalQuery, setOperators);
1749
+ }
1750
+ return finalQuery;
1751
+ }
1752
+ buildSetOperations(leftSelect, setOperators) {
1753
+ const [setOperator, ...rest] = setOperators;
1754
+ if (!setOperator) {
1755
+ throw new Error("Cannot pass undefined values to any set operator");
1756
+ }
1757
+ if (rest.length === 0) {
1758
+ return this.buildSetOperationQuery({ leftSelect, setOperator });
1759
+ }
1760
+ return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest);
1761
+ }
1762
+ buildSetOperationQuery({
1763
+ leftSelect,
1764
+ setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
1765
+ }) {
1766
+ const leftChunk = sql`(${leftSelect.getSQL()}) `;
1767
+ const rightChunk = sql`(${rightSelect.getSQL()})`;
1768
+ let orderBySql;
1769
+ if (orderBy && orderBy.length > 0) {
1770
+ const orderByValues = [];
1771
+ for (const singleOrderBy of orderBy) {
1772
+ if (is(singleOrderBy, PgColumn)) {
1773
+ orderByValues.push(sql.identifier(singleOrderBy.name));
1774
+ } else if (is(singleOrderBy, SQL)) {
1775
+ for (let i = 0;i < singleOrderBy.queryChunks.length; i++) {
1776
+ const chunk = singleOrderBy.queryChunks[i];
1777
+ if (is(chunk, PgColumn)) {
1778
+ singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
1779
+ }
1780
+ }
1781
+ orderByValues.push(sql`${singleOrderBy}`);
1782
+ } else {
1783
+ orderByValues.push(sql`${singleOrderBy}`);
1784
+ }
1785
+ }
1786
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
1787
+ }
1788
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
1789
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
1790
+ const offsetSql = offset ? sql` offset ${offset}` : undefined;
1791
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
1792
+ }
1793
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
1794
+ const valuesSqlList = [];
1795
+ const columns = table[Table.Symbol.Columns];
1796
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
1797
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
1798
+ if (select) {
1799
+ const select2 = valuesOrSelect;
1800
+ if (is(select2, SQL)) {
1801
+ valuesSqlList.push(select2);
1802
+ } else {
1803
+ valuesSqlList.push(select2.getSQL());
1804
+ }
1805
+ } else {
1806
+ const values = valuesOrSelect;
1807
+ valuesSqlList.push(sql.raw("values "));
1808
+ for (const [valueIndex, value] of values.entries()) {
1809
+ const valueList = [];
1810
+ for (const [fieldName, col] of colEntries) {
1811
+ const colValue = value[fieldName];
1812
+ if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) {
1813
+ if (col.defaultFn !== undefined) {
1814
+ const defaultFnResult = col.defaultFn();
1815
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
1816
+ valueList.push(defaultValue);
1817
+ } else if (!col.default && col.onUpdateFn !== undefined) {
1818
+ const onUpdateFnResult = col.onUpdateFn();
1819
+ const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
1820
+ valueList.push(newValue);
1821
+ } else {
1822
+ valueList.push(sql`default`);
1823
+ }
1824
+ } else {
1825
+ valueList.push(colValue);
1826
+ }
1827
+ }
1828
+ valuesSqlList.push(valueList);
1829
+ if (valueIndex < values.length - 1) {
1830
+ valuesSqlList.push(sql`, `);
1831
+ }
1832
+ }
1833
+ }
1834
+ const withSql = this.buildWithCTE(withList);
1835
+ const valuesSql = sql.join(valuesSqlList);
1836
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
1837
+ const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined;
1838
+ const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : undefined;
1839
+ return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
1840
+ }
1841
+ buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
1842
+ const concurrentlySql = concurrently ? sql` concurrently` : undefined;
1843
+ const withNoDataSql = withNoData ? sql` with no data` : undefined;
1844
+ return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
1845
+ }
1846
+ prepareTyping(encoder) {
1847
+ if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
1848
+ return "json";
1849
+ } else if (is(encoder, PgNumeric)) {
1850
+ return "decimal";
1851
+ } else if (is(encoder, PgTime)) {
1852
+ return "time";
1853
+ } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
1854
+ return "timestamp";
1855
+ } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
1856
+ return "date";
1857
+ } else if (is(encoder, PgUUID)) {
1858
+ return "uuid";
1859
+ } else {
1860
+ return "none";
1861
+ }
1862
+ }
1863
+ sqlToQuery(sql2, invokeSource) {
1864
+ return sql2.toQuery({
1865
+ casing: this.casing,
1866
+ escapeName: this.escapeName,
1867
+ escapeParam: this.escapeParam,
1868
+ escapeString: this.escapeString,
1869
+ prepareTyping: this.prepareTyping,
1870
+ invokeSource
1871
+ });
1872
+ }
1873
+ buildRelationalQueryWithoutPK({
1874
+ fullSchema,
1875
+ schema,
1876
+ tableNamesMap,
1877
+ table,
1878
+ tableConfig,
1879
+ queryConfig: config,
1880
+ tableAlias,
1881
+ nestedQueryRelation,
1882
+ joinOn
1883
+ }) {
1884
+ let selection = [];
1885
+ let limit, offset, orderBy = [], where;
1886
+ const joins = [];
1887
+ if (config === true) {
1888
+ const selectionEntries = Object.entries(tableConfig.columns);
1889
+ selection = selectionEntries.map(([key, value]) => ({
1890
+ dbKey: value.name,
1891
+ tsKey: key,
1892
+ field: aliasedTableColumn(value, tableAlias),
1893
+ relationTableTsKey: undefined,
1894
+ isJson: false,
1895
+ selection: []
1896
+ }));
1897
+ } else {
1898
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
1899
+ if (config.where) {
1900
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
1901
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
1902
+ }
1903
+ const fieldsSelection = [];
1904
+ let selectedColumns = [];
1905
+ if (config.columns) {
1906
+ let isIncludeMode = false;
1907
+ for (const [field, value] of Object.entries(config.columns)) {
1908
+ if (value === undefined) {
1909
+ continue;
1910
+ }
1911
+ if (field in tableConfig.columns) {
1912
+ if (!isIncludeMode && value === true) {
1913
+ isIncludeMode = true;
1914
+ }
1915
+ selectedColumns.push(field);
1916
+ }
1917
+ }
1918
+ if (selectedColumns.length > 0) {
1919
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1920
+ }
1921
+ } else {
1922
+ selectedColumns = Object.keys(tableConfig.columns);
1923
+ }
1924
+ for (const field of selectedColumns) {
1925
+ const column = tableConfig.columns[field];
1926
+ fieldsSelection.push({ tsKey: field, value: column });
1927
+ }
1928
+ let selectedRelations = [];
1929
+ if (config.with) {
1930
+ selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
1931
+ }
1932
+ let extras;
1933
+ if (config.extras) {
1934
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
1935
+ for (const [tsKey, value] of Object.entries(extras)) {
1936
+ fieldsSelection.push({
1937
+ tsKey,
1938
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
1939
+ });
1940
+ }
1941
+ }
1942
+ for (const { tsKey, value } of fieldsSelection) {
1943
+ selection.push({
1944
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
1945
+ tsKey,
1946
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
1947
+ relationTableTsKey: undefined,
1948
+ isJson: false,
1949
+ selection: []
1950
+ });
1951
+ }
1952
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
1953
+ if (!Array.isArray(orderByOrig)) {
1954
+ orderByOrig = [orderByOrig];
1955
+ }
1956
+ orderBy = orderByOrig.map((orderByValue) => {
1957
+ if (is(orderByValue, Column)) {
1958
+ return aliasedTableColumn(orderByValue, tableAlias);
1959
+ }
1960
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1961
+ });
1962
+ limit = config.limit;
1963
+ offset = config.offset;
1964
+ for (const {
1965
+ tsKey: selectedRelationTsKey,
1966
+ queryConfig: selectedRelationConfigValue,
1967
+ relation
1968
+ } of selectedRelations) {
1969
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1970
+ const relationTableName = getTableUniqueName(relation.referencedTable);
1971
+ const relationTableTsName = tableNamesMap[relationTableName];
1972
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1973
+ const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
1974
+ const builtRelation = this.buildRelationalQueryWithoutPK({
1975
+ fullSchema,
1976
+ schema,
1977
+ tableNamesMap,
1978
+ table: fullSchema[relationTableTsName],
1979
+ tableConfig: schema[relationTableTsName],
1980
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
1981
+ tableAlias: relationTableAlias,
1982
+ joinOn: joinOn2,
1983
+ nestedQueryRelation: relation
1984
+ });
1985
+ const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
1986
+ joins.push({
1987
+ on: sql`true`,
1988
+ table: new Subquery(builtRelation.sql, {}, relationTableAlias),
1989
+ alias: relationTableAlias,
1990
+ joinType: "left",
1991
+ lateral: true
1992
+ });
1993
+ selection.push({
1994
+ dbKey: selectedRelationTsKey,
1995
+ tsKey: selectedRelationTsKey,
1996
+ field,
1997
+ relationTableTsKey: relationTableTsName,
1998
+ isJson: true,
1999
+ selection: builtRelation.selection
2000
+ });
2001
+ }
2002
+ }
2003
+ if (selection.length === 0) {
2004
+ throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
2005
+ }
2006
+ let result;
2007
+ where = and(joinOn, where);
2008
+ if (nestedQueryRelation) {
2009
+ let field = sql`json_build_array(${sql.join(selection.map(({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
2010
+ if (is(nestedQueryRelation, Many)) {
2011
+ field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : undefined}), '[]'::json)`;
2012
+ }
2013
+ const nestedSelection = [{
2014
+ dbKey: "data",
2015
+ tsKey: "data",
2016
+ field: field.as("data"),
2017
+ isJson: true,
2018
+ relationTableTsKey: tableConfig.tsName,
2019
+ selection
2020
+ }];
2021
+ const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
2022
+ if (needsSubquery) {
2023
+ result = this.buildSelectQuery({
2024
+ table: aliasedTable(table, tableAlias),
2025
+ fields: {},
2026
+ fieldsFlat: [{
2027
+ path: [],
2028
+ field: sql.raw("*")
2029
+ }],
2030
+ where,
2031
+ limit,
2032
+ offset,
2033
+ orderBy,
2034
+ setOperators: []
2035
+ });
2036
+ where = undefined;
2037
+ limit = undefined;
2038
+ offset = undefined;
2039
+ orderBy = [];
2040
+ } else {
2041
+ result = aliasedTable(table, tableAlias);
2042
+ }
2043
+ result = this.buildSelectQuery({
2044
+ table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
2045
+ fields: {},
2046
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
2047
+ path: [],
2048
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
2049
+ })),
2050
+ joins,
2051
+ where,
2052
+ limit,
2053
+ offset,
2054
+ orderBy,
2055
+ setOperators: []
2056
+ });
2057
+ } else {
2058
+ result = this.buildSelectQuery({
2059
+ table: aliasedTable(table, tableAlias),
2060
+ fields: {},
2061
+ fieldsFlat: selection.map(({ field }) => ({
2062
+ path: [],
2063
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
2064
+ })),
2065
+ joins,
2066
+ where,
2067
+ limit,
2068
+ offset,
2069
+ orderBy,
2070
+ setOperators: []
2071
+ });
2072
+ }
2073
+ return {
2074
+ tableTsKey: tableConfig.tsName,
2075
+ sql: result,
2076
+ selection
2077
+ };
2078
+ }
2079
+ }
2080
+
2081
+ // node_modules/drizzle-orm/query-builders/query-builder.js
2082
+ class TypedQueryBuilder {
2083
+ static [entityKind] = "TypedQueryBuilder";
2084
+ getSelectedFields() {
2085
+ return this._.selectedFields;
2086
+ }
2087
+ }
2088
+
2089
+ // node_modules/drizzle-orm/pg-core/query-builders/select.js
2090
+ class PgSelectBuilder {
2091
+ static [entityKind] = "PgSelectBuilder";
2092
+ fields;
2093
+ session;
2094
+ dialect;
2095
+ withList = [];
2096
+ distinct;
2097
+ constructor(config) {
2098
+ this.fields = config.fields;
2099
+ this.session = config.session;
2100
+ this.dialect = config.dialect;
2101
+ if (config.withList) {
2102
+ this.withList = config.withList;
2103
+ }
2104
+ this.distinct = config.distinct;
2105
+ }
2106
+ authToken;
2107
+ setToken(token) {
2108
+ this.authToken = token;
2109
+ return this;
2110
+ }
2111
+ from(source) {
2112
+ const isPartialSelect = !!this.fields;
2113
+ const src = source;
2114
+ let fields;
2115
+ if (this.fields) {
2116
+ fields = this.fields;
2117
+ } else if (is(src, Subquery)) {
2118
+ fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]]));
2119
+ } else if (is(src, PgViewBase)) {
2120
+ fields = src[ViewBaseConfig].selectedFields;
2121
+ } else if (is(src, SQL)) {
2122
+ fields = {};
2123
+ } else {
2124
+ fields = getTableColumns(src);
2125
+ }
2126
+ return new PgSelectBase({
2127
+ table: src,
2128
+ fields,
2129
+ isPartialSelect,
2130
+ session: this.session,
2131
+ dialect: this.dialect,
2132
+ withList: this.withList,
2133
+ distinct: this.distinct
2134
+ }).setToken(this.authToken);
2135
+ }
2136
+ }
2137
+
2138
+ class PgSelectQueryBuilderBase extends TypedQueryBuilder {
2139
+ static [entityKind] = "PgSelectQueryBuilder";
2140
+ _;
2141
+ config;
2142
+ joinsNotNullableMap;
2143
+ tableName;
2144
+ isPartialSelect;
2145
+ session;
2146
+ dialect;
2147
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
2148
+ super();
2149
+ this.config = {
2150
+ withList,
2151
+ table,
2152
+ fields: { ...fields },
2153
+ distinct,
2154
+ setOperators: []
2155
+ };
2156
+ this.isPartialSelect = isPartialSelect;
2157
+ this.session = session;
2158
+ this.dialect = dialect;
2159
+ this._ = {
2160
+ selectedFields: fields
2161
+ };
2162
+ this.tableName = getTableLikeName(table);
2163
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
2164
+ }
2165
+ createJoin(joinType) {
2166
+ return (table, on) => {
2167
+ const baseTableName = this.tableName;
2168
+ const tableName = getTableLikeName(table);
2169
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
2170
+ throw new Error(`Alias "${tableName}" is already used in this query`);
2171
+ }
2172
+ if (!this.isPartialSelect) {
2173
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
2174
+ this.config.fields = {
2175
+ [baseTableName]: this.config.fields
2176
+ };
2177
+ }
2178
+ if (typeof tableName === "string" && !is(table, SQL)) {
2179
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
2180
+ this.config.fields[tableName] = selection;
2181
+ }
2182
+ }
2183
+ if (typeof on === "function") {
2184
+ on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
2185
+ }
2186
+ if (!this.config.joins) {
2187
+ this.config.joins = [];
2188
+ }
2189
+ this.config.joins.push({ on, table, joinType, alias: tableName });
2190
+ if (typeof tableName === "string") {
2191
+ switch (joinType) {
2192
+ case "left": {
2193
+ this.joinsNotNullableMap[tableName] = false;
2194
+ break;
2195
+ }
2196
+ case "right": {
2197
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2198
+ this.joinsNotNullableMap[tableName] = true;
2199
+ break;
2200
+ }
2201
+ case "inner": {
2202
+ this.joinsNotNullableMap[tableName] = true;
2203
+ break;
2204
+ }
2205
+ case "full": {
2206
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2207
+ this.joinsNotNullableMap[tableName] = false;
2208
+ break;
2209
+ }
2210
+ }
2211
+ }
2212
+ return this;
2213
+ };
2214
+ }
2215
+ leftJoin = this.createJoin("left");
2216
+ rightJoin = this.createJoin("right");
2217
+ innerJoin = this.createJoin("inner");
2218
+ fullJoin = this.createJoin("full");
2219
+ createSetOperator(type, isAll) {
2220
+ return (rightSelection) => {
2221
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
2222
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
2223
+ throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
2224
+ }
2225
+ this.config.setOperators.push({ type, isAll, rightSelect });
2226
+ return this;
2227
+ };
2228
+ }
2229
+ union = this.createSetOperator("union", false);
2230
+ unionAll = this.createSetOperator("union", true);
2231
+ intersect = this.createSetOperator("intersect", false);
2232
+ intersectAll = this.createSetOperator("intersect", true);
2233
+ except = this.createSetOperator("except", false);
2234
+ exceptAll = this.createSetOperator("except", true);
2235
+ addSetOperators(setOperators) {
2236
+ this.config.setOperators.push(...setOperators);
2237
+ return this;
2238
+ }
2239
+ where(where) {
2240
+ if (typeof where === "function") {
2241
+ where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
2242
+ }
2243
+ this.config.where = where;
2244
+ return this;
2245
+ }
2246
+ having(having) {
2247
+ if (typeof having === "function") {
2248
+ having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
2249
+ }
2250
+ this.config.having = having;
2251
+ return this;
2252
+ }
2253
+ groupBy(...columns) {
2254
+ if (typeof columns[0] === "function") {
2255
+ const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
2256
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
2257
+ } else {
2258
+ this.config.groupBy = columns;
2259
+ }
2260
+ return this;
2261
+ }
2262
+ orderBy(...columns) {
2263
+ if (typeof columns[0] === "function") {
2264
+ const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
2265
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
2266
+ if (this.config.setOperators.length > 0) {
2267
+ this.config.setOperators.at(-1).orderBy = orderByArray;
2268
+ } else {
2269
+ this.config.orderBy = orderByArray;
2270
+ }
2271
+ } else {
2272
+ const orderByArray = columns;
2273
+ if (this.config.setOperators.length > 0) {
2274
+ this.config.setOperators.at(-1).orderBy = orderByArray;
2275
+ } else {
2276
+ this.config.orderBy = orderByArray;
2277
+ }
2278
+ }
2279
+ return this;
2280
+ }
2281
+ limit(limit) {
2282
+ if (this.config.setOperators.length > 0) {
2283
+ this.config.setOperators.at(-1).limit = limit;
2284
+ } else {
2285
+ this.config.limit = limit;
2286
+ }
2287
+ return this;
2288
+ }
2289
+ offset(offset) {
2290
+ if (this.config.setOperators.length > 0) {
2291
+ this.config.setOperators.at(-1).offset = offset;
2292
+ } else {
2293
+ this.config.offset = offset;
2294
+ }
2295
+ return this;
2296
+ }
2297
+ for(strength, config = {}) {
2298
+ this.config.lockingClause = { strength, config };
2299
+ return this;
2300
+ }
2301
+ getSQL() {
2302
+ return this.dialect.buildSelectQuery(this.config);
2303
+ }
2304
+ toSQL() {
2305
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2306
+ return rest;
2307
+ }
2308
+ as(alias) {
2309
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
2310
+ }
2311
+ getSelectedFields() {
2312
+ return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
2313
+ }
2314
+ $dynamic() {
2315
+ return this;
2316
+ }
2317
+ }
2318
+
2319
+ class PgSelectBase extends PgSelectQueryBuilderBase {
2320
+ static [entityKind] = "PgSelect";
2321
+ _prepare(name) {
2322
+ const { session, config, dialect, joinsNotNullableMap, authToken } = this;
2323
+ if (!session) {
2324
+ throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
2325
+ }
2326
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2327
+ const fieldsList = orderSelectedFields(config.fields);
2328
+ const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true);
2329
+ query.joinsNotNullableMap = joinsNotNullableMap;
2330
+ return query.setToken(authToken);
2331
+ });
2332
+ }
2333
+ prepare(name) {
2334
+ return this._prepare(name);
2335
+ }
2336
+ authToken;
2337
+ setToken(token) {
2338
+ this.authToken = token;
2339
+ return this;
2340
+ }
2341
+ execute = (placeholderValues) => {
2342
+ return tracer.startActiveSpan("drizzle.operation", () => {
2343
+ return this._prepare().execute(placeholderValues, this.authToken);
2344
+ });
2345
+ };
2346
+ }
2347
+ applyMixins(PgSelectBase, [QueryPromise]);
2348
+ function createSetOperator(type, isAll) {
2349
+ return (leftSelect, rightSelect, ...restSelects) => {
2350
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
2351
+ type,
2352
+ isAll,
2353
+ rightSelect: select
2354
+ }));
2355
+ for (const setOperator of setOperators) {
2356
+ if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
2357
+ throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
2358
+ }
2359
+ }
2360
+ return leftSelect.addSetOperators(setOperators);
2361
+ };
2362
+ }
2363
+ var getPgSetOperators = () => ({
2364
+ union,
2365
+ unionAll,
2366
+ intersect,
2367
+ intersectAll,
2368
+ except,
2369
+ exceptAll
2370
+ });
2371
+ var union = createSetOperator("union", false);
2372
+ var unionAll = createSetOperator("union", true);
2373
+ var intersect = createSetOperator("intersect", false);
2374
+ var intersectAll = createSetOperator("intersect", true);
2375
+ var except = createSetOperator("except", false);
2376
+ var exceptAll = createSetOperator("except", true);
2377
+
2378
+ // node_modules/drizzle-orm/pg-core/query-builders/query-builder.js
2379
+ class QueryBuilder {
2380
+ static [entityKind] = "PgQueryBuilder";
2381
+ dialect;
2382
+ dialectConfig;
2383
+ constructor(dialect) {
2384
+ this.dialect = is(dialect, PgDialect) ? dialect : undefined;
2385
+ this.dialectConfig = is(dialect, PgDialect) ? undefined : dialect;
2386
+ }
2387
+ $with = (alias, selection) => {
2388
+ const queryBuilder = this;
2389
+ const as = (qb) => {
2390
+ if (typeof qb === "function") {
2391
+ qb = qb(queryBuilder);
2392
+ }
2393
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
2394
+ };
2395
+ return { as };
2396
+ };
2397
+ with(...queries) {
2398
+ const self = this;
2399
+ function select(fields) {
2400
+ return new PgSelectBuilder({
2401
+ fields: fields ?? undefined,
2402
+ session: undefined,
2403
+ dialect: self.getDialect(),
2404
+ withList: queries
2405
+ });
2406
+ }
2407
+ function selectDistinct(fields) {
2408
+ return new PgSelectBuilder({
2409
+ fields: fields ?? undefined,
2410
+ session: undefined,
2411
+ dialect: self.getDialect(),
2412
+ distinct: true
2413
+ });
2414
+ }
2415
+ function selectDistinctOn(on, fields) {
2416
+ return new PgSelectBuilder({
2417
+ fields: fields ?? undefined,
2418
+ session: undefined,
2419
+ dialect: self.getDialect(),
2420
+ distinct: { on }
2421
+ });
2422
+ }
2423
+ return { select, selectDistinct, selectDistinctOn };
2424
+ }
2425
+ select(fields) {
2426
+ return new PgSelectBuilder({
2427
+ fields: fields ?? undefined,
2428
+ session: undefined,
2429
+ dialect: this.getDialect()
2430
+ });
2431
+ }
2432
+ selectDistinct(fields) {
2433
+ return new PgSelectBuilder({
2434
+ fields: fields ?? undefined,
2435
+ session: undefined,
2436
+ dialect: this.getDialect(),
2437
+ distinct: true
2438
+ });
2439
+ }
2440
+ selectDistinctOn(on, fields) {
2441
+ return new PgSelectBuilder({
2442
+ fields: fields ?? undefined,
2443
+ session: undefined,
2444
+ dialect: this.getDialect(),
2445
+ distinct: { on }
2446
+ });
2447
+ }
2448
+ getDialect() {
2449
+ if (!this.dialect) {
2450
+ this.dialect = new PgDialect(this.dialectConfig);
2451
+ }
2452
+ return this.dialect;
2453
+ }
2454
+ }
2455
+
2456
+ // node_modules/drizzle-orm/pg-core/query-builders/insert.js
2457
+ class PgInsertBuilder {
2458
+ constructor(table, session, dialect, withList, overridingSystemValue_) {
2459
+ this.table = table;
2460
+ this.session = session;
2461
+ this.dialect = dialect;
2462
+ this.withList = withList;
2463
+ this.overridingSystemValue_ = overridingSystemValue_;
2464
+ }
2465
+ static [entityKind] = "PgInsertBuilder";
2466
+ authToken;
2467
+ setToken(token) {
2468
+ this.authToken = token;
2469
+ return this;
2470
+ }
2471
+ overridingSystemValue() {
2472
+ this.overridingSystemValue_ = true;
2473
+ return this;
2474
+ }
2475
+ values(values) {
2476
+ values = Array.isArray(values) ? values : [values];
2477
+ if (values.length === 0) {
2478
+ throw new Error("values() must be called with at least one value");
2479
+ }
2480
+ const mappedValues = values.map((entry) => {
2481
+ const result = {};
2482
+ const cols = this.table[Table.Symbol.Columns];
2483
+ for (const colKey of Object.keys(entry)) {
2484
+ const colValue = entry[colKey];
2485
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
2486
+ }
2487
+ return result;
2488
+ });
2489
+ return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_).setToken(this.authToken);
2490
+ }
2491
+ select(selectQuery) {
2492
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery;
2493
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
2494
+ throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
2495
+ }
2496
+ return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
2497
+ }
2498
+ }
2499
+
2500
+ class PgInsertBase extends QueryPromise {
2501
+ constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
2502
+ super();
2503
+ this.session = session;
2504
+ this.dialect = dialect;
2505
+ this.config = { table, values, withList, select, overridingSystemValue_ };
2506
+ }
2507
+ static [entityKind] = "PgInsert";
2508
+ config;
2509
+ returning(fields = this.config.table[Table.Symbol.Columns]) {
2510
+ this.config.returningFields = fields;
2511
+ this.config.returning = orderSelectedFields(fields);
2512
+ return this;
2513
+ }
2514
+ onConflictDoNothing(config = {}) {
2515
+ if (config.target === undefined) {
2516
+ this.config.onConflict = sql`do nothing`;
2517
+ } else {
2518
+ let targetColumn = "";
2519
+ targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
2520
+ const whereSql = config.where ? sql` where ${config.where}` : undefined;
2521
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
2522
+ }
2523
+ return this;
2524
+ }
2525
+ onConflictDoUpdate(config) {
2526
+ if (config.where && (config.targetWhere || config.setWhere)) {
2527
+ throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');
2528
+ }
2529
+ const whereSql = config.where ? sql` where ${config.where}` : undefined;
2530
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
2531
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
2532
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
2533
+ let targetColumn = "";
2534
+ targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
2535
+ this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
2536
+ return this;
2537
+ }
2538
+ getSQL() {
2539
+ return this.dialect.buildInsertQuery(this.config);
2540
+ }
2541
+ toSQL() {
2542
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2543
+ return rest;
2544
+ }
2545
+ _prepare(name) {
2546
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2547
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
2548
+ });
2549
+ }
2550
+ prepare(name) {
2551
+ return this._prepare(name);
2552
+ }
2553
+ authToken;
2554
+ setToken(token) {
2555
+ this.authToken = token;
2556
+ return this;
2557
+ }
2558
+ execute = (placeholderValues) => {
2559
+ return tracer.startActiveSpan("drizzle.operation", () => {
2560
+ return this._prepare().execute(placeholderValues, this.authToken);
2561
+ });
2562
+ };
2563
+ getSelectedFields() {
2564
+ return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
2565
+ alias: getTableName(this.config.table),
2566
+ sqlAliasedBehavior: "alias",
2567
+ sqlBehavior: "error"
2568
+ })) : undefined;
2569
+ }
2570
+ $dynamic() {
2571
+ return this;
2572
+ }
2573
+ }
2574
+
2575
+ // node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js
2576
+ class PgRefreshMaterializedView extends QueryPromise {
2577
+ constructor(view, session, dialect) {
2578
+ super();
2579
+ this.session = session;
2580
+ this.dialect = dialect;
2581
+ this.config = { view };
2582
+ }
2583
+ static [entityKind] = "PgRefreshMaterializedView";
2584
+ config;
2585
+ concurrently() {
2586
+ if (this.config.withNoData !== undefined) {
2587
+ throw new Error("Cannot use concurrently and withNoData together");
2588
+ }
2589
+ this.config.concurrently = true;
2590
+ return this;
2591
+ }
2592
+ withNoData() {
2593
+ if (this.config.concurrently !== undefined) {
2594
+ throw new Error("Cannot use concurrently and withNoData together");
2595
+ }
2596
+ this.config.withNoData = true;
2597
+ return this;
2598
+ }
2599
+ getSQL() {
2600
+ return this.dialect.buildRefreshMaterializedViewQuery(this.config);
2601
+ }
2602
+ toSQL() {
2603
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2604
+ return rest;
2605
+ }
2606
+ _prepare(name) {
2607
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2608
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true);
2609
+ });
2610
+ }
2611
+ prepare(name) {
2612
+ return this._prepare(name);
2613
+ }
2614
+ authToken;
2615
+ setToken(token) {
2616
+ this.authToken = token;
2617
+ return this;
2618
+ }
2619
+ execute = (placeholderValues) => {
2620
+ return tracer.startActiveSpan("drizzle.operation", () => {
2621
+ return this._prepare().execute(placeholderValues, this.authToken);
2622
+ });
2623
+ };
2624
+ }
2625
+
2626
+ // node_modules/drizzle-orm/pg-core/query-builders/update.js
2627
+ class PgUpdateBuilder {
2628
+ constructor(table, session, dialect, withList) {
2629
+ this.table = table;
2630
+ this.session = session;
2631
+ this.dialect = dialect;
2632
+ this.withList = withList;
2633
+ }
2634
+ static [entityKind] = "PgUpdateBuilder";
2635
+ authToken;
2636
+ setToken(token) {
2637
+ this.authToken = token;
2638
+ return this;
2639
+ }
2640
+ set(values) {
2641
+ return new PgUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList).setToken(this.authToken);
2642
+ }
2643
+ }
2644
+
2645
+ class PgUpdateBase extends QueryPromise {
2646
+ constructor(table, set, session, dialect, withList) {
2647
+ super();
2648
+ this.session = session;
2649
+ this.dialect = dialect;
2650
+ this.config = { set, table, withList, joins: [] };
2651
+ this.tableName = getTableLikeName(table);
2652
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
2653
+ }
2654
+ static [entityKind] = "PgUpdate";
2655
+ config;
2656
+ tableName;
2657
+ joinsNotNullableMap;
2658
+ from(source) {
2659
+ const src = source;
2660
+ const tableName = getTableLikeName(src);
2661
+ if (typeof tableName === "string") {
2662
+ this.joinsNotNullableMap[tableName] = true;
2663
+ }
2664
+ this.config.from = src;
2665
+ return this;
2666
+ }
2667
+ getTableLikeFields(table) {
2668
+ if (is(table, PgTable)) {
2669
+ return table[Table.Symbol.Columns];
2670
+ } else if (is(table, Subquery)) {
2671
+ return table._.selectedFields;
2672
+ }
2673
+ return table[ViewBaseConfig].selectedFields;
2674
+ }
2675
+ createJoin(joinType) {
2676
+ return (table, on) => {
2677
+ const tableName = getTableLikeName(table);
2678
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
2679
+ throw new Error(`Alias "${tableName}" is already used in this query`);
2680
+ }
2681
+ if (typeof on === "function") {
2682
+ const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : undefined;
2683
+ on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
2684
+ }
2685
+ this.config.joins.push({ on, table, joinType, alias: tableName });
2686
+ if (typeof tableName === "string") {
2687
+ switch (joinType) {
2688
+ case "left": {
2689
+ this.joinsNotNullableMap[tableName] = false;
2690
+ break;
2691
+ }
2692
+ case "right": {
2693
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2694
+ this.joinsNotNullableMap[tableName] = true;
2695
+ break;
2696
+ }
2697
+ case "inner": {
2698
+ this.joinsNotNullableMap[tableName] = true;
2699
+ break;
2700
+ }
2701
+ case "full": {
2702
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
2703
+ this.joinsNotNullableMap[tableName] = false;
2704
+ break;
2705
+ }
2706
+ }
2707
+ }
2708
+ return this;
2709
+ };
2710
+ }
2711
+ leftJoin = this.createJoin("left");
2712
+ rightJoin = this.createJoin("right");
2713
+ innerJoin = this.createJoin("inner");
2714
+ fullJoin = this.createJoin("full");
2715
+ where(where) {
2716
+ this.config.where = where;
2717
+ return this;
2718
+ }
2719
+ returning(fields) {
2720
+ if (!fields) {
2721
+ fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
2722
+ if (this.config.from) {
2723
+ const tableName = getTableLikeName(this.config.from);
2724
+ if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
2725
+ const fromFields = this.getTableLikeFields(this.config.from);
2726
+ fields[tableName] = fromFields;
2727
+ }
2728
+ for (const join of this.config.joins) {
2729
+ const tableName2 = getTableLikeName(join.table);
2730
+ if (typeof tableName2 === "string" && !is(join.table, SQL)) {
2731
+ const fromFields = this.getTableLikeFields(join.table);
2732
+ fields[tableName2] = fromFields;
2733
+ }
2734
+ }
2735
+ }
2736
+ }
2737
+ this.config.returningFields = fields;
2738
+ this.config.returning = orderSelectedFields(fields);
2739
+ return this;
2740
+ }
2741
+ getSQL() {
2742
+ return this.dialect.buildUpdateQuery(this.config);
2743
+ }
2744
+ toSQL() {
2745
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2746
+ return rest;
2747
+ }
2748
+ _prepare(name) {
2749
+ const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
2750
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
2751
+ return query;
2752
+ }
2753
+ prepare(name) {
2754
+ return this._prepare(name);
2755
+ }
2756
+ authToken;
2757
+ setToken(token) {
2758
+ this.authToken = token;
2759
+ return this;
2760
+ }
2761
+ execute = (placeholderValues) => {
2762
+ return this._prepare().execute(placeholderValues, this.authToken);
2763
+ };
2764
+ getSelectedFields() {
2765
+ return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
2766
+ alias: getTableName(this.config.table),
2767
+ sqlAliasedBehavior: "alias",
2768
+ sqlBehavior: "error"
2769
+ })) : undefined;
2770
+ }
2771
+ $dynamic() {
2772
+ return this;
2773
+ }
2774
+ }
2775
+
2776
+ // node_modules/drizzle-orm/pg-core/query-builders/count.js
2777
+ class PgCountBuilder extends SQL {
2778
+ constructor(params) {
2779
+ super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
2780
+ this.params = params;
2781
+ this.mapWith(Number);
2782
+ this.session = params.session;
2783
+ this.sql = PgCountBuilder.buildCount(params.source, params.filters);
2784
+ }
2785
+ sql;
2786
+ token;
2787
+ static [entityKind] = "PgCountBuilder";
2788
+ [Symbol.toStringTag] = "PgCountBuilder";
2789
+ session;
2790
+ static buildEmbeddedCount(source, filters) {
2791
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
2792
+ }
2793
+ static buildCount(source, filters) {
2794
+ return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
2795
+ }
2796
+ setToken(token) {
2797
+ this.token = token;
2798
+ return this;
2799
+ }
2800
+ then(onfulfilled, onrejected) {
2801
+ return Promise.resolve(this.session.count(this.sql, this.token)).then(onfulfilled, onrejected);
2802
+ }
2803
+ catch(onRejected) {
2804
+ return this.then(undefined, onRejected);
2805
+ }
2806
+ finally(onFinally) {
2807
+ return this.then((value) => {
2808
+ onFinally?.();
2809
+ return value;
2810
+ }, (reason) => {
2811
+ onFinally?.();
2812
+ throw reason;
2813
+ });
2814
+ }
2815
+ }
2816
+
2817
+ // node_modules/drizzle-orm/pg-core/query-builders/query.js
2818
+ class RelationalQueryBuilder {
2819
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
2820
+ this.fullSchema = fullSchema;
2821
+ this.schema = schema;
2822
+ this.tableNamesMap = tableNamesMap;
2823
+ this.table = table;
2824
+ this.tableConfig = tableConfig;
2825
+ this.dialect = dialect;
2826
+ this.session = session;
2827
+ }
2828
+ static [entityKind] = "PgRelationalQueryBuilder";
2829
+ findMany(config) {
2830
+ return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
2831
+ }
2832
+ findFirst(config) {
2833
+ return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first");
2834
+ }
2835
+ }
2836
+
2837
+ class PgRelationalQuery extends QueryPromise {
2838
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
2839
+ super();
2840
+ this.fullSchema = fullSchema;
2841
+ this.schema = schema;
2842
+ this.tableNamesMap = tableNamesMap;
2843
+ this.table = table;
2844
+ this.tableConfig = tableConfig;
2845
+ this.dialect = dialect;
2846
+ this.session = session;
2847
+ this.config = config;
2848
+ this.mode = mode;
2849
+ }
2850
+ static [entityKind] = "PgRelationalQuery";
2851
+ _prepare(name) {
2852
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
2853
+ const { query, builtQuery } = this._toSQL();
2854
+ return this.session.prepareQuery(builtQuery, undefined, name, true, (rawRows, mapColumnValue) => {
2855
+ const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
2856
+ if (this.mode === "first") {
2857
+ return rows[0];
2858
+ }
2859
+ return rows;
2860
+ });
2861
+ });
2862
+ }
2863
+ prepare(name) {
2864
+ return this._prepare(name);
2865
+ }
2866
+ _getQuery() {
2867
+ return this.dialect.buildRelationalQueryWithoutPK({
2868
+ fullSchema: this.fullSchema,
2869
+ schema: this.schema,
2870
+ tableNamesMap: this.tableNamesMap,
2871
+ table: this.table,
2872
+ tableConfig: this.tableConfig,
2873
+ queryConfig: this.config,
2874
+ tableAlias: this.tableConfig.tsName
2875
+ });
2876
+ }
2877
+ getSQL() {
2878
+ return this._getQuery().sql;
2879
+ }
2880
+ _toSQL() {
2881
+ const query = this._getQuery();
2882
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
2883
+ return { query, builtQuery };
2884
+ }
2885
+ toSQL() {
2886
+ return this._toSQL().builtQuery;
2887
+ }
2888
+ authToken;
2889
+ setToken(token) {
2890
+ this.authToken = token;
2891
+ return this;
2892
+ }
2893
+ execute() {
2894
+ return tracer.startActiveSpan("drizzle.operation", () => {
2895
+ return this._prepare().execute(undefined, this.authToken);
2896
+ });
2897
+ }
2898
+ }
2899
+
2900
+ // node_modules/drizzle-orm/pg-core/query-builders/raw.js
2901
+ class PgRaw extends QueryPromise {
2902
+ constructor(execute, sql2, query, mapBatchResult) {
2903
+ super();
2904
+ this.execute = execute;
2905
+ this.sql = sql2;
2906
+ this.query = query;
2907
+ this.mapBatchResult = mapBatchResult;
2908
+ }
2909
+ static [entityKind] = "PgRaw";
2910
+ getSQL() {
2911
+ return this.sql;
2912
+ }
2913
+ getQuery() {
2914
+ return this.query;
2915
+ }
2916
+ mapResult(result, isFromBatch) {
2917
+ return isFromBatch ? this.mapBatchResult(result) : result;
2918
+ }
2919
+ _prepare() {
2920
+ return this;
2921
+ }
2922
+ isResponseInArrayMode() {
2923
+ return false;
2924
+ }
2925
+ }
2926
+
2927
+ // node_modules/drizzle-orm/pg-core/db.js
2928
+ class PgDatabase {
2929
+ constructor(dialect, session, schema) {
2930
+ this.dialect = dialect;
2931
+ this.session = session;
2932
+ this._ = schema ? {
2933
+ schema: schema.schema,
2934
+ fullSchema: schema.fullSchema,
2935
+ tableNamesMap: schema.tableNamesMap,
2936
+ session
2937
+ } : {
2938
+ schema: undefined,
2939
+ fullSchema: {},
2940
+ tableNamesMap: {},
2941
+ session
2942
+ };
2943
+ this.query = {};
2944
+ if (this._.schema) {
2945
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
2946
+ this.query[tableName] = new RelationalQueryBuilder(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
2947
+ }
2948
+ }
2949
+ }
2950
+ static [entityKind] = "PgDatabase";
2951
+ query;
2952
+ $with = (alias, selection) => {
2953
+ const self = this;
2954
+ const as = (qb) => {
2955
+ if (typeof qb === "function") {
2956
+ qb = qb(new QueryBuilder(self.dialect));
2957
+ }
2958
+ return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
2959
+ };
2960
+ return { as };
2961
+ };
2962
+ $count(source, filters) {
2963
+ return new PgCountBuilder({ source, filters, session: this.session });
2964
+ }
2965
+ with(...queries) {
2966
+ const self = this;
2967
+ function select(fields) {
2968
+ return new PgSelectBuilder({
2969
+ fields: fields ?? undefined,
2970
+ session: self.session,
2971
+ dialect: self.dialect,
2972
+ withList: queries
2973
+ });
2974
+ }
2975
+ function selectDistinct(fields) {
2976
+ return new PgSelectBuilder({
2977
+ fields: fields ?? undefined,
2978
+ session: self.session,
2979
+ dialect: self.dialect,
2980
+ withList: queries,
2981
+ distinct: true
2982
+ });
2983
+ }
2984
+ function selectDistinctOn(on, fields) {
2985
+ return new PgSelectBuilder({
2986
+ fields: fields ?? undefined,
2987
+ session: self.session,
2988
+ dialect: self.dialect,
2989
+ withList: queries,
2990
+ distinct: { on }
2991
+ });
2992
+ }
2993
+ function update(table) {
2994
+ return new PgUpdateBuilder(table, self.session, self.dialect, queries);
2995
+ }
2996
+ function insert(table) {
2997
+ return new PgInsertBuilder(table, self.session, self.dialect, queries);
2998
+ }
2999
+ function delete_(table) {
3000
+ return new PgDeleteBase(table, self.session, self.dialect, queries);
3001
+ }
3002
+ return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
3003
+ }
3004
+ select(fields) {
3005
+ return new PgSelectBuilder({
3006
+ fields: fields ?? undefined,
3007
+ session: this.session,
3008
+ dialect: this.dialect
3009
+ });
3010
+ }
3011
+ selectDistinct(fields) {
3012
+ return new PgSelectBuilder({
3013
+ fields: fields ?? undefined,
3014
+ session: this.session,
3015
+ dialect: this.dialect,
3016
+ distinct: true
3017
+ });
3018
+ }
3019
+ selectDistinctOn(on, fields) {
3020
+ return new PgSelectBuilder({
3021
+ fields: fields ?? undefined,
3022
+ session: this.session,
3023
+ dialect: this.dialect,
3024
+ distinct: { on }
3025
+ });
3026
+ }
3027
+ update(table) {
3028
+ return new PgUpdateBuilder(table, this.session, this.dialect);
3029
+ }
3030
+ insert(table) {
3031
+ return new PgInsertBuilder(table, this.session, this.dialect);
3032
+ }
3033
+ delete(table) {
3034
+ return new PgDeleteBase(table, this.session, this.dialect);
3035
+ }
3036
+ refreshMaterializedView(view) {
3037
+ return new PgRefreshMaterializedView(view, this.session, this.dialect);
3038
+ }
3039
+ authToken;
3040
+ execute(query) {
3041
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3042
+ const builtQuery = this.dialect.sqlToQuery(sequel);
3043
+ const prepared = this.session.prepareQuery(builtQuery, undefined, undefined, false);
3044
+ return new PgRaw(() => prepared.execute(undefined, this.authToken), sequel, builtQuery, (result) => prepared.mapResult(result, true));
3045
+ }
3046
+ transaction(transaction, config) {
3047
+ return this.session.transaction(transaction, config);
3048
+ }
3049
+ }
3050
+
3051
+ // node_modules/drizzle-orm/pg-core/session.js
3052
+ class PgPreparedQuery {
3053
+ constructor(query) {
3054
+ this.query = query;
3055
+ }
3056
+ authToken;
3057
+ getQuery() {
3058
+ return this.query;
3059
+ }
3060
+ mapResult(response, _isFromBatch) {
3061
+ return response;
3062
+ }
3063
+ setToken(token) {
3064
+ this.authToken = token;
3065
+ return this;
3066
+ }
3067
+ static [entityKind] = "PgPreparedQuery";
3068
+ joinsNotNullableMap;
3069
+ }
3070
+
3071
+ class PgSession {
3072
+ constructor(dialect) {
3073
+ this.dialect = dialect;
3074
+ }
3075
+ static [entityKind] = "PgSession";
3076
+ execute(query, token) {
3077
+ return tracer.startActiveSpan("drizzle.operation", () => {
3078
+ const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
3079
+ return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false);
3080
+ });
3081
+ return prepared.setToken(token).execute(undefined, token);
3082
+ });
3083
+ }
3084
+ all(query) {
3085
+ return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false).all();
3086
+ }
3087
+ async count(sql2, token) {
3088
+ const res = await this.execute(sql2, token);
3089
+ return Number(res[0]["count"]);
3090
+ }
3091
+ }
3092
+
3093
+ class PgTransaction extends PgDatabase {
3094
+ constructor(dialect, session, schema, nestedIndex = 0) {
3095
+ super(dialect, session, schema);
3096
+ this.schema = schema;
3097
+ this.nestedIndex = nestedIndex;
3098
+ }
3099
+ static [entityKind] = "PgTransaction";
3100
+ rollback() {
3101
+ throw new TransactionRollbackError;
3102
+ }
3103
+ getTransactionConfigSQL(config) {
3104
+ const chunks = [];
3105
+ if (config.isolationLevel) {
3106
+ chunks.push(`isolation level ${config.isolationLevel}`);
3107
+ }
3108
+ if (config.accessMode) {
3109
+ chunks.push(config.accessMode);
3110
+ }
3111
+ if (typeof config.deferrable === "boolean") {
3112
+ chunks.push(config.deferrable ? "deferrable" : "not deferrable");
3113
+ }
3114
+ return sql.raw(chunks.join(" "));
3115
+ }
3116
+ setTransaction(config) {
3117
+ return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
3118
+ }
3119
+ }
3120
+
3121
+ // src/utils.ts
3122
+ function mapResultRow(columns, row, joinsNotNullableMap) {
3123
+ const nullifyMap = {};
3124
+ const result = columns.reduce((result2, { path, field }, columnIndex) => {
3125
+ let decoder;
3126
+ if (is(field, Column)) {
3127
+ decoder = field;
3128
+ } else if (is(field, SQL)) {
3129
+ decoder = field.decoder;
3130
+ } else {
3131
+ decoder = field.sql.decoder;
3132
+ }
3133
+ let node = result2;
3134
+ for (const [pathChunkIndex, pathChunk] of path.entries()) {
3135
+ if (pathChunkIndex < path.length - 1) {
3136
+ if (!(pathChunk in node)) {
3137
+ node[pathChunk] = {};
3138
+ }
3139
+ node = node[pathChunk];
3140
+ continue;
3141
+ }
3142
+ const rawValue = row[columnIndex];
3143
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
3144
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
3145
+ const objectName = path[0];
3146
+ if (!(objectName in nullifyMap)) {
3147
+ nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
3148
+ } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
3149
+ nullifyMap[objectName] = false;
3150
+ }
3151
+ continue;
3152
+ }
3153
+ if (joinsNotNullableMap && is(field, SQL.Aliased) && path.length === 2) {
3154
+ const col = field.sql.queryChunks.find((chunk) => is(chunk, Column));
3155
+ const tableName = col?.table && getTableName(col?.table);
3156
+ if (!tableName) {
3157
+ continue;
3158
+ }
3159
+ const objectName = path[0];
3160
+ if (!(objectName in nullifyMap)) {
3161
+ nullifyMap[objectName] = value === null ? tableName : false;
3162
+ continue;
3163
+ }
3164
+ if (nullifyMap[objectName] && nullifyMap[objectName] !== tableName) {
3165
+ nullifyMap[objectName] = false;
3166
+ }
3167
+ continue;
3168
+ }
3169
+ }
3170
+ return result2;
3171
+ }, {});
3172
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
3173
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) {
3174
+ if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
3175
+ result[objectName] = null;
3176
+ }
3177
+ }
3178
+ }
3179
+ return result;
3180
+ }
3181
+ function aliasFields(fields, fullJoin = false) {
3182
+ return Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "enableRLS").map(([key, value]) => {
3183
+ if (fullJoin && is(value, Column)) {
3184
+ return [
3185
+ key,
3186
+ sql`${value}`.as(`${getTableName(value.table)}.${value.name}`)
3187
+ ];
3188
+ }
3189
+ if (fullJoin && is(value, SQL)) {
3190
+ const col = value.getSQL().queryChunks.find((chunk) => is(chunk, Column));
3191
+ const tableName = col?.table && getTableName(col?.table);
3192
+ return [key, value.as(tableName ? `${tableName}.${key}` : key)];
3193
+ }
3194
+ if (is(value, SQL) || is(value, Column)) {
3195
+ return [key, (is(value, SQL) ? value : sql`${value}`).as(key)];
3196
+ }
3197
+ if (is(value, SQL.Aliased)) {
3198
+ return [key, value];
3199
+ }
3200
+ if (typeof value === "object") {
3201
+ const parentKey = key;
3202
+ return [
3203
+ key,
3204
+ Object.fromEntries(Object.entries(value).filter(([childKey]) => childKey !== "enableRLS").map(([childKey, childValue]) => [
3205
+ childKey,
3206
+ (is(childValue, SQL) ? childValue : sql`${childValue}`).as(`${parentKey}.${childKey}`)
3207
+ ]))
3208
+ ];
3209
+ }
3210
+ return [key, value];
3211
+ }));
3212
+ }
3213
+ var tableIdPropSelectionRegex = new RegExp([
3214
+ `("(.+)"\\."(.+)")`,
3215
+ `(\\s+as\\s+'?(.+?)'?\\.'?(.+?)'?)?`
3216
+ ].join(""), "i");
3217
+
3218
+ // src/session.ts
3219
+ class DuckDBPreparedQuery extends PgPreparedQuery {
3220
+ client;
3221
+ queryString;
3222
+ params;
3223
+ logger;
3224
+ fields;
3225
+ _isResponseInArrayMode;
3226
+ customResultMapper;
3227
+ static [entityKind] = "DuckDBPreparedQuery";
3228
+ constructor(client, queryString, params, logger, fields, _isResponseInArrayMode, customResultMapper) {
3229
+ super({ sql: queryString, params });
3230
+ this.client = client;
3231
+ this.queryString = queryString;
3232
+ this.params = params;
3233
+ this.logger = logger;
3234
+ this.fields = fields;
3235
+ this._isResponseInArrayMode = _isResponseInArrayMode;
3236
+ this.customResultMapper = customResultMapper;
3237
+ }
3238
+ async execute(placeholderValues = {}) {
3239
+ const params = fillPlaceholders(this.params, placeholderValues);
3240
+ this.logger.logQuery(this.queryString, params);
3241
+ const {
3242
+ fields,
3243
+ client,
3244
+ joinsNotNullableMap,
3245
+ customResultMapper,
3246
+ queryString
3247
+ } = this;
3248
+ const rows = await client.all(queryString, ...params) ?? [];
3249
+ if (rows.length === 0 || !fields) {
3250
+ return rows;
3251
+ }
3252
+ const rowValues = rows.map((row) => Object.values(row));
3253
+ return customResultMapper ? customResultMapper(rowValues) : rowValues.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
3254
+ }
3255
+ all(placeholderValues = {}) {
3256
+ return this.execute(placeholderValues);
3257
+ }
3258
+ isResponseInArrayMode() {
3259
+ return false;
3260
+ }
3261
+ }
3262
+
3263
+ class DuckDBSession extends PgSession {
3264
+ client;
3265
+ schema;
3266
+ options;
3267
+ static [entityKind] = "DuckDBSession";
3268
+ logger;
3269
+ constructor(client, dialect, schema, options = {}) {
3270
+ super(dialect);
3271
+ this.client = client;
3272
+ this.schema = schema;
3273
+ this.options = options;
3274
+ this.logger = options.logger ?? new NoopLogger;
3275
+ }
3276
+ prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper) {
3277
+ return new DuckDBPreparedQuery(this.client, query.sql, query.params, this.logger, fields, isResponseInArrayMode, customResultMapper);
3278
+ }
3279
+ async transaction(transaction) {
3280
+ const connection = "connect" in this.client ? await this.client.connect() : this.client;
3281
+ const session = new DuckDBSession(connection, this.dialect, this.schema, this.options);
3282
+ const tx = new DuckDBTransaction(this.dialect, session, this.schema);
3283
+ await tx.execute(sql`BEGIN TRANSACTION;`);
3284
+ try {
3285
+ const result = await transaction(tx);
3286
+ await tx.execute(sql`commit`);
3287
+ return result;
3288
+ } catch (error) {
3289
+ await tx.execute(sql`rollback`);
3290
+ throw error;
3291
+ } finally {
3292
+ await connection.close();
3293
+ }
3294
+ }
3295
+ }
3296
+
3297
+ class DuckDBTransaction extends PgTransaction {
3298
+ static [entityKind] = "DuckDBTransaction";
3299
+ rollback() {
3300
+ throw new TransactionRollbackError;
3301
+ }
3302
+ getTransactionConfigSQL(config) {
3303
+ const chunks = [];
3304
+ if (config.isolationLevel) {
3305
+ chunks.push(`isolation level ${config.isolationLevel}`);
3306
+ }
3307
+ if (config.accessMode) {
3308
+ chunks.push(config.accessMode);
3309
+ }
3310
+ if (typeof config.deferrable === "boolean") {
3311
+ chunks.push(config.deferrable ? "deferrable" : "not deferrable");
3312
+ }
3313
+ return sql.raw(chunks.join(" "));
3314
+ }
3315
+ setTransaction(config) {
3316
+ return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
3317
+ }
3318
+ async transaction(transaction) {
3319
+ const savepointName = `sp${this.nestedIndex + 1}`;
3320
+ const tx = new DuckDBTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1);
3321
+ await tx.execute(sql.raw(`savepoint ${savepointName}`));
3322
+ try {
3323
+ const result = await transaction(tx);
3324
+ await tx.execute(sql.raw(`release savepoint ${savepointName}`));
3325
+ return result;
3326
+ } catch (err) {
3327
+ await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
3328
+ throw err;
3329
+ }
3330
+ }
3331
+ }
3332
+
3333
+ // src/dialect.ts
3334
+ class DuckDBDialect extends PgDialect {
3335
+ static [entityKind] = "DuckDBPgDialect";
3336
+ async migrate(migrations, session, config) {
3337
+ const migrationsSchema = config.migrationsSchema ?? "drizzle";
3338
+ const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
3339
+ const migrationTableCreate = sql`
3340
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
3341
+ id integer PRIMARY KEY default nextval('migrations_pk_seq'),
3342
+ hash text NOT NULL,
3343
+ created_at bigint
3344
+ )
3345
+ `;
3346
+ await session.execute(sql.raw("CREATE SEQUENCE IF NOT EXISTS migrations_pk_seq"));
3347
+ await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
3348
+ await session.execute(migrationTableCreate);
3349
+ const dbMigrations = await session.all(sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`);
3350
+ const lastDbMigration = dbMigrations[0];
3351
+ await session.transaction(async (tx) => {
3352
+ for await (const migration of migrations) {
3353
+ if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
3354
+ for (const stmt of migration.sql) {
3355
+ await tx.execute(sql.raw(stmt));
3356
+ }
3357
+ await tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`);
3358
+ }
3359
+ }
3360
+ });
3361
+ }
3362
+ prepareTyping(encoder) {
3363
+ if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
3364
+ throw new Error("JSON and JSONB types are not supported in DuckDB");
3365
+ } else if (is(encoder, PgNumeric)) {
3366
+ return "decimal";
3367
+ } else if (is(encoder, PgTime)) {
3368
+ return "time";
3369
+ } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
3370
+ return "timestamp";
3371
+ } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
3372
+ return "date";
3373
+ } else if (is(encoder, PgUUID)) {
3374
+ return "uuid";
3375
+ } else {
3376
+ return "none";
3377
+ }
3378
+ }
3379
+ }
3380
+
3381
+ // src/driver.ts
3382
+ class DuckDBDriver {
3383
+ client;
3384
+ dialect;
3385
+ options;
3386
+ static [entityKind] = "DuckDBDriver";
3387
+ constructor(client, dialect, options = {}) {
3388
+ this.client = client;
3389
+ this.dialect = dialect;
3390
+ this.options = options;
3391
+ }
3392
+ createSession(schema) {
3393
+ return new DuckDBSession(this.client, this.dialect, schema, {
3394
+ logger: this.options.logger
3395
+ });
3396
+ }
3397
+ }
3398
+ function drizzle(client, config = {}) {
3399
+ const dialect = new DuckDBDialect;
3400
+ const logger = config.logger === true ? new DefaultLogger : config.logger || undefined;
3401
+ let schema;
3402
+ if (config.schema) {
3403
+ const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
3404
+ schema = {
3405
+ fullSchema: config.schema,
3406
+ schema: tablesConfig.tables,
3407
+ tableNamesMap: tablesConfig.tableNamesMap
3408
+ };
3409
+ }
3410
+ const driver = new DuckDBDriver(client, dialect, { logger });
3411
+ const session = driver.createSession(schema);
3412
+ return new DuckDBDatabase(dialect, session, schema);
3413
+ }
3414
+
3415
+ class DuckDBDatabase extends PgDatabase {
3416
+ dialect;
3417
+ session;
3418
+ static [entityKind] = "DuckDBDatabase";
3419
+ constructor(dialect, session, schema) {
3420
+ super(dialect, session, schema);
3421
+ this.dialect = dialect;
3422
+ this.session = session;
3423
+ }
3424
+ select(fields) {
3425
+ if (!fields) {
3426
+ return new DuckDBSelectBuilder({
3427
+ fields: fields ?? undefined,
3428
+ session: this.session,
3429
+ dialect: this.dialect
3430
+ });
3431
+ }
3432
+ const aliasedFields = aliasFields(fields);
3433
+ return new DuckDBSelectBuilder({
3434
+ fields: aliasedFields,
3435
+ session: this.session,
3436
+ dialect: this.dialect
3437
+ });
3438
+ }
3439
+ async transaction(transaction) {
3440
+ return await this.session.transaction(transaction);
3441
+ }
3442
+ }
3443
+
3444
+ class DuckDBSelectBuilder extends PgSelectBuilder {
3445
+ _fields;
3446
+ _session;
3447
+ _dialect;
3448
+ _withList = [];
3449
+ _distinct;
3450
+ constructor(config) {
3451
+ super(config);
3452
+ this._fields = config.fields;
3453
+ this._session = config.session;
3454
+ this._dialect = config.dialect;
3455
+ if (config.withList) {
3456
+ this._withList = config.withList;
3457
+ }
3458
+ this._distinct = config.distinct;
3459
+ }
3460
+ from(source) {
3461
+ const isPartialSelect = !!this._fields;
3462
+ const src = source;
3463
+ let fields;
3464
+ if (this._fields) {
3465
+ fields = this._fields;
3466
+ } else if (is(src, Subquery)) {
3467
+ fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [
3468
+ key,
3469
+ src[key]
3470
+ ]));
3471
+ } else if (is(src, PgViewBase)) {
3472
+ fields = src[ViewBaseConfig]?.selectedFields;
3473
+ } else if (is(src, SQL)) {
3474
+ fields = {};
3475
+ } else {
3476
+ fields = aliasFields(getTableColumns(src), !isPartialSelect);
3477
+ }
3478
+ return new PgSelectBase({
3479
+ table: src,
3480
+ fields,
3481
+ isPartialSelect,
3482
+ session: this._session,
3483
+ dialect: this._dialect,
3484
+ withList: this._withList,
3485
+ distinct: this._distinct
3486
+ });
3487
+ }
3488
+ }
3489
+ export {
3490
+ drizzle,
3491
+ DuckDBTransaction,
3492
+ DuckDBSession,
3493
+ DuckDBSelectBuilder,
3494
+ DuckDBPreparedQuery,
3495
+ DuckDBDriver,
3496
+ DuckDBDatabase
3497
+ };