drizzle-databend 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/columns.d.ts +25 -37
  2. package/dist/databend-core/alias.d.ts +1 -0
  3. package/dist/databend-core/columns/all.d.ts +35 -0
  4. package/dist/databend-core/columns/array.d.ts +16 -0
  5. package/dist/databend-core/columns/bigint.d.ts +24 -0
  6. package/dist/databend-core/columns/binary.d.ts +13 -0
  7. package/dist/databend-core/columns/bitmap.d.ts +13 -0
  8. package/dist/databend-core/columns/boolean.d.ts +13 -0
  9. package/dist/databend-core/columns/common.d.ts +45 -0
  10. package/dist/databend-core/columns/custom.d.ts +33 -0
  11. package/dist/databend-core/columns/date.d.ts +16 -0
  12. package/dist/databend-core/columns/decimal.d.ts +19 -0
  13. package/dist/databend-core/columns/double.d.ts +14 -0
  14. package/dist/databend-core/columns/float.d.ts +14 -0
  15. package/dist/databend-core/columns/index.d.ts +21 -0
  16. package/dist/databend-core/columns/integer.d.ts +13 -0
  17. package/dist/databend-core/columns/map.d.ts +17 -0
  18. package/dist/databend-core/columns/smallint.d.ts +13 -0
  19. package/dist/databend-core/columns/text.d.ts +13 -0
  20. package/dist/databend-core/columns/timestamp.d.ts +16 -0
  21. package/dist/databend-core/columns/tinyint.d.ts +13 -0
  22. package/dist/databend-core/columns/tuple.d.ts +16 -0
  23. package/dist/databend-core/columns/varchar.d.ts +17 -0
  24. package/dist/databend-core/columns/variant.d.ts +15 -0
  25. package/dist/databend-core/db.d.ts +31 -0
  26. package/dist/databend-core/dialect.d.ts +29 -0
  27. package/dist/databend-core/index.d.ts +18 -0
  28. package/dist/databend-core/indexes.d.ts +24 -0
  29. package/dist/databend-core/primary-keys.d.ts +20 -0
  30. package/dist/databend-core/query-builders/count.d.ts +18 -0
  31. package/dist/databend-core/query-builders/delete.d.ts +18 -0
  32. package/dist/databend-core/query-builders/index.d.ts +5 -0
  33. package/dist/databend-core/query-builders/insert.d.ts +27 -0
  34. package/dist/databend-core/query-builders/query-builder.d.ts +19 -0
  35. package/dist/databend-core/query-builders/query.d.ts +37 -0
  36. package/dist/databend-core/query-builders/raw.d.ts +17 -0
  37. package/dist/databend-core/query-builders/select.d.ts +66 -0
  38. package/dist/databend-core/query-builders/update.d.ts +27 -0
  39. package/dist/databend-core/schema.d.ts +12 -0
  40. package/dist/databend-core/session.d.ts +28 -0
  41. package/dist/databend-core/subquery.d.ts +1 -0
  42. package/dist/databend-core/table.d.ts +12 -0
  43. package/dist/databend-core/utils.d.ts +7 -0
  44. package/dist/databend-core/view-base.d.ts +5 -0
  45. package/dist/databend-core/view-common.d.ts +1 -0
  46. package/dist/databend-core/view.d.ts +30 -0
  47. package/dist/dialect.d.ts +1 -10
  48. package/dist/driver.d.ts +4 -4
  49. package/dist/index.d.ts +10 -0
  50. package/dist/index.mjs +2611 -205
  51. package/dist/session.d.ts +22 -19
  52. package/dist/sql/result-mapper.d.ts +2 -3
  53. package/dist/sql/selection.d.ts +2 -1
  54. package/package.json +4 -4
  55. package/src/columns.ts +8 -7
  56. package/src/databend-core/alias.ts +5 -0
  57. package/src/databend-core/columns/all.ts +38 -0
  58. package/src/databend-core/columns/array.ts +46 -0
  59. package/src/databend-core/columns/bigint.ts +52 -0
  60. package/src/databend-core/columns/binary.ts +27 -0
  61. package/src/databend-core/columns/bitmap.ts +27 -0
  62. package/src/databend-core/columns/boolean.ts +27 -0
  63. package/src/databend-core/columns/common.ts +97 -0
  64. package/src/databend-core/columns/custom.ts +86 -0
  65. package/src/databend-core/columns/date.ts +49 -0
  66. package/src/databend-core/columns/decimal.ts +44 -0
  67. package/src/databend-core/columns/double.ts +34 -0
  68. package/src/databend-core/columns/float.ts +31 -0
  69. package/src/databend-core/columns/index.ts +21 -0
  70. package/src/databend-core/columns/integer.ts +27 -0
  71. package/src/databend-core/columns/map.ts +49 -0
  72. package/src/databend-core/columns/smallint.ts +27 -0
  73. package/src/databend-core/columns/text.ts +27 -0
  74. package/src/databend-core/columns/timestamp.ts +51 -0
  75. package/src/databend-core/columns/tinyint.ts +27 -0
  76. package/src/databend-core/columns/tuple.ts +46 -0
  77. package/src/databend-core/columns/varchar.ts +35 -0
  78. package/src/databend-core/columns/variant.ts +45 -0
  79. package/src/databend-core/db.ts +153 -0
  80. package/src/databend-core/dialect.ts +725 -0
  81. package/src/databend-core/index.ts +18 -0
  82. package/src/databend-core/indexes.ts +67 -0
  83. package/src/databend-core/primary-keys.ts +48 -0
  84. package/src/databend-core/query-builders/count.ts +47 -0
  85. package/src/databend-core/query-builders/delete.ts +56 -0
  86. package/src/databend-core/query-builders/index.ts +5 -0
  87. package/src/databend-core/query-builders/insert.ts +105 -0
  88. package/src/databend-core/query-builders/query-builder.ts +77 -0
  89. package/src/databend-core/query-builders/query.ts +124 -0
  90. package/src/databend-core/query-builders/raw.ts +37 -0
  91. package/src/databend-core/query-builders/select.ts +412 -0
  92. package/src/databend-core/query-builders/update.ts +82 -0
  93. package/src/databend-core/schema.ts +29 -0
  94. package/src/databend-core/session.ts +85 -0
  95. package/src/databend-core/subquery.ts +1 -0
  96. package/src/databend-core/table.ts +67 -0
  97. package/src/databend-core/utils.ts +34 -0
  98. package/src/databend-core/view-base.ts +6 -0
  99. package/src/databend-core/view-common.ts +1 -0
  100. package/src/databend-core/view.ts +127 -0
  101. package/src/dialect.ts +3 -119
  102. package/src/driver.ts +6 -7
  103. package/src/index.ts +27 -0
  104. package/src/migrator.ts +1 -2
  105. package/src/session.ts +42 -57
  106. package/src/sql/result-mapper.ts +12 -54
  107. package/src/sql/selection.ts +2 -1
package/dist/index.mjs CHANGED
@@ -125,8 +125,140 @@ async function closeClientConnection(connection) {
125
125
  }
126
126
  }
127
127
 
128
+ // src/databend-core/columns/custom.ts
129
+ import { entityKind as entityKind2 } from "drizzle-orm/entity";
130
+
131
+ // src/databend-core/columns/common.ts
132
+ import { Column } from "drizzle-orm/column";
133
+ import { ColumnBuilder } from "drizzle-orm/column-builder";
134
+ import { entityKind } from "drizzle-orm/entity";
135
+ var DatabendColumnBuilder = class extends ColumnBuilder {
136
+ static [entityKind] = "DatabendColumnBuilder";
137
+ generatedAlwaysAs(as, _config) {
138
+ this.config.generated = { as, type: "always", mode: "stored" };
139
+ return this;
140
+ }
141
+ unique(name, config) {
142
+ this.config.isUnique = true;
143
+ this.config.uniqueName = name;
144
+ this.config.uniqueType = config?.nulls;
145
+ return this;
146
+ }
147
+ /** @internal */
148
+ buildForeignKeys(_column, _table) {
149
+ return [];
150
+ }
151
+ /** @internal */
152
+ buildExtraConfigColumn(table) {
153
+ return new DatabendExtraConfigColumn(table, this.config);
154
+ }
155
+ };
156
+ var DatabendColumn = class extends Column {
157
+ static [entityKind] = "DatabendColumn";
158
+ constructor(table, config) {
159
+ super(table, config);
160
+ }
161
+ getSQLType() {
162
+ return "";
163
+ }
164
+ };
165
+ var DatabendExtraConfigColumn = class extends DatabendColumn {
166
+ static [entityKind] = "DatabendExtraConfigColumn";
167
+ getSQLType() {
168
+ return this.getSQLType();
169
+ }
170
+ indexConfig = {
171
+ order: this.config.order ?? "asc",
172
+ nulls: this.config.nulls ?? "last",
173
+ opClass: this.config.opClass
174
+ };
175
+ defaultConfig = {
176
+ order: "asc",
177
+ nulls: "last",
178
+ opClass: void 0
179
+ };
180
+ asc() {
181
+ this.indexConfig.order = "asc";
182
+ return this;
183
+ }
184
+ desc() {
185
+ this.indexConfig.order = "desc";
186
+ return this;
187
+ }
188
+ nullsFirst() {
189
+ this.indexConfig.nulls = "first";
190
+ return this;
191
+ }
192
+ nullsLast() {
193
+ this.indexConfig.nulls = "last";
194
+ return this;
195
+ }
196
+ };
197
+ var IndexedColumn = class {
198
+ static [entityKind] = "IndexedColumn";
199
+ name;
200
+ keyAsName;
201
+ type;
202
+ indexConfig;
203
+ constructor(name, keyAsName, type, indexConfig) {
204
+ this.name = name;
205
+ this.keyAsName = keyAsName;
206
+ this.type = type;
207
+ this.indexConfig = indexConfig;
208
+ }
209
+ };
210
+
211
+ // src/databend-core/columns/custom.ts
212
+ var DatabendCustomColumnBuilder = class extends DatabendColumnBuilder {
213
+ static [entityKind2] = "DatabendCustomColumnBuilder";
214
+ sqlDataType;
215
+ mapTo;
216
+ mapFrom;
217
+ constructor(name, fieldConfig, customTypeParams) {
218
+ super(name, "custom", "DatabendCustomColumn");
219
+ this.sqlDataType = customTypeParams.dataType(fieldConfig);
220
+ this.mapTo = customTypeParams.toDriver;
221
+ this.mapFrom = customTypeParams.fromDriver;
222
+ }
223
+ /** @internal */
224
+ build(table) {
225
+ return new DatabendCustomColumn(
226
+ table,
227
+ this.config,
228
+ this.sqlDataType,
229
+ this.mapTo,
230
+ this.mapFrom
231
+ );
232
+ }
233
+ };
234
+ var DatabendCustomColumn = class extends DatabendColumn {
235
+ static [entityKind2] = "DatabendCustomColumn";
236
+ sqlDataType;
237
+ mapTo;
238
+ mapFrom;
239
+ constructor(table, config, sqlDataType, mapTo, mapFrom) {
240
+ super(table, config);
241
+ this.sqlDataType = sqlDataType;
242
+ this.mapTo = mapTo;
243
+ this.mapFrom = mapFrom;
244
+ }
245
+ getSQLType() {
246
+ return this.sqlDataType;
247
+ }
248
+ mapFromDriverValue(value) {
249
+ return this.mapFrom ? this.mapFrom(value) : value;
250
+ }
251
+ mapToDriverValue(value) {
252
+ return this.mapTo ? this.mapTo(value) : value;
253
+ }
254
+ };
255
+ function customType(customTypeParams) {
256
+ return (dbName, fieldConfig) => {
257
+ return new DatabendCustomColumnBuilder(dbName, fieldConfig, customTypeParams);
258
+ };
259
+ }
260
+
128
261
  // src/columns.ts
