Repository navigation
Expand file tree
/
Copy pathduckdb.py
More file actions
4721 lines (3921 loc) · 185 KB
/
Copy pathduckdb.py
File metadata and controls
4721 lines (3921 loc) · 185 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from decimal import Decimal
from itertools import groupby
import re
import typing as t
from sqlglot import exp, generator, transforms
from sqlglot.dialects.dialect import (
DATETIME_DELTA,
JSON_EXTRACT_TYPE,
approx_count_distinct_sql,
array_append_sql,
array_compact_sql,
array_concat_sql,
arrow_json_extract_sql,
count_if_to_sum,
date_delta_to_binary_interval_op,
datestrtodate_sql,
encode_decode_sql,
explode_to_unnest_sql,
generate_series_sql,
getbit_sql,
groupconcat_sql,
inline_array_unless_query,
months_between_sql,
no_datetime_sql,
no_comment_column_constraint_sql,
no_make_interval_sql,
no_time_sql,
no_timestamp_sql,
rename_func,
remove_from_array_using_filter,
strposition_sql,
timestrtotime_sql,
unit_to_str,
week_unit_to_dow,
WEEK_START_DAY_TO_DOW,
)
from sqlglot.generator import unsupported_args
from sqlglot.helper import find_new_name, is_date_unit, seq_get
from sqlglot.optimizer.scope import find_all_in_scope
from builtins import type as Type
_CONNECT_BY_ARGS_TO_SKIP = frozenset({"connect", "where", "from_", "with_", "expressions"})
# Regex to detect time zones in timestamps of the form [+|-]TT[:tt]
# The pattern matches timezone offsets that appear after the time portion
TIMEZONE_PATTERN = re.compile(r":\d{2}.*?[+\-]\d{2}(?::\d{2})?")
# Characters that must be escaped when building regex expressions in INITCAP
REGEX_ESCAPE_REPLACEMENTS = {
"\\": "\\\\",
"-": r"\-",
"^": r"\^",
"[": r"\[",
"]": r"\]",
}
# Used to in RANDSTR transpilation
RANDSTR_CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
RANDSTR_SEED = 123456
# Whitespace control characters that DuckDB must process with `CHR({val})` calls
WS_CONTROL_CHARS_TO_DUCK = {
"\u000b": 11,
"\u001c": 28,
"\u001d": 29,
"\u001e": 30,
"\u001f": 31,
}
MAX_BIT_POSITION = exp.Literal.number(32768)
# cs/as/ps are Snowflake defaults; DuckDB already behaves the same way, so they are safe to drop.
# Note: "as" is also a reserved keyword in DuckDB, making it impossible to pass through.
_SNOWFLAKE_COLLATION_DEFAULTS = frozenset({"cs", "as", "ps"})
_SNOWFLAKE_COLLATION_UNSUPPORTED = frozenset(
{"ci", "ai", "upper", "lower", "utf8", "bin", "pi", "fl", "fu", "trim", "ltrim", "rtrim"}
)
# Window functions that support IGNORE/RESPECT NULLS in DuckDB
_IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS = (
exp.FirstValue,
exp.Lag,
exp.LastValue,
exp.Lead,
exp.NthValue,
)
# SEQ function constants
_SEQ_BASE: exp.Expr = exp.maybe_parse("(ROW_NUMBER() OVER (ORDER BY 1) - 1)")
_SEQ_RESTRICTED = (exp.Where, exp.Having, exp.AggFunc, exp.Order, exp.Select)
# Maps SEQ expression types to their byte width (suffix indicates bytes: SEQ1=1, SEQ2=2, etc.)
_SEQ_BYTE_WIDTH = {exp.Seq1: 1, exp.Seq2: 2, exp.Seq4: 4, exp.Seq8: 8}
# Template for generating signed and unsigned SEQ values within a specified range
_SEQ_UNSIGNED: exp.Expr = exp.maybe_parse(":base % :max_val")
_SEQ_SIGNED: exp.Expr = exp.maybe_parse(
"(CASE WHEN :base % :max_val >= :half "
"THEN :base % :max_val - :max_val "
"ELSE :base % :max_val END)"
)
def _apply_base64_alphabet_replacements(
result: exp.Expr,
alphabet: exp.Expr | None,
reverse: bool = False,
) -> exp.Expr:
"""
Apply base64 alphabet character replacements.
Base64 alphabet can be 1-3 chars: 1st = index 62 ('+'), 2nd = index 63 ('/'), 3rd = padding ('=').
zip truncates to the shorter string, so 1-char alphabet only replaces '+', 2-char replaces '+/', etc.
Args:
result: The expression to apply replacements to
alphabet: Custom alphabet literal (expected chars for +/=)
reverse: If False, replace default with custom (encode)
If True, replace custom with default (decode)
"""
if isinstance(alphabet, exp.Literal) and alphabet.is_string:
for default_char, new_char in zip("+/=", alphabet.this):
if new_char != default_char:
find, replace = (new_char, default_char) if reverse else (default_char, new_char)
result = exp.Replace(
this=result,
expression=exp.Literal.string(find),
replacement=exp.Literal.string(replace),
)
return result
def _base64_decode_sql(self: DuckDBGenerator, expression: exp.Expr, to_string: bool) -> str:
"""
Transpile Snowflake BASE64_DECODE_STRING/BINARY to DuckDB.
DuckDB uses FROM_BASE64() which returns BLOB. For string output, wrap with DECODE().
Custom alphabets require REPLACE() calls to convert to standard base64.
"""
input_expr = expression.this
alphabet = expression.args.get("alphabet")
# Handle custom alphabet by replacing non-standard chars with standard ones
input_expr = _apply_base64_alphabet_replacements(input_expr, alphabet, reverse=True)
# FROM_BASE64 returns BLOB
input_expr = exp.FromBase64(this=input_expr)
if to_string:
input_expr = exp.Decode(this=input_expr)
return self.sql(input_expr)
def _last_day_sql(self: DuckDBGenerator, expression: exp.LastDay) -> str:
"""
DuckDB's LAST_DAY only supports finding the last day of a month.
For other date parts (year, quarter, week), we need to implement equivalent logic.
"""
date_expr = expression.this
unit = expression.text("unit")
if not unit or unit.upper() == "MONTH":
# Default behavior - use DuckDB's native LAST_DAY
return self.func("LAST_DAY", date_expr)
if unit.upper() == "YEAR":
# Last day of year: December 31st of the same year
year_expr = exp.func("EXTRACT", "YEAR", date_expr)
make_date_expr = exp.func(
"MAKE_DATE", year_expr, exp.Literal.number(12), exp.Literal.number(31)
)
return self.sql(make_date_expr)
if unit.upper() == "QUARTER":
# Last day of quarter
year_expr = exp.func("EXTRACT", "YEAR", date_expr)
quarter_expr = exp.func("EXTRACT", "QUARTER", date_expr)
# Calculate last month of quarter: quarter * 3. Quarter can be 1 to 4
last_month_expr = exp.Mul(this=quarter_expr, expression=exp.Literal.number(3))
first_day_last_month_expr = exp.func(
"MAKE_DATE", year_expr, last_month_expr, exp.Literal.number(1)
)
# Last day of the last month of the quarter
last_day_expr = exp.func("LAST_DAY", first_day_last_month_expr)
return self.sql(last_day_expr)
if unit.upper() == "WEEK":
# DuckDB DAYOFWEEK: Sunday=0, Monday=1, ..., Saturday=6
dow = exp.func("EXTRACT", "DAYOFWEEK", date_expr)
# Days to the last day of week: (7 - dayofweek) % 7, assuming the last day of week is Sunday (Snowflake)
# Wrap in parentheses to ensure correct precedence
days_to_sunday_expr = exp.Mod(
this=exp.Paren(this=exp.Sub(this=exp.Literal.number(7), expression=dow)),
expression=exp.Literal.number(7),
)
interval_expr = exp.Interval(this=days_to_sunday_expr, unit=exp.var("DAY"))
add_expr = exp.Add(this=date_expr, expression=interval_expr)
cast_expr = exp.cast(add_expr, exp.DType.DATE)
return self.sql(cast_expr)
self.unsupported(f"Unsupported date part '{unit}' in LAST_DAY function")
return self.function_fallback_sql(expression)
def _is_nanosecond_unit(unit: exp.Expr | None) -> bool:
return isinstance(unit, (exp.Var, exp.Literal)) and unit.name.upper() == "NANOSECOND"
def _handle_nanosecond_diff(
self: DuckDBGenerator,
end_time: exp.Expr,
start_time: exp.Expr,
) -> str:
"""Generate NANOSECOND diff using EPOCH_NS since DATE_DIFF doesn't support it."""
end_ns = exp.cast(end_time, exp.DType.TIMESTAMP_NS)
start_ns = exp.cast(start_time, exp.DType.TIMESTAMP_NS)
# Build expression tree: EPOCH_NS(end) - EPOCH_NS(start)
return self.sql(
exp.Sub(this=exp.func("EPOCH_NS", end_ns), expression=exp.func("EPOCH_NS", start_ns))
)
def _to_boolean_sql(self: DuckDBGenerator, expression: exp.ToBoolean) -> str:
"""
Transpile TO_BOOLEAN and TRY_TO_BOOLEAN functions from Snowflake to DuckDB equivalent.
DuckDB's CAST to BOOLEAN supports most of Snowflake's TO_BOOLEAN strings except 'on'/'off'.
We need to handle the 'on'/'off' cases explicitly.
For TO_BOOLEAN (safe=False): NaN and INF values cause errors. We use DuckDB's native ERROR()
function to replicate this behavior with a clear error message.
For TRY_TO_BOOLEAN (safe=True): Use DuckDB's TRY_CAST for conversion, which returns NULL
for invalid inputs instead of throwing errors.
"""
arg = expression.this
is_safe = expression.args.get("safe", False)
base_case_expr = (
exp.case()
.when(
# Handle 'on' -> TRUE (case insensitive)
exp.Upper(this=exp.cast(arg, exp.DType.VARCHAR)).eq(exp.Literal.string("ON")),
exp.true(),
)
.when(
# Handle 'off' -> FALSE (case insensitive)
exp.Upper(this=exp.cast(arg, exp.DType.VARCHAR)).eq(exp.Literal.string("OFF")),
exp.false(),
)
)
if is_safe:
# TRY_TO_BOOLEAN: handle 'on'/'off' and use TRY_CAST for everything else
case_expr = base_case_expr.else_(exp.func("TRY_CAST", arg, exp.DType.BOOLEAN.into_expr()))
else:
# TO_BOOLEAN: handle NaN/INF errors, 'on'/'off', and use regular CAST
cast_to_real = exp.func("TRY_CAST", arg, exp.DType.FLOAT.into_expr())
# Check for NaN and INF values
nan_inf_check = exp.Or(
this=exp.func("ISNAN", cast_to_real), expression=exp.func("ISINF", cast_to_real)
)
case_expr = base_case_expr.when(
nan_inf_check,
exp.func(
"ERROR",
exp.Literal.string("TO_BOOLEAN: Non-numeric values NaN and INF are not supported"),
),
).else_(exp.cast(arg, exp.DType.BOOLEAN))
return self.sql(case_expr)
# BigQuery -> DuckDB conversion for the DATE function
def _date_sql(self: DuckDBGenerator, expression: exp.Date) -> str:
this = expression.this
zone = self.sql(expression, "zone")
if zone:
# BigQuery considers "this" at UTC, converts it to the specified
# time zone and then keeps only the DATE part
# To micmic that, we:
# (1) Cast to TIMESTAMP to remove DuckDB's local tz
# (2) Apply consecutive AtTimeZone calls for UTC -> zone conversion
this = exp.cast(this, exp.DType.TIMESTAMP)
at_utc = exp.AtTimeZone(this=this, zone=exp.Literal.string("UTC"))
this = exp.AtTimeZone(this=at_utc, zone=zone)
return self.sql(exp.cast(expression=this, to=exp.DType.DATE))
# BigQuery -> DuckDB conversion for the TIME_DIFF function
def _timediff_sql(self: DuckDBGenerator, expression: exp.TimeDiff) -> str:
unit = expression.unit
if _is_nanosecond_unit(unit):
return _handle_nanosecond_diff(self, expression.expression, expression.this)
this = exp.cast(expression.this, exp.DType.TIME)
expr = exp.cast(expression.expression, exp.DType.TIME)
# Although the 2 dialects share similar signatures, BQ seems to inverse
# the sign of the result so the start/end time operands are flipped
return self.func("DATE_DIFF", unit_to_str(expression), expr, this)
def _date_delta_to_binary_interval_op(
cast: bool = True,
) -> t.Callable[[DuckDBGenerator, DATETIME_DELTA], str]:
"""
DuckDB override to handle:
1. NANOSECOND operations (DuckDB doesn't support INTERVAL ... NANOSECOND)
2. Float/decimal interval values (DuckDB INTERVAL requires integers)
"""
base_impl = date_delta_to_binary_interval_op(cast=cast)
def _duckdb_date_delta_sql(self: DuckDBGenerator, expression: DATETIME_DELTA) -> str:
unit = expression.unit
interval_value = expression.expression
# Handle NANOSECOND unit (DuckDB doesn't support INTERVAL ... NANOSECOND)
if _is_nanosecond_unit(unit):
if isinstance(interval_value, exp.Interval):
interval_value = interval_value.this
timestamp_ns = exp.cast(expression.this, exp.DType.TIMESTAMP_NS)
return self.sql(
exp.func(
"MAKE_TIMESTAMP_NS",
exp.Add(this=exp.func("EPOCH_NS", timestamp_ns), expression=interval_value),
)
)
# Handle float/decimal interval values as duckDB INTERVAL requires integer expressions
if not interval_value or isinstance(interval_value, exp.Interval):
return base_impl(self, expression)
if interval_value.is_type(*exp.DataType.REAL_TYPES):
expression.set("expression", exp.cast(exp.func("ROUND", interval_value), "INT"))
return base_impl(self, expression)
return _duckdb_date_delta_sql
def _array_insert_sql(self: DuckDBGenerator, expression: exp.ArrayInsert) -> str:
"""
Transpile ARRAY_INSERT to DuckDB using LIST_CONCAT and slicing.
Handles:
- 0-based and 1-based indexing (normalizes to 0-based for calculations)
- Negative position conversion (requires array length)
- NULL propagation (source dialects return NULL, DuckDB creates single-element array)
- Assumes position is within bounds per user constraint
Note: All dialects that support ARRAY_INSERT (Snowflake, Spark, Databricks) have
ARRAY_FUNCS_PROPAGATES_NULLS=True, so we always assume source propagates NULLs.
Args:
expression: The ArrayInsert expression to transpile.
Returns:
SQL string implementing ARRAY_INSERT behavior.
"""
this = expression.this
position = expression.args.get("position")
element = expression.expression
element_array = exp.Array(expressions=[element])
index_offset = expression.args.get("offset", 0)
if not position or not position.is_int:
self.unsupported("ARRAY_INSERT can only be transpiled with a literal position")
return self.func("ARRAY_INSERT", this, position, element)
pos_value = position.to_py()
# Normalize one-based indexing to zero-based for slice calculations
# Spark (1-based) -> Snowflake (0-based):
# Positive: pos=1 -> pos=0 (subtract 1)
# Negative: pos=-2 -> pos=-1 (add 1)
# Example: Spark array_insert([a,b,c], -2, d) -> [a,b,d,c] is same as Snowflake pos=-1
if pos_value > 0:
pos_value = pos_value - index_offset
elif pos_value < 0:
pos_value = pos_value + index_offset
# Build the appropriate list_concat expression based on position
if pos_value == 0:
# insert at beginning
concat_exprs = [element_array, this]
elif pos_value > 0:
# Positive position: LIST_CONCAT(arr[1:pos], [elem], arr[pos+1:])
# 0-based -> DuckDB 1-based slicing
# left slice: arr[1:pos]
slice_start = exp.Bracket(
this=this,
expressions=[
exp.Slice(this=exp.Literal.number(1), expression=exp.Literal.number(pos_value))
],
)
# right slice: arr[pos+1:]
slice_end = exp.Bracket(
this=this, expressions=[exp.Slice(this=exp.Literal.number(pos_value + 1))]
)
concat_exprs = [slice_start, element_array, slice_end]
else:
# Negative position: arr[1:LEN(arr)+pos], [elem], arr[LEN(arr)+pos+1:]
# pos=-1 means insert before last element
arr_len = exp.Length(this=this)
# Calculate slice position: LEN(arr) + pos (e.g., LEN(arr) + (-1) = LEN(arr) - 1)
slice_end_pos = arr_len + exp.Literal.number(pos_value)
slice_start_pos = slice_end_pos + exp.Literal.number(1)
# left slice: arr[1:LEN(arr)+pos]
slice_start = exp.Bracket(
this=this,
expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end_pos)],
)
# right slice: arr[LEN(arr)+pos+1:]
slice_end = exp.Bracket(this=this, expressions=[exp.Slice(this=slice_start_pos)])
concat_exprs = [slice_start, element_array, slice_end]
# All dialects that support ARRAY_INSERT propagate NULLs (Snowflake/Spark/Databricks)
# Wrap in CASE WHEN array IS NULL THEN NULL ELSE func_expr END
return self.sql(
exp.If(
this=exp.Is(this=this, expression=exp.Null()),
true=exp.Null(),
false=self.func("LIST_CONCAT", *concat_exprs),
)
)
def _array_remove_at_sql(self: DuckDBGenerator, expression: exp.ArrayRemoveAt) -> str:
"""
Transpile ARRAY_REMOVE_AT to DuckDB using LIST_CONCAT and slicing.
Handles:
- Positive positions (0-based indexing)
- Negative positions (from end of array)
- NULL propagation (Snowflake returns NULL for NULL array, DuckDB doesn't auto-propagate)
- Only supports literal integer positions (non-literals remain untranspiled)
Transpilation patterns:
- pos=0 (first): arr[2:]
- pos>0 (middle): LIST_CONCAT(arr[1:p], arr[p+2:])
- pos=-1 (last): arr[1:LEN(arr)-1]
- pos<-1: LIST_CONCAT(arr[1:LEN(arr)+p], arr[LEN(arr)+p+2:])
All wrapped in: CASE WHEN arr IS NULL THEN NULL ELSE ... END
Args:
expression: The ArrayRemoveAt expression to transpile.
Returns:
SQL string implementing ARRAY_REMOVE_AT behavior.
"""
this = expression.this
position = expression.args.get("position")
if not position or not position.is_int:
self.unsupported("ARRAY_REMOVE_AT can only be transpiled with a literal position")
return self.func("ARRAY_REMOVE_AT", this, position)
pos_value = position.to_py()
# Build the appropriate expression based on position
if pos_value == 0:
# Remove first element: arr[2:]
result_expr: exp.Expr | str = exp.Bracket(
this=this,
expressions=[exp.Slice(this=exp.Literal.number(2))],
)
elif pos_value > 0:
# Remove at positive position: LIST_CONCAT(arr[1:pos], arr[pos+2:])
# DuckDB uses 1-based slicing
left_slice = exp.Bracket(
this=this,
expressions=[
exp.Slice(this=exp.Literal.number(1), expression=exp.Literal.number(pos_value))
],
)
right_slice = exp.Bracket(
this=this,
expressions=[exp.Slice(this=exp.Literal.number(pos_value + 2))],
)
result_expr = self.func("LIST_CONCAT", left_slice, right_slice)
elif pos_value == -1:
# Remove last element: arr[1:LEN(arr)-1]
# Optimization: simpler than general negative case
arr_len = exp.Length(this=this)
slice_end = arr_len + exp.Literal.number(-1)
result_expr = exp.Bracket(
this=this,
expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end)],
)
else:
# Remove at negative position: LIST_CONCAT(arr[1:LEN(arr)+pos], arr[LEN(arr)+pos+2:])
arr_len = exp.Length(this=this)
slice_end_pos = arr_len + exp.Literal.number(pos_value)
slice_start_pos = slice_end_pos + exp.Literal.number(2)
left_slice = exp.Bracket(
this=this,
expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end_pos)],
)
right_slice = exp.Bracket(
this=this,
expressions=[exp.Slice(this=slice_start_pos)],
)
result_expr = self.func("LIST_CONCAT", left_slice, right_slice)
# Snowflake ARRAY_FUNCS_PROPAGATES_NULLS=True, so wrap in NULL check
# CASE WHEN array IS NULL THEN NULL ELSE result_expr END
return self.sql(
exp.If(
this=exp.Is(this=this, expression=exp.Null()),
true=exp.Null(),
false=result_expr,
)
)
@unsupported_args(("expression", "DuckDB's ARRAY_SORT does not support a comparator."))
def _array_sort_sql(self: DuckDBGenerator, expression: exp.ArraySort) -> str:
return self.func("ARRAY_SORT", expression.this)
def _array_contains_sql(self: DuckDBGenerator, expression: exp.ArrayContains) -> str:
this = expression.this
expr = expression.expression
func = self.func("ARRAY_CONTAINS", this, expr)
if expression.args.get("check_null"):
check_null_in_array = exp.Nullif(
this=exp.NEQ(this=exp.ArraySize(this=this), expression=exp.func("LIST_COUNT", this)),
expression=exp.false(),
)
return self.sql(exp.If(this=expr.is_(exp.Null()), true=check_null_in_array, false=func))
return func
def _array_overlaps_sql(self: DuckDBGenerator, expression: exp.ArrayOverlaps) -> str:
"""
Translates Snowflake's NULL-safe ARRAYS_OVERLAP to DuckDB.
DuckDB's native && operator is not NULL-safe: [1,NULL,3] && [NULL,4,5] returns FALSE.
Snowflake returns TRUE when both arrays contain NULL (NULLs are treated as known values).
Generated SQL: (arr1 && arr2) OR (ARRAY_LENGTH(arr1) <> LIST_COUNT(arr1) AND ARRAY_LENGTH(arr2) <> LIST_COUNT(arr2))
ARRAY_LENGTH counts all elements (including NULLs); LIST_COUNT counts only non-NULLs.
When they differ, the array contains at least one NULL, matching Snowflake's NULL-safe semantics.
"""
if not expression.args.get("null_safe"):
return self.binary(expression, "&&")
arr1 = expression.this
arr2 = expression.expression
check_nulls = exp.and_(
exp.NEQ(
this=exp.ArraySize(this=arr1.copy()),
expression=exp.func("LIST_COUNT", arr1.copy()),
),
exp.NEQ(
this=exp.ArraySize(this=arr2.copy()),
expression=exp.func("LIST_COUNT", arr2.copy()),
),
copy=False,
)
overlap = exp.ArrayOverlaps(this=arr1.copy(), expression=arr2.copy())
return self.sql(
exp.or_(
exp.paren(overlap, copy=False),
exp.paren(check_nulls, copy=False),
copy=False,
wrap=False,
)
)
def _struct_sql(self: DuckDBGenerator, expression: exp.Struct) -> str:
ancestor_cast = expression.find_ancestor(exp.Cast, exp.Select)
ancestor_cast = None if isinstance(ancestor_cast, exp.Select) else ancestor_cast
# Empty struct cast works with MAP() since DuckDB can't parse {}
if not expression.expressions:
if isinstance(ancestor_cast, exp.Cast) and ancestor_cast.to.is_type(exp.DType.MAP):
return "MAP()"
args: list[str] = []
# BigQuery allows inline construction such as "STRUCT<a STRING, b INTEGER>('str', 1)" which is
# canonicalized to "ROW('str', 1) AS STRUCT(a TEXT, b INT)" in DuckDB
# The transformation to ROW will take place if:
# 1. The STRUCT itself does not have proper fields (key := value) as a "proper" STRUCT would
# 2. A cast to STRUCT / ARRAY of STRUCTs is found
is_bq_inline_struct = (
(expression.find(exp.PropertyEQ) is None)
and ancestor_cast
and any(
casted_type.is_type(exp.DType.STRUCT)
for casted_type in ancestor_cast.find_all(exp.DataType)
)
)
for i, expr in enumerate(expression.expressions):
is_property_eq = isinstance(expr, exp.PropertyEQ)
this = expr.this
value = expr.expression if is_property_eq else expr
if is_bq_inline_struct:
args.append(self.sql(value))
else:
if isinstance(this, exp.Identifier):
key = self.sql(exp.Literal.string(expr.name))
elif is_property_eq:
key = self.sql(this)
else:
key = self.sql(exp.Literal.string(f"_{i}"))
args.append(f"{key}: {self.sql(value)}")
csv_args = ", ".join(args)
return f"ROW({csv_args})" if is_bq_inline_struct else f"{{{csv_args}}}"
def _datatype_sql(self: DuckDBGenerator, expression: exp.DataType) -> str:
if expression.is_type("array"):
return f"{self.expressions(expression, flat=True)}[{self.expressions(expression, key='values', flat=True)}]"
# Modifiers are not supported for TIME, [TIME | TIMESTAMP] WITH TIME ZONE
if expression.is_type(exp.DType.TIME, exp.DType.TIMETZ, exp.DType.TIMESTAMPTZ):
return expression.this.value
return self.datatype_sql(expression)
def _json_format_sql(self: DuckDBGenerator, expression: exp.JSONFormat) -> str:
sql = self.func("TO_JSON", expression.this, expression.args.get("options"))
return f"CAST({sql} AS TEXT)"
def _build_seq_expression(base: exp.Expr, byte_width: int, signed: bool) -> exp.Expr:
"""Build a SEQ expression with the given base, byte width, and signedness."""
bits = byte_width * 8
max_val = exp.Literal.number(2**bits)
if signed:
half = exp.Literal.number(2 ** (bits - 1))
return exp.replace_placeholders(_SEQ_SIGNED.copy(), base=base, max_val=max_val, half=half)
return exp.replace_placeholders(_SEQ_UNSIGNED.copy(), base=base, max_val=max_val)
def _seq_to_range_in_generator(expression: exp.Expr) -> exp.Expr:
"""
Transform SEQ functions to `range` column references when inside a GENERATOR context.
When GENERATOR(ROWCOUNT => N) becomes RANGE(N) in DuckDB, it produces a column
named `range` with values 0, 1, ..., N-1. SEQ functions produce the same sequence,
so we replace them with `range % max_val` to avoid nested window function issues.
"""
if not isinstance(expression, exp.Select):
return expression
from_ = expression.args.get("from_")
if not (
from_
and isinstance(from_.this, exp.TableFromRows)
and isinstance(from_.this.this, exp.Generator)
):
return expression
def replace_seq(node: exp.Expr) -> exp.Expr:
if isinstance(node, (exp.Seq1, exp.Seq2, exp.Seq4, exp.Seq8)):
byte_width = _SEQ_BYTE_WIDTH[type(node)]
return _build_seq_expression(exp.column("range"), byte_width, signed=node.name == "1")
return node
return expression.transform(replace_seq, copy=False)
def connect_by_to_recursive_cte(expression: exp.Expr) -> exp.Expr:
# Rewrites START WITH ... CONNECT BY PRIOR into WITH RECURSIVE
# Falls through unchanged if there are no PRIORs.
if not isinstance(expression, exp.Select) or not expression.args.get("connect"):
return expression
connect = expression.args["connect"]
connect_pred = connect.args["connect"]
priors = list(connect_pred.find_all(exp.Prior))
if not priors:
return expression
from_ = expression.args.get("from_")
if not from_ or expression.args.get("joins"):
return expression
source_table = from_.this
base_select_exprs = expression.expressions
base_where = expression.args.get("where")
base_with = expression.args.get("with_")
# LEVEL is a Snowflake pseudo-column: it's always computed as a depth counter in the CTE.
has_level = any(
isinstance(col, exp.Column) and col.name.upper() == "LEVEL"
for e in base_select_exprs
for col in e.find_all(exp.Column)
)
has_star = expression.is_star
# CONNECT_BY_ROOT col yields the value of `col` from the START WITH row that begins each
# branch. Each one is threaded through the CTE as an extra column: the anchor binds it to the
# row's own value, the recursive arm forwards the parent's value unchanged.
root_col_names: list[str] = []
anchor_root_cols: list[exp.Expr] = []
inner_root_cols: list[exp.Expr] = []
roots = [root for e in base_select_exprs for root in e.find_all(exp.ConnectByRoot)]
for i, root in enumerate(roots):
name = f"_connect_by_root_{i}"
root_col_names.append(name)
anchor_root_cols.append(exp.alias_(root.this, name))
inner_root_cols.append(exp.alias_(exp.column(name, "_parent_row"), name))
root.replace(exp.column(name))
# Build the join condition from the full CONNECT BY predicate:
# PRIOR(col) → _parent_row.col, unqualified cols → _child_row.col.
def _qualify_connect_pred(node: exp.Expression) -> exp.Expression:
for col in find_all_in_scope(node, exp.Column):
col.set(
"table",
exp.to_identifier(
"_parent_row" if isinstance(col.parent, exp.Prior) else "_child_row"
),
)
for prior in find_all_in_scope(node, exp.Prior):
prior.replace(prior.this)
return node
# Avoid colliding with any CTE names already on the query.
cte_name = find_new_name(
{cte.alias for cte in (base_with.expressions if base_with else [])}, "_rootcte"
)
# Anchor: project all source columns + seed LEVEL at 1 + bind each root column to its own value.
anchor = exp.select(
exp.Star(), exp.alias_(exp.Literal.number(1), "level"), *anchor_root_cols
).from_(source_table)
if connect.args.get("start"):
anchor = anchor.where(connect.args["start"])
# Recursive arm: carry all child columns + increment level + forward each root value.
# SELECT * in both arms means WHERE/PRIOR columns are always available without explicit tracking.
inner_query = (
exp.select(
exp.Column(this=exp.Star(), table=exp.to_identifier("_child_row")),
exp.alias_(exp.column("level", "_parent_row") + 1, "level"),
*inner_root_cols,
)
.from_(source_table.as_("_child_row"))
.join(exp.to_table(cte_name).as_("_parent_row"), on=_qualify_connect_pred(connect_pred))
)
# Outer SELECT re-projects from the CTE. Synthetic level/root columns are excluded from any
# star expansion (level only when not referenced) but kept where explicitly projected.
if has_star:
except_cols = [] if has_level else [exp.column("level")]
except_cols.extend(exp.column(name) for name in root_col_names)
star = exp.Star(except_=except_cols) if except_cols else exp.Star()
outer_select_exprs: list[exp.Expr] = [
star,
*(e for e in base_select_exprs if not e.is_star),
]
else:
outer_select_exprs = base_select_exprs
outer_query = exp.select(*outer_select_exprs).from_(cte_name)
if base_where:
outer_query = outer_query.where(base_where.this)
# Attach the CTE, marking the WITH clause recursive.
if base_with:
outer_query.set("with_", base_with)
outer_query = outer_query.with_(
cte_name, as_=anchor.union(inner_query, distinct=False), recursive=True, copy=False
)
for arg, val in expression.args.items():
if val and arg not in _CONNECT_BY_ARGS_TO_SKIP:
outer_query.set(arg, val)
# Strip stale source table qualifiers in one pass; CTEs are child scopes so
# find_all_in_scope stays within the outer query only.
for col in find_all_in_scope(outer_query, exp.Column):
col.set("table", None)
return outer_query
def _seq_sql(self: DuckDBGenerator, expression: exp.Func, byte_width: int) -> str:
"""
Transpile Snowflake SEQ1/SEQ2/SEQ4/SEQ8 to DuckDB.
Generates monotonically increasing integers starting from 0.
The signed parameter (0 or 1) affects wrap-around behavior:
- Unsigned (0): wraps at 2^(bits) - 1
- Signed (1): wraps at 2^(bits-1) - 1, then goes negative
"""
# Warn if SEQ is in a restricted context (Select stops search at current scope)
ancestor = expression.find_ancestor(*_SEQ_RESTRICTED)
if ancestor and (
(not isinstance(ancestor, (exp.Order, exp.Select)))
or (isinstance(ancestor, exp.Order) and isinstance(ancestor.parent, exp.Window))
):
self.unsupported("SEQ in restricted context is not supported - use CTE or subquery")
result = _build_seq_expression(_SEQ_BASE.copy(), byte_width, signed=expression.name == "1")
return self.sql(result)
def _unix_to_time_sql(self: DuckDBGenerator, expression: exp.UnixToTime) -> str:
scale = expression.args.get("scale")
timestamp = expression.this
target_type = expression.args.get("target_type")
# Check if we need NTZ (naive timestamp in UTC)
is_ntz = target_type and target_type.this in (
exp.DType.TIMESTAMP,
exp.DType.TIMESTAMPNTZ,
)
if scale == exp.UnixToTime.MILLIS:
# EPOCH_MS already returns TIMESTAMP (naive, UTC)
return self.func("EPOCH_MS", timestamp)
if scale == exp.UnixToTime.MICROS:
# MAKE_TIMESTAMP already returns TIMESTAMP (naive, UTC)
return self.func("MAKE_TIMESTAMP", timestamp)
# Other scales: divide and use TO_TIMESTAMP
if scale not in (None, exp.UnixToTime.SECONDS):
timestamp = exp.Div(this=timestamp, expression=exp.func("POW", 10, scale))
to_timestamp: exp.Expr = exp.Anonymous(this="TO_TIMESTAMP", expressions=[timestamp])
if is_ntz:
to_timestamp = exp.AtTimeZone(this=to_timestamp, zone=exp.Literal.string("UTC"))
return self.sql(to_timestamp)
WRAPPED_JSON_EXTRACT_EXPRESSIONS = (exp.Binary, exp.Bracket, exp.In, exp.Not)
def _arrow_json_extract_sql(self: DuckDBGenerator, expression: JSON_EXTRACT_TYPE) -> str:
arrow_sql = arrow_json_extract_sql(self, expression)
if not expression.same_parent and isinstance(
expression.parent, WRAPPED_JSON_EXTRACT_EXPRESSIONS
):
arrow_sql = self.wrap(arrow_sql)
return arrow_sql
def _implicit_datetime_cast(
arg: exp.Expr | None, type: exp.DType = exp.DType.DATE
) -> exp.Expr | None:
if isinstance(arg, exp.Literal) and arg.is_string:
ts = arg.name
if type == exp.DType.DATE and ":" in ts:
type = exp.DType.TIMESTAMPTZ if TIMEZONE_PATTERN.search(ts) else exp.DType.TIMESTAMP
arg = exp.cast(arg, type)
return arg
def _build_week_trunc_expression(
date_expr: exp.Expr,
start_dow: int,
preserve_start_day: bool = False,
) -> exp.Expr:
"""
Build DATE_TRUNC expression for week boundaries with custom start day.
DuckDB's DATE_TRUNC('WEEK', ...) always returns Monday. To align to a different
start day, we shift the date before truncating.
Args:
date_expr: The date expression to truncate.
start_dow: ISO 8601 day-of-week number (Monday=1, ..., Sunday=7).
preserve_start_day: If True, reverse the shift after truncating so the result lands on the
correct week start day. Needed for DATE_TRUNC (absolute result matters) but
not for DATE_DIFF (only relative alignment matters).
Shift formula: Sunday (7) gets +1, others get (1 - start_dow).
"""
shift_days = 1 if start_dow == 7 else 1 - start_dow
truncated = exp.func("DATE_TRUNC", unit=exp.var("WEEK"), this=date_expr)
if shift_days == 0:
return truncated
shift = exp.Interval(this=exp.Literal.string(str(shift_days)), unit=exp.var("DAY"))
shifted_date = exp.DateAdd(this=date_expr, expression=shift)
truncated.set("this", shifted_date)
if preserve_start_day:
interval = exp.Interval(this=exp.Literal.string(str(-shift_days)), unit=exp.var("DAY"))
return exp.cast(
exp.DateAdd(this=truncated, expression=interval), to=exp.DType.DATE, copy=False
)
return truncated
def _date_diff_sql(self: DuckDBGenerator, expression: exp.DateDiff | exp.DatetimeDiff) -> str:
unit = expression.unit
if _is_nanosecond_unit(unit):
return _handle_nanosecond_diff(self, expression.this, expression.expression)
this = _implicit_datetime_cast(expression.this)
expr = _implicit_datetime_cast(expression.expression)
# DuckDB's WEEK diff does not respect Monday crossing (week boundaries), it checks (end_day - start_day) / 7:
# SELECT DATE_DIFF('WEEK', CAST('2024-12-13' AS DATE), CAST('2024-12-17' AS DATE)) --> 0 (Monday crossed)
# SELECT DATE_DIFF('WEEK', CAST('2024-12-13' AS DATE), CAST('2024-12-20' AS DATE)) --> 1 (7 days difference)
# Whereas for other units such as MONTH it does respect month boundaries:
# SELECT DATE_DIFF('MONTH', CAST('2024-11-30' AS DATE), CAST('2024-12-01' AS DATE)) --> 1 (Month crossed)
date_part_boundary = expression.args.get("date_part_boundary")
# Extract week start day; returns None if day is dynamic (column/placeholder)
week_start = week_unit_to_dow(unit)
if date_part_boundary and week_start and this and expr:
expression.set("unit", exp.Literal.string("WEEK"))
# Truncate both dates to week boundaries to respect input dialect semantics
this = _build_week_trunc_expression(this, week_start)
expr = _build_week_trunc_expression(expr, week_start)
return self.func("DATE_DIFF", unit_to_str(expression), expr, this)
def _generate_datetime_array_sql(
self: DuckDBGenerator, expression: exp.GenerateDateArray | exp.GenerateTimestampArray
) -> str:
is_generate_date_array = isinstance(expression, exp.GenerateDateArray)
type = exp.DType.DATE if is_generate_date_array else exp.DType.TIMESTAMP
start = _implicit_datetime_cast(expression.args.get("start"), type=type)
end = _implicit_datetime_cast(expression.args.get("end"), type=type)
# BQ's GENERATE_DATE_ARRAY & GENERATE_TIMESTAMP_ARRAY are transformed to DuckDB'S GENERATE_SERIES
gen_series: exp.GenerateSeries | exp.Cast = exp.GenerateSeries(
start=start, end=end, step=expression.args.get("step")
)
if is_generate_date_array:
# The GENERATE_SERIES result type is TIMESTAMP array, so to match BQ's semantics for
# GENERATE_DATE_ARRAY we must cast it back to DATE array
gen_series = exp.cast(gen_series, exp.DataType.from_str("ARRAY<DATE>"))
return self.sql(gen_series)
def _json_extract_value_array_sql(
self: DuckDBGenerator, expression: exp.JSONValueArray | exp.JSONExtractArray
) -> str:
json_extract = exp.JSONExtract(this=expression.this, expression=expression.expression)
data_type = "ARRAY<STRING>" if isinstance(expression, exp.JSONValueArray) else "ARRAY<JSON>"
return self.sql(exp.cast(json_extract, to=exp.DataType.from_str(data_type)))
def _cast_to_varchar(arg: exp.Expr | None) -> exp.Expr | None:
if arg and arg.type and not arg.is_type(*exp.DataType.TEXT_TYPES, exp.DType.UNKNOWN):
return exp.cast(arg, exp.DType.VARCHAR)
return arg