@leonardovida-md/drizzle-neo-duckdb 2.2.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { entityKind as entityKind3, is as is4 } from "drizzle-orm/entity";
14
14
  import { NoopLogger } from "drizzle-orm/logger";
15
- import { PgArray as PgArray2, PgTransaction } from "drizzle-orm/pg-core";
15
+ import { getTableConfig, PgArray as PgArray2, PgTransaction } from "drizzle-orm/pg-core";
16
16
  import { PgPreparedQuery, PgSession } from "drizzle-orm/pg-core/session";
17
17
  import {
18
18
  fillPlaceholders,
@@ -103,7 +103,7 @@ function arrayBoundsSql(name, arr) {
103
103
  if (name === "array_lower") {
104
104
  return `CASE WHEN array_length(${arr}) > 0 THEN 1 ELSE NULL END`;
105
105
  }
106
- return arr.includes("(") ? `list_extract(list_transform(list_value(array_length(${arr})), __drizzle_array_length -> nullif(__drizzle_array_length, 0)), 1)` : `nullif(array_length(${arr}), 0)`;
106
+ return arr.includes("(") ? `list_extract(list_transform(list_value(array_length(${arr})), lambda __drizzle_array_length: nullif(__drizzle_array_length, 0)), 1)` : `nullif(array_length(${arr}), 0)`;
107
107
  }
108
108
  function rewriteArrayBoundsText(query) {
109
109
  let output = "";
@@ -185,6 +185,16 @@ function assignOwnProperty(target, key, value) {
185
185
 
186
186
  // src/time.ts
187
187
  var MICROS_PER_DAY = 86400000000n;
188
+ var droppedMicros = new WeakMap;
189
+ function rememberDroppedMicros(date, micros) {
190
+ droppedMicros.set(date, micros);
191
+ }
192
+ function dateSubMillisecondMicros(date) {
193
+ return droppedMicros.get(date) ?? 0;
194
+ }
195
+ function dateToMicros(date) {
196
+ return BigInt(date.getTime()) * 1000n + BigInt(dateSubMillisecondMicros(date));
197
+ }
188
198
  function pad(value, length) {
189
199
  return value.toString().padStart(length, "0");
190
200
  }
@@ -397,8 +407,8 @@ function normalizeInet(value) {
397
407
  if (address < 0n || address > 0xffffffffn) {
398
408
  return value;
399
409
  }
400
- const suffix2 = value.mask !== 32 ? `/${value.mask}` : "";
401
- return `${formatIpv4(address)}${suffix2}`;
410
+ const suffix = value.mask !== 32 ? `/${value.mask}` : "";
411
+ return `${formatIpv4(address)}${suffix}`;
402
412
  }
403
413
  const unsigned = address + (1n << 127n);
404
414
  if (unsigned < 0n || unsigned >= 1n << 128n) {
@@ -415,8 +425,10 @@ function normalizeTimestampString(value, withTimezone) {
415
425
  return value;
416
426
  }
417
427
  if (value instanceof Date) {
418
- const iso = value.toISOString().replace("T", " ");
419
- return withTimezone ? iso.replace("Z", "+00") : iso.replace("Z", "");
428
+ const micros = dateSubMillisecondMicros(value);
429
+ const digits = micros ? String(micros).padStart(3, "0").replace(/0+$/, "") : "";
430
+ const iso = value.toISOString().replace("T", " ").replace("Z", digits);
431
+ return withTimezone ? `${iso}+00` : iso;
420
432
  }
421
433
  if (typeof value === "string") {
422
434
  const normalized = value.replace("T", " ");
@@ -442,10 +454,10 @@ function normalizeTimestamp(value, withTimezone) {
442
454
  }
443
455
  function normalizeDateString(value) {
444
456
  if (value instanceof Date) {
445
- return value.toISOString().slice(0, 10);
457
+ return dateStringFromDate(value);
446
458
  }
447
459
  if (typeof value === "string") {
448
- return value.slice(0, 10);
460
+ return value === "infinity" || value === "-infinity" ? value : value.slice(0, 10);
449
461
  }
450
462
  return value;
451
463
  }
@@ -453,6 +465,9 @@ function normalizeDateValue(value) {
453
465
  if (value instanceof Date) {
454
466
  return value;
455
467
  }
468
+ if (isInfiniteTimestamp(value)) {
469
+ return value;
470
+ }
456
471
  if (typeof value === "string") {
457
472
  return new Date(`${value.slice(0, 10)}T00:00:00Z`);
458
473
  }
@@ -470,13 +485,7 @@ function normalizeTime(value) {
470
485
  function normalizeInterval(value) {
471
486
  if (value && typeof value === "object" && "days" in value && "months" in value) {
472
487
  const { months, days, micros } = value;
473
- if (months === 0 && days !== undefined) {
474
- if (micros && Number(micros) !== 0) {
475
- const seconds = Number(micros) / 1e6;
476
- return `${days} day${days === 1 ? "" : "s"} ${seconds} seconds`.trim();
477
- }
478
- return `${days} day${days === 1 ? "" : "s"}`;
479
- }
488
+ return intervalToString(Number(months), Number(days), BigInt(micros ?? 0));
480
489
  }
481
490
  return value;
482
491
  }
@@ -489,20 +498,13 @@ function decodesInet(decoder) {
489
498
  }
490
499
  return true;
491
500
  }
492
- function compileValueMapper(decoder) {
501
+ function compileValueNormalizer(decoder) {
493
502
  const inet = decodesInet(decoder) ? normalizeInet : (value) => value;
494
503
  let normalize = (value) => value;
495
504
  if (is(decoder, PgTimestampString)) {
496
505
  normalize = (value) => normalizeTimestampString(value, decoder.withTimezone);
497
506
  } else if (is(decoder, PgTimestamp)) {
498
- return (value) => {
499
- if (value === null)
500
- return null;
501
- if (isInfiniteTimestamp(value))
502
- return value;
503
- const normalized = normalizeTimestamp(inet(value), decoder.withTimezone);
504
- return normalized instanceof Date ? normalized : decoder.mapFromDriverValue(toDecoderInput(decoder, normalized));
505
- };
507
+ normalize = (value) => isInfiniteTimestamp(value) ? value : normalizeTimestamp(value, decoder.withTimezone);
506
508
  } else if (is(decoder, PgDateString)) {
507
509
  normalize = normalizeDateString;
508
510
  } else if (is(decoder, PgDate)) {
@@ -512,7 +514,30 @@ function compileValueMapper(decoder) {
512
514
  } else if (is(decoder, PgInterval)) {
513
515
  normalize = normalizeInterval;
514
516
  }
515
- return (value) => value === null ? null : decoder.mapFromDriverValue(toDecoderInput(decoder, normalize(inet(value))));
517
+ return (value) => value === null ? null : normalize(inet(value));
518
+ }
519
+ function compileValueMapper(decoder) {
520
+ const normalize = compileValueNormalizer(decoder);
521
+ if (is(decoder, PgTimestamp) || is(decoder, PgDate)) {
522
+ return (value) => {
523
+ const normalized = normalize(value);
524
+ return normalized === null || normalized instanceof Date || isInfiniteTimestamp(normalized) ? normalized : decoder.mapFromDriverValue(toDecoderInput(decoder, normalized));
525
+ };
526
+ }
527
+ return (value) => {
528
+ const normalized = normalize(value);
529
+ return normalized === null ? null : decoder.mapFromDriverValue(toDecoderInput(decoder, normalized));
530
+ };
531
+ }
532
+ function compileRelationalRowNormalizer(selection) {
533
+ const normalizers = selection.map((item) => item.isJson ? undefined : compileValueNormalizer(resolveFieldDecoder(item.field)));
534
+ return (row) => {
535
+ for (let index = 0;index < normalizers.length; index += 1) {
536
+ const normalize = normalizers[index];
537
+ if (normalize)
538
+ row[index] = normalize(row[index]);
539
+ }
540
+ };
516
541
  }
517
542
  function assignResultPath(result, path, value) {
518
543
  if (path.length === 0) {
@@ -659,8 +684,17 @@ function arrayBoundsExpr(functionName, arrayExpr) {
659
684
  call("list_value", [lengthExpr]),
660
685
  {
661
686
  type: "binary_expr",
662
- operator: "->",
663
- left: length,
687
+ operator: ":",
688
+ left: {
689
+ type: "column_ref",
690
+ table: null,
691
+ column: {
692
+ expr: {
693
+ type: "default",
694
+ value: "lambda __drizzle_array_length"
695
+ }
696
+ }
697
+ },
664
698
  right: nullIf(length)
665
699
  }
666
700
  ]),
@@ -1599,20 +1633,20 @@ function scanSqlTokens(query) {
1599
1633
  };
1600
1634
  const readQuoted = (start, quote) => {
1601
1635
  const backslashEscapes = isEscapeStringAt(query, start);
1602
- let index2 = start + 1;
1603
- while (index2 < query.length) {
1604
- if (backslashEscapes && query[index2] === "\\") {
1605
- index2 += 2;
1636
+ let index = start + 1;
1637
+ while (index < query.length) {
1638
+ if (backslashEscapes && query[index] === "\\") {
1639
+ index += 2;
1606
1640
  continue;
1607
1641
  }
1608
- if (query[index2] === quote) {
1609
- if (query[index2 + 1] === quote) {
1610
- index2 += 2;
1642
+ if (query[index] === quote) {
1643
+ if (query[index + 1] === quote) {
1644
+ index += 2;
1611
1645
  continue;
1612
1646
  }
1613
- return index2;
1647
+ return index;
1614
1648
  }
1615
- index2 += 1;
1649
+ index += 1;
1616
1650
  }
1617
1651
  return -1;
1618
1652
  };
@@ -1764,8 +1798,8 @@ function transformSQL(query, options = {}) {
1764
1798
  function rewriteRemainingArrayBounds(result) {
1765
1799
  if (!ARRAY_BOUNDS_PATTERN.test(result.sql))
1766
1800
  return result;
1767
- const sql2 = rewriteArrayBoundsText(result.sql);
1768
- return sql2 === result.sql ? result : { sql: sql2, transformed: true };
1801
+ const sql = rewriteArrayBoundsText(result.sql);
1802
+ return sql === result.sql ? result : { sql, transformed: true };
1769
1803
  }
1770
1804
  function transformWithAst(query, {
1771
1805
  needsArrayTransform,
@@ -1815,6 +1849,10 @@ function transformWithAst(query, {
1815
1849
  // src/dialect.ts
1816
1850
  var PG_JSON_UNSUPPORTED_MESSAGE = "Pg JSON/JSONB columns are not supported in DuckDB. Replace them with duckDbJson() to use DuckDB's native JSON type.";
1817
1851
  var DUCKDB_SCALAR_COLUMN_TYPING = "duckdb:scalar";
1852
+ var relationalSelections = new WeakMap;
1853
+ function relationalSelectionOf(query) {
1854
+ return relationalSelections.get(query);
1855
+ }
1818
1856
  var DUCKDB_ARRAY_COLUMN_TYPING = "duckdb:array";
1819
1857
  var MIGRATION_CONFLICT_MAX_ATTEMPTS = 10;
1820
1858
  var MIGRATION_RETRY_BASE_DELAY_MS = 20;
@@ -1863,6 +1901,7 @@ var RELATIONAL_JSON_CHUNKS = new Map([
1863
1901
  ["), '[]'::json)", ")), '[]'::json)"]
1864
1902
  ]);
1865
1903
  var RELATIONAL_LIMIT_CHUNKS = new Set([" limit ", " offset "]);
1904
+ var EXACT_BIGINT_COLUMN_TYPES = new Set(["PgBigInt64", "PgBigSerial64"]);
1866
1905
  function rewriteRelationalJsonChunks(chunks, exactDecimals = false) {
1867
1906
  for (let index = 0;index < chunks.length; index += 1) {
1868
1907
  const chunk = chunks[index];
@@ -1871,10 +1910,17 @@ function rewriteRelationalJsonChunks(chunks, exactDecimals = false) {
1871
1910
  const replacement = value === undefined ? undefined : RELATIONAL_JSON_CHUNKS.get(value);
1872
1911
  const next = chunks[index + 1];
1873
1912
  if (replacement) {
1874
- if (exactDecimals && value === "json_build_array(" && is2(next, SQL2)) {
1913
+ if (value === "json_build_array(" && is2(next, SQL2)) {
1875
1914
  const fields = next.queryChunks.map((item) => {
1876
- if (!is2(item, Column2))
1915
+ if (!is2(item, Column2)) {
1916
+ return item;
1917
+ }
1918
+ if (EXACT_BIGINT_COLUMN_TYPES.has(item.columnType)) {
1919
+ return sql2`cast(${item} as VARCHAR)`;
1920
+ }
1921
+ if (!exactDecimals && !item.columnType.startsWith("PgNumeric")) {
1877
1922
  return item;
1923
+ }
1878
1924
  const originalType = item.getSQLType();
1879
1925
  const exactType = decimalStringType(originalType);
1880
1926
  return exactType === originalType ? item : sql2`cast(${item} as ${sql2.raw(exactType)})`;
@@ -2032,6 +2078,7 @@ class DuckDBDialect extends PgDialect {
2032
2078
  const result = super.buildRelationalQueryWithoutPK(config);
2033
2079
  if (!config.nestedQueryRelation && is2(result.sql, SQL2)) {
2034
2080
  rewriteRelationalJsonChunks(result.sql.queryChunks, this.options.decimalMode === "string");
2081
+ relationalSelections.set(result.sql, result.selection);
2035
2082
  }
2036
2083
  return result;
2037
2084
  }
@@ -2040,10 +2087,14 @@ class DuckDBDialect extends PgDialect {
2040
2087
  const transformed = transformSQL(result.sql, {
2041
2088
  qualifyJoinColumns: this.options.qualifyRawJoinColumns === true
2042
2089
  });
2043
- return {
2090
+ const query = {
2044
2091
  ...result,
2045
2092
  sql: transformed.sql
2046
2093
  };
2094
+ const selection = relationalSelections.get(sqlObj);
2095
+ if (selection)
2096
+ relationalSelections.set(query, selection);
2097
+ return query;
2047
2098
  }
2048
2099
  }
2049
2100
 
@@ -2054,6 +2105,7 @@ import {
2054
2105
  JSDuckDBValueConverter,
2055
2106
  JsonDuckDBValueConverter,
2056
2107
  listValue as listValue2,
2108
+ TIMESTAMPTZ as TIMESTAMPTZ2,
2057
2109
  timestampTZValue as timestampTZValue2,
2058
2110
  timestampValue as timestampValue2
2059
2111
  } from "@duckdb/node-api";
@@ -2169,7 +2221,7 @@ function wrapJson(data) {
2169
2221
  }
2170
2222
 
2171
2223
  // src/value-wrappers.ts
2172
- function dateToMicros(value) {
2224
+ function dateToMicros2(value) {
2173
2225
  if (value instanceof Date) {
2174
2226
  return dateToEpochMicros(value);
2175
2227
  }
@@ -2227,7 +2279,7 @@ function wrapperToNodeApiValue(wrapper, toValue) {
2227
2279
  return withNodeApiItemTypeHint(mapValue(convertMapEntries(wrapper.data, toValue, valueType)), valueType);
2228
2280
  }
2229
2281
  case "timestamp":
2230
- return wrapper.withTimezone ? timestampTZValue(dateToMicros(wrapper.data)) : timestampValue(dateToMicros(wrapper.data));
2282
+ return wrapper.withTimezone ? timestampTZValue(dateToMicros2(wrapper.data)) : timestampValue(dateToMicros2(wrapper.data));
2231
2283
  case "blob":
2232
2284
  return blobValue(toUint8Array(wrapper.data));
2233
2285
  case "json":
@@ -2635,105 +2687,6 @@ function parsePgArrayLiteral(value) {
2635
2687
 
2636
2688
  // src/prepared-statement-cache.ts
2637
2689
  var PREPARED_CACHE = Symbol.for("drizzle-duckdb:prepared-cache");
2638
- function destroyPreparedStatement(entry) {
2639
- if (!entry)
2640
- return;
2641
- try {
2642
- entry.statement.destroySync();
2643
- } catch {}
2644
- }
2645
-
2646
- class PreparedStatementCache {
2647
- connection;
2648
- size;
2649
- entries = new Map;
2650
- executionTail = Promise.resolve();
2651
- hits = 0;
2652
- misses = 0;
2653
- evictions = 0;
2654
- stats() {
2655
- return {
2656
- size: this.entries.size,
2657
- capacity: this.size,
2658
- hits: this.hits,
2659
- misses: this.misses,
2660
- evictions: this.evictions
2661
- };
2662
- }
2663
- constructor(connection, size) {
2664
- this.connection = connection;
2665
- this.size = size;
2666
- }
2667
- resize(size) {
2668
- this.size = size;
2669
- this.trimToSize();
2670
- }
2671
- async getOrPrepare(query) {
2672
- const cached = this.entries.get(query);
2673
- if (cached) {
2674
- this.hits += 1;
2675
- return this.remember(query, cached.statement);
2676
- }
2677
- this.misses += 1;
2678
- const statement = await this.connection.prepare(query);
2679
- this.remember(query, statement);
2680
- return statement;
2681
- }
2682
- async runExclusive(operation) {
2683
- const previous = this.executionTail;
2684
- let release = () => {};
2685
- this.executionTail = new Promise((resolve) => {
2686
- release = resolve;
2687
- });
2688
- await previous;
2689
- try {
2690
- return await operation();
2691
- } finally {
2692
- release();
2693
- }
2694
- }
2695
- remember(query, statement) {
2696
- this.entries.delete(query);
2697
- this.entries.set(query, { statement });
2698
- this.trimToSize();
2699
- return statement;
2700
- }
2701
- evict(query) {
2702
- const entry = this.entries.get(query);
2703
- if (entry)
2704
- this.evictions += 1;
2705
- this.entries.delete(query);
2706
- destroyPreparedStatement(entry);
2707
- }
2708
- clear() {
2709
- for (const entry of this.entries.values()) {
2710
- destroyPreparedStatement(entry);
2711
- }
2712
- this.entries.clear();
2713
- }
2714
- evictOldest() {
2715
- const oldest = this.entries.keys().next();
2716
- if (!oldest.done) {
2717
- this.evict(oldest.value);
2718
- }
2719
- }
2720
- trimToSize() {
2721
- while (this.entries.size > this.size) {
2722
- this.evictOldest();
2723
- }
2724
- }
2725
- }
2726
- function getPreparedStatementCache(connection, size) {
2727
- const store = connection;
2728
- const existing = store[PREPARED_CACHE];
2729
- if (existing) {
2730
- existing.resize(size);
2731
- return existing;
2732
- }
2733
- const cache = new PreparedStatementCache(connection, size);
2734
- store[PREPARED_CACHE] = cache;
2735
- return cache;
2736
- }
2737
2690
  function clearPreparedStatementCache(connection) {
2738
2691
  const store = connection;
2739
2692
  store[PREPARED_CACHE]?.clear();
@@ -2742,17 +2695,6 @@ function getPreparedStatementCacheStats(connection) {
2742
2695
  const store = connection;
2743
2696
  return store[PREPARED_CACHE]?.stats();
2744
2697
  }
2745
- function bindPreparedStatement(statement, values, types) {
2746
- if (values) {
2747
- if (types) {
2748
- statement.bind(values, types);
2749
- } else {
2750
- statement.bind(values);
2751
- }
2752
- return;
2753
- }
2754
- statement.clearBindings?.();
2755
- }
2756
2698
 
2757
2699
  // src/client.ts
2758
2700
  function isPool(client) {
@@ -2918,14 +2860,16 @@ var NO_NODE_API_PARAMS = {
2918
2860
  values: undefined,
2919
2861
  types: undefined
2920
2862
  };
2921
- function toNodeApiParams(params) {
2863
+ function toNodeApiParams(params, dateParams) {
2922
2864
  if (params.length === 0) {
2923
2865
  return NO_NODE_API_PARAMS;
2924
2866
  }
2867
+ const dateType = dateParams === "timestamptz" ? TIMESTAMPTZ2 : undefined;
2925
2868
  const values = new Array(params.length);
2926
2869
  let types;
2927
2870
  for (let index = 0;index < params.length; index += 1) {
2928
- const value = toNodeApiValue(params[index]);
2871
+ const param = params[index];
2872
+ const value = toNodeApiValue(param, dateType && param instanceof Date ? dateType : undefined);
2929
2873
  values[index] = value;
2930
2874
  if (value !== null && (typeof value === "object" || typeof value === "number" && Number.isInteger(value) && (value > 2147483647 || value < -2147483648))) {
2931
2875
  const typed = typedNodeApiParam(value);
@@ -3068,18 +3012,35 @@ function wrapUnsupportedNodeApiTypeError(result, error) {
3068
3012
  }
3069
3013
  var TIMESTAMP_INFINITY_MICROS = 9223372036854775807n;
3070
3014
  var MAX_DATE_MILLIS = 8640000000000000n;
3015
+ var MAX_SAFE_MICROS = BigInt(Number.MAX_SAFE_INTEGER);
3016
+ var DATE_INFINITY_DAYS = 2147483647;
3071
3017
  function dateFromTimestampUnits(units, unitsPerMilli, typeName) {
3072
3018
  if (units === TIMESTAMP_INFINITY_MICROS)
3073
3019
  return "infinity";
3074
3020
  if (units === -TIMESTAMP_INFINITY_MICROS)
3075
3021
  return "-infinity";
3022
+ if (unitsPerMilli === 1000n && units >= -MAX_SAFE_MICROS && units <= MAX_SAFE_MICROS) {
3023
+ const micros = Number(units);
3024
+ const wholeMillis = Math.floor(micros / 1000);
3025
+ const date = new Date(wholeMillis);
3026
+ const dropped = micros - wholeMillis * 1000;
3027
+ if (dropped !== 0)
3028
+ rememberDroppedMicros(date, dropped);
3029
+ return date;
3030
+ }
3076
3031
  let millis = units / unitsPerMilli;
3077
3032
  if (units % unitsPerMilli < 0n)
3078
3033
  millis -= 1n;
3079
3034
  if (millis < -MAX_DATE_MILLIS || millis > MAX_DATE_MILLIS) {
3080
3035
  throw new Error(`${typeName} value out of range for JS Date: ${units}`);
3081
3036
  }
3082
- return new Date(Number(millis));
3037
+ const date = new Date(Number(millis));
3038
+ if (unitsPerMilli === 1000n) {
3039
+ const dropped = units - millis * 1000n;
3040
+ if (dropped !== 0n)
3041
+ rememberDroppedMicros(date, Number(dropped));
3042
+ }
3043
+ return date;
3083
3044
  }
3084
3045
  var JSValueConverter = (value, type, converter) => {
3085
3046
  if (value !== null && typeof value === "object") {
@@ -3089,13 +3050,20 @@ var JSValueConverter = (value, type, converter) => {
3089
3050
  if (type.typeId === DuckDBTypeId2.TIMESTAMP_NS && "nanos" in value && typeof value.nanos === "bigint") {
3090
3051
  return dateFromTimestampUnits(value.nanos, 1000000n, "TIMESTAMP_NS");
3091
3052
  }
3053
+ if (type.typeId === DuckDBTypeId2.DATE && "days" in value) {
3054
+ if (value.days === DATE_INFINITY_DAYS)
3055
+ return "infinity";
3056
+ if (value.days === -DATE_INFINITY_DAYS)
3057
+ return "-infinity";
3058
+ }
3092
3059
  }
3093
3060
  return JSDuckDBValueConverter(value, type, converter);
3094
3061
  };
3095
3062
  var FLOORED_TIMESTAMP_TYPE_IDS = new Set([
3096
3063
  DuckDBTypeId2.TIMESTAMP,
3097
3064
  DuckDBTypeId2.TIMESTAMP_TZ,
3098
- DuckDBTypeId2.TIMESTAMP_NS
3065
+ DuckDBTypeId2.TIMESTAMP_NS,
3066
+ DuckDBTypeId2.DATE
3099
3067
  ]);
3100
3068
  function containsFlooredTimestamp(type) {
3101
3069
  if (FLOORED_TIMESTAMP_TYPE_IDS.has(type.typeId))
@@ -3177,8 +3145,8 @@ function hasFetchAllChunks(result) {
3177
3145
  async function materializeResultRows(result, exactDecimals = false, recursiveDecimals = false) {
3178
3146
  if (hasFetchAllChunks(result)) {
3179
3147
  const exactDecimalColumns = exactDecimals || recursiveDecimals ? findDecimalColumns(result) : [];
3180
- const rows2 = await readResultChunkRows(result, exactDecimalColumns.length > 0, recursiveDecimals);
3181
- return exactDecimalColumns.length > 0 ? { columns: resolveResultColumns(result), rows: rows2, exactDecimalColumns } : { columns: resolveResultColumns(result), rows: rows2 };
3148
+ const rows = await readResultChunkRows(result, exactDecimalColumns.length > 0, recursiveDecimals);
3149
+ return exactDecimalColumns.length > 0 ? { columns: resolveResultColumns(result), rows, exactDecimalColumns } : { columns: resolveResultColumns(result), rows };
3182
3150
  }
3183
3151
  const getRowsJson = typeof result.getRowsJson === "function" ? result.getRowsJson.bind(result) : undefined;
3184
3152
  const rows = await readPreferredResult({
@@ -3189,36 +3157,6 @@ async function materializeResultRows(result, exactDecimals = false, recursiveDec
3189
3157
  const columns = resolveResultColumns(result);
3190
3158
  return { columns, rows };
3191
3159
  }
3192
- function isUnpreparableQueryError(error) {
3193
- return error instanceof Error && /Cannot prepare multiple statements at once|No statement to prepare/.test(error.message);
3194
- }
3195
- async function executePreparedQuery(connection, query, { values, types }, cacheConfig, exactDecimals = false, recursiveDecimals = false) {
3196
- const cache = getPreparedStatementCache(connection, cacheConfig.size);
3197
- return await cache.runExclusive(async () => {
3198
- assertConnectionAvailable(connection);
3199
- let statement;
3200
- try {
3201
- statement = await cache.getOrPrepare(query);
3202
- } catch (error) {
3203
- if (!isUnpreparableQueryError(error)) {
3204
- throw error;
3205
- }
3206
- assertConnectionAvailable(connection);
3207
- const result = await connection.run(query, values, types);
3208
- return await materializeResultRows(result, exactDecimals, recursiveDecimals);
3209
- }
3210
- assertConnectionAvailable(connection);
3211
- try {
3212
- bindPreparedStatement(statement, values, types);
3213
- const result = await statement.run();
3214
- cache.remember(query, statement);
3215
- return await materializeResultRows(result, exactDecimals, recursiveDecimals);
3216
- } catch (error) {
3217
- cache.evict(query);
3218
- throw error;
3219
- }
3220
- });
3221
- }
3222
3160
  async function* yieldChunkRows(fetchChunk, preferJson, exactDecimals = false) {
3223
3161
  let useJson = preferJson;
3224
3162
  let yieldedRows = false;
@@ -3261,10 +3199,7 @@ async function materializeRows(client, query, params, options = {}) {
3261
3199
  return await materializePgDuckRows(connection, query, params);
3262
3200
  }
3263
3201
  return await runNodeApiOperation(connection, async () => {
3264
- const nodeApiParams = toNodeApiParams(params);
3265
- if (options.prepareCache && typeof connection.prepare === "function") {
3266
- return await executePreparedQuery(connection, query, nodeApiParams, options.prepareCache, options.exactDecimals, options.decimalMode === "string");
3267
- }
3202
+ const nodeApiParams = toNodeApiParams(params, options.dateParams);
3268
3203
  const result = await connection.run(query, nodeApiParams.values, nodeApiParams.types);
3269
3204
  return await materializeResultRows(result, options.exactDecimals, options.decimalMode === "string");
3270
3205
  });
@@ -3409,7 +3344,7 @@ async function* streamRawBatches(client, query, params, options = {}) {
3409
3344
  streamingConnections.add(connection);
3410
3345
  let result;
3411
3346
  try {
3412
- const { values, types } = toNodeApiParams(params);
3347
+ const { values, types } = toNodeApiParams(params, options.dateParams);
3413
3348
  result = await connection.stream(query, values, types);
3414
3349
  yield* streamNodeApiResult(connection, result, rowsPerChunk, options.decimalMode === "string");
3415
3350
  } finally {
@@ -3474,7 +3409,7 @@ async function executeArrowOnClient(client, query, params, options = {}) {
3474
3409
  return mapRowsToColumnData(columns, rows);
3475
3410
  }
3476
3411
  return await runNodeApiOperation(connection, async () => {
3477
- const { values, types } = toNodeApiParams(params);
3412
+ const { values, types } = toNodeApiParams(params, options.dateParams);
3478
3413
  const result = await connection.run(query, values, types);
3479
3414
  const maybeArrow = result.toArrow ?? result.getArrowTable;
3480
3415
  if (typeof maybeArrow === "function") {
@@ -3487,23 +3422,23 @@ async function executeArrowOnClient(client, query, params, options = {}) {
3487
3422
  const js = jsConverterFor(chunks);
3488
3423
  const convert = (baseConverter) => {
3489
3424
  const converter = options.decimalMode === "string" ? withExactDecimals(baseConverter, true, js) : baseConverter;
3490
- const values2 = columns.map(() => []);
3425
+ const values = columns.map(() => []);
3491
3426
  for (const chunk of chunks) {
3492
3427
  if (typeof chunk.convertColumns === "function") {
3493
3428
  const converted = chunk.convertColumns(converter);
3494
3429
  for (let index = 0;index < columns.length; index += 1) {
3495
3430
  for (const value of converted[index] ?? [])
3496
- values2[index].push(value);
3431
+ values[index].push(value);
3497
3432
  }
3498
3433
  } else {
3499
3434
  for (const row of chunk.convertRows(converter)) {
3500
3435
  for (let index = 0;index < columns.length; index += 1)
3501
- values2[index].push(row[index]);
3436
+ values[index].push(row[index]);
3502
3437
  }
3503
3438
  }
3504
3439
  }
3505
3440
  const data = {};
3506
- columns.forEach((name, index) => assignOwnProperty(data, name, values2[index]));
3441
+ columns.forEach((name, index) => assignOwnProperty(data, name, values[index]));
3507
3442
  return data;
3508
3443
  };
3509
3444
  try {
@@ -3527,6 +3462,96 @@ async function executeArrowOnClient(client, query, params, options = {}) {
3527
3462
  });
3528
3463
  });
3529
3464
  }
3465
+ var APPEND_DEFAULT = Symbol("drizzle-duckdb:append-default");
3466
+ var INT64_MIN = -(2n ** 63n);
3467
+ var INT64_MAX = 2n ** 63n - 1n;
3468
+ function appendCell(appender, value, columnType) {
3469
+ if (value === APPEND_DEFAULT) {
3470
+ appender.appendDefault();
3471
+ return;
3472
+ }
3473
+ const nodeValue = toNodeApiValue(value, columnType);
3474
+ if (nodeValue === null) {
3475
+ appender.appendNull();
3476
+ return;
3477
+ }
3478
+ switch (typeof nodeValue) {
3479
+ case "string":
3480
+ appender.appendVarchar(nodeValue);
3481
+ return;
3482
+ case "number":
3483
+ if (!Number.isInteger(nodeValue)) {
3484
+ appender.appendDouble(nodeValue);
3485
+ } else if (nodeValue >= -2147483648 && nodeValue <= 2147483647) {
3486
+ appender.appendInteger(nodeValue);
3487
+ } else if (Number.isSafeInteger(nodeValue)) {
3488
+ appender.appendBigInt(BigInt(nodeValue));
3489
+ } else {
3490
+ appender.appendDouble(nodeValue);
3491
+ }
3492
+ return;
3493
+ case "boolean":
3494
+ appender.appendBoolean(nodeValue);
3495
+ return;
3496
+ case "bigint":
3497
+ if (nodeValue >= INT64_MIN && nodeValue <= INT64_MAX) {
3498
+ appender.appendBigInt(nodeValue);
3499
+ } else {
3500
+ appender.appendHugeInt(nodeValue);
3501
+ }
3502
+ return;
3503
+ default: {
3504
+ const typed = typedNodeApiParam(nodeValue);
3505
+ if (typed) {
3506
+ appender.appendValue(typed.value, typed.type);
3507
+ } else {
3508
+ appender.appendValue(nodeValue);
3509
+ }
3510
+ }
3511
+ }
3512
+ }
3513
+ function quoteAppendIdentifier(name) {
3514
+ return `"${name.replace(/"/g, '""')}"`;
3515
+ }
3516
+ async function appendRowsOnClient(client, target, rowCount, bindRows) {
3517
+ return await withConnection(client, async (connection) => {
3518
+ if (!isNodeApiConnection(connection) || typeof connection.createAppender !== "function") {
3519
+ throw new Error("appendRows() needs an @duckdb/node-api connection. Use db.insert() with pg_duckdb clients.");
3520
+ }
3521
+ return await runNodeApiOperation(connection, async () => {
3522
+ const qualified = target.schema ? `${quoteAppendIdentifier(target.schema)}.${quoteAppendIdentifier(target.table)}` : quoteAppendIdentifier(target.table);
3523
+ const probe = await connection.run(`select * from ${qualified} limit 0`);
3524
+ const columnNames = probe.columnNames();
3525
+ const appender = await connection.createAppender(target.table, target.schema ?? null);
3526
+ let failed = true;
3527
+ try {
3528
+ if (appender.columnCount !== columnNames.length) {
3529
+ throw new Error(`appendRows() cannot append to ${qualified}: the table has ${columnNames.length} columns but its appender takes ${appender.columnCount}, as for tables with generated columns. Use db.insert() instead.`);
3530
+ }
3531
+ const columnTypes = columnNames.map((_, index) => appender.columnType(index));
3532
+ const valueAt = bindRows(columnNames);
3533
+ for (let rowIndex = 0;rowIndex < rowCount; rowIndex += 1) {
3534
+ for (let columnIndex = 0;columnIndex < columnTypes.length; columnIndex += 1) {
3535
+ appendCell(appender, valueAt(rowIndex, columnIndex), columnTypes[columnIndex]);
3536
+ }
3537
+ appender.endRow();
3538
+ }
3539
+ appender.flushSync();
3540
+ failed = false;
3541
+ return rowCount;
3542
+ } finally {
3543
+ try {
3544
+ if (failed)
3545
+ appender.clear?.();
3546
+ appender.closeSync();
3547
+ } catch (error) {
3548
+ if (!failed)
3549
+ throw error;
3550
+ }
3551
+ }
3552
+ });
3553
+ });
3554
+ }
3530
3555
 
3531
3556
  // src/select-builder.ts
3532
3557
  import {
@@ -3648,8 +3673,8 @@ function qualifySubqueryFields(select) {
3648
3673
  const internals = select;
3649
3674
  const baseAs = internals.as.bind(internals);
3650
3675
  internals.as = (alias) => {
3651
- const { sql: sql4, usedTables } = baseAs(alias)._;
3652
- return new Proxy(new Subquery3(sql4, exposeSubqueryFields(internals.config.fields), alias, false, usedTables), new SelectionProxyHandler({
3676
+ const { sql, usedTables } = baseAs(alias)._;
3677
+ return new Proxy(new Subquery3(sql, exposeSubqueryFields(internals.config.fields), alias, false, usedTables), new SelectionProxyHandler({
3653
3678
  alias,
3654
3679
  sqlAliasedBehavior: "alias",
3655
3680
  sqlBehavior: "error"
@@ -3964,9 +3989,12 @@ class DuckDBPreparedQuery extends PgPreparedQuery {
3964
3989
  onStatementError;
3965
3990
  decimalMode;
3966
3991
  waitForTransactions;
3992
+ relationalSelection;
3993
+ dateParams;
3967
3994
  static [entityKind3] = "DuckDBPreparedQuery";
3968
3995
  resultMapper;
3969
- constructor(client, dialect, queryString, params, logger, fields, _isResponseInArrayMode, customResultMapper, rejectStringArrayLiterals, prepareCache, queryMetadata, cacheConfig, warnOnStringArrayLiteral, scalarParamIndexes, onStatementError, decimalMode = "number", waitForTransactions = false) {
3996
+ relationalRowNormalizer;
3997
+ constructor(client, dialect, queryString, params, logger, fields, _isResponseInArrayMode, customResultMapper, rejectStringArrayLiterals, prepareCache, queryMetadata, cacheConfig, warnOnStringArrayLiteral, scalarParamIndexes, onStatementError, decimalMode = "number", waitForTransactions = false, relationalSelection, dateParams) {
3970
3998
  super(...[
3971
3999
  { sql: queryString, params },
3972
4000
  undefined,
@@ -3988,6 +4016,8 @@ class DuckDBPreparedQuery extends PgPreparedQuery {
3988
4016
  this.onStatementError = onStatementError;
3989
4017
  this.decimalMode = decimalMode;
3990
4018
  this.waitForTransactions = waitForTransactions;
4019
+ this.relationalSelection = relationalSelection;
4020
+ this.dateParams = dateParams;
3991
4021
  }
3992
4022
  async execute(placeholderValues = {}) {
3993
4023
  try {
@@ -4013,23 +4043,32 @@ class DuckDBPreparedQuery extends PgPreparedQuery {
4013
4043
  });
4014
4044
  const { fields, joinsNotNullableMap, customResultMapper } = this;
4015
4045
  if (!fields && !customResultMapper) {
4016
- const rows2 = await executeOnClient(this.client, queryString, params, {
4046
+ const rows = await executeOnClient(this.client, queryString, params, {
4017
4047
  prepareCache: this.prepareCache,
4018
- decimalMode: this.decimalMode
4048
+ decimalMode: this.decimalMode,
4049
+ dateParams: this.dateParams
4019
4050
  });
4020
- return rows2;
4051
+ return rows;
4021
4052
  }
4053
+ const relationalSelection = customResultMapper ? this.relationalSelection : undefined;
4022
4054
  const { rows, exactDecimalColumns } = await executeArraysOnClient(this.client, queryString, params, {
4023
4055
  prepareCache: this.prepareCache,
4024
- exactDecimals: !customResultMapper,
4025
- decimalMode: this.decimalMode
4056
+ exactDecimals: !customResultMapper || relationalSelection !== undefined,
4057
+ decimalMode: this.decimalMode,
4058
+ dateParams: this.dateParams
4026
4059
  });
4060
+ const decimalFields = relationalSelection ?? fields;
4061
+ if (exactDecimalColumns && decimalFields && this.decimalMode !== "string") {
4062
+ restoreNonNumericDecimals(rows, decimalFields, exactDecimalColumns);
4063
+ }
4027
4064
  if (customResultMapper) {
4065
+ if (relationalSelection) {
4066
+ this.relationalRowNormalizer ??= compileRelationalRowNormalizer(relationalSelection);
4067
+ for (const row of rows)
4068
+ this.relationalRowNormalizer(row);
4069
+ }
4028
4070
  return customResultMapper(rows);
4029
4071
  }
4030
- if (exactDecimalColumns && this.decimalMode !== "string") {
4031
- restoreNonNumericDecimals(rows, fields, exactDecimalColumns);
4032
- }
4033
4072
  this.resultMapper ??= compileResultMapper(fields, joinsNotNullableMap);
4034
4073
  return rows.map(this.resultMapper);
4035
4074
  }
@@ -4070,7 +4109,7 @@ class DuckDBSession extends PgSession {
4070
4109
  };
4071
4110
  }
4072
4111
  prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
4073
- return new DuckDBPreparedQuery(this.client, this.dialect, query.sql, bindEmptyArrays(query.params, query.params, query.typings), this.logger, fields, isResponseInArrayMode, customResultMapper, this.rejectStringArrayLiterals, this.prepareCache, queryMetadata, cacheConfig, this.rejectStringArrayLiterals ? undefined : this.warnOnStringArrayLiteral, getScalarParamIndexes(query.params, query.typings), this.statementFailures || this.waitsForTransactions() ? this.recordStatementFailure : undefined, this.options.decimalMode, this.waitsForTransactions());
4112
+ return new DuckDBPreparedQuery(this.client, this.dialect, query.sql, bindEmptyArrays(query.params, query.params, query.typings), this.logger, fields, isResponseInArrayMode, customResultMapper, this.rejectStringArrayLiterals, this.prepareCache, queryMetadata, cacheConfig, this.rejectStringArrayLiterals ? undefined : this.warnOnStringArrayLiteral, getScalarParamIndexes(query.params, query.typings), this.statementFailures || this.waitsForTransactions() ? this.recordStatementFailure : undefined, this.options.decimalMode, this.waitsForTransactions(), relationalSelectionOf(query), this.options.dateParams);
4074
4113
  }
4075
4114
  waitsForTransactions() {
4076
4115
  return !this.statementFailures && !isPool(this.client);
@@ -4238,6 +4277,7 @@ query: ${query}`, []);
4238
4277
  const { sql: queryString, params } = this.prepareQueryExecution(query);
4239
4278
  return this.trackStreamFailures(this.afterOpenTransaction(executeInBatches(this.client, queryString, params, {
4240
4279
  decimalMode: this.options.decimalMode,
4280
+ dateParams: this.options.dateParams,
4241
4281
  ...options
4242
4282
  })));
4243
4283
  }
@@ -4245,6 +4285,7 @@ query: ${query}`, []);
4245
4285
  const { sql: queryString, params } = this.prepareQueryExecution(query);
4246
4286
  return this.trackStreamFailures(this.afterOpenTransaction(executeInBatchesRaw(this.client, queryString, params, {
4247
4287
  decimalMode: this.options.decimalMode,
4288
+ dateParams: this.options.dateParams,
4248
4289
  ...options
4249
4290
  })));
4250
4291
  }
@@ -4255,7 +4296,65 @@ query: ${query}`, []);
4255
4296
  }
4256
4297
  try {
4257
4298
  return await executeArrowOnClient(this.client, queryString, params, {
4258
- decimalMode: this.options.decimalMode
4299
+ decimalMode: this.options.decimalMode,
4300
+ dateParams: this.options.dateParams
4301
+ });
4302
+ } catch (error) {
4303
+ this.recordStatementFailure(error);
4304
+ throw error;
4305
+ }
4306
+ }
4307
+ async appendRows(table, rows) {
4308
+ if (rows.length === 0) {
4309
+ return 0;
4310
+ }
4311
+ const { name, schema, columns } = getTableConfig(table);
4312
+ const keyOf = new Map;
4313
+ for (const [key, column] of Object.entries(table)) {
4314
+ keyOf.set(column, key);
4315
+ }
4316
+ const byName = new Map(columns.map((column) => [column.name, column]));
4317
+ if (this.waitsForTransactions()) {
4318
+ await waitForOpenTransaction(this.client);
4319
+ }
4320
+ try {
4321
+ return await appendRowsOnClient(this.client, { table: name, schema }, rows.length, (columnNames) => {
4322
+ const known = new Set(columnNames);
4323
+ for (const column of columns) {
4324
+ if (!known.has(column.name)) {
4325
+ throw new Error(`appendRows(): column "${column.name}" is not a column of table "${name}".`);
4326
+ }
4327
+ }
4328
+ const plan = columnNames.map((columnName) => {
4329
+ const column = byName.get(columnName);
4330
+ return column ? { column, key: keyOf.get(column) ?? column.name } : undefined;
4331
+ });
4332
+ return (rowIndex, columnIndex) => {
4333
+ const entry = plan[columnIndex];
4334
+ if (!entry)
4335
+ return APPEND_DEFAULT;
4336
+ const { column, key } = entry;
4337
+ let value = rows[rowIndex][key];
4338
+ if (value === undefined) {
4339
+ if (column.defaultFn !== undefined) {
4340
+ value = column.defaultFn();
4341
+ } else if (column.onUpdateFn !== undefined) {
4342
+ value = column.onUpdateFn();
4343
+ } else {
4344
+ return APPEND_DEFAULT;
4345
+ }
4346
+ }
4347
+ if (value === null)
4348
+ return null;
4349
+ if (is4(value, SQL4)) {
4350
+ throw new Error(`appendRows(): column "${column.name}" got a SQL expression, which the appender cannot evaluate. Use db.insert() for such rows.`);
4351
+ }
4352
+ const driverValue = column.mapToDriverValue(value);
4353
+ if (is4(driverValue, SQL4)) {
4354
+ throw new Error(`appendRows(): column "${column.name}" encodes this value as a SQL literal (a struct, union, empty list, or a list of objects or blobs), which the appender cannot take. Use db.insert() for such rows.`);
4355
+ }
4356
+ return driverValue;
4357
+ };
4259
4358
  });
4260
4359
  } catch (error) {
4261
4360
  this.recordStatementFailure(error);
@@ -4336,6 +4435,9 @@ class DuckDBTransaction extends PgTransaction {
4336
4435
  executeArrow(query) {
4337
4436
  return this.getInternals().session.executeArrow(query);
4338
4437
  }
4438
+ appendRows(table, rows) {
4439
+ return this.getInternals().session.appendRows(table, rows);
4440
+ }
4339
4441
  async transaction(transaction) {
4340
4442
  const internals = this.getInternals();
4341
4443
  const savepoint = `drizzle_savepoint_${this.nestedIndex + 1}`;
@@ -4438,8 +4540,12 @@ function resolvePoolSize(pool) {
4438
4540
  return false;
4439
4541
  if (pool === undefined)
4440
4542
  return DEFAULT_POOL_SIZE;
4441
- if (typeof pool === "string")
4442
- return POOL_PRESETS[pool] ?? DEFAULT_POOL_SIZE;
4543
+ if (typeof pool === "string") {
4544
+ if (!Object.hasOwn(POOL_PRESETS, pool)) {
4545
+ throw new Error(`Unknown pool preset ${JSON.stringify(pool)}. Expected one of: ${Object.keys(POOL_PRESETS).join(", ")}.`);
4546
+ }
4547
+ return POOL_PRESETS[pool];
4548
+ }
4443
4549
  return resolveSize(pool.size);
4444
4550
  }
4445
4551
  var POOL_CLOSED_MESSAGE = "DuckDB connection pool is closed";
@@ -4671,9 +4777,9 @@ function createDuckDBConnectionPool(instance, options = {}) {
4671
4777
  if (waiting.length >= maxWaitingRequests) {
4672
4778
  throw new Error(`DuckDB connection pool queue is full (max ${maxWaitingRequests} waiting requests)`);
4673
4779
  }
4674
- return await new Promise((resolve2, reject) => {
4780
+ return await new Promise((resolve, reject) => {
4675
4781
  const waiter = {
4676
- resolve: resolve2,
4782
+ resolve,
4677
4783
  reject,
4678
4784
  timeoutId: undefined,
4679
4785
  queuedAt: Date.now()
@@ -5122,7 +5228,8 @@ class DuckDBDriver {
5122
5228
  rejectStringArrayLiterals: this.options.rejectStringArrayLiterals,
5123
5229
  arrayLiteralWarning: this.options.arrayLiteralWarning,
5124
5230
  prepareCache: this.options.prepareCache,
5125
- decimalMode: this.options.decimalMode
5231
+ decimalMode: this.options.decimalMode,
5232
+ dateParams: this.options.dateParams
5126
5233
  });
5127
5234
  }
5128
5235
  }
@@ -5184,6 +5291,15 @@ function isNodePostgresPool(value) {
5184
5291
  const candidate = value;
5185
5292
  return typeof candidate.connect === "function" && typeof candidate.query === "function" && typeof candidate.acquire !== "function" && typeof candidate.totalCount === "number" && typeof candidate.idleCount === "number";
5186
5293
  }
5294
+ var PREPARE_CACHE_WARNING = "The prepareCache option is deprecated and ignored. DuckDB plans a prepared statement from the table statistics at prepare time, so a cached statement can return wrong results after the data changes. Remove the option. It will be removed in the next major version.";
5295
+ var hasWarnedPrepareCache = false;
5296
+ function warnPrepareCacheIgnored() {
5297
+ if (hasWarnedPrepareCache) {
5298
+ return;
5299
+ }
5300
+ hasWarnedPrepareCache = true;
5301
+ console.warn(PREPARE_CACHE_WARNING);
5302
+ }
5187
5303
  function createFromClient(client, config = {}, instance) {
5188
5304
  let finalClient = isNodePostgresPool(client) ? createPgDuckConnectionPool(client) : client;
5189
5305
  if (config.ducklake) {
@@ -5199,6 +5315,9 @@ function createFromClient(client, config = {}, instance) {
5199
5315
  decimalMode: config.decimalMode
5200
5316
  });
5201
5317
  const prepareCache = resolvePrepareCacheOption(config.prepareCache);
5318
+ if (prepareCache) {
5319
+ warnPrepareCacheIgnored();
5320
+ }
5202
5321
  const logger = config.logger === true ? new DefaultLogger : config.logger || undefined;
5203
5322
  let schema;
5204
5323
  if (config.schema) {
@@ -5214,7 +5333,8 @@ function createFromClient(client, config = {}, instance) {
5214
5333
  rejectStringArrayLiterals: config.rejectStringArrayLiterals,
5215
5334
  arrayLiteralWarning: config.arrayLiteralWarning,
5216
5335
  prepareCache,
5217
- decimalMode: config.decimalMode
5336
+ decimalMode: config.decimalMode,
5337
+ dateParams: config.dateParams
5218
5338
  });
5219
5339
  const session = driver.createSession(schema);
5220
5340
  const db = new DuckDBDatabase(dialect, session, schema, finalClient, instance);
@@ -5337,6 +5457,9 @@ class DuckDBDatabase extends PgDatabase {
5337
5457
  executeArrow(query) {
5338
5458
  return this.session.executeArrow(query);
5339
5459
  }
5460
+ appendRows(table, rows) {
5461
+ return this.session.appendRows(table, rows);
5462
+ }
5340
5463
  async transaction(transaction, config) {
5341
5464
  return await this.session.transaction(transaction, config);
5342
5465
  }
@@ -5744,8 +5867,8 @@ function timestampLiteral(value, withTimezone) {
5744
5867
  const fraction = parts.fraction ? `.${parts.fraction}` : "";
5745
5868
  const offset = parts.offset === "Z" ? "+00" : parts.offset;
5746
5869
  if (withTimezone) {
5747
- const time2 = ` ${parts.time ?? "00:00:00"}`;
5748
- return `${parts.date}${time2}${fraction}${offset ?? "+00"}`;
5870
+ const time = ` ${parts.time ?? "00:00:00"}`;
5871
+ return `${parts.date}${time}${fraction}${offset ?? "+00"}`;
5749
5872
  }
5750
5873
  if (offset && !/^[+-]00(:00)?$/.test(offset)) {
5751
5874
  const utc = utcTimestampString(parts);
@@ -5758,7 +5881,7 @@ function timestampLiteral(value, withTimezone) {
5758
5881
  }
5759
5882
  function timestampModeString(value, withTimezone) {
5760
5883
  if (value instanceof Date) {
5761
- return timestampStringFromMicros(BigInt(value.getTime()) * 1000n, withTimezone);
5884
+ return timestampStringFromMicros(dateToMicros(value), withTimezone);
5762
5885
  }
5763
5886
  if (value !== null && typeof value === "object" && "micros" in value && typeof value.micros === "bigint") {
5764
5887
  return timestampStringFromMicros(value.micros, withTimezone);
@@ -6390,26 +6513,24 @@ function emitConstraints(plan, plans, tableIdentifiers) {
6390
6513
  const param = allocateIdentifier("t", referencedTables);
6391
6514
  const ownColumns = (columns) => columns.map((col) => memberAccess(param, plan.columnProperties.get(col) ?? columnProperty(col))).join(", ");
6392
6515
  const entries = [];
6393
- const usedKeys = new Set;
6394
6516
  for (const constraint of constraints) {
6395
- const key = allocateIdentifier(toIdentifier(constraint.name || `${table.name}_constraint`), usedKeys);
6396
6517
  const name = JSON.stringify(constraint.name);
6397
6518
  if (constraint.type === "PRIMARY KEY") {
6398
- entries.push(`${key}: primaryKey({ columns: [${ownColumns(constraint.columns)}], name: ${name} })`);
6519
+ entries.push(`primaryKey({ columns: [${ownColumns(constraint.columns)}], name: ${name} })`);
6399
6520
  } else if (constraint.type === "UNIQUE") {
6400
- entries.push(`${key}: unique(${name}).on(${ownColumns(constraint.columns)})`);
6521
+ entries.push(`unique(${name}).on(${ownColumns(constraint.columns)})`);
6401
6522
  } else {
6402
6523
  const target = resolveTarget(constraint);
6403
6524
  const targetVar = target.key === selfKey ? param : target.identifier;
6404
6525
  const foreignColumns = constraint.referencedTable.columns.map((col) => memberAccess(targetVar, target.columnProperties?.get(col) ?? columnProperty(col))).join(", ");
6405
- entries.push(`${key}: foreignKey({ columns: [${ownColumns(constraint.columns)}], foreignColumns: [${foreignColumns}], name: ${name} })`);
6526
+ entries.push(`foreignKey({ columns: [${ownColumns(constraint.columns)}], foreignColumns: [${foreignColumns}], name: ${name} })`);
6406
6527
  }
6407
6528
  }
6408
- const lines = [`(${param}) => ({`];
6529
+ const lines = [`(${param}) => [`];
6409
6530
  for (const entry of entries) {
6410
6531
  lines.push(` ${entry},`);
6411
6532
  }
6412
- lines.push("})");
6533
+ lines.push("]");
6413
6534
  return lines.join(`
6414
6535
  `);
6415
6536
  }
@@ -6633,7 +6754,7 @@ function nestedValueType(raw) {
6633
6754
  return `Array<${nestedValueType(array[1])} | null>`;
6634
6755
  if (type.startsWith("STRUCT")) {
6635
6756
  const fields = parseStructFields(type.replace(/^STRUCT\s*\(/i, "").replace(/\)$/, ""));
6636
- return `{ ${fields.map(({ name, type: type2 }) => `${JSON.stringify(name)}: ${nestedValueType(type2)} | null`).join("; ")} }`;
6757
+ return `{ ${fields.map(({ name, type }) => `${JSON.stringify(name)}: ${nestedValueType(type)} | null`).join("; ")} }`;
6637
6758
  }
6638
6759
  if (type.startsWith("MAP(")) {
6639
6760
  const { keyType, valueType } = parseMapTypes(type);
@@ -6701,14 +6822,14 @@ function mapDuckDbType(column, imports, options) {
6701
6822
  imports.pgCore.add("numeric");
6702
6823
  const precision = column.numericPrecision;
6703
6824
  const scale = column.numericScale;
6704
- const options2 = [];
6825
+ const options = [];
6705
6826
  if (precision !== null && precision !== undefined) {
6706
- options2.push(`precision: ${precision}`);
6827
+ options.push(`precision: ${precision}`);
6707
6828
  }
6708
6829
  if (scale !== null && scale !== undefined) {
6709
- options2.push(`scale: ${scale}`);
6830
+ options.push(`scale: ${scale}`);
6710
6831
  }
6711
- const suffix = options2.length ? `, { ${options2.join(", ")} }` : "";
6832
+ const suffix = options.length ? `, { ${options.join(", ")} }` : "";
6712
6833
  return {
6713
6834
  builder: `numeric(${columnName(column.name)}${suffix})`,
6714
6835
  defaultLiterals: STRING_DEFAULTS
@@ -7015,9 +7136,9 @@ function uniqueSchemas(tables) {
7015
7136
  }
7016
7137
  function renderImports(imports, importBasePath) {
7017
7138
  const lines = [];
7018
- const drizzle2 = [...imports.drizzle];
7019
- if (drizzle2.length) {
7020
- lines.push(`import { ${drizzle2.sort().join(", ")} } from 'drizzle-orm';`);
7139
+ const drizzle = [...imports.drizzle];
7140
+ if (drizzle.length) {
7141
+ lines.push(`import { ${drizzle.sort().join(", ")} } from 'drizzle-orm';`);
7021
7142
  }
7022
7143
  const pgCore = [...imports.pgCore];
7023
7144
  if (pgCore.length) {
@@ -7203,7 +7324,10 @@ import { sql as sql9 } from "drizzle-orm";
7203
7324
  import { isSQLWrapper as isSQLWrapper4 } from "drizzle-orm/sql/sql";
7204
7325
  var motherDuckFlightReservedConfigKeys = new Set([
7205
7326
  "MOTHERDUCK_TOKEN",
7206
- "MOTHERDUCK_FLIGHTS_RUN"
7327
+ "MOTHERDUCK_FLIGHTS_RUN",
7328
+ "MOTHERDUCK_FLIGHT_ID",
7329
+ "MOTHERDUCK_FLIGHT_RUN_ID",
7330
+ "MOTHERDUCK_HOST"
7207
7331
  ]);
7208
7332
  var motherDuckTableFunctionNameList = [
7209
7333
  "read_parquet",
@@ -8022,144 +8146,146 @@ function mdPrompt(input, options = {}) {
8022
8146
  return sql12`prompt(${sql12.join(args, sql12`, `)})`;
8023
8147
  }
8024
8148
  export {
8025
- wrapperToNodeApiValue,
8026
- wrapTimestamp,
8027
- wrapStruct,
8028
- wrapMap,
8029
- wrapList,
8030
- wrapJson,
8031
- wrapDuckLakePool,
8032
- wrapBlob,
8033
- wrapArray,
8034
- toIdentifier,
8035
- sumN,
8036
- sumDistinctN,
8037
- splitTopLevel,
8038
- rowNumber,
8039
- resolvePrepareCacheOption,
8040
- resolvePoolSize,
8041
- rank,
8042
- prepareParams,
8043
- percentileCont,
8044
- parseStructFields,
8045
- parseMapValue,
8046
- parseMapKey,
8047
- olap,
8048
- normalizeTypeLiteral,
8049
- normalizePositiveInteger,
8050
- normalizeArrayPredicateValue,
8051
- motherDuckTableFunction,
8052
- motherDuckReadParquet,
8053
- motherDuckReadJsonAuto,
8054
- motherDuckReadCsvAuto,
8055
- migrate,
8056
- median,
8057
- mdUpdateJob,
8058
- mdUpdateFlight,
8059
- mdUpdateDiveStatus,
8060
- mdUpdateDiveMetadata,
8061
- mdUpdateDiveContent,
8062
- mdSessionRoles,
8063
- mdRunJob,
8064
- mdRunFlight,
8065
- mdPromptJev,
8066
- mdPrompt,
8067
- mdListRolesGrantedToUser,
8068
- mdListRolesGrantedToRole,
8069
- mdListRoles,
8070
- mdListRoleMembers,
8071
- mdListFlights,
8072
- mdListFlightVersions,
8073
- mdListFlightRuns,
8074
- mdListFlightGrantees,
8075
- mdListFiles,
8076
- mdListDives,
8077
- mdListDiveVersions,
8078
- mdJobs,
8079
- mdJobVersions,
8080
- mdJobRuns,
8081
- mdJobRunLogs,
8082
- mdIsRoleInSession,
8083
- mdGetJobVersion,
8084
- mdGetJob,
8085
- mdGetFlightVersion,
8086
- mdGetFlightRun,
8087
- mdGetFlightLogs,
8088
- mdGetFlight,
8089
- mdGetDiveVersion,
8090
- mdGetDive,
8091
- mdFlights,
8092
- mdFlightVersions,
8093
- mdFlightRuns,
8094
- mdFlightLogs,
8095
- mdDeleteJob,
8096
- mdDeleteFlight,
8097
- mdDeleteDive,
8098
- mdCurrentEmail,
8099
- mdCreateJob,
8100
- mdCreateFlight,
8101
- mdCreateDive,
8102
- mdCancelJobRun,
8103
- mdCancelFlightRun,
8104
- mdAccessTokens,
8105
- lead,
8106
- lanceVectorSearch,
8107
- lanceHybridSearch,
8108
- lanceFts,
8109
- lag,
8110
- isPool,
8111
- isDuckDBWrapper,
8112
- introspect,
8113
- getPreparedStatementCacheStats,
8114
- formatLiteral,
8115
- executeOnClient,
8116
- executeInBatchesRaw,
8117
- executeInBatches,
8118
- executeArrowOnClient,
8119
- executeArraysOnClient,
8120
- duckLakeMergeAdjacentFiles,
8121
- duckDbUnion,
8122
- duckDbTimestamp,
8123
- duckDbTime,
8124
- duckDbStruct,
8125
- duckDbMap,
8126
- duckDbList,
8127
- duckDbJson,
8128
- duckDbInterval,
8129
- duckDbInet,
8130
- duckDbDate,
8131
- duckDbBlob,
8132
- duckDbArrayOverlaps,
8133
- duckDbArrayContains,
8134
- duckDbArrayContained,
8135
- duckDbArray,
8136
- drizzle,
8137
- denseRank,
8138
- createPgDuckConnectionPool,
8139
- createDuckDBConnectionPool,
8140
- countN,
8141
- configureDuckLake,
8142
- coerceArrayString,
8143
- closeDuckDbInstance,
8144
- closeClientConnection,
8145
- buildStructLiteral,
8146
- buildMapLiteral,
8147
- buildListLiteral,
8148
- buildDefault,
8149
- avgN,
8150
- duckDbArrayOverlaps as arrayHasAny,
8151
- duckDbArrayContains as arrayHasAll,
8152
- duckDbArrayContained as arrayContainedBy,
8153
- anyValue,
8154
- POOL_PRESETS,
8155
- OlapBuilder,
8156
- DuckDBTransaction,
8157
- DuckDBSession,
8158
- DuckDBSelectBuilder,
8159
- DuckDBPreparedQuery,
8160
- DuckDBDriver,
8161
- DuckDBDialect,
8162
- DuckDBDatabase,
8149
+ APPEND_DEFAULT,
8150
+ DEFAULT_IMPORT_BASE,
8163
8151
  DUCKDB_VALUE_MARKER,
8164
- DEFAULT_IMPORT_BASE
8152
+ DuckDBDatabase,
8153
+ DuckDBDialect,
8154
+ DuckDBDriver,
8155
+ DuckDBPreparedQuery,
8156
+ DuckDBSelectBuilder,
8157
+ DuckDBSession,
8158
+ DuckDBTransaction,
8159
+ OlapBuilder,
8160
+ POOL_PRESETS,
8161
+ anyValue,
8162
+ appendRowsOnClient,
8163
+ duckDbArrayContained as arrayContainedBy,
8164
+ duckDbArrayContains as arrayHasAll,
8165
+ duckDbArrayOverlaps as arrayHasAny,
8166
+ avgN,
8167
+ buildDefault,
8168
+ buildListLiteral,
8169
+ buildMapLiteral,
8170
+ buildStructLiteral,
8171
+ closeClientConnection,
8172
+ closeDuckDbInstance,
8173
+ coerceArrayString,
8174
+ configureDuckLake,
8175
+ countN,
8176
+ createDuckDBConnectionPool,
8177
+ createPgDuckConnectionPool,
8178
+ denseRank,
8179
+ drizzle,
8180
+ duckDbArray,
8181
+ duckDbArrayContained,
8182
+ duckDbArrayContains,
8183
+ duckDbArrayOverlaps,
8184
+ duckDbBlob,
8185
+ duckDbDate,
8186
+ duckDbInet,
8187
+ duckDbInterval,
8188
+ duckDbJson,
8189
+ duckDbList,
8190
+ duckDbMap,
8191
+ duckDbStruct,
8192
+ duckDbTime,
8193
+ duckDbTimestamp,
8194
+ duckDbUnion,
8195
+ duckLakeMergeAdjacentFiles,
8196
+ executeArraysOnClient,
8197
+ executeArrowOnClient,
8198
+ executeInBatches,
8199
+ executeInBatchesRaw,
8200
+ executeOnClient,
8201
+ formatLiteral,
8202
+ getPreparedStatementCacheStats,
8203
+ introspect,
8204
+ isDuckDBWrapper,
8205
+ isPool,
8206
+ lag,
8207
+ lanceFts,
8208
+ lanceHybridSearch,
8209
+ lanceVectorSearch,
8210
+ lead,
8211
+ mdAccessTokens,
8212
+ mdCancelFlightRun,
8213
+ mdCancelJobRun,
8214
+ mdCreateDive,
8215
+ mdCreateFlight,
8216
+ mdCreateJob,
8217
+ mdCurrentEmail,
8218
+ mdDeleteDive,
8219
+ mdDeleteFlight,
8220
+ mdDeleteJob,
8221
+ mdFlightLogs,
8222
+ mdFlightRuns,
8223
+ mdFlightVersions,
8224
+ mdFlights,
8225
+ mdGetDive,
8226
+ mdGetDiveVersion,
8227
+ mdGetFlight,
8228
+ mdGetFlightLogs,
8229
+ mdGetFlightRun,
8230
+ mdGetFlightVersion,
8231
+ mdGetJob,
8232
+ mdGetJobVersion,
8233
+ mdIsRoleInSession,
8234
+ mdJobRunLogs,
8235
+ mdJobRuns,
8236
+ mdJobVersions,
8237
+ mdJobs,
8238
+ mdListDiveVersions,
8239
+ mdListDives,
8240
+ mdListFiles,
8241
+ mdListFlightGrantees,
8242
+ mdListFlightRuns,
8243
+ mdListFlightVersions,
8244
+ mdListFlights,
8245
+ mdListRoleMembers,
8246
+ mdListRoles,
8247
+ mdListRolesGrantedToRole,
8248
+ mdListRolesGrantedToUser,
8249
+ mdPrompt,
8250
+ mdPromptJev,
8251
+ mdRunFlight,
8252
+ mdRunJob,
8253
+ mdSessionRoles,
8254
+ mdUpdateDiveContent,
8255
+ mdUpdateDiveMetadata,
8256
+ mdUpdateDiveStatus,
8257
+ mdUpdateFlight,
8258
+ mdUpdateJob,
8259
+ median,
8260
+ migrate,
8261
+ motherDuckReadCsvAuto,
8262
+ motherDuckReadJsonAuto,
8263
+ motherDuckReadParquet,
8264
+ motherDuckTableFunction,
8265
+ normalizeArrayPredicateValue,
8266
+ normalizePositiveInteger,
8267
+ normalizeTypeLiteral,
8268
+ olap,
8269
+ parseMapKey,
8270
+ parseMapValue,
8271
+ parseStructFields,
8272
+ percentileCont,
8273
+ prepareParams,
8274
+ rank,
8275
+ resolvePoolSize,
8276
+ resolvePrepareCacheOption,
8277
+ rowNumber,
8278
+ splitTopLevel,
8279
+ sumDistinctN,
8280
+ sumN,
8281
+ toIdentifier,
8282
+ wrapArray,
8283
+ wrapBlob,
8284
+ wrapDuckLakePool,
8285
+ wrapJson,
8286
+ wrapList,
8287
+ wrapMap,
8288
+ wrapStruct,
8289
+ wrapTimestamp,
8290
+ wrapperToNodeApiValue
8165
8291
  };