129
- import { customType } from "drizzle-orm/pg-core";
130
262
  var databendVariant = (name) => customType({
131
263
  dataType() {
132
264
  return "VARIANT";
@@ -221,118 +353,2358 @@ var databendTimestamp = (name) => customType({
221
353
  const normalized = hasOffset ? str.replace(" ", "T") : `${str.replace(" ", "T")}Z`;
222
354
  return new Date(normalized);
223
355
  }
224
- })(name);
225
- var databendDate = (name) => customType({
226
- dataType() {
227
- return "DATE";
228
- },
229
- toDriver(value) {
230
- if (value instanceof Date) {
231
- return value.toISOString().slice(0, 10);
232
- }
233
- return value;
234
- },
235
- fromDriver(value) {
236
- if (value instanceof Date) {
237
- return value.toISOString().slice(0, 10);
356
+ })(name);
357
+ var databendDate = (name) => customType({
358
+ dataType() {
359
+ return "DATE";
360
+ },
361
+ toDriver(value) {
362
+ if (value instanceof Date) {
363
+ return value.toISOString().slice(0, 10);
364
+ }
365
+ return value;
366
+ },
367
+ fromDriver(value) {
368
+ if (value instanceof Date) {
369
+ return value.toISOString().slice(0, 10);
370
+ }
371
+ return value.slice(0, 10);
372
+ }
373
+ })(name);
374
+
375
+ // src/databend-core/alias.ts
376
+ import { TableAliasProxyHandler } from "drizzle-orm/alias";
377
+ function alias(table, alias2) {
378
+ return new Proxy(table, new TableAliasProxyHandler(alias2, false));
379
+ }
380
+
381
+ // src/databend-core/columns/bigint.ts
382
+ import { entityKind as entityKind3 } from "drizzle-orm/entity";
383
+ var DatabendBigInt53Builder = class extends DatabendColumnBuilder {
384
+ static [entityKind3] = "DatabendBigInt53Builder";
385
+ constructor(name) {
386
+ super(name, "number", "DatabendBigInt53");
387
+ }
388
+ /** @internal */
389
+ build(table) {
390
+ return new DatabendBigInt53(table, this.config);
391
+ }
392
+ };
393
+ var DatabendBigInt53 = class extends DatabendColumn {
394
+ static [entityKind3] = "DatabendBigInt53";
395
+ getSQLType() {
396
+ return "bigint";
397
+ }
398
+ };
399
+ var DatabendBigInt64Builder = class extends DatabendColumnBuilder {
400
+ static [entityKind3] = "DatabendBigInt64Builder";
401
+ constructor(name) {
402
+ super(name, "bigint", "DatabendBigInt64");
403
+ }
404
+ /** @internal */
405
+ build(table) {
406
+ return new DatabendBigInt64(table, this.config);
407
+ }
408
+ };
409
+ var DatabendBigInt64 = class extends DatabendColumn {
410
+ static [entityKind3] = "DatabendBigInt64";
411
+ getSQLType() {
412
+ return "bigint";
413
+ }
414
+ mapFromDriverValue(value) {
415
+ return BigInt(value);
416
+ }
417
+ };
418
+ function bigint(name) {
419
+ return new DatabendBigInt53Builder(name ?? "");
420
+ }
421
+
422
+ // src/databend-core/columns/binary.ts
423
+ import { entityKind as entityKind4 } from "drizzle-orm/entity";
424
+ var DatabendBinaryBuilder = class extends DatabendColumnBuilder {
425
+ static [entityKind4] = "DatabendBinaryBuilder";
426
+ constructor(name) {
427
+ super(name, "string", "DatabendBinary");
428
+ }
429
+ /** @internal */
430
+ build(table) {
431
+ return new DatabendBinary(table, this.config);
432
+ }
433
+ };
434
+ var DatabendBinary = class extends DatabendColumn {
435
+ static [entityKind4] = "DatabendBinary";
436
+ getSQLType() {
437
+ return "binary";
438
+ }
439
+ };
440
+ function binary(name) {
441
+ return new DatabendBinaryBuilder(name ?? "");
442
+ }
443
+
444
+ // src/databend-core/columns/bitmap.ts
445
+ import { entityKind as entityKind5 } from "drizzle-orm/entity";
446
+ var DatabendBitmapBuilder = class extends DatabendColumnBuilder {
447
+ static [entityKind5] = "DatabendBitmapBuilder";
448
+ constructor(name) {
449
+ super(name, "string", "DatabendBitmap");
450
+ }
451
+ /** @internal */
452
+ build(table) {
453
+ return new DatabendBitmap(table, this.config);
454
+ }
455
+ };
456
+ var DatabendBitmap = class extends DatabendColumn {
457
+ static [entityKind5] = "DatabendBitmap";
458
+ getSQLType() {
459
+ return "bitmap";
460
+ }
461
+ };
462
+ function bitmap(name) {
463
+ return new DatabendBitmapBuilder(name ?? "");
464
+ }
465
+
466
+ // src/databend-core/columns/boolean.ts
467
+ import { entityKind as entityKind6 } from "drizzle-orm/entity";
468
+ var DatabendBooleanBuilder = class extends DatabendColumnBuilder {
469
+ static [entityKind6] = "DatabendBooleanBuilder";
470
+ constructor(name) {
471
+ super(name, "boolean", "DatabendBoolean");
472
+ }
473
+ /** @internal */
474
+ build(table) {
475
+ return new DatabendBoolean(table, this.config);
476
+ }
477
+ };
478
+ var DatabendBoolean = class extends DatabendColumn {
479
+ static [entityKind6] = "DatabendBoolean";
480
+ getSQLType() {
481
+ return "boolean";
482
+ }
483
+ };
484
+ function boolean(name) {
485
+ return new DatabendBooleanBuilder(name ?? "");
486
+ }
487
+
488
+ // src/databend-core/columns/date.ts
489
+ import { entityKind as entityKind7 } from "drizzle-orm/entity";
490
+ import { sql } from "drizzle-orm/sql/sql";
491
+ var DatabendDateBuilder = class extends DatabendColumnBuilder {
492
+ static [entityKind7] = "DatabendDateBuilder";
493
+ constructor(name) {
494
+ super(name, "string", "DatabendDate");
495
+ }
496
+ defaultNow() {
497
+ return this.default(sql`now()`);
498
+ }
499
+ /** @internal */
500
+ build(table) {
501
+ return new DatabendDate(table, this.config);
502
+ }
503
+ };
504
+ var DatabendDate = class extends DatabendColumn {
505
+ static [entityKind7] = "DatabendDate";
506
+ getSQLType() {
507
+ return "date";
508
+ }
509
+ mapFromDriverValue(value) {
510
+ if (value instanceof Date) {
511
+ return value.toISOString().slice(0, 10);
512
+ }
513
+ if (typeof value === "string") {
514
+ return value.slice(0, 10);
515
+ }
516
+ return value;
517
+ }
518
+ mapToDriverValue(value) {
519
+ if (value instanceof Date) {
520
+ return value.toISOString().slice(0, 10);
521
+ }
522
+ return value;
523
+ }
524
+ };
525
+ function date(name) {
526
+ return new DatabendDateBuilder(name ?? "");
527
+ }
528
+
529
+ // src/databend-core/columns/decimal.ts
530
+ import { entityKind as entityKind8 } from "drizzle-orm/entity";
531
+ var DatabendDecimalBuilder = class extends DatabendColumnBuilder {
532
+ static [entityKind8] = "DatabendDecimalBuilder";
533
+ constructor(name, precision, scale) {
534
+ super(name, "string", "DatabendDecimal");
535
+ this.config.precision = precision;
536
+ this.config.scale = scale;
537
+ }
538
+ /** @internal */
539
+ build(table) {
540
+ return new DatabendDecimal(table, this.config);
541
+ }
542
+ };
543
+ var DatabendDecimal = class extends DatabendColumn {
544
+ static [entityKind8] = "DatabendDecimal";
545
+ precision;
546
+ scale;
547
+ constructor(table, config) {
548
+ super(table, config);
549
+ this.precision = config.precision;
550
+ this.scale = config.scale;
551
+ }
552
+ getSQLType() {
553
+ if (this.precision !== void 0 && this.scale !== void 0) {
554
+ return `decimal(${this.precision}, ${this.scale})`;
555
+ }
556
+ if (this.precision !== void 0) {
557
+ return `decimal(${this.precision})`;
558
+ }
559
+ return "decimal";
560
+ }
561
+ };
562
+ function decimal(name, config) {
563
+ return new DatabendDecimalBuilder(name ?? "", config?.precision, config?.scale);
564
+ }
565
+
566
+ // src/databend-core/columns/double.ts
567
+ import { entityKind as entityKind9 } from "drizzle-orm/entity";
568
+ var DatabendDoublePrecisionBuilder = class extends DatabendColumnBuilder {
569
+ static [entityKind9] = "DatabendDoublePrecisionBuilder";
570
+ constructor(name) {
571
+ super(name, "number", "DatabendDoublePrecision");
572
+ }
573
+ /** @internal */
574
+ build(table) {
575
+ return new DatabendDoublePrecision(table, this.config);
576
+ }
577
+ };
578
+ var DatabendDoublePrecision = class extends DatabendColumn {
579
+ static [entityKind9] = "DatabendDoublePrecision";
580
+ getSQLType() {
581
+ return "double";
582
+ }
583
+ mapFromDriverValue(value) {
584
+ if (typeof value === "string") {
585
+ return Number.parseFloat(value);
586
+ }
587
+ return value;
588
+ }
589
+ };
590
+ function doublePrecision(name) {
591
+ return new DatabendDoublePrecisionBuilder(name ?? "");
592
+ }
593
+
594
+ // src/databend-core/columns/float.ts
595
+ import { entityKind as entityKind10 } from "drizzle-orm/entity";
596
+ var DatabendRealBuilder = class extends DatabendColumnBuilder {
597
+ static [entityKind10] = "DatabendRealBuilder";
598
+ constructor(name) {
599
+ super(name, "number", "DatabendReal");
600
+ }
601
+ /** @internal */
602
+ build(table) {
603
+ return new DatabendReal(table, this.config);
604
+ }
605
+ };
606
+ var DatabendReal = class extends DatabendColumn {
607
+ static [entityKind10] = "DatabendReal";
608
+ getSQLType() {
609
+ return "real";
610
+ }
611
+ };
612
+ function real(name) {
613
+ return new DatabendRealBuilder(name ?? "");
614
+ }
615
+ function float(name) {
616
+ return new DatabendRealBuilder(name ?? "");
617
+ }
618
+
619
+ // src/databend-core/columns/integer.ts
620
+ import { entityKind as entityKind11 } from "drizzle-orm/entity";
621
+ var DatabendIntegerBuilder = class extends DatabendColumnBuilder {
622
+ static [entityKind11] = "DatabendIntegerBuilder";
623
+ constructor(name) {
624
+ super(name, "number", "DatabendInteger");
625
+ }
626
+ /** @internal */
627
+ build(table) {
628
+ return new DatabendInteger(table, this.config);
629
+ }
630
+ };
631
+ var DatabendInteger = class extends DatabendColumn {
632
+ static [entityKind11] = "DatabendInteger";
633
+ getSQLType() {
634
+ return "integer";
635
+ }
636
+ };
637
+ function integer(name) {
638
+ return new DatabendIntegerBuilder(name ?? "");
639
+ }
640
+
641
+ // src/databend-core/columns/smallint.ts
642
+ import { entityKind as entityKind12 } from "drizzle-orm/entity";
643
+ var DatabendSmallIntBuilder = class extends DatabendColumnBuilder {
644
+ static [entityKind12] = "DatabendSmallIntBuilder";
645
+ constructor(name) {
646
+ super(name, "number", "DatabendSmallInt");
647
+ }
648
+ /** @internal */
649
+ build(table) {
650
+ return new DatabendSmallInt(table, this.config);
651
+ }
652
+ };
653
+ var DatabendSmallInt = class extends DatabendColumn {
654
+ static [entityKind12] = "DatabendSmallInt";
655
+ getSQLType() {
656
+ return "smallint";
657
+ }
658
+ };
659
+ function smallint(name) {
660
+ return new DatabendSmallIntBuilder(name ?? "");
661
+ }
662
+
663
+ // src/databend-core/columns/text.ts
664
+ import { entityKind as entityKind13 } from "drizzle-orm/entity";
665
+ var DatabendTextBuilder = class extends DatabendColumnBuilder {
666
+ static [entityKind13] = "DatabendTextBuilder";
667
+ constructor(name) {
668
+ super(name, "string", "DatabendText");
669
+ }
670
+ /** @internal */
671
+ build(table) {
672
+ return new DatabendText(table, this.config);
673
+ }
674
+ };
675
+ var DatabendText = class extends DatabendColumn {
676
+ static [entityKind13] = "DatabendText";
677
+ getSQLType() {
678
+ return "text";
679
+ }
680
+ };
681
+ function text(name) {
682
+ return new DatabendTextBuilder(name ?? "");
683
+ }
684
+
685
+ // src/databend-core/columns/timestamp.ts
686
+ import { entityKind as entityKind14 } from "drizzle-orm/entity";
687
+ import { sql as sql2 } from "drizzle-orm/sql/sql";
688
+ var DatabendTimestampBuilder = class extends DatabendColumnBuilder {
689
+ static [entityKind14] = "DatabendTimestampBuilder";
690
+ constructor(name) {
691
+ super(name, "date", "DatabendTimestamp");
692
+ }
693
+ defaultNow() {
694
+ return this.default(sql2`now()`);
695
+ }
696
+ /** @internal */
697
+ build(table) {
698
+ return new DatabendTimestamp(table, this.config);
699
+ }
700
+ };
701
+ var DatabendTimestamp = class extends DatabendColumn {
702
+ static [entityKind14] = "DatabendTimestamp";
703
+ getSQLType() {
704
+ return "timestamp";
705
+ }
706
+ mapFromDriverValue(value) {
707
+ if (value instanceof Date) {
708
+ return value;
709
+ }
710
+ const str = String(value);
711
+ const hasOffset = str.endsWith("Z") || /[+-]\d{2}:?\d{2}$/.test(str);
712
+ const normalized = hasOffset ? str.replace(" ", "T") : `${str.replace(" ", "T")}Z`;
713
+ return new Date(normalized);
714
+ }
715
+ mapToDriverValue(value) {
716
+ if (value instanceof Date) {
717
+ return value.toISOString();
718
+ }
719
+ return value;
720
+ }
721
+ };
722
+ function timestamp(name) {
723
+ return new DatabendTimestampBuilder(name ?? "");
724
+ }
725
+
726
+ // src/databend-core/columns/tinyint.ts
727
+ import { entityKind as entityKind15 } from "drizzle-orm/entity";
728
+ var DatabendTinyIntBuilder = class extends DatabendColumnBuilder {
729
+ static [entityKind15] = "DatabendTinyIntBuilder";
730
+ constructor(name) {
731
+ super(name, "number", "DatabendTinyInt");
732
+ }
733
+ /** @internal */
734
+ build(table) {
735
+ return new DatabendTinyInt(table, this.config);
736
+ }
737
+ };
738
+ var DatabendTinyInt = class extends DatabendColumn {
739
+ static [entityKind15] = "DatabendTinyInt";
740
+ getSQLType() {
741
+ return "tinyint";
742
+ }
743
+ };
744
+ function tinyint(name) {
745
+ return new DatabendTinyIntBuilder(name ?? "");
746
+ }
747
+
748
+ // src/databend-core/columns/varchar.ts
749
+ import { entityKind as entityKind16 } from "drizzle-orm/entity";
750
+ var DatabendVarcharBuilder = class extends DatabendColumnBuilder {
751
+ static [entityKind16] = "DatabendVarcharBuilder";
752
+ constructor(name, length) {
753
+ super(name, "string", "DatabendVarchar");
754
+ this.config.length = length;
755
+ }
756
+ /** @internal */
757
+ build(table) {
758
+ return new DatabendVarchar(table, this.config);
759
+ }
760
+ };
761
+ var DatabendVarchar = class extends DatabendColumn {
762
+ static [entityKind16] = "DatabendVarchar";
763
+ length;
764
+ constructor(table, config) {
765
+ super(table, config);
766
+ this.length = config.length;
767
+ }
768
+ getSQLType() {
769
+ return this.length ? `varchar(${this.length})` : "varchar";
770
+ }
771
+ };
772
+ function varchar(name, config) {
773
+ return new DatabendVarcharBuilder(name ?? "", config?.length);
774
+ }
775
+
776
+ // src/databend-core/columns/variant.ts
777
+ import { entityKind as entityKind17 } from "drizzle-orm/entity";
778
+ var DatabendVariantBuilder = class extends DatabendColumnBuilder {
779
+ static [entityKind17] = "DatabendVariantBuilder";
780
+ constructor(name) {
781
+ super(name, "json", "DatabendVariant");
782
+ }
783
+ /** @internal */
784
+ build(table) {
785
+ return new DatabendVariant(table, this.config);
786
+ }
787
+ };
788
+ var DatabendVariant = class extends DatabendColumn {
789
+ static [entityKind17] = "DatabendVariant";
790
+ getSQLType() {
791
+ return "variant";
792
+ }
793
+ mapFromDriverValue(value) {
794
+ if (typeof value === "string") {
795
+ try {
796
+ return JSON.parse(value);
797
+ } catch {
798
+ return value;
799
+ }
800
+ }
801
+ return value;
802
+ }
803
+ mapToDriverValue(value) {
804
+ if (typeof value === "string") {
805
+ return value;
806
+ }
807
+ return JSON.stringify(value);
808
+ }
809
+ };
810
+ function variant(name) {
811
+ return new DatabendVariantBuilder(name ?? "");
812
+ }
813
+
814
+ // src/databend-core/columns/all.ts
815
+ function getDatabendColumnBuilders() {
816
+ return {
817
+ bigint,
818
+ binary,
819
+ bitmap,
820
+ boolean,
821
+ customType,
822
+ date,
823
+ decimal,
824
+ doublePrecision,
825
+ float,
826
+ integer,
827
+ real,
828
+ smallint,
829
+ text,
830
+ timestamp,
831
+ tinyint,
832
+ varchar,
833
+ variant
834
+ };
835
+ }
836
+
837
+ // src/databend-core/dialect.ts
838
+ import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from "drizzle-orm/alias";
839
+ import { CasingCache } from "drizzle-orm/casing";
840
+ import { Column as Column2 } from "drizzle-orm/column";
841
+ import { entityKind as entityKind20, is } from "drizzle-orm/entity";
842
+ import { DrizzleError } from "drizzle-orm/errors";
843
+ import {
844
+ getOperators,
845
+ getOrderByOperators,
846
+ Many,
847
+ normalizeRelation,
848
+ One
849
+ } from "drizzle-orm/relations";
850
+ import { and, eq, View as View2 } from "drizzle-orm/sql";
851
+ import { Param, SQL, sql as sql3 } from "drizzle-orm/sql/sql";
852
+ import { Subquery } from "drizzle-orm/subquery";
853
+ import { getTableName, getTableUniqueName, Table as Table2 } from "drizzle-orm/table";
854
+ import { orderSelectedFields } from "drizzle-orm/utils";
855
+ import { ViewBaseConfig } from "drizzle-orm/view-common";
856
+
857
+ // src/databend-core/table.ts
858
+ import { entityKind as entityKind18 } from "drizzle-orm/entity";
859
+ import { Table } from "drizzle-orm/table";
860
+ var DatabendTable = class extends Table {
861
+ static [entityKind18] = "DatabendTable";
862
+ /** @internal */
863
+ static Symbol = Object.assign({}, Table.Symbol, {});
864
+ constructor(name, schema, baseName) {
865
+ super(name, schema, baseName);
866
+ this[Table.Symbol.ExtraConfigBuilder] = void 0;
867
+ this[Table.Symbol.ExtraConfigColumns] = {};
868
+ }
869
+ };
870
+ function databendTableWithSchema(name, columns, extraConfig, schema, baseName = name) {
871
+ const rawTable = new DatabendTable(name, schema, baseName);
872
+ const parsedColumns = typeof columns === "function" ? columns(getDatabendColumnBuilders()) : columns;
873
+ const builtColumns = Object.fromEntries(
874
+ Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
875
+ const colBuilder = colBuilderBase;
876
+ colBuilder.setName(name2);
877
+ const column = colBuilder.build(rawTable);
878
+ return [name2, column];
879
+ })
880
+ );
881
+ const builtColumnsForExtraConfig = Object.fromEntries(
882
+ Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
883
+ const colBuilder = colBuilderBase;
884
+ colBuilder.setName(name2);
885
+ const column = colBuilder.buildExtraConfigColumn(rawTable);
886
+ return [name2, column];
887
+ })
888
+ );
889
+ const table = Object.assign(rawTable, builtColumns);
890
+ table[Table.Symbol.Columns] = builtColumns;
891
+ table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
892
+ if (extraConfig) {
893
+ table[DatabendTable.Symbol.ExtraConfigBuilder] = extraConfig;
894
+ }
895
+ return table;
896
+ }
897
+ var databendTable = (name, columns, extraConfig) => {
898
+ return databendTableWithSchema(name, columns, extraConfig, void 0);
899
+ };
900
+ function databendTableCreator(customizeTableName) {
901
+ return (name, columns, extraConfig) => {
902
+ return databendTableWithSchema(customizeTableName(name), columns, extraConfig, void 0, name);
903
+ };
904
+ }
905
+
906
+ // src/databend-core/view-base.ts
907
+ import { entityKind as entityKind19 } from "drizzle-orm/entity";
908
+ import { View } from "drizzle-orm/sql/sql";
909
+ var DatabendViewBase = class extends View {
910
+ static [entityKind19] = "DatabendViewBase";
911
+ };
912
+
913
+ // src/databend-core/dialect.ts
914
+ var DatabendDialect = class {
915
+ static [entityKind20] = "DatabendDialect";
916
+ /** @internal */
917
+ casing;
918
+ constructor(config) {
919
+ this.casing = new CasingCache(config?.casing);
920
+ }
921
+ async migrate(migrations, session, config) {
922
+ const migrationConfig = typeof config === "string" ? { migrationsFolder: config } : config;
923
+ const migrationsSchema = migrationConfig.migrationsSchema ?? "default";
924
+ const migrationsTable = migrationConfig.migrationsTable ?? "__drizzle_migrations";
925
+ const migrationTableCreate = sql3`
926
+ CREATE TABLE IF NOT EXISTS ${sql3.identifier(migrationsSchema)}.${sql3.identifier(
927
+ migrationsTable
928
+ )} (
929
+ id INT NOT NULL,
930
+ hash VARCHAR NOT NULL,
931
+ created_at BIGINT
932
+ )
933
+ `;
934
+ await session.execute(migrationTableCreate);
935
+ const dbMigrations = await session.all(
936
+ sql3`SELECT id, hash, created_at FROM ${sql3.identifier(
937
+ migrationsSchema
938
+ )}.${sql3.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
939
+ );
940
+ const lastDbMigration = dbMigrations[0];
941
+ await session.transaction(async (tx) => {
942
+ for await (const migration of migrations) {
943
+ if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
944
+ for (const stmt of migration.sql) {
945
+ await tx.execute(sql3.raw(stmt));
946
+ }
947
+ await tx.execute(
948
+ sql3`INSERT INTO ${sql3.identifier(
949
+ migrationsSchema
950
+ )}.${sql3.identifier(migrationsTable)} (id, hash, created_at)
951
+ VALUES (
952
+ (SELECT COALESCE(MAX(id), 0) + 1 FROM ${sql3.identifier(
953
+ migrationsSchema
954
+ )}.${sql3.identifier(migrationsTable)}),
955
+ ${migration.hash},
956
+ ${migration.folderMillis}
957
+ )`
958
+ );
959
+ }
960
+ }
961
+ });
962
+ }
963
+ escapeName(name) {
964
+ return `"${name}"`;
965
+ }
966
+ escapeParam(num) {
967
+ return `$${num + 1}`;
968
+ }
969
+ escapeString(str) {
970
+ return `'${str.replace(/'/g, "''")}'`;
971
+ }
972
+ buildWithCTE(queries) {
973
+ if (!queries?.length) return void 0;
974
+ const withSqlChunks = [sql3`with `];
975
+ for (const [i, w] of queries.entries()) {
976
+ withSqlChunks.push(sql3`${sql3.identifier(w._.alias)} as (${w._.sql})`);
977
+ if (i < queries.length - 1) {
978
+ withSqlChunks.push(sql3`, `);
979
+ }
980
+ }
981
+ withSqlChunks.push(sql3` `);
982
+ return sql3.join(withSqlChunks);
983
+ }
984
+ buildDeleteQuery({ table, where, withList }) {
985
+ const withSql = this.buildWithCTE(withList);
986
+ const whereSql = where ? sql3` where ${where}` : void 0;
987
+ return sql3`${withSql}delete from ${table}${whereSql}`;
988
+ }
989
+ buildUpdateSet(table, set) {
990
+ const tableColumns = table[Table2.Symbol.Columns];
991
+ const columnNames = Object.keys(tableColumns).filter(
992
+ (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
993
+ );
994
+ const setSize = columnNames.length;
995
+ return sql3.join(
996
+ columnNames.flatMap((colName, i) => {
997
+ const col = tableColumns[colName];
998
+ const value = set[colName] ?? sql3.param(col.onUpdateFn(), col);
999
+ const res = sql3`${sql3.identifier(this.casing.getColumnCasing(col))} = ${value}`;
1000
+ if (i < setSize - 1) {
1001
+ return [res, sql3.raw(", ")];
1002
+ }
1003
+ return [res];
1004
+ })
1005
+ );
1006
+ }
1007
+ buildUpdateQuery({ table, set, where, withList }) {
1008
+ const withSql = this.buildWithCTE(withList);
1009
+ const tableName = table[DatabendTable.Symbol.Name];
1010
+ const tableSchema = table[DatabendTable.Symbol.Schema];
1011
+ const origTableName = table[DatabendTable.Symbol.OriginalName];
1012
+ const alias2 = tableName === origTableName ? void 0 : tableName;
1013
+ const tableSql = sql3`${tableSchema ? sql3`${sql3.identifier(tableSchema)}.` : void 0}${sql3.identifier(origTableName)}${alias2 && sql3` ${sql3.identifier(alias2)}`}`;
1014
+ const setSql = this.buildUpdateSet(table, set);
1015
+ const whereSql = where ? sql3` where ${where}` : void 0;
1016
+ return sql3`${withSql}update ${tableSql} set ${setSql}${whereSql}`;
1017
+ }
1018
+ buildSelection(fields, { isSingleTable = false } = {}) {
1019
+ const columnsLen = fields.length;
1020
+ const chunks = fields.flatMap(({ field }, i) => {
1021
+ const chunk = [];
1022
+ if (is(field, SQL.Aliased) && field.isSelectionField) {
1023
+ chunk.push(sql3.identifier(field.fieldAlias));
1024
+ } else if (is(field, SQL.Aliased) || is(field, SQL)) {
1025
+ const query = is(field, SQL.Aliased) ? field.sql : field;
1026
+ if (isSingleTable) {
1027
+ chunk.push(
1028
+ new SQL(
1029
+ query.queryChunks.map((c) => {
1030
+ if (is(c, DatabendColumn)) {
1031
+ return sql3.identifier(this.casing.getColumnCasing(c));
1032
+ }
1033
+ return c;
1034
+ })
1035
+ )
1036
+ );
1037
+ } else {
1038
+ chunk.push(query);
1039
+ }
1040
+ if (is(field, SQL.Aliased)) {
1041
+ chunk.push(sql3` as ${sql3.identifier(field.fieldAlias)}`);
1042
+ }
1043
+ } else if (is(field, Column2)) {
1044
+ if (isSingleTable) {
1045
+ chunk.push(sql3.identifier(this.casing.getColumnCasing(field)));
1046
+ } else {
1047
+ chunk.push(field);
1048
+ }
1049
+ }
1050
+ if (i < columnsLen - 1) {
1051
+ chunk.push(sql3`, `);
1052
+ }
1053
+ return chunk;
1054
+ });
1055
+ return sql3.join(chunks);
1056
+ }
1057
+ buildJoins(joins) {
1058
+ if (!joins || joins.length === 0) {
1059
+ return void 0;
1060
+ }
1061
+ const joinsArray = [];
1062
+ for (const [index2, joinMeta] of joins.entries()) {
1063
+ if (index2 === 0) {
1064
+ joinsArray.push(sql3` `);
1065
+ }
1066
+ const table = joinMeta.table;
1067
+ const lateralSql = joinMeta.lateral ? sql3` lateral` : void 0;
1068
+ const onClause = joinMeta.on ? sql3` on ${joinMeta.on}` : void 0;
1069
+ if (is(table, DatabendTable)) {
1070
+ const t = table;
1071
+ const tableName = t[DatabendTable.Symbol.Name];
1072
+ const tableSchema = t[DatabendTable.Symbol.Schema];
1073
+ const origTableName = t[DatabendTable.Symbol.OriginalName];
1074
+ const alias2 = tableName === origTableName ? void 0 : joinMeta.alias;
1075
+ joinsArray.push(
1076
+ sql3`${sql3.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql3`${sql3.identifier(tableSchema)}.` : void 0}${sql3.identifier(origTableName)}${alias2 && sql3` ${sql3.identifier(alias2)}`}${onClause}`
1077
+ );
1078
+ } else if (is(table, View2)) {
1079
+ const viewName = table[ViewBaseConfig].name;
1080
+ const viewSchema = table[ViewBaseConfig].schema;
1081
+ const origViewName = table[ViewBaseConfig].originalName;
1082
+ const alias2 = viewName === origViewName ? void 0 : joinMeta.alias;
1083
+ joinsArray.push(
1084
+ sql3`${sql3.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql3`${sql3.identifier(viewSchema)}.` : void 0}${sql3.identifier(origViewName)}${alias2 && sql3` ${sql3.identifier(alias2)}`}${onClause}`
1085
+ );
1086
+ } else {
1087
+ joinsArray.push(
1088
+ sql3`${sql3.raw(joinMeta.joinType)} join${lateralSql} ${table}${onClause}`
1089
+ );
1090
+ }
1091
+ if (index2 < joins.length - 1) {
1092
+ joinsArray.push(sql3` `);
1093
+ }
1094
+ }
1095
+ return sql3.join(joinsArray);
1096
+ }
1097
+ buildFromTable(table) {
1098
+ if (is(table, Table2)) {
1099
+ const t = table;
1100
+ if (t[Table2.Symbol.OriginalName] !== t[Table2.Symbol.Name]) {
1101
+ let fullName = sql3`${sql3.identifier(t[Table2.Symbol.OriginalName])}`;
1102
+ if (t[Table2.Symbol.Schema]) {
1103
+ fullName = sql3`${sql3.identifier(t[Table2.Symbol.Schema])}.${fullName}`;
1104
+ }
1105
+ return sql3`${fullName} ${sql3.identifier(t[Table2.Symbol.Name])}`;
1106
+ }
1107
+ }
1108
+ return table;
1109
+ }
1110
+ buildSelectQuery({
1111
+ withList,
1112
+ fields,
1113
+ fieldsFlat,
1114
+ where,
1115
+ having,
1116
+ table,
1117
+ joins,
1118
+ orderBy,
1119
+ groupBy,
1120
+ limit,
1121
+ offset,
1122
+ distinct,
1123
+ setOperators
1124
+ }) {
1125
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
1126
+ for (const f of fieldsList) {
1127
+ if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, DatabendViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(
1128
+ ({ alias: alias2 }) => alias2 === (table2[Table2.Symbol.IsAlias] ? getTableName(table2) : table2[Table2.Symbol.BaseName])
1129
+ ))(f.field.table)) {
1130
+ const tableName = getTableName(f.field.table);
1131
+ throw new Error(
1132
+ `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?`
1133
+ );
1134
+ }
1135
+ }
1136
+ const isSingleTable = !joins || joins.length === 0;
1137
+ const withSql = this.buildWithCTE(withList);
1138
+ let distinctSql;
1139
+ if (distinct) {
1140
+ distinctSql = distinct === true ? sql3` distinct` : sql3` distinct on (${sql3.join(distinct.on, sql3`, `)})`;
1141
+ }
1142
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
1143
+ const tableSql = this.buildFromTable(table);
1144
+ const joinsSql = this.buildJoins(joins);
1145
+ const whereSql = where ? sql3` where ${where}` : void 0;
1146
+ const havingSql = having ? sql3` having ${having}` : void 0;
1147
+ let orderBySql;
1148
+ if (orderBy && orderBy.length > 0) {
1149
+ orderBySql = sql3` order by ${sql3.join(orderBy, sql3`, `)}`;
1150
+ }
1151
+ let groupBySql;
1152
+ if (groupBy && groupBy.length > 0) {
1153
+ groupBySql = sql3` group by ${sql3.join(groupBy, sql3`, `)}`;
1154
+ }
1155
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql3` limit ${limit}` : void 0;
1156
+ const offsetSql = offset ? sql3` offset ${offset}` : void 0;
1157
+ const finalQuery = sql3`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
1158
+ if (setOperators.length > 0) {
1159
+ return this.buildSetOperations(finalQuery, setOperators);
1160
+ }
1161
+ return finalQuery;
1162
+ }
1163
+ buildSetOperations(leftSelect, setOperators) {
1164
+ const [setOperator, ...rest] = setOperators;
1165
+ if (!setOperator) {
1166
+ throw new Error("Cannot pass undefined values to any set operator");
1167
+ }
1168
+ if (rest.length === 0) {
1169
+ return this.buildSetOperationQuery({ leftSelect, setOperator });
1170
+ }
1171
+ return this.buildSetOperations(
1172
+ this.buildSetOperationQuery({ leftSelect, setOperator }),
1173
+ rest
1174
+ );
1175
+ }
1176
+ buildSetOperationQuery({
1177
+ leftSelect,
1178
+ setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
1179
+ }) {
1180
+ const leftChunk = sql3`(${leftSelect.getSQL()}) `;
1181
+ const rightChunk = sql3`(${rightSelect.getSQL()})`;
1182
+ let orderBySql;
1183
+ if (orderBy && orderBy.length > 0) {
1184
+ const orderByValues = [];
1185
+ for (const singleOrderBy of orderBy) {
1186
+ if (is(singleOrderBy, DatabendColumn)) {
1187
+ orderByValues.push(sql3.identifier(singleOrderBy.name));
1188
+ } else if (is(singleOrderBy, SQL)) {
1189
+ for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
1190
+ const chunk = singleOrderBy.queryChunks[i];
1191
+ if (is(chunk, DatabendColumn)) {
1192
+ singleOrderBy.queryChunks[i] = sql3.identifier(chunk.name);
1193
+ }
1194
+ }
1195
+ orderByValues.push(sql3`${singleOrderBy}`);
1196
+ } else {
1197
+ orderByValues.push(sql3`${singleOrderBy}`);
1198
+ }
1199
+ }
1200
+ orderBySql = sql3` order by ${sql3.join(orderByValues, sql3`, `)} `;
1201
+ }
1202
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql3` limit ${limit}` : void 0;
1203
+ const operatorChunk = sql3.raw(`${type} ${isAll ? "all " : ""}`);
1204
+ const offsetSql = offset ? sql3` offset ${offset}` : void 0;
1205
+ return sql3`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
1206
+ }
1207
+ buildInsertQuery({ table, values: valuesOrSelect, withList, select }) {
1208
+ const valuesSqlList = [];
1209
+ const columns = table[Table2.Symbol.Columns];
1210
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
1211
+ const insertOrder = colEntries.map(
1212
+ ([, column]) => sql3.identifier(this.casing.getColumnCasing(column))
1213
+ );
1214
+ if (select) {
1215
+ const select2 = valuesOrSelect;
1216
+ if (is(select2, SQL)) {
1217
+ valuesSqlList.push(select2);
1218
+ } else {
1219
+ valuesSqlList.push(select2.getSQL());
1220
+ }
1221
+ } else {
1222
+ const values = valuesOrSelect;
1223
+ valuesSqlList.push(sql3.raw("values "));
1224
+ for (const [valueIndex, value] of values.entries()) {
1225
+ const valueList = [];
1226
+ for (const [fieldName, col] of colEntries) {
1227
+ const colValue = value[fieldName];
1228
+ if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
1229
+ if (col.defaultFn !== void 0) {
1230
+ const defaultFnResult = col.defaultFn();
1231
+ const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql3.param(defaultFnResult, col);
1232
+ valueList.push(defaultValue);
1233
+ } else if (!col.default && col.onUpdateFn !== void 0) {
1234
+ const onUpdateFnResult = col.onUpdateFn();
1235
+ const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql3.param(onUpdateFnResult, col);
1236
+ valueList.push(newValue);
1237
+ } else {
1238
+ valueList.push(sql3`default`);
1239
+ }
1240
+ } else {
1241
+ valueList.push(colValue);
1242
+ }
1243
+ }
1244
+ valuesSqlList.push(valueList);
1245
+ if (valueIndex < values.length - 1) {
1246
+ valuesSqlList.push(sql3`, `);
1247
+ }
1248
+ }
1249
+ }
1250
+ const withSql = this.buildWithCTE(withList);
1251
+ const valuesSql = sql3.join(valuesSqlList);
1252
+ return sql3`${withSql}insert into ${table} ${insertOrder} ${valuesSql}`;
1253
+ }
1254
+ prepareTyping(encoder) {
1255
+ if (is(encoder, DatabendDecimal) || is(encoder, DatabendColumn)) {
1256
+ const sqlType = encoder.getSQLType?.();
1257
+ if (sqlType) {
1258
+ const lower = sqlType.toLowerCase();
1259
+ if (lower === "integer" || lower === "int" || lower === "smallint" || lower === "tinyint" || lower === "bigint" || lower === "real" || lower === "double" || lower === "float" || lower.startsWith("decimal")) {
1260
+ return "decimal";
1261
+ }
1262
+ if (lower === "timestamp") {
1263
+ return "timestamp";
1264
+ }
1265
+ if (lower === "date") {
1266
+ return "date";
1267
+ }
1268
+ }
1269
+ }
1270
+ if (is(encoder, DatabendTimestamp)) {
1271
+ return "timestamp";
1272
+ }
1273
+ if (is(encoder, DatabendVariant)) {
1274
+ return "none";
1275
+ }
1276
+ return "none";
1277
+ }
1278
+ sqlToQuery(sql22, invokeSource) {
1279
+ return sql22.toQuery({
1280
+ casing: this.casing,
1281
+ escapeName: this.escapeName,
1282
+ escapeParam: this.escapeParam,
1283
+ escapeString: this.escapeString,
1284
+ prepareTyping: this.prepareTyping.bind(this),
1285
+ invokeSource
1286
+ });
1287
+ }
1288
+ buildRelationalQueryWithoutPK({
1289
+ fullSchema,
1290
+ schema,
1291
+ tableNamesMap,
1292
+ table,
1293
+ tableConfig,
1294
+ queryConfig: config,
1295
+ tableAlias,
1296
+ nestedQueryRelation,
1297
+ joinOn
1298
+ }) {
1299
+ let selection = [];
1300
+ let limit, offset, orderBy = [], where;
1301
+ const joins = [];
1302
+ if (config === true) {
1303
+ const selectionEntries = Object.entries(tableConfig.columns);
1304
+ selection = selectionEntries.map(([key, value]) => ({
1305
+ dbKey: value.name,
1306
+ tsKey: key,
1307
+ field: aliasedTableColumn(value, tableAlias),
1308
+ relationTableTsKey: void 0,
1309
+ isJson: false,
1310
+ selection: []
1311
+ }));
1312
+ } else {
1313
+ const aliasedColumns = Object.fromEntries(
1314
+ Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
1315
+ );
1316
+ if (config.where) {
1317
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
1318
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
1319
+ }
1320
+ const fieldsSelection = [];
1321
+ let selectedColumns = [];
1322
+ if (config.columns) {
1323
+ let isIncludeMode = false;
1324
+ for (const [field, value] of Object.entries(config.columns)) {
1325
+ if (value === void 0) continue;
1326
+ if (field in tableConfig.columns) {
1327
+ if (!isIncludeMode && value === true) {
1328
+ isIncludeMode = true;
1329
+ }
1330
+ selectedColumns.push(field);
1331
+ }
1332
+ }
1333
+ if (selectedColumns.length > 0) {
1334
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
1335
+ }
1336
+ } else {
1337
+ selectedColumns = Object.keys(tableConfig.columns);
1338
+ }
1339
+ for (const field of selectedColumns) {
1340
+ const column = tableConfig.columns[field];
1341
+ fieldsSelection.push({ tsKey: field, value: column });
1342
+ }
1343
+ let selectedRelations = [];
1344
+ if (config.with) {
1345
+ selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({
1346
+ tsKey,
1347
+ queryConfig,
1348
+ relation: tableConfig.relations[tsKey]
1349
+ }));
1350
+ }
1351
+ if (config.extras) {
1352
+ const extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: sql3 }) : config.extras;
1353
+ for (const [tsKey, value] of Object.entries(extras)) {
1354
+ fieldsSelection.push({
1355
+ tsKey,
1356
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
1357
+ });
1358
+ }
1359
+ }
1360
+ for (const { tsKey, value } of fieldsSelection) {
1361
+ selection.push({
1362
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
1363
+ tsKey,
1364
+ field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
1365
+ relationTableTsKey: void 0,
1366
+ isJson: false,
1367
+ selection: []
1368
+ });
1369
+ }
1370
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
1371
+ if (!Array.isArray(orderByOrig)) {
1372
+ orderByOrig = [orderByOrig];
1373
+ }
1374
+ orderBy = orderByOrig.map((orderByValue) => {
1375
+ if (is(orderByValue, Column2)) {
1376
+ return aliasedTableColumn(orderByValue, tableAlias);
1377
+ }
1378
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
1379
+ });
1380
+ limit = config.limit;
1381
+ offset = config.offset;
1382
+ for (const {
1383
+ tsKey: selectedRelationTsKey,
1384
+ queryConfig: selectedRelationConfigValue,
1385
+ relation
1386
+ } of selectedRelations) {
1387
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
1388
+ const relationTableName = getTableUniqueName(relation.referencedTable);
1389
+ const relationTableTsName = tableNamesMap[relationTableName];
1390
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
1391
+ const joinOn2 = and(
1392
+ ...normalizedRelation.fields.map(
1393
+ (field2, i) => eq(
1394
+ aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
1395
+ aliasedTableColumn(field2, tableAlias)
1396
+ )
1397
+ )
1398
+ );
1399
+ const builtRelation = this.buildRelationalQueryWithoutPK({
1400
+ fullSchema,
1401
+ schema,
1402
+ tableNamesMap,
1403
+ table: fullSchema[relationTableTsName],
1404
+ tableConfig: schema[relationTableTsName],
1405
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
1406
+ tableAlias: relationTableAlias,
1407
+ joinOn: joinOn2,
1408
+ nestedQueryRelation: relation
1409
+ });
1410
+ const field = sql3`${sql3.identifier(relationTableAlias)}.${sql3.identifier("data")}`.as(selectedRelationTsKey);
1411
+ joins.push({
1412
+ on: sql3`true`,
1413
+ table: new Subquery(builtRelation.sql, {}, relationTableAlias),
1414
+ alias: relationTableAlias,
1415
+ joinType: "left",
1416
+ lateral: true
1417
+ });
1418
+ selection.push({
1419
+ dbKey: selectedRelationTsKey,
1420
+ tsKey: selectedRelationTsKey,
1421
+ field,
1422
+ relationTableTsKey: relationTableTsName,
1423
+ isJson: true,
1424
+ selection: builtRelation.selection
1425
+ });
1426
+ }
1427
+ }
1428
+ if (selection.length === 0) {
1429
+ throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
1430
+ }
1431
+ let result;
1432
+ where = and(joinOn, where);
1433
+ if (nestedQueryRelation) {
1434
+ let field = sql3`json_build_array(${sql3.join(
1435
+ selection.map(
1436
+ ({ field: field2, tsKey, isJson }) => isJson ? sql3`${sql3.identifier(`${tableAlias}_${tsKey}`)}.${sql3.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
1437
+ ),
1438
+ sql3`, `
1439
+ )})`;
1440
+ if (is(nestedQueryRelation, Many)) {
1441
+ field = sql3`coalesce(json_agg(${field}${orderBy.length > 0 ? sql3` order by ${sql3.join(orderBy, sql3`, `)}` : void 0}), '[]'::json)`;
1442
+ }
1443
+ const nestedSelection = [{
1444
+ dbKey: "data",
1445
+ tsKey: "data",
1446
+ field: field.as("data"),
1447
+ isJson: true,
1448
+ relationTableTsKey: tableConfig.tsName,
1449
+ selection
1450
+ }];
1451
+ const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
1452
+ if (needsSubquery) {
1453
+ result = this.buildSelectQuery({
1454
+ table: aliasedTable(table, tableAlias),
1455
+ fields: {},
1456
+ fieldsFlat: [{ path: [], field: sql3.raw("*") }],
1457
+ where,
1458
+ limit,
1459
+ offset,
1460
+ orderBy,
1461
+ setOperators: []
1462
+ });
1463
+ where = void 0;
1464
+ limit = void 0;
1465
+ offset = void 0;
1466
+ orderBy = [];
1467
+ } else {
1468
+ result = aliasedTable(table, tableAlias);
1469
+ }
1470
+ result = this.buildSelectQuery({
1471
+ table: is(result, DatabendTable) ? result : new Subquery(result, {}, tableAlias),
1472
+ fields: {},
1473
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
1474
+ path: [],
1475
+ field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
1476
+ })),
1477
+ joins,
1478
+ where,
1479
+ limit,
1480
+ offset,
1481
+ orderBy,
1482
+ setOperators: []
1483
+ });
1484
+ } else {
1485
+ result = this.buildSelectQuery({
1486
+ table: aliasedTable(table, tableAlias),
1487
+ fields: {},
1488
+ fieldsFlat: selection.map(({ field }) => ({
1489
+ path: [],
1490
+ field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
1491
+ })),
1492
+ joins,
1493
+ where,
1494
+ limit,
1495
+ offset,
1496
+ orderBy,
1497
+ setOperators: []
1498
+ });
1499
+ }
1500
+ return {
1501
+ tableTsKey: tableConfig.tsName,
1502
+ sql: result,
1503
+ selection
1504
+ };
1505
+ }
1506
+ };
1507
+
1508
+ // src/databend-core/indexes.ts
1509
+ import { entityKind as entityKind21, is as is2 } from "drizzle-orm/entity";
1510
+ import { SQL as SQL2 } from "drizzle-orm/sql/sql";
1511
+ var IndexBuilderOn = class {
1512
+ constructor(unique, name) {
1513
+ this.unique = unique;
1514
+ this.name = name;
1515
+ }
1516
+ static [entityKind21] = "DatabendIndexBuilderOn";
1517
+ on(...columns) {
1518
+ return new IndexBuilder(
1519
+ columns.map((it) => {
1520
+ if (is2(it, SQL2)) {
1521
+ return it;
1522
+ }
1523
+ const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
1524
+ it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
1525
+ return clonedIndexedColumn;
1526
+ }),
1527
+ this.unique,
1528
+ this.name
1529
+ );
1530
+ }
1531
+ };
1532
+ var IndexBuilder = class {
1533
+ static [entityKind21] = "DatabendIndexBuilder";
1534
+ /** @internal */
1535
+ config;
1536
+ constructor(columns, unique, name) {
1537
+ this.config = {
1538
+ name,
1539
+ columns,
1540
+ unique
1541
+ };
1542
+ }
1543
+ where(condition) {
1544
+ this.config.where = condition;
1545
+ return this;
1546
+ }
1547
+ /** @internal */
1548
+ build(table) {
1549
+ return new Index(this.config, table);
1550
+ }
1551
+ };
1552
+ var Index = class {
1553
+ static [entityKind21] = "DatabendIndex";
1554
+ config;
1555
+ constructor(config, table) {
1556
+ this.config = { ...config, table };
1557
+ }
1558
+ };
1559
+ function index(name) {
1560
+ return new IndexBuilderOn(false, name);
1561
+ }
1562
+ function uniqueIndex(name) {
1563
+ return new IndexBuilderOn(true, name);
1564
+ }
1565
+
1566
+ // src/databend-core/primary-keys.ts
1567
+ import { entityKind as entityKind22 } from "drizzle-orm/entity";
1568
+ function primaryKey(...config) {
1569
+ if (config[0].columns) {
1570
+ return new PrimaryKeyBuilder(config[0].columns, config[0].name);
1571
+ }
1572
+ return new PrimaryKeyBuilder(config);
1573
+ }
1574
+ var PrimaryKeyBuilder = class {
1575
+ static [entityKind22] = "DatabendPrimaryKeyBuilder";
1576
+ /** @internal */
1577
+ columns;
1578
+ /** @internal */
1579
+ name;
1580
+ constructor(columns, name) {
1581
+ this.columns = columns;
1582
+ this.name = name;
1583
+ }
1584
+ /** @internal */
1585
+ build(table) {
1586
+ return new PrimaryKey(table, this.columns, this.name);
1587
+ }
1588
+ };
1589
+ var PrimaryKey = class {
1590
+ constructor(table, columns, name) {
1591
+ this.table = table;
1592
+ this.columns = columns;
1593
+ this.name = name;
1594
+ }
1595
+ static [entityKind22] = "DatabendPrimaryKey";
1596
+ columns;
1597
+ name;
1598
+ getName() {
1599
+ return this.name ?? `${this.table[DatabendTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1600
+ }
1601
+ };
1602
+
1603
+ // src/databend-core/schema.ts
1604
+ import { entityKind as entityKind23, is as is3 } from "drizzle-orm/entity";
1605
+ import { SQL as SQL3, sql as sql4 } from "drizzle-orm/sql/sql";
1606
+ var DatabendSchema = class {
1607
+ constructor(schemaName) {
1608
+ this.schemaName = schemaName;
1609
+ }
1610
+ static [entityKind23] = "DatabendSchema";
1611
+ table = (name, columns, extraConfig) => {
1612
+ return databendTableWithSchema(name, columns, extraConfig, this.schemaName);
1613
+ };
1614
+ getSQL() {
1615
+ return new SQL3([sql4.identifier(this.schemaName)]);
1616
+ }
1617
+ shouldOmitSQLParens() {
1618
+ return true;
1619
+ }
1620
+ };
1621
+ function databendSchema(name) {
1622
+ return new DatabendSchema(name);
1623
+ }
1624
+
1625
+ // src/databend-core/utils.ts
1626
+ import { is as is4 } from "drizzle-orm/entity";
1627
+ import { Table as Table3 } from "drizzle-orm/table";
1628
+ function getTableConfig(table) {
1629
+ const columns = Object.values(table[Table3.Symbol.Columns]);
1630
+ const indexes = [];
1631
+ const primaryKeys = [];
1632
+ const name = table[Table3.Symbol.Name];
1633
+ const schema = table[Table3.Symbol.Schema];
1634
+ const extraConfigBuilder = table[DatabendTable.Symbol.ExtraConfigBuilder];
1635
+ if (extraConfigBuilder !== void 0) {
1636
+ const extraConfig = extraConfigBuilder(table[Table3.Symbol.ExtraConfigColumns]);
1637
+ const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
1638
+ for (const builder of extraValues) {
1639
+ if (is4(builder, IndexBuilder)) {
1640
+ indexes.push(builder.build(table));
1641
+ } else if (is4(builder, PrimaryKeyBuilder)) {
1642
+ primaryKeys.push(builder.build(table));
1643
+ }
1644
+ }
1645
+ }
1646
+ return {
1647
+ columns,
1648
+ indexes,
1649
+ primaryKeys,
1650
+ name,
1651
+ schema
1652
+ };
1653
+ }
1654
+
1655
+ // src/databend-core/view.ts
1656
+ import { entityKind as entityKind26, is as is7 } from "drizzle-orm/entity";
1657
+ import { SelectionProxyHandler as SelectionProxyHandler3 } from "drizzle-orm/selection-proxy";
1658
+ import { getTableColumns as getTableColumns2 } from "drizzle-orm/utils";
1659
+
1660
+ // src/databend-core/query-builders/query-builder.ts
1661
+ import { entityKind as entityKind25, is as is6 } from "drizzle-orm/entity";
1662
+ import { SelectionProxyHandler as SelectionProxyHandler2 } from "drizzle-orm/selection-proxy";
1663
+ import { WithSubquery } from "drizzle-orm/subquery";
1664
+
1665
+ // src/databend-core/query-builders/select.ts
1666
+ import { entityKind as entityKind24, is as is5 } from "drizzle-orm/entity";
1667
+ import { TypedQueryBuilder } from "drizzle-orm/query-builders/query-builder";
1668
+ import { QueryPromise } from "drizzle-orm/query-promise";
1669
+ import { SelectionProxyHandler } from "drizzle-orm/selection-proxy";
1670
+ import { SQL as SQL4, View as View3 } from "drizzle-orm/sql/sql";
1671
+ import { Subquery as Subquery2 } from "drizzle-orm/subquery";
1672
+ import { Table as Table4 } from "drizzle-orm/table";
1673
+ import { tracer } from "drizzle-orm/tracing";
1674
+ import {
1675
+ applyMixins,
1676
+ getTableColumns,
1677
+ getTableLikeName,
1678
+ haveSameKeys,
1679
+ orderSelectedFields as orderSelectedFields2
1680
+ } from "drizzle-orm/utils";
1681
+ import { ViewBaseConfig as ViewBaseConfig2 } from "drizzle-orm/view-common";
1682
+ var DatabendSelectBuilder = class {
1683
+ static [entityKind24] = "DatabendSelectBuilder";
1684
+ fields;
1685
+ session;
1686
+ dialect;
1687
+ withList = [];
1688
+ distinct;
1689
+ constructor(config) {
1690
+ this.fields = config.fields;
1691
+ this.session = config.session;
1692
+ this.dialect = config.dialect;
1693
+ if (config.withList) {
1694
+ this.withList = config.withList;
1695
+ }
1696
+ this.distinct = config.distinct;
1697
+ }
1698
+ from(source) {
1699
+ const isPartialSelect = !!this.fields;
1700
+ let fields;
1701
+ if (this.fields) {
1702
+ fields = this.fields;
1703
+ } else if (is5(source, Subquery2)) {
1704
+ fields = Object.fromEntries(
1705
+ Object.keys(source._.selectedFields).map((key) => [key, source[key]])
1706
+ );
1707
+ } else if (is5(source, DatabendViewBase)) {
1708
+ fields = source[ViewBaseConfig2].selectedFields;
1709
+ } else if (is5(source, SQL4)) {
1710
+ fields = {};
1711
+ } else {
1712
+ fields = getTableColumns(source);
1713
+ }
1714
+ return new DatabendSelectBase({
1715
+ table: source,
1716
+ fields,
1717
+ isPartialSelect,
1718
+ session: this.session,
1719
+ dialect: this.dialect,
1720
+ withList: this.withList,
1721
+ distinct: this.distinct
1722
+ });
1723
+ }
1724
+ };
1725
+ var DatabendSelectQueryBuilderBase = class extends TypedQueryBuilder {
1726
+ static [entityKind24] = "DatabendSelectQueryBuilder";
1727
+ _;
1728
+ config;
1729
+ joinsNotNullableMap;
1730
+ tableName;
1731
+ isPartialSelect;
1732
+ session;
1733
+ dialect;
1734
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
1735
+ super();
1736
+ this.config = {
1737
+ withList,
1738
+ table,
1739
+ fields: { ...fields },
1740
+ distinct,
1741
+ setOperators: []
1742
+ };
1743
+ this.isPartialSelect = isPartialSelect;
1744
+ this.session = session;
1745
+ this.dialect = dialect;
1746
+ this._ = {
1747
+ selectedFields: fields
1748
+ };
1749
+ this.tableName = getTableLikeName(table);
1750
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
1751
+ }
1752
+ createJoin(joinType) {
1753
+ return (table, on) => {
1754
+ const baseTableName = this.tableName;
1755
+ const tableName = getTableLikeName(table);
1756
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
1757
+ throw new Error(`Alias "${tableName}" is already used in this query`);
1758
+ }
1759
+ if (!this.isPartialSelect) {
1760
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
1761
+ this.config.fields = {
1762
+ [baseTableName]: this.config.fields
1763
+ };
1764
+ }
1765
+ if (typeof tableName === "string" && !is5(table, SQL4)) {
1766
+ const selection = is5(table, Subquery2) ? table._.selectedFields : is5(table, View3) ? table[ViewBaseConfig2].selectedFields : table[Table4.Symbol.Columns];
1767
+ this.config.fields[tableName] = selection;
1768
+ }
1769
+ }
1770
+ if (typeof on === "function") {
1771
+ on = on(
1772
+ new Proxy(
1773
+ this.config.fields,
1774
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1775
+ )
1776
+ );
1777
+ }
1778
+ if (!this.config.joins) {
1779
+ this.config.joins = [];
1780
+ }
1781
+ this.config.joins.push({ on, table, joinType, alias: tableName });
1782
+ if (typeof tableName === "string") {
1783
+ switch (joinType) {
1784
+ case "left":
1785
+ this.joinsNotNullableMap[tableName] = false;
1786
+ break;
1787
+ case "right":
1788
+ this.joinsNotNullableMap = Object.fromEntries(
1789
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
1790
+ );
1791
+ this.joinsNotNullableMap[tableName] = true;
1792
+ break;
1793
+ case "inner":
1794
+ this.joinsNotNullableMap[tableName] = true;
1795
+ break;
1796
+ case "full":
1797
+ this.joinsNotNullableMap = Object.fromEntries(
1798
+ Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
1799
+ );
1800
+ this.joinsNotNullableMap[tableName] = false;
1801
+ break;
1802
+ }
1803
+ }
1804
+ return this;
1805
+ };
1806
+ }
1807
+ leftJoin = this.createJoin("left");
1808
+ rightJoin = this.createJoin("right");
1809
+ innerJoin = this.createJoin("inner");
1810
+ fullJoin = this.createJoin("full");
1811
+ crossJoin = (table) => {
1812
+ const baseTableName = this.tableName;
1813
+ const tableName = getTableLikeName(table);
1814
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
1815
+ throw new Error(`Alias "${tableName}" is already used in this query`);
1816
+ }
1817
+ if (!this.isPartialSelect) {
1818
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
1819
+ this.config.fields = {
1820
+ [baseTableName]: this.config.fields
1821
+ };
1822
+ }
1823
+ if (typeof tableName === "string" && !is5(table, SQL4)) {
1824
+ const selection = is5(table, Subquery2) ? table._.selectedFields : is5(table, View3) ? table[ViewBaseConfig2].selectedFields : table[Table4.Symbol.Columns];
1825
+ this.config.fields[tableName] = selection;
1826
+ }
1827
+ }
1828
+ if (!this.config.joins) {
1829
+ this.config.joins = [];
1830
+ }
1831
+ this.config.joins.push({ on: void 0, table, joinType: "cross", alias: tableName });
1832
+ if (typeof tableName === "string") {
1833
+ this.joinsNotNullableMap[tableName] = true;
1834
+ }
1835
+ return this;
1836
+ };
1837
+ createSetOperator(type, isAll) {
1838
+ return (rightSelection) => {
1839
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getDatabendSetOperators()) : rightSelection;
1840
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
1841
+ throw new Error(
1842
+ "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
1843
+ );
1844
+ }
1845
+ this.config.setOperators.push({ type, isAll, rightSelect });
1846
+ return this;
1847
+ };
1848
+ }
1849
+ union = this.createSetOperator("union", false);
1850
+ unionAll = this.createSetOperator("union", true);
1851
+ intersect = this.createSetOperator("intersect", false);
1852
+ intersectAll = this.createSetOperator("intersect", true);
1853
+ except = this.createSetOperator("except", false);
1854
+ exceptAll = this.createSetOperator("except", true);
1855
+ /** @internal */
1856
+ addSetOperators(setOperators) {
1857
+ this.config.setOperators.push(...setOperators);
1858
+ return this;
1859
+ }
1860
+ where(where) {
1861
+ if (typeof where === "function") {
1862
+ where = where(
1863
+ new Proxy(
1864
+ this.config.fields,
1865
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1866
+ )
1867
+ );
1868
+ }
1869
+ this.config.where = where;
1870
+ return this;
1871
+ }
1872
+ having(having) {
1873
+ if (typeof having === "function") {
1874
+ having = having(
1875
+ new Proxy(
1876
+ this.config.fields,
1877
+ new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
1878
+ )
1879
+ );
1880
+ }
1881
+ this.config.having = having;
1882
+ return this;
1883
+ }
1884
+ groupBy(...columns) {
1885
+ if (typeof columns[0] === "function") {
1886
+ const groupBy = columns[0](
1887
+ new Proxy(
1888
+ this.config.fields,
1889
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
1890
+ )
1891
+ );
1892
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
1893
+ } else {
1894
+ this.config.groupBy = columns;
1895
+ }
1896
+ return this;
1897
+ }
1898
+ orderBy(...columns) {
1899
+ if (typeof columns[0] === "function") {
1900
+ const orderBy = columns[0](
1901
+ new Proxy(
1902
+ this.config.fields,
1903
+ new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
1904
+ )
1905
+ );
1906
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
1907
+ if (this.config.setOperators.length > 0) {
1908
+ this.config.setOperators.at(-1).orderBy = orderByArray;
1909
+ } else {
1910
+ this.config.orderBy = orderByArray;
1911
+ }
1912
+ } else {
1913
+ const orderByArray = columns;
1914
+ if (this.config.setOperators.length > 0) {
1915
+ this.config.setOperators.at(-1).orderBy = orderByArray;
1916
+ } else {
1917
+ this.config.orderBy = orderByArray;
1918
+ }
1919
+ }
1920
+ return this;
1921
+ }
1922
+ limit(limit) {
1923
+ if (this.config.setOperators.length > 0) {
1924
+ this.config.setOperators.at(-1).limit = limit;
1925
+ } else {
1926
+ this.config.limit = limit;
1927
+ }
1928
+ return this;
1929
+ }
1930
+ offset(offset) {
1931
+ if (this.config.setOperators.length > 0) {
1932
+ this.config.setOperators.at(-1).offset = offset;
1933
+ } else {
1934
+ this.config.offset = offset;
1935
+ }
1936
+ return this;
1937
+ }
1938
+ /** @internal */
1939
+ getSQL() {
1940
+ return this.dialect.buildSelectQuery(this.config);
1941
+ }
1942
+ toSQL() {
1943
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
1944
+ return rest;
1945
+ }
1946
+ as(alias2) {
1947
+ return new Proxy(
1948
+ new Subquery2(this.getSQL(), this.config.fields, alias2),
1949
+ new SelectionProxyHandler({ alias: alias2, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
1950
+ );
1951
+ }
1952
+ /** @internal */
1953
+ getSelectedFields() {
1954
+ return new Proxy(
1955
+ this.config.fields,
1956
+ new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
1957
+ );
1958
+ }
1959
+ $dynamic() {
1960
+ return this;
1961
+ }
1962
+ };
1963
+ var DatabendSelectBase = class extends DatabendSelectQueryBuilderBase {
1964
+ static [entityKind24] = "DatabendSelect";
1965
+ /** @internal */
1966
+ _prepare(name) {
1967
+ const { session, config, dialect, joinsNotNullableMap } = this;
1968
+ if (!session) {
1969
+ throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
1970
+ }
1971
+ return tracer.startActiveSpan("drizzle.prepareQuery", () => {
1972
+ const fieldsList = orderSelectedFields2(config.fields);
1973
+ const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true);
1974
+ query.joinsNotNullableMap = joinsNotNullableMap;
1975
+ return query;
1976
+ });
1977
+ }
1978
+ prepare(name) {
1979
+ return this._prepare(name);
1980
+ }
1981
+ execute = (placeholderValues) => {
1982
+ return tracer.startActiveSpan("drizzle.operation", () => {
1983
+ return this._prepare().execute(placeholderValues);
1984
+ });
1985
+ };
1986
+ };
1987
+ applyMixins(DatabendSelectBase, [QueryPromise]);
1988
+ function createSetOperator(type, isAll) {
1989
+ return (leftSelect, rightSelect, ...restSelects) => {
1990
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
1991
+ type,
1992
+ isAll,
1993
+ rightSelect: select
1994
+ }));
1995
+ for (const setOperator of setOperators) {
1996
+ if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
1997
+ throw new Error(
1998
+ "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
1999
+ );
2000
+ }
2001
+ }
2002
+ return leftSelect.addSetOperators(setOperators);
2003
+ };
2004
+ }
2005
+ var getDatabendSetOperators = () => ({
2006
+ union,
2007
+ unionAll,
2008
+ intersect,
2009
+ intersectAll,
2010
+ except,
2011
+ exceptAll
2012
+ });
2013
+ var union = createSetOperator("union", false);
2014
+ var unionAll = createSetOperator("union", true);
2015
+ var intersect = createSetOperator("intersect", false);
2016
+ var intersectAll = createSetOperator("intersect", true);
2017
+ var except = createSetOperator("except", false);
2018
+ var exceptAll = createSetOperator("except", true);
2019
+
2020
+ // src/databend-core/query-builders/query-builder.ts
2021
+ var QueryBuilder = class {
2022
+ static [entityKind25] = "DatabendQueryBuilder";
2023
+ dialect;
2024
+ dialectConfig;
2025
+ constructor(dialect) {
2026
+ this.dialect = is6(dialect, DatabendDialect) ? dialect : void 0;
2027
+ this.dialectConfig = is6(dialect, DatabendDialect) ? void 0 : dialect;
2028
+ }
2029
+ $with(alias2) {
2030
+ const queryBuilder = this;
2031
+ return {
2032
+ as(qb) {
2033
+ if (typeof qb === "function") {
2034
+ qb = qb(queryBuilder);
2035
+ }
2036
+ return new Proxy(
2037
+ new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias2, true),
2038
+ new SelectionProxyHandler2({ alias: alias2, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
2039
+ );
2040
+ }
2041
+ };
2042
+ }
2043
+ with(...queries) {
2044
+ const self = this;
2045
+ function select(fields) {
2046
+ return new DatabendSelectBuilder({
2047
+ fields: fields ?? void 0,
2048
+ session: void 0,
2049
+ dialect: self.getDialect(),
2050
+ withList: queries
2051
+ });
2052
+ }
2053
+ function selectDistinct(fields) {
2054
+ return new DatabendSelectBuilder({
2055
+ fields: fields ?? void 0,
2056
+ session: void 0,
2057
+ dialect: self.getDialect(),
2058
+ distinct: true
2059
+ });
2060
+ }
2061
+ return { select, selectDistinct };
2062
+ }
2063
+ select(fields) {
2064
+ return new DatabendSelectBuilder({
2065
+ fields: fields ?? void 0,
2066
+ session: void 0,
2067
+ dialect: this.getDialect()
2068
+ });
2069
+ }
2070
+ selectDistinct(fields) {
2071
+ return new DatabendSelectBuilder({
2072
+ fields: fields ?? void 0,
2073
+ session: void 0,
2074
+ dialect: this.getDialect(),
2075
+ distinct: true
2076
+ });
2077
+ }
2078
+ getDialect() {
2079
+ if (!this.dialect) {
2080
+ this.dialect = new DatabendDialect(this.dialectConfig);
2081
+ }
2082
+ return this.dialect;
2083
+ }
2084
+ };
2085
+
2086
+ // src/databend-core/view-common.ts
2087
+ var DatabendViewConfig = Symbol.for("drizzle:DatabendViewConfig");
2088
+
2089
+ // src/databend-core/view.ts
2090
+ var DefaultViewBuilderCore = class {
2091
+ constructor(name, schema) {
2092
+ this.name = name;
2093
+ this.schema = schema;
2094
+ }
2095
+ static [entityKind26] = "DatabendDefaultViewBuilderCore";
2096
+ config = {};
2097
+ with(config) {
2098
+ this.config.with = config;
2099
+ return this;
2100
+ }
2101
+ };
2102
+ var ViewBuilder = class extends DefaultViewBuilderCore {
2103
+ static [entityKind26] = "DatabendViewBuilder";
2104
+ as(qb) {
2105
+ if (typeof qb === "function") {
2106
+ qb = qb(new QueryBuilder());
2107
+ }
2108
+ const selectionProxy = new SelectionProxyHandler3({
2109
+ alias: this.name,
2110
+ sqlBehavior: "error",
2111
+ sqlAliasedBehavior: "alias",
2112
+ replaceOriginalName: true
2113
+ });
2114
+ const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
2115
+ return new Proxy(
2116
+ new DatabendView({
2117
+ databendConfig: this.config,
2118
+ config: {
2119
+ name: this.name,
2120
+ schema: this.schema,
2121
+ selectedFields: aliasedSelection,
2122
+ query: qb.getSQL().inlineParams()
2123
+ }
2124
+ }),
2125
+ selectionProxy
2126
+ );
2127
+ }
2128
+ };
2129
+ var ManualViewBuilder = class extends DefaultViewBuilderCore {
2130
+ static [entityKind26] = "DatabendManualViewBuilder";
2131
+ columns;
2132
+ constructor(name, columns, schema) {
2133
+ super(name, schema);
2134
+ this.columns = getTableColumns2(databendTable(name, columns));
2135
+ }
2136
+ existing() {
2137
+ return new Proxy(
2138
+ new DatabendView({
2139
+ databendConfig: void 0,
2140
+ config: {
2141
+ name: this.name,
2142
+ schema: this.schema,
2143
+ selectedFields: this.columns,
2144
+ query: void 0
2145
+ }
2146
+ }),
2147
+ new SelectionProxyHandler3({
2148
+ alias: this.name,
2149
+ sqlBehavior: "error",
2150
+ sqlAliasedBehavior: "alias",
2151
+ replaceOriginalName: true
2152
+ })
2153
+ );
2154
+ }
2155
+ as(query) {
2156
+ return new Proxy(
2157
+ new DatabendView({
2158
+ databendConfig: this.config,
2159
+ config: {
2160
+ name: this.name,
2161
+ schema: this.schema,
2162
+ selectedFields: this.columns,
2163
+ query: query.inlineParams()
2164
+ }
2165
+ }),
2166
+ new SelectionProxyHandler3({
2167
+ alias: this.name,
2168
+ sqlBehavior: "error",
2169
+ sqlAliasedBehavior: "alias",
2170
+ replaceOriginalName: true
2171
+ })
2172
+ );
2173
+ }
2174
+ };
2175
+ var DatabendView = class extends DatabendViewBase {
2176
+ static [entityKind26] = "DatabendView";
2177
+ [DatabendViewConfig];
2178
+ constructor({ databendConfig, config }) {
2179
+ super(config);
2180
+ if (databendConfig) {
2181
+ this[DatabendViewConfig] = {
2182
+ with: databendConfig.with
2183
+ };
238
2184
  }
239
- return value.slice(0, 10);
240
2185
  }
241
- })(name);
2186
+ };
2187
+ function databendViewWithSchema(name, selection, schema) {
2188
+ if (selection) {
2189
+ return new ManualViewBuilder(name, selection, schema);
2190
+ }
2191
+ return new ViewBuilder(name, schema);
2192
+ }
2193
+ function databendView(name, columns) {
2194
+ return databendViewWithSchema(name, columns, void 0);
2195
+ }
242
2196
 
243
2197
  // src/driver.ts
244
2198
  import { Client } from "databend-driver";
245
- import { entityKind as entityKind3 } from "drizzle-orm/entity";
2199
+ import { entityKind as entityKind36 } from "drizzle-orm/entity";
246
2200
  import { DefaultLogger } from "drizzle-orm/logger";
247
- import { PgDatabase } from "drizzle-orm/pg-core/db";
248
2201
  import {
249
2202
  createTableRelationsHelpers,
250
2203
  extractTablesRelationalConfig
251
2204
  } from "drizzle-orm/relations";
252
2205
 
253
- // src/dialect.ts
254
- import {
255
- sql
256
- } from "drizzle-orm";
257
- import { entityKind, is } from "drizzle-orm/entity";
258
- import {
259
- PgBigInt53,
260
- PgBigInt64,
261
- PgDate,
262
- PgDateString,
263
- PgDialect,
264
- PgDoublePrecision,
265
- PgInteger,
266
- PgNumeric,
267
- PgReal,
268
- PgSmallInt,
269
- PgTime,
270
- PgTimestamp,
271
- PgTimestampString,
272
- PgUUID
273
- } from "drizzle-orm/pg-core";
274
- var DatabendDialect = class extends PgDialect {
275
- static [entityKind] = "DatabendPgDialect";
276
- // Databend does not support savepoints
277
- areSavepointsUnsupported() {
278
- return true;
2206
+ // src/databend-core/db.ts
2207
+ import { entityKind as entityKind33 } from "drizzle-orm/entity";
2208
+ import { SelectionProxyHandler as SelectionProxyHandler4 } from "drizzle-orm/selection-proxy";
2209
+ import { sql as sql6 } from "drizzle-orm/sql/sql";
2210
+ import { WithSubquery as WithSubquery2 } from "drizzle-orm/subquery";
2211
+
2212
+ // src/databend-core/query-builders/count.ts
2213
+ import { entityKind as entityKind27 } from "drizzle-orm/entity";
2214
+ import { SQL as SQL5, sql as sql5 } from "drizzle-orm/sql/sql";
2215
+ var DatabendCountBuilder = class _DatabendCountBuilder extends SQL5 {
2216
+ static [entityKind27] = "DatabendCountBuilder";
2217
+ [Symbol.toStringTag] = "DatabendCountBuilder";
2218
+ sql;
2219
+ session;
2220
+ constructor(params) {
2221
+ super(_DatabendCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
2222
+ this.mapWith(Number);
2223
+ this.session = params.session;
2224
+ this.sql = _DatabendCountBuilder.buildCount(params.source, params.filters);
279
2225
  }
280
- async migrate(migrations, session, config) {
281
- const migrationConfig = typeof config === "string" ? { migrationsFolder: config } : config;
282
- const migrationsSchema = migrationConfig.migrationsSchema ?? "default";
283
- const migrationsTable = migrationConfig.migrationsTable ?? "__drizzle_migrations";
284
- const migrationTableCreate = sql`
285
- CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(
286
- migrationsTable
287
- )} (
288
- id INT NOT NULL,
289
- hash VARCHAR NOT NULL,
290
- created_at BIGINT
291
- )
292
- `;
293
- await session.execute(migrationTableCreate);
294
- const dbMigrations = await session.all(
295
- sql`SELECT id, hash, created_at FROM ${sql.identifier(
296
- migrationsSchema
297
- )}.${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
2226
+ static buildEmbeddedCount(source, filters) {
2227
+ return sql5`(select count(*) from ${source}${sql5.raw(" where ").if(filters)}${filters})`;
2228
+ }
2229
+ static buildCount(source, filters) {
2230
+ return sql5`select count(*) as count from ${source}${sql5.raw(" where ").if(filters)}${filters};`;
2231
+ }
2232
+ // biome-ignore lint/suspicious/noThenProperty: Promise-like interface required for await support
2233
+ then(onfulfilled, onrejected) {
2234
+ return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
2235
+ }
2236
+ catch(onRejected) {
2237
+ return this.then(void 0, onRejected);
2238
+ }
2239
+ finally(onFinally) {
2240
+ return this.then(
2241
+ (value) => {
2242
+ onFinally?.();
2243
+ return value;
2244
+ },
2245
+ (reason) => {
2246
+ onFinally?.();
2247
+ throw reason;
2248
+ }
298
2249
  );
299
- const lastDbMigration = dbMigrations[0];
300
- await session.transaction(async (tx) => {
301
- for await (const migration of migrations) {
302
- if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
303
- for (const stmt of migration.sql) {
304
- await tx.execute(sql.raw(stmt));
305
- }
306
- await tx.execute(
307
- sql`INSERT INTO ${sql.identifier(
308
- migrationsSchema
309
- )}.${sql.identifier(migrationsTable)} (id, hash, created_at)
310
- VALUES (
311
- (SELECT COALESCE(MAX(id), 0) + 1 FROM ${sql.identifier(
312
- migrationsSchema
313
- )}.${sql.identifier(migrationsTable)}),
314
- ${migration.hash},
315
- ${migration.folderMillis}
316
- )`
2250
+ }
2251
+ };
2252
+
2253
+ // src/databend-core/query-builders/delete.ts
2254
+ import { entityKind as entityKind28 } from "drizzle-orm/entity";
2255
+ import { QueryPromise as QueryPromise2 } from "drizzle-orm/query-promise";
2256
+ import { tracer as tracer2 } from "drizzle-orm/tracing";
2257
+ var DatabendDeleteBase = class extends QueryPromise2 {
2258
+ constructor(table, session, dialect, withList) {
2259
+ super();
2260
+ this.session = session;
2261
+ this.dialect = dialect;
2262
+ this.config = { table, withList };
2263
+ }
2264
+ static [entityKind28] = "DatabendDelete";
2265
+ config;
2266
+ where(where) {
2267
+ this.config.where = where;
2268
+ return this;
2269
+ }
2270
+ /** @internal */
2271
+ getSQL() {
2272
+ return this.dialect.buildDeleteQuery(this.config);
2273
+ }
2274
+ toSQL() {
2275
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2276
+ return rest;
2277
+ }
2278
+ /** @internal */
2279
+ _prepare(name) {
2280
+ return tracer2.startActiveSpan("drizzle.prepareQuery", () => {
2281
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
2282
+ });
2283
+ }
2284
+ prepare(name) {
2285
+ return this._prepare(name);
2286
+ }
2287
+ execute = (placeholderValues) => {
2288
+ return tracer2.startActiveSpan("drizzle.operation", () => {
2289
+ return this._prepare().execute(placeholderValues);
2290
+ });
2291
+ };
2292
+ $dynamic() {
2293
+ return this;
2294
+ }
2295
+ };
2296
+
2297
+ // src/databend-core/query-builders/insert.ts
2298
+ import { entityKind as entityKind29, is as is8 } from "drizzle-orm/entity";
2299
+ import { QueryPromise as QueryPromise3 } from "drizzle-orm/query-promise";
2300
+ import { Param as Param2, SQL as SQL6 } from "drizzle-orm/sql/sql";
2301
+ import { Table as Table5 } from "drizzle-orm/table";
2302
+ import { tracer as tracer3 } from "drizzle-orm/tracing";
2303
+ import { haveSameKeys as haveSameKeys2 } from "drizzle-orm/utils";
2304
+ var DatabendInsertBuilder = class {
2305
+ constructor(table, session, dialect, withList) {
2306
+ this.table = table;
2307
+ this.session = session;
2308
+ this.dialect = dialect;
2309
+ this.withList = withList;
2310
+ }
2311
+ static [entityKind29] = "DatabendInsertBuilder";
2312
+ values(values) {
2313
+ values = Array.isArray(values) ? values : [values];
2314
+ if (values.length === 0) {
2315
+ throw new Error("values() must be called with at least one value");
2316
+ }
2317
+ const mappedValues = values.map((entry) => {
2318
+ const result = {};
2319
+ const cols = this.table[Table5.Symbol.Columns];
2320
+ for (const colKey of Object.keys(entry)) {
2321
+ const colValue = entry[colKey];
2322
+ result[colKey] = is8(colValue, SQL6) ? colValue : new Param2(colValue, cols[colKey]);
2323
+ }
2324
+ return result;
2325
+ });
2326
+ return new DatabendInsertBase(
2327
+ this.table,
2328
+ mappedValues,
2329
+ this.session,
2330
+ this.dialect,
2331
+ this.withList,
2332
+ false
2333
+ );
2334
+ }
2335
+ select(selectQuery) {
2336
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
2337
+ if (!is8(select, SQL6) && !haveSameKeys2(this.table[Table5.Symbol.Columns], select._.selectedFields)) {
2338
+ throw new Error(
2339
+ "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
2340
+ );
2341
+ }
2342
+ return new DatabendInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
2343
+ }
2344
+ };
2345
+ var DatabendInsertBase = class extends QueryPromise3 {
2346
+ constructor(table, values, session, dialect, withList, select) {
2347
+ super();
2348
+ this.session = session;
2349
+ this.dialect = dialect;
2350
+ this.config = { table, values, withList, select };
2351
+ }
2352
+ static [entityKind29] = "DatabendInsert";
2353
+ config;
2354
+ /** @internal */
2355
+ getSQL() {
2356
+ return this.dialect.buildInsertQuery(this.config);
2357
+ }
2358
+ toSQL() {
2359
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2360
+ return rest;
2361
+ }
2362
+ /** @internal */
2363
+ _prepare(name) {
2364
+ return tracer3.startActiveSpan("drizzle.prepareQuery", () => {
2365
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
2366
+ });
2367
+ }
2368
+ prepare(name) {
2369
+ return this._prepare(name);
2370
+ }
2371
+ execute = (placeholderValues) => {
2372
+ return tracer3.startActiveSpan("drizzle.operation", () => {
2373
+ return this._prepare().execute(placeholderValues);
2374
+ });
2375
+ };
2376
+ $dynamic() {
2377
+ return this;
2378
+ }
2379
+ };
2380
+
2381
+ // src/databend-core/query-builders/update.ts
2382
+ import { entityKind as entityKind30 } from "drizzle-orm/entity";
2383
+ import { QueryPromise as QueryPromise4 } from "drizzle-orm/query-promise";
2384
+ import "drizzle-orm/sql/sql";
2385
+ import "drizzle-orm/table";
2386
+ import { tracer as tracer4 } from "drizzle-orm/tracing";
2387
+ import { mapUpdateSet } from "drizzle-orm/utils";
2388
+ var DatabendUpdateBuilder = class {
2389
+ constructor(table, session, dialect, withList) {
2390
+ this.table = table;
2391
+ this.session = session;
2392
+ this.dialect = dialect;
2393
+ this.withList = withList;
2394
+ }
2395
+ static [entityKind30] = "DatabendUpdateBuilder";
2396
+ set(values) {
2397
+ return new DatabendUpdateBase(
2398
+ this.table,
2399
+ mapUpdateSet(this.table, values),
2400
+ this.session,
2401
+ this.dialect,
2402
+ this.withList
2403
+ );
2404
+ }
2405
+ };
2406
+ var DatabendUpdateBase = class extends QueryPromise4 {
2407
+ constructor(table, set, session, dialect, withList) {
2408
+ super();
2409
+ this.session = session;
2410
+ this.dialect = dialect;
2411
+ this.config = { set, table, withList };
2412
+ }
2413
+ static [entityKind30] = "DatabendUpdate";
2414
+ config;
2415
+ where(where) {
2416
+ this.config.where = where;
2417
+ return this;
2418
+ }
2419
+ /** @internal */
2420
+ getSQL() {
2421
+ return this.dialect.buildUpdateQuery(this.config);
2422
+ }
2423
+ toSQL() {
2424
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2425
+ return rest;
2426
+ }
2427
+ /** @internal */
2428
+ _prepare(name) {
2429
+ return tracer4.startActiveSpan("drizzle.prepareQuery", () => {
2430
+ return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
2431
+ });
2432
+ }
2433
+ prepare(name) {
2434
+ return this._prepare(name);
2435
+ }
2436
+ execute = (placeholderValues) => {
2437
+ return tracer4.startActiveSpan("drizzle.operation", () => {
2438
+ return this._prepare().execute(placeholderValues);
2439
+ });
2440
+ };
2441
+ $dynamic() {
2442
+ return this;
2443
+ }
2444
+ };
2445
+
2446
+ // src/databend-core/query-builders/query.ts
2447
+ import { entityKind as entityKind31 } from "drizzle-orm/entity";
2448
+ import { QueryPromise as QueryPromise5 } from "drizzle-orm/query-promise";
2449
+ import { mapRelationalRow } from "drizzle-orm/relations";
2450
+ import { tracer as tracer5 } from "drizzle-orm/tracing";
2451
+ var RelationalQueryBuilder = class {
2452
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
2453
+ this.fullSchema = fullSchema;
2454
+ this.schema = schema;
2455
+ this.tableNamesMap = tableNamesMap;
2456
+ this.table = table;
2457
+ this.tableConfig = tableConfig;
2458
+ this.dialect = dialect;
2459
+ this.session = session;
2460
+ }
2461
+ static [entityKind31] = "DatabendRelationalQueryBuilder";
2462
+ findMany(config) {
2463
+ return new DatabendRelationalQuery(
2464
+ this.fullSchema,
2465
+ this.schema,
2466
+ this.tableNamesMap,
2467
+ this.table,
2468
+ this.tableConfig,
2469
+ this.dialect,
2470
+ this.session,
2471
+ config ? config : {},
2472
+ "many"
2473
+ );
2474
+ }
2475
+ findFirst(config) {
2476
+ return new DatabendRelationalQuery(
2477
+ this.fullSchema,
2478
+ this.schema,
2479
+ this.tableNamesMap,
2480
+ this.table,
2481
+ this.tableConfig,
2482
+ this.dialect,
2483
+ this.session,
2484
+ config ? { ...config, limit: 1 } : { limit: 1 },
2485
+ "first"
2486
+ );
2487
+ }
2488
+ };
2489
+ var DatabendRelationalQuery = class extends QueryPromise5 {
2490
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
2491
+ super();
2492
+ this.fullSchema = fullSchema;
2493
+ this.schema = schema;
2494
+ this.tableNamesMap = tableNamesMap;
2495
+ this.table = table;
2496
+ this.tableConfig = tableConfig;
2497
+ this.dialect = dialect;
2498
+ this.session = session;
2499
+ this.config = config;
2500
+ this.mode = mode;
2501
+ }
2502
+ static [entityKind31] = "DatabendRelationalQuery";
2503
+ /** @internal */
2504
+ _prepare(name) {
2505
+ return tracer5.startActiveSpan("drizzle.prepareQuery", () => {
2506
+ const { query, builtQuery } = this._toSQL();
2507
+ return this.session.prepareQuery(
2508
+ builtQuery,
2509
+ void 0,
2510
+ name,
2511
+ true,
2512
+ (rawRows, mapColumnValue) => {
2513
+ const rows = rawRows.map(
2514
+ (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
317
2515
  );
2516
+ if (this.mode === "first") {
2517
+ return rows[0];
2518
+ }
2519
+ return rows;
318
2520
  }
319
- }
2521
+ );
320
2522
  });
321
2523
  }
322
- prepareTyping(encoder) {
323
- if (is(encoder, PgNumeric) || is(encoder, PgInteger) || is(encoder, PgSmallInt) || is(encoder, PgReal) || is(encoder, PgDoublePrecision) || is(encoder, PgBigInt53) || is(encoder, PgBigInt64)) {
324
- return "decimal";
325
- } else if (is(encoder, PgTime)) {
326
- return "time";
327
- } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
328
- return "timestamp";
329
- } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
330
- return "date";
331
- } else if (is(encoder, PgUUID)) {
332
- return "uuid";
333
- } else {
334
- return "none";
2524
+ prepare(name) {
2525
+ return this._prepare(name);
2526
+ }
2527
+ _getQuery() {
2528
+ return this.dialect.buildRelationalQueryWithoutPK({
2529
+ fullSchema: this.fullSchema,
2530
+ schema: this.schema,
2531
+ tableNamesMap: this.tableNamesMap,
2532
+ table: this.table,
2533
+ tableConfig: this.tableConfig,
2534
+ queryConfig: this.config,
2535
+ tableAlias: this.tableConfig.tsName
2536
+ });
2537
+ }
2538
+ /** @internal */
2539
+ getSQL() {
2540
+ return this._getQuery().sql;
2541
+ }
2542
+ _toSQL() {
2543
+ const query = this._getQuery();
2544
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
2545
+ return { query, builtQuery };
2546
+ }
2547
+ toSQL() {
2548
+ return this._toSQL().builtQuery;
2549
+ }
2550
+ execute() {
2551
+ return tracer5.startActiveSpan("drizzle.operation", () => {
2552
+ return this._prepare().execute(void 0);
2553
+ });
2554
+ }
2555
+ };
2556
+
2557
+ // src/databend-core/query-builders/raw.ts
2558
+ import { entityKind as entityKind32 } from "drizzle-orm/entity";
2559
+ import { QueryPromise as QueryPromise6 } from "drizzle-orm/query-promise";
2560
+ var DatabendRaw = class extends QueryPromise6 {
2561
+ constructor(execute, sql8, query, mapBatchResult) {
2562
+ super();
2563
+ this.execute = execute;
2564
+ this.sql = sql8;
2565
+ this.query = query;
2566
+ this.mapBatchResult = mapBatchResult;
2567
+ }
2568
+ static [entityKind32] = "DatabendRaw";
2569
+ /** @internal */
2570
+ getSQL() {
2571
+ return this.sql;
2572
+ }
2573
+ getQuery() {
2574
+ return this.query;
2575
+ }
2576
+ mapResult(result, isFromBatch) {
2577
+ return isFromBatch ? this.mapBatchResult(result) : result;
2578
+ }
2579
+ _prepare() {
2580
+ return this;
2581
+ }
2582
+ /** @internal */
2583
+ isResponseInArrayMode() {
2584
+ return false;
2585
+ }
2586
+ };
2587
+
2588
+ // src/databend-core/db.ts
2589
+ var DatabendDatabase = class {
2590
+ constructor(dialect, session, schema) {
2591
+ this.dialect = dialect;
2592
+ this.session = session;
2593
+ this._ = schema ? {
2594
+ schema: schema.schema,
2595
+ fullSchema: schema.fullSchema,
2596
+ tableNamesMap: schema.tableNamesMap,
2597
+ session
2598
+ } : {
2599
+ schema: void 0,
2600
+ fullSchema: {},
2601
+ tableNamesMap: {},
2602
+ session
2603
+ };
2604
+ this.query = {};
2605
+ if (this._.schema) {
2606
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
2607
+ this.query[tableName] = new RelationalQueryBuilder(
2608
+ schema.fullSchema,
2609
+ this._.schema,
2610
+ this._.tableNamesMap,
2611
+ schema.fullSchema[tableName],
2612
+ columns,
2613
+ dialect,
2614
+ session
2615
+ );
2616
+ }
2617
+ }
2618
+ }
2619
+ static [entityKind33] = "DatabendDatabase";
2620
+ _;
2621
+ query;
2622
+ $with(alias2) {
2623
+ const self = this;
2624
+ return {
2625
+ as(qb) {
2626
+ if (typeof qb === "function") {
2627
+ qb = qb(new QueryBuilder(self.dialect));
2628
+ }
2629
+ const sqlObj = typeof qb.getSQL === "function" ? qb.getSQL() : qb;
2630
+ const fields = typeof qb.getSelectedFields === "function" ? qb.getSelectedFields() : {};
2631
+ return new Proxy(
2632
+ new WithSubquery2(sqlObj, fields, alias2, true),
2633
+ new SelectionProxyHandler4({ alias: alias2, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
2634
+ );
2635
+ }
2636
+ };
2637
+ }
2638
+ $count(source, filters) {
2639
+ return new DatabendCountBuilder({ source, filters, session: this.session });
2640
+ }
2641
+ with(...queries) {
2642
+ const self = this;
2643
+ function select(fields) {
2644
+ return new DatabendSelectBuilder({
2645
+ fields: fields ?? void 0,
2646
+ session: self.session,
2647
+ dialect: self.dialect,
2648
+ withList: queries
2649
+ });
335
2650
  }
2651
+ function selectDistinct(fields) {
2652
+ return new DatabendSelectBuilder({
2653
+ fields: fields ?? void 0,
2654
+ session: self.session,
2655
+ dialect: self.dialect,
2656
+ withList: queries,
2657
+ distinct: true
2658
+ });
2659
+ }
2660
+ function update(table) {
2661
+ return new DatabendUpdateBuilder(table, self.session, self.dialect, queries);
2662
+ }
2663
+ function insert(table) {
2664
+ return new DatabendInsertBuilder(table, self.session, self.dialect, queries);
2665
+ }
2666
+ function delete_(table) {
2667
+ return new DatabendDeleteBase(table, self.session, self.dialect, queries);
2668
+ }
2669
+ return { select, selectDistinct, update, insert, delete: delete_ };
2670
+ }
2671
+ select(fields) {
2672
+ return new DatabendSelectBuilder({
2673
+ fields: fields ?? void 0,
2674
+ session: this.session,
2675
+ dialect: this.dialect
2676
+ });
2677
+ }
2678
+ selectDistinct(fields) {
2679
+ return new DatabendSelectBuilder({
2680
+ fields: fields ?? void 0,
2681
+ session: this.session,
2682
+ dialect: this.dialect,
2683
+ distinct: true
2684
+ });
2685
+ }
2686
+ update(table) {
2687
+ return new DatabendUpdateBuilder(table, this.session, this.dialect);
2688
+ }
2689
+ insert(table) {
2690
+ return new DatabendInsertBuilder(table, this.session, this.dialect);
2691
+ }
2692
+ delete(table) {
2693
+ return new DatabendDeleteBase(table, this.session, this.dialect);
2694
+ }
2695
+ execute(query) {
2696
+ const sequel = typeof query === "string" ? sql6.raw(query) : query.getSQL();
2697
+ const builtQuery = this.dialect.sqlToQuery(sequel);
2698
+ const prepared = this.session.prepareQuery(builtQuery, void 0, void 0, false);
2699
+ return new DatabendRaw(
2700
+ () => prepared.execute(void 0),
2701
+ sequel,
2702
+ builtQuery,
2703
+ (result) => prepared.mapResult(result, true)
2704
+ );
2705
+ }
2706
+ transaction(transaction) {
2707
+ return this.session.transaction(transaction);
336
2708
  }
337
2709
  };
338
2710
 
@@ -501,54 +2873,97 @@ function createDatabendConnectionPool(client, options = {}) {
501
2873
  }
502
2874
 
503
2875
  // src/session.ts
504
- import { entityKind as entityKind2 } from "drizzle-orm/entity";
505
- import { TransactionRollbackError } from "drizzle-orm/errors";
2876
+ import { entityKind as entityKind35 } from "drizzle-orm/entity";
2877
+ import { TransactionRollbackError as TransactionRollbackError2 } from "drizzle-orm/errors";
506
2878
  import { NoopLogger } from "drizzle-orm/logger";
507
- import { PgTransaction } from "drizzle-orm/pg-core";
508
- import { PgPreparedQuery, PgSession } from "drizzle-orm/pg-core/session";
509
- import { fillPlaceholders, sql as sql2 } from "drizzle-orm/sql/sql";
2879
+ import { fillPlaceholders, sql as sql7 } from "drizzle-orm/sql/sql";
2880
+
2881
+ // src/databend-core/session.ts
2882
+ import { entityKind as entityKind34 } from "drizzle-orm/entity";
2883
+ import { TransactionRollbackError } from "drizzle-orm/errors";
2884
+ import { tracer as tracer6 } from "drizzle-orm/tracing";
2885
+ var DatabendPreparedQuery = class {
2886
+ constructor(query) {
2887
+ this.query = query;
2888
+ }
2889
+ static [entityKind34] = "DatabendPreparedQuery";
2890
+ /** @internal */
2891
+ joinsNotNullableMap;
2892
+ getQuery() {
2893
+ return this.query;
2894
+ }
2895
+ mapResult(response, _isFromBatch) {
2896
+ return response;
2897
+ }
2898
+ };
2899
+ var DatabendSession = class {
2900
+ constructor(dialect) {
2901
+ this.dialect = dialect;
2902
+ }
2903
+ static [entityKind34] = "DatabendSession";
2904
+ execute(query) {
2905
+ return tracer6.startActiveSpan("drizzle.operation", () => {
2906
+ const prepared = tracer6.startActiveSpan("drizzle.prepareQuery", () => {
2907
+ return this.prepareQuery(
2908
+ this.dialect.sqlToQuery(query),
2909
+ void 0,
2910
+ void 0,
2911
+ false
2912
+ );
2913
+ });
2914
+ return prepared.execute(void 0);
2915
+ });
2916
+ }
2917
+ all(query) {
2918
+ return this.prepareQuery(
2919
+ this.dialect.sqlToQuery(query),
2920
+ void 0,
2921
+ void 0,
2922
+ false
2923
+ ).all();
2924
+ }
2925
+ async count(sql8) {
2926
+ const res = await this.execute(sql8);
2927
+ return Number(res[0]["count"]);
2928
+ }
2929
+ prepareQuery(_query, _fields, _name, _isResponseInArrayMode, _customResultMapper) {
2930
+ throw new Error("prepareQuery not implemented");
2931
+ }
2932
+ transaction(_transaction, _config) {
2933
+ throw new Error("transaction not implemented");
2934
+ }
2935
+ };
2936
+ var DatabendTransaction = class extends DatabendDatabase {
2937
+ constructor(dialect, session, schema, nestedIndex = 0) {
2938
+ super(dialect, session, schema);
2939
+ this.nestedIndex = nestedIndex;
2940
+ this.schema = schema;
2941
+ }
2942
+ static [entityKind34] = "DatabendTransaction";
2943
+ rollback() {
2944
+ throw new TransactionRollbackError();
2945
+ }
2946
+ };
510
2947
 
511
2948
  // src/sql/result-mapper.ts
512
2949
  import {
513
- Column,
514
- getTableName,
515
- is as is2,
516
- SQL
2950
+ Column as Column3,
2951
+ getTableName as getTableName2,
2952
+ is as is10,
2953
+ SQL as SQL8
517
2954
  } from "drizzle-orm";
518
- import {
519
- PgCustomColumn,
520
- PgDate as PgDate2,
521
- PgDateString as PgDateString2,
522
- PgTime as PgTime2,
523
- PgTimestamp as PgTimestamp2,
524
- PgTimestampString as PgTimestampString2
525
- } from "drizzle-orm/pg-core";
526
2955
  function toDecoderInput(decoder, value) {
527
2956
  void decoder;
528
2957
  return value;
529
2958
  }
530
- function normalizeTimestampString(value, withTimezone) {
531
- if (value instanceof Date) {
532
- const iso = value.toISOString().replace("T", " ");
533
- return withTimezone ? iso.replace("Z", "+00") : iso.replace("Z", "");
534
- }
535
- if (typeof value === "string") {
536
- const normalized = value.replace("T", " ");
537
- if (withTimezone) {
538
- return normalized.includes("+") ? normalized : `${normalized}+00`;
539
- }
540
- return normalized.replace(/\+00$/, "");
541
- }
542
- return value;
543
- }
544
- function normalizeTimestamp(value, withTimezone) {
2959
+ function normalizeTimestamp(value, _withTimezone) {
545
2960
  if (value instanceof Date) {
546
2961
  return value;
547
2962
  }
548
2963
  if (typeof value === "string") {
549
2964
  const hasOffset = value.endsWith("Z") || /[+-]\d{2}:?\d{2}$/.test(value.trim());
550
2965
  const spaced = value.replace(" ", "T");
551
- const normalized = withTimezone || hasOffset ? spaced : `${spaced}+00`;
2966
+ const normalized = hasOffset ? spaced : `${spaced}Z`;
552
2967
  return new Date(normalized);
553
2968
  }
554
2969
  return value;
@@ -562,57 +2977,19 @@ function normalizeDateString(value) {
562
2977
  }
563
2978
  return value;
564
2979
  }
565
- function normalizeDateValue(value) {
566
- if (value instanceof Date) {
567
- return value;
568
- }
569
- if (typeof value === "string") {
570
- return /* @__PURE__ */ new Date(`${value.slice(0, 10)}T00:00:00Z`);
571
- }
572
- return value;
573
- }
574
- function normalizeTime(value) {
575
- if (typeof value === "bigint") {
576
- const totalMillis = Number(value) / 1e3;
577
- const date = new Date(totalMillis);
578
- return date.toISOString().split("T")[1].replace("Z", "");
579
- }
580
- if (value instanceof Date) {
581
- return value.toISOString().split("T")[1].replace("Z", "");
582
- }
583
- return value;
584
- }
585
2980
  function mapDriverValue(decoder, rawValue) {
586
- if (is2(decoder, PgTimestampString2)) {
587
- return decoder.mapFromDriverValue(
588
- toDecoderInput(
589
- decoder,
590
- normalizeTimestampString(rawValue, decoder.withTimezone)
591
- )
592
- );
593
- }
594
- if (is2(decoder, PgTimestamp2)) {
595
- const normalized = normalizeTimestamp(rawValue, decoder.withTimezone);
2981
+ if (is10(decoder, DatabendTimestamp)) {
2982
+ const normalized = normalizeTimestamp(rawValue, false);
596
2983
  if (normalized instanceof Date) {
597
2984
  return normalized;
598
2985
  }
599
2986
  return decoder.mapFromDriverValue(toDecoderInput(decoder, normalized));
600
2987
  }
601
- if (is2(decoder, PgDateString2)) {
2988
+ if (is10(decoder, DatabendDate)) {
602
2989
  return decoder.mapFromDriverValue(
603
2990
  toDecoderInput(decoder, normalizeDateString(rawValue))
604
2991
  );
605
2992
  }
606
- if (is2(decoder, PgDate2)) {
607
- return decoder.mapFromDriverValue(
608
- toDecoderInput(decoder, normalizeDateValue(rawValue))
609
- );
610
- }
611
- if (is2(decoder, PgTime2)) {
612
- return decoder.mapFromDriverValue(
613
- toDecoderInput(decoder, normalizeTime(rawValue))
614
- );
615
- }
616
2993
  return decoder.mapFromDriverValue(toDecoderInput(decoder, rawValue));
617
2994
  }
618
2995
  function mapResultRow(columns, row, joinsNotNullableMap) {
@@ -620,13 +2997,13 @@ function mapResultRow(columns, row, joinsNotNullableMap) {
620
2997
  const result = columns.reduce(
621
2998
  (acc, { path, field }, columnIndex) => {
622
2999
  let decoder;
623
- if (is2(field, Column)) {
3000
+ if (is10(field, Column3)) {
624
3001
  decoder = field;
625
- } else if (is2(field, SQL)) {
3002
+ } else if (is10(field, SQL8)) {
626
3003
  decoder = field.decoder;
627
3004
  } else {
628
- const col = field.sql.queryChunks.find((chunk) => is2(chunk, Column));
629
- if (is2(col, PgCustomColumn)) {
3005
+ const col = field.sql.queryChunks.find((chunk) => is10(chunk, Column3));
3006
+ if (is10(col, DatabendCustomColumn)) {
630
3007
  decoder = col;
631
3008
  } else {
632
3009
  decoder = field.sql.decoder;
@@ -643,18 +3020,18 @@ function mapResultRow(columns, row, joinsNotNullableMap) {
643
3020
  }
644
3021
  const rawValue = row[columnIndex];
645
3022
  const value = node[pathChunk] = rawValue === null ? null : mapDriverValue(decoder, rawValue);
646
- if (joinsNotNullableMap && is2(field, Column) && path.length === 2) {
3023
+ if (joinsNotNullableMap && is10(field, Column3) && path.length === 2) {
647
3024
  const objectName = path[0];
648
3025
  if (!(objectName in nullifyMap)) {
649
- nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
650
- } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
3026
+ nullifyMap[objectName] = value === null ? getTableName2(field.table) : false;
3027
+ } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName2(field.table)) {
651
3028
  nullifyMap[objectName] = false;
652
3029
  }
653
3030
  continue;
654
3031
  }
655
- if (joinsNotNullableMap && is2(field, SQL.Aliased) && path.length === 2) {
656
- const col = field.sql.queryChunks.find((chunk) => is2(chunk, Column));
657
- const tableName = col?.table && getTableName(col?.table);
3032
+ if (joinsNotNullableMap && is10(field, SQL8.Aliased) && path.length === 2) {
3033
+ const col = field.sql.queryChunks.find((chunk) => is10(chunk, Column3));
3034
+ const tableName = col?.table && getTableName2(col?.table);
658
3035
  if (!tableName) {
659
3036
  continue;
660
3037
  }
@@ -683,7 +3060,7 @@ function mapResultRow(columns, row, joinsNotNullableMap) {
683
3060
  }
684
3061
 
685
3062
  // src/session.ts
686
- var DatabendPreparedQuery = class extends PgPreparedQuery {
3063
+ var DatabendPreparedQuery2 = class extends DatabendPreparedQuery {
687
3064
  constructor(client, queryString, params, logger, fields, _isResponseInArrayMode, customResultMapper, typings) {
688
3065
  super({ sql: queryString, params });
689
3066
  this.client = client;
@@ -695,7 +3072,7 @@ var DatabendPreparedQuery = class extends PgPreparedQuery {
695
3072
  this.customResultMapper = customResultMapper;
696
3073
  this.typings = typings;
697
3074
  }
698
- static [entityKind2] = "DatabendPreparedQuery";
3075
+ static [entityKind35] = "DatabendPreparedQuery";
699
3076
  async execute(placeholderValues = {}) {
700
3077
  const params = fillPlaceholders(this.params, placeholderValues);
701
3078
  this.logger.logQuery(this.queryString, params);
@@ -724,7 +3101,7 @@ var DatabendPreparedQuery = class extends PgPreparedQuery {
724
3101
  return this._isResponseInArrayMode;
725
3102
  }
726
3103
  };
727
- var DatabendSession = class _DatabendSession extends PgSession {
3104
+ var DatabendSession2 = class _DatabendSession extends DatabendSession {
728
3105
  constructor(client, dialect, schema, options = {}) {
729
3106
  super(dialect);
730
3107
  this.client = client;
@@ -733,13 +3110,13 @@ var DatabendSession = class _DatabendSession extends PgSession {
733
3110
  this.dialect = dialect;
734
3111
  this.logger = options.logger ?? new NoopLogger();
735
3112
  }
736
- static [entityKind2] = "DatabendSession";
3113
+ static [entityKind35] = "DatabendSession";
737
3114
  dialect;
738
3115
  logger;
739
3116
  rollbackOnly = false;
740
3117
  prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper) {
741
3118
  void name;
742
- return new DatabendPreparedQuery(
3119
+ return new DatabendPreparedQuery2(
743
3120
  this.client,
744
3121
  query.sql,
745
3122
  query.params,
@@ -765,26 +3142,26 @@ var DatabendSession = class _DatabendSession extends PgSession {
765
3142
  this.schema,
766
3143
  this.options
767
3144
  );
768
- const tx = new DatabendTransaction(
3145
+ const tx = new DatabendTransaction2(
769
3146
  this.dialect,
770
3147
  session,
771
3148
  this.schema
772
3149
  );
773
3150
  try {
774
- await tx.execute(sql2`BEGIN`);
3151
+ await tx.execute(sql7`BEGIN`);
775
3152
  if (config) {
776
3153
  await tx.setTransaction(config);
777
3154
  }
778
3155
  try {
779
3156
  const result = await transaction(tx);
780
3157
  if (session.isRollbackOnly()) {
781
- await tx.execute(sql2`ROLLBACK`);
782
- throw new TransactionRollbackError();
3158
+ await tx.execute(sql7`ROLLBACK`);
3159
+ throw new TransactionRollbackError2();
783
3160
  }
784
- await tx.execute(sql2`COMMIT`);
3161
+ await tx.execute(sql7`COMMIT`);
785
3162
  return result;
786
3163
  } catch (error) {
787
- await tx.execute(sql2`ROLLBACK`);
3164
+ await tx.execute(sql7`ROLLBACK`);
788
3165
  throw error;
789
3166
  }
790
3167
  } finally {
@@ -810,10 +3187,10 @@ var VALID_TRANSACTION_ACCESS_MODES = /* @__PURE__ */ new Set([
810
3187
  "read only",
811
3188
  "read write"
812
3189
  ]);
813
- var DatabendTransaction = class _DatabendTransaction extends PgTransaction {
814
- static [entityKind2] = "DatabendTransaction";
3190
+ var DatabendTransaction2 = class _DatabendTransaction extends DatabendTransaction {
3191
+ static [entityKind35] = "DatabendTransaction";
815
3192
  rollback() {
816
- throw new TransactionRollbackError();
3193
+ throw new TransactionRollbackError2();
817
3194
  }
818
3195
  getTransactionConfigSQL(config) {
819
3196
  if (config.isolationLevel && !VALID_TRANSACTION_ISOLATION_LEVELS.has(config.isolationLevel)) {
@@ -837,11 +3214,11 @@ var DatabendTransaction = class _DatabendTransaction extends PgTransaction {
837
3214
  if (config.accessMode) {
838
3215
  chunks.push(config.accessMode);
839
3216
  }
840
- return sql2.raw(chunks.join(" "));
3217
+ return sql7.raw(chunks.join(" "));
841
3218
  }
842
3219
  setTransaction(config) {
843
3220
  return this.session.execute(
844
- sql2`SET TRANSACTION ${this.getTransactionConfigSQL(config)}`
3221
+ sql7`SET TRANSACTION ${this.getTransactionConfigSQL(config)}`
845
3222
  );
846
3223
  }
847
3224
  async transaction(transaction) {
@@ -866,9 +3243,9 @@ var DatabendDriver = class {
866
3243
  this.dialect = dialect;
867
3244
  this.options = options;
868
3245
  }
869
- static [entityKind3] = "DatabendDriver";
3246
+ static [entityKind36] = "DatabendDriver";
870
3247
  createSession(schema) {
871
- return new DatabendSession(this.client, this.dialect, schema, {
3248
+ return new DatabendSession2(this.client, this.dialect, schema, {
872
3249
  logger: this.options.logger
873
3250
  });
874
3251
  }
@@ -895,7 +3272,7 @@ function createFromClient(client, config = {}, databendClient) {
895
3272
  }
896
3273
  const driver = new DatabendDriver(client, dialect, { logger });
897
3274
  const session = driver.createSession(schema);
898
- const db = new DatabendDatabase(
3275
+ const db = new DatabendDatabase2(
899
3276
  dialect,
900
3277
  session,
901
3278
  schema,
@@ -942,7 +3319,7 @@ function drizzle(clientOrConfigOrDsn, config) {
942
3319
  }
943
3320
  return createFromClient(clientOrConfigOrDsn, config);
944
3321
  }
945
- var DatabendDatabase = class extends PgDatabase {
3322
+ var DatabendDatabase2 = class extends DatabendDatabase {
946
3323
  constructor(dialect, session, schema, client, databendClient) {
947
3324
  super(dialect, session, schema);
948
3325
  this.dialect = dialect;
@@ -950,7 +3327,7 @@ var DatabendDatabase = class extends PgDatabase {
950
3327
  this.$client = client;
951
3328
  this.$databendClient = databendClient;
952
3329
  }
953
- static [entityKind3] = "DatabendDatabase";
3330
+ static [entityKind36] = "DatabendDatabase";
954
3331
  /** The underlying connection or pool */
955
3332
  $client;
956
3333
  /** The Databend Client instance (when created from DSN) */
@@ -980,24 +3357,53 @@ async function migrate(db, config) {
980
3357
  );
981
3358
  }
982
3359
  export {
983
- DatabendDatabase,
3360
+ DatabendColumn,
3361
+ DatabendColumnBuilder,
3362
+ DatabendDatabase2 as DatabendDatabase,
3363
+ DatabendDialect,
984
3364
  DatabendDriver,
985
- DatabendPreparedQuery,
986
- DatabendSession,
987
- DatabendTransaction,
3365
+ DatabendPreparedQuery2 as DatabendPreparedQuery,
3366
+ DatabendSession2 as DatabendSession,
3367
+ DatabendTable,
3368
+ DatabendTransaction2 as DatabendTransaction,
3369
+ alias,
3370
+ bigint,
3371
+ binary,
3372
+ bitmap,
3373
+ boolean,
988
3374
  closeClientConnection,
989
3375
  createDatabendConnectionPool,
990
3376
  databendArray,
991
3377
  databendDate,
992
3378
  databendMap,
3379
+ databendSchema,
3380
+ databendTable,
3381
+ databendTableCreator,
993
3382
  databendTimestamp,
994
3383
  databendTuple,
995
3384
  databendVariant,
3385
+ databendView,
3386
+ date,
3387
+ decimal,
3388
+ doublePrecision,
996
3389
  drizzle,
997
3390
  execOnClient,
998
3391
  executeArraysOnClient,
999
3392
  executeOnClient,
3393
+ float,
3394
+ getTableConfig,
3395
+ index,
3396
+ integer,
1000
3397
  isPool,
1001
3398
  migrate,
1002
- prepareParams
3399
+ prepareParams,
3400
+ primaryKey,
3401
+ real,
3402
+ smallint,
3403
+ text,
3404
+ timestamp,
3405
+ tinyint,
3406
+ uniqueIndex,
3407
+ varchar,
3408
+ variant
1003
3409
  };