sqlglot.generators.duckdb
1from __future__ import annotations 2 3from decimal import Decimal 4from itertools import groupby 5import re 6import typing as t 7 8from sqlglot import exp, generator, transforms 9from sqlglot.dialects.dialect import ( 10 array_sort_order, 11 DATETIME_DELTA, 12 JSON_EXTRACT_TYPE, 13 approx_count_distinct_sql, 14 arrow_json_extract_sql, 15 array_append_sql, 16 array_compact_sql, 17 array_concat_sql, 18 count_if_to_sum, 19 date_delta_to_binary_interval_op, 20 datestrtodate_sql, 21 encode_decode_sql, 22 explode_to_unnest_sql, 23 generate_series_sql, 24 getbit_sql, 25 groupconcat_sql, 26 inline_array_unless_query, 27 map_date_part, 28 months_between_sql, 29 no_datetime_sql, 30 no_comment_column_constraint_sql, 31 no_make_interval_sql, 32 no_time_sql, 33 no_timestamp_sql, 34 rename_func, 35 remove_from_array_using_filter, 36 strposition_sql, 37 timestrtotime_sql, 38 unit_to_str, 39 week_unit_to_dow, 40 weekstart_unit_to_str, 41 WEEK_START_DAY_TO_DOW, 42) 43from sqlglot.generator import unsupported_args 44from sqlglot.helper import decode_unicode_escapes, find_new_name, is_date_unit, seq_get 45from sqlglot.optimizer.scope import find_all_in_scope 46from builtins import type as Type 47 48_SIMILAR_TO_REGEX_CHARS = frozenset(r"\|*+?{}()[]") 49 50_ROUND_SCALE_INTEGER_TYPES = exp.DataType.INTEGER_TYPES - {exp.DType.BIGNUM} 51 52_CONNECT_BY_ARGS_TO_SKIP = frozenset({"connect", "where", "from_", "with_", "expressions"}) 53 54# Regex to detect time zones in timestamps of the form [+|-]TT[:tt] 55# The pattern matches timezone offsets that appear after the time portion 56TIMEZONE_PATTERN = re.compile(r":\d{2}.*?[+\-]\d{2}(?::\d{2})?") 57 58# Characters that must be escaped when building regex expressions in INITCAP 59REGEX_ESCAPE_REPLACEMENTS = { 60 "\\": "\\\\", 61 "-": r"\-", 62 "^": r"\^", 63 "[": r"\[", 64 "]": r"\]", 65} 66 67# Used to in RANDSTR transpilation 68RANDSTR_CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 69RANDSTR_SEED = 123456 70 71# Whitespace control characters that DuckDB must process with `CHR({val})` calls 72WS_CONTROL_CHARS_TO_DUCK = { 73 "\u000b": 11, 74 "\u001c": 28, 75 "\u001d": 29, 76 "\u001e": 30, 77 "\u001f": 31, 78} 79 80MAX_BIT_POSITION = exp.Literal.number(32768) 81 82# cs/as/ps are Snowflake defaults; DuckDB already behaves the same way, so they are safe to drop. 83# Note: "as" is also a reserved keyword in DuckDB, making it impossible to pass through. 84_SNOWFLAKE_COLLATION_DEFAULTS = frozenset({"cs", "as", "ps"}) 85_SNOWFLAKE_COLLATION_UNSUPPORTED = frozenset( 86 {"ci", "ai", "upper", "lower", "utf8", "bin", "pi", "fl", "fu", "trim", "ltrim", "rtrim"} 87) 88 89# Window functions that support IGNORE/RESPECT NULLS in DuckDB 90_IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS = ( 91 exp.FirstValue, 92 exp.Lag, 93 exp.LastValue, 94 exp.Lead, 95 exp.NthValue, 96) 97 98# SEQ function constants 99_SEQ_BASE: exp.Expr = exp.maybe_parse("(ROW_NUMBER() OVER (ORDER BY 1) - 1)") 100_SEQ_RESTRICTED = (exp.Where, exp.Having, exp.AggFunc, exp.Order, exp.Select) 101# Maps SEQ expression types to their byte width (suffix indicates bytes: SEQ1=1, SEQ2=2, etc.) 102_SEQ_BYTE_WIDTH = {exp.Seq1: 1, exp.Seq2: 2, exp.Seq4: 4, exp.Seq8: 8} 103 104# Template for generating signed and unsigned SEQ values within a specified range 105_SEQ_UNSIGNED: exp.Expr = exp.maybe_parse(":base % :max_val") 106_SEQ_SIGNED: exp.Expr = exp.maybe_parse( 107 "(CASE WHEN :base % :max_val >= :half " 108 "THEN :base % :max_val - :max_val " 109 "ELSE :base % :max_val END)" 110) 111 112 113def _apply_base64_alphabet_replacements( 114 result: exp.Expr, 115 alphabet: exp.Expr | None, 116 reverse: bool = False, 117) -> exp.Expr: 118 """ 119 Translate base64 alphabet characters without cascading replacements. 120 121 Base64 alphabet can be 1-3 chars: 1st = index 62 ('+'), 2nd = index 63 ('/'), 3rd = padding ('='). 122 zip truncates to the shorter string, so 1-char alphabet only replaces '+', 2-char replaces '+/', etc. 123 124 Args: 125 result: The expression to apply replacements to 126 alphabet: Custom alphabet literal (expected chars for +/=) 127 reverse: If False, replace default with custom (encode) 128 If True, replace custom with default (decode) 129 """ 130 if isinstance(alphabet, exp.Literal) and alphabet.is_string: 131 source, target = "", "" 132 for default_char, new_char in zip("+/=", alphabet.this): 133 if new_char != default_char: 134 source += default_char 135 target += new_char 136 if source: 137 if reverse: 138 source, target = target, source 139 result = exp.Translate( 140 this=result, 141 from_=exp.Literal.string(source), 142 to=exp.Literal.string(target), 143 ) 144 return result 145 146 147def _base64_decode_sql(self: DuckDBGenerator, expression: exp.Expr, to_string: bool) -> str: 148 """ 149 Transpile Snowflake BASE64_DECODE_STRING/BINARY to DuckDB. 150 151 DuckDB uses FROM_BASE64() which returns BLOB. For string output, wrap with DECODE(). 152 Custom alphabets require TRANSLATE() to convert to standard base64. 153 """ 154 input_expr = expression.this 155 alphabet = expression.args.get("alphabet") 156 157 # Handle custom alphabet by replacing non-standard chars with standard ones 158 input_expr = _apply_base64_alphabet_replacements(input_expr, alphabet, reverse=True) 159 160 # FROM_BASE64 returns BLOB 161 input_expr = exp.FromBase64(this=input_expr) 162 163 if to_string: 164 input_expr = exp.Decode(this=input_expr) 165 166 return self.sql(input_expr) 167 168 169def _last_day_sql(self: DuckDBGenerator, expression: exp.LastDay) -> str: 170 """ 171 DuckDB's LAST_DAY only supports finding the last day of a month. 172 For other date parts (year, quarter, week), we need to implement equivalent logic. 173 """ 174 date_expr = expression.this 175 unit_expr = expression.args.get("unit") 176 177 week_start = week_unit_to_dow(unit_expr) 178 if week_start: 179 # The week's last day precedes its start day; DuckDB DAYOFWEEK: Sunday=0, ..., Saturday=6 180 last_dow = week_start - 1 181 dow = exp.func("EXTRACT", "DAYOFWEEK", date_expr) 182 183 # Days to the last day of week: (last_dow + 7 - dayofweek) % 7 184 days_to_last_expr = exp.Mod( 185 this=exp.Paren(this=exp.Sub(this=exp.Literal.number(last_dow + 7), expression=dow)), 186 expression=exp.Literal.number(7), 187 ) 188 interval_expr = exp.Interval(this=days_to_last_expr, unit=exp.var("DAY")) 189 add_expr = exp.Add(this=date_expr, expression=interval_expr) 190 191 return self.sql(exp.cast(add_expr, exp.DType.DATE)) 192 193 unit = expression.text("unit") 194 195 if not unit or unit.upper() == "MONTH": 196 # Default behavior - use DuckDB's native LAST_DAY 197 return self.func("LAST_DAY", date_expr) 198 199 if unit.upper() == "YEAR": 200 # Last day of year: December 31st of the same year 201 year_expr = exp.func("EXTRACT", "YEAR", date_expr) 202 make_date_expr = exp.func( 203 "MAKE_DATE", year_expr, exp.Literal.number(12), exp.Literal.number(31) 204 ) 205 return self.sql(make_date_expr) 206 207 if unit.upper() == "QUARTER": 208 # Last day of quarter 209 year_expr = exp.func("EXTRACT", "YEAR", date_expr) 210 quarter_expr = exp.func("EXTRACT", "QUARTER", date_expr) 211 212 # Calculate last month of quarter: quarter * 3. Quarter can be 1 to 4 213 last_month_expr = exp.Mul(this=quarter_expr, expression=exp.Literal.number(3)) 214 first_day_last_month_expr = exp.func( 215 "MAKE_DATE", year_expr, last_month_expr, exp.Literal.number(1) 216 ) 217 218 # Last day of the last month of the quarter 219 last_day_expr = exp.func("LAST_DAY", first_day_last_month_expr) 220 return self.sql(last_day_expr) 221 222 self.unsupported(f"Unsupported date part '{unit}' in LAST_DAY function") 223 return self.function_fallback_sql(expression) 224 225 226def _is_nanosecond_unit(unit: exp.Expr | None) -> bool: 227 return isinstance(unit, (exp.Var, exp.Literal)) and unit.name.upper() == "NANOSECOND" 228 229 230def _handle_nanosecond_diff( 231 self: DuckDBGenerator, 232 end_time: exp.Expr, 233 start_time: exp.Expr, 234) -> str: 235 """Generate NANOSECOND diff using EPOCH_NS since DATE_DIFF doesn't support it.""" 236 end_ns = exp.cast(end_time, exp.DType.TIMESTAMP_NS) 237 start_ns = exp.cast(start_time, exp.DType.TIMESTAMP_NS) 238 239 # Build expression tree: EPOCH_NS(end) - EPOCH_NS(start) 240 return self.sql( 241 exp.Sub(this=exp.func("EPOCH_NS", end_ns), expression=exp.func("EPOCH_NS", start_ns)) 242 ) 243 244 245def _to_boolean_sql(self: DuckDBGenerator, expression: exp.ToBoolean) -> str: 246 """ 247 Transpile TO_BOOLEAN and TRY_TO_BOOLEAN functions from Snowflake to DuckDB equivalent. 248 249 DuckDB's CAST to BOOLEAN supports most of Snowflake's TO_BOOLEAN strings except 'on'/'off'. 250 We need to handle the 'on'/'off' cases explicitly. 251 252 For TO_BOOLEAN (safe=False): NaN and INF values cause errors. We use DuckDB's native ERROR() 253 function to replicate this behavior with a clear error message. 254 255 For TRY_TO_BOOLEAN (safe=True): Use DuckDB's TRY_CAST for conversion, which returns NULL 256 for invalid inputs instead of throwing errors. 257 """ 258 arg = expression.this 259 is_safe = expression.args.get("safe", False) 260 261 base_case_expr = ( 262 exp.case() 263 .when( 264 # Handle 'on' -> TRUE (case insensitive) 265 exp.Upper(this=exp.cast(arg, exp.DType.VARCHAR)).eq(exp.Literal.string("ON")), 266 exp.true(), 267 ) 268 .when( 269 # Handle 'off' -> FALSE (case insensitive) 270 exp.Upper(this=exp.cast(arg, exp.DType.VARCHAR)).eq(exp.Literal.string("OFF")), 271 exp.false(), 272 ) 273 ) 274 275 if is_safe: 276 # TRY_TO_BOOLEAN: handle 'on'/'off' and use TRY_CAST for everything else 277 case_expr = base_case_expr.else_(exp.func("TRY_CAST", arg, exp.DType.BOOLEAN.into_expr())) 278 else: 279 # TO_BOOLEAN: handle NaN/INF errors, 'on'/'off', and use regular CAST 280 cast_to_real = exp.func("TRY_CAST", arg, exp.DType.FLOAT.into_expr()) 281 282 # Check for NaN and INF values 283 nan_inf_check = exp.Or( 284 this=exp.func("ISNAN", cast_to_real), expression=exp.func("ISINF", cast_to_real) 285 ) 286 287 case_expr = base_case_expr.when( 288 nan_inf_check, 289 exp.func( 290 "ERROR", 291 exp.Literal.string("TO_BOOLEAN: Non-numeric values NaN and INF are not supported"), 292 ), 293 ).else_(exp.cast(arg, exp.DType.BOOLEAN)) 294 295 return self.sql(case_expr) 296 297 298def _normalize_timezone_offset(zone: exp.Expr) -> exp.Expr: 299 # DuckDB needs the GMT prefix to preserve minutes in offsets like UTC+05:30. 300 offset_prefix = r"^(?:UTC)?([+-])" 301 replacement = r"GMT\1" 302 if zone.is_string: 303 name = re.sub(offset_prefix, replacement, zone.name) 304 return exp.Literal.string(name) if name != zone.name else zone 305 306 return exp.RegexpReplace( 307 this=zone, 308 expression=exp.Literal.string(offset_prefix), 309 replacement=exp.Literal.string(replacement), 310 single_replace=True, 311 ) 312 313 314# BigQuery -> DuckDB conversion for the DATE function 315def _date_sql(self: DuckDBGenerator, expression: exp.Date) -> str: 316 this = expression.this 317 zone = self.sql(expression, "zone") 318 319 if zone: 320 # BigQuery considers "this" at UTC, converts it to the specified 321 # time zone and then keeps only the DATE part 322 # To micmic that, we: 323 # (1) Cast to TIMESTAMP to remove DuckDB's local tz 324 # (2) Apply consecutive AtTimeZone calls for UTC -> zone conversion 325 this = exp.cast(this, exp.DType.TIMESTAMP) 326 at_utc = exp.AtTimeZone(this=this, zone=exp.Literal.string("UTC")) 327 this = exp.AtTimeZone(this=at_utc, zone=zone) 328 329 return self.sql(exp.cast(expression=this, to=exp.DType.DATE)) 330 331 332# BigQuery -> DuckDB conversion for the TIME_DIFF function 333def _timediff_sql(self: DuckDBGenerator, expression: exp.TimeDiff) -> str: 334 unit = expression.unit 335 336 if _is_nanosecond_unit(unit): 337 return _handle_nanosecond_diff(self, expression.expression, expression.this) 338 339 this = exp.cast(expression.this, exp.DType.TIME) 340 expr = exp.cast(expression.expression, exp.DType.TIME) 341 342 # Although the 2 dialects share similar signatures, BQ seems to inverse 343 # the sign of the result so the start/end time operands are flipped 344 return self.func("DATE_DIFF", unit_to_str(expression), expr, this) 345 346 347def _date_delta_to_binary_interval_op( 348 cast: bool = True, 349) -> t.Callable[[DuckDBGenerator, DATETIME_DELTA], str]: 350 """ 351 DuckDB override to handle: 352 1. NANOSECOND operations (DuckDB doesn't support INTERVAL ... NANOSECOND) 353 2. Float/decimal interval values (DuckDB INTERVAL requires integers) 354 """ 355 base_impl = date_delta_to_binary_interval_op(cast=cast) 356 357 def _duckdb_date_delta_sql(self: DuckDBGenerator, expression: DATETIME_DELTA) -> str: 358 unit = expression.unit 359 interval_value = expression.expression 360 361 # Handle NANOSECOND unit (DuckDB doesn't support INTERVAL ... NANOSECOND) 362 if _is_nanosecond_unit(unit): 363 if isinstance(interval_value, exp.Interval): 364 interval_value = interval_value.this 365 366 timestamp_ns = exp.cast(expression.this, exp.DType.TIMESTAMP_NS) 367 368 return self.sql( 369 exp.func( 370 "MAKE_TIMESTAMP_NS", 371 exp.Add(this=exp.func("EPOCH_NS", timestamp_ns), expression=interval_value), 372 ) 373 ) 374 375 # Handle float/decimal interval values as duckDB INTERVAL requires integer expressions 376 if not interval_value or isinstance(interval_value, exp.Interval): 377 return base_impl(self, expression) 378 379 if interval_value.is_type(*exp.DataType.REAL_TYPES): 380 expression.set("expression", exp.cast(exp.func("ROUND", interval_value), "INT")) 381 382 return base_impl(self, expression) 383 384 return _duckdb_date_delta_sql 385 386 387def _array_insert_sql(self: DuckDBGenerator, expression: exp.ArrayInsert) -> str: 388 """ 389 Transpile ARRAY_INSERT to DuckDB using LIST_CONCAT and slicing. 390 391 Handles: 392 - 0-based and 1-based indexing (normalizes to 0-based for calculations) 393 - Negative position conversion (requires array length) 394 - NULL propagation (source dialects return NULL, DuckDB creates single-element array) 395 - Assumes position is within bounds per user constraint 396 397 Note: All dialects that support ARRAY_INSERT (Snowflake, Spark, Databricks) have 398 ARRAY_FUNCS_PROPAGATES_NULLS=True, so we always assume source propagates NULLs. 399 400 Args: 401 expression: The ArrayInsert expression to transpile. 402 403 Returns: 404 SQL string implementing ARRAY_INSERT behavior. 405 """ 406 this = expression.this 407 position = expression.args.get("position") 408 element = expression.expression 409 element_array = exp.Array(expressions=[element]) 410 index_offset = expression.args.get("offset", 0) 411 412 if not position or not position.is_int: 413 self.unsupported("ARRAY_INSERT can only be transpiled with a literal position") 414 return self.func("ARRAY_INSERT", this, position, element) 415 416 pos_value = position.to_py() 417 418 # 1-based -1 appends (Spark/Databricks); the 0-based normalization below 419 # would otherwise map it onto the prepend branch. 420 append = index_offset == 1 and pos_value == -1 421 422 # Normalize one-based indexing to zero-based for slice calculations 423 # Spark (1-based) -> Snowflake (0-based): 424 # Positive: pos=1 -> pos=0 (subtract 1) 425 # Negative: pos=-2 -> pos=-1 (add 1) 426 # Example: Spark array_insert([a,b,c], -2, d) -> [a,b,d,c] is same as Snowflake pos=-1 427 if pos_value > 0: 428 pos_value = pos_value - index_offset 429 elif pos_value < 0: 430 pos_value = pos_value + index_offset 431 432 # Build the appropriate list_concat expression based on position 433 if append: 434 # append at end 435 concat_exprs = [this, element_array] 436 elif pos_value == 0: 437 # insert at beginning 438 concat_exprs = [element_array, this] 439 elif pos_value > 0: 440 # Positive position: LIST_CONCAT(arr[1:pos], [elem], arr[pos+1:]) 441 # 0-based -> DuckDB 1-based slicing 442 443 # left slice: arr[1:pos] 444 slice_start = exp.Bracket( 445 this=this, 446 expressions=[ 447 exp.Slice(this=exp.Literal.number(1), expression=exp.Literal.number(pos_value)) 448 ], 449 ) 450 451 # right slice: arr[pos+1:] 452 slice_end = exp.Bracket( 453 this=this, expressions=[exp.Slice(this=exp.Literal.number(pos_value + 1))] 454 ) 455 456 concat_exprs = [slice_start, element_array, slice_end] 457 else: 458 # Negative position: arr[1:LEN(arr)+pos], [elem], arr[LEN(arr)+pos+1:] 459 # pos=-1 means insert before last element 460 arr_len = exp.Length(this=this) 461 462 # Calculate slice position: LEN(arr) + pos (e.g., LEN(arr) + (-1) = LEN(arr) - 1) 463 slice_end_pos = arr_len + exp.Literal.number(pos_value) 464 slice_start_pos = slice_end_pos + exp.Literal.number(1) 465 466 # left slice: arr[1:LEN(arr)+pos] 467 slice_start = exp.Bracket( 468 this=this, 469 expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end_pos)], 470 ) 471 472 # right slice: arr[LEN(arr)+pos+1:] 473 slice_end = exp.Bracket(this=this, expressions=[exp.Slice(this=slice_start_pos)]) 474 475 concat_exprs = [slice_start, element_array, slice_end] 476 477 # All dialects that support ARRAY_INSERT propagate NULLs (Snowflake/Spark/Databricks) 478 # Wrap in CASE WHEN array IS NULL THEN NULL ELSE func_expr END 479 return self.sql( 480 exp.If( 481 this=exp.Is(this=this, expression=exp.Null()), 482 true=exp.Null(), 483 false=self.func("LIST_CONCAT", *concat_exprs), 484 ) 485 ) 486 487 488def _array_remove_at_sql(self: DuckDBGenerator, expression: exp.ArrayRemoveAt) -> str: 489 """ 490 Transpile ARRAY_REMOVE_AT to DuckDB using LIST_CONCAT and slicing. 491 492 Handles: 493 - Positive positions (0-based indexing) 494 - Negative positions (from end of array) 495 - NULL propagation (Snowflake returns NULL for NULL array, DuckDB doesn't auto-propagate) 496 - Only supports literal integer positions (non-literals remain untranspiled) 497 498 Transpilation patterns: 499 - pos=0 (first): arr[2:] 500 - pos>0 (middle): LIST_CONCAT(arr[1:p], arr[p+2:]) 501 - pos=-1 (last): arr[1:LEN(arr)-1] 502 - pos<-1: LIST_CONCAT(arr[1:LEN(arr)+p], arr[LEN(arr)+p+2:]) 503 504 All wrapped in: CASE WHEN arr IS NULL THEN NULL ELSE ... END 505 506 Args: 507 expression: The ArrayRemoveAt expression to transpile. 508 509 Returns: 510 SQL string implementing ARRAY_REMOVE_AT behavior. 511 """ 512 this = expression.this 513 position = expression.args.get("position") 514 515 if not position or not position.is_int: 516 self.unsupported("ARRAY_REMOVE_AT can only be transpiled with a literal position") 517 return self.func("ARRAY_REMOVE_AT", this, position) 518 519 pos_value = position.to_py() 520 521 # Build the appropriate expression based on position 522 if pos_value == 0: 523 # Remove first element: arr[2:] 524 result_expr: exp.Expr | str = exp.Bracket( 525 this=this, 526 expressions=[exp.Slice(this=exp.Literal.number(2))], 527 ) 528 elif pos_value > 0: 529 # Remove at positive position: LIST_CONCAT(arr[1:pos], arr[pos+2:]) 530 # DuckDB uses 1-based slicing 531 left_slice = exp.Bracket( 532 this=this, 533 expressions=[ 534 exp.Slice(this=exp.Literal.number(1), expression=exp.Literal.number(pos_value)) 535 ], 536 ) 537 right_slice = exp.Bracket( 538 this=this, 539 expressions=[exp.Slice(this=exp.Literal.number(pos_value + 2))], 540 ) 541 result_expr = self.func("LIST_CONCAT", left_slice, right_slice) 542 elif pos_value == -1: 543 # Remove last element: arr[1:LEN(arr)-1] 544 # Optimization: simpler than general negative case 545 arr_len = exp.Length(this=this) 546 slice_end = arr_len + exp.Literal.number(-1) 547 result_expr = exp.Bracket( 548 this=this, 549 expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end)], 550 ) 551 else: 552 # Remove at negative position: LIST_CONCAT(arr[1:LEN(arr)+pos], arr[LEN(arr)+pos+2:]) 553 arr_len = exp.Length(this=this) 554 slice_end_pos = arr_len + exp.Literal.number(pos_value) 555 slice_start_pos = slice_end_pos + exp.Literal.number(2) 556 557 left_slice = exp.Bracket( 558 this=this, 559 expressions=[exp.Slice(this=exp.Literal.number(1), expression=slice_end_pos)], 560 ) 561 right_slice = exp.Bracket( 562 this=this, 563 expressions=[exp.Slice(this=slice_start_pos)], 564 ) 565 result_expr = self.func("LIST_CONCAT", left_slice, right_slice) 566 567 # Snowflake ARRAY_FUNCS_PROPAGATES_NULLS=True, so wrap in NULL check 568 # CASE WHEN array IS NULL THEN NULL ELSE result_expr END 569 return self.sql( 570 exp.If( 571 this=exp.Is(this=this, expression=exp.Null()), 572 true=exp.Null(), 573 false=result_expr, 574 ) 575 ) 576 577 578@unsupported_args(("expression", "DuckDB's LIST_SORT does not support a comparator.")) 579def _array_sort_sql(self: DuckDBGenerator, expression: exp.ArraySort) -> str: 580 order = array_sort_order(expression) 581 if order is None: 582 self.unsupported("LIST_SORT only takes literal orders") 583 return self.func("LIST_SORT", expression.this) 584 585 asc, nulls_first = order 586 if not nulls_first: 587 return self.func("LIST_SORT" if asc else "ARRAY_REVERSE_SORT", expression.this) 588 return self.func( 589 "LIST_SORT", 590 expression.this, 591 exp.Literal.string("ASC" if asc else "DESC"), 592 exp.Literal.string("NULLS FIRST"), 593 ) 594 595 596def _array_contains_sql(self: DuckDBGenerator, expression: exp.ArrayContains) -> str: 597 this = expression.this 598 expr = expression.expression 599 600 func = self.func("ARRAY_CONTAINS", this, expr) 601 602 if expression.args.get("check_null"): 603 check_null_in_array = exp.Nullif( 604 this=exp.NEQ(this=exp.ArraySize(this=this), expression=exp.func("LIST_COUNT", this)), 605 expression=exp.false(), 606 ) 607 return self.sql(exp.If(this=expr.is_(exp.Null()), true=check_null_in_array, false=func)) 608 609 return func 610 611 612def _array_overlaps_sql(self: DuckDBGenerator, expression: exp.ArrayOverlaps) -> str: 613 """ 614 Translates Snowflake's NULL-safe ARRAYS_OVERLAP to DuckDB. 615 616 DuckDB's native && operator is not NULL-safe: [1,NULL,3] && [NULL,4,5] returns FALSE. 617 Snowflake returns TRUE when both arrays contain NULL (NULLs are treated as known values). 618 619 Generated SQL: (arr1 && arr2) OR (ARRAY_LENGTH(arr1) <> LIST_COUNT(arr1) AND ARRAY_LENGTH(arr2) <> LIST_COUNT(arr2)) 620 621 ARRAY_LENGTH counts all elements (including NULLs); LIST_COUNT counts only non-NULLs. 622 When they differ, the array contains at least one NULL, matching Snowflake's NULL-safe semantics. 623 """ 624 if not expression.args.get("null_safe"): 625 return self.binary(expression, "&&") 626 627 arr1 = expression.this 628 arr2 = expression.expression 629 630 check_nulls = exp.and_( 631 exp.NEQ( 632 this=exp.ArraySize(this=arr1.copy()), 633 expression=exp.func("LIST_COUNT", arr1.copy()), 634 ), 635 exp.NEQ( 636 this=exp.ArraySize(this=arr2.copy()), 637 expression=exp.func("LIST_COUNT", arr2.copy()), 638 ), 639 copy=False, 640 ) 641 642 overlap = exp.ArrayOverlaps(this=arr1.copy(), expression=arr2.copy()) 643 644 return self.sql( 645 exp.or_( 646 exp.paren(overlap, copy=False), 647 exp.paren(check_nulls, copy=False), 648 copy=False, 649 wrap=False, 650 ) 651 ) 652 653 654def _struct_sql(self: DuckDBGenerator, expression: exp.Struct) -> str: 655 ancestor_cast = expression.find_ancestor(exp.Cast, exp.Select) 656 ancestor_cast = None if isinstance(ancestor_cast, exp.Select) else ancestor_cast 657 658 # Empty struct cast works with MAP() since DuckDB can't parse {} 659 if not expression.expressions: 660 if isinstance(ancestor_cast, exp.Cast) and ancestor_cast.to.is_type(exp.DType.MAP): 661 return "MAP()" 662 663 args: list[str] = [] 664 665 # BigQuery allows inline construction such as "STRUCT<a STRING, b INTEGER>('str', 1)" which is 666 # canonicalized to "ROW('str', 1) AS STRUCT(a TEXT, b INT)" in DuckDB 667 # The transformation to ROW will take place if: 668 # 1. The STRUCT itself does not have proper fields (key := value) as a "proper" STRUCT would 669 # 2. A cast to STRUCT / ARRAY of STRUCTs is found 670 is_bq_inline_struct = ( 671 (expression.find(exp.PropertyEQ) is None) 672 and ancestor_cast 673 and any( 674 casted_type.is_type(exp.DType.STRUCT) 675 for casted_type in ancestor_cast.find_all(exp.DataType) 676 ) 677 ) 678 679 for i, expr in enumerate(expression.expressions): 680 is_property_eq = isinstance(expr, exp.PropertyEQ) 681 this = expr.this 682 value = expr.expression if is_property_eq else expr 683 684 if is_bq_inline_struct: 685 args.append(self.sql(value)) 686 else: 687 if isinstance(this, exp.Identifier): 688 key = self.sql(exp.Literal.string(expr.name)) 689 elif is_property_eq: 690 key = self.sql(this) 691 else: 692 key = self.sql(exp.Literal.string(f"_{i}")) 693 694 args.append(f"{key}: {self.sql(value)}") 695 696 csv_args = ", ".join(args) 697 698 return f"ROW({csv_args})" if is_bq_inline_struct else f"{{{csv_args}}}" 699 700 701@unsupported_args("unique_keys", "return_type", "encoding", "strict") 702def _json_constructor_sql(self: DuckDBGenerator, expression: exp.JSONArray | exp.JSONObject) -> str: 703 if expression.args.get("null_handling") == "ABSENT ON NULL": 704 self.unsupported("ABSENT ON NULL is not supported in DuckDB") 705 706 name = "JSON_ARRAY" if isinstance(expression, exp.JSONArray) else "JSON_OBJECT" 707 return self.func(name, *expression.expressions) 708 709 710def _json_format_sql(self: DuckDBGenerator, expression: exp.JSONFormat) -> str: 711 sql = self.func("TO_JSON", expression.this, expression.args.get("options")) 712 return f"CAST({sql} AS TEXT)" 713 714 715def _build_seq_expression(base: exp.Expr, byte_width: int, signed: bool) -> exp.Expr: 716 """Build a SEQ expression with the given base, byte width, and signedness.""" 717 bits = byte_width * 8 718 max_val = exp.Literal.number(2**bits) 719 720 if signed: 721 half = exp.Literal.number(2 ** (bits - 1)) 722 return exp.replace_placeholders(_SEQ_SIGNED.copy(), base=base, max_val=max_val, half=half) 723 return exp.replace_placeholders(_SEQ_UNSIGNED.copy(), base=base, max_val=max_val) 724 725 726def _seq_to_range_in_generator(expression: exp.Expr) -> exp.Expr: 727 """ 728 Transform SEQ functions to `range` column references when inside a GENERATOR context. 729 730 When GENERATOR(ROWCOUNT => N) becomes RANGE(N) in DuckDB, it produces a column 731 named `range` with values 0, 1, ..., N-1. SEQ functions produce the same sequence, 732 so we replace them with `range % max_val` to avoid nested window function issues. 733 """ 734 if not isinstance(expression, exp.Select): 735 return expression 736 737 from_ = expression.args.get("from_") 738 if not ( 739 from_ 740 and isinstance(from_.this, exp.TableFromRows) 741 and isinstance(from_.this.this, exp.Generator) 742 ): 743 return expression 744 745 def replace_seq(node: exp.Expr) -> exp.Expr: 746 if isinstance(node, (exp.Seq1, exp.Seq2, exp.Seq4, exp.Seq8)): 747 byte_width = _SEQ_BYTE_WIDTH[type(node)] 748 return _build_seq_expression(exp.column("range"), byte_width, signed=node.name == "1") 749 return node 750 751 return expression.transform(replace_seq, copy=False) 752 753 754def connect_by_to_recursive_cte(expression: exp.Expr) -> exp.Expr: 755 # Rewrites START WITH ... CONNECT BY PRIOR into WITH RECURSIVE 756 # Falls through unchanged if there are no PRIORs. 757 if not isinstance(expression, exp.Select) or not expression.args.get("connect"): 758 return expression 759 760 connect = expression.args["connect"] 761 connect_pred = connect.args["connect"] 762 763 priors = list(connect_pred.find_all(exp.Prior)) 764 if not priors: 765 return expression 766 767 from_ = expression.args.get("from_") 768 if not from_ or expression.args.get("joins"): 769 return expression 770 771 source_table = from_.this 772 base_select_exprs = expression.expressions 773 base_where = expression.args.get("where") 774 base_with = expression.args.get("with_") 775 776 # LEVEL is a Snowflake pseudo-column: it's always computed as a depth counter in the CTE. 777 has_level = any( 778 isinstance(col, exp.Column) and col.name.upper() == "LEVEL" 779 for e in base_select_exprs 780 for col in e.find_all(exp.Column) 781 ) 782 has_star = expression.is_star 783 784 # CONNECT_BY_ROOT col yields the value of `col` from the START WITH row that begins each 785 # branch. Each one is threaded through the CTE as an extra column: the anchor binds it to the 786 # row's own value, the recursive arm forwards the parent's value unchanged. 787 root_col_names: list[str] = [] 788 anchor_root_cols: list[exp.Expr] = [] 789 inner_root_cols: list[exp.Expr] = [] 790 roots = [root for e in base_select_exprs for root in e.find_all(exp.ConnectByRoot)] 791 792 for i, root in enumerate(roots): 793 name = f"_connect_by_root_{i}" 794 root_col_names.append(name) 795 anchor_root_cols.append(exp.alias_(root.this, name)) 796 inner_root_cols.append(exp.alias_(exp.column(name, "_parent_row"), name)) 797 root.replace(exp.column(name)) 798 799 # Build the join condition from the full CONNECT BY predicate: 800 # PRIOR(col) → _parent_row.col, unqualified cols → _child_row.col. 801 def _qualify_connect_pred(node: exp.Expression) -> exp.Expression: 802 for col in find_all_in_scope(node, exp.Column): 803 col.set( 804 "table", 805 exp.to_identifier( 806 "_parent_row" if isinstance(col.parent, exp.Prior) else "_child_row" 807 ), 808 ) 809 for prior in find_all_in_scope(node, exp.Prior): 810 prior.replace(prior.this) 811 return node 812 813 # Avoid colliding with any CTE names already on the query. 814 cte_name = find_new_name( 815 {cte.alias for cte in (base_with.expressions if base_with else [])}, "_rootcte" 816 ) 817 818 # Anchor: project all source columns + seed LEVEL at 1 + bind each root column to its own value. 819 anchor = exp.select( 820 exp.Star(), exp.alias_(exp.Literal.number(1), "level"), *anchor_root_cols 821 ).from_(source_table) 822 if connect.args.get("start"): 823 anchor = anchor.where(connect.args["start"]) 824 825 # Recursive arm: carry all child columns + increment level + forward each root value. 826 # SELECT * in both arms means WHERE/PRIOR columns are always available without explicit tracking. 827 inner_query = ( 828 exp.select( 829 exp.Column(this=exp.Star(), table=exp.to_identifier("_child_row")), 830 exp.alias_(exp.column("level", "_parent_row") + 1, "level"), 831 *inner_root_cols, 832 ) 833 .from_(source_table.as_("_child_row")) 834 .join(exp.to_table(cte_name).as_("_parent_row"), on=_qualify_connect_pred(connect_pred)) 835 ) 836 837 # Outer SELECT re-projects from the CTE. Synthetic level/root columns are excluded from any 838 # star expansion (level only when not referenced) but kept where explicitly projected. 839 if has_star: 840 except_cols = [] if has_level else [exp.column("level")] 841 except_cols.extend(exp.column(name) for name in root_col_names) 842 star = exp.Star(except_=except_cols) if except_cols else exp.Star() 843 outer_select_exprs: list[exp.Expr] = [ 844 star, 845 *(e for e in base_select_exprs if not e.is_star), 846 ] 847 else: 848 outer_select_exprs = base_select_exprs 849 outer_query = exp.select(*outer_select_exprs).from_(cte_name) 850 if base_where: 851 outer_query = outer_query.where(base_where.this) 852 853 # Attach the CTE, marking the WITH clause recursive. 854 if base_with: 855 outer_query.set("with_", base_with) 856 outer_query = outer_query.with_( 857 cte_name, as_=anchor.union(inner_query, distinct=False), recursive=True, copy=False 858 ) 859 860 for arg, val in expression.args.items(): 861 if val and arg not in _CONNECT_BY_ARGS_TO_SKIP: 862 outer_query.set(arg, val) 863 864 # Strip stale source table qualifiers in one pass; CTEs are child scopes so 865 # find_all_in_scope stays within the outer query only. 866 for col in find_all_in_scope(outer_query, exp.Column, include_udtfs=True): 867 col.set("table", None) 868 869 return outer_query 870 871 872def _seq_sql(self: DuckDBGenerator, expression: exp.Func, byte_width: int) -> str: 873 """ 874 Transpile Snowflake SEQ1/SEQ2/SEQ4/SEQ8 to DuckDB. 875 876 Generates monotonically increasing integers starting from 0. 877 The signed parameter (0 or 1) affects wrap-around behavior: 878 - Unsigned (0): wraps at 2^(bits) - 1 879 - Signed (1): wraps at 2^(bits-1) - 1, then goes negative 880 """ 881 # Warn if SEQ is in a restricted context (Select stops search at current scope) 882 ancestor = expression.find_ancestor(*_SEQ_RESTRICTED) 883 if ancestor and ( 884 (not isinstance(ancestor, (exp.Order, exp.Select))) 885 or (isinstance(ancestor, exp.Order) and isinstance(ancestor.parent, exp.Window)) 886 ): 887 self.unsupported("SEQ in restricted context is not supported - use CTE or subquery") 888 889 result = _build_seq_expression(_SEQ_BASE.copy(), byte_width, signed=expression.name == "1") 890 return self.sql(result) 891 892 893def _unix_to_time_sql(self: DuckDBGenerator, expression: exp.UnixToTime) -> str: 894 scale = expression.args.get("scale") 895 timestamp = expression.this 896 target_type = expression.args.get("target_type") 897 898 # Check if we need NTZ (naive timestamp in UTC) 899 is_ntz = target_type and target_type.this in ( 900 exp.DType.TIMESTAMP, 901 exp.DType.TIMESTAMPNTZ, 902 ) 903 904 if scale == exp.UnixToTime.MILLIS: 905 # EPOCH_MS already returns TIMESTAMP (naive, UTC) 906 return self.func("EPOCH_MS", timestamp) 907 if scale == exp.UnixToTime.MICROS: 908 # MAKE_TIMESTAMP already returns TIMESTAMP (naive, UTC) 909 return self.func("MAKE_TIMESTAMP", timestamp) 910 911 # Other scales: divide and use TO_TIMESTAMP 912 if scale not in (None, exp.UnixToTime.SECONDS): 913 timestamp = exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)) 914 915 to_timestamp: exp.Expr = exp.Anonymous(this="TO_TIMESTAMP", expressions=[timestamp]) 916 917 if is_ntz: 918 to_timestamp = exp.AtTimeZone(this=to_timestamp, zone=exp.Literal.string("UTC")) 919 920 return self.sql(to_timestamp) 921 922 923WRAPPED_JSON_EXTRACT_EXPRESSIONS = (exp.Binary, exp.Bracket, exp.In, exp.Not) 924 925 926def _arrow_json_extract_sql(self: DuckDBGenerator, expression: JSON_EXTRACT_TYPE) -> str: 927 paths = expression.expressions 928 if isinstance(expression, exp.JSONExtract) and paths: 929 # JSON_EXTRACT with several paths (SQLite, MySQL) returns a JSON array of the results, 930 # which DuckDB builds from a list of paths 931 return self.func( 932 "TO_JSON", 933 self.func( 934 "JSON_EXTRACT", 935 expression.this, 936 exp.Array(expressions=[expression.expression, *paths]), 937 ), 938 ) 939 940 arrow_sql = arrow_json_extract_sql(self, expression) 941 if not expression.same_parent and isinstance( 942 expression.parent, WRAPPED_JSON_EXTRACT_EXPRESSIONS 943 ): 944 arrow_sql = self.wrap(arrow_sql) 945 return arrow_sql 946 947 948def _implicit_datetime_cast( 949 arg: exp.Expr | None, type: exp.DType = exp.DType.DATE 950) -> exp.Expr | None: 951 if isinstance(arg, exp.Literal) and arg.is_string: 952 ts = arg.name 953 if type == exp.DType.DATE and ":" in ts: 954 type = exp.DType.TIMESTAMPTZ if TIMEZONE_PATTERN.search(ts) else exp.DType.TIMESTAMP 955 956 arg = exp.cast(arg, type) 957 958 return arg 959 960 961def _week_trunc_start_dow(unit: exp.Expr | None) -> int | None: 962 # DuckDB's weeks are ISO 8601, so ISOWEEK maps to its plain WEEK unit 963 if isinstance(unit, exp.Literal) and unit.name.upper() == "ISOWEEK": 964 return 1 965 return week_unit_to_dow(unit) 966 967 968def _build_week_trunc_expression( 969 date_expr: exp.Expr, 970 start_dow: int, 971 preserve_start_day: bool = False, 972 cast_to_date: bool = True, 973) -> exp.Expr: 974 """ 975 Build DATE_TRUNC expression for week boundaries with custom start day. 976 977 DuckDB's DATE_TRUNC('WEEK', ...) always returns Monday. To align to a different 978 start day, we shift the date before truncating. 979 980 Args: 981 date_expr: The date expression to truncate. 982 start_dow: ISO 8601 day-of-week number (Monday=1, ..., Sunday=7). 983 preserve_start_day: If True, reverse the shift after truncating so the result lands on the 984 correct week start day. Needed for DATE_TRUNC (absolute result matters) but 985 not for DATE_DIFF (only relative alignment matters). 986 cast_to_date: If True, cast the shifted result back to DATE; set to False for 987 timestamp-valued inputs, where the result must remain a timestamp. 988 989 Shift formula: Sunday (7) gets +1, others get (1 - start_dow). 990 """ 991 shift_days = 1 if start_dow == 7 else 1 - start_dow 992 truncated = exp.func("DATE_TRUNC", unit=exp.var("WEEK"), this=date_expr) 993 994 if shift_days == 0: 995 return truncated 996 997 shift = exp.Interval(this=exp.Literal.string(str(shift_days)), unit=exp.var("DAY")) 998 shifted_date = exp.DateAdd(this=date_expr, expression=shift) 999 truncated.set("this", shifted_date) 1000 1001 if preserve_start_day: 1002 interval = exp.Interval(this=exp.Literal.string(str(-shift_days)), unit=exp.var("DAY")) 1003 shifted_back: exp.Expr = exp.DateAdd(this=truncated, expression=interval) 1004 if cast_to_date: 1005 return exp.cast(shifted_back, to=exp.DType.DATE, copy=False) 1006 return shifted_back 1007 1008 return truncated 1009 1010 1011def _date_diff_sql(self: DuckDBGenerator, expression: exp.DateDiff | exp.DatetimeDiff) -> str: 1012 unit = expression.unit 1013 1014 if _is_nanosecond_unit(unit): 1015 return _handle_nanosecond_diff(self, expression.this, expression.expression) 1016 1017 this = _implicit_datetime_cast(expression.this) 1018 expr = _implicit_datetime_cast(expression.expression) 1019 1020 # DuckDB's WEEK diff does not respect Monday crossing (week boundaries), it checks (end_day - start_day) / 7: 1021 # SELECT DATE_DIFF('WEEK', CAST('2024-12-13' AS DATE), CAST('2024-12-17' AS DATE)) --> 0 (Monday crossed) 1022 # SELECT DATE_DIFF('WEEK', CAST('2024-12-13' AS DATE), CAST('2024-12-20' AS DATE)) --> 1 (7 days difference) 1023 # Whereas for other units such as MONTH it does respect month boundaries: 1024 # SELECT DATE_DIFF('MONTH', CAST('2024-11-30' AS DATE), CAST('2024-12-01' AS DATE)) --> 1 (Month crossed) 1025 date_part_boundary = expression.args.get("date_part_boundary") 1026 1027 # Extract week start day; returns None if day is dynamic (column/placeholder) 1028 week_start = week_unit_to_dow(unit) 1029 if date_part_boundary and week_start and this and expr: 1030 expression.set("unit", exp.Literal.string("WEEK")) 1031 1032 # Truncate both dates to week boundaries to respect input dialect semantics 1033 this = _build_week_trunc_expression(this, week_start) 1034 expr = _build_week_trunc_expression(expr, week_start) 1035 1036 return self.func("DATE_DIFF", unit_to_str(expression), expr, this) 1037 1038 1039def _generate_datetime_array_sql( 1040 self: DuckDBGenerator, expression: exp.GenerateDateArray | exp.GenerateTimestampArray 1041) -> str: 1042 is_generate_date_array = isinstance(expression, exp.GenerateDateArray) 1043 1044 type = exp.DType.DATE if is_generate_date_array else exp.DType.TIMESTAMP 1045 start = _implicit_datetime_cast(expression.args.get("start"), type=type) 1046 end = _implicit_datetime_cast(expression.args.get("end"), type=type) 1047 1048 # BQ's GENERATE_DATE_ARRAY & GENERATE_TIMESTAMP_ARRAY are transformed to DuckDB'S GENERATE_SERIES 1049 gen_series: exp.GenerateSeries | exp.Cast = exp.GenerateSeries( 1050 start=start, end=end, step=expression.args.get("step") 1051 ) 1052 1053 if is_generate_date_array: 1054 # The GENERATE_SERIES result type is TIMESTAMP array, so to match BQ's semantics for 1055 # GENERATE_DATE_ARRAY we must cast it back to DATE array 1056 gen_series = exp.cast(gen_series, exp.DataType.from_str("ARRAY<DATE>")) 1057 1058 return self.sql(gen_series) 1059 1060 1061def _json_extract_value_array_sql( 1062 self: DuckDBGenerator, expression: exp.JSONValueArray | exp.JSONExtractArray 1063) -> str: 1064 json_extract = exp.JSONExtract(this=expression.this, expression=expression.expression) 1065 data_type = "ARRAY<STRING>" if isinstance(expression, exp.JSONValueArray) else "ARRAY<JSON>" 1066 return self.sql(exp.cast(json_extract, to=exp.DataType.from_str(data_type))) 1067 1068 1069def _cast_to_varchar(arg: exp.Expr | None) -> exp.Expr | None: 1070 if arg and arg.type and not arg.is_type(*exp.DataType.TEXT_TYPES, exp.DType.UNKNOWN): 1071 return exp.cast(arg, exp.DType.VARCHAR) 1072 return arg 1073 1074 1075def _cast_to_boolean(arg: exp.Expr | None) -> exp.Expr | None: 1076 if arg and not arg.is_type(exp.DType.BOOLEAN): 1077 return exp.cast(arg, exp.DType.BOOLEAN) 1078 return arg 1079 1080 1081def _is_binary(arg: exp.Expr) -> bool: 1082 return arg.is_type( 1083 exp.DType.BINARY, 1084 exp.DType.VARBINARY, 1085 exp.DType.BLOB, 1086 ) 1087 1088 1089def _gen_with_cast_to_blob(self: DuckDBGenerator, expression: exp.Expr, result_sql: str) -> str: 1090 if _is_binary(expression): 1091 blob = exp.DataType.from_str("BLOB", dialect="duckdb") 1092 result_sql = self.sql(exp.Cast(this=result_sql, to=blob)) 1093 return result_sql 1094 1095 1096def _cast_to_bit(arg: exp.Expr) -> exp.Expr: 1097 if not _is_binary(arg): 1098 return arg 1099 1100 if isinstance(arg, exp.HexString): 1101 arg = exp.Unhex(this=exp.Literal.string(arg.this)) 1102 1103 return exp.cast(arg, exp.DType.BIT) 1104 1105 1106def _prepare_binary_bitwise_args(expression: exp.Binary) -> None: 1107 if _is_binary(expression.this): 1108 expression.set("this", _cast_to_bit(expression.this)) 1109 if _is_binary(expression.expression): 1110 expression.set("expression", _cast_to_bit(expression.expression)) 1111 1112 1113def _day_navigation_sql(self: DuckDBGenerator, expression: exp.NextDay | exp.PreviousDay) -> str: 1114 """ 1115 Transpile Snowflake's NEXT_DAY / PREVIOUS_DAY to DuckDB using date arithmetic. 1116 1117 Returns the DATE of the next/previous occurrence of the specified weekday. 1118 1119 Formulas: 1120 - NEXT_DAY: (target_dow - current_dow + 6) % 7 + 1 1121 - PREVIOUS_DAY: (current_dow - target_dow + 6) % 7 + 1 1122 1123 Supports both literal and non-literal day names: 1124 - Literal: Direct lookup (e.g., 'Monday' -> 1) 1125 - Non-literal: CASE statement for runtime evaluation 1126 1127 Examples: 1128 NEXT_DAY('2024-01-01' (Monday), 'Monday') 1129 -> (1 - 1 + 6) % 7 + 1 = 6 % 7 + 1 = 7 days -> 2024-01-08 1130 1131 PREVIOUS_DAY('2024-01-15' (Monday), 'Friday') 1132 -> (1 - 5 + 6) % 7 + 1 = 2 % 7 + 1 = 3 days -> 2024-01-12 1133 """ 1134 date_expr = expression.this 1135 day_name_expr = expression.expression 1136 1137 # Build ISODOW call for current day of week 1138 isodow_call = exp.func("ISODOW", date_expr) 1139 1140 # Determine target day of week 1141 if isinstance(day_name_expr, exp.Literal): 1142 # Literal day name: lookup target_dow directly 1143 day_name_str = day_name_expr.name.upper() 1144 matching_day = next( 1145 (day for day in WEEK_START_DAY_TO_DOW if day.startswith(day_name_str)), None 1146 ) 1147 if matching_day: 1148 target_dow: exp.Expr = exp.Literal.number(WEEK_START_DAY_TO_DOW[matching_day]) 1149 else: 1150 # Unrecognized day name, use fallback 1151 return self.function_fallback_sql(expression) 1152 else: 1153 # Non-literal day name: build CASE statement for runtime mapping 1154 upper_day_name = exp.Upper(this=day_name_expr) 1155 target_dow = exp.Case( 1156 ifs=[ 1157 exp.If( 1158 this=exp.func( 1159 "STARTS_WITH", upper_day_name.copy(), exp.Literal.string(day[:2]) 1160 ), 1161 true=exp.Literal.number(dow_num), 1162 ) 1163 for day, dow_num in WEEK_START_DAY_TO_DOW.items() 1164 ] 1165 ) 1166 1167 # Calculate days offset and apply interval based on direction 1168 if isinstance(expression, exp.NextDay): 1169 # NEXT_DAY: (target_dow - current_dow + 6) % 7 + 1 1170 days_offset = exp.paren(target_dow - isodow_call + 6, copy=False) % 7 + 1 1171 date_with_offset = date_expr + exp.Interval(this=days_offset, unit=exp.var("DAY")) 1172 else: # exp.PreviousDay 1173 # PREVIOUS_DAY: (current_dow - target_dow + 6) % 7 + 1 1174 days_offset = exp.paren(isodow_call - target_dow + 6, copy=False) % 7 + 1 1175 date_with_offset = date_expr - exp.Interval(this=days_offset, unit=exp.var("DAY")) 1176 1177 # Build final: CAST(date_with_offset AS DATE) 1178 return self.sql(exp.cast(date_with_offset, exp.DType.DATE)) 1179 1180 1181def _arg_max_or_min_sql(self: DuckDBGenerator, expression: exp.ArgMax | exp.ArgMin) -> str: 1182 if not expression.args.get("include_nulls"): 1183 return self.function_fallback_sql(expression) 1184 1185 return self._arg_max_or_min_with_count_sql(expression) or self.func( 1186 f"{expression.sql_name()}_NULL", expression.this, expression.expression 1187 ) 1188 1189 1190def _anyvalue_sql(self: DuckDBGenerator, expression: exp.AnyValue) -> str: 1191 # Transform ANY_VALUE(expr HAVING MAX/MIN having_expr) to ARG_MAX_NULL/ARG_MIN_NULL 1192 having = expression.this 1193 if isinstance(having, exp.HavingMax): 1194 func_name = "ARG_MAX_NULL" if having.args.get("max") else "ARG_MIN_NULL" 1195 return self.func(func_name, having.this, having.expression) 1196 return self.function_fallback_sql(expression) 1197 1198 1199def _bitwise_agg_sql( 1200 self: DuckDBGenerator, 1201 expression: exp.BitwiseOrAgg | exp.BitwiseAndAgg | exp.BitwiseXorAgg, 1202) -> str: 1203 """ 1204 DuckDB's bitwise aggregate functions only accept integer types. For other types: 1205 - DECIMAL/STRING: Use CAST(arg AS INT) to convert directly, will round to nearest int 1206 - FLOAT/DOUBLE: Use ROUND(arg)::INT to round to nearest integer, required due to float precision loss 1207 """ 1208 if isinstance(expression, exp.BitwiseOrAgg): 1209 func_name = "BIT_OR" 1210 elif isinstance(expression, exp.BitwiseAndAgg): 1211 func_name = "BIT_AND" 1212 else: # exp.BitwiseXorAgg 1213 func_name = "BIT_XOR" 1214 1215 arg = expression.this 1216 1217 if not arg.type: 1218 from sqlglot.optimizer.annotate_types import annotate_types 1219 1220 arg = annotate_types(arg, dialect=self.dialect) 1221 1222 if arg.is_type(*exp.DataType.REAL_TYPES, *exp.DataType.TEXT_TYPES): 1223 if arg.is_type(*exp.DataType.FLOAT_TYPES): 1224 # float types need to be rounded first due to precision loss 1225 arg = exp.func("ROUND", arg) 1226 1227 arg = exp.cast(arg, exp.DType.INT) 1228 1229 return self.func(func_name, arg) 1230 1231 1232def _literal_sql_with_ws_chr(self: DuckDBGenerator, literal: str) -> str: 1233 # DuckDB does not support \uXXXX escapes, so we must use CHR() instead of replacing them directly 1234 if not any(ch in WS_CONTROL_CHARS_TO_DUCK for ch in literal): 1235 return self.sql(exp.Literal.string(literal)) 1236 1237 sql_segments: list[str] = [] 1238 for is_ws_control, group in groupby(literal, key=lambda ch: ch in WS_CONTROL_CHARS_TO_DUCK): 1239 if is_ws_control: 1240 for ch in group: 1241 duckdb_char_code = WS_CONTROL_CHARS_TO_DUCK[ch] 1242 sql_segments.append(self.func("CHR", exp.Literal.number(str(duckdb_char_code)))) 1243 else: 1244 sql_segments.append(self.sql(exp.Literal.string("".join(group)))) 1245 1246 sql = " || ".join(sql_segments) 1247 return sql if len(sql_segments) == 1 else f"({sql})" 1248 1249 1250def _escape_regex_metachars( 1251 self: DuckDBGenerator, delimiters: exp.Expr | None, delimiters_sql: str 1252) -> str: 1253 r""" 1254 Escapes regex metacharacters \ - ^ [ ] for use in character classes regex expressions. 1255 1256 Literal strings are escaped at transpile time, expressions handled with REPLACE() calls. 1257 """ 1258 if not delimiters: 1259 return delimiters_sql 1260 1261 if delimiters.is_string: 1262 literal_value = delimiters.this 1263 escaped_literal = "".join(REGEX_ESCAPE_REPLACEMENTS.get(ch, ch) for ch in literal_value) 1264 return _literal_sql_with_ws_chr(self, escaped_literal) 1265 1266 escaped_sql = delimiters_sql 1267 for raw, escaped in REGEX_ESCAPE_REPLACEMENTS.items(): 1268 escaped_sql = self.func( 1269 "REPLACE", 1270 escaped_sql, 1271 self.sql(exp.Literal.string(raw)), 1272 self.sql(exp.Literal.string(escaped)), 1273 ) 1274 1275 return escaped_sql 1276 1277 1278def _build_capitalization_sql( 1279 self: DuckDBGenerator, 1280 value_to_split: str, 1281 delimiters_sql: str, 1282) -> str: 1283 # empty string delimiter --> treat value as one word, no need to split 1284 if delimiters_sql == "''": 1285 return f"UPPER(LEFT({value_to_split}, 1)) || LOWER(SUBSTRING({value_to_split}, 2))" 1286 1287 delim_regex_sql = f"'[' || {delimiters_sql} || ']'" 1288 split_regex_sql = f"'([' || {delimiters_sql} || ']+|[^' || {delimiters_sql} || ']+)'" 1289 1290 # REGEXP_EXTRACT_ALL produces a list of string segments, alternating between delimiter and non-delimiter segments. 1291 # We do not know whether the first segment is a delimiter or not, so we check the first character of the string 1292 # with REGEXP_MATCHES. If the first char is a delimiter, we capitalize even list indexes, otherwise capitalize odd. 1293 return self.func( 1294 "ARRAY_TO_STRING", 1295 exp.case() 1296 .when( 1297 f"REGEXP_MATCHES(LEFT({value_to_split}, 1), {delim_regex_sql})", 1298 self.func( 1299 "LIST_TRANSFORM", 1300 self.func("REGEXP_EXTRACT_ALL", value_to_split, split_regex_sql), 1301 "LAMBDA seg, idx : CASE WHEN idx % 2 = 0 THEN UPPER(LEFT(seg, 1)) || LOWER(SUBSTRING(seg, 2)) ELSE seg END", 1302 ), 1303 dialect=self.dialect, 1304 ) 1305 .else_( 1306 self.func( 1307 "LIST_TRANSFORM", 1308 self.func("REGEXP_EXTRACT_ALL", value_to_split, split_regex_sql), 1309 "LAMBDA seg, idx : CASE WHEN idx % 2 = 1 THEN UPPER(LEFT(seg, 1)) || LOWER(SUBSTRING(seg, 2)) ELSE seg END", 1310 ), 1311 dialect=self.dialect, 1312 ), 1313 "''", 1314 ) 1315 1316 1317def _initcap_sql(self: DuckDBGenerator, expression: exp.Initcap) -> str: 1318 this_sql = self.sql(expression, "this") 1319 delimiters = expression.args.get("expression") 1320 if delimiters is None: 1321 # fallback for manually created exp.Initcap w/o delimiters arg 1322 delimiters = exp.Literal.string(self.dialect.INITCAP_DEFAULT_DELIMITER_CHARS) 1323 delimiters_sql = self.sql(delimiters) 1324 1325 escaped_delimiters_sql = _escape_regex_metachars(self, delimiters, delimiters_sql) 1326 1327 return _build_capitalization_sql(self, this_sql, escaped_delimiters_sql) 1328 1329 1330def _boolxor_agg_sql(self: DuckDBGenerator, expression: exp.BoolxorAgg) -> str: 1331 """ 1332 Snowflake's `BOOLXOR_AGG(col)` returns TRUE if exactly one input in `col` is TRUE, FALSE otherwise; 1333 Since DuckDB does not have a mapping function, we mimic the behavior by generating `COUNT_IF(col) = 1`. 1334 1335 DuckDB's COUNT_IF strictly requires boolean inputs, so cast if not already boolean. 1336 """ 1337 return self.sql( 1338 exp.EQ( 1339 this=exp.CountIf(this=_cast_to_boolean(expression.this)), 1340 expression=exp.Literal.number(1), 1341 ) 1342 ) 1343 1344 1345def _bitshift_sql( 1346 self: DuckDBGenerator, expression: exp.BitwiseLeftShift | exp.BitwiseRightShift 1347) -> str: 1348 """ 1349 Transform bitshift expressions for DuckDB by injecting BIT/INT128 casts. 1350 1351 DuckDB's bitwise shift operators don't work with BLOB/BINARY types, so we cast 1352 them to BIT for the operation, then cast the result back to the original type. 1353 1354 Note: Assumes type annotation has been applied with the source dialect. 1355 """ 1356 operator = "<<" if isinstance(expression, exp.BitwiseLeftShift) else ">>" 1357 result_is_blob = False 1358 this = expression.this 1359 1360 if _is_binary(this): 1361 result_is_blob = True 1362 expression.set("this", exp.cast(this, exp.DType.BIT)) 1363 elif expression.args.get("requires_int128"): 1364 this.replace(exp.cast(this, exp.DType.INT128)) 1365 1366 result_sql = self.binary(expression, operator) 1367 1368 # Wrap in parentheses if parent is a bitwise operator to "fix" DuckDB precedence issue 1369 # DuckDB parses: a << b | c << d as (a << b | c) << d 1370 if isinstance(expression.parent, exp.Binary): 1371 result_sql = self.sql(exp.Paren(this=result_sql)) 1372 1373 if result_is_blob: 1374 result_sql = self.sql( 1375 exp.Cast(this=result_sql, to=exp.DataType.from_str("BLOB", dialect="duckdb")) 1376 ) 1377 1378 return result_sql 1379 1380 1381def _scale_rounding_sql( 1382 self: DuckDBGenerator, 1383 expression: exp.Expr, 1384 rounding_func: Type[exp.Expr], 1385) -> str | None: 1386 """ 1387 Handle scale parameter transformation for rounding functions. 1388 1389 DuckDB doesn't support the scale parameter for certain functions (e.g., FLOOR, CEIL), 1390 so we transform: FUNC(x, n) to ROUND(FUNC(x * 10^n) / 10^n, n) 1391 1392 Args: 1393 self: The DuckDB generator instance 1394 expression: The expression to transform (must have 'this', 'decimals', and 'to' args) 1395 rounding_func: The rounding function class to use in the transformation 1396 1397 Returns: 1398 The transformed SQL string if decimals parameter exists, None otherwise 1399 """ 1400 decimals = expression.args.get("decimals") 1401 1402 if decimals is None or expression.args.get("to") is not None: 1403 return None 1404 1405 this = expression.this 1406 if isinstance(this, exp.Binary): 1407 this = exp.Paren(this=this) 1408 1409 n_int = decimals 1410 if not (decimals.is_int or decimals.is_type(*_ROUND_SCALE_INTEGER_TYPES)): 1411 n_int = exp.cast(decimals, exp.DType.INT) 1412 1413 pow_ = exp.Pow(this=exp.Literal.number("10"), expression=n_int) 1414 rounded = rounding_func(this=exp.Mul(this=this, expression=pow_)) 1415 result = exp.Div(this=rounded, expression=pow_.copy()) 1416 1417 return self.round_sql( 1418 exp.Round(this=result, decimals=decimals, casts_non_integer_decimals=True) 1419 ) 1420 1421 1422def _ceil_floor(self: DuckDBGenerator, expression: exp.Floor | exp.Ceil) -> str: 1423 scaled_sql = _scale_rounding_sql(self, expression, type(expression)) 1424 if scaled_sql is not None: 1425 return scaled_sql 1426 return self.ceil_floor(expression) 1427 1428 1429def _regr_val_sql( 1430 self: DuckDBGenerator, 1431 expression: exp.RegrValx | exp.RegrValy, 1432) -> str: 1433 """ 1434 Transpile Snowflake's REGR_VALX/REGR_VALY to DuckDB equivalent. 1435 1436 REGR_VALX(y, x) returns NULL if y is NULL; otherwise returns x. 1437 REGR_VALY(y, x) returns NULL if x is NULL; otherwise returns y. 1438 """ 1439 from sqlglot.optimizer.annotate_types import annotate_types 1440 1441 y = expression.this 1442 x = expression.expression 1443 1444 # Determine which argument to check for NULL and which to return based on expression type 1445 if isinstance(expression, exp.RegrValx): 1446 # REGR_VALX: check y for NULL, return x 1447 check_for_null = y 1448 return_value = x 1449 return_value_attr = "expression" 1450 else: 1451 # REGR_VALY: check x for NULL, return y 1452 check_for_null = x 1453 return_value = y 1454 return_value_attr = "this" 1455 1456 # Get the type from the return argument 1457 result_type = return_value.type 1458 1459 # If no type info, annotate the expression to infer types 1460 if not result_type or result_type.this == exp.DType.UNKNOWN: 1461 try: 1462 annotated = annotate_types(expression.copy(), dialect=self.dialect) 1463 result_type = getattr(annotated, return_value_attr).type 1464 except Exception: 1465 pass 1466 1467 # Default to DOUBLE for regression functions if type still unknown 1468 if not result_type or result_type.this == exp.DType.UNKNOWN: 1469 result_type = exp.DType.DOUBLE.into_expr() 1470 1471 # Cast NULL to the same type as return_value to avoid DuckDB type inference issues 1472 typed_null = exp.Cast(this=exp.Null(), to=result_type) 1473 1474 return self.sql( 1475 exp.If( 1476 this=exp.Is(this=check_for_null.copy(), expression=exp.Null()), 1477 true=typed_null, 1478 false=return_value.copy(), 1479 ) 1480 ) 1481 1482 1483def _unwrap_aggregate_modifiers(expression: exp.Expr) -> exp.Expr: 1484 while isinstance(expression, (exp.Window, exp.Filter)): 1485 expression = expression.this 1486 return expression 1487 1488 1489def _maybe_corr_null_to_false( 1490 expression: exp.Filter | exp.Window | exp.Corr, 1491) -> exp.Filter | exp.Window | exp.Corr | None: 1492 corr = _unwrap_aggregate_modifiers(expression) 1493 if not isinstance(corr, exp.Corr) or not corr.args.get("null_on_zero_variance"): 1494 return None 1495 1496 corr.set("null_on_zero_variance", False) 1497 return expression 1498 1499 1500def _date_from_parts_sql(self, expression: exp.DateFromParts) -> str: 1501 """ 1502 Snowflake's DATE_FROM_PARTS allows out-of-range values for the month and day input. 1503 E.g., larger values (month=13, day=100), zero-values (month=0, day=0), negative values (month=-13, day=-100). 1504 1505 DuckDB's MAKE_DATE does not support out-of-range values, but DuckDB's INTERVAL type does. 1506 1507 We convert to date arithmetic: 1508 DATE_FROM_PARTS(year, month, day) 1509 - MAKE_DATE(year, 1, 1) + INTERVAL (month-1) MONTH + INTERVAL (day-1) DAY 1510 """ 1511 year_expr = expression.args.get("year") 1512 month_expr = expression.args.get("month") 1513 day_expr = expression.args.get("day") 1514 1515 if expression.args.get("allow_overflow"): 1516 base_date: exp.Expr = exp.func( 1517 "MAKE_DATE", year_expr, exp.Literal.number(1), exp.Literal.number(1) 1518 ) 1519 1520 if month_expr: 1521 base_date = base_date + exp.Interval(this=month_expr - 1, unit=exp.var("MONTH")) 1522 1523 if day_expr: 1524 base_date = base_date + exp.Interval(this=day_expr - 1, unit=exp.var("DAY")) 1525 1526 return self.sql(exp.cast(expression=base_date, to=exp.DType.DATE)) 1527 1528 return self.func("MAKE_DATE", year_expr, month_expr, day_expr) 1529 1530 1531def _round_arg(arg: exp.Expr, round_input: bool | None = None) -> exp.Expr: 1532 if round_input: 1533 return exp.func("ROUND", arg, exp.Literal.number(0)) 1534 return arg 1535 1536 1537def _boolnot_sql(self: DuckDBGenerator, expression: exp.Boolnot) -> str: 1538 arg = _round_arg(expression.this, expression.args.get("round_input")) 1539 return self.sql(exp.not_(exp.paren(arg))) 1540 1541 1542def _booland_sql(self: DuckDBGenerator, expression: exp.Booland) -> str: 1543 round_input = expression.args.get("round_input") 1544 left = _round_arg(expression.this, round_input) 1545 right = _round_arg(expression.expression, round_input) 1546 return self.sql(exp.paren(exp.and_(exp.paren(left), exp.paren(right), wrap=False))) 1547 1548 1549def _boolor_sql(self: DuckDBGenerator, expression: exp.Boolor) -> str: 1550 round_input = expression.args.get("round_input") 1551 left = _round_arg(expression.this, round_input) 1552 right = _round_arg(expression.expression, round_input) 1553 return self.sql(exp.paren(exp.or_(exp.paren(left), exp.paren(right), wrap=False))) 1554 1555 1556def _xor_sql(self: DuckDBGenerator, expression: exp.Xor) -> str: 1557 round_input = expression.args.get("round_input") 1558 left = _round_arg(expression.this, round_input) 1559 right = _round_arg(expression.expression, round_input) 1560 return self.sql( 1561 exp.or_( 1562 exp.paren(exp.and_(left.copy(), exp.paren(right.not_()), wrap=False)), 1563 exp.paren(exp.and_(exp.paren(left.not_()), right.copy(), wrap=False)), 1564 wrap=False, 1565 ) 1566 ) 1567 1568 1569def _explode_to_unnest_sql(self: DuckDBGenerator, expression: exp.Lateral) -> str: 1570 """Handle LATERAL VIEW EXPLODE/INLINE conversion to UNNEST for DuckDB.""" 1571 explode = expression.this 1572 1573 if isinstance(explode, exp.Inline): 1574 # For INLINE, create CROSS JOIN LATERAL (SELECT UNNEST(..., max_depth => 2)) 1575 # Build the UNNEST call with DuckDB-style named parameter 1576 unnest_expr = exp.Unnest( 1577 expressions=[ 1578 explode.this, 1579 exp.Kwarg(this=exp.var("max_depth"), expression=exp.Literal.number(2)), 1580 ] 1581 ) 1582 select_expr = exp.Select(expressions=[unnest_expr]).subquery() 1583 1584 alias_expr = expression.args.get("alias") 1585 if alias_expr and not alias_expr.this: 1586 # we need to provide a table name if not present 1587 alias_expr.set("this", exp.to_identifier(f"_u_{expression.index}")) 1588 1589 transformed_lateral_expr = exp.Lateral(this=select_expr, alias=alias_expr) 1590 if expression.args.get("outer"): 1591 return self.sql(exp.Join(this=transformed_lateral_expr, side="LEFT", on=exp.true())) 1592 1593 cross_join_lateral_expr = exp.Join(this=transformed_lateral_expr, kind="CROSS") 1594 1595 return self.sql(cross_join_lateral_expr) 1596 1597 # For other cases, use the standard conversion 1598 return explode_to_unnest_sql(self, expression) 1599 1600 1601def _sha_sql( 1602 self: DuckDBGenerator, 1603 expression: exp.Expr, 1604 hash_func: str, 1605 is_binary: bool = False, 1606) -> str: 1607 arg = expression.this 1608 1609 # For SHA2 variants, check digest length (DuckDB only supports SHA256) 1610 if hash_func == "SHA256": 1611 length = expression.text("length") or "256" 1612 if length != "256": 1613 self.unsupported("DuckDB only supports SHA256 hashing algorithm.") 1614 1615 # Cast if type is incompatible with DuckDB 1616 if ( 1617 arg.type 1618 and arg.type.this != exp.DType.UNKNOWN 1619 and not arg.is_type(*exp.DataType.TEXT_TYPES) 1620 and not _is_binary(arg) 1621 ): 1622 arg = exp.cast(arg, exp.DType.VARCHAR) 1623 1624 result = self.func(hash_func, arg) 1625 return self.func("UNHEX", result) if is_binary else result 1626 1627 1628def _unqualify_pivot_columns(expression: exp.Expr) -> exp.Expr: 1629 # DuckDB requires unqualified pivot expressions. The source and CTEs have their own scope. 1630 # https://github.com/duckdb/duckdb/blob/671faf92411182f81dce42ac43de8bfb05d9909e/src/planner/binder/tableref/bind_pivot.cpp#L61-L62 1631 for clause in expression.iter_expressions(): 1632 if clause.arg_key not in ("this", "with_"): 1633 transforms.unqualify_columns(clause) 1634 return expression 1635 1636 1637class DuckDBGenerator(generator.Generator): 1638 DAYOFWEEK_NAME = "DAYOFWEEK" 1639 DAYOFWEEK_ZERO_BASED = True 1640 PARAMETER_TOKEN = "$" 1641 NAMED_PLACEHOLDER_TOKEN = "$" 1642 JOIN_HINTS = False 1643 SUPPORTS_MULTI_ARG_CHR = False 1644 TABLE_HINTS = False 1645 QUERY_HINTS = False 1646 LIMIT_FETCH = "LIMIT" 1647 SUPPORTS_NEAREST_JOIN = True 1648 MATCH_CONDITION_IN_ON = True 1649 STRUCT_DELIMITER = ("(", ")") 1650 RENAME_TABLE_WITH_DB = False 1651 NVL2_SUPPORTED = False 1652 SEMI_ANTI_JOIN_WITH_SIDE = False 1653 CAST_TO_INT_ROUNDS = True 1654 SAFE_INT_DIVISION = True 1655 INT_DIV_OPERATOR: str | None = "//" 1656 TABLESAMPLE_KEYWORDS = "USING SAMPLE" 1657 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 1658 LAST_DAY_SUPPORTS_DATE_PART = False 1659 JSON_KEY_VALUE_PAIR_SEP = "," 1660 IGNORE_NULLS_IN_FUNC = True 1661 IGNORE_NULLS_BEFORE_ORDER = False 1662 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 1663 SUPPORTS_CREATE_TABLE_LIKE = False 1664 MULTI_ARG_DISTINCT = False 1665 CAN_IMPLEMENT_ARRAY_ANY = True 1666 SUPPORTS_TO_NUMBER = False 1667 SELECT_KINDS = () 1668 SUPPORTS_DECODE_CASE = False 1669 SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY = False 1670 1671 # USING SAMPLE goes after QUALIFY and before ORDER BY / LIMIT 1672 # https://duckdb.org/docs/preview/sql/query_syntax/sample 1673 AFTER_HAVING_MODIFIER_TRANSFORMS = { 1674 **generator.AFTER_HAVING_MODIFIER_TRANSFORMS, 1675 "sample": lambda self, e: self.sql(e, "sample"), 1676 } 1677 SUPPORTS_WINDOW_EXCLUDE = True 1678 COPY_HAS_INTO_KEYWORD = False 1679 STAR_EXCEPT = "EXCLUDE" 1680 PAD_FILL_PATTERN_IS_REQUIRED = True 1681 ARRAY_SIZE_DIM_REQUIRED: bool | None = False 1682 NORMALIZE_EXTRACT_DATE_PARTS = True 1683 SUPPORTS_LIKE_QUANTIFIERS = False 1684 HISTORICAL_DATA_POST_ALIAS = True 1685 SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD = True 1686 1687 TRANSFORMS = { 1688 **generator.Generator.TRANSFORMS, 1689 exp.AnyValue: _anyvalue_sql, 1690 exp.ApproxDistinct: approx_count_distinct_sql, 1691 exp.ArgMax: _arg_max_or_min_sql, 1692 exp.ArgMin: _arg_max_or_min_sql, 1693 exp.Boolnot: _boolnot_sql, 1694 exp.Booland: _booland_sql, 1695 exp.Boolor: _boolor_sql, 1696 exp.Array: transforms.preprocess( 1697 [transforms.inherit_struct_field_names], 1698 generator=inline_array_unless_query, 1699 ), 1700 exp.ArrayAppend: array_append_sql("LIST_APPEND"), 1701 exp.ArrayCompact: array_compact_sql, 1702 exp.ArrayConstructCompact: lambda self, e: self.sql( 1703 exp.ArrayCompact(this=exp.Array(expressions=e.expressions)) 1704 ), 1705 exp.ArrayConcat: array_concat_sql("LIST_CONCAT"), 1706 exp.ArrayContains: _array_contains_sql, 1707 exp.ArrayOverlaps: _array_overlaps_sql, 1708 exp.ArrayFilter: rename_func("LIST_FILTER"), 1709 exp.ArrayInsert: _array_insert_sql, 1710 exp.ArrayPosition: lambda self, e: ( 1711 self.sql( 1712 exp.Sub( 1713 this=exp.ArrayPosition(this=e.this, expression=e.expression), 1714 expression=exp.Literal.number(1), 1715 ) 1716 ) 1717 if e.args.get("zero_based") 1718 else self.func("ARRAY_POSITION", e.this, e.expression) 1719 ), 1720 exp.ArrayRemoveAt: _array_remove_at_sql, 1721 exp.ArrayRemove: remove_from_array_using_filter, 1722 exp.ArraySort: _array_sort_sql, 1723 exp.ArrayPrepend: array_append_sql("LIST_PREPEND", swap_params=True), 1724 exp.ArraySum: rename_func("LIST_SUM"), 1725 exp.ArrayMax: rename_func("LIST_MAX"), 1726 exp.ArrayMin: rename_func("LIST_MIN"), 1727 exp.Base64DecodeBinary: lambda self, e: _base64_decode_sql(self, e, to_string=False), 1728 exp.Base64DecodeString: lambda self, e: _base64_decode_sql(self, e, to_string=True), 1729 exp.BitwiseAnd: lambda self, e: self._bitwise_op(e, "&"), 1730 exp.BitwiseAndAgg: _bitwise_agg_sql, 1731 exp.BitwiseCount: rename_func("BIT_COUNT"), 1732 exp.BitwiseLeftShift: _bitshift_sql, 1733 exp.BitwiseOr: lambda self, e: self._bitwise_op(e, "|"), 1734 exp.BitwiseOrAgg: _bitwise_agg_sql, 1735 exp.BitwiseRightShift: _bitshift_sql, 1736 exp.BitwiseXorAgg: _bitwise_agg_sql, 1737 exp.CommentColumnConstraint: no_comment_column_constraint_sql, 1738 exp.Corr: lambda self, e: self._corr_sql(e), 1739 exp.CosineDistance: rename_func("LIST_COSINE_DISTANCE"), 1740 exp.CurrentTime: lambda *_: "CURRENT_TIME", 1741 exp.CurrentSchemas: lambda self, e: self.func( 1742 "current_schemas", e.this if e.this else exp.true() 1743 ), 1744 exp.CurrentTimestamp: lambda self, e: ( 1745 self.sql( 1746 exp.AtTimeZone(this=exp.var("CURRENT_TIMESTAMP"), zone=exp.Literal.string("UTC")) 1747 ) 1748 if e.args.get("sysdate") 1749 else "CURRENT_TIMESTAMP" 1750 ), 1751 exp.CurrentVersion: rename_func("version"), 1752 exp.Localtime: unsupported_args("this")(lambda *_: "LOCALTIME"), 1753 exp.DayOfMonth: rename_func("DAYOFMONTH"), 1754 exp.DayOfWeekIso: rename_func("ISODOW"), 1755 exp.DayOfYear: rename_func("DAYOFYEAR"), 1756 exp.Dayname: lambda self, e: ( 1757 self.func("STRFTIME", e.this, exp.Literal.string("%a")) 1758 if e.args.get("abbreviated") 1759 else self.func("DAYNAME", e.this) 1760 ), 1761 exp.Monthname: lambda self, e: ( 1762 self.func("STRFTIME", e.this, exp.Literal.string("%b")) 1763 if e.args.get("abbreviated") 1764 else self.func("MONTHNAME", e.this) 1765 ), 1766 exp.Date: _date_sql, 1767 exp.DateAdd: _date_delta_to_binary_interval_op(), 1768 exp.DateFromParts: _date_from_parts_sql, 1769 exp.DateSub: _date_delta_to_binary_interval_op(), 1770 exp.DateDiff: _date_diff_sql, 1771 exp.DateStrToDate: datestrtodate_sql, 1772 exp.Datetime: no_datetime_sql, 1773 exp.DatetimeDiff: _date_diff_sql, 1774 exp.DatetimeSub: _date_delta_to_binary_interval_op(), 1775 exp.DatetimeAdd: _date_delta_to_binary_interval_op(), 1776 exp.DateToDi: lambda self, e: ( 1777 f"CAST(STRFTIME({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) AS INT)" 1778 ), 1779 exp.Decode: lambda self, e: encode_decode_sql(self, e, "DECODE", replace=False), 1780 exp.HexDecodeString: lambda self, e: self.sql(exp.Decode(this=exp.Unhex(this=e.this))), 1781 exp.DiToDate: lambda self, e: ( 1782 f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {self.dialect.DATEINT_FORMAT}) AS DATE)" 1783 ), 1784 exp.Encode: lambda self, e: encode_decode_sql(self, e, "ENCODE", replace=False), 1785 exp.EqualNull: lambda self, e: self.sql( 1786 exp.NullSafeEQ(this=e.this, expression=e.expression) 1787 ), 1788 exp.EuclideanDistance: rename_func("LIST_DISTANCE"), 1789 exp.GenerateDateArray: _generate_datetime_array_sql, 1790 exp.GenerateSeries: generate_series_sql("GENERATE_SERIES", "RANGE"), 1791 exp.GenerateTimestampArray: _generate_datetime_array_sql, 1792 exp.Getbit: getbit_sql, 1793 exp.Explode: rename_func("UNNEST"), 1794 exp.IcebergProperty: lambda *_: "", 1795 exp.IsInf: rename_func("ISINF"), 1796 exp.IsNan: rename_func("ISNAN"), 1797 exp.IsNullValue: lambda self, e: self.sql( 1798 exp.func("JSON_TYPE", e.this).eq(exp.Literal.string("NULL")) 1799 ), 1800 exp.IsArray: lambda self, e: self.sql( 1801 exp.func("JSON_TYPE", e.this).eq(exp.Literal.string("ARRAY")) 1802 ), 1803 exp.Ceil: _ceil_floor, 1804 exp.Floor: _ceil_floor, 1805 exp.JSONBExists: rename_func("JSON_EXISTS"), 1806 exp.JSONExtract: _arrow_json_extract_sql, 1807 exp.JSONExtractArray: _json_extract_value_array_sql, 1808 exp.JSONFormat: _json_format_sql, 1809 exp.JSONValueArray: _json_extract_value_array_sql, 1810 exp.Lateral: _explode_to_unnest_sql, 1811 exp.LogicalOr: lambda self, e: self.func("BOOL_OR", _cast_to_boolean(e.this)), 1812 exp.LogicalAnd: lambda self, e: self.func("BOOL_AND", _cast_to_boolean(e.this)), 1813 exp.Select: transforms.preprocess( 1814 [connect_by_to_recursive_cte, _seq_to_range_in_generator] 1815 ), 1816 exp.Seq1: lambda self, e: _seq_sql(self, e, 1), 1817 exp.Seq2: lambda self, e: _seq_sql(self, e, 2), 1818 exp.Seq4: lambda self, e: _seq_sql(self, e, 4), 1819 exp.Seq8: lambda self, e: _seq_sql(self, e, 8), 1820 exp.BoolxorAgg: _boolxor_agg_sql, 1821 exp.MakeInterval: lambda self, e: no_make_interval_sql(self, e, sep=" "), 1822 exp.Initcap: _initcap_sql, 1823 exp.MD5Digest: lambda self, e: self.func("UNHEX", self.func("MD5", e.this)), 1824 exp.Max: rename_func("MAX"), 1825 exp.Min: rename_func("MIN"), 1826 exp.SHA: lambda self, e: _sha_sql(self, e, "SHA1"), 1827 exp.SHA1Digest: lambda self, e: _sha_sql(self, e, "SHA1", is_binary=True), 1828 exp.SHA2: lambda self, e: _sha_sql(self, e, "SHA256"), 1829 exp.SHA2Digest: lambda self, e: _sha_sql(self, e, "SHA256", is_binary=True), 1830 exp.MonthsBetween: months_between_sql, 1831 exp.NextDay: _day_navigation_sql, 1832 exp.PercentileCont: rename_func("QUANTILE_CONT"), 1833 exp.PercentileDisc: rename_func("QUANTILE_DISC"), 1834 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 1835 exp.PreviousDay: _day_navigation_sql, 1836 exp.RegexpILike: lambda self, e: self.func( 1837 "REGEXP_MATCHES", e.this, e.expression, exp.Literal.string("i") 1838 ), 1839 exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"), 1840 exp.RegrValx: _regr_val_sql, 1841 exp.RegrValy: _regr_val_sql, 1842 exp.Return: lambda self, e: self.sql(e, "this"), 1843 exp.ReturnsProperty: lambda self, e: "TABLE" if isinstance(e.this, exp.Schema) else "", 1844 exp.StrToUnix: lambda self, e: self.func( 1845 "EPOCH", self.func("STRPTIME", e.this, self.format_time(e)) 1846 ), 1847 exp.Struct: _struct_sql, 1848 exp.Transform: rename_func("LIST_TRANSFORM"), 1849 exp.TimeAdd: _date_delta_to_binary_interval_op(), 1850 exp.TimeSub: _date_delta_to_binary_interval_op(), 1851 exp.Time: no_time_sql, 1852 exp.TimeDiff: _timediff_sql, 1853 exp.TimestampAdd: _date_delta_to_binary_interval_op(), 1854 exp.TimestampSub: _date_delta_to_binary_interval_op(), 1855 exp.TimeStrToDate: lambda self, e: self.sql(exp.cast(e.this, exp.DType.DATE)), 1856 exp.TimeStrToTime: timestrtotime_sql, 1857 exp.TimeStrToUnix: lambda self, e: self.func( 1858 "EPOCH", exp.cast(e.this, exp.DType.TIMESTAMP) 1859 ), 1860 exp.TimeToStr: lambda self, e: self.func("STRFTIME", e.this, self.format_time(e)), 1861 exp.ToBoolean: _to_boolean_sql, 1862 exp.ToVariant: lambda self, e: self.sql( 1863 exp.cast(e.this, exp.DataType.from_str("VARIANT", dialect="duckdb")) 1864 ), 1865 exp.TimeToUnix: rename_func("EPOCH"), 1866 exp.TsOrDiToDi: lambda self, e: ( 1867 f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)" 1868 ), 1869 exp.TsOrDsAdd: _date_delta_to_binary_interval_op(), 1870 exp.TsOrDsDiff: lambda self, e: self.func( 1871 "DATE_DIFF", 1872 exp.Literal.string(e.unit or "DAY"), 1873 exp.cast(e.expression, exp.DType.TIMESTAMP), 1874 exp.cast(e.this, exp.DType.TIMESTAMP), 1875 ), 1876 exp.UnixMicros: lambda self, e: self.func("EPOCH_US", _implicit_datetime_cast(e.this)), 1877 exp.UnixMillis: lambda self, e: self.func("EPOCH_MS", _implicit_datetime_cast(e.this)), 1878 exp.UnixSeconds: lambda self, e: self.sql( 1879 exp.cast(self.func("EPOCH", _implicit_datetime_cast(e.this)), exp.DType.BIGINT) 1880 ), 1881 exp.UnixToStr: lambda self, e: self.func( 1882 "STRFTIME", self.func("TO_TIMESTAMP", e.this), self.format_time(e) 1883 ), 1884 exp.UnixToTime: _unix_to_time_sql, 1885 exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)", 1886 exp.VariancePop: rename_func("VAR_POP"), 1887 exp.WeekOfYear: rename_func("WEEKOFYEAR"), 1888 exp.YearOfWeek: lambda self, e: self.sql( 1889 exp.Extract( 1890 this=exp.Var(this="ISOYEAR"), 1891 expression=e.this, 1892 ) 1893 ), 1894 exp.YearOfWeekIso: lambda self, e: self.sql( 1895 exp.Extract( 1896 this=exp.Var(this="ISOYEAR"), 1897 expression=e.this, 1898 ) 1899 ), 1900 exp.Xor: _xor_sql, 1901 exp.JSONObjectAgg: rename_func("JSON_GROUP_OBJECT"), 1902 exp.JSONArray: _json_constructor_sql, 1903 exp.JSONObject: _json_constructor_sql, 1904 exp.JSONBObjectAgg: rename_func("JSON_GROUP_OBJECT"), 1905 exp.DateBin: rename_func("TIME_BUCKET"), 1906 exp.LastDay: _last_day_sql, 1907 } 1908 1909 SUPPORTED_JSON_PATH_PARTS = { 1910 exp.JSONPathKey, 1911 exp.JSONPathRoot, 1912 exp.JSONPathSubscript, 1913 exp.JSONPathWildcard, 1914 } 1915 1916 TYPE_MAPPING = { 1917 **generator.Generator.TYPE_MAPPING, 1918 exp.DType.BINARY: "BLOB", 1919 exp.DType.BPCHAR: "TEXT", 1920 exp.DType.CHAR: "TEXT", 1921 exp.DType.DATETIME: "TIMESTAMP", 1922 exp.DType.DECFLOAT: "DECIMAL", 1923 exp.DType.FLOAT: "REAL", 1924 exp.DType.JSONB: "JSON", 1925 exp.DType.NCHAR: "TEXT", 1926 exp.DType.NVARCHAR: "TEXT", 1927 exp.DType.UINT: "UINTEGER", 1928 exp.DType.VARBINARY: "BLOB", 1929 exp.DType.ROWVERSION: "BLOB", 1930 exp.DType.VARCHAR: "TEXT", 1931 exp.DType.TIMESTAMPLTZ: "TIMESTAMPTZ", 1932 exp.DType.TIMESTAMPNTZ: "TIMESTAMP", 1933 exp.DType.TIMESTAMP_S: "TIMESTAMP_S", 1934 exp.DType.TIMESTAMP_MS: "TIMESTAMP_MS", 1935 exp.DType.TIMESTAMP_NS: "TIMESTAMP_NS", 1936 exp.DType.BIGDECIMAL: "DECIMAL", 1937 } 1938 1939 TYPE_PARAM_SETTINGS = { 1940 **generator.Generator.TYPE_PARAM_SETTINGS, 1941 exp.DType.BIGDECIMAL: ((38, 5), (38, 38)), 1942 exp.DType.DECFLOAT: ((38, 5), (38, 38)), 1943 } 1944 1945 # https://github.com/duckdb/duckdb/blob/ff7f24fd8e3128d94371827523dae85ebaf58713/third_party/libpg_query/grammar/keywords/reserved_keywords.list#L1-L77 1946 RESERVED_KEYWORDS = { 1947 "array", 1948 "analyse", 1949 "union", 1950 "all", 1951 "when", 1952 "in", 1953 "default", 1954 "create", 1955 "window", 1956 "asymmetric", 1957 "to", 1958 "else", 1959 "localtime", 1960 "from", 1961 "end", 1962 "select", 1963 "current_date", 1964 "foreign", 1965 "with", 1966 "grant", 1967 "session_user", 1968 "or", 1969 "except", 1970 "references", 1971 "fetch", 1972 "limit", 1973 "group", 1974 "leading", 1975 "into", 1976 "collate", 1977 "offset", 1978 "do", 1979 "then", 1980 "localtimestamp", 1981 "check", 1982 "lateral", 1983 "current_role", 1984 "where", 1985 "asc", 1986 "placing", 1987 "desc", 1988 "user", 1989 "unique", 1990 "initially", 1991 "column", 1992 "both", 1993 "some", 1994 "as", 1995 "any", 1996 "only", 1997 "deferrable", 1998 "null", 1999 "current_time", 2000 "true", 2001 "table", 2002 "case", 2003 "trailing", 2004 "variadic", 2005 "for", 2006 "on", 2007 "distinct", 2008 "false", 2009 "not", 2010 "constraint", 2011 "current_timestamp", 2012 "returning", 2013 "primary", 2014 "intersect", 2015 "having", 2016 "analyze", 2017 "current_user", 2018 "and", 2019 "cast", 2020 "symmetric", 2021 "using", 2022 "order", 2023 "current_catalog", 2024 "describe", 2025 "lambda", 2026 "pivot", 2027 "pivot_longer", 2028 "pivot_wider", 2029 "qualify", 2030 "show", 2031 "summarize", 2032 "unpivot", 2033 "anti", 2034 "asof", 2035 "at", 2036 "authorization", 2037 "binary", 2038 "by", 2039 "collation", 2040 "columns", 2041 "concurrently", 2042 "cross", 2043 "freeze", 2044 "full", 2045 "generated", 2046 "glob", 2047 "ilike", 2048 "inner", 2049 "is", 2050 "isnull", 2051 "join", 2052 "left", 2053 "like", 2054 "map", 2055 "natural", 2056 "notnull", 2057 "outer", 2058 "overlaps", 2059 "positional", 2060 "right", 2061 "semi", 2062 "similar", 2063 "struct", 2064 "tablesample", 2065 "try_cast", 2066 "tuple", 2067 "unpack", 2068 "verbose", 2069 } 2070 2071 UNWRAPPED_INTERVAL_VALUES = (exp.Literal, exp.Paren) 2072 2073 # DuckDB doesn't generally support CREATE TABLE .. properties 2074 # https://duckdb.org/docs/sql/statements/create_table.html 2075 # There are a few exceptions (e.g. temporary tables) which are supported or 2076 # can be transpiled to DuckDB, so we explicitly override them accordingly 2077 PROPERTIES_LOCATION = { 2078 **{ 2079 prop: exp.Properties.Location.UNSUPPORTED 2080 for prop in generator.Generator.PROPERTIES_LOCATION 2081 }, 2082 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 2083 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 2084 exp.ReturnsProperty: exp.Properties.Location.POST_ALIAS, 2085 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 2086 exp.TriggerProperties: exp.Properties.Location.POST_EXPRESSION, 2087 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 2088 } 2089 2090 IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS: t.ClassVar = _IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS 2091 2092 # Template for ZIPF transpilation - placeholders get replaced with actual parameters 2093 ZIPF_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2094 """ 2095 WITH rand AS (SELECT :random_expr AS r), 2096 weights AS ( 2097 SELECT i, 1.0 / POWER(i, :s) AS w 2098 FROM RANGE(1, :n + 1) AS t(i) 2099 ), 2100 cdf AS ( 2101 SELECT i, SUM(w) OVER (ORDER BY i) / SUM(w) OVER () AS p 2102 FROM weights 2103 ) 2104 SELECT MIN(i) 2105 FROM cdf 2106 WHERE p >= (SELECT r FROM rand) 2107 """ 2108 ) 2109 2110 # Template for NORMAL transpilation using Box-Muller transform 2111 # mean + (stddev * sqrt(-2 * ln(u1)) * cos(2 * pi * u2)) 2112 NORMAL_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2113 ":mean + (:stddev * SQRT(-2 * LN(GREATEST(:u1, 1e-10))) * COS(2 * PI() * :u2))" 2114 ) 2115 2116 # Template for generating a seeded pseudo-random value in [0, 1) from a hash 2117 SEEDED_RANDOM_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2118 "(ABS(HASH(:seed)) % 1000000) / 1000000.0" 2119 ) 2120 2121 # Template for generating signed and unsigned SEQ values within a specified range 2122 SEQ_UNSIGNED: t.ClassVar[exp.Expr] = _SEQ_UNSIGNED 2123 SEQ_SIGNED: t.ClassVar[exp.Expr] = _SEQ_SIGNED 2124 2125 # Template for MAP_CAT transpilation - Snowflake semantics: 2126 # 1. Returns NULL if either input is NULL 2127 # 2. For duplicate keys, prefers non-NULL value (COALESCE(m2[k], m1[k])) 2128 # 3. Filters out entries with NULL values from the result 2129 MAPCAT_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2130 """ 2131 CASE 2132 WHEN :map1 IS NULL OR :map2 IS NULL THEN NULL 2133 ELSE MAP_FROM_ENTRIES(LIST_FILTER(LIST_TRANSFORM( 2134 LIST_DISTINCT(LIST_CONCAT(MAP_KEYS(:map1), MAP_KEYS(:map2))), 2135 __k -> STRUCT_PACK(key := __k, value := COALESCE(:map2[__k], :map1[__k])) 2136 ), __x -> __x.value IS NOT NULL)) 2137 END 2138 """ 2139 ) 2140 2141 # Mappings for EXTRACT/DATE_PART transpilation 2142 # Maps Snowflake specifiers unsupported in DuckDB to strftime format codes 2143 EXTRACT_STRFTIME_MAPPINGS: t.ClassVar[dict[str, tuple[str, str]]] = { 2144 "WEEKISO": ("%V", "INTEGER"), 2145 "YEAROFWEEK": ("%G", "INTEGER"), 2146 "YEAROFWEEKISO": ("%G", "INTEGER"), 2147 "NANOSECOND": ("%n", "BIGINT"), 2148 } 2149 2150 # Maps epoch-based specifiers to DuckDB epoch functions 2151 EXTRACT_EPOCH_MAPPINGS: t.ClassVar[dict[str, str]] = { 2152 "EPOCH_SECOND": "EPOCH", 2153 "EPOCH_MILLISECOND": "EPOCH_MS", 2154 "EPOCH_MICROSECOND": "EPOCH_US", 2155 "EPOCH_NANOSECOND": "EPOCH_NS", 2156 } 2157 2158 # Template for BITMAP_CONSTRUCT_AGG transpilation 2159 # 2160 # BACKGROUND: 2161 # Snowflake's BITMAP_CONSTRUCT_AGG aggregates integers into a compact binary bitmap. 2162 # Supports values in range 0-32767, this version returns NULL if any value is out of range 2163 # See: https://docs.snowflake.com/en/sql-reference/functions/bitmap_construct_agg 2164 # See: https://docs.snowflake.com/en/user-guide/querying-bitmaps-for-distinct-counts 2165 # 2166 # Snowflake uses two different formats based on the number of unique values: 2167 # 2168 # Format 1 - Small bitmap (< 5 unique values): Length of 10 bytes 2169 # Bytes 0-1: Count of values as 2-byte big-endian integer (e.g., 3 values = 0x0003) 2170 # Bytes 2-9: Up to 4 values, each as 2-byte little-endian integers, zero-padded to 8 bytes 2171 # Example: Values [1, 2, 3] -> 0x0003 0100 0200 0300 0000 (hex) 2172 # count v1 v2 v3 pad 2173 # 2174 # Format 2 - Large bitmap (>= 5 unique values): Length of 10 + (2 * count) bytes 2175 # Bytes 0-9: Fixed header 0x08 followed by 9 zero bytes 2176 # Bytes 10+: Each value as 2-byte little-endian integer (no padding) 2177 # Example: Values [1,2,3,4,5] -> 0x08 00000000 00000000 00 0100 0200 0300 0400 0500 2178 # hdr ----9 zero bytes---- v1 v2 v3 v4 v5 2179 # 2180 # TEMPLATE STRUCTURE 2181 # 2182 # Phase 1 - Innermost subquery: Data preparation 2183 # SELECT LIST_SORT(...) AS l 2184 # - Aggregates all input values into a list, remove NULLs, duplicates and sorts 2185 # Result: Clean, sorted list of unique non-null integers stored as 'l' 2186 # 2187 # Phase 2 - Middle subquery: Hex string construction 2188 # LIST_TRANSFORM(...) 2189 # - Converts each integer to 2-byte little-endian hex representation 2190 # - & 255 extracts low byte, >> 8 extracts high byte 2191 # - LIST_REDUCE: Concatenates all hex pairs into single string 'h' 2192 # Result: Hex string of all values 2193 # 2194 # Phase 3 - Outer SELECT: Final bitmap assembly 2195 # LENGTH(l) < 5: 2196 # - Small format: 2-byte count (big-endian via %04X) + values + zero padding 2197 # LENGTH(l) >= 5: 2198 # - Large format: Fixed 10-byte header + values (no padding needed) 2199 # Result: Complete binary bitmap as BLOB 2200 # 2201 BITMAP_CONSTRUCT_AGG_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2202 """ 2203 SELECT CASE 2204 WHEN l IS NULL OR LENGTH(l) = 0 THEN NULL 2205 WHEN LENGTH(l) != LENGTH(LIST_FILTER(l, __v -> __v BETWEEN 0 AND 32767)) THEN NULL 2206 WHEN LENGTH(l) < 5 THEN UNHEX(PRINTF('%04X', LENGTH(l)) || h || REPEAT('00', GREATEST(0, 4 - LENGTH(l)) * 2)) 2207 ELSE UNHEX('08000000000000000000' || h) 2208 END 2209 FROM ( 2210 SELECT l, COALESCE(LIST_REDUCE( 2211 LIST_TRANSFORM(l, __x -> PRINTF('%02X%02X', CAST(__x AS INT) & 255, (CAST(__x AS INT) >> 8) & 255)), 2212 (__a, __b) -> __a || __b, '' 2213 ), '') AS h 2214 FROM (SELECT LIST_SORT(LIST_DISTINCT(LIST(:arg) FILTER(NOT :arg IS NULL))) AS l) 2215 ) 2216 """ 2217 ) 2218 2219 # Template for RANDSTR transpilation - placeholders get replaced with actual parameters 2220 RANDSTR_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2221 f""" 2222 SELECT LISTAGG( 2223 SUBSTRING( 2224 '{RANDSTR_CHAR_POOL}', 2225 1 + CAST(FLOOR(random_value * 62) AS INT), 2226 1 2227 ), 2228 '' 2229 ) 2230 FROM ( 2231 SELECT (ABS(HASH(i + :seed)) % 1000) / 1000.0 AS random_value 2232 FROM RANGE(:length) AS t(i) 2233 ) 2234 """, 2235 ) 2236 2237 # Template for MINHASH transpilation 2238 # Computes k minimum hash values across aggregated data using DuckDB list functions 2239 # Returns JSON matching Snowflake format: {"state": [...], "type": "minhash", "version": 1} 2240 MINHASH_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2241 """ 2242 SELECT JSON_OBJECT('state', LIST(min_h ORDER BY seed), 'type', 'minhash', 'version', 1) 2243 FROM ( 2244 SELECT seed, LIST_MIN(LIST_TRANSFORM(vals, __v -> HASH(CAST(__v AS VARCHAR) || CAST(seed AS VARCHAR)))) AS min_h 2245 FROM (SELECT LIST(:expr) AS vals), RANGE(0, :k) AS t(seed) 2246 ) 2247 """, 2248 ) 2249 2250 # Template for MINHASH_COMBINE transpilation 2251 # Combines multiple minhash signatures by taking element-wise minimum 2252 MINHASH_COMBINE_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2253 """ 2254 SELECT JSON_OBJECT('state', LIST(min_h ORDER BY idx), 'type', 'minhash', 'version', 1) 2255 FROM ( 2256 SELECT 2257 pos AS idx, 2258 MIN(val) AS min_h 2259 FROM 2260 UNNEST(LIST(:expr)) AS _(sig), 2261 UNNEST(CAST(sig -> 'state' AS UBIGINT[])) WITH ORDINALITY AS t(val, pos) 2262 GROUP BY pos 2263 ) 2264 """, 2265 ) 2266 2267 # Template for APPROXIMATE_SIMILARITY transpilation 2268 # Computes multi-way Jaccard similarity: fraction of positions where ALL signatures agree 2269 APPROXIMATE_SIMILARITY_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2270 """ 2271 SELECT CAST(SUM(CASE WHEN num_distinct = 1 THEN 1 ELSE 0 END) AS DOUBLE) / COUNT(*) 2272 FROM ( 2273 SELECT pos, COUNT(DISTINCT h) AS num_distinct 2274 FROM ( 2275 SELECT h, pos 2276 FROM UNNEST(LIST(:expr)) AS _(sig), 2277 UNNEST(CAST(sig -> 'state' AS UBIGINT[])) WITH ORDINALITY AS s(h, pos) 2278 ) 2279 GROUP BY pos 2280 ) 2281 """, 2282 ) 2283 2284 # Template for ARRAYS_ZIP transpilation 2285 # Snowflake pads to longest array; DuckDB LIST_ZIP truncates to shortest 2286 # Uses RANGE + indexing to match Snowflake behavior 2287 ARRAYS_ZIP_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2288 """ 2289 CASE WHEN :null_check THEN NULL 2290 WHEN :all_empty_check THEN [:empty_struct] 2291 ELSE LIST_TRANSFORM(RANGE(0, :max_len), __i -> :transform_struct) 2292 END 2293 """, 2294 ) 2295 2296 UUID_V5_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2297 """ 2298 (SELECT 2299 LOWER( 2300 SUBSTR(h, 1, 8) || '-' || 2301 SUBSTR(h, 9, 4) || '-' || 2302 '5' || SUBSTR(h, 14, 3) || '-' || 2303 PRINTF('%02x', CAST('0x' || SUBSTR(h, 17, 2) AS INT) & 63 | 128) || SUBSTR(h, 19, 2) || '-' || 2304 SUBSTR(h, 21, 12) 2305 ) 2306 FROM ( 2307 SELECT SUBSTR(SHA1(UNHEX(REPLACE(:namespace, '-', '')) || ENCODE(:name, 'utf8')), 1, 32) AS h 2308 )) 2309 """ 2310 ) 2311 2312 # Shared bag semantics outer frame for ARRAY_EXCEPT and ARRAY_INTERSECTION. 2313 # Each element is paired with its 1-based position via LIST_ZIP, then filtered 2314 # by a comparison operator (supplied via :cond) that determines the operation: 2315 # EXCEPT (>): keep the N-th occurrence only if N > count in arr2 2316 # e.g. [2,2,2] EXCEPT [2,2] -> [2] 2317 # INTERSECTION (<=): keep the N-th occurrence only if N <= count in arr2 2318 # e.g. [2,2,2] INTERSECT [2,2] -> [2,2] 2319 # IS NOT DISTINCT FROM is used for NULL-safe element comparison. 2320 ARRAY_BAG_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2321 """ 2322 CASE 2323 WHEN :arr1 IS NULL OR :arr2 IS NULL THEN NULL 2324 ELSE LIST_TRANSFORM( 2325 LIST_FILTER( 2326 LIST_ZIP(:arr1, GENERATE_SERIES(1, LEN(:arr1))), 2327 pair -> :cond 2328 ), 2329 pair -> pair[0] 2330 ) 2331 END 2332 """ 2333 ) 2334 2335 ARRAY_EXCEPT_CONDITION: t.ClassVar[exp.Expr] = exp.maybe_parse( 2336 "LEN(LIST_FILTER(:arr1[1:pair[1]], e -> e IS NOT DISTINCT FROM pair[0]))" 2337 " > LEN(LIST_FILTER(:arr2, e -> e IS NOT DISTINCT FROM pair[0]))" 2338 ) 2339 2340 ARRAY_INTERSECTION_CONDITION: t.ClassVar[exp.Expr] = exp.maybe_parse( 2341 "LEN(LIST_FILTER(:arr1[1:pair[1]], e -> e IS NOT DISTINCT FROM pair[0]))" 2342 " <= LEN(LIST_FILTER(:arr2, e -> e IS NOT DISTINCT FROM pair[0]))" 2343 ) 2344 2345 # Set semantics for ARRAY_EXCEPT. Deduplicates arr1 via LIST_DISTINCT, then 2346 # filters out any element that appears at least once in arr2. 2347 # e.g. [1,1,2,3] EXCEPT [1] -> [2,3] 2348 # IS NOT DISTINCT FROM is used for NULL-safe element comparison. 2349 ARRAY_EXCEPT_SET_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2350 """ 2351 CASE 2352 WHEN :arr1 IS NULL OR :arr2 IS NULL THEN NULL 2353 ELSE LIST_FILTER( 2354 LIST_DISTINCT(:arr1), 2355 e -> LEN(LIST_FILTER(:arr2, x -> x IS NOT DISTINCT FROM e)) = 0 2356 ) 2357 END 2358 """ 2359 ) 2360 2361 # BigQuery's `x IN UNNEST(arr)` NULL semantics: 2362 # NULL IN UNNEST([1, 2]) -> NULL 2363 # 3 IN UNNEST([1, NULL]) -> NULL 2364 # 3 IN UNNEST([1, 2]) -> FALSE 2365 # 1 IN UNNEST(NULL) -> FALSE (not NULL) 2366 # 1 IN UNNEST([]) -> FALSE 2367 # The default `IN (SELECT UNNEST(...))` rewrite creates a correlated subquery 2368 # that DuckDB rejects inside non-inner joins, so a CASE expression is used instead. 2369 IN_UNNEST_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2370 """ 2371 CASE 2372 WHEN :arr IS NULL OR ARRAY_LENGTH(:arr) = 0 THEN FALSE 2373 WHEN ARRAY_CONTAINS(:arr, :value) THEN TRUE 2374 WHEN :value IS NULL OR ARRAY_LENGTH(:arr) <> LIST_COUNT(:arr) THEN NULL 2375 ELSE FALSE 2376 END 2377 """ 2378 ) 2379 2380 STRTOK_TO_ARRAY_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2381 """ 2382 CASE WHEN :delimiter IS NULL THEN NULL 2383 ELSE LIST_FILTER( 2384 REGEXP_SPLIT_TO_ARRAY(:string, CASE WHEN :delimiter = '' THEN '.^' ELSE CONCAT('[', :escaped, ']') END), 2385 x -> NOT x = '' 2386 ) END 2387 """ 2388 ) 2389 2390 # Template for STRTOK function transpilation 2391 # 2392 # DuckDB itself doesn't have a strtok function. This handles the transpilation from Snowflake to DuckDB. 2393 # We may need to adjust this if we want to support transpilation from other dialects 2394 # 2395 # CASE 2396 # -- Snowflake: empty delimiter + empty input string -> NULL 2397 # WHEN delimiter = '' AND input_str = '' THEN NULL 2398 # 2399 # -- Snowflake: empty delimiter + non-empty input string -> treats whole input as 1 token -> return input string if index is 1 2400 # WHEN delimiter = '' AND index = 1 THEN input_str 2401 # 2402 # -- Snowflake: empty delimiter + non-empty input string -> treats whole input as 1 token -> return NULL if index is not 1 2403 # WHEN delimiter = '' THEN NULL 2404 # 2405 # -- Snowflake: negative indices return NULL 2406 # WHEN index < 0 THEN NULL 2407 # 2408 # -- Snowflake: return NULL if any argument is NULL 2409 # WHEN input_str IS NULL OR delimiter IS NULL OR index IS NULL THEN NULL 2410 # 2411 # 2412 # ELSE LIST_FILTER( 2413 # REGEXP_SPLIT_TO_ARRAY( 2414 # input_str, 2415 # CASE 2416 # -- if delimiter is '', we don't want to surround it with '[' and ']' as '[]' is invalid for DuckDB 2417 # WHEN delimiter = '' THEN '' 2418 # 2419 # -- handle problematic regex characters in delimiter with REGEXP_REPLACE 2420 # -- turn delimiter into a regex char set, otherwise DuckDB will match in order, which we don't want 2421 # ELSE '[' || REGEXP_REPLACE(delimiter, problematic_char_set, '\\\1', 'g') || ']' 2422 # END 2423 # ), 2424 # 2425 # -- Snowflake: don't return empty strings 2426 # x -> NOT x = '' 2427 # )[index] 2428 # END 2429 STRTOK_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2430 """ 2431 CASE 2432 WHEN :delimiter = '' AND :string = '' THEN NULL 2433 WHEN :delimiter = '' AND :part_index = 1 THEN :string 2434 WHEN :delimiter = '' THEN NULL 2435 WHEN :part_index < 0 THEN NULL 2436 WHEN :string IS NULL OR :delimiter IS NULL OR :part_index IS NULL THEN NULL 2437 ELSE :base_func 2438 END 2439 """ 2440 ) 2441 2442 # Snowflake AUTO detects 3 DATE formats: YYYY-MM-DD (ISO-8601), MM/DD/YYYY, DD-MON-YYYY. 2443 # DuckDB TRY_CAST handles ISO-8601 natively. For the other two formats we use CONTAINS('/') 2444 # and REGEXP_MATCHES('[A-Za-z]') as heuristics — these correctly handle single-digit months 2445 # and days (e.g. 1/5/2020, 5-JAN-2020) where a positional char check would fail. 2446 # Ref: https://docs.snowflake.com/en/sql-reference/date-time-input-output#date-formats 2447 _TRYCAST_DATE_SLASH_FMT = "%m/%d/%Y" 2448 _TRYCAST_DATE_MON_FMT = "%d-%b-%Y" 2449 2450 def datatype_sql(self, expression: exp.DataType) -> str: 2451 if expression.is_type(exp.DType.ARRAY): 2452 return f"{self.expressions(expression, flat=True)}[{self.expressions(expression, key='values', flat=True)}]" 2453 2454 # Modifiers are not supported for TIME, [TIME | TIMESTAMP] WITH TIME ZONE 2455 if expression.is_type( 2456 exp.DType.TIME, exp.DType.TIMETZ, exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ 2457 ): 2458 expression.set("expressions", None) 2459 2460 return super().datatype_sql(expression) 2461 2462 def _array_bag_sql(self, condition: exp.Expr, arr1: exp.Expr, arr2: exp.Expr) -> str: 2463 cond = exp.Paren(this=exp.replace_placeholders(condition, arr1=arr1, arr2=arr2)) 2464 return self.sql( 2465 exp.replace_placeholders(self.ARRAY_BAG_TEMPLATE, arr1=arr1, arr2=arr2, cond=cond) 2466 ) 2467 2468 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 2469 """ 2470 Transform Snowflake's TIME_SLICE to DuckDB's time_bucket. 2471 2472 Snowflake: TIME_SLICE(date_expr, slice_length, 'UNIT' [, 'START'|'END']) 2473 DuckDB: time_bucket(INTERVAL 'slice_length' UNIT, date_expr, origin) 2474 2475 Snowflake aligns slices to the 1970-01-01 epoch, so an explicit origin is 2476 required because DuckDB's default origin differs. For 'END' kind, add the 2477 interval to get the next slice's start; for DATE input, cast back to DATE. 2478 """ 2479 date_expr = expression.this 2480 slice_length = expression.expression 2481 # Normalize unit aliases (e.g. W/WK/WOY -> WEEK) so the interval and origin agree 2482 unit = map_date_part(expression.unit, self.dialect) 2483 kind = expression.text("kind").upper() 2484 2485 interval_expr = exp.Interval(this=slice_length, unit=unit) 2486 2487 origin = expression.args.get("origin") 2488 if origin is None: 2489 # Snowflake aligns to 1970-01-01; WEEK to the Monday of the epoch week (WEEK_START=0) 2490 origin = exp.Literal.string( 2491 "1969-12-29" if unit and unit.name.upper() == "WEEK" else "1970-01-01" 2492 ) 2493 # A DATE origin keeps a DATE input a DATE; DuckDB widens it for TIMESTAMP inputs 2494 time_bucket_expr = exp.func( 2495 "time_bucket", interval_expr, date_expr, exp.cast(origin, exp.DType.DATE) 2496 ) 2497 2498 if kind != "END": 2499 return self.sql(time_bucket_expr) 2500 2501 add_expr = exp.Add(this=time_bucket_expr, expression=interval_expr.copy()) 2502 2503 # DuckDB widens DATE to TIMESTAMP when adding intervals, so cast back 2504 if date_expr.is_type(exp.DType.DATE): 2505 return self.sql(exp.cast(add_expr, exp.DType.DATE)) 2506 2507 return self.sql(add_expr) 2508 2509 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 2510 # DuckDB has no Unicode escape strings and doesn't read \u in a string, so the escapes 2511 # are decoded into the characters, e.g. U&'d\0061t\0061' and U&'d!+000061ta' UESCAPE '!' 2512 # are both 'data' 2513 escape = expression.args.get("escape") 2514 text = decode_unicode_escapes( 2515 expression.name, escape.name if isinstance(escape, exp.Expr) else "\\" 2516 ) 2517 return self.sql(exp.Literal.string(text)) 2518 2519 def bytestring_sql(self, expression: exp.ByteString) -> str: 2520 if not expression.args.get("is_bytes"): 2521 return super().bytestring_sql(expression) 2522 2523 # Each char is a byte. Casting to BLOB decodes \xHH, so everything but printable ASCII 2524 # (including the backslash itself) is written as such 2525 text = "".join( 2526 ch if ch.isascii() and ch.isprintable() and ch != "\\" else f"\\x{ord(ch):02x}" 2527 for ch in expression.this 2528 ) 2529 return self.sql(exp.cast(exp.Literal.string(text), exp.DType.BINARY)) 2530 2531 def bitmapbucketnumber_sql(self, expression: exp.BitmapBucketNumber) -> str: 2532 """ 2533 Transpile BITMAP_BUCKET_NUMBER function from Snowflake to DuckDB equivalent. 2534 2535 Snowflake's BITMAP_BUCKET_NUMBER returns a 1-based bucket identifier where: 2536 - Each bucket covers 32,768 values 2537 - Bucket numbering starts at 1 2538 - Formula: ((value - 1) // 32768) + 1 for positive values 2539 2540 For non-positive values (0 and negative), we use value // 32768 to avoid 2541 producing bucket 0 or positive bucket IDs for negative inputs. 2542 """ 2543 value = expression.this 2544 2545 positive_formula = ((value - 1) // 32768) + 1 2546 non_positive_formula = value // 32768 2547 2548 # CASE WHEN value > 0 THEN ((value - 1) // 32768) + 1 ELSE value // 32768 END 2549 case_expr = ( 2550 exp.case() 2551 .when(exp.GT(this=value, expression=exp.Literal.number(0)), positive_formula) 2552 .else_(non_positive_formula) 2553 ) 2554 return self.sql(case_expr) 2555 2556 def bitmapbitposition_sql(self, expression: exp.BitmapBitPosition) -> str: 2557 """ 2558 Transpile Snowflake's BITMAP_BIT_POSITION to DuckDB CASE expression. 2559 2560 Snowflake's BITMAP_BIT_POSITION behavior: 2561 - For n <= 0: returns ABS(n) % 32768 2562 - For n > 0: returns (n - 1) % 32768 (maximum return value is 32767) 2563 """ 2564 this = expression.this 2565 2566 return self.sql( 2567 exp.Mod( 2568 this=exp.Paren( 2569 this=exp.If( 2570 this=exp.GT(this=this, expression=exp.Literal.number(0)), 2571 true=this - exp.Literal.number(1), 2572 false=exp.Abs(this=this), 2573 ) 2574 ), 2575 expression=MAX_BIT_POSITION, 2576 ) 2577 ) 2578 2579 def bitmapconstructagg_sql(self, expression: exp.BitmapConstructAgg) -> str: 2580 """ 2581 Transpile Snowflake's BITMAP_CONSTRUCT_AGG to DuckDB equivalent. 2582 Uses a pre-parsed template with placeholders replaced by expression nodes. 2583 2584 Snowflake bitmap format: 2585 - Small (< 5 unique values): 2-byte count (big-endian) + values (little-endian) + padding to 10 bytes 2586 - Large (>= 5 unique values): 10-byte header (0x08 + 9 zeros) + values (little-endian) 2587 """ 2588 arg = expression.this 2589 return ( 2590 f"({self.sql(exp.replace_placeholders(self.BITMAP_CONSTRUCT_AGG_TEMPLATE, arg=arg))})" 2591 ) 2592 2593 def getignorecase_sql(self, expression: exp.GetIgnoreCase) -> str: 2594 self.unsupported("DuckDB does not support the GET_IGNORE_CASE() function") 2595 return self.function_fallback_sql(expression) 2596 2597 def compress_sql(self, expression: exp.Compress) -> str: 2598 self.unsupported("DuckDB does not support the COMPRESS() function") 2599 return self.function_fallback_sql(expression) 2600 2601 def encrypt_sql(self, expression: exp.Encrypt) -> str: 2602 self.unsupported("ENCRYPT is not supported in DuckDB") 2603 return self.function_fallback_sql(expression) 2604 2605 def decrypt_sql(self, expression: exp.Decrypt) -> str: 2606 func_name = "TRY_DECRYPT" if expression.args.get("safe") else "DECRYPT" 2607 self.unsupported(f"{func_name} is not supported in DuckDB") 2608 return self.function_fallback_sql(expression) 2609 2610 def decryptraw_sql(self, expression: exp.DecryptRaw) -> str: 2611 func_name = "TRY_DECRYPT_RAW" if expression.args.get("safe") else "DECRYPT_RAW" 2612 self.unsupported(f"{func_name} is not supported in DuckDB") 2613 return self.function_fallback_sql(expression) 2614 2615 def encryptraw_sql(self, expression: exp.EncryptRaw) -> str: 2616 self.unsupported("ENCRYPT_RAW is not supported in DuckDB") 2617 return self.function_fallback_sql(expression) 2618 2619 def parseurl_sql(self, expression: exp.ParseUrl) -> str: 2620 self.unsupported("PARSE_URL is not supported in DuckDB") 2621 return self.function_fallback_sql(expression) 2622 2623 def parseip_sql(self, expression: exp.ParseIp) -> str: 2624 self.unsupported("PARSE_IP is not supported in DuckDB") 2625 return self.function_fallback_sql(expression) 2626 2627 def decompressstring_sql(self, expression: exp.DecompressString) -> str: 2628 self.unsupported("DECOMPRESS_STRING is not supported in DuckDB") 2629 return self.function_fallback_sql(expression) 2630 2631 def decompressbinary_sql(self, expression: exp.DecompressBinary) -> str: 2632 self.unsupported("DECOMPRESS_BINARY is not supported in DuckDB") 2633 return self.function_fallback_sql(expression) 2634 2635 def jarowinklersimilarity_sql(self, expression: exp.JarowinklerSimilarity) -> str: 2636 this = expression.this 2637 expr = expression.expression 2638 2639 if expression.args.get("case_insensitive"): 2640 this = exp.Upper(this=this) 2641 expr = exp.Upper(this=expr) 2642 2643 result = exp.func("JARO_WINKLER_SIMILARITY", this, expr) 2644 2645 if expression.args.get("integer_scale"): 2646 result = exp.cast(result * 100, "INTEGER") 2647 2648 return self.sql(result) 2649 2650 def randstr_sql(self, expression: exp.Randstr) -> str: 2651 """ 2652 Transpile Snowflake's RANDSTR to DuckDB equivalent using deterministic hash-based random. 2653 Uses a pre-parsed template with placeholders replaced by expression nodes. 2654 2655 RANDSTR(length, generator) generates a random string of specified length. 2656 - With numeric seed: Use HASH(i + seed) for deterministic output (same seed = same result) 2657 - With RANDOM(): Use RANDOM() in the hash for non-deterministic output 2658 - No generator: Use default seed value 2659 """ 2660 length = expression.this 2661 generator = expression.args.get("generator") 2662 2663 if generator: 2664 if isinstance(generator, exp.Rand): 2665 # If it's RANDOM(), use its seed if available, otherwise use RANDOM() itself 2666 seed_value = generator.this or generator 2667 else: 2668 # Const/int or other expression - use as seed directly 2669 seed_value = generator 2670 else: 2671 # No generator specified, use default seed (arbitrary but deterministic) 2672 seed_value = exp.Literal.number(RANDSTR_SEED) 2673 2674 replacements = {"seed": seed_value, "length": length} 2675 return f"({self.sql(exp.replace_placeholders(self.RANDSTR_TEMPLATE, **replacements))})" 2676 2677 @unsupported_args("finish") 2678 def reduce_sql(self, expression: exp.Reduce) -> str: 2679 array_arg = expression.this 2680 initial_value = expression.args.get("initial") 2681 merge_lambda = expression.args.get("merge") 2682 2683 return self.func("list_reduce", array_arg, merge_lambda, initial_value) 2684 2685 def zipf_sql(self, expression: exp.Zipf) -> str: 2686 """ 2687 Transpile Snowflake's ZIPF to DuckDB using CDF-based inverse sampling. 2688 Uses a pre-parsed template with placeholders replaced by expression nodes. 2689 """ 2690 s = expression.this 2691 n = expression.args["elementcount"] 2692 gen = expression.args["gen"] 2693 2694 if not isinstance(gen, exp.Rand): 2695 # (ABS(HASH(seed)) % 1000000) / 1000000.0 2696 random_expr: exp.Expr = exp.Div( 2697 this=exp.Paren( 2698 this=exp.Mod( 2699 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen.copy()])), 2700 expression=exp.Literal.number(1000000), 2701 ) 2702 ), 2703 expression=exp.Literal.number(1000000.0), 2704 ) 2705 else: 2706 # Use RANDOM() for non-deterministic output 2707 random_expr = exp.Rand() 2708 2709 replacements = {"s": s, "n": n, "random_expr": random_expr} 2710 return f"({self.sql(exp.replace_placeholders(self.ZIPF_TEMPLATE, **replacements))})" 2711 2712 def tobinary_sql(self, expression: exp.ToBinary) -> str: 2713 """ 2714 TO_BINARY and TRY_TO_BINARY transpilation: 2715 - 'HEX': TO_BINARY('48454C50', 'HEX') -> UNHEX('48454C50') 2716 - 'UTF-8': TO_BINARY('TEST', 'UTF-8') -> ENCODE('TEST') 2717 - 'BASE64': TO_BINARY('SEVMUA==', 'BASE64') -> FROM_BASE64('SEVMUA==') 2718 2719 For TRY_TO_BINARY (safe=True), wrap with TRY(): 2720 - 'HEX': TRY_TO_BINARY('invalid', 'HEX') -> TRY(UNHEX('invalid')) 2721 """ 2722 value = expression.this 2723 format_arg = expression.args.get("format") 2724 is_safe = expression.args.get("safe") 2725 is_binary = _is_binary(expression) 2726 2727 if not format_arg and not is_binary: 2728 func_name = "TRY_TO_BINARY" if is_safe else "TO_BINARY" 2729 return self.func(func_name, value) 2730 2731 # Snowflake defaults to HEX encoding when no format is specified 2732 fmt = format_arg.name.upper() if format_arg else "HEX" 2733 2734 if fmt in ("UTF-8", "UTF8"): 2735 # DuckDB ENCODE always uses UTF-8, no charset parameter needed 2736 result = self.func("ENCODE", value) 2737 elif fmt == "BASE64": 2738 result = self.func("FROM_BASE64", value) 2739 elif fmt == "HEX": 2740 result = self.func("UNHEX", value) 2741 else: 2742 if is_safe: 2743 return self.sql(exp.null()) 2744 else: 2745 self.unsupported(f"format {fmt} is not supported") 2746 result = self.func("TO_BINARY", value) 2747 return f"TRY({result})" if is_safe else result 2748 2749 def tonumber_sql(self, expression: exp.ToNumber) -> str: 2750 fmt = expression.args.get("format") 2751 precision = expression.args.get("precision") 2752 scale = expression.args.get("scale") 2753 2754 if not fmt and precision and scale: 2755 to = exp.DataType.build(f"DECIMAL({precision.name}, {scale.name})", dialect="duckdb") 2756 if expression.args.get("safe"): 2757 return self.sql(exp.TryCast(this=expression.this, to=to)) 2758 return self.sql(exp.cast(expression.this, to, dialect="duckdb")) 2759 2760 return super().tonumber_sql(expression) 2761 2762 def _greatest_least_sql(self, expression: exp.Greatest | exp.Least) -> str: 2763 """ 2764 Handle GREATEST/LEAST functions with dialect-aware NULL behavior. 2765 2766 - If ignore_nulls=False (BigQuery-style): return NULL if any argument is NULL 2767 - If ignore_nulls=True (DuckDB/PostgreSQL-style): ignore NULLs, return greatest/least non-NULL value 2768 """ 2769 # Get all arguments 2770 all_args = [expression.this, *expression.expressions] 2771 fallback_sql = self.function_fallback_sql(expression) 2772 2773 if expression.args.get("ignore_nulls"): 2774 # DuckDB/PostgreSQL behavior: use native GREATEST/LEAST (ignores NULLs) 2775 return self.sql(fallback_sql) 2776 2777 # return NULL if any argument is NULL 2778 case_expr = exp.case().when( 2779 exp.or_(*[arg.is_(exp.null()) for arg in all_args], copy=False), 2780 exp.null(), 2781 copy=False, 2782 ) 2783 case_expr.set("default", fallback_sql) 2784 return self.sql(case_expr) 2785 2786 def generator_sql(self, expression: exp.Generator) -> str: 2787 # Transpile Snowflake GENERATOR to DuckDB range() 2788 rowcount = expression.args.get("rowcount") 2789 time_limit = expression.args.get("time_limit") 2790 2791 if time_limit: 2792 self.unsupported("GENERATOR TIMELIMIT parameter is not supported in DuckDB") 2793 2794 if not rowcount: 2795 self.unsupported("GENERATOR without ROWCOUNT is not supported in DuckDB") 2796 return self.func("range", exp.Literal.number(0)) 2797 2798 return self.func("range", rowcount) 2799 2800 def greatest_sql(self, expression: exp.Greatest) -> str: 2801 return self._greatest_least_sql(expression) 2802 2803 def least_sql(self, expression: exp.Least) -> str: 2804 return self._greatest_least_sql(expression) 2805 2806 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->", wrap: bool = True) -> str: 2807 if self.dialect.version >= (1, 3): 2808 prefix = "LAMBDA " 2809 arrow_sep = ":" 2810 wrap = False 2811 else: 2812 prefix = "" 2813 2814 lambda_sql = super().lambda_sql(expression, arrow_sep=arrow_sep, wrap=wrap) 2815 return f"{prefix}{lambda_sql}" 2816 2817 def show_sql(self, expression: exp.Show) -> str: 2818 from_ = self.sql(expression, "from_") 2819 from_ = f" FROM {from_}" if from_ else "" 2820 return f"SHOW {expression.name}{from_}" 2821 2822 def soundex_sql(self, expression: exp.Soundex) -> str: 2823 self.unsupported("SOUNDEX is not supported in DuckDB") 2824 return self.func("SOUNDEX", expression.this) 2825 2826 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2827 if isinstance(expression.this, exp.Identifier): 2828 return f"${self.sql(expression, 'this')}" 2829 return super().placeholder_sql(expression) 2830 2831 def install_sql(self, expression: exp.Install) -> str: 2832 force = "FORCE " if expression.args.get("force") else "" 2833 this = self.sql(expression, "this") 2834 from_clause = expression.args.get("from_") 2835 from_clause = f" FROM {from_clause}" if from_clause else "" 2836 return f"{force}INSTALL {this}{from_clause}" 2837 2838 def approxtopk_sql(self, expression: exp.ApproxTopK) -> str: 2839 self.unsupported( 2840 "APPROX_TOP_K cannot be transpiled to DuckDB due to incompatible return types. " 2841 ) 2842 return self.function_fallback_sql(expression) 2843 2844 def strposition_sql(self, expression: exp.StrPosition) -> str: 2845 this = expression.this 2846 substr = expression.args["substr"] 2847 position = expression.args.get("position") 2848 clamp_position = expression.args.get("clamp_position") 2849 2850 if clamp_position and position: 2851 position = exp.If( 2852 this=exp.LTE(this=position, expression=exp.Literal.number(0)), 2853 true=exp.Literal.number(1), 2854 false=position.copy(), 2855 ) 2856 2857 # For BINARY/BLOB: DuckDB's STRPOS doesn't support BLOB types 2858 if _is_binary(this): 2859 haystack: exp.Expr = exp.Hex(this=this) 2860 offset: exp.Expr = exp.Literal.number(0) 2861 if position: 2862 # Bound the arithmetic too: DuckDB may fold unreachable CASE branches. 2863 limit = exp.func("COALESCE", exp.ByteLength(this=this), 0) + 1 2864 offset = exp.Least(this=position, expressions=[limit], ignore_nulls=True) - 1 2865 haystack = exp.Substring(this=haystack, start=offset * 2 + 1) 2866 2867 # Match whole bytes, counting a two-character sentinel as the first byte. 2868 prefix = exp.RegexpExtract( 2869 this=exp.DPipe(this=exp.Literal.string("xx"), expression=haystack), 2870 expression=exp.DPipe( 2871 this=exp.Literal.string("^(xx(?:..)*?)"), expression=exp.Hex(this=substr) 2872 ), 2873 group=exp.Literal.number(1), 2874 ) 2875 result: exp.Expr = exp.paren(exp.Length(this=prefix) // 2) 2876 if position: 2877 result = ( 2878 exp.case() 2879 .when( 2880 exp.or_( 2881 this.is_(exp.null()), substr.is_(exp.null()), position.is_(exp.null()) 2882 ), 2883 exp.null(), 2884 ) 2885 .when( 2886 position > exp.func("GREATEST", exp.ByteLength(this=this), 1), 2887 exp.Literal.number(0), 2888 ) 2889 .else_(exp.func("COALESCE", exp.func("NULLIF", result, 0) + offset, 0)) 2890 ) 2891 return self.sql(result) 2892 2893 if clamp_position and position: 2894 expression = expression.copy() 2895 expression.set("position", position) 2896 2897 return strposition_sql(self, expression) 2898 2899 def similarto_sql(self, expression: exp.SimilarTo) -> str: 2900 pattern = expression.expression.unnest() 2901 if ( 2902 pattern.is_string 2903 and not isinstance(expression.parent, exp.Escape) 2904 and _SIMILAR_TO_REGEX_CHARS.isdisjoint(pattern.name) 2905 ): 2906 return self.sql(expression.this.like(pattern)) 2907 2908 self.unsupported("Cannot translate this SIMILAR TO pattern to DuckDB LIKE") 2909 return super().similarto_sql(expression) 2910 2911 def substring_sql(self, expression: exp.Substring) -> str: 2912 if expression.args.get("zero_start"): 2913 start = expression.args.get("start") 2914 length = expression.args.get("length") 2915 2916 if start := expression.args.get("start"): 2917 start = exp.If(this=start.eq(0), true=exp.Literal.number(1), false=start) 2918 if length := expression.args.get("length"): 2919 length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length) 2920 2921 return self.func("SUBSTRING", expression.this, start, length) 2922 2923 return self.function_fallback_sql(expression) 2924 2925 def strtotime_sql(self, expression: exp.StrToTime) -> str: 2926 # Check if target_type requires TIMESTAMPTZ (for LTZ/TZ variants) 2927 target_type = expression.args.get("target_type") 2928 needs_tz = target_type and target_type.this in ( 2929 exp.DType.TIMESTAMPLTZ, 2930 exp.DType.TIMESTAMPTZ, 2931 ) 2932 2933 value, formatted_time = self._strptime_default_year(expression) 2934 2935 if expression.args.get("safe"): 2936 cast_type = exp.DType.TIMESTAMPTZ if needs_tz else exp.DType.TIMESTAMP 2937 return self.sql(exp.cast(self.func("TRY_STRPTIME", value, formatted_time), cast_type)) 2938 2939 base_sql = self.func("STRPTIME", value, formatted_time) 2940 if needs_tz: 2941 return self.sql( 2942 exp.cast( 2943 base_sql, 2944 exp.DataType(this=exp.DType.TIMESTAMPTZ), 2945 ) 2946 ) 2947 return base_sql 2948 2949 def strtodate_sql(self, expression: exp.StrToDate) -> str: 2950 value, formatted_time = self._strptime_default_year(expression) 2951 function_name = "STRPTIME" if not expression.args.get("safe") else "TRY_STRPTIME" 2952 return self.sql( 2953 exp.cast( 2954 self.func(function_name, value, formatted_time), 2955 exp.DataType(this=exp.DType.DATE), 2956 ) 2957 ) 2958 2959 def _strptime_default_year( 2960 self, expression: exp.StrToTime | exp.StrToDate | exp.ParseDatetime 2961 ) -> tuple[exp.ExpOrStr, exp.ExpOrStr | None]: 2962 value: exp.ExpOrStr = expression.this 2963 formatted_time: exp.ExpOrStr | None = self.format_time(expression) 2964 2965 if default_year := expression.args.get("default_year"): 2966 value = exp.DPipe(this=exp.Literal.string(f"{default_year.name} "), expression=value) 2967 formatted_time = exp.DPipe(this=exp.Literal.string("%Y "), expression=formatted_time) 2968 2969 return value, formatted_time 2970 2971 def parsedatetime_sql(self, expression: exp.ParseDatetime) -> str: 2972 value, formatted_time = self._strptime_default_year(expression) 2973 return self.func("STRPTIME", value, formatted_time) 2974 2975 def parsetime_sql(self, expression: exp.ParseTime) -> str: 2976 formatted_time = self.format_time(expression) 2977 return self.sql( 2978 exp.cast( 2979 self.func("STRPTIME", expression.this, formatted_time), 2980 exp.DataType(this=exp.DType.TIME), 2981 ) 2982 ) 2983 2984 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 2985 this = expression.this 2986 time_format = self.format_time(expression) 2987 safe = expression.args.get("safe") 2988 time_type = exp.DataType.from_str("TIME", dialect="duckdb") 2989 cast_expr = exp.TryCast if safe else exp.Cast 2990 2991 if time_format: 2992 func_name = "TRY_STRPTIME" if safe else "STRPTIME" 2993 strptime = exp.Anonymous(this=func_name, expressions=[this, time_format]) 2994 return self.sql(cast_expr(this=strptime, to=time_type)) 2995 2996 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 2997 return self.sql(this) 2998 2999 return self.sql(cast_expr(this=this, to=time_type)) 3000 3001 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3002 if not expression.this: 3003 return "CURRENT_DATE" 3004 3005 expr = exp.Cast( 3006 this=exp.AtTimeZone(this=exp.CurrentTimestamp(), zone=expression.this), 3007 to=exp.DataType(this=exp.DType.DATE), 3008 ) 3009 return self.sql(expr) 3010 3011 def currentdatetime_sql(self, expression: exp.CurrentDatetime) -> str: 3012 zone = expression.this or exp.Literal.string("UTC") 3013 return self.sql( 3014 exp.AtTimeZone(this=exp.CurrentTimestamp(), zone=_normalize_timezone_offset(zone)) 3015 ) 3016 3017 def checkjson_sql(self, expression: exp.CheckJson) -> str: 3018 arg = expression.this 3019 return self.sql( 3020 exp.case() 3021 .when( 3022 exp.or_(arg.is_(exp.Null()), arg.eq(""), exp.func("json_valid", arg)), 3023 exp.null(), 3024 ) 3025 .else_(exp.Literal.string("Invalid JSON")) 3026 ) 3027 3028 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 3029 arg = expression.this 3030 if expression.args.get("safe"): 3031 return self.sql( 3032 exp.case() 3033 .when(exp.func("json_valid", arg), exp.cast(arg.copy(), "JSON")) 3034 .else_(exp.null()) 3035 ) 3036 return self.func("JSON", arg) 3037 3038 def unicode_sql(self, expression: exp.Unicode) -> str: 3039 if expression.args.get("empty_is_null"): 3040 return self.func("NULLIF", self.func("UNICODE", expression.this), "-1") 3041 3042 if expression.args.get("empty_is_zero"): 3043 return self.sql( 3044 exp.case() 3045 .when(expression.this.eq(exp.Literal.string("")), exp.Literal.number(0)) 3046 .else_(exp.Anonymous(this="UNICODE", expressions=[expression.this])) 3047 ) 3048 3049 return self.func("UNICODE", expression.this) 3050 3051 def stripnullvalue_sql(self, expression: exp.StripNullValue) -> str: 3052 return self.sql( 3053 exp.case() 3054 .when(exp.func("json_type", expression.this).eq("NULL"), exp.null()) 3055 .else_(expression.this) 3056 ) 3057 3058 def trunc_sql(self, expression: exp.Trunc) -> str: 3059 decimals = expression.args.get("decimals") 3060 if ( 3061 expression.args.get("fractions_supported") 3062 and decimals 3063 and not decimals.is_type(exp.DType.INT) 3064 ): 3065 decimals = exp.cast(decimals, exp.DType.INT, dialect="duckdb") 3066 3067 return self.func("TRUNC", expression.this, decimals) 3068 3069 def normal_sql(self, expression: exp.Normal) -> str: 3070 """ 3071 Transpile Snowflake's NORMAL(mean, stddev, gen) to DuckDB. 3072 3073 Uses the Box-Muller transform via NORMAL_TEMPLATE. 3074 """ 3075 mean = expression.this 3076 stddev = expression.args["stddev"] 3077 gen: exp.Expr = expression.args["gen"] 3078 3079 # Build two uniform random values [0, 1) for Box-Muller transform 3080 if isinstance(gen, exp.Rand) and gen.this is None: 3081 u1: exp.Expr = exp.Rand() 3082 u2: exp.Expr = exp.Rand() 3083 else: 3084 # Seeded: derive two values using HASH with different inputs 3085 seed = gen.this if isinstance(gen, exp.Rand) else gen 3086 u1 = exp.replace_placeholders(self.SEEDED_RANDOM_TEMPLATE, seed=seed) 3087 u2 = exp.replace_placeholders( 3088 self.SEEDED_RANDOM_TEMPLATE, 3089 seed=exp.Add(this=seed.copy(), expression=exp.Literal.number(1)), 3090 ) 3091 3092 replacements = {"mean": mean, "stddev": stddev, "u1": u1, "u2": u2} 3093 return self.sql(exp.replace_placeholders(self.NORMAL_TEMPLATE, **replacements)) 3094 3095 def uniform_sql(self, expression: exp.Uniform) -> str: 3096 """ 3097 Transpile Snowflake's UNIFORM(min, max, gen) to DuckDB. 3098 3099 UNIFORM returns a random value in [min, max]: 3100 - Integer result if both min and max are integers 3101 - Float result if either min or max is a float 3102 """ 3103 min_val = expression.this 3104 max_val = expression.expression 3105 gen = expression.args.get("gen") or expression.args.get("seed") or exp.Rand() 3106 3107 # Determine if result should be integer (both bounds are integers). 3108 # We do this to emulate Snowflake's behavior, INT -> INT, FLOAT -> FLOAT 3109 is_int_result = min_val.is_int and max_val.is_int 3110 3111 # Build the random value expression [0, 1) 3112 if not isinstance(gen, exp.Rand): 3113 # Seed value: (ABS(HASH(seed)) % 1000000) / 1000000.0 3114 random_expr: exp.Expr = exp.Div( 3115 this=exp.Paren( 3116 this=exp.Mod( 3117 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen])), 3118 expression=exp.Literal.number(1000000), 3119 ) 3120 ), 3121 expression=exp.Literal.number(1000000.0), 3122 ) 3123 else: 3124 random_expr = exp.Rand() 3125 3126 # Build: min + random * (max - min [+ 1 for int]) 3127 range_expr: exp.Expr = exp.Sub(this=max_val, expression=min_val) 3128 if is_int_result: 3129 range_expr = exp.Add(this=range_expr, expression=exp.Literal.number(1)) 3130 3131 result: exp.Expr = exp.Add( 3132 this=min_val, 3133 expression=exp.Mul(this=random_expr, expression=exp.Paren(this=range_expr)), 3134 ) 3135 3136 if is_int_result: 3137 result = exp.Cast(this=exp.Floor(this=result), to=exp.DType.BIGINT.into_expr()) 3138 3139 return self.sql(result) 3140 3141 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 3142 nano = expression.args.get("nano") 3143 overflow = expression.args.get("overflow") 3144 3145 # Snowflake's TIME_FROM_PARTS supports overflow 3146 if overflow: 3147 hour = expression.args["hour"] 3148 minute = expression.args["min"] 3149 sec = expression.args["sec"] 3150 3151 # Check if values are within normal ranges - use MAKE_TIME for efficiency 3152 if not nano and all(arg.is_int for arg in [hour, minute, sec]): 3153 try: 3154 h_val = hour.to_py() 3155 m_val = minute.to_py() 3156 s_val = sec.to_py() 3157 if 0 <= h_val <= 23 and 0 <= m_val <= 59 and 0 <= s_val <= 59: 3158 return rename_func("MAKE_TIME")(self, expression) 3159 except ValueError: 3160 pass 3161 3162 # Overflow or nanoseconds detected - use INTERVAL arithmetic 3163 if nano: 3164 sec = sec + nano.pop() / exp.Literal.number(1000000000.0) 3165 3166 total_seconds = hour * exp.Literal.number(3600) + minute * exp.Literal.number(60) + sec 3167 3168 return self.sql( 3169 exp.Add( 3170 this=exp.Cast( 3171 this=exp.Literal.string("00:00:00"), to=exp.DType.TIME.into_expr() 3172 ), 3173 expression=exp.Interval(this=total_seconds, unit=exp.var("SECOND")), 3174 ) 3175 ) 3176 3177 # Default: MAKE_TIME 3178 if nano: 3179 expression.set( 3180 "sec", expression.args["sec"] + nano.pop() / exp.Literal.number(1000000000.0) 3181 ) 3182 3183 return rename_func("MAKE_TIME")(self, expression) 3184 3185 def extract_sql(self, expression: exp.Extract) -> str: 3186 """ 3187 Transpile EXTRACT/DATE_PART for DuckDB, handling specifiers not natively supported. 3188 3189 DuckDB doesn't support: WEEKISO, YEAROFWEEK, YEAROFWEEKISO, NANOSECOND, 3190 EPOCH_SECOND (as integer), EPOCH_MILLISECOND, EPOCH_MICROSECOND, EPOCH_NANOSECOND 3191 """ 3192 this = expression.this 3193 datetime_expr = expression.expression 3194 3195 # TIMESTAMPTZ extractions may produce different results between Snowflake and DuckDB 3196 # because Snowflake applies server timezone while DuckDB uses local timezone 3197 if datetime_expr.is_type(exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ): 3198 self.unsupported( 3199 "EXTRACT from TIMESTAMPTZ / TIMESTAMPLTZ may produce different results due to timezone handling differences" 3200 ) 3201 3202 part_name = this.name.upper() 3203 3204 if part_name in self.EXTRACT_STRFTIME_MAPPINGS: 3205 fmt, cast_type = self.EXTRACT_STRFTIME_MAPPINGS[part_name] 3206 3207 # Problem: strftime doesn't accept TIME and there's no NANOSECOND function 3208 # So, for NANOSECOND with TIME, fallback to MICROSECOND * 1000 3209 is_nano_time = part_name == "NANOSECOND" and datetime_expr.is_type( 3210 exp.DType.TIME, exp.DType.TIMETZ 3211 ) 3212 3213 if is_nano_time: 3214 self.unsupported("Parameter NANOSECOND is not supported with TIME type in DuckDB") 3215 return self.sql( 3216 exp.cast( 3217 exp.Mul( 3218 this=exp.Extract(this=exp.var("MICROSECOND"), expression=datetime_expr), 3219 expression=exp.Literal.number(1000), 3220 ), 3221 exp.DataType.from_str(cast_type, dialect="duckdb"), 3222 ) 3223 ) 3224 3225 # For NANOSECOND, cast to TIMESTAMP_NS to preserve nanosecond precision 3226 strftime_input = datetime_expr 3227 if part_name == "NANOSECOND": 3228 strftime_input = exp.cast(datetime_expr, exp.DType.TIMESTAMP_NS) 3229 3230 return self.sql( 3231 exp.cast( 3232 exp.Anonymous( 3233 this="STRFTIME", 3234 expressions=[strftime_input, exp.Literal.string(fmt)], 3235 ), 3236 exp.DataType.from_str(cast_type, dialect="duckdb"), 3237 ) 3238 ) 3239 3240 if part_name in self.EXTRACT_EPOCH_MAPPINGS: 3241 func_name = self.EXTRACT_EPOCH_MAPPINGS[part_name] 3242 result: exp.Expr = exp.Anonymous(this=func_name, expressions=[datetime_expr]) 3243 # EPOCH returns float, cast to BIGINT for integer result 3244 if part_name == "EPOCH_SECOND": 3245 result = exp.cast(result, exp.DataType.from_str("BIGINT", dialect="duckdb")) 3246 return self.sql(result) 3247 3248 return super().extract_sql(expression) 3249 3250 def timestamp_sql(self, expression: exp.Timestamp) -> str: 3251 zone = expression.args.get("zone") 3252 if expression.args.get("with_tz") and zone: 3253 return self.sql( 3254 exp.AtTimeZone( 3255 this=exp.cast(expression.this, exp.DType.TIMESTAMP), 3256 zone=_normalize_timezone_offset(zone), 3257 ) 3258 ) 3259 return no_timestamp_sql(self, expression) 3260 3261 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 3262 # Check if this is the date/time expression form: TIMESTAMP_FROM_PARTS(date_expr, time_expr) 3263 date_expr = expression.this 3264 time_expr = expression.expression 3265 3266 if date_expr is not None and time_expr is not None: 3267 # In DuckDB, DATE + TIME produces TIMESTAMP 3268 return self.sql(exp.Add(this=date_expr, expression=time_expr)) 3269 3270 # Component-based form: TIMESTAMP_FROM_PARTS(year, month, day, hour, minute, second, ...) 3271 sec = expression.args.get("sec") 3272 if sec is None: 3273 # This shouldn't happen with valid input, but handle gracefully 3274 return rename_func("MAKE_TIMESTAMP")(self, expression) 3275 3276 milli = expression.args.get("milli") 3277 if milli is not None: 3278 sec += milli.pop() / exp.Literal.number(1000.0) 3279 3280 nano = expression.args.get("nano") 3281 if nano is not None: 3282 sec += nano.pop() / exp.Literal.number(1000000000.0) 3283 3284 if milli or nano: 3285 expression.set("sec", sec) 3286 3287 if zone := expression.args.get("zone"): 3288 return self.sql(exp.AtTimeZone(this=expression, zone=zone.pop())) 3289 3290 return rename_func("MAKE_TIMESTAMP")(self, expression) 3291 3292 @unsupported_args("nano") 3293 def timestampltzfromparts_sql(self, expression: exp.TimestampLtzFromParts) -> str: 3294 # Pop nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3295 if nano := expression.args.get("nano"): 3296 nano.pop() 3297 3298 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3299 return f"CAST({timestamp} AS TIMESTAMPTZ)" 3300 3301 @unsupported_args("nano") 3302 def timestamptzfromparts_sql(self, expression: exp.TimestampTzFromParts) -> str: 3303 # Extract zone before popping 3304 zone = expression.args.get("zone") 3305 # Pop zone and nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3306 if zone: 3307 zone = zone.pop() 3308 3309 if nano := expression.args.get("nano"): 3310 nano.pop() 3311 3312 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3313 3314 if zone: 3315 # Use AT TIME ZONE to apply the explicit timezone 3316 return f"{timestamp} AT TIME ZONE {self.sql(zone)}" 3317 3318 return timestamp 3319 3320 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 3321 locks = self.expressions(expression, key="locks", sep=" ") 3322 return [f" {locks}" if locks else ""] 3323 3324 def tablesample_sql( 3325 self, 3326 expression: exp.TableSample, 3327 tablesample_keyword: str | None = None, 3328 ) -> str: 3329 if not isinstance(expression.parent, exp.Select): 3330 # This sample clause only applies to a single source, not the entire resulting relation 3331 tablesample_keyword = "TABLESAMPLE" 3332 3333 if expression.args.get("size"): 3334 method = expression.args.get("method") 3335 if method and method.name.upper() != "RESERVOIR": 3336 self.unsupported( 3337 f"Sampling method {method} is not supported with a discrete sample count, " 3338 "defaulting to reservoir sampling" 3339 ) 3340 expression.set("method", exp.var("RESERVOIR")) 3341 3342 return super().tablesample_sql(expression, tablesample_keyword=tablesample_keyword) 3343 3344 def in_sql(self, expression: exp.In) -> str: 3345 unnest = expression.args.get("unnest") 3346 if unnest: 3347 return self.sql( 3348 exp.replace_placeholders( 3349 self.IN_UNNEST_TEMPLATE, arr=unnest.expressions[0], value=expression.this 3350 ) 3351 ) 3352 return super().in_sql(expression) 3353 3354 def interval_sql(self, expression: exp.Interval) -> str: 3355 # DuckDB truncates INTERVAL '1.5' DAY to 1 day, but keeps the fraction in INTERVAL '1.5 DAY' 3356 this = expression.this 3357 unit = expression.unit 3358 if expression.args.get("fraction_in_string") and this and isinstance(unit, exp.Var): 3359 return f"INTERVAL '{this.name} {self.sql(unit)}'" 3360 3361 return super().interval_sql(expression) 3362 3363 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3364 if expression.kind in ("MARK", "SINGLE") or ( 3365 expression.side == "RIGHT" and expression.is_semi_or_anti_join 3366 ): 3367 kind = "_".join(part for part in (expression.side, expression.kind) if part) 3368 return super().join_sql(expression, join_op=f"JOIN BY (TYPE {kind})") 3369 3370 if ( 3371 not expression.args.get("using") 3372 and not expression.args.get("on") 3373 and not expression.args.get("nearest") 3374 and not expression.method 3375 and (expression.kind in ("", "INNER", "OUTER")) 3376 ): 3377 # Some dialects support `LEFT/INNER JOIN UNNEST(...)` without an explicit ON clause 3378 # DuckDB doesn't, but we can just add a dummy ON clause that is always true 3379 if isinstance(expression.this, exp.Unnest): 3380 return super().join_sql(expression.on(exp.true())) 3381 3382 expression.set("side", None) 3383 expression.set("kind", None) 3384 3385 return super().join_sql(expression, join_op=join_op) 3386 3387 def countif_sql(self, expression: exp.CountIf) -> str: 3388 if self.dialect.version >= (1, 2): 3389 this = expression.this 3390 if expression.args.get("zero_on_all_null") and not isinstance(this, exp.Distinct): 3391 # DuckDB >= 1.2's COUNT_IF returns NULL when the condition is NULL on all rows, 3392 # so we wrap the condition in IS TRUE to preserve count-like semantics 3393 expression = exp.CountIf(this=exp.paren(this).is_(exp.true())) 3394 return self.function_fallback_sql(expression) 3395 3396 # https://github.com/tobymao/sqlglot/pull/4749 3397 return count_if_to_sum(self, expression) 3398 3399 def bracket_sql(self, expression: exp.Bracket) -> str: 3400 if self.dialect.version >= (1, 2): 3401 return super().bracket_sql(expression) 3402 3403 # https://duckdb.org/2025/02/05/announcing-duckdb-120.html#breaking-changes 3404 this = expression.this 3405 if isinstance(this, exp.Array): 3406 this.replace(exp.paren(this)) 3407 3408 bracket = super().bracket_sql(expression) 3409 3410 if not expression.args.get("returns_list_for_maps"): 3411 if not this.type: 3412 from sqlglot.optimizer.annotate_types import annotate_types 3413 3414 this = annotate_types(this, dialect=self.dialect) 3415 3416 if this.is_type(exp.DType.MAP): 3417 bracket = f"({bracket})[1]" 3418 3419 return bracket 3420 3421 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 3422 func = expression.this 3423 3424 # For ARRAY_AGG, DuckDB requires ORDER BY inside the function, not in WITHIN GROUP 3425 # Transform: ARRAY_AGG(x) WITHIN GROUP (ORDER BY y) -> ARRAY_AGG(x ORDER BY y) 3426 if isinstance(func, exp.ArrayAgg): 3427 if not isinstance(order := expression.expression, exp.Order): 3428 return self.sql(func) 3429 3430 # Save the original column for FILTER clause (before wrapping with Order) 3431 original_this = func.this 3432 3433 # Move ORDER BY inside ARRAY_AGG by wrapping its argument with Order 3434 # ArrayAgg.this should become Order(this=ArrayAgg.this, expressions=order.expressions) 3435 func.set( 3436 "this", 3437 exp.Order( 3438 this=func.this.copy(), 3439 expressions=order.expressions, 3440 ), 3441 ) 3442 3443 # Generate the ARRAY_AGG function with ORDER BY and add FILTER clause if needed 3444 # Use original_this (not the Order-wrapped version) for the FILTER condition 3445 array_agg_sql = self.function_fallback_sql(func) 3446 return self._add_arrayagg_null_filter(array_agg_sql, func, original_this) 3447 3448 # For other functions (like PERCENTILES), use existing logic 3449 expression_sql = self.sql(expression, "expression") 3450 3451 if isinstance(func, exp.PERCENTILES): 3452 # Make the order key the first arg and slide the fraction to the right 3453 # https://duckdb.org/docs/sql/aggregates#ordered-set-aggregate-functions 3454 order_col = expression.find(exp.Ordered) 3455 if order_col: 3456 func.set("expression", func.this) 3457 func.set("this", order_col.this) 3458 3459 this = self.sql(expression, "this").removesuffix(")") 3460 3461 return f"{this}{expression_sql})" 3462 3463 def length_sql(self, expression: exp.Length) -> str: 3464 arg = expression.this 3465 3466 def text_arg(value: exp.Expr) -> exp.Expr: 3467 if expression.args.get("null_terminated"): 3468 return exp.SplitPart( 3469 this=value.copy(), 3470 delimiter=exp.Chr(expressions=[exp.Literal.number(0)]), 3471 part_index=exp.Literal.number(1), 3472 ) 3473 return value 3474 3475 # SQLite, BQ and Snowflake also accept binary values as args, so 3476 # DDB will attempt to infer the type or resort to case/when resolution 3477 if ( 3478 not (expression.args.get("binary") or expression.args.get("null_terminated")) 3479 or arg.is_string 3480 ): 3481 return self.func("LENGTH", text_arg(arg)) 3482 3483 if not arg.type: 3484 from sqlglot.optimizer.annotate_types import annotate_types 3485 3486 arg = annotate_types(arg, dialect=self.dialect) 3487 3488 if arg.is_type(*exp.DataType.TEXT_TYPES): 3489 return self.func("LENGTH", text_arg(arg)) 3490 3491 # We need these casts to make duckdb's static type checker happy 3492 blob = exp.cast(arg, exp.DType.VARBINARY) 3493 varchar = exp.cast(arg, exp.DType.VARCHAR) 3494 3495 case = ( 3496 exp.case(exp.Typeof(this=arg.copy())) 3497 .when(exp.Literal.string("BLOB"), exp.ByteLength(this=blob)) 3498 .else_(exp.Length(this=text_arg(varchar))) 3499 ) 3500 return self.sql(case) 3501 3502 def bitlength_sql(self, expression: exp.BitLength) -> str: 3503 if not _is_binary(arg := expression.this): 3504 return self.func("BIT_LENGTH", arg) 3505 3506 blob = exp.cast(arg, exp.DataType.Type.VARBINARY) 3507 return self.sql(exp.ByteLength(this=blob) * exp.Literal.number(8)) 3508 3509 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 3510 if len(expression.expressions) > 1: 3511 return super().chr_sql(expression, name) 3512 3513 arg = expression.expressions[0] 3514 if arg.is_type(*exp.DataType.REAL_TYPES): 3515 arg = exp.cast(arg, exp.DType.INT) 3516 return self.func("CHR", arg) 3517 3518 def collation_sql(self, expression: exp.Collation) -> str: 3519 self.unsupported("COLLATION function is not supported by DuckDB") 3520 return self.function_fallback_sql(expression) 3521 3522 def collate_sql(self, expression: exp.Collate) -> str: 3523 if not expression.expression.is_string: 3524 return super().collate_sql(expression) 3525 3526 raw = expression.expression.name 3527 if not raw: 3528 return self.sql(expression.this) 3529 3530 parts = [] 3531 for part in raw.split("-"): 3532 lower = part.lower() 3533 if lower not in _SNOWFLAKE_COLLATION_DEFAULTS: 3534 if lower in _SNOWFLAKE_COLLATION_UNSUPPORTED: 3535 self.unsupported( 3536 f"Snowflake collation specifier '{part}' has no DuckDB equivalent" 3537 ) 3538 parts.append(lower) 3539 3540 if not parts: 3541 return self.sql(expression.this) 3542 return super().collate_sql( 3543 exp.Collate(this=expression.this, expression=exp.var(".".join(parts))) 3544 ) 3545 3546 def _validate_regexp_flags(self, flags: exp.Expr | None, supported_flags: str) -> str | None: 3547 """ 3548 Validate and filter regexp flags for DuckDB compatibility. 3549 3550 Args: 3551 flags: The flags expression to validate 3552 supported_flags: String of supported flags (e.g., "ims", "cims"). 3553 Only these flags will be returned. 3554 3555 Returns: 3556 Validated/filtered flag string, or None if no valid flags remain 3557 """ 3558 if not isinstance(flags, exp.Expr): 3559 return None 3560 3561 if not flags.is_string: 3562 self.unsupported("Non-literal regexp flags are not fully supported in DuckDB") 3563 return None 3564 3565 flag_str = flags.this 3566 unsupported = set(flag_str) - set(supported_flags) 3567 3568 if unsupported: 3569 self.unsupported( 3570 f"Regexp flags {sorted(unsupported)} are not supported in this context" 3571 ) 3572 3573 flag_str = "".join(f for f in flag_str if f in supported_flags) 3574 return flag_str if flag_str else None 3575 3576 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 3577 this = expression.this 3578 pattern = expression.expression 3579 position = expression.args.get("position") 3580 parameters = expression.args.get("parameters") 3581 3582 # Validate flags - only "ims" flags are supported for embedded patterns 3583 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 3584 3585 if position: 3586 this = exp.Substring(this=this, start=position) 3587 3588 # Handle empty pattern: Snowflake returns 0, DuckDB would match between every character. 3589 # Checked before the flags are embedded, which would make the pattern non-empty 3590 is_empty = exp.EQ(this=pattern.copy(), expression=exp.Literal.string("")) 3591 3592 # Embed flags in pattern (REGEXP_EXTRACT_ALL doesn't support flags argument) 3593 if validated_flags: 3594 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 3595 3596 result = ( 3597 exp.case() 3598 .when(is_empty, exp.Literal.number(0)) 3599 .else_( 3600 exp.Length( 3601 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 3602 ) 3603 ) 3604 ) 3605 3606 return self.sql(result) 3607 3608 def regexpreplace_sql(self, expression: exp.RegexpReplace) -> str: 3609 subject = expression.this 3610 pattern = expression.expression 3611 replacement = expression.args.get("replacement") or exp.Literal.string("") 3612 position = expression.args.get("position") 3613 occurrence = expression.args.get("occurrence") 3614 modifiers = expression.args.get("modifiers") 3615 3616 validated_flags = self._validate_regexp_flags(modifiers, supported_flags="cimsg") or "" 3617 3618 # Handle occurrence (only literals supported) 3619 if occurrence and not occurrence.is_int: 3620 self.unsupported("REGEXP_REPLACE with non-literal occurrence") 3621 else: 3622 occurrence = occurrence.to_py() if occurrence and occurrence.is_int else 0 3623 if occurrence > 1: 3624 self.unsupported(f"REGEXP_REPLACE occurrence={occurrence} not supported") 3625 # flag duckdb to do either all or none, single_replace check is for duckdb round trip 3626 elif ( 3627 occurrence == 0 3628 and "g" not in validated_flags 3629 and not expression.args.get("single_replace") 3630 ): 3631 validated_flags += "g" 3632 3633 # Handle position (only literals supported) 3634 prefix = None 3635 if position and not position.is_int: 3636 self.unsupported("REGEXP_REPLACE with non-literal position") 3637 elif position and position.is_int and position.to_py() > 1: 3638 pos = position.to_py() 3639 prefix = exp.Substring( 3640 this=subject, start=exp.Literal.number(1), length=exp.Literal.number(pos - 1) 3641 ) 3642 subject = exp.Substring(this=subject, start=exp.Literal.number(pos)) 3643 3644 result: exp.Expr = exp.Anonymous( 3645 this="REGEXP_REPLACE", 3646 expressions=[ 3647 subject, 3648 pattern, 3649 replacement, 3650 exp.Literal.string(validated_flags) if validated_flags else None, 3651 ], 3652 ) 3653 3654 if prefix: 3655 result = exp.Concat(expressions=[prefix, result]) 3656 3657 return self.sql(result) 3658 3659 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 3660 this = expression.this 3661 pattern = expression.expression 3662 flag = expression.args.get("flag") 3663 3664 if expression.args.get("full_match"): 3665 validated_flags = self._validate_regexp_flags(flag, supported_flags="cims") 3666 flag = exp.Literal.string(validated_flags) if validated_flags else None 3667 return self.func("REGEXP_FULL_MATCH", this, pattern, flag) 3668 3669 return self.func("REGEXP_MATCHES", this, pattern, flag) 3670 3671 @unsupported_args("ins_cost", "del_cost", "sub_cost") 3672 def levenshtein_sql(self, expression: exp.Levenshtein) -> str: 3673 this = expression.this 3674 expr = expression.expression 3675 max_dist = expression.args.get("max_dist") 3676 3677 if max_dist is None: 3678 return self.func("LEVENSHTEIN", this, expr) 3679 3680 # Emulate Snowflake semantics: if distance > max_dist, return max_dist 3681 levenshtein = exp.Levenshtein(this=this, expression=expr) 3682 return self.sql(exp.Least(this=levenshtein, expressions=[max_dist])) 3683 3684 def pad_sql(self, expression: exp.Pad) -> str: 3685 """ 3686 Handle RPAD/LPAD for VARCHAR and BINARY types. 3687 3688 For VARCHAR: Delegate to parent class 3689 For BINARY: Lower to: input || REPEAT(pad, GREATEST(0, target_len - OCTET_LENGTH(input))) 3690 """ 3691 string_arg = expression.this 3692 fill_arg = expression.args.get("fill_pattern") or exp.Literal.string(" ") 3693 3694 if _is_binary(string_arg) or _is_binary(fill_arg): 3695 length_arg = expression.expression 3696 is_left = expression.args.get("is_left") 3697 3698 input_len = exp.ByteLength(this=string_arg) 3699 chars_needed = length_arg - input_len 3700 pad_count = exp.Greatest( 3701 this=exp.Literal.number(0), expressions=[chars_needed], ignore_nulls=True 3702 ) 3703 repeat_expr = exp.Repeat(this=fill_arg, times=pad_count) 3704 3705 left, right = string_arg, repeat_expr 3706 if is_left: 3707 left, right = right, left 3708 3709 result = exp.DPipe(this=left, expression=right) 3710 return self.sql(result) 3711 3712 # For VARCHAR: Delegate to parent class (handles PAD_FILL_PATTERN_IS_REQUIRED) 3713 return super().pad_sql(expression) 3714 3715 def minhash_sql(self, expression: exp.Minhash) -> str: 3716 k = expression.this 3717 exprs = expression.expressions 3718 3719 if len(exprs) != 1 or isinstance(exprs[0], exp.Star): 3720 self.unsupported( 3721 "MINHASH with multiple expressions or * requires manual query restructuring" 3722 ) 3723 return self.func("MINHASH", k, *exprs) 3724 3725 expr = exprs[0] 3726 result = exp.replace_placeholders(self.MINHASH_TEMPLATE.copy(), expr=expr, k=k) 3727 return f"({self.sql(result)})" 3728 3729 def minhashcombine_sql(self, expression: exp.MinhashCombine) -> str: 3730 expr = expression.this 3731 result = exp.replace_placeholders(self.MINHASH_COMBINE_TEMPLATE.copy(), expr=expr) 3732 return f"({self.sql(result)})" 3733 3734 def approximatesimilarity_sql(self, expression: exp.ApproximateSimilarity) -> str: 3735 expr = expression.this 3736 result = exp.replace_placeholders(self.APPROXIMATE_SIMILARITY_TEMPLATE.copy(), expr=expr) 3737 return f"({self.sql(result)})" 3738 3739 def arrayall_sql(self, expression: exp.ArrayAll) -> str: 3740 return self.func( 3741 "LIST_REDUCE", 3742 exp.Transform(this=expression.this, expression=expression.expression), 3743 exp.Lambda( 3744 this=exp.and_(exp.to_identifier("_a"), exp.to_identifier("_b")), 3745 expressions=[exp.to_identifier("_a"), exp.to_identifier("_b")], 3746 ), 3747 exp.true(), 3748 ) 3749 3750 def arrayuniqueagg_sql(self, expression: exp.ArrayUniqueAgg) -> str: 3751 return self.sql( 3752 exp.Filter( 3753 this=exp.func("LIST", exp.Distinct(expressions=[expression.this])), 3754 expression=exp.Where(this=expression.this.copy().is_(exp.null()).not_()), 3755 ) 3756 ) 3757 3758 def arrayconcatagg_sql(self, expression: exp.ArrayConcatAgg) -> str: 3759 this = expression.this 3760 3761 if isinstance(this, exp.Limit): 3762 self.unsupported("LIMIT in ARRAY_CONCAT_AGG cannot be transpiled to DuckDB") 3763 this = this.this 3764 3765 inner = this.this if isinstance(this, exp.Order) else this 3766 3767 return self.func( 3768 "FLATTEN", 3769 exp.Filter( 3770 this=exp.ArrayAgg(this=this), 3771 expression=exp.Where(this=inner.copy().is_(exp.null()).not_()), 3772 ), 3773 ) 3774 3775 def arrayunionagg_sql(self, expression: exp.ArrayUnionAgg) -> str: 3776 self.unsupported("ARRAY_UNION_AGG is not supported in DuckDB") 3777 return self.function_fallback_sql(expression) 3778 3779 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 3780 arr = expression.this 3781 func = self.func("LIST_DISTINCT", arr) 3782 3783 if expression.args.get("check_null"): 3784 add_null_to_array = exp.func( 3785 "LIST_APPEND", exp.func("LIST_DISTINCT", exp.ArrayCompact(this=arr)), exp.Null() 3786 ) 3787 return self.sql( 3788 exp.If( 3789 this=exp.NEQ( 3790 this=exp.ArraySize(this=arr), expression=exp.func("LIST_COUNT", arr) 3791 ), 3792 true=add_null_to_array, 3793 false=func, 3794 ) 3795 ) 3796 3797 return func 3798 3799 def arrayintersect_sql(self, expression: exp.ArrayIntersect) -> str: 3800 if expression.args.get("is_multiset") and len(expression.expressions) == 2: 3801 return self._array_bag_sql( 3802 self.ARRAY_INTERSECTION_CONDITION, 3803 expression.expressions[0], 3804 expression.expressions[1], 3805 ) 3806 return self.function_fallback_sql(expression) 3807 3808 def arrayexcept_sql(self, expression: exp.ArrayExcept) -> str: 3809 arr1, arr2 = expression.this, expression.expression 3810 if expression.args.get("is_multiset"): 3811 return self._array_bag_sql(self.ARRAY_EXCEPT_CONDITION, arr1, arr2) 3812 return self.sql( 3813 exp.replace_placeholders(self.ARRAY_EXCEPT_SET_TEMPLATE, arr1=arr1, arr2=arr2) 3814 ) 3815 3816 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 3817 separator = expression.args.get("separator") 3818 if ( 3819 expression.args.get("null_separator_is_empty") 3820 and separator is not None 3821 and not separator.is_string 3822 ): 3823 expression.set( 3824 "separator", exp.Coalesce(this=separator, expressions=[exp.Literal.string("")]) 3825 ) 3826 return groupconcat_sql(self, expression, within_group=False) 3827 3828 def arrayslice_sql(self, expression: exp.ArraySlice) -> str: 3829 """ 3830 Spark's SLICE uses a length, so normalize negative starts before computing 3831 the inclusive end index. Starts before the array produce an empty slice. 3832 3833 Transpiles Snowflake's ARRAY_SLICE (0-indexed, exclusive end) to DuckDB's 3834 ARRAY_SLICE (1-indexed, inclusive end) by wrapping start and end in CASE 3835 expressions that adjust the index at query time: 3836 - start: CASE WHEN start >= 0 THEN start + 1 ELSE start END 3837 - end: CASE WHEN end < 0 THEN end - 1 ELSE end END 3838 """ 3839 start, end = expression.args.get("start"), expression.args.get("end") 3840 3841 if expression.args.get("zero_based"): 3842 if start is not None: 3843 start = ( 3844 exp.case() 3845 .when( 3846 exp.GTE(this=start.copy(), expression=exp.Literal.number(0)), 3847 exp.Add(this=start.copy(), expression=exp.Literal.number(1)), 3848 ) 3849 .else_(start) 3850 ) 3851 if end is not None and not expression.args.get("is_length"): 3852 end = ( 3853 exp.case() 3854 .when( 3855 exp.LT(this=end.copy(), expression=exp.Literal.number(0)), 3856 exp.Sub(this=end.copy(), expression=exp.Literal.number(1)), 3857 ) 3858 .else_(end) 3859 ) 3860 3861 if expression.args.get("is_length") and start is not None and end is not None: 3862 if not start.is_int or start.to_py() < 0: 3863 size = exp.ArraySize(this=expression.this.copy()) 3864 start = ( 3865 exp.case() 3866 .when(start < -size, size + 1) 3867 .when(start < 0, size + start + 1) 3868 .else_(start) 3869 ) 3870 3871 if start.is_int and end.is_int: 3872 end = exp.Literal.number(start.to_py() + end.to_py() - 1) 3873 else: 3874 end = start + exp.cast(end, "BIGINT") - 1 3875 return self.func("ARRAY_SLICE", expression.this, start, end, expression.args.get("step")) 3876 3877 def arrayszip_sql(self, expression: exp.ArraysZip) -> str: 3878 args = expression.expressions 3879 3880 if not args: 3881 # Return [{}] - using MAP([], []) since DuckDB can't represent empty structs 3882 return self.sql(exp.array(exp.Map(keys=exp.array(), values=exp.array()))) 3883 3884 # Build placeholder values for template 3885 lengths = [exp.Length(this=arg) for arg in args] 3886 max_len = ( 3887 lengths[0] 3888 if len(lengths) == 1 3889 else exp.Greatest(this=lengths[0], expressions=lengths[1:]) 3890 ) 3891 3892 # Empty struct with same schema: {'$1': NULL, '$2': NULL, ...} 3893 empty_struct = exp.func( 3894 "STRUCT", 3895 *[ 3896 exp.PropertyEQ(this=exp.Literal.string(f"${i + 1}"), expression=exp.Null()) 3897 for i in range(len(args)) 3898 ], 3899 ) 3900 3901 # Struct for transform: {'$1': COALESCE(arr1, [])[__i + 1], ...} 3902 # COALESCE wrapping handles NULL arrays - prevents invalid NULL[i] syntax 3903 index = exp.column("__i") + 1 3904 transform_struct = exp.func( 3905 "STRUCT", 3906 *[ 3907 exp.PropertyEQ( 3908 this=exp.Literal.string(f"${i + 1}"), 3909 expression=exp.func("COALESCE", arg, exp.array())[index], 3910 ) 3911 for i, arg in enumerate(args) 3912 ], 3913 ) 3914 3915 result = exp.replace_placeholders( 3916 self.ARRAYS_ZIP_TEMPLATE.copy(), 3917 null_check=exp.or_(*[arg.is_(exp.Null()) for arg in args]), 3918 all_empty_check=exp.and_( 3919 *[ 3920 exp.EQ(this=exp.Length(this=arg), expression=exp.Literal.number(0)) 3921 for arg in args 3922 ] 3923 ), 3924 empty_struct=empty_struct, 3925 max_len=max_len, 3926 transform_struct=transform_struct, 3927 ) 3928 return self.sql(result) 3929 3930 def lower_sql(self, expression: exp.Lower) -> str: 3931 result_sql = self.func("LOWER", _cast_to_varchar(expression.this)) 3932 return _gen_with_cast_to_blob(self, expression, result_sql) 3933 3934 def upper_sql(self, expression: exp.Upper) -> str: 3935 result_sql = self.func("UPPER", _cast_to_varchar(expression.this)) 3936 return _gen_with_cast_to_blob(self, expression, result_sql) 3937 3938 def reverse_sql(self, expression: exp.Reverse) -> str: 3939 result_sql = self.func("REVERSE", _cast_to_varchar(expression.this)) 3940 return _gen_with_cast_to_blob(self, expression, result_sql) 3941 3942 def _left_right_sql(self, expression: exp.Left | exp.Right, func_name: str) -> str: 3943 arg = expression.this 3944 length = expression.expression 3945 is_binary = _is_binary(arg) 3946 3947 if expression.args.get("negative_length_returns_empty"): 3948 # A negative length returns an empty string. Clamping it to 0 instead of 3949 # returning '' directly keeps the result NULL when the input is NULL. 3950 length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length) 3951 3952 if is_binary: 3953 # LEFT/RIGHT(blob, n) becomes UNHEX(LEFT/RIGHT(HEX(blob), n * 2)) 3954 # Each byte becomes 2 hex chars, so multiply length by 2 3955 hex_arg = exp.Hex(this=arg) 3956 hex_length = exp.Mul(this=length, expression=exp.Literal.number(2)) 3957 result: exp.Expression = exp.Unhex( 3958 this=exp.Anonymous(this=func_name, expressions=[hex_arg, hex_length]) 3959 ) 3960 else: 3961 result = exp.Anonymous(this=func_name, expressions=[arg, length]) 3962 3963 return self.sql(result) 3964 3965 def left_sql(self, expression: exp.Left) -> str: 3966 return self._left_right_sql(expression, "LEFT") 3967 3968 def right_sql(self, expression: exp.Right) -> str: 3969 return self._left_right_sql(expression, "RIGHT") 3970 3971 def rtrimmedlength_sql(self, expression: exp.RtrimmedLength) -> str: 3972 return self.func("LENGTH", exp.Trim(this=expression.this, position="TRAILING")) 3973 3974 def stuff_sql(self, expression: exp.Stuff) -> str: 3975 base = expression.this 3976 start = expression.args["start"] 3977 length = expression.args["length"] 3978 insertion = expression.expression 3979 is_binary = _is_binary(base) 3980 3981 if is_binary: 3982 # DuckDB's SUBSTRING doesn't accept BLOB; operate on the HEX string instead 3983 # (each byte = 2 hex chars), then UNHEX back to BLOB 3984 base = exp.Hex(this=base) 3985 insertion = exp.Hex(this=insertion) 3986 left = exp.Substring( 3987 this=base.copy(), 3988 start=exp.Literal.number(1), 3989 length=(start.copy() - exp.Literal.number(1)) * exp.Literal.number(2), 3990 ) 3991 right = exp.Substring( 3992 this=base.copy(), 3993 start=((start + length) - exp.Literal.number(1)) * exp.Literal.number(2) 3994 + exp.Literal.number(1), 3995 ) 3996 else: 3997 left = exp.Substring( 3998 this=base.copy(), 3999 start=exp.Literal.number(1), 4000 length=start.copy() - exp.Literal.number(1), 4001 ) 4002 right = exp.Substring(this=base.copy(), start=start + length) 4003 result: exp.Expr = exp.DPipe( 4004 this=exp.DPipe(this=left, expression=insertion), expression=right 4005 ) 4006 4007 if is_binary: 4008 result = exp.Unhex(this=result) 4009 4010 return self.sql(result) 4011 4012 def rand_sql(self, expression: exp.Rand) -> str: 4013 seed = expression.this 4014 if seed is not None: 4015 self.unsupported("RANDOM with seed is not supported in DuckDB") 4016 4017 lower = expression.args.get("lower") 4018 upper = expression.args.get("upper") 4019 4020 if lower and upper: 4021 # Build 64 random bits in integer arithmetic to preserve the low bits and 4022 # avoid overflow when the inclusive range spans signed BIGINT's limits. 4023 random_bits = exp.cast(exp.Floor(this=exp.Rand() * (1 << 32)), exp.DType.INT128) 4024 random = random_bits * (1 << 32) + random_bits.copy() 4025 lower = exp.cast(lower, exp.DType.INT128) 4026 upper = exp.cast(upper, exp.DType.INT128) 4027 return self.sql(exp.cast(random % (upper - lower + 1) + lower, exp.DType.BIGINT)) 4028 4029 # Default DuckDB behavior - just return RANDOM() as float 4030 return "RANDOM()" 4031 4032 def bytelength_sql(self, expression: exp.ByteLength) -> str: 4033 arg = expression.this 4034 4035 # Check if it's a text type (handles both literals and annotated expressions) 4036 if arg.is_type(*exp.DataType.TEXT_TYPES): 4037 return self.func("OCTET_LENGTH", exp.Encode(this=arg)) 4038 4039 # Default: pass through as-is (conservative for DuckDB, handles binary and unannotated) 4040 return self.func("OCTET_LENGTH", arg) 4041 4042 def base64encode_sql(self, expression: exp.Base64Encode) -> str: 4043 # DuckDB TO_BASE64 requires BLOB input 4044 # Snowflake BASE64_ENCODE accepts both VARCHAR and BINARY - for VARCHAR it implicitly 4045 # encodes UTF-8 bytes. We add ENCODE unless the input is a binary type. 4046 result = expression.this 4047 4048 # Check if input is a string type - ENCODE only accepts VARCHAR 4049 if result.is_type(*exp.DataType.TEXT_TYPES): 4050 result = exp.Encode(this=result) 4051 4052 result = exp.ToBase64(this=result) 4053 4054 max_line_length = expression.args.get("max_line_length") 4055 alphabet = expression.args.get("alphabet") 4056 4057 # Handle custom alphabet by replacing standard chars with custom ones 4058 result = _apply_base64_alphabet_replacements(result, alphabet) 4059 4060 # Handle max_line_length by inserting newlines every N characters 4061 line_length = ( 4062 t.cast(int, max_line_length.to_py()) 4063 if isinstance(max_line_length, exp.Literal) and max_line_length.is_number 4064 else 0 4065 ) 4066 if line_length > 0: 4067 newline = exp.Chr(expressions=[exp.Literal.number(10)]) 4068 result = exp.Trim( 4069 this=exp.RegexpReplace( 4070 this=result, 4071 expression=exp.Literal.string(f"(.{{{line_length}}})"), 4072 replacement=exp.Concat(expressions=[exp.Literal.string("\\1"), newline.copy()]), 4073 ), 4074 expression=newline, 4075 position="TRAILING", 4076 ) 4077 4078 return self.sql(result) 4079 4080 def hex_sql(self, expression: exp.Hex) -> str: 4081 case = expression.args.get("case") 4082 4083 if not case: 4084 return self.func("HEX", expression.this) 4085 4086 hex_expr = exp.Hex(this=expression.this) 4087 return self.sql( 4088 exp.case() 4089 .when(case.is_(exp.null()), exp.null()) 4090 .when(case.copy().eq(0), exp.Lower(this=hex_expr.copy())) 4091 .else_(hex_expr) 4092 ) 4093 4094 def replace_sql(self, expression: exp.Replace) -> str: 4095 result_sql = self.func( 4096 "REPLACE", 4097 _cast_to_varchar(expression.this), 4098 _cast_to_varchar(expression.expression), 4099 _cast_to_varchar(expression.args.get("replacement")), 4100 ) 4101 return _gen_with_cast_to_blob(self, expression, result_sql) 4102 4103 def _bitwise_op(self, expression: exp.Binary, op: str) -> str: 4104 _prepare_binary_bitwise_args(expression) 4105 result_sql = self.binary(expression, op) 4106 return _gen_with_cast_to_blob(self, expression, result_sql) 4107 4108 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 4109 _prepare_binary_bitwise_args(expression) 4110 result_sql = self.func("XOR", expression.this, expression.expression) 4111 return _gen_with_cast_to_blob(self, expression, result_sql) 4112 4113 def objectinsert_sql(self, expression: exp.ObjectInsert) -> str: 4114 this = expression.this 4115 key = expression.args.get("key") 4116 key_sql = key.name if isinstance(key, exp.Expr) else "" 4117 value_sql = self.sql(expression, "value") 4118 4119 kv_sql = f"{key_sql} := {value_sql}" 4120 4121 # If the input struct is empty e.g. transpiling OBJECT_INSERT(OBJECT_CONSTRUCT(), key, value) from Snowflake 4122 # then we can generate STRUCT_PACK which will build it since STRUCT_INSERT({}, key := value) is not valid DuckDB 4123 if isinstance(this, exp.Struct) and not this.expressions: 4124 return self.func("STRUCT_PACK", kv_sql) 4125 4126 return self.func("STRUCT_INSERT", this, kv_sql) 4127 4128 def mapcat_sql(self, expression: exp.MapCat) -> str: 4129 result = exp.replace_placeholders( 4130 self.MAPCAT_TEMPLATE.copy(), 4131 map1=expression.this, 4132 map2=expression.expression, 4133 ) 4134 return self.sql(result) 4135 4136 def mapcontainskey_sql(self, expression: exp.MapContainsKey) -> str: 4137 return self.func( 4138 "ARRAY_CONTAINS", exp.func("MAP_KEYS", expression.args["key"]), expression.this 4139 ) 4140 4141 def mapdelete_sql(self, expression: exp.MapDelete) -> str: 4142 map_arg = expression.this 4143 keys_to_delete = expression.expressions 4144 4145 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4146 4147 lambda_expr = exp.Lambda( 4148 this=exp.In(this=x_dot_key, expressions=keys_to_delete).not_(), 4149 expressions=[exp.to_identifier("x")], 4150 ) 4151 result = exp.func( 4152 "MAP_FROM_ENTRIES", 4153 exp.ArrayFilter(this=exp.func("MAP_ENTRIES", map_arg), expression=lambda_expr), 4154 ) 4155 return self.sql(result) 4156 4157 def mappick_sql(self, expression: exp.MapPick) -> str: 4158 map_arg = expression.this 4159 keys_to_pick = expression.expressions 4160 4161 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4162 4163 if len(keys_to_pick) == 1 and keys_to_pick[0].is_type(exp.DType.ARRAY): 4164 lambda_expr = exp.Lambda( 4165 this=exp.func("ARRAY_CONTAINS", keys_to_pick[0], x_dot_key), 4166 expressions=[exp.to_identifier("x")], 4167 ) 4168 else: 4169 lambda_expr = exp.Lambda( 4170 this=exp.In(this=x_dot_key, expressions=keys_to_pick), 4171 expressions=[exp.to_identifier("x")], 4172 ) 4173 4174 result = exp.func( 4175 "MAP_FROM_ENTRIES", 4176 exp.func("LIST_FILTER", exp.func("MAP_ENTRIES", map_arg), lambda_expr), 4177 ) 4178 return self.sql(result) 4179 4180 def mapsize_sql(self, expression: exp.MapSize) -> str: 4181 return self.func("CARDINALITY", expression.this) 4182 4183 @unsupported_args("update_flag") 4184 def mapinsert_sql(self, expression: exp.MapInsert) -> str: 4185 map_arg = expression.this 4186 key = expression.args.get("key") 4187 value = expression.args.get("value") 4188 4189 map_type = map_arg.type 4190 4191 if value is not None: 4192 if map_type and map_type.expressions and len(map_type.expressions) > 1: 4193 # Extract the value type from MAP(key_type, value_type) 4194 value_type = map_type.expressions[1] 4195 # Cast value to match the map's value type to avoid type conflicts 4196 value = exp.cast(value, value_type) 4197 # else: polymorphic MAP case - no type parameters available, use value as-is 4198 4199 # Create a single-entry map for the new key-value pair 4200 new_entry_struct = exp.Struct(expressions=[exp.PropertyEQ(this=key, expression=value)]) 4201 new_entry: exp.Expression = exp.ToMap(this=new_entry_struct) 4202 4203 # Use MAP_CONCAT to merge the original map with the new entry 4204 # This automatically handles both insert and update cases 4205 result = exp.func("MAP_CONCAT", map_arg, new_entry) 4206 4207 return self.sql(result) 4208 4209 def startswith_sql(self, expression: exp.StartsWith) -> str: 4210 return self.func( 4211 "STARTS_WITH", 4212 _cast_to_varchar(expression.this), 4213 _cast_to_varchar(expression.expression), 4214 ) 4215 4216 def space_sql(self, expression: exp.Space) -> str: 4217 # DuckDB's REPEAT requires BIGINT for the count parameter 4218 return self.sql( 4219 exp.Repeat( 4220 this=exp.Literal.string(" "), 4221 times=exp.cast(expression.this, exp.DType.BIGINT), 4222 ) 4223 ) 4224 4225 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 4226 # For GENERATOR, unwrap TABLE() - just emit the Generator (becomes RANGE) 4227 if isinstance(expression.this, exp.Generator): 4228 # Preserve alias, joins, and other table-level args 4229 table = exp.Table( 4230 this=expression.this, 4231 alias=expression.args.get("alias"), 4232 joins=expression.args.get("joins"), 4233 ) 4234 return self.sql(table) 4235 4236 return super().tablefromrows_sql(expression) 4237 4238 def unnest_sql(self, expression: exp.Unnest) -> str: 4239 explode_array = expression.args.get("explode_array") 4240 if explode_array: 4241 # In BigQuery, UNNESTing a nested array leads to explosion of the top-level array & struct 4242 # This is transpiled to DDB by transforming "FROM UNNEST(...)" to "FROM (SELECT UNNEST(..., max_depth => 2))" 4243 expression.expressions.append( 4244 exp.Kwarg(this=exp.var("max_depth"), expression=exp.Literal.number(2)) 4245 ) 4246 4247 # If BQ's UNNEST is aliased, we transform it from a column alias to a table alias in DDB 4248 alias = expression.args.get("alias") 4249 if isinstance(alias, exp.TableAlias): 4250 expression.set("alias", None) 4251 if alias.columns: 4252 alias = exp.TableAlias(this=seq_get(alias.columns, 0)) 4253 4254 unnest_sql = super().unnest_sql(expression) 4255 select = exp.Select(expressions=[unnest_sql]).subquery(alias) 4256 return self.sql(select) 4257 4258 if query := transforms.unnest_with_offset(expression): 4259 return self.sql(query) 4260 4261 return super().unnest_sql(expression) 4262 4263 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4264 if isinstance(expression.this, exp.Limit): 4265 self.unsupported("LIMIT inside ARRAY_AGG is not supported in DuckDB") 4266 4267 return super().arrayagg_sql(expression) 4268 4269 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 4270 this = expression.this 4271 4272 if isinstance(this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4273 # DuckDB should render IGNORE NULLS only for the general-purpose 4274 # window functions that accept it e.g. FIRST_VALUE(... IGNORE NULLS) OVER (...) 4275 return super().ignorenulls_sql(expression) 4276 4277 # For ARRAY_AGG(expr IGNORE NULLS ...), convert IGNORE NULLS to a 4278 # FILTER(WHERE expr IS NOT NULL) clause by setting nulls_excluded on 4279 # the ArrayAgg. The existing _add_arrayagg_null_filter method will 4280 # emit the FILTER clause during arrayagg_sql / withingroup_sql. 4281 if isinstance(this, exp.ArrayAgg): 4282 this.set("nulls_excluded", True) 4283 return self.sql(this) 4284 4285 if isinstance(this, exp.First): 4286 this = exp.AnyValue(this=this.this) 4287 4288 if not isinstance(this, (exp.AnyValue, exp.ApproxQuantiles)): 4289 self.unsupported("IGNORE NULLS is not supported for non-window functions.") 4290 4291 return self.sql(this) 4292 4293 def split_sql(self, expression: exp.Split) -> str: 4294 base_func = exp.func("STR_SPLIT", expression.this, expression.expression) 4295 4296 case_expr = exp.case().else_(base_func) 4297 needs_case = False 4298 4299 if expression.args.get("null_returns_null"): 4300 case_expr = case_expr.when(expression.expression.is_(exp.null()), exp.null()) 4301 needs_case = True 4302 4303 if expression.args.get("empty_delimiter_returns_whole"): 4304 # When delimiter is empty string, return input string as single array element 4305 array_with_input = exp.array(expression.this) 4306 case_expr = case_expr.when( 4307 expression.expression.eq(exp.Literal.string("")), array_with_input 4308 ) 4309 needs_case = True 4310 4311 return self.sql(case_expr if needs_case else base_func) 4312 4313 def splitpart_sql(self, expression: exp.SplitPart) -> str: 4314 string_arg = expression.this 4315 delimiter_arg = expression.args.get("delimiter") 4316 part_index_arg = expression.args.get("part_index") 4317 4318 if delimiter_arg and part_index_arg: 4319 # Handle Snowflake's "index 0 and 1 both return first element" behavior 4320 if expression.args.get("part_index_zero_as_one"): 4321 # Convert 0 to 1 for compatibility 4322 4323 part_index_arg = exp.Paren( 4324 this=exp.case() 4325 .when(part_index_arg.eq(exp.Literal.number("0")), exp.Literal.number("1")) 4326 .else_(part_index_arg) 4327 ) 4328 4329 # Use Anonymous to avoid recursion 4330 base_func_expr: exp.Expr = exp.Anonymous( 4331 this="SPLIT_PART", expressions=[string_arg, delimiter_arg, part_index_arg] 4332 ) 4333 needs_case_transform = False 4334 case_expr = exp.case().else_(base_func_expr) 4335 4336 if expression.args.get("empty_delimiter_returns_whole"): 4337 # When delimiter is empty string: 4338 # - Return whole string if part_index is 1 or -1 4339 # - Return empty string otherwise 4340 empty_case = exp.Paren( 4341 this=exp.case() 4342 .when( 4343 exp.or_( 4344 part_index_arg.eq(exp.Literal.number("1")), 4345 part_index_arg.eq(exp.Literal.number("-1")), 4346 ), 4347 string_arg, 4348 ) 4349 .else_(exp.Literal.string("")) 4350 ) 4351 4352 case_expr = case_expr.when(delimiter_arg.eq(exp.Literal.string("")), empty_case) 4353 needs_case_transform = True 4354 4355 """ 4356 Output looks something like this: 4357 4358 CASE 4359 WHEN delimiter is '' THEN 4360 ( 4361 CASE 4362 WHEN adjusted_part_index = 1 OR adjusted_part_index = -1 THEN input 4363 ELSE '' END 4364 ) 4365 ELSE SPLIT_PART(input, delimiter, adjusted_part_index) 4366 END 4367 4368 """ 4369 return self.sql(case_expr if needs_case_transform else base_func_expr) 4370 4371 return self.function_fallback_sql(expression) 4372 4373 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 4374 if isinstance(expression.this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4375 # DuckDB should render RESPECT NULLS only for the general-purpose 4376 # window functions that accept it e.g. FIRST_VALUE(... RESPECT NULLS) OVER (...) 4377 return super().respectnulls_sql(expression) 4378 4379 self.unsupported("RESPECT NULLS is not supported for non-window functions.") 4380 return self.sql(expression, "this") 4381 4382 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 4383 null = expression.args.get("null") 4384 4385 if expression.args.get("null_is_empty"): 4386 x = exp.to_identifier("x") 4387 list_transform = exp.Transform( 4388 this=expression.this.copy(), 4389 expression=exp.Lambda( 4390 this=exp.Coalesce( 4391 this=exp.cast(x, "TEXT"), expressions=[exp.Literal.string("")] 4392 ), 4393 expressions=[x], 4394 ), 4395 ) 4396 array_to_string = exp.ArrayToString( 4397 this=list_transform, expression=expression.expression 4398 ) 4399 if expression.args.get("null_delim_is_null"): 4400 return self.sql( 4401 exp.case() 4402 .when(expression.expression.copy().is_(exp.null()), exp.null()) 4403 .else_(array_to_string) 4404 ) 4405 return self.sql(array_to_string) 4406 4407 if null: 4408 x = exp.to_identifier("x") 4409 return self.sql( 4410 exp.ArrayToString( 4411 this=exp.Transform( 4412 this=expression.this, 4413 expression=exp.Lambda( 4414 this=exp.Coalesce(this=exp.cast(x, "TEXT"), expressions=[null]), 4415 expressions=[x], 4416 ), 4417 ), 4418 expression=expression.expression, 4419 ) 4420 ) 4421 4422 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 4423 4424 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4425 # DuckDB-specific: handle binary types using DPipe (||) operator 4426 separator = seq_get(expression.expressions, 0) 4427 args = expression.expressions[1:] 4428 4429 if any(_is_binary(arg) for arg in [separator, *args]): 4430 result = args[0] 4431 for arg in args[1:]: 4432 result = exp.DPipe( 4433 this=exp.DPipe(this=result, expression=separator), expression=arg 4434 ) 4435 return self.sql(result) 4436 4437 if expression.args.get("flatten") and any( 4438 isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY) for arg in args 4439 ): 4440 arrays = [] 4441 for arg in args: 4442 if isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY): 4443 arg = exp.cast(arg, "TEXT[]") 4444 else: 4445 if (not arg.type or arg.is_type(exp.DType.UNKNOWN)) and not isinstance( 4446 arg, exp.CONSTANTS 4447 ): 4448 self.unsupported( 4449 "Cannot transpile CONCAT_WS with unknown argument types to DuckDB." 4450 ) 4451 arg = exp.array(exp.cast(arg, exp.DType.TEXT)) 4452 4453 arrays.append(arg) 4454 4455 array = ( 4456 exp.ArrayConcat(this=arrays[0], expressions=arrays[1:]) 4457 if len(arrays) > 1 4458 else arrays[0] 4459 ) 4460 return self.func("CONCAT_WS", separator, self.func("ARRAY_TO_STRING", array, separator)) 4461 4462 return super().concatws_sql(expression) 4463 4464 def _regexp_extract_sql(self, expression: exp.RegexpExtract | exp.RegexpExtractAll) -> str: 4465 this = expression.this 4466 group = expression.args.get("group") 4467 params = expression.args.get("parameters") 4468 position = expression.args.get("position") 4469 occurrence = expression.args.get("occurrence") 4470 null_if_pos_overflow = expression.args.get("null_if_pos_overflow") 4471 null_if_no_match = expression.args.get("null_if_no_match") 4472 4473 # Handle Snowflake's 'e' flag: it enables capture group extraction 4474 # In DuckDB, this is controlled by the group parameter directly 4475 if params and params.is_string and "e" in params.name: 4476 params = exp.Literal.string(params.name.replace("e", "")) 4477 4478 validated_flags = self._validate_regexp_flags(params, supported_flags="cims") 4479 4480 # Strip default group when no following params (DuckDB default is same as group=0) 4481 if ( 4482 not validated_flags 4483 and group 4484 and group.name == str(self.dialect.REGEXP_EXTRACT_DEFAULT_GROUP) 4485 ): 4486 group = None 4487 4488 flags_expr = exp.Literal.string(validated_flags) if validated_flags else None 4489 4490 # use substring to handle position argument 4491 if position and (not position.is_int or position.to_py() > 1): 4492 this = exp.Substring(this=this, start=position) 4493 4494 if null_if_pos_overflow: 4495 this = exp.Nullif(this=this, expression=exp.Literal.string("")) 4496 4497 is_extract_all = isinstance(expression, exp.RegexpExtractAll) 4498 non_single_occurrence = occurrence and (not occurrence.is_int or occurrence.to_py() > 1) 4499 4500 if is_extract_all or non_single_occurrence or null_if_no_match: 4501 name = "REGEXP_EXTRACT_ALL" 4502 else: 4503 name = "REGEXP_EXTRACT" 4504 4505 result: exp.Expr = exp.Anonymous( 4506 this=name, expressions=[this, expression.expression, group, flags_expr] 4507 ) 4508 4509 # Array slicing for REGEXP_EXTRACT_ALL with occurrence 4510 if is_extract_all and non_single_occurrence: 4511 result = exp.Bracket(this=result, expressions=[exp.Slice(this=occurrence)]) 4512 elif not is_extract_all and (non_single_occurrence or null_if_no_match): 4513 # Non-participating capture group yields [NULL] in DuckDB; Snowflake returns '' on a match 4514 if ( 4515 expression.args.get("empty_if_group_missing") 4516 and group 4517 and not (group.is_int and group.to_py() == 0) 4518 ): 4519 result = exp.Transform( 4520 this=result, 4521 expression=exp.Lambda( 4522 this=exp.Coalesce( 4523 this=exp.column("x"), expressions=[exp.Literal.string("")] 4524 ), 4525 expressions=[exp.to_identifier("x")], 4526 ), 4527 ) 4528 return self.func( 4529 "ARRAY_EXTRACT", 4530 result, 4531 occurrence if non_single_occurrence else exp.Literal.number(1), 4532 ) 4533 4534 return self.sql(result) 4535 4536 def regexpextract_sql(self, expression: exp.RegexpExtract) -> str: 4537 return self._regexp_extract_sql(expression) 4538 4539 def regexpextractall_sql(self, expression: exp.RegexpExtractAll) -> str: 4540 return self._regexp_extract_sql(expression) 4541 4542 def regexpinstr_sql(self, expression: exp.RegexpInstr) -> str: 4543 this = expression.this 4544 pattern = expression.expression 4545 position = expression.args.get("position") 4546 orig_occ = expression.args.get("occurrence") 4547 occurrence = orig_occ or exp.Literal.number(1) 4548 option = expression.args.get("option") 4549 parameters = expression.args.get("parameters") 4550 4551 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 4552 # Checked before the flags are embedded, which would make the pattern non-empty 4553 is_empty = pattern.copy().eq(exp.Literal.string("")) 4554 if validated_flags: 4555 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 4556 4557 # Handle starting position offset 4558 pos_offset: exp.Expr = exp.Literal.number(0) 4559 if position and (not position.is_int or position.to_py() > 1): 4560 this = exp.Substring(this=this, start=position) 4561 pos_offset = position - exp.Literal.number(1) 4562 4563 # Helper: LIST_SUM(LIST_TRANSFORM(list[1:end], x -> LENGTH(x))) 4564 def sum_lengths(func_name: str, end: exp.Expr) -> exp.Expr: 4565 lst = exp.Bracket( 4566 this=exp.Anonymous(this=func_name, expressions=[this, pattern]), 4567 expressions=[exp.Slice(this=exp.Literal.number(1), expression=end)], 4568 offset=1, 4569 ) 4570 transform = exp.Anonymous( 4571 this="LIST_TRANSFORM", 4572 expressions=[ 4573 lst, 4574 exp.Lambda( 4575 this=exp.Length(this=exp.to_identifier("x")), 4576 expressions=[exp.to_identifier("x")], 4577 ), 4578 ], 4579 ) 4580 return exp.Coalesce( 4581 this=exp.Anonymous(this="LIST_SUM", expressions=[transform]), 4582 expressions=[exp.Literal.number(0)], 4583 ) 4584 4585 # Position = 1 + sum(split_lengths[1:occ]) + sum(match_lengths[1:occ-1]) + offset 4586 base_pos: exp.Expr = ( 4587 exp.Literal.number(1) 4588 + sum_lengths("STRING_SPLIT_REGEX", occurrence) 4589 + sum_lengths("REGEXP_EXTRACT_ALL", occurrence - exp.Literal.number(1)) 4590 + pos_offset 4591 ) 4592 4593 # option=1: add match length for end position 4594 if option and option.is_int and option.to_py() == 1: 4595 match_at_occ = exp.Bracket( 4596 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]), 4597 expressions=[occurrence], 4598 offset=1, 4599 ) 4600 base_pos = base_pos + exp.Coalesce( 4601 this=exp.Length(this=match_at_occ), expressions=[exp.Literal.number(0)] 4602 ) 4603 4604 # NULL checks for all provided arguments 4605 # .copy() is used strictly because .is_() alters the node's parent pointer, mutating the parsed AST 4606 null_args = [ 4607 expression.this, 4608 expression.expression, 4609 position, 4610 orig_occ, 4611 option, 4612 parameters, 4613 ] 4614 null_checks = [arg.copy().is_(exp.Null()) for arg in null_args if arg] 4615 4616 matches = exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 4617 4618 return self.sql( 4619 exp.case() 4620 .when(exp.or_(*null_checks), exp.Null()) 4621 .when(is_empty, exp.Literal.number(0)) 4622 .when(exp.Length(this=matches) < occurrence, exp.Literal.number(0)) 4623 .else_(base_pos) 4624 ) 4625 4626 @unsupported_args("culture") 4627 def numbertostr_sql(self, expression: exp.NumberToStr) -> str: 4628 fmt = expression.args.get("format") 4629 if fmt and fmt.is_int: 4630 return self.func("FORMAT", f"'{{:,.{fmt.name}f}}'", expression.this) 4631 4632 self.unsupported("Only integer formats are supported by NumberToStr") 4633 return self.function_fallback_sql(expression) 4634 4635 def autoincrementcolumnconstraint_sql(self, _) -> str: 4636 self.unsupported("The AUTOINCREMENT column constraint is not supported by DuckDB") 4637 return "" 4638 4639 def onconflict_sql(self, expression: exp.OnConflict) -> str: 4640 if expression.arg_key == "on_conflict": 4641 self.unsupported("DuckDB does not support ON CONFLICT on table or column constraints") 4642 return "" 4643 return super().onconflict_sql(expression) 4644 4645 def aliases_sql(self, expression: exp.Aliases) -> str: 4646 this = expression.this 4647 if isinstance(this, exp.Posexplode): 4648 return self.posexplode_sql(this) 4649 4650 return super().aliases_sql(expression) 4651 4652 def posexplode_sql(self, expression: exp.Posexplode) -> str: 4653 this = expression.this 4654 parent = expression.parent 4655 4656 # The default Spark aliases are "pos" and "col", unless specified otherwise 4657 pos, col = exp.to_identifier("pos"), exp.to_identifier("col") 4658 4659 if isinstance(parent, exp.Aliases): 4660 # Column case: SELECT POSEXPLODE(col) [AS (a, b)] 4661 pos, col = parent.expressions 4662 elif isinstance(parent, exp.Table): 4663 # Table case: SELECT * FROM POSEXPLODE(col) [AS (a, b)] 4664 alias = parent.args.get("alias") 4665 if alias: 4666 pos, col = alias.columns or [pos, col] 4667 alias.pop() 4668 4669 # Translate POSEXPLODE to UNNEST + GENERATE_SUBSCRIPTS 4670 # Note: In Spark pos is 0-indexed, but in DuckDB it's 1-indexed, so we subtract 1 from GENERATE_SUBSCRIPTS 4671 unnest_sql = self.sql(exp.Unnest(expressions=[this], alias=col)) 4672 gen_subscripts = self.sql( 4673 exp.Alias( 4674 this=exp.Anonymous( 4675 this="GENERATE_SUBSCRIPTS", expressions=[this, exp.Literal.number(1)] 4676 ) 4677 - exp.Literal.number(1), 4678 alias=pos, 4679 ) 4680 ) 4681 4682 posexplode_sql = self.format_args(gen_subscripts, unnest_sql) 4683 4684 if isinstance(parent, exp.From) or (parent and isinstance(parent.parent, exp.From)): 4685 # SELECT * FROM POSEXPLODE(col) -> SELECT * FROM (SELECT GENERATE_SUBSCRIPTS(...), UNNEST(...)) 4686 return self.sql(exp.Subquery(this=exp.Select(expressions=[posexplode_sql]))) 4687 4688 return posexplode_sql 4689 4690 def addmonths_sql(self, expression: exp.AddMonths) -> str: 4691 """ 4692 Handles three key issues: 4693 1. Float/decimal months: e.g., Snowflake rounds, whereas DuckDB INTERVAL requires integers 4694 2. End-of-month preservation: If input is last day of month, result is last day of result month 4695 3. Type preservation: Maintains DATE/TIMESTAMPTZ types (DuckDB defaults to TIMESTAMP) 4696 """ 4697 from sqlglot.optimizer.annotate_types import annotate_types 4698 4699 this = expression.this 4700 if not this.type: 4701 this = annotate_types(this, dialect=self.dialect) 4702 4703 if this.is_type(*exp.DataType.TEXT_TYPES): 4704 this = exp.Cast(this=this, to=exp.DataType(this=exp.DType.TIMESTAMP)) 4705 4706 # Detect float/decimal months to apply rounding (Snowflake behavior) 4707 # DuckDB INTERVAL syntax doesn't support non-integer expressions, so use TO_MONTHS 4708 months_expr = expression.expression 4709 if not months_expr.type: 4710 months_expr = annotate_types(months_expr, dialect=self.dialect) 4711 4712 # Build interval or to_months expression based on type 4713 # Float/decimal case: Round and use TO_MONTHS(CAST(ROUND(value) AS INT)) 4714 interval_or_to_months = ( 4715 exp.func("TO_MONTHS", exp.cast(exp.func("ROUND", months_expr), "INT")) 4716 if months_expr.is_type( 4717 exp.DType.FLOAT, 4718 exp.DType.DOUBLE, 4719 exp.DType.DECIMAL, 4720 ) 4721 # Integer case: standard INTERVAL N MONTH syntax 4722 else exp.Interval(this=months_expr, unit=exp.var("MONTH")) 4723 ) 4724 4725 date_add_expr = exp.Add(this=this, expression=interval_or_to_months) 4726 4727 # Apply end-of-month preservation if Snowflake flag is set 4728 # CASE WHEN LAST_DAY(date) = date THEN LAST_DAY(result) ELSE result END 4729 preserve_eom = expression.args.get("preserve_end_of_month") 4730 result_expr = ( 4731 exp.case() 4732 .when( 4733 exp.EQ(this=exp.func("LAST_DAY", this), expression=this), 4734 exp.func("LAST_DAY", date_add_expr), 4735 ) 4736 .else_(date_add_expr) 4737 if preserve_eom 4738 else date_add_expr 4739 ) 4740 4741 # DuckDB's DATE_ADD function returns TIMESTAMP/DATETIME by default, even when the input is DATE 4742 # To match for example Snowflake's ADD_MONTHS behavior (which preserves the input type) 4743 # We need to cast the result back to the original type when the input is DATE or TIMESTAMPTZ 4744 # Example: ADD_MONTHS('2023-01-31'::date, 1) should return DATE, not TIMESTAMP 4745 if this.is_type(exp.DType.DATE, exp.DType.TIMESTAMPTZ): 4746 return self.sql(exp.Cast(this=result_expr, to=this.type)) 4747 return self.sql(result_expr) 4748 4749 def format_sql(self, expression: exp.Format) -> str: 4750 if expression.args.get("is_fmt"): 4751 return self.func("FORMAT", expression.this, *expression.expressions) 4752 4753 fmt = expression.name 4754 if expression.this.is_string and fmt == "%S" and len(expression.expressions) == 1: 4755 return self.func( 4756 "UPPER", self.func("FORMAT", exp.Literal.string("{}"), expression.expressions[0]) 4757 ) 4758 4759 if expression.this.is_string and "%s" in fmt and "%" not in re.sub(r"%%|%s", "", fmt): 4760 # Use brace formatting to support non-string %s arguments, as in PostgreSQL. 4761 fmt = fmt.replace("{", "{{").replace("}", "}}") 4762 fmt = re.sub(r"%%|%s", lambda m: "%" if m[0] == "%%" else "{}", fmt) 4763 return self.func("FORMAT", exp.Literal.string(fmt), *expression.expressions) 4764 4765 return self.func("PRINTF", expression.this, *expression.expressions) 4766 4767 def hexstring_sql( 4768 self, expression: exp.HexString, binary_function_repr: str | None = None 4769 ) -> str: 4770 # UNHEX('FF') correctly produces blob \xFF in DuckDB 4771 return super().hexstring_sql(expression, binary_function_repr="UNHEX") 4772 4773 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 4774 unit = expression.args.get("unit") 4775 date = expression.this 4776 4777 week_start = _week_trunc_start_dow(unit) 4778 unit = ( 4779 unit_to_str(expression) 4780 if week_start 4781 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4782 ) 4783 4784 if week_start: 4785 result = self.sql( 4786 _build_week_trunc_expression(date, week_start, preserve_start_day=True) 4787 ) 4788 else: 4789 result = self.func("DATE_TRUNC", unit, date) 4790 4791 if expression.args.get("input_type_preserved") and date.is_type( 4792 *exp.DataType.TEMPORAL_TYPES 4793 ): 4794 return self.sql(exp.Cast(this=result, to=date.type)) 4795 4796 return result 4797 4798 def datetimetrunc_sql(self, expression: exp.DatetimeTrunc) -> str: 4799 this = exp.cast(expression.this, exp.DType.DATETIME) 4800 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4801 if week_start: 4802 return self.sql( 4803 _build_week_trunc_expression( 4804 this, week_start, preserve_start_day=True, cast_to_date=False 4805 ) 4806 ) 4807 4808 return self.func("DATE_TRUNC", unit_to_str(expression), this) 4809 4810 def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str: 4811 zone = expression.args.get("zone") 4812 timestamp = expression.this 4813 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4814 4815 # The week start emulation below is exact, so avoid weekstart_unit_to_str's degrade warning 4816 unit = ( 4817 unit_to_str(expression) 4818 if week_start 4819 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4820 ) 4821 date_unit = is_date_unit(unit) or bool(week_start) 4822 4823 def _trunc_expr(this: exp.Expr) -> exp.Expr: 4824 if week_start: 4825 return _build_week_trunc_expression( 4826 this, week_start, preserve_start_day=True, cast_to_date=False 4827 ) 4828 return exp.DateTrunc( 4829 unit=unit, 4830 this=this, 4831 century_from_zero=expression.args.get("century_from_zero"), 4832 ) 4833 4834 if date_unit and zone: 4835 # BigQuery's TIMESTAMP_TRUNC with timezone truncates in the target timezone and returns as UTC. 4836 # Double AT TIME ZONE needed for BigQuery compatibility: 4837 # 1. First AT TIME ZONE: ensures truncation happens in the target timezone 4838 # 2. Second AT TIME ZONE: converts the DATE result back to TIMESTAMPTZ (preserving time component) 4839 timestamp = exp.AtTimeZone(this=timestamp, zone=zone) 4840 trunced = _trunc_expr(timestamp) 4841 if isinstance(trunced, exp.DateAdd): 4842 # Parenthesize so the trailing AT TIME ZONE binds to the whole shifted expression 4843 trunced = exp.Paren(this=trunced) 4844 return self.sql(exp.AtTimeZone(this=trunced, zone=zone)) 4845 4846 result = self.sql(_trunc_expr(timestamp)) 4847 if expression.args.get("input_type_preserved"): 4848 if timestamp.type and timestamp.is_type(exp.DType.TIME, exp.DType.TIMETZ): 4849 dummy_date = exp.Cast( 4850 this=exp.Literal.string("1970-01-01"), 4851 to=exp.DataType(this=exp.DType.DATE), 4852 ) 4853 date_time = exp.Add(this=dummy_date, expression=timestamp) 4854 result = self.func("DATE_TRUNC", unit, date_time) 4855 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4856 4857 if timestamp.is_type(*exp.DataType.TEMPORAL_TYPES): 4858 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4859 4860 return result 4861 4862 def timestampdiff_sql(self, expression: exp.TimestampDiff) -> str: 4863 unit = expression.unit 4864 4865 if _is_nanosecond_unit(unit): 4866 return _handle_nanosecond_diff(self, expression.this, expression.expression) 4867 4868 unit_str = unit.name.upper() if isinstance(unit, (exp.Var, exp.Literal)) else "" 4869 4870 if expression.args.get("boundary_for_date") and all( 4871 arg.is_type(exp.DType.DATE, exp.DType.DATETIME, exp.DType.TIMESTAMP) 4872 for arg in (expression.this, expression.expression) 4873 ): 4874 return _date_diff_sql( 4875 self, 4876 exp.DateDiff( 4877 this=expression.this, 4878 expression=expression.expression, 4879 unit=unit, 4880 date_part_boundary=True, 4881 ), 4882 ) 4883 4884 # Cast untyped args (bare NULLs, string literals) so DuckDB can resolve the overload 4885 this = ( 4886 exp.cast(expression.this, exp.DType.TIMESTAMPTZ) 4887 if isinstance(expression.this, (exp.Null, exp.Literal)) 4888 else expression.this 4889 ) 4890 expr = ( 4891 exp.cast(expression.expression, exp.DType.TIMESTAMPTZ) 4892 if isinstance(expression.expression, (exp.Null, exp.Literal)) 4893 else expression.expression 4894 ) 4895 4896 if unit_str == "DAY": 4897 date_sub = exp.func( 4898 "DATE_SUB", exp.Literal.string("HOUR"), expr, this, dialect="duckdb" 4899 ) 4900 return self.sql(exp.IntDiv(this=date_sub, expression=exp.Literal.number(24))) 4901 4902 return self.func("DATE_SUB", unit_to_str(expression), expr, this) 4903 4904 def trim_sql(self, expression: exp.Trim) -> str: 4905 expression.this.replace(_cast_to_varchar(expression.this)) 4906 if expression.expression: 4907 expression.expression.replace(_cast_to_varchar(expression.expression)) 4908 4909 result_sql = super().trim_sql(expression) 4910 return _gen_with_cast_to_blob(self, expression, result_sql) 4911 4912 def round_sql(self, expression: exp.Round) -> str: 4913 this = expression.this 4914 decimals = expression.args.get("decimals") 4915 truncate = expression.args.get("truncate") 4916 4917 if decimals is not None and expression.args.get("negative_decimals_are_zero"): 4918 if decimals.is_int: 4919 decimals = exp.Literal.number(max(0, decimals.to_py())) 4920 else: 4921 # DuckDB's DECIMAL overload requires constant precision; SQLite rounds doubles. 4922 this = exp.cast(this, exp.DType.DOUBLE) 4923 # Preserve NULL precision, which GREATEST(decimals, 0) would replace with 0. 4924 decimals = exp.If( 4925 this=decimals < 0, true=exp.Literal.number(0), false=decimals.copy() 4926 ) 4927 4928 # DuckDB requires the scale (decimals) argument to be an INT 4929 # Some dialects (e.g., Snowflake) allow non-integer scales and cast to an integer internally 4930 if decimals is not None and expression.args.get("casts_non_integer_decimals"): 4931 if not (decimals.is_int or decimals.is_type(*_ROUND_SCALE_INTEGER_TYPES)): 4932 decimals = exp.cast(decimals, exp.DType.INT) 4933 4934 func = "ROUND" 4935 if truncate: 4936 # BigQuery uses ROUND_HALF_EVEN; Snowflake uses HALF_TO_EVEN 4937 if truncate.this in ("ROUND_HALF_EVEN", "HALF_TO_EVEN"): 4938 func = "ROUND_EVEN" 4939 truncate = None 4940 # BigQuery uses ROUND_HALF_AWAY_FROM_ZERO; Snowflake uses HALF_AWAY_FROM_ZERO 4941 elif truncate.this in ("ROUND_HALF_AWAY_FROM_ZERO", "HALF_AWAY_FROM_ZERO"): 4942 truncate = None 4943 4944 return self.func(func, this, decimals, truncate) 4945 4946 def trycast_sql(self, expression: exp.TryCast) -> str: 4947 to = expression.to 4948 to_type = to.this 4949 src = expression.this 4950 4951 if ( 4952 expression.args.get("null_on_text_overflow") 4953 and to_type in exp.DataType.TEXT_TYPES 4954 and to.expressions 4955 ): 4956 return self.sql( 4957 exp.case() 4958 .when( 4959 exp.LTE(this=exp.func("LENGTH", src), expression=to.expressions[0].this), 4960 exp.cast(src, "TEXT"), 4961 ) 4962 .else_(exp.Null()) 4963 ) 4964 elif to_type == exp.DType.DATE and expression.args.get("probe_date_format"): 4965 slash_strptime = exp.cast( 4966 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_SLASH_FMT)), 4967 "DATE", 4968 ) 4969 mon_strptime = exp.cast( 4970 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_MON_FMT)), 4971 "DATE", 4972 ) 4973 return self.sql( 4974 exp.case() 4975 .when(exp.func("CONTAINS", src, exp.Literal.string("/")), slash_strptime) 4976 .when( 4977 exp.RegexpLike(this=src, expression=exp.Literal.string("[A-Za-z]")), 4978 mon_strptime, 4979 ) 4980 .else_(exp.TryCast(this=src, to=to)) 4981 ) 4982 elif ( 4983 isinstance(to_type, exp.Interval) 4984 and (unit := to_type.unit) 4985 and expression.args.get("requires_string") 4986 ): 4987 interval_type = exp.DataType.build("INTERVAL") 4988 if isinstance(unit, exp.IntervalSpan): 4989 self.unsupported( 4990 "TRY_CAST to INTERVAL with span (e.g. HOUR TO MINUTE) is not supported in DuckDB" 4991 ) 4992 return self.sql(exp.TryCast(this=src, to=interval_type)) 4993 return self.sql( 4994 exp.TryCast( 4995 this=exp.DPipe(this=src, expression=exp.Literal.string(f" {unit.name}")), 4996 to=interval_type, 4997 ) 4998 ) 4999 5000 return super().trycast_sql(expression) 5001 5002 def strtok_sql(self, expression: exp.Strtok) -> str: 5003 string_arg = expression.this 5004 delimiter_arg = expression.args.get("delimiter") 5005 part_index_arg = expression.args.get("part_index") 5006 5007 if delimiter_arg and part_index_arg: 5008 # Escape regex chars and build character class at runtime using REGEXP_REPLACE 5009 escaped_delimiter = exp.Anonymous( 5010 this="REGEXP_REPLACE", 5011 expressions=[ 5012 delimiter_arg, 5013 exp.Literal.string( 5014 r"([\[\]^.\-*+?(){}|$\\])" 5015 ), # Escape problematic regex chars 5016 exp.Literal.string( 5017 r"\\\1" 5018 ), # Replace with escaped version using $1 backreference 5019 exp.Literal.string("g"), # Global flag 5020 ], 5021 ) 5022 # CASE WHEN delimiter = '' THEN '' ELSE CONCAT('[', escaped_delimiter, ']') END 5023 regex_pattern = ( 5024 exp.case() 5025 .when(delimiter_arg.eq(exp.Literal.string("")), exp.Literal.string("")) 5026 .else_( 5027 exp.func( 5028 "CONCAT", 5029 exp.Literal.string("["), 5030 escaped_delimiter, 5031 exp.Literal.string("]"), 5032 ) 5033 ) 5034 ) 5035 5036 # STRTOK skips empty strings, so we need to filter them out 5037 # LIST_FILTER(REGEXP_SPLIT_TO_ARRAY(string, pattern), x -> x != '')[index] 5038 split_array = exp.func("REGEXP_SPLIT_TO_ARRAY", string_arg, regex_pattern) 5039 x = exp.to_identifier("x") 5040 is_empty = x.eq(exp.Literal.string("")) 5041 filtered_array = exp.func( 5042 "LIST_FILTER", 5043 split_array, 5044 exp.Lambda(this=exp.not_(is_empty.copy()), expressions=[x.copy()]), 5045 ) 5046 base_func = exp.Bracket( 5047 this=filtered_array, 5048 expressions=[part_index_arg], 5049 offset=1, 5050 ) 5051 5052 # Use template with the built regex pattern 5053 result = exp.replace_placeholders( 5054 self.STRTOK_TEMPLATE.copy(), 5055 string=string_arg, 5056 delimiter=delimiter_arg, 5057 part_index=part_index_arg, 5058 base_func=base_func, 5059 ) 5060 5061 return self.sql(result) 5062 5063 return self.function_fallback_sql(expression) 5064 5065 def strtoktoarray_sql(self, expression: exp.StrtokToArray) -> str: 5066 string_arg = expression.this 5067 delimiter_arg = expression.args.get("expression") or exp.Literal.string(" ") 5068 5069 escaped = exp.RegexpReplace( 5070 this=delimiter_arg.copy(), 5071 expression=exp.Literal.string(r"([\[\]^.\-*+?(){}|$\\])"), 5072 replacement=exp.Literal.string(r"\\\1"), 5073 modifiers=exp.Literal.string("g"), 5074 ) 5075 return self.sql( 5076 exp.replace_placeholders( 5077 self.STRTOK_TO_ARRAY_TEMPLATE.copy(), 5078 string=string_arg, 5079 delimiter=delimiter_arg, 5080 escaped=escaped, 5081 ) 5082 ) 5083 5084 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 5085 result = self.func("APPROX_QUANTILE", expression.this, expression.args.get("quantile")) 5086 5087 # DuckDB returns the input's type, e.g. an integer or DECIMAL, so cast when a float is expected 5088 if expression.is_type(*exp.DataType.FLOAT_TYPES): 5089 result = f"CAST({result} AS DOUBLE)" 5090 5091 return result 5092 5093 def approxquantiles_sql(self, expression: exp.ApproxQuantiles) -> str: 5094 """ 5095 BigQuery's APPROX_QUANTILES(expr, n) returns an array of n+1 approximate quantile values 5096 dividing the input distribution into n equal-sized buckets. 5097 5098 Both BigQuery and DuckDB use approximate algorithms for quantile estimation, but BigQuery 5099 does not document the specific algorithm used so results may differ. DuckDB does not 5100 support RESPECT NULLS. 5101 """ 5102 this = expression.this 5103 if isinstance(this, exp.Distinct): 5104 # APPROX_QUANTILES requires 2 args and DISTINCT node grabs both 5105 if len(this.expressions) < 2: 5106 self.unsupported("APPROX_QUANTILES requires a bucket count argument") 5107 return self.function_fallback_sql(expression) 5108 num_quantiles_expr = this.expressions[1].pop() 5109 else: 5110 num_quantiles_expr = expression.expression 5111 5112 if not isinstance(num_quantiles_expr, exp.Literal) or not num_quantiles_expr.is_int: 5113 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5114 return self.function_fallback_sql(expression) 5115 5116 num_quantiles = t.cast(int, num_quantiles_expr.to_py()) 5117 if num_quantiles <= 0: 5118 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5119 return self.function_fallback_sql(expression) 5120 5121 quantiles = [ 5122 exp.Literal.number(Decimal(i) / Decimal(num_quantiles)) 5123 for i in range(num_quantiles + 1) 5124 ] 5125 5126 return self.sql(exp.ApproxQuantile(this=this, quantile=exp.Array(expressions=quantiles))) 5127 5128 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 5129 if expression.args.get("scalar_only"): 5130 json_value = exp.JSONExtractScalar( 5131 this=rename_func("JSON_VALUE")(self, expression), expression="'$'" 5132 ) 5133 5134 # `->>` binds looser than most operators, so the wrap logic needs the parent 5135 json_value.parent = expression.parent 5136 expression = json_value 5137 5138 return _arrow_json_extract_sql(self, expression) 5139 5140 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 5141 this = expression.this 5142 5143 if _is_binary(this): 5144 expression.type = exp.DType.BINARY.into_expr() 5145 5146 arg = _cast_to_bit(this) 5147 5148 if isinstance(this, exp.Neg): 5149 arg = exp.Paren(this=arg) 5150 5151 expression.set("this", arg) 5152 5153 result_sql = f"~{self.sql(expression, 'this')}" 5154 5155 return _gen_with_cast_to_blob(self, expression, result_sql) 5156 5157 def window_sql(self, expression: exp.Window) -> str: 5158 this = expression.this 5159 if isinstance(this, exp.Corr) or ( 5160 isinstance(this, exp.Filter) and isinstance(this.this, exp.Corr) 5161 ): 5162 return self._corr_sql(expression) 5163 5164 return self._arg_max_or_min_with_count_sql(expression) or super().window_sql(expression) 5165 5166 def filter_sql(self, expression: exp.Filter) -> str: 5167 if isinstance(expression.this, exp.Corr): 5168 return self._corr_sql(expression) 5169 5170 return self._arg_max_or_min_with_count_sql(expression) or super().filter_sql(expression) 5171 5172 def _arg_max_or_min_with_count_sql(self, expression: exp.Expr) -> str | None: 5173 agg = _unwrap_aggregate_modifiers(expression) 5174 if not ( 5175 isinstance(agg, (exp.ArgMax, exp.ArgMin)) 5176 and agg.args.get("count") 5177 and agg.args.get("include_nulls") 5178 ): 5179 return None 5180 5181 # DuckDB's three-argument aggregate skips NULL values. Rank singleton lists 5182 # so [NULL] participates, then unwrap them after any FILTER or OVER clause. 5183 expression = expression.copy() 5184 expression.comments = None 5185 agg = _unwrap_aggregate_modifiers(expression) 5186 value = agg.this 5187 if isinstance(value, exp.Distinct): 5188 value.set("expressions", [exp.array(value.expressions[0], copy=False)]) 5189 else: 5190 agg.set("this", exp.array(value, copy=False)) 5191 agg.set("include_nulls", None) 5192 return self.func("FLATTEN", expression) 5193 5194 def _corr_sql( 5195 self, 5196 expression: exp.Filter | exp.Window | exp.Corr, 5197 ) -> str: 5198 if isinstance(expression, exp.Corr) and not expression.args.get("null_on_zero_variance"): 5199 return self.func("CORR", expression.this, expression.expression) 5200 5201 corr_expr = _maybe_corr_null_to_false(expression) 5202 if corr_expr is None: 5203 if isinstance(expression, exp.Window): 5204 return super().window_sql(expression) 5205 if isinstance(expression, exp.Filter): 5206 return super().filter_sql(expression) 5207 corr_expr = expression # make mypy happy 5208 5209 return self.sql(exp.case().when(exp.IsNan(this=corr_expr), exp.null()).else_(corr_expr)) 5210 5211 def uuid_sql(self, expression: exp.Uuid) -> str: 5212 namespace = expression.this 5213 name = expression.args.get("name") 5214 5215 # UUID v5 (namespace + name) - Emulate using SHA1 5216 if namespace and name: 5217 result = exp.replace_placeholders( 5218 self.UUID_V5_TEMPLATE.copy(), 5219 namespace=namespace, 5220 name=name, 5221 ) 5222 return self.sql(result) 5223 5224 return super().uuid_sql(expression)
755def connect_by_to_recursive_cte(expression: exp.Expr) -> exp.Expr: 756 # Rewrites START WITH ... CONNECT BY PRIOR into WITH RECURSIVE 757 # Falls through unchanged if there are no PRIORs. 758 if not isinstance(expression, exp.Select) or not expression.args.get("connect"): 759 return expression 760 761 connect = expression.args["connect"] 762 connect_pred = connect.args["connect"] 763 764 priors = list(connect_pred.find_all(exp.Prior)) 765 if not priors: 766 return expression 767 768 from_ = expression.args.get("from_") 769 if not from_ or expression.args.get("joins"): 770 return expression 771 772 source_table = from_.this 773 base_select_exprs = expression.expressions 774 base_where = expression.args.get("where") 775 base_with = expression.args.get("with_") 776 777 # LEVEL is a Snowflake pseudo-column: it's always computed as a depth counter in the CTE. 778 has_level = any( 779 isinstance(col, exp.Column) and col.name.upper() == "LEVEL" 780 for e in base_select_exprs 781 for col in e.find_all(exp.Column) 782 ) 783 has_star = expression.is_star 784 785 # CONNECT_BY_ROOT col yields the value of `col` from the START WITH row that begins each 786 # branch. Each one is threaded through the CTE as an extra column: the anchor binds it to the 787 # row's own value, the recursive arm forwards the parent's value unchanged. 788 root_col_names: list[str] = [] 789 anchor_root_cols: list[exp.Expr] = [] 790 inner_root_cols: list[exp.Expr] = [] 791 roots = [root for e in base_select_exprs for root in e.find_all(exp.ConnectByRoot)] 792 793 for i, root in enumerate(roots): 794 name = f"_connect_by_root_{i}" 795 root_col_names.append(name) 796 anchor_root_cols.append(exp.alias_(root.this, name)) 797 inner_root_cols.append(exp.alias_(exp.column(name, "_parent_row"), name)) 798 root.replace(exp.column(name)) 799 800 # Build the join condition from the full CONNECT BY predicate: 801 # PRIOR(col) → _parent_row.col, unqualified cols → _child_row.col. 802 def _qualify_connect_pred(node: exp.Expression) -> exp.Expression: 803 for col in find_all_in_scope(node, exp.Column): 804 col.set( 805 "table", 806 exp.to_identifier( 807 "_parent_row" if isinstance(col.parent, exp.Prior) else "_child_row" 808 ), 809 ) 810 for prior in find_all_in_scope(node, exp.Prior): 811 prior.replace(prior.this) 812 return node 813 814 # Avoid colliding with any CTE names already on the query. 815 cte_name = find_new_name( 816 {cte.alias for cte in (base_with.expressions if base_with else [])}, "_rootcte" 817 ) 818 819 # Anchor: project all source columns + seed LEVEL at 1 + bind each root column to its own value. 820 anchor = exp.select( 821 exp.Star(), exp.alias_(exp.Literal.number(1), "level"), *anchor_root_cols 822 ).from_(source_table) 823 if connect.args.get("start"): 824 anchor = anchor.where(connect.args["start"]) 825 826 # Recursive arm: carry all child columns + increment level + forward each root value. 827 # SELECT * in both arms means WHERE/PRIOR columns are always available without explicit tracking. 828 inner_query = ( 829 exp.select( 830 exp.Column(this=exp.Star(), table=exp.to_identifier("_child_row")), 831 exp.alias_(exp.column("level", "_parent_row") + 1, "level"), 832 *inner_root_cols, 833 ) 834 .from_(source_table.as_("_child_row")) 835 .join(exp.to_table(cte_name).as_("_parent_row"), on=_qualify_connect_pred(connect_pred)) 836 ) 837 838 # Outer SELECT re-projects from the CTE. Synthetic level/root columns are excluded from any 839 # star expansion (level only when not referenced) but kept where explicitly projected. 840 if has_star: 841 except_cols = [] if has_level else [exp.column("level")] 842 except_cols.extend(exp.column(name) for name in root_col_names) 843 star = exp.Star(except_=except_cols) if except_cols else exp.Star() 844 outer_select_exprs: list[exp.Expr] = [ 845 star, 846 *(e for e in base_select_exprs if not e.is_star), 847 ] 848 else: 849 outer_select_exprs = base_select_exprs 850 outer_query = exp.select(*outer_select_exprs).from_(cte_name) 851 if base_where: 852 outer_query = outer_query.where(base_where.this) 853 854 # Attach the CTE, marking the WITH clause recursive. 855 if base_with: 856 outer_query.set("with_", base_with) 857 outer_query = outer_query.with_( 858 cte_name, as_=anchor.union(inner_query, distinct=False), recursive=True, copy=False 859 ) 860 861 for arg, val in expression.args.items(): 862 if val and arg not in _CONNECT_BY_ARGS_TO_SKIP: 863 outer_query.set(arg, val) 864 865 # Strip stale source table qualifiers in one pass; CTEs are child scopes so 866 # find_all_in_scope stays within the outer query only. 867 for col in find_all_in_scope(outer_query, exp.Column, include_udtfs=True): 868 col.set("table", None) 869 870 return outer_query
1638class DuckDBGenerator(generator.Generator): 1639 DAYOFWEEK_NAME = "DAYOFWEEK" 1640 DAYOFWEEK_ZERO_BASED = True 1641 PARAMETER_TOKEN = "$" 1642 NAMED_PLACEHOLDER_TOKEN = "$" 1643 JOIN_HINTS = False 1644 SUPPORTS_MULTI_ARG_CHR = False 1645 TABLE_HINTS = False 1646 QUERY_HINTS = False 1647 LIMIT_FETCH = "LIMIT" 1648 SUPPORTS_NEAREST_JOIN = True 1649 MATCH_CONDITION_IN_ON = True 1650 STRUCT_DELIMITER = ("(", ")") 1651 RENAME_TABLE_WITH_DB = False 1652 NVL2_SUPPORTED = False 1653 SEMI_ANTI_JOIN_WITH_SIDE = False 1654 CAST_TO_INT_ROUNDS = True 1655 SAFE_INT_DIVISION = True 1656 INT_DIV_OPERATOR: str | None = "//" 1657 TABLESAMPLE_KEYWORDS = "USING SAMPLE" 1658 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 1659 LAST_DAY_SUPPORTS_DATE_PART = False 1660 JSON_KEY_VALUE_PAIR_SEP = "," 1661 IGNORE_NULLS_IN_FUNC = True 1662 IGNORE_NULLS_BEFORE_ORDER = False 1663 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 1664 SUPPORTS_CREATE_TABLE_LIKE = False 1665 MULTI_ARG_DISTINCT = False 1666 CAN_IMPLEMENT_ARRAY_ANY = True 1667 SUPPORTS_TO_NUMBER = False 1668 SELECT_KINDS = () 1669 SUPPORTS_DECODE_CASE = False 1670 SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY = False 1671 1672 # USING SAMPLE goes after QUALIFY and before ORDER BY / LIMIT 1673 # https://duckdb.org/docs/preview/sql/query_syntax/sample 1674 AFTER_HAVING_MODIFIER_TRANSFORMS = { 1675 **generator.AFTER_HAVING_MODIFIER_TRANSFORMS, 1676 "sample": lambda self, e: self.sql(e, "sample"), 1677 } 1678 SUPPORTS_WINDOW_EXCLUDE = True 1679 COPY_HAS_INTO_KEYWORD = False 1680 STAR_EXCEPT = "EXCLUDE" 1681 PAD_FILL_PATTERN_IS_REQUIRED = True 1682 ARRAY_SIZE_DIM_REQUIRED: bool | None = False 1683 NORMALIZE_EXTRACT_DATE_PARTS = True 1684 SUPPORTS_LIKE_QUANTIFIERS = False 1685 HISTORICAL_DATA_POST_ALIAS = True 1686 SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD = True 1687 1688 TRANSFORMS = { 1689 **generator.Generator.TRANSFORMS, 1690 exp.AnyValue: _anyvalue_sql, 1691 exp.ApproxDistinct: approx_count_distinct_sql, 1692 exp.ArgMax: _arg_max_or_min_sql, 1693 exp.ArgMin: _arg_max_or_min_sql, 1694 exp.Boolnot: _boolnot_sql, 1695 exp.Booland: _booland_sql, 1696 exp.Boolor: _boolor_sql, 1697 exp.Array: transforms.preprocess( 1698 [transforms.inherit_struct_field_names], 1699 generator=inline_array_unless_query, 1700 ), 1701 exp.ArrayAppend: array_append_sql("LIST_APPEND"), 1702 exp.ArrayCompact: array_compact_sql, 1703 exp.ArrayConstructCompact: lambda self, e: self.sql( 1704 exp.ArrayCompact(this=exp.Array(expressions=e.expressions)) 1705 ), 1706 exp.ArrayConcat: array_concat_sql("LIST_CONCAT"), 1707 exp.ArrayContains: _array_contains_sql, 1708 exp.ArrayOverlaps: _array_overlaps_sql, 1709 exp.ArrayFilter: rename_func("LIST_FILTER"), 1710 exp.ArrayInsert: _array_insert_sql, 1711 exp.ArrayPosition: lambda self, e: ( 1712 self.sql( 1713 exp.Sub( 1714 this=exp.ArrayPosition(this=e.this, expression=e.expression), 1715 expression=exp.Literal.number(1), 1716 ) 1717 ) 1718 if e.args.get("zero_based") 1719 else self.func("ARRAY_POSITION", e.this, e.expression) 1720 ), 1721 exp.ArrayRemoveAt: _array_remove_at_sql, 1722 exp.ArrayRemove: remove_from_array_using_filter, 1723 exp.ArraySort: _array_sort_sql, 1724 exp.ArrayPrepend: array_append_sql("LIST_PREPEND", swap_params=True), 1725 exp.ArraySum: rename_func("LIST_SUM"), 1726 exp.ArrayMax: rename_func("LIST_MAX"), 1727 exp.ArrayMin: rename_func("LIST_MIN"), 1728 exp.Base64DecodeBinary: lambda self, e: _base64_decode_sql(self, e, to_string=False), 1729 exp.Base64DecodeString: lambda self, e: _base64_decode_sql(self, e, to_string=True), 1730 exp.BitwiseAnd: lambda self, e: self._bitwise_op(e, "&"), 1731 exp.BitwiseAndAgg: _bitwise_agg_sql, 1732 exp.BitwiseCount: rename_func("BIT_COUNT"), 1733 exp.BitwiseLeftShift: _bitshift_sql, 1734 exp.BitwiseOr: lambda self, e: self._bitwise_op(e, "|"), 1735 exp.BitwiseOrAgg: _bitwise_agg_sql, 1736 exp.BitwiseRightShift: _bitshift_sql, 1737 exp.BitwiseXorAgg: _bitwise_agg_sql, 1738 exp.CommentColumnConstraint: no_comment_column_constraint_sql, 1739 exp.Corr: lambda self, e: self._corr_sql(e), 1740 exp.CosineDistance: rename_func("LIST_COSINE_DISTANCE"), 1741 exp.CurrentTime: lambda *_: "CURRENT_TIME", 1742 exp.CurrentSchemas: lambda self, e: self.func( 1743 "current_schemas", e.this if e.this else exp.true() 1744 ), 1745 exp.CurrentTimestamp: lambda self, e: ( 1746 self.sql( 1747 exp.AtTimeZone(this=exp.var("CURRENT_TIMESTAMP"), zone=exp.Literal.string("UTC")) 1748 ) 1749 if e.args.get("sysdate") 1750 else "CURRENT_TIMESTAMP" 1751 ), 1752 exp.CurrentVersion: rename_func("version"), 1753 exp.Localtime: unsupported_args("this")(lambda *_: "LOCALTIME"), 1754 exp.DayOfMonth: rename_func("DAYOFMONTH"), 1755 exp.DayOfWeekIso: rename_func("ISODOW"), 1756 exp.DayOfYear: rename_func("DAYOFYEAR"), 1757 exp.Dayname: lambda self, e: ( 1758 self.func("STRFTIME", e.this, exp.Literal.string("%a")) 1759 if e.args.get("abbreviated") 1760 else self.func("DAYNAME", e.this) 1761 ), 1762 exp.Monthname: lambda self, e: ( 1763 self.func("STRFTIME", e.this, exp.Literal.string("%b")) 1764 if e.args.get("abbreviated") 1765 else self.func("MONTHNAME", e.this) 1766 ), 1767 exp.Date: _date_sql, 1768 exp.DateAdd: _date_delta_to_binary_interval_op(), 1769 exp.DateFromParts: _date_from_parts_sql, 1770 exp.DateSub: _date_delta_to_binary_interval_op(), 1771 exp.DateDiff: _date_diff_sql, 1772 exp.DateStrToDate: datestrtodate_sql, 1773 exp.Datetime: no_datetime_sql, 1774 exp.DatetimeDiff: _date_diff_sql, 1775 exp.DatetimeSub: _date_delta_to_binary_interval_op(), 1776 exp.DatetimeAdd: _date_delta_to_binary_interval_op(), 1777 exp.DateToDi: lambda self, e: ( 1778 f"CAST(STRFTIME({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) AS INT)" 1779 ), 1780 exp.Decode: lambda self, e: encode_decode_sql(self, e, "DECODE", replace=False), 1781 exp.HexDecodeString: lambda self, e: self.sql(exp.Decode(this=exp.Unhex(this=e.this))), 1782 exp.DiToDate: lambda self, e: ( 1783 f"CAST(STRPTIME(CAST({self.sql(e, 'this')} AS TEXT), {self.dialect.DATEINT_FORMAT}) AS DATE)" 1784 ), 1785 exp.Encode: lambda self, e: encode_decode_sql(self, e, "ENCODE", replace=False), 1786 exp.EqualNull: lambda self, e: self.sql( 1787 exp.NullSafeEQ(this=e.this, expression=e.expression) 1788 ), 1789 exp.EuclideanDistance: rename_func("LIST_DISTANCE"), 1790 exp.GenerateDateArray: _generate_datetime_array_sql, 1791 exp.GenerateSeries: generate_series_sql("GENERATE_SERIES", "RANGE"), 1792 exp.GenerateTimestampArray: _generate_datetime_array_sql, 1793 exp.Getbit: getbit_sql, 1794 exp.Explode: rename_func("UNNEST"), 1795 exp.IcebergProperty: lambda *_: "", 1796 exp.IsInf: rename_func("ISINF"), 1797 exp.IsNan: rename_func("ISNAN"), 1798 exp.IsNullValue: lambda self, e: self.sql( 1799 exp.func("JSON_TYPE", e.this).eq(exp.Literal.string("NULL")) 1800 ), 1801 exp.IsArray: lambda self, e: self.sql( 1802 exp.func("JSON_TYPE", e.this).eq(exp.Literal.string("ARRAY")) 1803 ), 1804 exp.Ceil: _ceil_floor, 1805 exp.Floor: _ceil_floor, 1806 exp.JSONBExists: rename_func("JSON_EXISTS"), 1807 exp.JSONExtract: _arrow_json_extract_sql, 1808 exp.JSONExtractArray: _json_extract_value_array_sql, 1809 exp.JSONFormat: _json_format_sql, 1810 exp.JSONValueArray: _json_extract_value_array_sql, 1811 exp.Lateral: _explode_to_unnest_sql, 1812 exp.LogicalOr: lambda self, e: self.func("BOOL_OR", _cast_to_boolean(e.this)), 1813 exp.LogicalAnd: lambda self, e: self.func("BOOL_AND", _cast_to_boolean(e.this)), 1814 exp.Select: transforms.preprocess( 1815 [connect_by_to_recursive_cte, _seq_to_range_in_generator] 1816 ), 1817 exp.Seq1: lambda self, e: _seq_sql(self, e, 1), 1818 exp.Seq2: lambda self, e: _seq_sql(self, e, 2), 1819 exp.Seq4: lambda self, e: _seq_sql(self, e, 4), 1820 exp.Seq8: lambda self, e: _seq_sql(self, e, 8), 1821 exp.BoolxorAgg: _boolxor_agg_sql, 1822 exp.MakeInterval: lambda self, e: no_make_interval_sql(self, e, sep=" "), 1823 exp.Initcap: _initcap_sql, 1824 exp.MD5Digest: lambda self, e: self.func("UNHEX", self.func("MD5", e.this)), 1825 exp.Max: rename_func("MAX"), 1826 exp.Min: rename_func("MIN"), 1827 exp.SHA: lambda self, e: _sha_sql(self, e, "SHA1"), 1828 exp.SHA1Digest: lambda self, e: _sha_sql(self, e, "SHA1", is_binary=True), 1829 exp.SHA2: lambda self, e: _sha_sql(self, e, "SHA256"), 1830 exp.SHA2Digest: lambda self, e: _sha_sql(self, e, "SHA256", is_binary=True), 1831 exp.MonthsBetween: months_between_sql, 1832 exp.NextDay: _day_navigation_sql, 1833 exp.PercentileCont: rename_func("QUANTILE_CONT"), 1834 exp.PercentileDisc: rename_func("QUANTILE_DISC"), 1835 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 1836 exp.PreviousDay: _day_navigation_sql, 1837 exp.RegexpILike: lambda self, e: self.func( 1838 "REGEXP_MATCHES", e.this, e.expression, exp.Literal.string("i") 1839 ), 1840 exp.RegexpSplit: rename_func("STR_SPLIT_REGEX"), 1841 exp.RegrValx: _regr_val_sql, 1842 exp.RegrValy: _regr_val_sql, 1843 exp.Return: lambda self, e: self.sql(e, "this"), 1844 exp.ReturnsProperty: lambda self, e: "TABLE" if isinstance(e.this, exp.Schema) else "", 1845 exp.StrToUnix: lambda self, e: self.func( 1846 "EPOCH", self.func("STRPTIME", e.this, self.format_time(e)) 1847 ), 1848 exp.Struct: _struct_sql, 1849 exp.Transform: rename_func("LIST_TRANSFORM"), 1850 exp.TimeAdd: _date_delta_to_binary_interval_op(), 1851 exp.TimeSub: _date_delta_to_binary_interval_op(), 1852 exp.Time: no_time_sql, 1853 exp.TimeDiff: _timediff_sql, 1854 exp.TimestampAdd: _date_delta_to_binary_interval_op(), 1855 exp.TimestampSub: _date_delta_to_binary_interval_op(), 1856 exp.TimeStrToDate: lambda self, e: self.sql(exp.cast(e.this, exp.DType.DATE)), 1857 exp.TimeStrToTime: timestrtotime_sql, 1858 exp.TimeStrToUnix: lambda self, e: self.func( 1859 "EPOCH", exp.cast(e.this, exp.DType.TIMESTAMP) 1860 ), 1861 exp.TimeToStr: lambda self, e: self.func("STRFTIME", e.this, self.format_time(e)), 1862 exp.ToBoolean: _to_boolean_sql, 1863 exp.ToVariant: lambda self, e: self.sql( 1864 exp.cast(e.this, exp.DataType.from_str("VARIANT", dialect="duckdb")) 1865 ), 1866 exp.TimeToUnix: rename_func("EPOCH"), 1867 exp.TsOrDiToDi: lambda self, e: ( 1868 f"CAST(SUBSTR(REPLACE(CAST({self.sql(e, 'this')} AS TEXT), '-', ''), 1, 8) AS INT)" 1869 ), 1870 exp.TsOrDsAdd: _date_delta_to_binary_interval_op(), 1871 exp.TsOrDsDiff: lambda self, e: self.func( 1872 "DATE_DIFF", 1873 exp.Literal.string(e.unit or "DAY"), 1874 exp.cast(e.expression, exp.DType.TIMESTAMP), 1875 exp.cast(e.this, exp.DType.TIMESTAMP), 1876 ), 1877 exp.UnixMicros: lambda self, e: self.func("EPOCH_US", _implicit_datetime_cast(e.this)), 1878 exp.UnixMillis: lambda self, e: self.func("EPOCH_MS", _implicit_datetime_cast(e.this)), 1879 exp.UnixSeconds: lambda self, e: self.sql( 1880 exp.cast(self.func("EPOCH", _implicit_datetime_cast(e.this)), exp.DType.BIGINT) 1881 ), 1882 exp.UnixToStr: lambda self, e: self.func( 1883 "STRFTIME", self.func("TO_TIMESTAMP", e.this), self.format_time(e) 1884 ), 1885 exp.UnixToTime: _unix_to_time_sql, 1886 exp.UnixToTimeStr: lambda self, e: f"CAST(TO_TIMESTAMP({self.sql(e, 'this')}) AS TEXT)", 1887 exp.VariancePop: rename_func("VAR_POP"), 1888 exp.WeekOfYear: rename_func("WEEKOFYEAR"), 1889 exp.YearOfWeek: lambda self, e: self.sql( 1890 exp.Extract( 1891 this=exp.Var(this="ISOYEAR"), 1892 expression=e.this, 1893 ) 1894 ), 1895 exp.YearOfWeekIso: lambda self, e: self.sql( 1896 exp.Extract( 1897 this=exp.Var(this="ISOYEAR"), 1898 expression=e.this, 1899 ) 1900 ), 1901 exp.Xor: _xor_sql, 1902 exp.JSONObjectAgg: rename_func("JSON_GROUP_OBJECT"), 1903 exp.JSONArray: _json_constructor_sql, 1904 exp.JSONObject: _json_constructor_sql, 1905 exp.JSONBObjectAgg: rename_func("JSON_GROUP_OBJECT"), 1906 exp.DateBin: rename_func("TIME_BUCKET"), 1907 exp.LastDay: _last_day_sql, 1908 } 1909 1910 SUPPORTED_JSON_PATH_PARTS = { 1911 exp.JSONPathKey, 1912 exp.JSONPathRoot, 1913 exp.JSONPathSubscript, 1914 exp.JSONPathWildcard, 1915 } 1916 1917 TYPE_MAPPING = { 1918 **generator.Generator.TYPE_MAPPING, 1919 exp.DType.BINARY: "BLOB", 1920 exp.DType.BPCHAR: "TEXT", 1921 exp.DType.CHAR: "TEXT", 1922 exp.DType.DATETIME: "TIMESTAMP", 1923 exp.DType.DECFLOAT: "DECIMAL", 1924 exp.DType.FLOAT: "REAL", 1925 exp.DType.JSONB: "JSON", 1926 exp.DType.NCHAR: "TEXT", 1927 exp.DType.NVARCHAR: "TEXT", 1928 exp.DType.UINT: "UINTEGER", 1929 exp.DType.VARBINARY: "BLOB", 1930 exp.DType.ROWVERSION: "BLOB", 1931 exp.DType.VARCHAR: "TEXT", 1932 exp.DType.TIMESTAMPLTZ: "TIMESTAMPTZ", 1933 exp.DType.TIMESTAMPNTZ: "TIMESTAMP", 1934 exp.DType.TIMESTAMP_S: "TIMESTAMP_S", 1935 exp.DType.TIMESTAMP_MS: "TIMESTAMP_MS", 1936 exp.DType.TIMESTAMP_NS: "TIMESTAMP_NS", 1937 exp.DType.BIGDECIMAL: "DECIMAL", 1938 } 1939 1940 TYPE_PARAM_SETTINGS = { 1941 **generator.Generator.TYPE_PARAM_SETTINGS, 1942 exp.DType.BIGDECIMAL: ((38, 5), (38, 38)), 1943 exp.DType.DECFLOAT: ((38, 5), (38, 38)), 1944 } 1945 1946 # https://github.com/duckdb/duckdb/blob/ff7f24fd8e3128d94371827523dae85ebaf58713/third_party/libpg_query/grammar/keywords/reserved_keywords.list#L1-L77 1947 RESERVED_KEYWORDS = { 1948 "array", 1949 "analyse", 1950 "union", 1951 "all", 1952 "when", 1953 "in", 1954 "default", 1955 "create", 1956 "window", 1957 "asymmetric", 1958 "to", 1959 "else", 1960 "localtime", 1961 "from", 1962 "end", 1963 "select", 1964 "current_date", 1965 "foreign", 1966 "with", 1967 "grant", 1968 "session_user", 1969 "or", 1970 "except", 1971 "references", 1972 "fetch", 1973 "limit", 1974 "group", 1975 "leading", 1976 "into", 1977 "collate", 1978 "offset", 1979 "do", 1980 "then", 1981 "localtimestamp", 1982 "check", 1983 "lateral", 1984 "current_role", 1985 "where", 1986 "asc", 1987 "placing", 1988 "desc", 1989 "user", 1990 "unique", 1991 "initially", 1992 "column", 1993 "both", 1994 "some", 1995 "as", 1996 "any", 1997 "only", 1998 "deferrable", 1999 "null", 2000 "current_time", 2001 "true", 2002 "table", 2003 "case", 2004 "trailing", 2005 "variadic", 2006 "for", 2007 "on", 2008 "distinct", 2009 "false", 2010 "not", 2011 "constraint", 2012 "current_timestamp", 2013 "returning", 2014 "primary", 2015 "intersect", 2016 "having", 2017 "analyze", 2018 "current_user", 2019 "and", 2020 "cast", 2021 "symmetric", 2022 "using", 2023 "order", 2024 "current_catalog", 2025 "describe", 2026 "lambda", 2027 "pivot", 2028 "pivot_longer", 2029 "pivot_wider", 2030 "qualify", 2031 "show", 2032 "summarize", 2033 "unpivot", 2034 "anti", 2035 "asof", 2036 "at", 2037 "authorization", 2038 "binary", 2039 "by", 2040 "collation", 2041 "columns", 2042 "concurrently", 2043 "cross", 2044 "freeze", 2045 "full", 2046 "generated", 2047 "glob", 2048 "ilike", 2049 "inner", 2050 "is", 2051 "isnull", 2052 "join", 2053 "left", 2054 "like", 2055 "map", 2056 "natural", 2057 "notnull", 2058 "outer", 2059 "overlaps", 2060 "positional", 2061 "right", 2062 "semi", 2063 "similar", 2064 "struct", 2065 "tablesample", 2066 "try_cast", 2067 "tuple", 2068 "unpack", 2069 "verbose", 2070 } 2071 2072 UNWRAPPED_INTERVAL_VALUES = (exp.Literal, exp.Paren) 2073 2074 # DuckDB doesn't generally support CREATE TABLE .. properties 2075 # https://duckdb.org/docs/sql/statements/create_table.html 2076 # There are a few exceptions (e.g. temporary tables) which are supported or 2077 # can be transpiled to DuckDB, so we explicitly override them accordingly 2078 PROPERTIES_LOCATION = { 2079 **{ 2080 prop: exp.Properties.Location.UNSUPPORTED 2081 for prop in generator.Generator.PROPERTIES_LOCATION 2082 }, 2083 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 2084 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 2085 exp.ReturnsProperty: exp.Properties.Location.POST_ALIAS, 2086 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 2087 exp.TriggerProperties: exp.Properties.Location.POST_EXPRESSION, 2088 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 2089 } 2090 2091 IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS: t.ClassVar = _IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS 2092 2093 # Template for ZIPF transpilation - placeholders get replaced with actual parameters 2094 ZIPF_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2095 """ 2096 WITH rand AS (SELECT :random_expr AS r), 2097 weights AS ( 2098 SELECT i, 1.0 / POWER(i, :s) AS w 2099 FROM RANGE(1, :n + 1) AS t(i) 2100 ), 2101 cdf AS ( 2102 SELECT i, SUM(w) OVER (ORDER BY i) / SUM(w) OVER () AS p 2103 FROM weights 2104 ) 2105 SELECT MIN(i) 2106 FROM cdf 2107 WHERE p >= (SELECT r FROM rand) 2108 """ 2109 ) 2110 2111 # Template for NORMAL transpilation using Box-Muller transform 2112 # mean + (stddev * sqrt(-2 * ln(u1)) * cos(2 * pi * u2)) 2113 NORMAL_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2114 ":mean + (:stddev * SQRT(-2 * LN(GREATEST(:u1, 1e-10))) * COS(2 * PI() * :u2))" 2115 ) 2116 2117 # Template for generating a seeded pseudo-random value in [0, 1) from a hash 2118 SEEDED_RANDOM_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2119 "(ABS(HASH(:seed)) % 1000000) / 1000000.0" 2120 ) 2121 2122 # Template for generating signed and unsigned SEQ values within a specified range 2123 SEQ_UNSIGNED: t.ClassVar[exp.Expr] = _SEQ_UNSIGNED 2124 SEQ_SIGNED: t.ClassVar[exp.Expr] = _SEQ_SIGNED 2125 2126 # Template for MAP_CAT transpilation - Snowflake semantics: 2127 # 1. Returns NULL if either input is NULL 2128 # 2. For duplicate keys, prefers non-NULL value (COALESCE(m2[k], m1[k])) 2129 # 3. Filters out entries with NULL values from the result 2130 MAPCAT_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2131 """ 2132 CASE 2133 WHEN :map1 IS NULL OR :map2 IS NULL THEN NULL 2134 ELSE MAP_FROM_ENTRIES(LIST_FILTER(LIST_TRANSFORM( 2135 LIST_DISTINCT(LIST_CONCAT(MAP_KEYS(:map1), MAP_KEYS(:map2))), 2136 __k -> STRUCT_PACK(key := __k, value := COALESCE(:map2[__k], :map1[__k])) 2137 ), __x -> __x.value IS NOT NULL)) 2138 END 2139 """ 2140 ) 2141 2142 # Mappings for EXTRACT/DATE_PART transpilation 2143 # Maps Snowflake specifiers unsupported in DuckDB to strftime format codes 2144 EXTRACT_STRFTIME_MAPPINGS: t.ClassVar[dict[str, tuple[str, str]]] = { 2145 "WEEKISO": ("%V", "INTEGER"), 2146 "YEAROFWEEK": ("%G", "INTEGER"), 2147 "YEAROFWEEKISO": ("%G", "INTEGER"), 2148 "NANOSECOND": ("%n", "BIGINT"), 2149 } 2150 2151 # Maps epoch-based specifiers to DuckDB epoch functions 2152 EXTRACT_EPOCH_MAPPINGS: t.ClassVar[dict[str, str]] = { 2153 "EPOCH_SECOND": "EPOCH", 2154 "EPOCH_MILLISECOND": "EPOCH_MS", 2155 "EPOCH_MICROSECOND": "EPOCH_US", 2156 "EPOCH_NANOSECOND": "EPOCH_NS", 2157 } 2158 2159 # Template for BITMAP_CONSTRUCT_AGG transpilation 2160 # 2161 # BACKGROUND: 2162 # Snowflake's BITMAP_CONSTRUCT_AGG aggregates integers into a compact binary bitmap. 2163 # Supports values in range 0-32767, this version returns NULL if any value is out of range 2164 # See: https://docs.snowflake.com/en/sql-reference/functions/bitmap_construct_agg 2165 # See: https://docs.snowflake.com/en/user-guide/querying-bitmaps-for-distinct-counts 2166 # 2167 # Snowflake uses two different formats based on the number of unique values: 2168 # 2169 # Format 1 - Small bitmap (< 5 unique values): Length of 10 bytes 2170 # Bytes 0-1: Count of values as 2-byte big-endian integer (e.g., 3 values = 0x0003) 2171 # Bytes 2-9: Up to 4 values, each as 2-byte little-endian integers, zero-padded to 8 bytes 2172 # Example: Values [1, 2, 3] -> 0x0003 0100 0200 0300 0000 (hex) 2173 # count v1 v2 v3 pad 2174 # 2175 # Format 2 - Large bitmap (>= 5 unique values): Length of 10 + (2 * count) bytes 2176 # Bytes 0-9: Fixed header 0x08 followed by 9 zero bytes 2177 # Bytes 10+: Each value as 2-byte little-endian integer (no padding) 2178 # Example: Values [1,2,3,4,5] -> 0x08 00000000 00000000 00 0100 0200 0300 0400 0500 2179 # hdr ----9 zero bytes---- v1 v2 v3 v4 v5 2180 # 2181 # TEMPLATE STRUCTURE 2182 # 2183 # Phase 1 - Innermost subquery: Data preparation 2184 # SELECT LIST_SORT(...) AS l 2185 # - Aggregates all input values into a list, remove NULLs, duplicates and sorts 2186 # Result: Clean, sorted list of unique non-null integers stored as 'l' 2187 # 2188 # Phase 2 - Middle subquery: Hex string construction 2189 # LIST_TRANSFORM(...) 2190 # - Converts each integer to 2-byte little-endian hex representation 2191 # - & 255 extracts low byte, >> 8 extracts high byte 2192 # - LIST_REDUCE: Concatenates all hex pairs into single string 'h' 2193 # Result: Hex string of all values 2194 # 2195 # Phase 3 - Outer SELECT: Final bitmap assembly 2196 # LENGTH(l) < 5: 2197 # - Small format: 2-byte count (big-endian via %04X) + values + zero padding 2198 # LENGTH(l) >= 5: 2199 # - Large format: Fixed 10-byte header + values (no padding needed) 2200 # Result: Complete binary bitmap as BLOB 2201 # 2202 BITMAP_CONSTRUCT_AGG_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2203 """ 2204 SELECT CASE 2205 WHEN l IS NULL OR LENGTH(l) = 0 THEN NULL 2206 WHEN LENGTH(l) != LENGTH(LIST_FILTER(l, __v -> __v BETWEEN 0 AND 32767)) THEN NULL 2207 WHEN LENGTH(l) < 5 THEN UNHEX(PRINTF('%04X', LENGTH(l)) || h || REPEAT('00', GREATEST(0, 4 - LENGTH(l)) * 2)) 2208 ELSE UNHEX('08000000000000000000' || h) 2209 END 2210 FROM ( 2211 SELECT l, COALESCE(LIST_REDUCE( 2212 LIST_TRANSFORM(l, __x -> PRINTF('%02X%02X', CAST(__x AS INT) & 255, (CAST(__x AS INT) >> 8) & 255)), 2213 (__a, __b) -> __a || __b, '' 2214 ), '') AS h 2215 FROM (SELECT LIST_SORT(LIST_DISTINCT(LIST(:arg) FILTER(NOT :arg IS NULL))) AS l) 2216 ) 2217 """ 2218 ) 2219 2220 # Template for RANDSTR transpilation - placeholders get replaced with actual parameters 2221 RANDSTR_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2222 f""" 2223 SELECT LISTAGG( 2224 SUBSTRING( 2225 '{RANDSTR_CHAR_POOL}', 2226 1 + CAST(FLOOR(random_value * 62) AS INT), 2227 1 2228 ), 2229 '' 2230 ) 2231 FROM ( 2232 SELECT (ABS(HASH(i + :seed)) % 1000) / 1000.0 AS random_value 2233 FROM RANGE(:length) AS t(i) 2234 ) 2235 """, 2236 ) 2237 2238 # Template for MINHASH transpilation 2239 # Computes k minimum hash values across aggregated data using DuckDB list functions 2240 # Returns JSON matching Snowflake format: {"state": [...], "type": "minhash", "version": 1} 2241 MINHASH_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2242 """ 2243 SELECT JSON_OBJECT('state', LIST(min_h ORDER BY seed), 'type', 'minhash', 'version', 1) 2244 FROM ( 2245 SELECT seed, LIST_MIN(LIST_TRANSFORM(vals, __v -> HASH(CAST(__v AS VARCHAR) || CAST(seed AS VARCHAR)))) AS min_h 2246 FROM (SELECT LIST(:expr) AS vals), RANGE(0, :k) AS t(seed) 2247 ) 2248 """, 2249 ) 2250 2251 # Template for MINHASH_COMBINE transpilation 2252 # Combines multiple minhash signatures by taking element-wise minimum 2253 MINHASH_COMBINE_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2254 """ 2255 SELECT JSON_OBJECT('state', LIST(min_h ORDER BY idx), 'type', 'minhash', 'version', 1) 2256 FROM ( 2257 SELECT 2258 pos AS idx, 2259 MIN(val) AS min_h 2260 FROM 2261 UNNEST(LIST(:expr)) AS _(sig), 2262 UNNEST(CAST(sig -> 'state' AS UBIGINT[])) WITH ORDINALITY AS t(val, pos) 2263 GROUP BY pos 2264 ) 2265 """, 2266 ) 2267 2268 # Template for APPROXIMATE_SIMILARITY transpilation 2269 # Computes multi-way Jaccard similarity: fraction of positions where ALL signatures agree 2270 APPROXIMATE_SIMILARITY_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2271 """ 2272 SELECT CAST(SUM(CASE WHEN num_distinct = 1 THEN 1 ELSE 0 END) AS DOUBLE) / COUNT(*) 2273 FROM ( 2274 SELECT pos, COUNT(DISTINCT h) AS num_distinct 2275 FROM ( 2276 SELECT h, pos 2277 FROM UNNEST(LIST(:expr)) AS _(sig), 2278 UNNEST(CAST(sig -> 'state' AS UBIGINT[])) WITH ORDINALITY AS s(h, pos) 2279 ) 2280 GROUP BY pos 2281 ) 2282 """, 2283 ) 2284 2285 # Template for ARRAYS_ZIP transpilation 2286 # Snowflake pads to longest array; DuckDB LIST_ZIP truncates to shortest 2287 # Uses RANGE + indexing to match Snowflake behavior 2288 ARRAYS_ZIP_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2289 """ 2290 CASE WHEN :null_check THEN NULL 2291 WHEN :all_empty_check THEN [:empty_struct] 2292 ELSE LIST_TRANSFORM(RANGE(0, :max_len), __i -> :transform_struct) 2293 END 2294 """, 2295 ) 2296 2297 UUID_V5_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2298 """ 2299 (SELECT 2300 LOWER( 2301 SUBSTR(h, 1, 8) || '-' || 2302 SUBSTR(h, 9, 4) || '-' || 2303 '5' || SUBSTR(h, 14, 3) || '-' || 2304 PRINTF('%02x', CAST('0x' || SUBSTR(h, 17, 2) AS INT) & 63 | 128) || SUBSTR(h, 19, 2) || '-' || 2305 SUBSTR(h, 21, 12) 2306 ) 2307 FROM ( 2308 SELECT SUBSTR(SHA1(UNHEX(REPLACE(:namespace, '-', '')) || ENCODE(:name, 'utf8')), 1, 32) AS h 2309 )) 2310 """ 2311 ) 2312 2313 # Shared bag semantics outer frame for ARRAY_EXCEPT and ARRAY_INTERSECTION. 2314 # Each element is paired with its 1-based position via LIST_ZIP, then filtered 2315 # by a comparison operator (supplied via :cond) that determines the operation: 2316 # EXCEPT (>): keep the N-th occurrence only if N > count in arr2 2317 # e.g. [2,2,2] EXCEPT [2,2] -> [2] 2318 # INTERSECTION (<=): keep the N-th occurrence only if N <= count in arr2 2319 # e.g. [2,2,2] INTERSECT [2,2] -> [2,2] 2320 # IS NOT DISTINCT FROM is used for NULL-safe element comparison. 2321 ARRAY_BAG_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2322 """ 2323 CASE 2324 WHEN :arr1 IS NULL OR :arr2 IS NULL THEN NULL 2325 ELSE LIST_TRANSFORM( 2326 LIST_FILTER( 2327 LIST_ZIP(:arr1, GENERATE_SERIES(1, LEN(:arr1))), 2328 pair -> :cond 2329 ), 2330 pair -> pair[0] 2331 ) 2332 END 2333 """ 2334 ) 2335 2336 ARRAY_EXCEPT_CONDITION: t.ClassVar[exp.Expr] = exp.maybe_parse( 2337 "LEN(LIST_FILTER(:arr1[1:pair[1]], e -> e IS NOT DISTINCT FROM pair[0]))" 2338 " > LEN(LIST_FILTER(:arr2, e -> e IS NOT DISTINCT FROM pair[0]))" 2339 ) 2340 2341 ARRAY_INTERSECTION_CONDITION: t.ClassVar[exp.Expr] = exp.maybe_parse( 2342 "LEN(LIST_FILTER(:arr1[1:pair[1]], e -> e IS NOT DISTINCT FROM pair[0]))" 2343 " <= LEN(LIST_FILTER(:arr2, e -> e IS NOT DISTINCT FROM pair[0]))" 2344 ) 2345 2346 # Set semantics for ARRAY_EXCEPT. Deduplicates arr1 via LIST_DISTINCT, then 2347 # filters out any element that appears at least once in arr2. 2348 # e.g. [1,1,2,3] EXCEPT [1] -> [2,3] 2349 # IS NOT DISTINCT FROM is used for NULL-safe element comparison. 2350 ARRAY_EXCEPT_SET_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2351 """ 2352 CASE 2353 WHEN :arr1 IS NULL OR :arr2 IS NULL THEN NULL 2354 ELSE LIST_FILTER( 2355 LIST_DISTINCT(:arr1), 2356 e -> LEN(LIST_FILTER(:arr2, x -> x IS NOT DISTINCT FROM e)) = 0 2357 ) 2358 END 2359 """ 2360 ) 2361 2362 # BigQuery's `x IN UNNEST(arr)` NULL semantics: 2363 # NULL IN UNNEST([1, 2]) -> NULL 2364 # 3 IN UNNEST([1, NULL]) -> NULL 2365 # 3 IN UNNEST([1, 2]) -> FALSE 2366 # 1 IN UNNEST(NULL) -> FALSE (not NULL) 2367 # 1 IN UNNEST([]) -> FALSE 2368 # The default `IN (SELECT UNNEST(...))` rewrite creates a correlated subquery 2369 # that DuckDB rejects inside non-inner joins, so a CASE expression is used instead. 2370 IN_UNNEST_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2371 """ 2372 CASE 2373 WHEN :arr IS NULL OR ARRAY_LENGTH(:arr) = 0 THEN FALSE 2374 WHEN ARRAY_CONTAINS(:arr, :value) THEN TRUE 2375 WHEN :value IS NULL OR ARRAY_LENGTH(:arr) <> LIST_COUNT(:arr) THEN NULL 2376 ELSE FALSE 2377 END 2378 """ 2379 ) 2380 2381 STRTOK_TO_ARRAY_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2382 """ 2383 CASE WHEN :delimiter IS NULL THEN NULL 2384 ELSE LIST_FILTER( 2385 REGEXP_SPLIT_TO_ARRAY(:string, CASE WHEN :delimiter = '' THEN '.^' ELSE CONCAT('[', :escaped, ']') END), 2386 x -> NOT x = '' 2387 ) END 2388 """ 2389 ) 2390 2391 # Template for STRTOK function transpilation 2392 # 2393 # DuckDB itself doesn't have a strtok function. This handles the transpilation from Snowflake to DuckDB. 2394 # We may need to adjust this if we want to support transpilation from other dialects 2395 # 2396 # CASE 2397 # -- Snowflake: empty delimiter + empty input string -> NULL 2398 # WHEN delimiter = '' AND input_str = '' THEN NULL 2399 # 2400 # -- Snowflake: empty delimiter + non-empty input string -> treats whole input as 1 token -> return input string if index is 1 2401 # WHEN delimiter = '' AND index = 1 THEN input_str 2402 # 2403 # -- Snowflake: empty delimiter + non-empty input string -> treats whole input as 1 token -> return NULL if index is not 1 2404 # WHEN delimiter = '' THEN NULL 2405 # 2406 # -- Snowflake: negative indices return NULL 2407 # WHEN index < 0 THEN NULL 2408 # 2409 # -- Snowflake: return NULL if any argument is NULL 2410 # WHEN input_str IS NULL OR delimiter IS NULL OR index IS NULL THEN NULL 2411 # 2412 # 2413 # ELSE LIST_FILTER( 2414 # REGEXP_SPLIT_TO_ARRAY( 2415 # input_str, 2416 # CASE 2417 # -- if delimiter is '', we don't want to surround it with '[' and ']' as '[]' is invalid for DuckDB 2418 # WHEN delimiter = '' THEN '' 2419 # 2420 # -- handle problematic regex characters in delimiter with REGEXP_REPLACE 2421 # -- turn delimiter into a regex char set, otherwise DuckDB will match in order, which we don't want 2422 # ELSE '[' || REGEXP_REPLACE(delimiter, problematic_char_set, '\\\1', 'g') || ']' 2423 # END 2424 # ), 2425 # 2426 # -- Snowflake: don't return empty strings 2427 # x -> NOT x = '' 2428 # )[index] 2429 # END 2430 STRTOK_TEMPLATE: t.ClassVar[exp.Expr] = exp.maybe_parse( 2431 """ 2432 CASE 2433 WHEN :delimiter = '' AND :string = '' THEN NULL 2434 WHEN :delimiter = '' AND :part_index = 1 THEN :string 2435 WHEN :delimiter = '' THEN NULL 2436 WHEN :part_index < 0 THEN NULL 2437 WHEN :string IS NULL OR :delimiter IS NULL OR :part_index IS NULL THEN NULL 2438 ELSE :base_func 2439 END 2440 """ 2441 ) 2442 2443 # Snowflake AUTO detects 3 DATE formats: YYYY-MM-DD (ISO-8601), MM/DD/YYYY, DD-MON-YYYY. 2444 # DuckDB TRY_CAST handles ISO-8601 natively. For the other two formats we use CONTAINS('/') 2445 # and REGEXP_MATCHES('[A-Za-z]') as heuristics — these correctly handle single-digit months 2446 # and days (e.g. 1/5/2020, 5-JAN-2020) where a positional char check would fail. 2447 # Ref: https://docs.snowflake.com/en/sql-reference/date-time-input-output#date-formats 2448 _TRYCAST_DATE_SLASH_FMT = "%m/%d/%Y" 2449 _TRYCAST_DATE_MON_FMT = "%d-%b-%Y" 2450 2451 def datatype_sql(self, expression: exp.DataType) -> str: 2452 if expression.is_type(exp.DType.ARRAY): 2453 return f"{self.expressions(expression, flat=True)}[{self.expressions(expression, key='values', flat=True)}]" 2454 2455 # Modifiers are not supported for TIME, [TIME | TIMESTAMP] WITH TIME ZONE 2456 if expression.is_type( 2457 exp.DType.TIME, exp.DType.TIMETZ, exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ 2458 ): 2459 expression.set("expressions", None) 2460 2461 return super().datatype_sql(expression) 2462 2463 def _array_bag_sql(self, condition: exp.Expr, arr1: exp.Expr, arr2: exp.Expr) -> str: 2464 cond = exp.Paren(this=exp.replace_placeholders(condition, arr1=arr1, arr2=arr2)) 2465 return self.sql( 2466 exp.replace_placeholders(self.ARRAY_BAG_TEMPLATE, arr1=arr1, arr2=arr2, cond=cond) 2467 ) 2468 2469 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 2470 """ 2471 Transform Snowflake's TIME_SLICE to DuckDB's time_bucket. 2472 2473 Snowflake: TIME_SLICE(date_expr, slice_length, 'UNIT' [, 'START'|'END']) 2474 DuckDB: time_bucket(INTERVAL 'slice_length' UNIT, date_expr, origin) 2475 2476 Snowflake aligns slices to the 1970-01-01 epoch, so an explicit origin is 2477 required because DuckDB's default origin differs. For 'END' kind, add the 2478 interval to get the next slice's start; for DATE input, cast back to DATE. 2479 """ 2480 date_expr = expression.this 2481 slice_length = expression.expression 2482 # Normalize unit aliases (e.g. W/WK/WOY -> WEEK) so the interval and origin agree 2483 unit = map_date_part(expression.unit, self.dialect) 2484 kind = expression.text("kind").upper() 2485 2486 interval_expr = exp.Interval(this=slice_length, unit=unit) 2487 2488 origin = expression.args.get("origin") 2489 if origin is None: 2490 # Snowflake aligns to 1970-01-01; WEEK to the Monday of the epoch week (WEEK_START=0) 2491 origin = exp.Literal.string( 2492 "1969-12-29" if unit and unit.name.upper() == "WEEK" else "1970-01-01" 2493 ) 2494 # A DATE origin keeps a DATE input a DATE; DuckDB widens it for TIMESTAMP inputs 2495 time_bucket_expr = exp.func( 2496 "time_bucket", interval_expr, date_expr, exp.cast(origin, exp.DType.DATE) 2497 ) 2498 2499 if kind != "END": 2500 return self.sql(time_bucket_expr) 2501 2502 add_expr = exp.Add(this=time_bucket_expr, expression=interval_expr.copy()) 2503 2504 # DuckDB widens DATE to TIMESTAMP when adding intervals, so cast back 2505 if date_expr.is_type(exp.DType.DATE): 2506 return self.sql(exp.cast(add_expr, exp.DType.DATE)) 2507 2508 return self.sql(add_expr) 2509 2510 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 2511 # DuckDB has no Unicode escape strings and doesn't read \u in a string, so the escapes 2512 # are decoded into the characters, e.g. U&'d\0061t\0061' and U&'d!+000061ta' UESCAPE '!' 2513 # are both 'data' 2514 escape = expression.args.get("escape") 2515 text = decode_unicode_escapes( 2516 expression.name, escape.name if isinstance(escape, exp.Expr) else "\\" 2517 ) 2518 return self.sql(exp.Literal.string(text)) 2519 2520 def bytestring_sql(self, expression: exp.ByteString) -> str: 2521 if not expression.args.get("is_bytes"): 2522 return super().bytestring_sql(expression) 2523 2524 # Each char is a byte. Casting to BLOB decodes \xHH, so everything but printable ASCII 2525 # (including the backslash itself) is written as such 2526 text = "".join( 2527 ch if ch.isascii() and ch.isprintable() and ch != "\\" else f"\\x{ord(ch):02x}" 2528 for ch in expression.this 2529 ) 2530 return self.sql(exp.cast(exp.Literal.string(text), exp.DType.BINARY)) 2531 2532 def bitmapbucketnumber_sql(self, expression: exp.BitmapBucketNumber) -> str: 2533 """ 2534 Transpile BITMAP_BUCKET_NUMBER function from Snowflake to DuckDB equivalent. 2535 2536 Snowflake's BITMAP_BUCKET_NUMBER returns a 1-based bucket identifier where: 2537 - Each bucket covers 32,768 values 2538 - Bucket numbering starts at 1 2539 - Formula: ((value - 1) // 32768) + 1 for positive values 2540 2541 For non-positive values (0 and negative), we use value // 32768 to avoid 2542 producing bucket 0 or positive bucket IDs for negative inputs. 2543 """ 2544 value = expression.this 2545 2546 positive_formula = ((value - 1) // 32768) + 1 2547 non_positive_formula = value // 32768 2548 2549 # CASE WHEN value > 0 THEN ((value - 1) // 32768) + 1 ELSE value // 32768 END 2550 case_expr = ( 2551 exp.case() 2552 .when(exp.GT(this=value, expression=exp.Literal.number(0)), positive_formula) 2553 .else_(non_positive_formula) 2554 ) 2555 return self.sql(case_expr) 2556 2557 def bitmapbitposition_sql(self, expression: exp.BitmapBitPosition) -> str: 2558 """ 2559 Transpile Snowflake's BITMAP_BIT_POSITION to DuckDB CASE expression. 2560 2561 Snowflake's BITMAP_BIT_POSITION behavior: 2562 - For n <= 0: returns ABS(n) % 32768 2563 - For n > 0: returns (n - 1) % 32768 (maximum return value is 32767) 2564 """ 2565 this = expression.this 2566 2567 return self.sql( 2568 exp.Mod( 2569 this=exp.Paren( 2570 this=exp.If( 2571 this=exp.GT(this=this, expression=exp.Literal.number(0)), 2572 true=this - exp.Literal.number(1), 2573 false=exp.Abs(this=this), 2574 ) 2575 ), 2576 expression=MAX_BIT_POSITION, 2577 ) 2578 ) 2579 2580 def bitmapconstructagg_sql(self, expression: exp.BitmapConstructAgg) -> str: 2581 """ 2582 Transpile Snowflake's BITMAP_CONSTRUCT_AGG to DuckDB equivalent. 2583 Uses a pre-parsed template with placeholders replaced by expression nodes. 2584 2585 Snowflake bitmap format: 2586 - Small (< 5 unique values): 2-byte count (big-endian) + values (little-endian) + padding to 10 bytes 2587 - Large (>= 5 unique values): 10-byte header (0x08 + 9 zeros) + values (little-endian) 2588 """ 2589 arg = expression.this 2590 return ( 2591 f"({self.sql(exp.replace_placeholders(self.BITMAP_CONSTRUCT_AGG_TEMPLATE, arg=arg))})" 2592 ) 2593 2594 def getignorecase_sql(self, expression: exp.GetIgnoreCase) -> str: 2595 self.unsupported("DuckDB does not support the GET_IGNORE_CASE() function") 2596 return self.function_fallback_sql(expression) 2597 2598 def compress_sql(self, expression: exp.Compress) -> str: 2599 self.unsupported("DuckDB does not support the COMPRESS() function") 2600 return self.function_fallback_sql(expression) 2601 2602 def encrypt_sql(self, expression: exp.Encrypt) -> str: 2603 self.unsupported("ENCRYPT is not supported in DuckDB") 2604 return self.function_fallback_sql(expression) 2605 2606 def decrypt_sql(self, expression: exp.Decrypt) -> str: 2607 func_name = "TRY_DECRYPT" if expression.args.get("safe") else "DECRYPT" 2608 self.unsupported(f"{func_name} is not supported in DuckDB") 2609 return self.function_fallback_sql(expression) 2610 2611 def decryptraw_sql(self, expression: exp.DecryptRaw) -> str: 2612 func_name = "TRY_DECRYPT_RAW" if expression.args.get("safe") else "DECRYPT_RAW" 2613 self.unsupported(f"{func_name} is not supported in DuckDB") 2614 return self.function_fallback_sql(expression) 2615 2616 def encryptraw_sql(self, expression: exp.EncryptRaw) -> str: 2617 self.unsupported("ENCRYPT_RAW is not supported in DuckDB") 2618 return self.function_fallback_sql(expression) 2619 2620 def parseurl_sql(self, expression: exp.ParseUrl) -> str: 2621 self.unsupported("PARSE_URL is not supported in DuckDB") 2622 return self.function_fallback_sql(expression) 2623 2624 def parseip_sql(self, expression: exp.ParseIp) -> str: 2625 self.unsupported("PARSE_IP is not supported in DuckDB") 2626 return self.function_fallback_sql(expression) 2627 2628 def decompressstring_sql(self, expression: exp.DecompressString) -> str: 2629 self.unsupported("DECOMPRESS_STRING is not supported in DuckDB") 2630 return self.function_fallback_sql(expression) 2631 2632 def decompressbinary_sql(self, expression: exp.DecompressBinary) -> str: 2633 self.unsupported("DECOMPRESS_BINARY is not supported in DuckDB") 2634 return self.function_fallback_sql(expression) 2635 2636 def jarowinklersimilarity_sql(self, expression: exp.JarowinklerSimilarity) -> str: 2637 this = expression.this 2638 expr = expression.expression 2639 2640 if expression.args.get("case_insensitive"): 2641 this = exp.Upper(this=this) 2642 expr = exp.Upper(this=expr) 2643 2644 result = exp.func("JARO_WINKLER_SIMILARITY", this, expr) 2645 2646 if expression.args.get("integer_scale"): 2647 result = exp.cast(result * 100, "INTEGER") 2648 2649 return self.sql(result) 2650 2651 def randstr_sql(self, expression: exp.Randstr) -> str: 2652 """ 2653 Transpile Snowflake's RANDSTR to DuckDB equivalent using deterministic hash-based random. 2654 Uses a pre-parsed template with placeholders replaced by expression nodes. 2655 2656 RANDSTR(length, generator) generates a random string of specified length. 2657 - With numeric seed: Use HASH(i + seed) for deterministic output (same seed = same result) 2658 - With RANDOM(): Use RANDOM() in the hash for non-deterministic output 2659 - No generator: Use default seed value 2660 """ 2661 length = expression.this 2662 generator = expression.args.get("generator") 2663 2664 if generator: 2665 if isinstance(generator, exp.Rand): 2666 # If it's RANDOM(), use its seed if available, otherwise use RANDOM() itself 2667 seed_value = generator.this or generator 2668 else: 2669 # Const/int or other expression - use as seed directly 2670 seed_value = generator 2671 else: 2672 # No generator specified, use default seed (arbitrary but deterministic) 2673 seed_value = exp.Literal.number(RANDSTR_SEED) 2674 2675 replacements = {"seed": seed_value, "length": length} 2676 return f"({self.sql(exp.replace_placeholders(self.RANDSTR_TEMPLATE, **replacements))})" 2677 2678 @unsupported_args("finish") 2679 def reduce_sql(self, expression: exp.Reduce) -> str: 2680 array_arg = expression.this 2681 initial_value = expression.args.get("initial") 2682 merge_lambda = expression.args.get("merge") 2683 2684 return self.func("list_reduce", array_arg, merge_lambda, initial_value) 2685 2686 def zipf_sql(self, expression: exp.Zipf) -> str: 2687 """ 2688 Transpile Snowflake's ZIPF to DuckDB using CDF-based inverse sampling. 2689 Uses a pre-parsed template with placeholders replaced by expression nodes. 2690 """ 2691 s = expression.this 2692 n = expression.args["elementcount"] 2693 gen = expression.args["gen"] 2694 2695 if not isinstance(gen, exp.Rand): 2696 # (ABS(HASH(seed)) % 1000000) / 1000000.0 2697 random_expr: exp.Expr = exp.Div( 2698 this=exp.Paren( 2699 this=exp.Mod( 2700 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen.copy()])), 2701 expression=exp.Literal.number(1000000), 2702 ) 2703 ), 2704 expression=exp.Literal.number(1000000.0), 2705 ) 2706 else: 2707 # Use RANDOM() for non-deterministic output 2708 random_expr = exp.Rand() 2709 2710 replacements = {"s": s, "n": n, "random_expr": random_expr} 2711 return f"({self.sql(exp.replace_placeholders(self.ZIPF_TEMPLATE, **replacements))})" 2712 2713 def tobinary_sql(self, expression: exp.ToBinary) -> str: 2714 """ 2715 TO_BINARY and TRY_TO_BINARY transpilation: 2716 - 'HEX': TO_BINARY('48454C50', 'HEX') -> UNHEX('48454C50') 2717 - 'UTF-8': TO_BINARY('TEST', 'UTF-8') -> ENCODE('TEST') 2718 - 'BASE64': TO_BINARY('SEVMUA==', 'BASE64') -> FROM_BASE64('SEVMUA==') 2719 2720 For TRY_TO_BINARY (safe=True), wrap with TRY(): 2721 - 'HEX': TRY_TO_BINARY('invalid', 'HEX') -> TRY(UNHEX('invalid')) 2722 """ 2723 value = expression.this 2724 format_arg = expression.args.get("format") 2725 is_safe = expression.args.get("safe") 2726 is_binary = _is_binary(expression) 2727 2728 if not format_arg and not is_binary: 2729 func_name = "TRY_TO_BINARY" if is_safe else "TO_BINARY" 2730 return self.func(func_name, value) 2731 2732 # Snowflake defaults to HEX encoding when no format is specified 2733 fmt = format_arg.name.upper() if format_arg else "HEX" 2734 2735 if fmt in ("UTF-8", "UTF8"): 2736 # DuckDB ENCODE always uses UTF-8, no charset parameter needed 2737 result = self.func("ENCODE", value) 2738 elif fmt == "BASE64": 2739 result = self.func("FROM_BASE64", value) 2740 elif fmt == "HEX": 2741 result = self.func("UNHEX", value) 2742 else: 2743 if is_safe: 2744 return self.sql(exp.null()) 2745 else: 2746 self.unsupported(f"format {fmt} is not supported") 2747 result = self.func("TO_BINARY", value) 2748 return f"TRY({result})" if is_safe else result 2749 2750 def tonumber_sql(self, expression: exp.ToNumber) -> str: 2751 fmt = expression.args.get("format") 2752 precision = expression.args.get("precision") 2753 scale = expression.args.get("scale") 2754 2755 if not fmt and precision and scale: 2756 to = exp.DataType.build(f"DECIMAL({precision.name}, {scale.name})", dialect="duckdb") 2757 if expression.args.get("safe"): 2758 return self.sql(exp.TryCast(this=expression.this, to=to)) 2759 return self.sql(exp.cast(expression.this, to, dialect="duckdb")) 2760 2761 return super().tonumber_sql(expression) 2762 2763 def _greatest_least_sql(self, expression: exp.Greatest | exp.Least) -> str: 2764 """ 2765 Handle GREATEST/LEAST functions with dialect-aware NULL behavior. 2766 2767 - If ignore_nulls=False (BigQuery-style): return NULL if any argument is NULL 2768 - If ignore_nulls=True (DuckDB/PostgreSQL-style): ignore NULLs, return greatest/least non-NULL value 2769 """ 2770 # Get all arguments 2771 all_args = [expression.this, *expression.expressions] 2772 fallback_sql = self.function_fallback_sql(expression) 2773 2774 if expression.args.get("ignore_nulls"): 2775 # DuckDB/PostgreSQL behavior: use native GREATEST/LEAST (ignores NULLs) 2776 return self.sql(fallback_sql) 2777 2778 # return NULL if any argument is NULL 2779 case_expr = exp.case().when( 2780 exp.or_(*[arg.is_(exp.null()) for arg in all_args], copy=False), 2781 exp.null(), 2782 copy=False, 2783 ) 2784 case_expr.set("default", fallback_sql) 2785 return self.sql(case_expr) 2786 2787 def generator_sql(self, expression: exp.Generator) -> str: 2788 # Transpile Snowflake GENERATOR to DuckDB range() 2789 rowcount = expression.args.get("rowcount") 2790 time_limit = expression.args.get("time_limit") 2791 2792 if time_limit: 2793 self.unsupported("GENERATOR TIMELIMIT parameter is not supported in DuckDB") 2794 2795 if not rowcount: 2796 self.unsupported("GENERATOR without ROWCOUNT is not supported in DuckDB") 2797 return self.func("range", exp.Literal.number(0)) 2798 2799 return self.func("range", rowcount) 2800 2801 def greatest_sql(self, expression: exp.Greatest) -> str: 2802 return self._greatest_least_sql(expression) 2803 2804 def least_sql(self, expression: exp.Least) -> str: 2805 return self._greatest_least_sql(expression) 2806 2807 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->", wrap: bool = True) -> str: 2808 if self.dialect.version >= (1, 3): 2809 prefix = "LAMBDA " 2810 arrow_sep = ":" 2811 wrap = False 2812 else: 2813 prefix = "" 2814 2815 lambda_sql = super().lambda_sql(expression, arrow_sep=arrow_sep, wrap=wrap) 2816 return f"{prefix}{lambda_sql}" 2817 2818 def show_sql(self, expression: exp.Show) -> str: 2819 from_ = self.sql(expression, "from_") 2820 from_ = f" FROM {from_}" if from_ else "" 2821 return f"SHOW {expression.name}{from_}" 2822 2823 def soundex_sql(self, expression: exp.Soundex) -> str: 2824 self.unsupported("SOUNDEX is not supported in DuckDB") 2825 return self.func("SOUNDEX", expression.this) 2826 2827 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2828 if isinstance(expression.this, exp.Identifier): 2829 return f"${self.sql(expression, 'this')}" 2830 return super().placeholder_sql(expression) 2831 2832 def install_sql(self, expression: exp.Install) -> str: 2833 force = "FORCE " if expression.args.get("force") else "" 2834 this = self.sql(expression, "this") 2835 from_clause = expression.args.get("from_") 2836 from_clause = f" FROM {from_clause}" if from_clause else "" 2837 return f"{force}INSTALL {this}{from_clause}" 2838 2839 def approxtopk_sql(self, expression: exp.ApproxTopK) -> str: 2840 self.unsupported( 2841 "APPROX_TOP_K cannot be transpiled to DuckDB due to incompatible return types. " 2842 ) 2843 return self.function_fallback_sql(expression) 2844 2845 def strposition_sql(self, expression: exp.StrPosition) -> str: 2846 this = expression.this 2847 substr = expression.args["substr"] 2848 position = expression.args.get("position") 2849 clamp_position = expression.args.get("clamp_position") 2850 2851 if clamp_position and position: 2852 position = exp.If( 2853 this=exp.LTE(this=position, expression=exp.Literal.number(0)), 2854 true=exp.Literal.number(1), 2855 false=position.copy(), 2856 ) 2857 2858 # For BINARY/BLOB: DuckDB's STRPOS doesn't support BLOB types 2859 if _is_binary(this): 2860 haystack: exp.Expr = exp.Hex(this=this) 2861 offset: exp.Expr = exp.Literal.number(0) 2862 if position: 2863 # Bound the arithmetic too: DuckDB may fold unreachable CASE branches. 2864 limit = exp.func("COALESCE", exp.ByteLength(this=this), 0) + 1 2865 offset = exp.Least(this=position, expressions=[limit], ignore_nulls=True) - 1 2866 haystack = exp.Substring(this=haystack, start=offset * 2 + 1) 2867 2868 # Match whole bytes, counting a two-character sentinel as the first byte. 2869 prefix = exp.RegexpExtract( 2870 this=exp.DPipe(this=exp.Literal.string("xx"), expression=haystack), 2871 expression=exp.DPipe( 2872 this=exp.Literal.string("^(xx(?:..)*?)"), expression=exp.Hex(this=substr) 2873 ), 2874 group=exp.Literal.number(1), 2875 ) 2876 result: exp.Expr = exp.paren(exp.Length(this=prefix) // 2) 2877 if position: 2878 result = ( 2879 exp.case() 2880 .when( 2881 exp.or_( 2882 this.is_(exp.null()), substr.is_(exp.null()), position.is_(exp.null()) 2883 ), 2884 exp.null(), 2885 ) 2886 .when( 2887 position > exp.func("GREATEST", exp.ByteLength(this=this), 1), 2888 exp.Literal.number(0), 2889 ) 2890 .else_(exp.func("COALESCE", exp.func("NULLIF", result, 0) + offset, 0)) 2891 ) 2892 return self.sql(result) 2893 2894 if clamp_position and position: 2895 expression = expression.copy() 2896 expression.set("position", position) 2897 2898 return strposition_sql(self, expression) 2899 2900 def similarto_sql(self, expression: exp.SimilarTo) -> str: 2901 pattern = expression.expression.unnest() 2902 if ( 2903 pattern.is_string 2904 and not isinstance(expression.parent, exp.Escape) 2905 and _SIMILAR_TO_REGEX_CHARS.isdisjoint(pattern.name) 2906 ): 2907 return self.sql(expression.this.like(pattern)) 2908 2909 self.unsupported("Cannot translate this SIMILAR TO pattern to DuckDB LIKE") 2910 return super().similarto_sql(expression) 2911 2912 def substring_sql(self, expression: exp.Substring) -> str: 2913 if expression.args.get("zero_start"): 2914 start = expression.args.get("start") 2915 length = expression.args.get("length") 2916 2917 if start := expression.args.get("start"): 2918 start = exp.If(this=start.eq(0), true=exp.Literal.number(1), false=start) 2919 if length := expression.args.get("length"): 2920 length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length) 2921 2922 return self.func("SUBSTRING", expression.this, start, length) 2923 2924 return self.function_fallback_sql(expression) 2925 2926 def strtotime_sql(self, expression: exp.StrToTime) -> str: 2927 # Check if target_type requires TIMESTAMPTZ (for LTZ/TZ variants) 2928 target_type = expression.args.get("target_type") 2929 needs_tz = target_type and target_type.this in ( 2930 exp.DType.TIMESTAMPLTZ, 2931 exp.DType.TIMESTAMPTZ, 2932 ) 2933 2934 value, formatted_time = self._strptime_default_year(expression) 2935 2936 if expression.args.get("safe"): 2937 cast_type = exp.DType.TIMESTAMPTZ if needs_tz else exp.DType.TIMESTAMP 2938 return self.sql(exp.cast(self.func("TRY_STRPTIME", value, formatted_time), cast_type)) 2939 2940 base_sql = self.func("STRPTIME", value, formatted_time) 2941 if needs_tz: 2942 return self.sql( 2943 exp.cast( 2944 base_sql, 2945 exp.DataType(this=exp.DType.TIMESTAMPTZ), 2946 ) 2947 ) 2948 return base_sql 2949 2950 def strtodate_sql(self, expression: exp.StrToDate) -> str: 2951 value, formatted_time = self._strptime_default_year(expression) 2952 function_name = "STRPTIME" if not expression.args.get("safe") else "TRY_STRPTIME" 2953 return self.sql( 2954 exp.cast( 2955 self.func(function_name, value, formatted_time), 2956 exp.DataType(this=exp.DType.DATE), 2957 ) 2958 ) 2959 2960 def _strptime_default_year( 2961 self, expression: exp.StrToTime | exp.StrToDate | exp.ParseDatetime 2962 ) -> tuple[exp.ExpOrStr, exp.ExpOrStr | None]: 2963 value: exp.ExpOrStr = expression.this 2964 formatted_time: exp.ExpOrStr | None = self.format_time(expression) 2965 2966 if default_year := expression.args.get("default_year"): 2967 value = exp.DPipe(this=exp.Literal.string(f"{default_year.name} "), expression=value) 2968 formatted_time = exp.DPipe(this=exp.Literal.string("%Y "), expression=formatted_time) 2969 2970 return value, formatted_time 2971 2972 def parsedatetime_sql(self, expression: exp.ParseDatetime) -> str: 2973 value, formatted_time = self._strptime_default_year(expression) 2974 return self.func("STRPTIME", value, formatted_time) 2975 2976 def parsetime_sql(self, expression: exp.ParseTime) -> str: 2977 formatted_time = self.format_time(expression) 2978 return self.sql( 2979 exp.cast( 2980 self.func("STRPTIME", expression.this, formatted_time), 2981 exp.DataType(this=exp.DType.TIME), 2982 ) 2983 ) 2984 2985 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 2986 this = expression.this 2987 time_format = self.format_time(expression) 2988 safe = expression.args.get("safe") 2989 time_type = exp.DataType.from_str("TIME", dialect="duckdb") 2990 cast_expr = exp.TryCast if safe else exp.Cast 2991 2992 if time_format: 2993 func_name = "TRY_STRPTIME" if safe else "STRPTIME" 2994 strptime = exp.Anonymous(this=func_name, expressions=[this, time_format]) 2995 return self.sql(cast_expr(this=strptime, to=time_type)) 2996 2997 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 2998 return self.sql(this) 2999 3000 return self.sql(cast_expr(this=this, to=time_type)) 3001 3002 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3003 if not expression.this: 3004 return "CURRENT_DATE" 3005 3006 expr = exp.Cast( 3007 this=exp.AtTimeZone(this=exp.CurrentTimestamp(), zone=expression.this), 3008 to=exp.DataType(this=exp.DType.DATE), 3009 ) 3010 return self.sql(expr) 3011 3012 def currentdatetime_sql(self, expression: exp.CurrentDatetime) -> str: 3013 zone = expression.this or exp.Literal.string("UTC") 3014 return self.sql( 3015 exp.AtTimeZone(this=exp.CurrentTimestamp(), zone=_normalize_timezone_offset(zone)) 3016 ) 3017 3018 def checkjson_sql(self, expression: exp.CheckJson) -> str: 3019 arg = expression.this 3020 return self.sql( 3021 exp.case() 3022 .when( 3023 exp.or_(arg.is_(exp.Null()), arg.eq(""), exp.func("json_valid", arg)), 3024 exp.null(), 3025 ) 3026 .else_(exp.Literal.string("Invalid JSON")) 3027 ) 3028 3029 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 3030 arg = expression.this 3031 if expression.args.get("safe"): 3032 return self.sql( 3033 exp.case() 3034 .when(exp.func("json_valid", arg), exp.cast(arg.copy(), "JSON")) 3035 .else_(exp.null()) 3036 ) 3037 return self.func("JSON", arg) 3038 3039 def unicode_sql(self, expression: exp.Unicode) -> str: 3040 if expression.args.get("empty_is_null"): 3041 return self.func("NULLIF", self.func("UNICODE", expression.this), "-1") 3042 3043 if expression.args.get("empty_is_zero"): 3044 return self.sql( 3045 exp.case() 3046 .when(expression.this.eq(exp.Literal.string("")), exp.Literal.number(0)) 3047 .else_(exp.Anonymous(this="UNICODE", expressions=[expression.this])) 3048 ) 3049 3050 return self.func("UNICODE", expression.this) 3051 3052 def stripnullvalue_sql(self, expression: exp.StripNullValue) -> str: 3053 return self.sql( 3054 exp.case() 3055 .when(exp.func("json_type", expression.this).eq("NULL"), exp.null()) 3056 .else_(expression.this) 3057 ) 3058 3059 def trunc_sql(self, expression: exp.Trunc) -> str: 3060 decimals = expression.args.get("decimals") 3061 if ( 3062 expression.args.get("fractions_supported") 3063 and decimals 3064 and not decimals.is_type(exp.DType.INT) 3065 ): 3066 decimals = exp.cast(decimals, exp.DType.INT, dialect="duckdb") 3067 3068 return self.func("TRUNC", expression.this, decimals) 3069 3070 def normal_sql(self, expression: exp.Normal) -> str: 3071 """ 3072 Transpile Snowflake's NORMAL(mean, stddev, gen) to DuckDB. 3073 3074 Uses the Box-Muller transform via NORMAL_TEMPLATE. 3075 """ 3076 mean = expression.this 3077 stddev = expression.args["stddev"] 3078 gen: exp.Expr = expression.args["gen"] 3079 3080 # Build two uniform random values [0, 1) for Box-Muller transform 3081 if isinstance(gen, exp.Rand) and gen.this is None: 3082 u1: exp.Expr = exp.Rand() 3083 u2: exp.Expr = exp.Rand() 3084 else: 3085 # Seeded: derive two values using HASH with different inputs 3086 seed = gen.this if isinstance(gen, exp.Rand) else gen 3087 u1 = exp.replace_placeholders(self.SEEDED_RANDOM_TEMPLATE, seed=seed) 3088 u2 = exp.replace_placeholders( 3089 self.SEEDED_RANDOM_TEMPLATE, 3090 seed=exp.Add(this=seed.copy(), expression=exp.Literal.number(1)), 3091 ) 3092 3093 replacements = {"mean": mean, "stddev": stddev, "u1": u1, "u2": u2} 3094 return self.sql(exp.replace_placeholders(self.NORMAL_TEMPLATE, **replacements)) 3095 3096 def uniform_sql(self, expression: exp.Uniform) -> str: 3097 """ 3098 Transpile Snowflake's UNIFORM(min, max, gen) to DuckDB. 3099 3100 UNIFORM returns a random value in [min, max]: 3101 - Integer result if both min and max are integers 3102 - Float result if either min or max is a float 3103 """ 3104 min_val = expression.this 3105 max_val = expression.expression 3106 gen = expression.args.get("gen") or expression.args.get("seed") or exp.Rand() 3107 3108 # Determine if result should be integer (both bounds are integers). 3109 # We do this to emulate Snowflake's behavior, INT -> INT, FLOAT -> FLOAT 3110 is_int_result = min_val.is_int and max_val.is_int 3111 3112 # Build the random value expression [0, 1) 3113 if not isinstance(gen, exp.Rand): 3114 # Seed value: (ABS(HASH(seed)) % 1000000) / 1000000.0 3115 random_expr: exp.Expr = exp.Div( 3116 this=exp.Paren( 3117 this=exp.Mod( 3118 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen])), 3119 expression=exp.Literal.number(1000000), 3120 ) 3121 ), 3122 expression=exp.Literal.number(1000000.0), 3123 ) 3124 else: 3125 random_expr = exp.Rand() 3126 3127 # Build: min + random * (max - min [+ 1 for int]) 3128 range_expr: exp.Expr = exp.Sub(this=max_val, expression=min_val) 3129 if is_int_result: 3130 range_expr = exp.Add(this=range_expr, expression=exp.Literal.number(1)) 3131 3132 result: exp.Expr = exp.Add( 3133 this=min_val, 3134 expression=exp.Mul(this=random_expr, expression=exp.Paren(this=range_expr)), 3135 ) 3136 3137 if is_int_result: 3138 result = exp.Cast(this=exp.Floor(this=result), to=exp.DType.BIGINT.into_expr()) 3139 3140 return self.sql(result) 3141 3142 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 3143 nano = expression.args.get("nano") 3144 overflow = expression.args.get("overflow") 3145 3146 # Snowflake's TIME_FROM_PARTS supports overflow 3147 if overflow: 3148 hour = expression.args["hour"] 3149 minute = expression.args["min"] 3150 sec = expression.args["sec"] 3151 3152 # Check if values are within normal ranges - use MAKE_TIME for efficiency 3153 if not nano and all(arg.is_int for arg in [hour, minute, sec]): 3154 try: 3155 h_val = hour.to_py() 3156 m_val = minute.to_py() 3157 s_val = sec.to_py() 3158 if 0 <= h_val <= 23 and 0 <= m_val <= 59 and 0 <= s_val <= 59: 3159 return rename_func("MAKE_TIME")(self, expression) 3160 except ValueError: 3161 pass 3162 3163 # Overflow or nanoseconds detected - use INTERVAL arithmetic 3164 if nano: 3165 sec = sec + nano.pop() / exp.Literal.number(1000000000.0) 3166 3167 total_seconds = hour * exp.Literal.number(3600) + minute * exp.Literal.number(60) + sec 3168 3169 return self.sql( 3170 exp.Add( 3171 this=exp.Cast( 3172 this=exp.Literal.string("00:00:00"), to=exp.DType.TIME.into_expr() 3173 ), 3174 expression=exp.Interval(this=total_seconds, unit=exp.var("SECOND")), 3175 ) 3176 ) 3177 3178 # Default: MAKE_TIME 3179 if nano: 3180 expression.set( 3181 "sec", expression.args["sec"] + nano.pop() / exp.Literal.number(1000000000.0) 3182 ) 3183 3184 return rename_func("MAKE_TIME")(self, expression) 3185 3186 def extract_sql(self, expression: exp.Extract) -> str: 3187 """ 3188 Transpile EXTRACT/DATE_PART for DuckDB, handling specifiers not natively supported. 3189 3190 DuckDB doesn't support: WEEKISO, YEAROFWEEK, YEAROFWEEKISO, NANOSECOND, 3191 EPOCH_SECOND (as integer), EPOCH_MILLISECOND, EPOCH_MICROSECOND, EPOCH_NANOSECOND 3192 """ 3193 this = expression.this 3194 datetime_expr = expression.expression 3195 3196 # TIMESTAMPTZ extractions may produce different results between Snowflake and DuckDB 3197 # because Snowflake applies server timezone while DuckDB uses local timezone 3198 if datetime_expr.is_type(exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ): 3199 self.unsupported( 3200 "EXTRACT from TIMESTAMPTZ / TIMESTAMPLTZ may produce different results due to timezone handling differences" 3201 ) 3202 3203 part_name = this.name.upper() 3204 3205 if part_name in self.EXTRACT_STRFTIME_MAPPINGS: 3206 fmt, cast_type = self.EXTRACT_STRFTIME_MAPPINGS[part_name] 3207 3208 # Problem: strftime doesn't accept TIME and there's no NANOSECOND function 3209 # So, for NANOSECOND with TIME, fallback to MICROSECOND * 1000 3210 is_nano_time = part_name == "NANOSECOND" and datetime_expr.is_type( 3211 exp.DType.TIME, exp.DType.TIMETZ 3212 ) 3213 3214 if is_nano_time: 3215 self.unsupported("Parameter NANOSECOND is not supported with TIME type in DuckDB") 3216 return self.sql( 3217 exp.cast( 3218 exp.Mul( 3219 this=exp.Extract(this=exp.var("MICROSECOND"), expression=datetime_expr), 3220 expression=exp.Literal.number(1000), 3221 ), 3222 exp.DataType.from_str(cast_type, dialect="duckdb"), 3223 ) 3224 ) 3225 3226 # For NANOSECOND, cast to TIMESTAMP_NS to preserve nanosecond precision 3227 strftime_input = datetime_expr 3228 if part_name == "NANOSECOND": 3229 strftime_input = exp.cast(datetime_expr, exp.DType.TIMESTAMP_NS) 3230 3231 return self.sql( 3232 exp.cast( 3233 exp.Anonymous( 3234 this="STRFTIME", 3235 expressions=[strftime_input, exp.Literal.string(fmt)], 3236 ), 3237 exp.DataType.from_str(cast_type, dialect="duckdb"), 3238 ) 3239 ) 3240 3241 if part_name in self.EXTRACT_EPOCH_MAPPINGS: 3242 func_name = self.EXTRACT_EPOCH_MAPPINGS[part_name] 3243 result: exp.Expr = exp.Anonymous(this=func_name, expressions=[datetime_expr]) 3244 # EPOCH returns float, cast to BIGINT for integer result 3245 if part_name == "EPOCH_SECOND": 3246 result = exp.cast(result, exp.DataType.from_str("BIGINT", dialect="duckdb")) 3247 return self.sql(result) 3248 3249 return super().extract_sql(expression) 3250 3251 def timestamp_sql(self, expression: exp.Timestamp) -> str: 3252 zone = expression.args.get("zone") 3253 if expression.args.get("with_tz") and zone: 3254 return self.sql( 3255 exp.AtTimeZone( 3256 this=exp.cast(expression.this, exp.DType.TIMESTAMP), 3257 zone=_normalize_timezone_offset(zone), 3258 ) 3259 ) 3260 return no_timestamp_sql(self, expression) 3261 3262 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 3263 # Check if this is the date/time expression form: TIMESTAMP_FROM_PARTS(date_expr, time_expr) 3264 date_expr = expression.this 3265 time_expr = expression.expression 3266 3267 if date_expr is not None and time_expr is not None: 3268 # In DuckDB, DATE + TIME produces TIMESTAMP 3269 return self.sql(exp.Add(this=date_expr, expression=time_expr)) 3270 3271 # Component-based form: TIMESTAMP_FROM_PARTS(year, month, day, hour, minute, second, ...) 3272 sec = expression.args.get("sec") 3273 if sec is None: 3274 # This shouldn't happen with valid input, but handle gracefully 3275 return rename_func("MAKE_TIMESTAMP")(self, expression) 3276 3277 milli = expression.args.get("milli") 3278 if milli is not None: 3279 sec += milli.pop() / exp.Literal.number(1000.0) 3280 3281 nano = expression.args.get("nano") 3282 if nano is not None: 3283 sec += nano.pop() / exp.Literal.number(1000000000.0) 3284 3285 if milli or nano: 3286 expression.set("sec", sec) 3287 3288 if zone := expression.args.get("zone"): 3289 return self.sql(exp.AtTimeZone(this=expression, zone=zone.pop())) 3290 3291 return rename_func("MAKE_TIMESTAMP")(self, expression) 3292 3293 @unsupported_args("nano") 3294 def timestampltzfromparts_sql(self, expression: exp.TimestampLtzFromParts) -> str: 3295 # Pop nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3296 if nano := expression.args.get("nano"): 3297 nano.pop() 3298 3299 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3300 return f"CAST({timestamp} AS TIMESTAMPTZ)" 3301 3302 @unsupported_args("nano") 3303 def timestamptzfromparts_sql(self, expression: exp.TimestampTzFromParts) -> str: 3304 # Extract zone before popping 3305 zone = expression.args.get("zone") 3306 # Pop zone and nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3307 if zone: 3308 zone = zone.pop() 3309 3310 if nano := expression.args.get("nano"): 3311 nano.pop() 3312 3313 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3314 3315 if zone: 3316 # Use AT TIME ZONE to apply the explicit timezone 3317 return f"{timestamp} AT TIME ZONE {self.sql(zone)}" 3318 3319 return timestamp 3320 3321 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 3322 locks = self.expressions(expression, key="locks", sep=" ") 3323 return [f" {locks}" if locks else ""] 3324 3325 def tablesample_sql( 3326 self, 3327 expression: exp.TableSample, 3328 tablesample_keyword: str | None = None, 3329 ) -> str: 3330 if not isinstance(expression.parent, exp.Select): 3331 # This sample clause only applies to a single source, not the entire resulting relation 3332 tablesample_keyword = "TABLESAMPLE" 3333 3334 if expression.args.get("size"): 3335 method = expression.args.get("method") 3336 if method and method.name.upper() != "RESERVOIR": 3337 self.unsupported( 3338 f"Sampling method {method} is not supported with a discrete sample count, " 3339 "defaulting to reservoir sampling" 3340 ) 3341 expression.set("method", exp.var("RESERVOIR")) 3342 3343 return super().tablesample_sql(expression, tablesample_keyword=tablesample_keyword) 3344 3345 def in_sql(self, expression: exp.In) -> str: 3346 unnest = expression.args.get("unnest") 3347 if unnest: 3348 return self.sql( 3349 exp.replace_placeholders( 3350 self.IN_UNNEST_TEMPLATE, arr=unnest.expressions[0], value=expression.this 3351 ) 3352 ) 3353 return super().in_sql(expression) 3354 3355 def interval_sql(self, expression: exp.Interval) -> str: 3356 # DuckDB truncates INTERVAL '1.5' DAY to 1 day, but keeps the fraction in INTERVAL '1.5 DAY' 3357 this = expression.this 3358 unit = expression.unit 3359 if expression.args.get("fraction_in_string") and this and isinstance(unit, exp.Var): 3360 return f"INTERVAL '{this.name} {self.sql(unit)}'" 3361 3362 return super().interval_sql(expression) 3363 3364 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3365 if expression.kind in ("MARK", "SINGLE") or ( 3366 expression.side == "RIGHT" and expression.is_semi_or_anti_join 3367 ): 3368 kind = "_".join(part for part in (expression.side, expression.kind) if part) 3369 return super().join_sql(expression, join_op=f"JOIN BY (TYPE {kind})") 3370 3371 if ( 3372 not expression.args.get("using") 3373 and not expression.args.get("on") 3374 and not expression.args.get("nearest") 3375 and not expression.method 3376 and (expression.kind in ("", "INNER", "OUTER")) 3377 ): 3378 # Some dialects support `LEFT/INNER JOIN UNNEST(...)` without an explicit ON clause 3379 # DuckDB doesn't, but we can just add a dummy ON clause that is always true 3380 if isinstance(expression.this, exp.Unnest): 3381 return super().join_sql(expression.on(exp.true())) 3382 3383 expression.set("side", None) 3384 expression.set("kind", None) 3385 3386 return super().join_sql(expression, join_op=join_op) 3387 3388 def countif_sql(self, expression: exp.CountIf) -> str: 3389 if self.dialect.version >= (1, 2): 3390 this = expression.this 3391 if expression.args.get("zero_on_all_null") and not isinstance(this, exp.Distinct): 3392 # DuckDB >= 1.2's COUNT_IF returns NULL when the condition is NULL on all rows, 3393 # so we wrap the condition in IS TRUE to preserve count-like semantics 3394 expression = exp.CountIf(this=exp.paren(this).is_(exp.true())) 3395 return self.function_fallback_sql(expression) 3396 3397 # https://github.com/tobymao/sqlglot/pull/4749 3398 return count_if_to_sum(self, expression) 3399 3400 def bracket_sql(self, expression: exp.Bracket) -> str: 3401 if self.dialect.version >= (1, 2): 3402 return super().bracket_sql(expression) 3403 3404 # https://duckdb.org/2025/02/05/announcing-duckdb-120.html#breaking-changes 3405 this = expression.this 3406 if isinstance(this, exp.Array): 3407 this.replace(exp.paren(this)) 3408 3409 bracket = super().bracket_sql(expression) 3410 3411 if not expression.args.get("returns_list_for_maps"): 3412 if not this.type: 3413 from sqlglot.optimizer.annotate_types import annotate_types 3414 3415 this = annotate_types(this, dialect=self.dialect) 3416 3417 if this.is_type(exp.DType.MAP): 3418 bracket = f"({bracket})[1]" 3419 3420 return bracket 3421 3422 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 3423 func = expression.this 3424 3425 # For ARRAY_AGG, DuckDB requires ORDER BY inside the function, not in WITHIN GROUP 3426 # Transform: ARRAY_AGG(x) WITHIN GROUP (ORDER BY y) -> ARRAY_AGG(x ORDER BY y) 3427 if isinstance(func, exp.ArrayAgg): 3428 if not isinstance(order := expression.expression, exp.Order): 3429 return self.sql(func) 3430 3431 # Save the original column for FILTER clause (before wrapping with Order) 3432 original_this = func.this 3433 3434 # Move ORDER BY inside ARRAY_AGG by wrapping its argument with Order 3435 # ArrayAgg.this should become Order(this=ArrayAgg.this, expressions=order.expressions) 3436 func.set( 3437 "this", 3438 exp.Order( 3439 this=func.this.copy(), 3440 expressions=order.expressions, 3441 ), 3442 ) 3443 3444 # Generate the ARRAY_AGG function with ORDER BY and add FILTER clause if needed 3445 # Use original_this (not the Order-wrapped version) for the FILTER condition 3446 array_agg_sql = self.function_fallback_sql(func) 3447 return self._add_arrayagg_null_filter(array_agg_sql, func, original_this) 3448 3449 # For other functions (like PERCENTILES), use existing logic 3450 expression_sql = self.sql(expression, "expression") 3451 3452 if isinstance(func, exp.PERCENTILES): 3453 # Make the order key the first arg and slide the fraction to the right 3454 # https://duckdb.org/docs/sql/aggregates#ordered-set-aggregate-functions 3455 order_col = expression.find(exp.Ordered) 3456 if order_col: 3457 func.set("expression", func.this) 3458 func.set("this", order_col.this) 3459 3460 this = self.sql(expression, "this").removesuffix(")") 3461 3462 return f"{this}{expression_sql})" 3463 3464 def length_sql(self, expression: exp.Length) -> str: 3465 arg = expression.this 3466 3467 def text_arg(value: exp.Expr) -> exp.Expr: 3468 if expression.args.get("null_terminated"): 3469 return exp.SplitPart( 3470 this=value.copy(), 3471 delimiter=exp.Chr(expressions=[exp.Literal.number(0)]), 3472 part_index=exp.Literal.number(1), 3473 ) 3474 return value 3475 3476 # SQLite, BQ and Snowflake also accept binary values as args, so 3477 # DDB will attempt to infer the type or resort to case/when resolution 3478 if ( 3479 not (expression.args.get("binary") or expression.args.get("null_terminated")) 3480 or arg.is_string 3481 ): 3482 return self.func("LENGTH", text_arg(arg)) 3483 3484 if not arg.type: 3485 from sqlglot.optimizer.annotate_types import annotate_types 3486 3487 arg = annotate_types(arg, dialect=self.dialect) 3488 3489 if arg.is_type(*exp.DataType.TEXT_TYPES): 3490 return self.func("LENGTH", text_arg(arg)) 3491 3492 # We need these casts to make duckdb's static type checker happy 3493 blob = exp.cast(arg, exp.DType.VARBINARY) 3494 varchar = exp.cast(arg, exp.DType.VARCHAR) 3495 3496 case = ( 3497 exp.case(exp.Typeof(this=arg.copy())) 3498 .when(exp.Literal.string("BLOB"), exp.ByteLength(this=blob)) 3499 .else_(exp.Length(this=text_arg(varchar))) 3500 ) 3501 return self.sql(case) 3502 3503 def bitlength_sql(self, expression: exp.BitLength) -> str: 3504 if not _is_binary(arg := expression.this): 3505 return self.func("BIT_LENGTH", arg) 3506 3507 blob = exp.cast(arg, exp.DataType.Type.VARBINARY) 3508 return self.sql(exp.ByteLength(this=blob) * exp.Literal.number(8)) 3509 3510 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 3511 if len(expression.expressions) > 1: 3512 return super().chr_sql(expression, name) 3513 3514 arg = expression.expressions[0] 3515 if arg.is_type(*exp.DataType.REAL_TYPES): 3516 arg = exp.cast(arg, exp.DType.INT) 3517 return self.func("CHR", arg) 3518 3519 def collation_sql(self, expression: exp.Collation) -> str: 3520 self.unsupported("COLLATION function is not supported by DuckDB") 3521 return self.function_fallback_sql(expression) 3522 3523 def collate_sql(self, expression: exp.Collate) -> str: 3524 if not expression.expression.is_string: 3525 return super().collate_sql(expression) 3526 3527 raw = expression.expression.name 3528 if not raw: 3529 return self.sql(expression.this) 3530 3531 parts = [] 3532 for part in raw.split("-"): 3533 lower = part.lower() 3534 if lower not in _SNOWFLAKE_COLLATION_DEFAULTS: 3535 if lower in _SNOWFLAKE_COLLATION_UNSUPPORTED: 3536 self.unsupported( 3537 f"Snowflake collation specifier '{part}' has no DuckDB equivalent" 3538 ) 3539 parts.append(lower) 3540 3541 if not parts: 3542 return self.sql(expression.this) 3543 return super().collate_sql( 3544 exp.Collate(this=expression.this, expression=exp.var(".".join(parts))) 3545 ) 3546 3547 def _validate_regexp_flags(self, flags: exp.Expr | None, supported_flags: str) -> str | None: 3548 """ 3549 Validate and filter regexp flags for DuckDB compatibility. 3550 3551 Args: 3552 flags: The flags expression to validate 3553 supported_flags: String of supported flags (e.g., "ims", "cims"). 3554 Only these flags will be returned. 3555 3556 Returns: 3557 Validated/filtered flag string, or None if no valid flags remain 3558 """ 3559 if not isinstance(flags, exp.Expr): 3560 return None 3561 3562 if not flags.is_string: 3563 self.unsupported("Non-literal regexp flags are not fully supported in DuckDB") 3564 return None 3565 3566 flag_str = flags.this 3567 unsupported = set(flag_str) - set(supported_flags) 3568 3569 if unsupported: 3570 self.unsupported( 3571 f"Regexp flags {sorted(unsupported)} are not supported in this context" 3572 ) 3573 3574 flag_str = "".join(f for f in flag_str if f in supported_flags) 3575 return flag_str if flag_str else None 3576 3577 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 3578 this = expression.this 3579 pattern = expression.expression 3580 position = expression.args.get("position") 3581 parameters = expression.args.get("parameters") 3582 3583 # Validate flags - only "ims" flags are supported for embedded patterns 3584 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 3585 3586 if position: 3587 this = exp.Substring(this=this, start=position) 3588 3589 # Handle empty pattern: Snowflake returns 0, DuckDB would match between every character. 3590 # Checked before the flags are embedded, which would make the pattern non-empty 3591 is_empty = exp.EQ(this=pattern.copy(), expression=exp.Literal.string("")) 3592 3593 # Embed flags in pattern (REGEXP_EXTRACT_ALL doesn't support flags argument) 3594 if validated_flags: 3595 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 3596 3597 result = ( 3598 exp.case() 3599 .when(is_empty, exp.Literal.number(0)) 3600 .else_( 3601 exp.Length( 3602 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 3603 ) 3604 ) 3605 ) 3606 3607 return self.sql(result) 3608 3609 def regexpreplace_sql(self, expression: exp.RegexpReplace) -> str: 3610 subject = expression.this 3611 pattern = expression.expression 3612 replacement = expression.args.get("replacement") or exp.Literal.string("") 3613 position = expression.args.get("position") 3614 occurrence = expression.args.get("occurrence") 3615 modifiers = expression.args.get("modifiers") 3616 3617 validated_flags = self._validate_regexp_flags(modifiers, supported_flags="cimsg") or "" 3618 3619 # Handle occurrence (only literals supported) 3620 if occurrence and not occurrence.is_int: 3621 self.unsupported("REGEXP_REPLACE with non-literal occurrence") 3622 else: 3623 occurrence = occurrence.to_py() if occurrence and occurrence.is_int else 0 3624 if occurrence > 1: 3625 self.unsupported(f"REGEXP_REPLACE occurrence={occurrence} not supported") 3626 # flag duckdb to do either all or none, single_replace check is for duckdb round trip 3627 elif ( 3628 occurrence == 0 3629 and "g" not in validated_flags 3630 and not expression.args.get("single_replace") 3631 ): 3632 validated_flags += "g" 3633 3634 # Handle position (only literals supported) 3635 prefix = None 3636 if position and not position.is_int: 3637 self.unsupported("REGEXP_REPLACE with non-literal position") 3638 elif position and position.is_int and position.to_py() > 1: 3639 pos = position.to_py() 3640 prefix = exp.Substring( 3641 this=subject, start=exp.Literal.number(1), length=exp.Literal.number(pos - 1) 3642 ) 3643 subject = exp.Substring(this=subject, start=exp.Literal.number(pos)) 3644 3645 result: exp.Expr = exp.Anonymous( 3646 this="REGEXP_REPLACE", 3647 expressions=[ 3648 subject, 3649 pattern, 3650 replacement, 3651 exp.Literal.string(validated_flags) if validated_flags else None, 3652 ], 3653 ) 3654 3655 if prefix: 3656 result = exp.Concat(expressions=[prefix, result]) 3657 3658 return self.sql(result) 3659 3660 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 3661 this = expression.this 3662 pattern = expression.expression 3663 flag = expression.args.get("flag") 3664 3665 if expression.args.get("full_match"): 3666 validated_flags = self._validate_regexp_flags(flag, supported_flags="cims") 3667 flag = exp.Literal.string(validated_flags) if validated_flags else None 3668 return self.func("REGEXP_FULL_MATCH", this, pattern, flag) 3669 3670 return self.func("REGEXP_MATCHES", this, pattern, flag) 3671 3672 @unsupported_args("ins_cost", "del_cost", "sub_cost") 3673 def levenshtein_sql(self, expression: exp.Levenshtein) -> str: 3674 this = expression.this 3675 expr = expression.expression 3676 max_dist = expression.args.get("max_dist") 3677 3678 if max_dist is None: 3679 return self.func("LEVENSHTEIN", this, expr) 3680 3681 # Emulate Snowflake semantics: if distance > max_dist, return max_dist 3682 levenshtein = exp.Levenshtein(this=this, expression=expr) 3683 return self.sql(exp.Least(this=levenshtein, expressions=[max_dist])) 3684 3685 def pad_sql(self, expression: exp.Pad) -> str: 3686 """ 3687 Handle RPAD/LPAD for VARCHAR and BINARY types. 3688 3689 For VARCHAR: Delegate to parent class 3690 For BINARY: Lower to: input || REPEAT(pad, GREATEST(0, target_len - OCTET_LENGTH(input))) 3691 """ 3692 string_arg = expression.this 3693 fill_arg = expression.args.get("fill_pattern") or exp.Literal.string(" ") 3694 3695 if _is_binary(string_arg) or _is_binary(fill_arg): 3696 length_arg = expression.expression 3697 is_left = expression.args.get("is_left") 3698 3699 input_len = exp.ByteLength(this=string_arg) 3700 chars_needed = length_arg - input_len 3701 pad_count = exp.Greatest( 3702 this=exp.Literal.number(0), expressions=[chars_needed], ignore_nulls=True 3703 ) 3704 repeat_expr = exp.Repeat(this=fill_arg, times=pad_count) 3705 3706 left, right = string_arg, repeat_expr 3707 if is_left: 3708 left, right = right, left 3709 3710 result = exp.DPipe(this=left, expression=right) 3711 return self.sql(result) 3712 3713 # For VARCHAR: Delegate to parent class (handles PAD_FILL_PATTERN_IS_REQUIRED) 3714 return super().pad_sql(expression) 3715 3716 def minhash_sql(self, expression: exp.Minhash) -> str: 3717 k = expression.this 3718 exprs = expression.expressions 3719 3720 if len(exprs) != 1 or isinstance(exprs[0], exp.Star): 3721 self.unsupported( 3722 "MINHASH with multiple expressions or * requires manual query restructuring" 3723 ) 3724 return self.func("MINHASH", k, *exprs) 3725 3726 expr = exprs[0] 3727 result = exp.replace_placeholders(self.MINHASH_TEMPLATE.copy(), expr=expr, k=k) 3728 return f"({self.sql(result)})" 3729 3730 def minhashcombine_sql(self, expression: exp.MinhashCombine) -> str: 3731 expr = expression.this 3732 result = exp.replace_placeholders(self.MINHASH_COMBINE_TEMPLATE.copy(), expr=expr) 3733 return f"({self.sql(result)})" 3734 3735 def approximatesimilarity_sql(self, expression: exp.ApproximateSimilarity) -> str: 3736 expr = expression.this 3737 result = exp.replace_placeholders(self.APPROXIMATE_SIMILARITY_TEMPLATE.copy(), expr=expr) 3738 return f"({self.sql(result)})" 3739 3740 def arrayall_sql(self, expression: exp.ArrayAll) -> str: 3741 return self.func( 3742 "LIST_REDUCE", 3743 exp.Transform(this=expression.this, expression=expression.expression), 3744 exp.Lambda( 3745 this=exp.and_(exp.to_identifier("_a"), exp.to_identifier("_b")), 3746 expressions=[exp.to_identifier("_a"), exp.to_identifier("_b")], 3747 ), 3748 exp.true(), 3749 ) 3750 3751 def arrayuniqueagg_sql(self, expression: exp.ArrayUniqueAgg) -> str: 3752 return self.sql( 3753 exp.Filter( 3754 this=exp.func("LIST", exp.Distinct(expressions=[expression.this])), 3755 expression=exp.Where(this=expression.this.copy().is_(exp.null()).not_()), 3756 ) 3757 ) 3758 3759 def arrayconcatagg_sql(self, expression: exp.ArrayConcatAgg) -> str: 3760 this = expression.this 3761 3762 if isinstance(this, exp.Limit): 3763 self.unsupported("LIMIT in ARRAY_CONCAT_AGG cannot be transpiled to DuckDB") 3764 this = this.this 3765 3766 inner = this.this if isinstance(this, exp.Order) else this 3767 3768 return self.func( 3769 "FLATTEN", 3770 exp.Filter( 3771 this=exp.ArrayAgg(this=this), 3772 expression=exp.Where(this=inner.copy().is_(exp.null()).not_()), 3773 ), 3774 ) 3775 3776 def arrayunionagg_sql(self, expression: exp.ArrayUnionAgg) -> str: 3777 self.unsupported("ARRAY_UNION_AGG is not supported in DuckDB") 3778 return self.function_fallback_sql(expression) 3779 3780 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 3781 arr = expression.this 3782 func = self.func("LIST_DISTINCT", arr) 3783 3784 if expression.args.get("check_null"): 3785 add_null_to_array = exp.func( 3786 "LIST_APPEND", exp.func("LIST_DISTINCT", exp.ArrayCompact(this=arr)), exp.Null() 3787 ) 3788 return self.sql( 3789 exp.If( 3790 this=exp.NEQ( 3791 this=exp.ArraySize(this=arr), expression=exp.func("LIST_COUNT", arr) 3792 ), 3793 true=add_null_to_array, 3794 false=func, 3795 ) 3796 ) 3797 3798 return func 3799 3800 def arrayintersect_sql(self, expression: exp.ArrayIntersect) -> str: 3801 if expression.args.get("is_multiset") and len(expression.expressions) == 2: 3802 return self._array_bag_sql( 3803 self.ARRAY_INTERSECTION_CONDITION, 3804 expression.expressions[0], 3805 expression.expressions[1], 3806 ) 3807 return self.function_fallback_sql(expression) 3808 3809 def arrayexcept_sql(self, expression: exp.ArrayExcept) -> str: 3810 arr1, arr2 = expression.this, expression.expression 3811 if expression.args.get("is_multiset"): 3812 return self._array_bag_sql(self.ARRAY_EXCEPT_CONDITION, arr1, arr2) 3813 return self.sql( 3814 exp.replace_placeholders(self.ARRAY_EXCEPT_SET_TEMPLATE, arr1=arr1, arr2=arr2) 3815 ) 3816 3817 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 3818 separator = expression.args.get("separator") 3819 if ( 3820 expression.args.get("null_separator_is_empty") 3821 and separator is not None 3822 and not separator.is_string 3823 ): 3824 expression.set( 3825 "separator", exp.Coalesce(this=separator, expressions=[exp.Literal.string("")]) 3826 ) 3827 return groupconcat_sql(self, expression, within_group=False) 3828 3829 def arrayslice_sql(self, expression: exp.ArraySlice) -> str: 3830 """ 3831 Spark's SLICE uses a length, so normalize negative starts before computing 3832 the inclusive end index. Starts before the array produce an empty slice. 3833 3834 Transpiles Snowflake's ARRAY_SLICE (0-indexed, exclusive end) to DuckDB's 3835 ARRAY_SLICE (1-indexed, inclusive end) by wrapping start and end in CASE 3836 expressions that adjust the index at query time: 3837 - start: CASE WHEN start >= 0 THEN start + 1 ELSE start END 3838 - end: CASE WHEN end < 0 THEN end - 1 ELSE end END 3839 """ 3840 start, end = expression.args.get("start"), expression.args.get("end") 3841 3842 if expression.args.get("zero_based"): 3843 if start is not None: 3844 start = ( 3845 exp.case() 3846 .when( 3847 exp.GTE(this=start.copy(), expression=exp.Literal.number(0)), 3848 exp.Add(this=start.copy(), expression=exp.Literal.number(1)), 3849 ) 3850 .else_(start) 3851 ) 3852 if end is not None and not expression.args.get("is_length"): 3853 end = ( 3854 exp.case() 3855 .when( 3856 exp.LT(this=end.copy(), expression=exp.Literal.number(0)), 3857 exp.Sub(this=end.copy(), expression=exp.Literal.number(1)), 3858 ) 3859 .else_(end) 3860 ) 3861 3862 if expression.args.get("is_length") and start is not None and end is not None: 3863 if not start.is_int or start.to_py() < 0: 3864 size = exp.ArraySize(this=expression.this.copy()) 3865 start = ( 3866 exp.case() 3867 .when(start < -size, size + 1) 3868 .when(start < 0, size + start + 1) 3869 .else_(start) 3870 ) 3871 3872 if start.is_int and end.is_int: 3873 end = exp.Literal.number(start.to_py() + end.to_py() - 1) 3874 else: 3875 end = start + exp.cast(end, "BIGINT") - 1 3876 return self.func("ARRAY_SLICE", expression.this, start, end, expression.args.get("step")) 3877 3878 def arrayszip_sql(self, expression: exp.ArraysZip) -> str: 3879 args = expression.expressions 3880 3881 if not args: 3882 # Return [{}] - using MAP([], []) since DuckDB can't represent empty structs 3883 return self.sql(exp.array(exp.Map(keys=exp.array(), values=exp.array()))) 3884 3885 # Build placeholder values for template 3886 lengths = [exp.Length(this=arg) for arg in args] 3887 max_len = ( 3888 lengths[0] 3889 if len(lengths) == 1 3890 else exp.Greatest(this=lengths[0], expressions=lengths[1:]) 3891 ) 3892 3893 # Empty struct with same schema: {'$1': NULL, '$2': NULL, ...} 3894 empty_struct = exp.func( 3895 "STRUCT", 3896 *[ 3897 exp.PropertyEQ(this=exp.Literal.string(f"${i + 1}"), expression=exp.Null()) 3898 for i in range(len(args)) 3899 ], 3900 ) 3901 3902 # Struct for transform: {'$1': COALESCE(arr1, [])[__i + 1], ...} 3903 # COALESCE wrapping handles NULL arrays - prevents invalid NULL[i] syntax 3904 index = exp.column("__i") + 1 3905 transform_struct = exp.func( 3906 "STRUCT", 3907 *[ 3908 exp.PropertyEQ( 3909 this=exp.Literal.string(f"${i + 1}"), 3910 expression=exp.func("COALESCE", arg, exp.array())[index], 3911 ) 3912 for i, arg in enumerate(args) 3913 ], 3914 ) 3915 3916 result = exp.replace_placeholders( 3917 self.ARRAYS_ZIP_TEMPLATE.copy(), 3918 null_check=exp.or_(*[arg.is_(exp.Null()) for arg in args]), 3919 all_empty_check=exp.and_( 3920 *[ 3921 exp.EQ(this=exp.Length(this=arg), expression=exp.Literal.number(0)) 3922 for arg in args 3923 ] 3924 ), 3925 empty_struct=empty_struct, 3926 max_len=max_len, 3927 transform_struct=transform_struct, 3928 ) 3929 return self.sql(result) 3930 3931 def lower_sql(self, expression: exp.Lower) -> str: 3932 result_sql = self.func("LOWER", _cast_to_varchar(expression.this)) 3933 return _gen_with_cast_to_blob(self, expression, result_sql) 3934 3935 def upper_sql(self, expression: exp.Upper) -> str: 3936 result_sql = self.func("UPPER", _cast_to_varchar(expression.this)) 3937 return _gen_with_cast_to_blob(self, expression, result_sql) 3938 3939 def reverse_sql(self, expression: exp.Reverse) -> str: 3940 result_sql = self.func("REVERSE", _cast_to_varchar(expression.this)) 3941 return _gen_with_cast_to_blob(self, expression, result_sql) 3942 3943 def _left_right_sql(self, expression: exp.Left | exp.Right, func_name: str) -> str: 3944 arg = expression.this 3945 length = expression.expression 3946 is_binary = _is_binary(arg) 3947 3948 if expression.args.get("negative_length_returns_empty"): 3949 # A negative length returns an empty string. Clamping it to 0 instead of 3950 # returning '' directly keeps the result NULL when the input is NULL. 3951 length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length) 3952 3953 if is_binary: 3954 # LEFT/RIGHT(blob, n) becomes UNHEX(LEFT/RIGHT(HEX(blob), n * 2)) 3955 # Each byte becomes 2 hex chars, so multiply length by 2 3956 hex_arg = exp.Hex(this=arg) 3957 hex_length = exp.Mul(this=length, expression=exp.Literal.number(2)) 3958 result: exp.Expression = exp.Unhex( 3959 this=exp.Anonymous(this=func_name, expressions=[hex_arg, hex_length]) 3960 ) 3961 else: 3962 result = exp.Anonymous(this=func_name, expressions=[arg, length]) 3963 3964 return self.sql(result) 3965 3966 def left_sql(self, expression: exp.Left) -> str: 3967 return self._left_right_sql(expression, "LEFT") 3968 3969 def right_sql(self, expression: exp.Right) -> str: 3970 return self._left_right_sql(expression, "RIGHT") 3971 3972 def rtrimmedlength_sql(self, expression: exp.RtrimmedLength) -> str: 3973 return self.func("LENGTH", exp.Trim(this=expression.this, position="TRAILING")) 3974 3975 def stuff_sql(self, expression: exp.Stuff) -> str: 3976 base = expression.this 3977 start = expression.args["start"] 3978 length = expression.args["length"] 3979 insertion = expression.expression 3980 is_binary = _is_binary(base) 3981 3982 if is_binary: 3983 # DuckDB's SUBSTRING doesn't accept BLOB; operate on the HEX string instead 3984 # (each byte = 2 hex chars), then UNHEX back to BLOB 3985 base = exp.Hex(this=base) 3986 insertion = exp.Hex(this=insertion) 3987 left = exp.Substring( 3988 this=base.copy(), 3989 start=exp.Literal.number(1), 3990 length=(start.copy() - exp.Literal.number(1)) * exp.Literal.number(2), 3991 ) 3992 right = exp.Substring( 3993 this=base.copy(), 3994 start=((start + length) - exp.Literal.number(1)) * exp.Literal.number(2) 3995 + exp.Literal.number(1), 3996 ) 3997 else: 3998 left = exp.Substring( 3999 this=base.copy(), 4000 start=exp.Literal.number(1), 4001 length=start.copy() - exp.Literal.number(1), 4002 ) 4003 right = exp.Substring(this=base.copy(), start=start + length) 4004 result: exp.Expr = exp.DPipe( 4005 this=exp.DPipe(this=left, expression=insertion), expression=right 4006 ) 4007 4008 if is_binary: 4009 result = exp.Unhex(this=result) 4010 4011 return self.sql(result) 4012 4013 def rand_sql(self, expression: exp.Rand) -> str: 4014 seed = expression.this 4015 if seed is not None: 4016 self.unsupported("RANDOM with seed is not supported in DuckDB") 4017 4018 lower = expression.args.get("lower") 4019 upper = expression.args.get("upper") 4020 4021 if lower and upper: 4022 # Build 64 random bits in integer arithmetic to preserve the low bits and 4023 # avoid overflow when the inclusive range spans signed BIGINT's limits. 4024 random_bits = exp.cast(exp.Floor(this=exp.Rand() * (1 << 32)), exp.DType.INT128) 4025 random = random_bits * (1 << 32) + random_bits.copy() 4026 lower = exp.cast(lower, exp.DType.INT128) 4027 upper = exp.cast(upper, exp.DType.INT128) 4028 return self.sql(exp.cast(random % (upper - lower + 1) + lower, exp.DType.BIGINT)) 4029 4030 # Default DuckDB behavior - just return RANDOM() as float 4031 return "RANDOM()" 4032 4033 def bytelength_sql(self, expression: exp.ByteLength) -> str: 4034 arg = expression.this 4035 4036 # Check if it's a text type (handles both literals and annotated expressions) 4037 if arg.is_type(*exp.DataType.TEXT_TYPES): 4038 return self.func("OCTET_LENGTH", exp.Encode(this=arg)) 4039 4040 # Default: pass through as-is (conservative for DuckDB, handles binary and unannotated) 4041 return self.func("OCTET_LENGTH", arg) 4042 4043 def base64encode_sql(self, expression: exp.Base64Encode) -> str: 4044 # DuckDB TO_BASE64 requires BLOB input 4045 # Snowflake BASE64_ENCODE accepts both VARCHAR and BINARY - for VARCHAR it implicitly 4046 # encodes UTF-8 bytes. We add ENCODE unless the input is a binary type. 4047 result = expression.this 4048 4049 # Check if input is a string type - ENCODE only accepts VARCHAR 4050 if result.is_type(*exp.DataType.TEXT_TYPES): 4051 result = exp.Encode(this=result) 4052 4053 result = exp.ToBase64(this=result) 4054 4055 max_line_length = expression.args.get("max_line_length") 4056 alphabet = expression.args.get("alphabet") 4057 4058 # Handle custom alphabet by replacing standard chars with custom ones 4059 result = _apply_base64_alphabet_replacements(result, alphabet) 4060 4061 # Handle max_line_length by inserting newlines every N characters 4062 line_length = ( 4063 t.cast(int, max_line_length.to_py()) 4064 if isinstance(max_line_length, exp.Literal) and max_line_length.is_number 4065 else 0 4066 ) 4067 if line_length > 0: 4068 newline = exp.Chr(expressions=[exp.Literal.number(10)]) 4069 result = exp.Trim( 4070 this=exp.RegexpReplace( 4071 this=result, 4072 expression=exp.Literal.string(f"(.{{{line_length}}})"), 4073 replacement=exp.Concat(expressions=[exp.Literal.string("\\1"), newline.copy()]), 4074 ), 4075 expression=newline, 4076 position="TRAILING", 4077 ) 4078 4079 return self.sql(result) 4080 4081 def hex_sql(self, expression: exp.Hex) -> str: 4082 case = expression.args.get("case") 4083 4084 if not case: 4085 return self.func("HEX", expression.this) 4086 4087 hex_expr = exp.Hex(this=expression.this) 4088 return self.sql( 4089 exp.case() 4090 .when(case.is_(exp.null()), exp.null()) 4091 .when(case.copy().eq(0), exp.Lower(this=hex_expr.copy())) 4092 .else_(hex_expr) 4093 ) 4094 4095 def replace_sql(self, expression: exp.Replace) -> str: 4096 result_sql = self.func( 4097 "REPLACE", 4098 _cast_to_varchar(expression.this), 4099 _cast_to_varchar(expression.expression), 4100 _cast_to_varchar(expression.args.get("replacement")), 4101 ) 4102 return _gen_with_cast_to_blob(self, expression, result_sql) 4103 4104 def _bitwise_op(self, expression: exp.Binary, op: str) -> str: 4105 _prepare_binary_bitwise_args(expression) 4106 result_sql = self.binary(expression, op) 4107 return _gen_with_cast_to_blob(self, expression, result_sql) 4108 4109 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 4110 _prepare_binary_bitwise_args(expression) 4111 result_sql = self.func("XOR", expression.this, expression.expression) 4112 return _gen_with_cast_to_blob(self, expression, result_sql) 4113 4114 def objectinsert_sql(self, expression: exp.ObjectInsert) -> str: 4115 this = expression.this 4116 key = expression.args.get("key") 4117 key_sql = key.name if isinstance(key, exp.Expr) else "" 4118 value_sql = self.sql(expression, "value") 4119 4120 kv_sql = f"{key_sql} := {value_sql}" 4121 4122 # If the input struct is empty e.g. transpiling OBJECT_INSERT(OBJECT_CONSTRUCT(), key, value) from Snowflake 4123 # then we can generate STRUCT_PACK which will build it since STRUCT_INSERT({}, key := value) is not valid DuckDB 4124 if isinstance(this, exp.Struct) and not this.expressions: 4125 return self.func("STRUCT_PACK", kv_sql) 4126 4127 return self.func("STRUCT_INSERT", this, kv_sql) 4128 4129 def mapcat_sql(self, expression: exp.MapCat) -> str: 4130 result = exp.replace_placeholders( 4131 self.MAPCAT_TEMPLATE.copy(), 4132 map1=expression.this, 4133 map2=expression.expression, 4134 ) 4135 return self.sql(result) 4136 4137 def mapcontainskey_sql(self, expression: exp.MapContainsKey) -> str: 4138 return self.func( 4139 "ARRAY_CONTAINS", exp.func("MAP_KEYS", expression.args["key"]), expression.this 4140 ) 4141 4142 def mapdelete_sql(self, expression: exp.MapDelete) -> str: 4143 map_arg = expression.this 4144 keys_to_delete = expression.expressions 4145 4146 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4147 4148 lambda_expr = exp.Lambda( 4149 this=exp.In(this=x_dot_key, expressions=keys_to_delete).not_(), 4150 expressions=[exp.to_identifier("x")], 4151 ) 4152 result = exp.func( 4153 "MAP_FROM_ENTRIES", 4154 exp.ArrayFilter(this=exp.func("MAP_ENTRIES", map_arg), expression=lambda_expr), 4155 ) 4156 return self.sql(result) 4157 4158 def mappick_sql(self, expression: exp.MapPick) -> str: 4159 map_arg = expression.this 4160 keys_to_pick = expression.expressions 4161 4162 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4163 4164 if len(keys_to_pick) == 1 and keys_to_pick[0].is_type(exp.DType.ARRAY): 4165 lambda_expr = exp.Lambda( 4166 this=exp.func("ARRAY_CONTAINS", keys_to_pick[0], x_dot_key), 4167 expressions=[exp.to_identifier("x")], 4168 ) 4169 else: 4170 lambda_expr = exp.Lambda( 4171 this=exp.In(this=x_dot_key, expressions=keys_to_pick), 4172 expressions=[exp.to_identifier("x")], 4173 ) 4174 4175 result = exp.func( 4176 "MAP_FROM_ENTRIES", 4177 exp.func("LIST_FILTER", exp.func("MAP_ENTRIES", map_arg), lambda_expr), 4178 ) 4179 return self.sql(result) 4180 4181 def mapsize_sql(self, expression: exp.MapSize) -> str: 4182 return self.func("CARDINALITY", expression.this) 4183 4184 @unsupported_args("update_flag") 4185 def mapinsert_sql(self, expression: exp.MapInsert) -> str: 4186 map_arg = expression.this 4187 key = expression.args.get("key") 4188 value = expression.args.get("value") 4189 4190 map_type = map_arg.type 4191 4192 if value is not None: 4193 if map_type and map_type.expressions and len(map_type.expressions) > 1: 4194 # Extract the value type from MAP(key_type, value_type) 4195 value_type = map_type.expressions[1] 4196 # Cast value to match the map's value type to avoid type conflicts 4197 value = exp.cast(value, value_type) 4198 # else: polymorphic MAP case - no type parameters available, use value as-is 4199 4200 # Create a single-entry map for the new key-value pair 4201 new_entry_struct = exp.Struct(expressions=[exp.PropertyEQ(this=key, expression=value)]) 4202 new_entry: exp.Expression = exp.ToMap(this=new_entry_struct) 4203 4204 # Use MAP_CONCAT to merge the original map with the new entry 4205 # This automatically handles both insert and update cases 4206 result = exp.func("MAP_CONCAT", map_arg, new_entry) 4207 4208 return self.sql(result) 4209 4210 def startswith_sql(self, expression: exp.StartsWith) -> str: 4211 return self.func( 4212 "STARTS_WITH", 4213 _cast_to_varchar(expression.this), 4214 _cast_to_varchar(expression.expression), 4215 ) 4216 4217 def space_sql(self, expression: exp.Space) -> str: 4218 # DuckDB's REPEAT requires BIGINT for the count parameter 4219 return self.sql( 4220 exp.Repeat( 4221 this=exp.Literal.string(" "), 4222 times=exp.cast(expression.this, exp.DType.BIGINT), 4223 ) 4224 ) 4225 4226 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 4227 # For GENERATOR, unwrap TABLE() - just emit the Generator (becomes RANGE) 4228 if isinstance(expression.this, exp.Generator): 4229 # Preserve alias, joins, and other table-level args 4230 table = exp.Table( 4231 this=expression.this, 4232 alias=expression.args.get("alias"), 4233 joins=expression.args.get("joins"), 4234 ) 4235 return self.sql(table) 4236 4237 return super().tablefromrows_sql(expression) 4238 4239 def unnest_sql(self, expression: exp.Unnest) -> str: 4240 explode_array = expression.args.get("explode_array") 4241 if explode_array: 4242 # In BigQuery, UNNESTing a nested array leads to explosion of the top-level array & struct 4243 # This is transpiled to DDB by transforming "FROM UNNEST(...)" to "FROM (SELECT UNNEST(..., max_depth => 2))" 4244 expression.expressions.append( 4245 exp.Kwarg(this=exp.var("max_depth"), expression=exp.Literal.number(2)) 4246 ) 4247 4248 # If BQ's UNNEST is aliased, we transform it from a column alias to a table alias in DDB 4249 alias = expression.args.get("alias") 4250 if isinstance(alias, exp.TableAlias): 4251 expression.set("alias", None) 4252 if alias.columns: 4253 alias = exp.TableAlias(this=seq_get(alias.columns, 0)) 4254 4255 unnest_sql = super().unnest_sql(expression) 4256 select = exp.Select(expressions=[unnest_sql]).subquery(alias) 4257 return self.sql(select) 4258 4259 if query := transforms.unnest_with_offset(expression): 4260 return self.sql(query) 4261 4262 return super().unnest_sql(expression) 4263 4264 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4265 if isinstance(expression.this, exp.Limit): 4266 self.unsupported("LIMIT inside ARRAY_AGG is not supported in DuckDB") 4267 4268 return super().arrayagg_sql(expression) 4269 4270 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 4271 this = expression.this 4272 4273 if isinstance(this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4274 # DuckDB should render IGNORE NULLS only for the general-purpose 4275 # window functions that accept it e.g. FIRST_VALUE(... IGNORE NULLS) OVER (...) 4276 return super().ignorenulls_sql(expression) 4277 4278 # For ARRAY_AGG(expr IGNORE NULLS ...), convert IGNORE NULLS to a 4279 # FILTER(WHERE expr IS NOT NULL) clause by setting nulls_excluded on 4280 # the ArrayAgg. The existing _add_arrayagg_null_filter method will 4281 # emit the FILTER clause during arrayagg_sql / withingroup_sql. 4282 if isinstance(this, exp.ArrayAgg): 4283 this.set("nulls_excluded", True) 4284 return self.sql(this) 4285 4286 if isinstance(this, exp.First): 4287 this = exp.AnyValue(this=this.this) 4288 4289 if not isinstance(this, (exp.AnyValue, exp.ApproxQuantiles)): 4290 self.unsupported("IGNORE NULLS is not supported for non-window functions.") 4291 4292 return self.sql(this) 4293 4294 def split_sql(self, expression: exp.Split) -> str: 4295 base_func = exp.func("STR_SPLIT", expression.this, expression.expression) 4296 4297 case_expr = exp.case().else_(base_func) 4298 needs_case = False 4299 4300 if expression.args.get("null_returns_null"): 4301 case_expr = case_expr.when(expression.expression.is_(exp.null()), exp.null()) 4302 needs_case = True 4303 4304 if expression.args.get("empty_delimiter_returns_whole"): 4305 # When delimiter is empty string, return input string as single array element 4306 array_with_input = exp.array(expression.this) 4307 case_expr = case_expr.when( 4308 expression.expression.eq(exp.Literal.string("")), array_with_input 4309 ) 4310 needs_case = True 4311 4312 return self.sql(case_expr if needs_case else base_func) 4313 4314 def splitpart_sql(self, expression: exp.SplitPart) -> str: 4315 string_arg = expression.this 4316 delimiter_arg = expression.args.get("delimiter") 4317 part_index_arg = expression.args.get("part_index") 4318 4319 if delimiter_arg and part_index_arg: 4320 # Handle Snowflake's "index 0 and 1 both return first element" behavior 4321 if expression.args.get("part_index_zero_as_one"): 4322 # Convert 0 to 1 for compatibility 4323 4324 part_index_arg = exp.Paren( 4325 this=exp.case() 4326 .when(part_index_arg.eq(exp.Literal.number("0")), exp.Literal.number("1")) 4327 .else_(part_index_arg) 4328 ) 4329 4330 # Use Anonymous to avoid recursion 4331 base_func_expr: exp.Expr = exp.Anonymous( 4332 this="SPLIT_PART", expressions=[string_arg, delimiter_arg, part_index_arg] 4333 ) 4334 needs_case_transform = False 4335 case_expr = exp.case().else_(base_func_expr) 4336 4337 if expression.args.get("empty_delimiter_returns_whole"): 4338 # When delimiter is empty string: 4339 # - Return whole string if part_index is 1 or -1 4340 # - Return empty string otherwise 4341 empty_case = exp.Paren( 4342 this=exp.case() 4343 .when( 4344 exp.or_( 4345 part_index_arg.eq(exp.Literal.number("1")), 4346 part_index_arg.eq(exp.Literal.number("-1")), 4347 ), 4348 string_arg, 4349 ) 4350 .else_(exp.Literal.string("")) 4351 ) 4352 4353 case_expr = case_expr.when(delimiter_arg.eq(exp.Literal.string("")), empty_case) 4354 needs_case_transform = True 4355 4356 """ 4357 Output looks something like this: 4358 4359 CASE 4360 WHEN delimiter is '' THEN 4361 ( 4362 CASE 4363 WHEN adjusted_part_index = 1 OR adjusted_part_index = -1 THEN input 4364 ELSE '' END 4365 ) 4366 ELSE SPLIT_PART(input, delimiter, adjusted_part_index) 4367 END 4368 4369 """ 4370 return self.sql(case_expr if needs_case_transform else base_func_expr) 4371 4372 return self.function_fallback_sql(expression) 4373 4374 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 4375 if isinstance(expression.this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4376 # DuckDB should render RESPECT NULLS only for the general-purpose 4377 # window functions that accept it e.g. FIRST_VALUE(... RESPECT NULLS) OVER (...) 4378 return super().respectnulls_sql(expression) 4379 4380 self.unsupported("RESPECT NULLS is not supported for non-window functions.") 4381 return self.sql(expression, "this") 4382 4383 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 4384 null = expression.args.get("null") 4385 4386 if expression.args.get("null_is_empty"): 4387 x = exp.to_identifier("x") 4388 list_transform = exp.Transform( 4389 this=expression.this.copy(), 4390 expression=exp.Lambda( 4391 this=exp.Coalesce( 4392 this=exp.cast(x, "TEXT"), expressions=[exp.Literal.string("")] 4393 ), 4394 expressions=[x], 4395 ), 4396 ) 4397 array_to_string = exp.ArrayToString( 4398 this=list_transform, expression=expression.expression 4399 ) 4400 if expression.args.get("null_delim_is_null"): 4401 return self.sql( 4402 exp.case() 4403 .when(expression.expression.copy().is_(exp.null()), exp.null()) 4404 .else_(array_to_string) 4405 ) 4406 return self.sql(array_to_string) 4407 4408 if null: 4409 x = exp.to_identifier("x") 4410 return self.sql( 4411 exp.ArrayToString( 4412 this=exp.Transform( 4413 this=expression.this, 4414 expression=exp.Lambda( 4415 this=exp.Coalesce(this=exp.cast(x, "TEXT"), expressions=[null]), 4416 expressions=[x], 4417 ), 4418 ), 4419 expression=expression.expression, 4420 ) 4421 ) 4422 4423 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 4424 4425 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4426 # DuckDB-specific: handle binary types using DPipe (||) operator 4427 separator = seq_get(expression.expressions, 0) 4428 args = expression.expressions[1:] 4429 4430 if any(_is_binary(arg) for arg in [separator, *args]): 4431 result = args[0] 4432 for arg in args[1:]: 4433 result = exp.DPipe( 4434 this=exp.DPipe(this=result, expression=separator), expression=arg 4435 ) 4436 return self.sql(result) 4437 4438 if expression.args.get("flatten") and any( 4439 isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY) for arg in args 4440 ): 4441 arrays = [] 4442 for arg in args: 4443 if isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY): 4444 arg = exp.cast(arg, "TEXT[]") 4445 else: 4446 if (not arg.type or arg.is_type(exp.DType.UNKNOWN)) and not isinstance( 4447 arg, exp.CONSTANTS 4448 ): 4449 self.unsupported( 4450 "Cannot transpile CONCAT_WS with unknown argument types to DuckDB." 4451 ) 4452 arg = exp.array(exp.cast(arg, exp.DType.TEXT)) 4453 4454 arrays.append(arg) 4455 4456 array = ( 4457 exp.ArrayConcat(this=arrays[0], expressions=arrays[1:]) 4458 if len(arrays) > 1 4459 else arrays[0] 4460 ) 4461 return self.func("CONCAT_WS", separator, self.func("ARRAY_TO_STRING", array, separator)) 4462 4463 return super().concatws_sql(expression) 4464 4465 def _regexp_extract_sql(self, expression: exp.RegexpExtract | exp.RegexpExtractAll) -> str: 4466 this = expression.this 4467 group = expression.args.get("group") 4468 params = expression.args.get("parameters") 4469 position = expression.args.get("position") 4470 occurrence = expression.args.get("occurrence") 4471 null_if_pos_overflow = expression.args.get("null_if_pos_overflow") 4472 null_if_no_match = expression.args.get("null_if_no_match") 4473 4474 # Handle Snowflake's 'e' flag: it enables capture group extraction 4475 # In DuckDB, this is controlled by the group parameter directly 4476 if params and params.is_string and "e" in params.name: 4477 params = exp.Literal.string(params.name.replace("e", "")) 4478 4479 validated_flags = self._validate_regexp_flags(params, supported_flags="cims") 4480 4481 # Strip default group when no following params (DuckDB default is same as group=0) 4482 if ( 4483 not validated_flags 4484 and group 4485 and group.name == str(self.dialect.REGEXP_EXTRACT_DEFAULT_GROUP) 4486 ): 4487 group = None 4488 4489 flags_expr = exp.Literal.string(validated_flags) if validated_flags else None 4490 4491 # use substring to handle position argument 4492 if position and (not position.is_int or position.to_py() > 1): 4493 this = exp.Substring(this=this, start=position) 4494 4495 if null_if_pos_overflow: 4496 this = exp.Nullif(this=this, expression=exp.Literal.string("")) 4497 4498 is_extract_all = isinstance(expression, exp.RegexpExtractAll) 4499 non_single_occurrence = occurrence and (not occurrence.is_int or occurrence.to_py() > 1) 4500 4501 if is_extract_all or non_single_occurrence or null_if_no_match: 4502 name = "REGEXP_EXTRACT_ALL" 4503 else: 4504 name = "REGEXP_EXTRACT" 4505 4506 result: exp.Expr = exp.Anonymous( 4507 this=name, expressions=[this, expression.expression, group, flags_expr] 4508 ) 4509 4510 # Array slicing for REGEXP_EXTRACT_ALL with occurrence 4511 if is_extract_all and non_single_occurrence: 4512 result = exp.Bracket(this=result, expressions=[exp.Slice(this=occurrence)]) 4513 elif not is_extract_all and (non_single_occurrence or null_if_no_match): 4514 # Non-participating capture group yields [NULL] in DuckDB; Snowflake returns '' on a match 4515 if ( 4516 expression.args.get("empty_if_group_missing") 4517 and group 4518 and not (group.is_int and group.to_py() == 0) 4519 ): 4520 result = exp.Transform( 4521 this=result, 4522 expression=exp.Lambda( 4523 this=exp.Coalesce( 4524 this=exp.column("x"), expressions=[exp.Literal.string("")] 4525 ), 4526 expressions=[exp.to_identifier("x")], 4527 ), 4528 ) 4529 return self.func( 4530 "ARRAY_EXTRACT", 4531 result, 4532 occurrence if non_single_occurrence else exp.Literal.number(1), 4533 ) 4534 4535 return self.sql(result) 4536 4537 def regexpextract_sql(self, expression: exp.RegexpExtract) -> str: 4538 return self._regexp_extract_sql(expression) 4539 4540 def regexpextractall_sql(self, expression: exp.RegexpExtractAll) -> str: 4541 return self._regexp_extract_sql(expression) 4542 4543 def regexpinstr_sql(self, expression: exp.RegexpInstr) -> str: 4544 this = expression.this 4545 pattern = expression.expression 4546 position = expression.args.get("position") 4547 orig_occ = expression.args.get("occurrence") 4548 occurrence = orig_occ or exp.Literal.number(1) 4549 option = expression.args.get("option") 4550 parameters = expression.args.get("parameters") 4551 4552 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 4553 # Checked before the flags are embedded, which would make the pattern non-empty 4554 is_empty = pattern.copy().eq(exp.Literal.string("")) 4555 if validated_flags: 4556 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 4557 4558 # Handle starting position offset 4559 pos_offset: exp.Expr = exp.Literal.number(0) 4560 if position and (not position.is_int or position.to_py() > 1): 4561 this = exp.Substring(this=this, start=position) 4562 pos_offset = position - exp.Literal.number(1) 4563 4564 # Helper: LIST_SUM(LIST_TRANSFORM(list[1:end], x -> LENGTH(x))) 4565 def sum_lengths(func_name: str, end: exp.Expr) -> exp.Expr: 4566 lst = exp.Bracket( 4567 this=exp.Anonymous(this=func_name, expressions=[this, pattern]), 4568 expressions=[exp.Slice(this=exp.Literal.number(1), expression=end)], 4569 offset=1, 4570 ) 4571 transform = exp.Anonymous( 4572 this="LIST_TRANSFORM", 4573 expressions=[ 4574 lst, 4575 exp.Lambda( 4576 this=exp.Length(this=exp.to_identifier("x")), 4577 expressions=[exp.to_identifier("x")], 4578 ), 4579 ], 4580 ) 4581 return exp.Coalesce( 4582 this=exp.Anonymous(this="LIST_SUM", expressions=[transform]), 4583 expressions=[exp.Literal.number(0)], 4584 ) 4585 4586 # Position = 1 + sum(split_lengths[1:occ]) + sum(match_lengths[1:occ-1]) + offset 4587 base_pos: exp.Expr = ( 4588 exp.Literal.number(1) 4589 + sum_lengths("STRING_SPLIT_REGEX", occurrence) 4590 + sum_lengths("REGEXP_EXTRACT_ALL", occurrence - exp.Literal.number(1)) 4591 + pos_offset 4592 ) 4593 4594 # option=1: add match length for end position 4595 if option and option.is_int and option.to_py() == 1: 4596 match_at_occ = exp.Bracket( 4597 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]), 4598 expressions=[occurrence], 4599 offset=1, 4600 ) 4601 base_pos = base_pos + exp.Coalesce( 4602 this=exp.Length(this=match_at_occ), expressions=[exp.Literal.number(0)] 4603 ) 4604 4605 # NULL checks for all provided arguments 4606 # .copy() is used strictly because .is_() alters the node's parent pointer, mutating the parsed AST 4607 null_args = [ 4608 expression.this, 4609 expression.expression, 4610 position, 4611 orig_occ, 4612 option, 4613 parameters, 4614 ] 4615 null_checks = [arg.copy().is_(exp.Null()) for arg in null_args if arg] 4616 4617 matches = exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 4618 4619 return self.sql( 4620 exp.case() 4621 .when(exp.or_(*null_checks), exp.Null()) 4622 .when(is_empty, exp.Literal.number(0)) 4623 .when(exp.Length(this=matches) < occurrence, exp.Literal.number(0)) 4624 .else_(base_pos) 4625 ) 4626 4627 @unsupported_args("culture") 4628 def numbertostr_sql(self, expression: exp.NumberToStr) -> str: 4629 fmt = expression.args.get("format") 4630 if fmt and fmt.is_int: 4631 return self.func("FORMAT", f"'{{:,.{fmt.name}f}}'", expression.this) 4632 4633 self.unsupported("Only integer formats are supported by NumberToStr") 4634 return self.function_fallback_sql(expression) 4635 4636 def autoincrementcolumnconstraint_sql(self, _) -> str: 4637 self.unsupported("The AUTOINCREMENT column constraint is not supported by DuckDB") 4638 return "" 4639 4640 def onconflict_sql(self, expression: exp.OnConflict) -> str: 4641 if expression.arg_key == "on_conflict": 4642 self.unsupported("DuckDB does not support ON CONFLICT on table or column constraints") 4643 return "" 4644 return super().onconflict_sql(expression) 4645 4646 def aliases_sql(self, expression: exp.Aliases) -> str: 4647 this = expression.this 4648 if isinstance(this, exp.Posexplode): 4649 return self.posexplode_sql(this) 4650 4651 return super().aliases_sql(expression) 4652 4653 def posexplode_sql(self, expression: exp.Posexplode) -> str: 4654 this = expression.this 4655 parent = expression.parent 4656 4657 # The default Spark aliases are "pos" and "col", unless specified otherwise 4658 pos, col = exp.to_identifier("pos"), exp.to_identifier("col") 4659 4660 if isinstance(parent, exp.Aliases): 4661 # Column case: SELECT POSEXPLODE(col) [AS (a, b)] 4662 pos, col = parent.expressions 4663 elif isinstance(parent, exp.Table): 4664 # Table case: SELECT * FROM POSEXPLODE(col) [AS (a, b)] 4665 alias = parent.args.get("alias") 4666 if alias: 4667 pos, col = alias.columns or [pos, col] 4668 alias.pop() 4669 4670 # Translate POSEXPLODE to UNNEST + GENERATE_SUBSCRIPTS 4671 # Note: In Spark pos is 0-indexed, but in DuckDB it's 1-indexed, so we subtract 1 from GENERATE_SUBSCRIPTS 4672 unnest_sql = self.sql(exp.Unnest(expressions=[this], alias=col)) 4673 gen_subscripts = self.sql( 4674 exp.Alias( 4675 this=exp.Anonymous( 4676 this="GENERATE_SUBSCRIPTS", expressions=[this, exp.Literal.number(1)] 4677 ) 4678 - exp.Literal.number(1), 4679 alias=pos, 4680 ) 4681 ) 4682 4683 posexplode_sql = self.format_args(gen_subscripts, unnest_sql) 4684 4685 if isinstance(parent, exp.From) or (parent and isinstance(parent.parent, exp.From)): 4686 # SELECT * FROM POSEXPLODE(col) -> SELECT * FROM (SELECT GENERATE_SUBSCRIPTS(...), UNNEST(...)) 4687 return self.sql(exp.Subquery(this=exp.Select(expressions=[posexplode_sql]))) 4688 4689 return posexplode_sql 4690 4691 def addmonths_sql(self, expression: exp.AddMonths) -> str: 4692 """ 4693 Handles three key issues: 4694 1. Float/decimal months: e.g., Snowflake rounds, whereas DuckDB INTERVAL requires integers 4695 2. End-of-month preservation: If input is last day of month, result is last day of result month 4696 3. Type preservation: Maintains DATE/TIMESTAMPTZ types (DuckDB defaults to TIMESTAMP) 4697 """ 4698 from sqlglot.optimizer.annotate_types import annotate_types 4699 4700 this = expression.this 4701 if not this.type: 4702 this = annotate_types(this, dialect=self.dialect) 4703 4704 if this.is_type(*exp.DataType.TEXT_TYPES): 4705 this = exp.Cast(this=this, to=exp.DataType(this=exp.DType.TIMESTAMP)) 4706 4707 # Detect float/decimal months to apply rounding (Snowflake behavior) 4708 # DuckDB INTERVAL syntax doesn't support non-integer expressions, so use TO_MONTHS 4709 months_expr = expression.expression 4710 if not months_expr.type: 4711 months_expr = annotate_types(months_expr, dialect=self.dialect) 4712 4713 # Build interval or to_months expression based on type 4714 # Float/decimal case: Round and use TO_MONTHS(CAST(ROUND(value) AS INT)) 4715 interval_or_to_months = ( 4716 exp.func("TO_MONTHS", exp.cast(exp.func("ROUND", months_expr), "INT")) 4717 if months_expr.is_type( 4718 exp.DType.FLOAT, 4719 exp.DType.DOUBLE, 4720 exp.DType.DECIMAL, 4721 ) 4722 # Integer case: standard INTERVAL N MONTH syntax 4723 else exp.Interval(this=months_expr, unit=exp.var("MONTH")) 4724 ) 4725 4726 date_add_expr = exp.Add(this=this, expression=interval_or_to_months) 4727 4728 # Apply end-of-month preservation if Snowflake flag is set 4729 # CASE WHEN LAST_DAY(date) = date THEN LAST_DAY(result) ELSE result END 4730 preserve_eom = expression.args.get("preserve_end_of_month") 4731 result_expr = ( 4732 exp.case() 4733 .when( 4734 exp.EQ(this=exp.func("LAST_DAY", this), expression=this), 4735 exp.func("LAST_DAY", date_add_expr), 4736 ) 4737 .else_(date_add_expr) 4738 if preserve_eom 4739 else date_add_expr 4740 ) 4741 4742 # DuckDB's DATE_ADD function returns TIMESTAMP/DATETIME by default, even when the input is DATE 4743 # To match for example Snowflake's ADD_MONTHS behavior (which preserves the input type) 4744 # We need to cast the result back to the original type when the input is DATE or TIMESTAMPTZ 4745 # Example: ADD_MONTHS('2023-01-31'::date, 1) should return DATE, not TIMESTAMP 4746 if this.is_type(exp.DType.DATE, exp.DType.TIMESTAMPTZ): 4747 return self.sql(exp.Cast(this=result_expr, to=this.type)) 4748 return self.sql(result_expr) 4749 4750 def format_sql(self, expression: exp.Format) -> str: 4751 if expression.args.get("is_fmt"): 4752 return self.func("FORMAT", expression.this, *expression.expressions) 4753 4754 fmt = expression.name 4755 if expression.this.is_string and fmt == "%S" and len(expression.expressions) == 1: 4756 return self.func( 4757 "UPPER", self.func("FORMAT", exp.Literal.string("{}"), expression.expressions[0]) 4758 ) 4759 4760 if expression.this.is_string and "%s" in fmt and "%" not in re.sub(r"%%|%s", "", fmt): 4761 # Use brace formatting to support non-string %s arguments, as in PostgreSQL. 4762 fmt = fmt.replace("{", "{{").replace("}", "}}") 4763 fmt = re.sub(r"%%|%s", lambda m: "%" if m[0] == "%%" else "{}", fmt) 4764 return self.func("FORMAT", exp.Literal.string(fmt), *expression.expressions) 4765 4766 return self.func("PRINTF", expression.this, *expression.expressions) 4767 4768 def hexstring_sql( 4769 self, expression: exp.HexString, binary_function_repr: str | None = None 4770 ) -> str: 4771 # UNHEX('FF') correctly produces blob \xFF in DuckDB 4772 return super().hexstring_sql(expression, binary_function_repr="UNHEX") 4773 4774 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 4775 unit = expression.args.get("unit") 4776 date = expression.this 4777 4778 week_start = _week_trunc_start_dow(unit) 4779 unit = ( 4780 unit_to_str(expression) 4781 if week_start 4782 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4783 ) 4784 4785 if week_start: 4786 result = self.sql( 4787 _build_week_trunc_expression(date, week_start, preserve_start_day=True) 4788 ) 4789 else: 4790 result = self.func("DATE_TRUNC", unit, date) 4791 4792 if expression.args.get("input_type_preserved") and date.is_type( 4793 *exp.DataType.TEMPORAL_TYPES 4794 ): 4795 return self.sql(exp.Cast(this=result, to=date.type)) 4796 4797 return result 4798 4799 def datetimetrunc_sql(self, expression: exp.DatetimeTrunc) -> str: 4800 this = exp.cast(expression.this, exp.DType.DATETIME) 4801 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4802 if week_start: 4803 return self.sql( 4804 _build_week_trunc_expression( 4805 this, week_start, preserve_start_day=True, cast_to_date=False 4806 ) 4807 ) 4808 4809 return self.func("DATE_TRUNC", unit_to_str(expression), this) 4810 4811 def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str: 4812 zone = expression.args.get("zone") 4813 timestamp = expression.this 4814 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4815 4816 # The week start emulation below is exact, so avoid weekstart_unit_to_str's degrade warning 4817 unit = ( 4818 unit_to_str(expression) 4819 if week_start 4820 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4821 ) 4822 date_unit = is_date_unit(unit) or bool(week_start) 4823 4824 def _trunc_expr(this: exp.Expr) -> exp.Expr: 4825 if week_start: 4826 return _build_week_trunc_expression( 4827 this, week_start, preserve_start_day=True, cast_to_date=False 4828 ) 4829 return exp.DateTrunc( 4830 unit=unit, 4831 this=this, 4832 century_from_zero=expression.args.get("century_from_zero"), 4833 ) 4834 4835 if date_unit and zone: 4836 # BigQuery's TIMESTAMP_TRUNC with timezone truncates in the target timezone and returns as UTC. 4837 # Double AT TIME ZONE needed for BigQuery compatibility: 4838 # 1. First AT TIME ZONE: ensures truncation happens in the target timezone 4839 # 2. Second AT TIME ZONE: converts the DATE result back to TIMESTAMPTZ (preserving time component) 4840 timestamp = exp.AtTimeZone(this=timestamp, zone=zone) 4841 trunced = _trunc_expr(timestamp) 4842 if isinstance(trunced, exp.DateAdd): 4843 # Parenthesize so the trailing AT TIME ZONE binds to the whole shifted expression 4844 trunced = exp.Paren(this=trunced) 4845 return self.sql(exp.AtTimeZone(this=trunced, zone=zone)) 4846 4847 result = self.sql(_trunc_expr(timestamp)) 4848 if expression.args.get("input_type_preserved"): 4849 if timestamp.type and timestamp.is_type(exp.DType.TIME, exp.DType.TIMETZ): 4850 dummy_date = exp.Cast( 4851 this=exp.Literal.string("1970-01-01"), 4852 to=exp.DataType(this=exp.DType.DATE), 4853 ) 4854 date_time = exp.Add(this=dummy_date, expression=timestamp) 4855 result = self.func("DATE_TRUNC", unit, date_time) 4856 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4857 4858 if timestamp.is_type(*exp.DataType.TEMPORAL_TYPES): 4859 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4860 4861 return result 4862 4863 def timestampdiff_sql(self, expression: exp.TimestampDiff) -> str: 4864 unit = expression.unit 4865 4866 if _is_nanosecond_unit(unit): 4867 return _handle_nanosecond_diff(self, expression.this, expression.expression) 4868 4869 unit_str = unit.name.upper() if isinstance(unit, (exp.Var, exp.Literal)) else "" 4870 4871 if expression.args.get("boundary_for_date") and all( 4872 arg.is_type(exp.DType.DATE, exp.DType.DATETIME, exp.DType.TIMESTAMP) 4873 for arg in (expression.this, expression.expression) 4874 ): 4875 return _date_diff_sql( 4876 self, 4877 exp.DateDiff( 4878 this=expression.this, 4879 expression=expression.expression, 4880 unit=unit, 4881 date_part_boundary=True, 4882 ), 4883 ) 4884 4885 # Cast untyped args (bare NULLs, string literals) so DuckDB can resolve the overload 4886 this = ( 4887 exp.cast(expression.this, exp.DType.TIMESTAMPTZ) 4888 if isinstance(expression.this, (exp.Null, exp.Literal)) 4889 else expression.this 4890 ) 4891 expr = ( 4892 exp.cast(expression.expression, exp.DType.TIMESTAMPTZ) 4893 if isinstance(expression.expression, (exp.Null, exp.Literal)) 4894 else expression.expression 4895 ) 4896 4897 if unit_str == "DAY": 4898 date_sub = exp.func( 4899 "DATE_SUB", exp.Literal.string("HOUR"), expr, this, dialect="duckdb" 4900 ) 4901 return self.sql(exp.IntDiv(this=date_sub, expression=exp.Literal.number(24))) 4902 4903 return self.func("DATE_SUB", unit_to_str(expression), expr, this) 4904 4905 def trim_sql(self, expression: exp.Trim) -> str: 4906 expression.this.replace(_cast_to_varchar(expression.this)) 4907 if expression.expression: 4908 expression.expression.replace(_cast_to_varchar(expression.expression)) 4909 4910 result_sql = super().trim_sql(expression) 4911 return _gen_with_cast_to_blob(self, expression, result_sql) 4912 4913 def round_sql(self, expression: exp.Round) -> str: 4914 this = expression.this 4915 decimals = expression.args.get("decimals") 4916 truncate = expression.args.get("truncate") 4917 4918 if decimals is not None and expression.args.get("negative_decimals_are_zero"): 4919 if decimals.is_int: 4920 decimals = exp.Literal.number(max(0, decimals.to_py())) 4921 else: 4922 # DuckDB's DECIMAL overload requires constant precision; SQLite rounds doubles. 4923 this = exp.cast(this, exp.DType.DOUBLE) 4924 # Preserve NULL precision, which GREATEST(decimals, 0) would replace with 0. 4925 decimals = exp.If( 4926 this=decimals < 0, true=exp.Literal.number(0), false=decimals.copy() 4927 ) 4928 4929 # DuckDB requires the scale (decimals) argument to be an INT 4930 # Some dialects (e.g., Snowflake) allow non-integer scales and cast to an integer internally 4931 if decimals is not None and expression.args.get("casts_non_integer_decimals"): 4932 if not (decimals.is_int or decimals.is_type(*_ROUND_SCALE_INTEGER_TYPES)): 4933 decimals = exp.cast(decimals, exp.DType.INT) 4934 4935 func = "ROUND" 4936 if truncate: 4937 # BigQuery uses ROUND_HALF_EVEN; Snowflake uses HALF_TO_EVEN 4938 if truncate.this in ("ROUND_HALF_EVEN", "HALF_TO_EVEN"): 4939 func = "ROUND_EVEN" 4940 truncate = None 4941 # BigQuery uses ROUND_HALF_AWAY_FROM_ZERO; Snowflake uses HALF_AWAY_FROM_ZERO 4942 elif truncate.this in ("ROUND_HALF_AWAY_FROM_ZERO", "HALF_AWAY_FROM_ZERO"): 4943 truncate = None 4944 4945 return self.func(func, this, decimals, truncate) 4946 4947 def trycast_sql(self, expression: exp.TryCast) -> str: 4948 to = expression.to 4949 to_type = to.this 4950 src = expression.this 4951 4952 if ( 4953 expression.args.get("null_on_text_overflow") 4954 and to_type in exp.DataType.TEXT_TYPES 4955 and to.expressions 4956 ): 4957 return self.sql( 4958 exp.case() 4959 .when( 4960 exp.LTE(this=exp.func("LENGTH", src), expression=to.expressions[0].this), 4961 exp.cast(src, "TEXT"), 4962 ) 4963 .else_(exp.Null()) 4964 ) 4965 elif to_type == exp.DType.DATE and expression.args.get("probe_date_format"): 4966 slash_strptime = exp.cast( 4967 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_SLASH_FMT)), 4968 "DATE", 4969 ) 4970 mon_strptime = exp.cast( 4971 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_MON_FMT)), 4972 "DATE", 4973 ) 4974 return self.sql( 4975 exp.case() 4976 .when(exp.func("CONTAINS", src, exp.Literal.string("/")), slash_strptime) 4977 .when( 4978 exp.RegexpLike(this=src, expression=exp.Literal.string("[A-Za-z]")), 4979 mon_strptime, 4980 ) 4981 .else_(exp.TryCast(this=src, to=to)) 4982 ) 4983 elif ( 4984 isinstance(to_type, exp.Interval) 4985 and (unit := to_type.unit) 4986 and expression.args.get("requires_string") 4987 ): 4988 interval_type = exp.DataType.build("INTERVAL") 4989 if isinstance(unit, exp.IntervalSpan): 4990 self.unsupported( 4991 "TRY_CAST to INTERVAL with span (e.g. HOUR TO MINUTE) is not supported in DuckDB" 4992 ) 4993 return self.sql(exp.TryCast(this=src, to=interval_type)) 4994 return self.sql( 4995 exp.TryCast( 4996 this=exp.DPipe(this=src, expression=exp.Literal.string(f" {unit.name}")), 4997 to=interval_type, 4998 ) 4999 ) 5000 5001 return super().trycast_sql(expression) 5002 5003 def strtok_sql(self, expression: exp.Strtok) -> str: 5004 string_arg = expression.this 5005 delimiter_arg = expression.args.get("delimiter") 5006 part_index_arg = expression.args.get("part_index") 5007 5008 if delimiter_arg and part_index_arg: 5009 # Escape regex chars and build character class at runtime using REGEXP_REPLACE 5010 escaped_delimiter = exp.Anonymous( 5011 this="REGEXP_REPLACE", 5012 expressions=[ 5013 delimiter_arg, 5014 exp.Literal.string( 5015 r"([\[\]^.\-*+?(){}|$\\])" 5016 ), # Escape problematic regex chars 5017 exp.Literal.string( 5018 r"\\\1" 5019 ), # Replace with escaped version using $1 backreference 5020 exp.Literal.string("g"), # Global flag 5021 ], 5022 ) 5023 # CASE WHEN delimiter = '' THEN '' ELSE CONCAT('[', escaped_delimiter, ']') END 5024 regex_pattern = ( 5025 exp.case() 5026 .when(delimiter_arg.eq(exp.Literal.string("")), exp.Literal.string("")) 5027 .else_( 5028 exp.func( 5029 "CONCAT", 5030 exp.Literal.string("["), 5031 escaped_delimiter, 5032 exp.Literal.string("]"), 5033 ) 5034 ) 5035 ) 5036 5037 # STRTOK skips empty strings, so we need to filter them out 5038 # LIST_FILTER(REGEXP_SPLIT_TO_ARRAY(string, pattern), x -> x != '')[index] 5039 split_array = exp.func("REGEXP_SPLIT_TO_ARRAY", string_arg, regex_pattern) 5040 x = exp.to_identifier("x") 5041 is_empty = x.eq(exp.Literal.string("")) 5042 filtered_array = exp.func( 5043 "LIST_FILTER", 5044 split_array, 5045 exp.Lambda(this=exp.not_(is_empty.copy()), expressions=[x.copy()]), 5046 ) 5047 base_func = exp.Bracket( 5048 this=filtered_array, 5049 expressions=[part_index_arg], 5050 offset=1, 5051 ) 5052 5053 # Use template with the built regex pattern 5054 result = exp.replace_placeholders( 5055 self.STRTOK_TEMPLATE.copy(), 5056 string=string_arg, 5057 delimiter=delimiter_arg, 5058 part_index=part_index_arg, 5059 base_func=base_func, 5060 ) 5061 5062 return self.sql(result) 5063 5064 return self.function_fallback_sql(expression) 5065 5066 def strtoktoarray_sql(self, expression: exp.StrtokToArray) -> str: 5067 string_arg = expression.this 5068 delimiter_arg = expression.args.get("expression") or exp.Literal.string(" ") 5069 5070 escaped = exp.RegexpReplace( 5071 this=delimiter_arg.copy(), 5072 expression=exp.Literal.string(r"([\[\]^.\-*+?(){}|$\\])"), 5073 replacement=exp.Literal.string(r"\\\1"), 5074 modifiers=exp.Literal.string("g"), 5075 ) 5076 return self.sql( 5077 exp.replace_placeholders( 5078 self.STRTOK_TO_ARRAY_TEMPLATE.copy(), 5079 string=string_arg, 5080 delimiter=delimiter_arg, 5081 escaped=escaped, 5082 ) 5083 ) 5084 5085 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 5086 result = self.func("APPROX_QUANTILE", expression.this, expression.args.get("quantile")) 5087 5088 # DuckDB returns the input's type, e.g. an integer or DECIMAL, so cast when a float is expected 5089 if expression.is_type(*exp.DataType.FLOAT_TYPES): 5090 result = f"CAST({result} AS DOUBLE)" 5091 5092 return result 5093 5094 def approxquantiles_sql(self, expression: exp.ApproxQuantiles) -> str: 5095 """ 5096 BigQuery's APPROX_QUANTILES(expr, n) returns an array of n+1 approximate quantile values 5097 dividing the input distribution into n equal-sized buckets. 5098 5099 Both BigQuery and DuckDB use approximate algorithms for quantile estimation, but BigQuery 5100 does not document the specific algorithm used so results may differ. DuckDB does not 5101 support RESPECT NULLS. 5102 """ 5103 this = expression.this 5104 if isinstance(this, exp.Distinct): 5105 # APPROX_QUANTILES requires 2 args and DISTINCT node grabs both 5106 if len(this.expressions) < 2: 5107 self.unsupported("APPROX_QUANTILES requires a bucket count argument") 5108 return self.function_fallback_sql(expression) 5109 num_quantiles_expr = this.expressions[1].pop() 5110 else: 5111 num_quantiles_expr = expression.expression 5112 5113 if not isinstance(num_quantiles_expr, exp.Literal) or not num_quantiles_expr.is_int: 5114 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5115 return self.function_fallback_sql(expression) 5116 5117 num_quantiles = t.cast(int, num_quantiles_expr.to_py()) 5118 if num_quantiles <= 0: 5119 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5120 return self.function_fallback_sql(expression) 5121 5122 quantiles = [ 5123 exp.Literal.number(Decimal(i) / Decimal(num_quantiles)) 5124 for i in range(num_quantiles + 1) 5125 ] 5126 5127 return self.sql(exp.ApproxQuantile(this=this, quantile=exp.Array(expressions=quantiles))) 5128 5129 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 5130 if expression.args.get("scalar_only"): 5131 json_value = exp.JSONExtractScalar( 5132 this=rename_func("JSON_VALUE")(self, expression), expression="'$'" 5133 ) 5134 5135 # `->>` binds looser than most operators, so the wrap logic needs the parent 5136 json_value.parent = expression.parent 5137 expression = json_value 5138 5139 return _arrow_json_extract_sql(self, expression) 5140 5141 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 5142 this = expression.this 5143 5144 if _is_binary(this): 5145 expression.type = exp.DType.BINARY.into_expr() 5146 5147 arg = _cast_to_bit(this) 5148 5149 if isinstance(this, exp.Neg): 5150 arg = exp.Paren(this=arg) 5151 5152 expression.set("this", arg) 5153 5154 result_sql = f"~{self.sql(expression, 'this')}" 5155 5156 return _gen_with_cast_to_blob(self, expression, result_sql) 5157 5158 def window_sql(self, expression: exp.Window) -> str: 5159 this = expression.this 5160 if isinstance(this, exp.Corr) or ( 5161 isinstance(this, exp.Filter) and isinstance(this.this, exp.Corr) 5162 ): 5163 return self._corr_sql(expression) 5164 5165 return self._arg_max_or_min_with_count_sql(expression) or super().window_sql(expression) 5166 5167 def filter_sql(self, expression: exp.Filter) -> str: 5168 if isinstance(expression.this, exp.Corr): 5169 return self._corr_sql(expression) 5170 5171 return self._arg_max_or_min_with_count_sql(expression) or super().filter_sql(expression) 5172 5173 def _arg_max_or_min_with_count_sql(self, expression: exp.Expr) -> str | None: 5174 agg = _unwrap_aggregate_modifiers(expression) 5175 if not ( 5176 isinstance(agg, (exp.ArgMax, exp.ArgMin)) 5177 and agg.args.get("count") 5178 and agg.args.get("include_nulls") 5179 ): 5180 return None 5181 5182 # DuckDB's three-argument aggregate skips NULL values. Rank singleton lists 5183 # so [NULL] participates, then unwrap them after any FILTER or OVER clause. 5184 expression = expression.copy() 5185 expression.comments = None 5186 agg = _unwrap_aggregate_modifiers(expression) 5187 value = agg.this 5188 if isinstance(value, exp.Distinct): 5189 value.set("expressions", [exp.array(value.expressions[0], copy=False)]) 5190 else: 5191 agg.set("this", exp.array(value, copy=False)) 5192 agg.set("include_nulls", None) 5193 return self.func("FLATTEN", expression) 5194 5195 def _corr_sql( 5196 self, 5197 expression: exp.Filter | exp.Window | exp.Corr, 5198 ) -> str: 5199 if isinstance(expression, exp.Corr) and not expression.args.get("null_on_zero_variance"): 5200 return self.func("CORR", expression.this, expression.expression) 5201 5202 corr_expr = _maybe_corr_null_to_false(expression) 5203 if corr_expr is None: 5204 if isinstance(expression, exp.Window): 5205 return super().window_sql(expression) 5206 if isinstance(expression, exp.Filter): 5207 return super().filter_sql(expression) 5208 corr_expr = expression # make mypy happy 5209 5210 return self.sql(exp.case().when(exp.IsNan(this=corr_expr), exp.null()).else_(corr_expr)) 5211 5212 def uuid_sql(self, expression: exp.Uuid) -> str: 5213 namespace = expression.this 5214 name = expression.args.get("name") 5215 5216 # UUID v5 (namespace + name) - Emulate using SHA1 5217 if namespace and name: 5218 result = exp.replace_placeholders( 5219 self.UUID_V5_TEMPLATE.copy(), 5220 namespace=namespace, 5221 name=name, 5222 ) 5223 return self.sql(result) 5224 5225 return super().uuid_sql(expression)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True
2451 def datatype_sql(self, expression: exp.DataType) -> str: 2452 if expression.is_type(exp.DType.ARRAY): 2453 return f"{self.expressions(expression, flat=True)}[{self.expressions(expression, key='values', flat=True)}]" 2454 2455 # Modifiers are not supported for TIME, [TIME | TIMESTAMP] WITH TIME ZONE 2456 if expression.is_type( 2457 exp.DType.TIME, exp.DType.TIMETZ, exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ 2458 ): 2459 expression.set("expressions", None) 2460 2461 return super().datatype_sql(expression)
2469 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 2470 """ 2471 Transform Snowflake's TIME_SLICE to DuckDB's time_bucket. 2472 2473 Snowflake: TIME_SLICE(date_expr, slice_length, 'UNIT' [, 'START'|'END']) 2474 DuckDB: time_bucket(INTERVAL 'slice_length' UNIT, date_expr, origin) 2475 2476 Snowflake aligns slices to the 1970-01-01 epoch, so an explicit origin is 2477 required because DuckDB's default origin differs. For 'END' kind, add the 2478 interval to get the next slice's start; for DATE input, cast back to DATE. 2479 """ 2480 date_expr = expression.this 2481 slice_length = expression.expression 2482 # Normalize unit aliases (e.g. W/WK/WOY -> WEEK) so the interval and origin agree 2483 unit = map_date_part(expression.unit, self.dialect) 2484 kind = expression.text("kind").upper() 2485 2486 interval_expr = exp.Interval(this=slice_length, unit=unit) 2487 2488 origin = expression.args.get("origin") 2489 if origin is None: 2490 # Snowflake aligns to 1970-01-01; WEEK to the Monday of the epoch week (WEEK_START=0) 2491 origin = exp.Literal.string( 2492 "1969-12-29" if unit and unit.name.upper() == "WEEK" else "1970-01-01" 2493 ) 2494 # A DATE origin keeps a DATE input a DATE; DuckDB widens it for TIMESTAMP inputs 2495 time_bucket_expr = exp.func( 2496 "time_bucket", interval_expr, date_expr, exp.cast(origin, exp.DType.DATE) 2497 ) 2498 2499 if kind != "END": 2500 return self.sql(time_bucket_expr) 2501 2502 add_expr = exp.Add(this=time_bucket_expr, expression=interval_expr.copy()) 2503 2504 # DuckDB widens DATE to TIMESTAMP when adding intervals, so cast back 2505 if date_expr.is_type(exp.DType.DATE): 2506 return self.sql(exp.cast(add_expr, exp.DType.DATE)) 2507 2508 return self.sql(add_expr)
Transform Snowflake's TIME_SLICE to DuckDB's time_bucket.
Snowflake: TIME_SLICE(date_expr, slice_length, 'UNIT' [, 'START'|'END']) DuckDB: time_bucket(INTERVAL 'slice_length' UNIT, date_expr, origin)
Snowflake aligns slices to the 1970-01-01 epoch, so an explicit origin is required because DuckDB's default origin differs. For 'END' kind, add the interval to get the next slice's start; for DATE input, cast back to DATE.
2510 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 2511 # DuckDB has no Unicode escape strings and doesn't read \u in a string, so the escapes 2512 # are decoded into the characters, e.g. U&'d\0061t\0061' and U&'d!+000061ta' UESCAPE '!' 2513 # are both 'data' 2514 escape = expression.args.get("escape") 2515 text = decode_unicode_escapes( 2516 expression.name, escape.name if isinstance(escape, exp.Expr) else "\\" 2517 ) 2518 return self.sql(exp.Literal.string(text))
2520 def bytestring_sql(self, expression: exp.ByteString) -> str: 2521 if not expression.args.get("is_bytes"): 2522 return super().bytestring_sql(expression) 2523 2524 # Each char is a byte. Casting to BLOB decodes \xHH, so everything but printable ASCII 2525 # (including the backslash itself) is written as such 2526 text = "".join( 2527 ch if ch.isascii() and ch.isprintable() and ch != "\\" else f"\\x{ord(ch):02x}" 2528 for ch in expression.this 2529 ) 2530 return self.sql(exp.cast(exp.Literal.string(text), exp.DType.BINARY))
2532 def bitmapbucketnumber_sql(self, expression: exp.BitmapBucketNumber) -> str: 2533 """ 2534 Transpile BITMAP_BUCKET_NUMBER function from Snowflake to DuckDB equivalent. 2535 2536 Snowflake's BITMAP_BUCKET_NUMBER returns a 1-based bucket identifier where: 2537 - Each bucket covers 32,768 values 2538 - Bucket numbering starts at 1 2539 - Formula: ((value - 1) // 32768) + 1 for positive values 2540 2541 For non-positive values (0 and negative), we use value // 32768 to avoid 2542 producing bucket 0 or positive bucket IDs for negative inputs. 2543 """ 2544 value = expression.this 2545 2546 positive_formula = ((value - 1) // 32768) + 1 2547 non_positive_formula = value // 32768 2548 2549 # CASE WHEN value > 0 THEN ((value - 1) // 32768) + 1 ELSE value // 32768 END 2550 case_expr = ( 2551 exp.case() 2552 .when(exp.GT(this=value, expression=exp.Literal.number(0)), positive_formula) 2553 .else_(non_positive_formula) 2554 ) 2555 return self.sql(case_expr)
Transpile BITMAP_BUCKET_NUMBER function from Snowflake to DuckDB equivalent.
Snowflake's BITMAP_BUCKET_NUMBER returns a 1-based bucket identifier where:
- Each bucket covers 32,768 values
- Bucket numbering starts at 1
- Formula: ((value - 1) // 32768) + 1 for positive values
For non-positive values (0 and negative), we use value // 32768 to avoid producing bucket 0 or positive bucket IDs for negative inputs.
2557 def bitmapbitposition_sql(self, expression: exp.BitmapBitPosition) -> str: 2558 """ 2559 Transpile Snowflake's BITMAP_BIT_POSITION to DuckDB CASE expression. 2560 2561 Snowflake's BITMAP_BIT_POSITION behavior: 2562 - For n <= 0: returns ABS(n) % 32768 2563 - For n > 0: returns (n - 1) % 32768 (maximum return value is 32767) 2564 """ 2565 this = expression.this 2566 2567 return self.sql( 2568 exp.Mod( 2569 this=exp.Paren( 2570 this=exp.If( 2571 this=exp.GT(this=this, expression=exp.Literal.number(0)), 2572 true=this - exp.Literal.number(1), 2573 false=exp.Abs(this=this), 2574 ) 2575 ), 2576 expression=MAX_BIT_POSITION, 2577 ) 2578 )
Transpile Snowflake's BITMAP_BIT_POSITION to DuckDB CASE expression.
Snowflake's BITMAP_BIT_POSITION behavior:
- For n <= 0: returns ABS(n) % 32768
- For n > 0: returns (n - 1) % 32768 (maximum return value is 32767)
2580 def bitmapconstructagg_sql(self, expression: exp.BitmapConstructAgg) -> str: 2581 """ 2582 Transpile Snowflake's BITMAP_CONSTRUCT_AGG to DuckDB equivalent. 2583 Uses a pre-parsed template with placeholders replaced by expression nodes. 2584 2585 Snowflake bitmap format: 2586 - Small (< 5 unique values): 2-byte count (big-endian) + values (little-endian) + padding to 10 bytes 2587 - Large (>= 5 unique values): 10-byte header (0x08 + 9 zeros) + values (little-endian) 2588 """ 2589 arg = expression.this 2590 return ( 2591 f"({self.sql(exp.replace_placeholders(self.BITMAP_CONSTRUCT_AGG_TEMPLATE, arg=arg))})" 2592 )
Transpile Snowflake's BITMAP_CONSTRUCT_AGG to DuckDB equivalent. Uses a pre-parsed template with placeholders replaced by expression nodes.
Snowflake bitmap format:
- Small (< 5 unique values): 2-byte count (big-endian) + values (little-endian) + padding to 10 bytes
- Large (>= 5 unique values): 10-byte header (0x08 + 9 zeros) + values (little-endian)
2636 def jarowinklersimilarity_sql(self, expression: exp.JarowinklerSimilarity) -> str: 2637 this = expression.this 2638 expr = expression.expression 2639 2640 if expression.args.get("case_insensitive"): 2641 this = exp.Upper(this=this) 2642 expr = exp.Upper(this=expr) 2643 2644 result = exp.func("JARO_WINKLER_SIMILARITY", this, expr) 2645 2646 if expression.args.get("integer_scale"): 2647 result = exp.cast(result * 100, "INTEGER") 2648 2649 return self.sql(result)
2651 def randstr_sql(self, expression: exp.Randstr) -> str: 2652 """ 2653 Transpile Snowflake's RANDSTR to DuckDB equivalent using deterministic hash-based random. 2654 Uses a pre-parsed template with placeholders replaced by expression nodes. 2655 2656 RANDSTR(length, generator) generates a random string of specified length. 2657 - With numeric seed: Use HASH(i + seed) for deterministic output (same seed = same result) 2658 - With RANDOM(): Use RANDOM() in the hash for non-deterministic output 2659 - No generator: Use default seed value 2660 """ 2661 length = expression.this 2662 generator = expression.args.get("generator") 2663 2664 if generator: 2665 if isinstance(generator, exp.Rand): 2666 # If it's RANDOM(), use its seed if available, otherwise use RANDOM() itself 2667 seed_value = generator.this or generator 2668 else: 2669 # Const/int or other expression - use as seed directly 2670 seed_value = generator 2671 else: 2672 # No generator specified, use default seed (arbitrary but deterministic) 2673 seed_value = exp.Literal.number(RANDSTR_SEED) 2674 2675 replacements = {"seed": seed_value, "length": length} 2676 return f"({self.sql(exp.replace_placeholders(self.RANDSTR_TEMPLATE, **replacements))})"
Transpile Snowflake's RANDSTR to DuckDB equivalent using deterministic hash-based random. Uses a pre-parsed template with placeholders replaced by expression nodes.
RANDSTR(length, generator) generates a random string of specified length.
- With numeric seed: Use HASH(i + seed) for deterministic output (same seed = same result)
- With RANDOM(): Use RANDOM() in the hash for non-deterministic output
- No generator: Use default seed value
2678 @unsupported_args("finish") 2679 def reduce_sql(self, expression: exp.Reduce) -> str: 2680 array_arg = expression.this 2681 initial_value = expression.args.get("initial") 2682 merge_lambda = expression.args.get("merge") 2683 2684 return self.func("list_reduce", array_arg, merge_lambda, initial_value)
2686 def zipf_sql(self, expression: exp.Zipf) -> str: 2687 """ 2688 Transpile Snowflake's ZIPF to DuckDB using CDF-based inverse sampling. 2689 Uses a pre-parsed template with placeholders replaced by expression nodes. 2690 """ 2691 s = expression.this 2692 n = expression.args["elementcount"] 2693 gen = expression.args["gen"] 2694 2695 if not isinstance(gen, exp.Rand): 2696 # (ABS(HASH(seed)) % 1000000) / 1000000.0 2697 random_expr: exp.Expr = exp.Div( 2698 this=exp.Paren( 2699 this=exp.Mod( 2700 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen.copy()])), 2701 expression=exp.Literal.number(1000000), 2702 ) 2703 ), 2704 expression=exp.Literal.number(1000000.0), 2705 ) 2706 else: 2707 # Use RANDOM() for non-deterministic output 2708 random_expr = exp.Rand() 2709 2710 replacements = {"s": s, "n": n, "random_expr": random_expr} 2711 return f"({self.sql(exp.replace_placeholders(self.ZIPF_TEMPLATE, **replacements))})"
Transpile Snowflake's ZIPF to DuckDB using CDF-based inverse sampling. Uses a pre-parsed template with placeholders replaced by expression nodes.
2713 def tobinary_sql(self, expression: exp.ToBinary) -> str: 2714 """ 2715 TO_BINARY and TRY_TO_BINARY transpilation: 2716 - 'HEX': TO_BINARY('48454C50', 'HEX') -> UNHEX('48454C50') 2717 - 'UTF-8': TO_BINARY('TEST', 'UTF-8') -> ENCODE('TEST') 2718 - 'BASE64': TO_BINARY('SEVMUA==', 'BASE64') -> FROM_BASE64('SEVMUA==') 2719 2720 For TRY_TO_BINARY (safe=True), wrap with TRY(): 2721 - 'HEX': TRY_TO_BINARY('invalid', 'HEX') -> TRY(UNHEX('invalid')) 2722 """ 2723 value = expression.this 2724 format_arg = expression.args.get("format") 2725 is_safe = expression.args.get("safe") 2726 is_binary = _is_binary(expression) 2727 2728 if not format_arg and not is_binary: 2729 func_name = "TRY_TO_BINARY" if is_safe else "TO_BINARY" 2730 return self.func(func_name, value) 2731 2732 # Snowflake defaults to HEX encoding when no format is specified 2733 fmt = format_arg.name.upper() if format_arg else "HEX" 2734 2735 if fmt in ("UTF-8", "UTF8"): 2736 # DuckDB ENCODE always uses UTF-8, no charset parameter needed 2737 result = self.func("ENCODE", value) 2738 elif fmt == "BASE64": 2739 result = self.func("FROM_BASE64", value) 2740 elif fmt == "HEX": 2741 result = self.func("UNHEX", value) 2742 else: 2743 if is_safe: 2744 return self.sql(exp.null()) 2745 else: 2746 self.unsupported(f"format {fmt} is not supported") 2747 result = self.func("TO_BINARY", value) 2748 return f"TRY({result})" if is_safe else result
TO_BINARY and TRY_TO_BINARY transpilation:
- 'HEX': TO_BINARY('48454C50', 'HEX') -> UNHEX('48454C50')
- 'UTF-8': TO_BINARY('TEST', 'UTF-8') -> ENCODE('TEST')
- 'BASE64': TO_BINARY('SEVMUA==', 'BASE64') -> FROM_BASE64('SEVMUA==')
For TRY_TO_BINARY (safe=True), wrap with TRY():
- 'HEX': TRY_TO_BINARY('invalid', 'HEX') -> TRY(UNHEX('invalid'))
2750 def tonumber_sql(self, expression: exp.ToNumber) -> str: 2751 fmt = expression.args.get("format") 2752 precision = expression.args.get("precision") 2753 scale = expression.args.get("scale") 2754 2755 if not fmt and precision and scale: 2756 to = exp.DataType.build(f"DECIMAL({precision.name}, {scale.name})", dialect="duckdb") 2757 if expression.args.get("safe"): 2758 return self.sql(exp.TryCast(this=expression.this, to=to)) 2759 return self.sql(exp.cast(expression.this, to, dialect="duckdb")) 2760 2761 return super().tonumber_sql(expression)
2787 def generator_sql(self, expression: exp.Generator) -> str: 2788 # Transpile Snowflake GENERATOR to DuckDB range() 2789 rowcount = expression.args.get("rowcount") 2790 time_limit = expression.args.get("time_limit") 2791 2792 if time_limit: 2793 self.unsupported("GENERATOR TIMELIMIT parameter is not supported in DuckDB") 2794 2795 if not rowcount: 2796 self.unsupported("GENERATOR without ROWCOUNT is not supported in DuckDB") 2797 return self.func("range", exp.Literal.number(0)) 2798 2799 return self.func("range", rowcount)
2807 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->", wrap: bool = True) -> str: 2808 if self.dialect.version >= (1, 3): 2809 prefix = "LAMBDA " 2810 arrow_sep = ":" 2811 wrap = False 2812 else: 2813 prefix = "" 2814 2815 lambda_sql = super().lambda_sql(expression, arrow_sep=arrow_sep, wrap=wrap) 2816 return f"{prefix}{lambda_sql}"
2832 def install_sql(self, expression: exp.Install) -> str: 2833 force = "FORCE " if expression.args.get("force") else "" 2834 this = self.sql(expression, "this") 2835 from_clause = expression.args.get("from_") 2836 from_clause = f" FROM {from_clause}" if from_clause else "" 2837 return f"{force}INSTALL {this}{from_clause}"
2845 def strposition_sql(self, expression: exp.StrPosition) -> str: 2846 this = expression.this 2847 substr = expression.args["substr"] 2848 position = expression.args.get("position") 2849 clamp_position = expression.args.get("clamp_position") 2850 2851 if clamp_position and position: 2852 position = exp.If( 2853 this=exp.LTE(this=position, expression=exp.Literal.number(0)), 2854 true=exp.Literal.number(1), 2855 false=position.copy(), 2856 ) 2857 2858 # For BINARY/BLOB: DuckDB's STRPOS doesn't support BLOB types 2859 if _is_binary(this): 2860 haystack: exp.Expr = exp.Hex(this=this) 2861 offset: exp.Expr = exp.Literal.number(0) 2862 if position: 2863 # Bound the arithmetic too: DuckDB may fold unreachable CASE branches. 2864 limit = exp.func("COALESCE", exp.ByteLength(this=this), 0) + 1 2865 offset = exp.Least(this=position, expressions=[limit], ignore_nulls=True) - 1 2866 haystack = exp.Substring(this=haystack, start=offset * 2 + 1) 2867 2868 # Match whole bytes, counting a two-character sentinel as the first byte. 2869 prefix = exp.RegexpExtract( 2870 this=exp.DPipe(this=exp.Literal.string("xx"), expression=haystack), 2871 expression=exp.DPipe( 2872 this=exp.Literal.string("^(xx(?:..)*?)"), expression=exp.Hex(this=substr) 2873 ), 2874 group=exp.Literal.number(1), 2875 ) 2876 result: exp.Expr = exp.paren(exp.Length(this=prefix) // 2) 2877 if position: 2878 result = ( 2879 exp.case() 2880 .when( 2881 exp.or_( 2882 this.is_(exp.null()), substr.is_(exp.null()), position.is_(exp.null()) 2883 ), 2884 exp.null(), 2885 ) 2886 .when( 2887 position > exp.func("GREATEST", exp.ByteLength(this=this), 1), 2888 exp.Literal.number(0), 2889 ) 2890 .else_(exp.func("COALESCE", exp.func("NULLIF", result, 0) + offset, 0)) 2891 ) 2892 return self.sql(result) 2893 2894 if clamp_position and position: 2895 expression = expression.copy() 2896 expression.set("position", position) 2897 2898 return strposition_sql(self, expression)
2900 def similarto_sql(self, expression: exp.SimilarTo) -> str: 2901 pattern = expression.expression.unnest() 2902 if ( 2903 pattern.is_string 2904 and not isinstance(expression.parent, exp.Escape) 2905 and _SIMILAR_TO_REGEX_CHARS.isdisjoint(pattern.name) 2906 ): 2907 return self.sql(expression.this.like(pattern)) 2908 2909 self.unsupported("Cannot translate this SIMILAR TO pattern to DuckDB LIKE") 2910 return super().similarto_sql(expression)
2912 def substring_sql(self, expression: exp.Substring) -> str: 2913 if expression.args.get("zero_start"): 2914 start = expression.args.get("start") 2915 length = expression.args.get("length") 2916 2917 if start := expression.args.get("start"): 2918 start = exp.If(this=start.eq(0), true=exp.Literal.number(1), false=start) 2919 if length := expression.args.get("length"): 2920 length = exp.If(this=length < 0, true=exp.Literal.number(0), false=length) 2921 2922 return self.func("SUBSTRING", expression.this, start, length) 2923 2924 return self.function_fallback_sql(expression)
2926 def strtotime_sql(self, expression: exp.StrToTime) -> str: 2927 # Check if target_type requires TIMESTAMPTZ (for LTZ/TZ variants) 2928 target_type = expression.args.get("target_type") 2929 needs_tz = target_type and target_type.this in ( 2930 exp.DType.TIMESTAMPLTZ, 2931 exp.DType.TIMESTAMPTZ, 2932 ) 2933 2934 value, formatted_time = self._strptime_default_year(expression) 2935 2936 if expression.args.get("safe"): 2937 cast_type = exp.DType.TIMESTAMPTZ if needs_tz else exp.DType.TIMESTAMP 2938 return self.sql(exp.cast(self.func("TRY_STRPTIME", value, formatted_time), cast_type)) 2939 2940 base_sql = self.func("STRPTIME", value, formatted_time) 2941 if needs_tz: 2942 return self.sql( 2943 exp.cast( 2944 base_sql, 2945 exp.DataType(this=exp.DType.TIMESTAMPTZ), 2946 ) 2947 ) 2948 return base_sql
2950 def strtodate_sql(self, expression: exp.StrToDate) -> str: 2951 value, formatted_time = self._strptime_default_year(expression) 2952 function_name = "STRPTIME" if not expression.args.get("safe") else "TRY_STRPTIME" 2953 return self.sql( 2954 exp.cast( 2955 self.func(function_name, value, formatted_time), 2956 exp.DataType(this=exp.DType.DATE), 2957 ) 2958 )
2985 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 2986 this = expression.this 2987 time_format = self.format_time(expression) 2988 safe = expression.args.get("safe") 2989 time_type = exp.DataType.from_str("TIME", dialect="duckdb") 2990 cast_expr = exp.TryCast if safe else exp.Cast 2991 2992 if time_format: 2993 func_name = "TRY_STRPTIME" if safe else "STRPTIME" 2994 strptime = exp.Anonymous(this=func_name, expressions=[this, time_format]) 2995 return self.sql(cast_expr(this=strptime, to=time_type)) 2996 2997 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 2998 return self.sql(this) 2999 3000 return self.sql(cast_expr(this=this, to=time_type))
3002 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3003 if not expression.this: 3004 return "CURRENT_DATE" 3005 3006 expr = exp.Cast( 3007 this=exp.AtTimeZone(this=exp.CurrentTimestamp(), zone=expression.this), 3008 to=exp.DataType(this=exp.DType.DATE), 3009 ) 3010 return self.sql(expr)
3029 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 3030 arg = expression.this 3031 if expression.args.get("safe"): 3032 return self.sql( 3033 exp.case() 3034 .when(exp.func("json_valid", arg), exp.cast(arg.copy(), "JSON")) 3035 .else_(exp.null()) 3036 ) 3037 return self.func("JSON", arg)
3039 def unicode_sql(self, expression: exp.Unicode) -> str: 3040 if expression.args.get("empty_is_null"): 3041 return self.func("NULLIF", self.func("UNICODE", expression.this), "-1") 3042 3043 if expression.args.get("empty_is_zero"): 3044 return self.sql( 3045 exp.case() 3046 .when(expression.this.eq(exp.Literal.string("")), exp.Literal.number(0)) 3047 .else_(exp.Anonymous(this="UNICODE", expressions=[expression.this])) 3048 ) 3049 3050 return self.func("UNICODE", expression.this)
3059 def trunc_sql(self, expression: exp.Trunc) -> str: 3060 decimals = expression.args.get("decimals") 3061 if ( 3062 expression.args.get("fractions_supported") 3063 and decimals 3064 and not decimals.is_type(exp.DType.INT) 3065 ): 3066 decimals = exp.cast(decimals, exp.DType.INT, dialect="duckdb") 3067 3068 return self.func("TRUNC", expression.this, decimals)
3070 def normal_sql(self, expression: exp.Normal) -> str: 3071 """ 3072 Transpile Snowflake's NORMAL(mean, stddev, gen) to DuckDB. 3073 3074 Uses the Box-Muller transform via NORMAL_TEMPLATE. 3075 """ 3076 mean = expression.this 3077 stddev = expression.args["stddev"] 3078 gen: exp.Expr = expression.args["gen"] 3079 3080 # Build two uniform random values [0, 1) for Box-Muller transform 3081 if isinstance(gen, exp.Rand) and gen.this is None: 3082 u1: exp.Expr = exp.Rand() 3083 u2: exp.Expr = exp.Rand() 3084 else: 3085 # Seeded: derive two values using HASH with different inputs 3086 seed = gen.this if isinstance(gen, exp.Rand) else gen 3087 u1 = exp.replace_placeholders(self.SEEDED_RANDOM_TEMPLATE, seed=seed) 3088 u2 = exp.replace_placeholders( 3089 self.SEEDED_RANDOM_TEMPLATE, 3090 seed=exp.Add(this=seed.copy(), expression=exp.Literal.number(1)), 3091 ) 3092 3093 replacements = {"mean": mean, "stddev": stddev, "u1": u1, "u2": u2} 3094 return self.sql(exp.replace_placeholders(self.NORMAL_TEMPLATE, **replacements))
Transpile Snowflake's NORMAL(mean, stddev, gen) to DuckDB.
Uses the Box-Muller transform via NORMAL_TEMPLATE.
3096 def uniform_sql(self, expression: exp.Uniform) -> str: 3097 """ 3098 Transpile Snowflake's UNIFORM(min, max, gen) to DuckDB. 3099 3100 UNIFORM returns a random value in [min, max]: 3101 - Integer result if both min and max are integers 3102 - Float result if either min or max is a float 3103 """ 3104 min_val = expression.this 3105 max_val = expression.expression 3106 gen = expression.args.get("gen") or expression.args.get("seed") or exp.Rand() 3107 3108 # Determine if result should be integer (both bounds are integers). 3109 # We do this to emulate Snowflake's behavior, INT -> INT, FLOAT -> FLOAT 3110 is_int_result = min_val.is_int and max_val.is_int 3111 3112 # Build the random value expression [0, 1) 3113 if not isinstance(gen, exp.Rand): 3114 # Seed value: (ABS(HASH(seed)) % 1000000) / 1000000.0 3115 random_expr: exp.Expr = exp.Div( 3116 this=exp.Paren( 3117 this=exp.Mod( 3118 this=exp.Abs(this=exp.Anonymous(this="HASH", expressions=[gen])), 3119 expression=exp.Literal.number(1000000), 3120 ) 3121 ), 3122 expression=exp.Literal.number(1000000.0), 3123 ) 3124 else: 3125 random_expr = exp.Rand() 3126 3127 # Build: min + random * (max - min [+ 1 for int]) 3128 range_expr: exp.Expr = exp.Sub(this=max_val, expression=min_val) 3129 if is_int_result: 3130 range_expr = exp.Add(this=range_expr, expression=exp.Literal.number(1)) 3131 3132 result: exp.Expr = exp.Add( 3133 this=min_val, 3134 expression=exp.Mul(this=random_expr, expression=exp.Paren(this=range_expr)), 3135 ) 3136 3137 if is_int_result: 3138 result = exp.Cast(this=exp.Floor(this=result), to=exp.DType.BIGINT.into_expr()) 3139 3140 return self.sql(result)
Transpile Snowflake's UNIFORM(min, max, gen) to DuckDB.
UNIFORM returns a random value in [min, max]:
- Integer result if both min and max are integers
- Float result if either min or max is a float
3142 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 3143 nano = expression.args.get("nano") 3144 overflow = expression.args.get("overflow") 3145 3146 # Snowflake's TIME_FROM_PARTS supports overflow 3147 if overflow: 3148 hour = expression.args["hour"] 3149 minute = expression.args["min"] 3150 sec = expression.args["sec"] 3151 3152 # Check if values are within normal ranges - use MAKE_TIME for efficiency 3153 if not nano and all(arg.is_int for arg in [hour, minute, sec]): 3154 try: 3155 h_val = hour.to_py() 3156 m_val = minute.to_py() 3157 s_val = sec.to_py() 3158 if 0 <= h_val <= 23 and 0 <= m_val <= 59 and 0 <= s_val <= 59: 3159 return rename_func("MAKE_TIME")(self, expression) 3160 except ValueError: 3161 pass 3162 3163 # Overflow or nanoseconds detected - use INTERVAL arithmetic 3164 if nano: 3165 sec = sec + nano.pop() / exp.Literal.number(1000000000.0) 3166 3167 total_seconds = hour * exp.Literal.number(3600) + minute * exp.Literal.number(60) + sec 3168 3169 return self.sql( 3170 exp.Add( 3171 this=exp.Cast( 3172 this=exp.Literal.string("00:00:00"), to=exp.DType.TIME.into_expr() 3173 ), 3174 expression=exp.Interval(this=total_seconds, unit=exp.var("SECOND")), 3175 ) 3176 ) 3177 3178 # Default: MAKE_TIME 3179 if nano: 3180 expression.set( 3181 "sec", expression.args["sec"] + nano.pop() / exp.Literal.number(1000000000.0) 3182 ) 3183 3184 return rename_func("MAKE_TIME")(self, expression)
3186 def extract_sql(self, expression: exp.Extract) -> str: 3187 """ 3188 Transpile EXTRACT/DATE_PART for DuckDB, handling specifiers not natively supported. 3189 3190 DuckDB doesn't support: WEEKISO, YEAROFWEEK, YEAROFWEEKISO, NANOSECOND, 3191 EPOCH_SECOND (as integer), EPOCH_MILLISECOND, EPOCH_MICROSECOND, EPOCH_NANOSECOND 3192 """ 3193 this = expression.this 3194 datetime_expr = expression.expression 3195 3196 # TIMESTAMPTZ extractions may produce different results between Snowflake and DuckDB 3197 # because Snowflake applies server timezone while DuckDB uses local timezone 3198 if datetime_expr.is_type(exp.DType.TIMESTAMPTZ, exp.DType.TIMESTAMPLTZ): 3199 self.unsupported( 3200 "EXTRACT from TIMESTAMPTZ / TIMESTAMPLTZ may produce different results due to timezone handling differences" 3201 ) 3202 3203 part_name = this.name.upper() 3204 3205 if part_name in self.EXTRACT_STRFTIME_MAPPINGS: 3206 fmt, cast_type = self.EXTRACT_STRFTIME_MAPPINGS[part_name] 3207 3208 # Problem: strftime doesn't accept TIME and there's no NANOSECOND function 3209 # So, for NANOSECOND with TIME, fallback to MICROSECOND * 1000 3210 is_nano_time = part_name == "NANOSECOND" and datetime_expr.is_type( 3211 exp.DType.TIME, exp.DType.TIMETZ 3212 ) 3213 3214 if is_nano_time: 3215 self.unsupported("Parameter NANOSECOND is not supported with TIME type in DuckDB") 3216 return self.sql( 3217 exp.cast( 3218 exp.Mul( 3219 this=exp.Extract(this=exp.var("MICROSECOND"), expression=datetime_expr), 3220 expression=exp.Literal.number(1000), 3221 ), 3222 exp.DataType.from_str(cast_type, dialect="duckdb"), 3223 ) 3224 ) 3225 3226 # For NANOSECOND, cast to TIMESTAMP_NS to preserve nanosecond precision 3227 strftime_input = datetime_expr 3228 if part_name == "NANOSECOND": 3229 strftime_input = exp.cast(datetime_expr, exp.DType.TIMESTAMP_NS) 3230 3231 return self.sql( 3232 exp.cast( 3233 exp.Anonymous( 3234 this="STRFTIME", 3235 expressions=[strftime_input, exp.Literal.string(fmt)], 3236 ), 3237 exp.DataType.from_str(cast_type, dialect="duckdb"), 3238 ) 3239 ) 3240 3241 if part_name in self.EXTRACT_EPOCH_MAPPINGS: 3242 func_name = self.EXTRACT_EPOCH_MAPPINGS[part_name] 3243 result: exp.Expr = exp.Anonymous(this=func_name, expressions=[datetime_expr]) 3244 # EPOCH returns float, cast to BIGINT for integer result 3245 if part_name == "EPOCH_SECOND": 3246 result = exp.cast(result, exp.DataType.from_str("BIGINT", dialect="duckdb")) 3247 return self.sql(result) 3248 3249 return super().extract_sql(expression)
Transpile EXTRACT/DATE_PART for DuckDB, handling specifiers not natively supported.
DuckDB doesn't support: WEEKISO, YEAROFWEEK, YEAROFWEEKISO, NANOSECOND, EPOCH_SECOND (as integer), EPOCH_MILLISECOND, EPOCH_MICROSECOND, EPOCH_NANOSECOND
3251 def timestamp_sql(self, expression: exp.Timestamp) -> str: 3252 zone = expression.args.get("zone") 3253 if expression.args.get("with_tz") and zone: 3254 return self.sql( 3255 exp.AtTimeZone( 3256 this=exp.cast(expression.this, exp.DType.TIMESTAMP), 3257 zone=_normalize_timezone_offset(zone), 3258 ) 3259 ) 3260 return no_timestamp_sql(self, expression)
3262 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 3263 # Check if this is the date/time expression form: TIMESTAMP_FROM_PARTS(date_expr, time_expr) 3264 date_expr = expression.this 3265 time_expr = expression.expression 3266 3267 if date_expr is not None and time_expr is not None: 3268 # In DuckDB, DATE + TIME produces TIMESTAMP 3269 return self.sql(exp.Add(this=date_expr, expression=time_expr)) 3270 3271 # Component-based form: TIMESTAMP_FROM_PARTS(year, month, day, hour, minute, second, ...) 3272 sec = expression.args.get("sec") 3273 if sec is None: 3274 # This shouldn't happen with valid input, but handle gracefully 3275 return rename_func("MAKE_TIMESTAMP")(self, expression) 3276 3277 milli = expression.args.get("milli") 3278 if milli is not None: 3279 sec += milli.pop() / exp.Literal.number(1000.0) 3280 3281 nano = expression.args.get("nano") 3282 if nano is not None: 3283 sec += nano.pop() / exp.Literal.number(1000000000.0) 3284 3285 if milli or nano: 3286 expression.set("sec", sec) 3287 3288 if zone := expression.args.get("zone"): 3289 return self.sql(exp.AtTimeZone(this=expression, zone=zone.pop())) 3290 3291 return rename_func("MAKE_TIMESTAMP")(self, expression)
3293 @unsupported_args("nano") 3294 def timestampltzfromparts_sql(self, expression: exp.TimestampLtzFromParts) -> str: 3295 # Pop nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3296 if nano := expression.args.get("nano"): 3297 nano.pop() 3298 3299 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3300 return f"CAST({timestamp} AS TIMESTAMPTZ)"
3302 @unsupported_args("nano") 3303 def timestamptzfromparts_sql(self, expression: exp.TimestampTzFromParts) -> str: 3304 # Extract zone before popping 3305 zone = expression.args.get("zone") 3306 # Pop zone and nano so rename_func only passes args that MAKE_TIMESTAMP accepts 3307 if zone: 3308 zone = zone.pop() 3309 3310 if nano := expression.args.get("nano"): 3311 nano.pop() 3312 3313 timestamp = rename_func("MAKE_TIMESTAMP")(self, expression) 3314 3315 if zone: 3316 # Use AT TIME ZONE to apply the explicit timezone 3317 return f"{timestamp} AT TIME ZONE {self.sql(zone)}" 3318 3319 return timestamp
3325 def tablesample_sql( 3326 self, 3327 expression: exp.TableSample, 3328 tablesample_keyword: str | None = None, 3329 ) -> str: 3330 if not isinstance(expression.parent, exp.Select): 3331 # This sample clause only applies to a single source, not the entire resulting relation 3332 tablesample_keyword = "TABLESAMPLE" 3333 3334 if expression.args.get("size"): 3335 method = expression.args.get("method") 3336 if method and method.name.upper() != "RESERVOIR": 3337 self.unsupported( 3338 f"Sampling method {method} is not supported with a discrete sample count, " 3339 "defaulting to reservoir sampling" 3340 ) 3341 expression.set("method", exp.var("RESERVOIR")) 3342 3343 return super().tablesample_sql(expression, tablesample_keyword=tablesample_keyword)
3355 def interval_sql(self, expression: exp.Interval) -> str: 3356 # DuckDB truncates INTERVAL '1.5' DAY to 1 day, but keeps the fraction in INTERVAL '1.5 DAY' 3357 this = expression.this 3358 unit = expression.unit 3359 if expression.args.get("fraction_in_string") and this and isinstance(unit, exp.Var): 3360 return f"INTERVAL '{this.name} {self.sql(unit)}'" 3361 3362 return super().interval_sql(expression)
3364 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3365 if expression.kind in ("MARK", "SINGLE") or ( 3366 expression.side == "RIGHT" and expression.is_semi_or_anti_join 3367 ): 3368 kind = "_".join(part for part in (expression.side, expression.kind) if part) 3369 return super().join_sql(expression, join_op=f"JOIN BY (TYPE {kind})") 3370 3371 if ( 3372 not expression.args.get("using") 3373 and not expression.args.get("on") 3374 and not expression.args.get("nearest") 3375 and not expression.method 3376 and (expression.kind in ("", "INNER", "OUTER")) 3377 ): 3378 # Some dialects support `LEFT/INNER JOIN UNNEST(...)` without an explicit ON clause 3379 # DuckDB doesn't, but we can just add a dummy ON clause that is always true 3380 if isinstance(expression.this, exp.Unnest): 3381 return super().join_sql(expression.on(exp.true())) 3382 3383 expression.set("side", None) 3384 expression.set("kind", None) 3385 3386 return super().join_sql(expression, join_op=join_op)
3388 def countif_sql(self, expression: exp.CountIf) -> str: 3389 if self.dialect.version >= (1, 2): 3390 this = expression.this 3391 if expression.args.get("zero_on_all_null") and not isinstance(this, exp.Distinct): 3392 # DuckDB >= 1.2's COUNT_IF returns NULL when the condition is NULL on all rows, 3393 # so we wrap the condition in IS TRUE to preserve count-like semantics 3394 expression = exp.CountIf(this=exp.paren(this).is_(exp.true())) 3395 return self.function_fallback_sql(expression) 3396 3397 # https://github.com/tobymao/sqlglot/pull/4749 3398 return count_if_to_sum(self, expression)
3400 def bracket_sql(self, expression: exp.Bracket) -> str: 3401 if self.dialect.version >= (1, 2): 3402 return super().bracket_sql(expression) 3403 3404 # https://duckdb.org/2025/02/05/announcing-duckdb-120.html#breaking-changes 3405 this = expression.this 3406 if isinstance(this, exp.Array): 3407 this.replace(exp.paren(this)) 3408 3409 bracket = super().bracket_sql(expression) 3410 3411 if not expression.args.get("returns_list_for_maps"): 3412 if not this.type: 3413 from sqlglot.optimizer.annotate_types import annotate_types 3414 3415 this = annotate_types(this, dialect=self.dialect) 3416 3417 if this.is_type(exp.DType.MAP): 3418 bracket = f"({bracket})[1]" 3419 3420 return bracket
3422 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 3423 func = expression.this 3424 3425 # For ARRAY_AGG, DuckDB requires ORDER BY inside the function, not in WITHIN GROUP 3426 # Transform: ARRAY_AGG(x) WITHIN GROUP (ORDER BY y) -> ARRAY_AGG(x ORDER BY y) 3427 if isinstance(func, exp.ArrayAgg): 3428 if not isinstance(order := expression.expression, exp.Order): 3429 return self.sql(func) 3430 3431 # Save the original column for FILTER clause (before wrapping with Order) 3432 original_this = func.this 3433 3434 # Move ORDER BY inside ARRAY_AGG by wrapping its argument with Order 3435 # ArrayAgg.this should become Order(this=ArrayAgg.this, expressions=order.expressions) 3436 func.set( 3437 "this", 3438 exp.Order( 3439 this=func.this.copy(), 3440 expressions=order.expressions, 3441 ), 3442 ) 3443 3444 # Generate the ARRAY_AGG function with ORDER BY and add FILTER clause if needed 3445 # Use original_this (not the Order-wrapped version) for the FILTER condition 3446 array_agg_sql = self.function_fallback_sql(func) 3447 return self._add_arrayagg_null_filter(array_agg_sql, func, original_this) 3448 3449 # For other functions (like PERCENTILES), use existing logic 3450 expression_sql = self.sql(expression, "expression") 3451 3452 if isinstance(func, exp.PERCENTILES): 3453 # Make the order key the first arg and slide the fraction to the right 3454 # https://duckdb.org/docs/sql/aggregates#ordered-set-aggregate-functions 3455 order_col = expression.find(exp.Ordered) 3456 if order_col: 3457 func.set("expression", func.this) 3458 func.set("this", order_col.this) 3459 3460 this = self.sql(expression, "this").removesuffix(")") 3461 3462 return f"{this}{expression_sql})"
3464 def length_sql(self, expression: exp.Length) -> str: 3465 arg = expression.this 3466 3467 def text_arg(value: exp.Expr) -> exp.Expr: 3468 if expression.args.get("null_terminated"): 3469 return exp.SplitPart( 3470 this=value.copy(), 3471 delimiter=exp.Chr(expressions=[exp.Literal.number(0)]), 3472 part_index=exp.Literal.number(1), 3473 ) 3474 return value 3475 3476 # SQLite, BQ and Snowflake also accept binary values as args, so 3477 # DDB will attempt to infer the type or resort to case/when resolution 3478 if ( 3479 not (expression.args.get("binary") or expression.args.get("null_terminated")) 3480 or arg.is_string 3481 ): 3482 return self.func("LENGTH", text_arg(arg)) 3483 3484 if not arg.type: 3485 from sqlglot.optimizer.annotate_types import annotate_types 3486 3487 arg = annotate_types(arg, dialect=self.dialect) 3488 3489 if arg.is_type(*exp.DataType.TEXT_TYPES): 3490 return self.func("LENGTH", text_arg(arg)) 3491 3492 # We need these casts to make duckdb's static type checker happy 3493 blob = exp.cast(arg, exp.DType.VARBINARY) 3494 varchar = exp.cast(arg, exp.DType.VARCHAR) 3495 3496 case = ( 3497 exp.case(exp.Typeof(this=arg.copy())) 3498 .when(exp.Literal.string("BLOB"), exp.ByteLength(this=blob)) 3499 .else_(exp.Length(this=text_arg(varchar))) 3500 ) 3501 return self.sql(case)
3510 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 3511 if len(expression.expressions) > 1: 3512 return super().chr_sql(expression, name) 3513 3514 arg = expression.expressions[0] 3515 if arg.is_type(*exp.DataType.REAL_TYPES): 3516 arg = exp.cast(arg, exp.DType.INT) 3517 return self.func("CHR", arg)
3523 def collate_sql(self, expression: exp.Collate) -> str: 3524 if not expression.expression.is_string: 3525 return super().collate_sql(expression) 3526 3527 raw = expression.expression.name 3528 if not raw: 3529 return self.sql(expression.this) 3530 3531 parts = [] 3532 for part in raw.split("-"): 3533 lower = part.lower() 3534 if lower not in _SNOWFLAKE_COLLATION_DEFAULTS: 3535 if lower in _SNOWFLAKE_COLLATION_UNSUPPORTED: 3536 self.unsupported( 3537 f"Snowflake collation specifier '{part}' has no DuckDB equivalent" 3538 ) 3539 parts.append(lower) 3540 3541 if not parts: 3542 return self.sql(expression.this) 3543 return super().collate_sql( 3544 exp.Collate(this=expression.this, expression=exp.var(".".join(parts))) 3545 )
3577 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 3578 this = expression.this 3579 pattern = expression.expression 3580 position = expression.args.get("position") 3581 parameters = expression.args.get("parameters") 3582 3583 # Validate flags - only "ims" flags are supported for embedded patterns 3584 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 3585 3586 if position: 3587 this = exp.Substring(this=this, start=position) 3588 3589 # Handle empty pattern: Snowflake returns 0, DuckDB would match between every character. 3590 # Checked before the flags are embedded, which would make the pattern non-empty 3591 is_empty = exp.EQ(this=pattern.copy(), expression=exp.Literal.string("")) 3592 3593 # Embed flags in pattern (REGEXP_EXTRACT_ALL doesn't support flags argument) 3594 if validated_flags: 3595 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 3596 3597 result = ( 3598 exp.case() 3599 .when(is_empty, exp.Literal.number(0)) 3600 .else_( 3601 exp.Length( 3602 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 3603 ) 3604 ) 3605 ) 3606 3607 return self.sql(result)
3609 def regexpreplace_sql(self, expression: exp.RegexpReplace) -> str: 3610 subject = expression.this 3611 pattern = expression.expression 3612 replacement = expression.args.get("replacement") or exp.Literal.string("") 3613 position = expression.args.get("position") 3614 occurrence = expression.args.get("occurrence") 3615 modifiers = expression.args.get("modifiers") 3616 3617 validated_flags = self._validate_regexp_flags(modifiers, supported_flags="cimsg") or "" 3618 3619 # Handle occurrence (only literals supported) 3620 if occurrence and not occurrence.is_int: 3621 self.unsupported("REGEXP_REPLACE with non-literal occurrence") 3622 else: 3623 occurrence = occurrence.to_py() if occurrence and occurrence.is_int else 0 3624 if occurrence > 1: 3625 self.unsupported(f"REGEXP_REPLACE occurrence={occurrence} not supported") 3626 # flag duckdb to do either all or none, single_replace check is for duckdb round trip 3627 elif ( 3628 occurrence == 0 3629 and "g" not in validated_flags 3630 and not expression.args.get("single_replace") 3631 ): 3632 validated_flags += "g" 3633 3634 # Handle position (only literals supported) 3635 prefix = None 3636 if position and not position.is_int: 3637 self.unsupported("REGEXP_REPLACE with non-literal position") 3638 elif position and position.is_int and position.to_py() > 1: 3639 pos = position.to_py() 3640 prefix = exp.Substring( 3641 this=subject, start=exp.Literal.number(1), length=exp.Literal.number(pos - 1) 3642 ) 3643 subject = exp.Substring(this=subject, start=exp.Literal.number(pos)) 3644 3645 result: exp.Expr = exp.Anonymous( 3646 this="REGEXP_REPLACE", 3647 expressions=[ 3648 subject, 3649 pattern, 3650 replacement, 3651 exp.Literal.string(validated_flags) if validated_flags else None, 3652 ], 3653 ) 3654 3655 if prefix: 3656 result = exp.Concat(expressions=[prefix, result]) 3657 3658 return self.sql(result)
3660 def regexplike_sql(self, expression: exp.RegexpLike) -> str: 3661 this = expression.this 3662 pattern = expression.expression 3663 flag = expression.args.get("flag") 3664 3665 if expression.args.get("full_match"): 3666 validated_flags = self._validate_regexp_flags(flag, supported_flags="cims") 3667 flag = exp.Literal.string(validated_flags) if validated_flags else None 3668 return self.func("REGEXP_FULL_MATCH", this, pattern, flag) 3669 3670 return self.func("REGEXP_MATCHES", this, pattern, flag)
3672 @unsupported_args("ins_cost", "del_cost", "sub_cost") 3673 def levenshtein_sql(self, expression: exp.Levenshtein) -> str: 3674 this = expression.this 3675 expr = expression.expression 3676 max_dist = expression.args.get("max_dist") 3677 3678 if max_dist is None: 3679 return self.func("LEVENSHTEIN", this, expr) 3680 3681 # Emulate Snowflake semantics: if distance > max_dist, return max_dist 3682 levenshtein = exp.Levenshtein(this=this, expression=expr) 3683 return self.sql(exp.Least(this=levenshtein, expressions=[max_dist]))
3685 def pad_sql(self, expression: exp.Pad) -> str: 3686 """ 3687 Handle RPAD/LPAD for VARCHAR and BINARY types. 3688 3689 For VARCHAR: Delegate to parent class 3690 For BINARY: Lower to: input || REPEAT(pad, GREATEST(0, target_len - OCTET_LENGTH(input))) 3691 """ 3692 string_arg = expression.this 3693 fill_arg = expression.args.get("fill_pattern") or exp.Literal.string(" ") 3694 3695 if _is_binary(string_arg) or _is_binary(fill_arg): 3696 length_arg = expression.expression 3697 is_left = expression.args.get("is_left") 3698 3699 input_len = exp.ByteLength(this=string_arg) 3700 chars_needed = length_arg - input_len 3701 pad_count = exp.Greatest( 3702 this=exp.Literal.number(0), expressions=[chars_needed], ignore_nulls=True 3703 ) 3704 repeat_expr = exp.Repeat(this=fill_arg, times=pad_count) 3705 3706 left, right = string_arg, repeat_expr 3707 if is_left: 3708 left, right = right, left 3709 3710 result = exp.DPipe(this=left, expression=right) 3711 return self.sql(result) 3712 3713 # For VARCHAR: Delegate to parent class (handles PAD_FILL_PATTERN_IS_REQUIRED) 3714 return super().pad_sql(expression)
Handle RPAD/LPAD for VARCHAR and BINARY types.
For VARCHAR: Delegate to parent class For BINARY: Lower to: input || REPEAT(pad, GREATEST(0, target_len - OCTET_LENGTH(input)))
3716 def minhash_sql(self, expression: exp.Minhash) -> str: 3717 k = expression.this 3718 exprs = expression.expressions 3719 3720 if len(exprs) != 1 or isinstance(exprs[0], exp.Star): 3721 self.unsupported( 3722 "MINHASH with multiple expressions or * requires manual query restructuring" 3723 ) 3724 return self.func("MINHASH", k, *exprs) 3725 3726 expr = exprs[0] 3727 result = exp.replace_placeholders(self.MINHASH_TEMPLATE.copy(), expr=expr, k=k) 3728 return f"({self.sql(result)})"
3740 def arrayall_sql(self, expression: exp.ArrayAll) -> str: 3741 return self.func( 3742 "LIST_REDUCE", 3743 exp.Transform(this=expression.this, expression=expression.expression), 3744 exp.Lambda( 3745 this=exp.and_(exp.to_identifier("_a"), exp.to_identifier("_b")), 3746 expressions=[exp.to_identifier("_a"), exp.to_identifier("_b")], 3747 ), 3748 exp.true(), 3749 )
3759 def arrayconcatagg_sql(self, expression: exp.ArrayConcatAgg) -> str: 3760 this = expression.this 3761 3762 if isinstance(this, exp.Limit): 3763 self.unsupported("LIMIT in ARRAY_CONCAT_AGG cannot be transpiled to DuckDB") 3764 this = this.this 3765 3766 inner = this.this if isinstance(this, exp.Order) else this 3767 3768 return self.func( 3769 "FLATTEN", 3770 exp.Filter( 3771 this=exp.ArrayAgg(this=this), 3772 expression=exp.Where(this=inner.copy().is_(exp.null()).not_()), 3773 ), 3774 )
3780 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 3781 arr = expression.this 3782 func = self.func("LIST_DISTINCT", arr) 3783 3784 if expression.args.get("check_null"): 3785 add_null_to_array = exp.func( 3786 "LIST_APPEND", exp.func("LIST_DISTINCT", exp.ArrayCompact(this=arr)), exp.Null() 3787 ) 3788 return self.sql( 3789 exp.If( 3790 this=exp.NEQ( 3791 this=exp.ArraySize(this=arr), expression=exp.func("LIST_COUNT", arr) 3792 ), 3793 true=add_null_to_array, 3794 false=func, 3795 ) 3796 ) 3797 3798 return func
3800 def arrayintersect_sql(self, expression: exp.ArrayIntersect) -> str: 3801 if expression.args.get("is_multiset") and len(expression.expressions) == 2: 3802 return self._array_bag_sql( 3803 self.ARRAY_INTERSECTION_CONDITION, 3804 expression.expressions[0], 3805 expression.expressions[1], 3806 ) 3807 return self.function_fallback_sql(expression)
3809 def arrayexcept_sql(self, expression: exp.ArrayExcept) -> str: 3810 arr1, arr2 = expression.this, expression.expression 3811 if expression.args.get("is_multiset"): 3812 return self._array_bag_sql(self.ARRAY_EXCEPT_CONDITION, arr1, arr2) 3813 return self.sql( 3814 exp.replace_placeholders(self.ARRAY_EXCEPT_SET_TEMPLATE, arr1=arr1, arr2=arr2) 3815 )
3817 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 3818 separator = expression.args.get("separator") 3819 if ( 3820 expression.args.get("null_separator_is_empty") 3821 and separator is not None 3822 and not separator.is_string 3823 ): 3824 expression.set( 3825 "separator", exp.Coalesce(this=separator, expressions=[exp.Literal.string("")]) 3826 ) 3827 return groupconcat_sql(self, expression, within_group=False)
3829 def arrayslice_sql(self, expression: exp.ArraySlice) -> str: 3830 """ 3831 Spark's SLICE uses a length, so normalize negative starts before computing 3832 the inclusive end index. Starts before the array produce an empty slice. 3833 3834 Transpiles Snowflake's ARRAY_SLICE (0-indexed, exclusive end) to DuckDB's 3835 ARRAY_SLICE (1-indexed, inclusive end) by wrapping start and end in CASE 3836 expressions that adjust the index at query time: 3837 - start: CASE WHEN start >= 0 THEN start + 1 ELSE start END 3838 - end: CASE WHEN end < 0 THEN end - 1 ELSE end END 3839 """ 3840 start, end = expression.args.get("start"), expression.args.get("end") 3841 3842 if expression.args.get("zero_based"): 3843 if start is not None: 3844 start = ( 3845 exp.case() 3846 .when( 3847 exp.GTE(this=start.copy(), expression=exp.Literal.number(0)), 3848 exp.Add(this=start.copy(), expression=exp.Literal.number(1)), 3849 ) 3850 .else_(start) 3851 ) 3852 if end is not None and not expression.args.get("is_length"): 3853 end = ( 3854 exp.case() 3855 .when( 3856 exp.LT(this=end.copy(), expression=exp.Literal.number(0)), 3857 exp.Sub(this=end.copy(), expression=exp.Literal.number(1)), 3858 ) 3859 .else_(end) 3860 ) 3861 3862 if expression.args.get("is_length") and start is not None and end is not None: 3863 if not start.is_int or start.to_py() < 0: 3864 size = exp.ArraySize(this=expression.this.copy()) 3865 start = ( 3866 exp.case() 3867 .when(start < -size, size + 1) 3868 .when(start < 0, size + start + 1) 3869 .else_(start) 3870 ) 3871 3872 if start.is_int and end.is_int: 3873 end = exp.Literal.number(start.to_py() + end.to_py() - 1) 3874 else: 3875 end = start + exp.cast(end, "BIGINT") - 1 3876 return self.func("ARRAY_SLICE", expression.this, start, end, expression.args.get("step"))
Spark's SLICE uses a length, so normalize negative starts before computing the inclusive end index. Starts before the array produce an empty slice.
Transpiles Snowflake's ARRAY_SLICE (0-indexed, exclusive end) to DuckDB's ARRAY_SLICE (1-indexed, inclusive end) by wrapping start and end in CASE expressions that adjust the index at query time:
- start: CASE WHEN start >= 0 THEN start + 1 ELSE start END
- end: CASE WHEN end < 0 THEN end - 1 ELSE end END
3878 def arrayszip_sql(self, expression: exp.ArraysZip) -> str: 3879 args = expression.expressions 3880 3881 if not args: 3882 # Return [{}] - using MAP([], []) since DuckDB can't represent empty structs 3883 return self.sql(exp.array(exp.Map(keys=exp.array(), values=exp.array()))) 3884 3885 # Build placeholder values for template 3886 lengths = [exp.Length(this=arg) for arg in args] 3887 max_len = ( 3888 lengths[0] 3889 if len(lengths) == 1 3890 else exp.Greatest(this=lengths[0], expressions=lengths[1:]) 3891 ) 3892 3893 # Empty struct with same schema: {'$1': NULL, '$2': NULL, ...} 3894 empty_struct = exp.func( 3895 "STRUCT", 3896 *[ 3897 exp.PropertyEQ(this=exp.Literal.string(f"${i + 1}"), expression=exp.Null()) 3898 for i in range(len(args)) 3899 ], 3900 ) 3901 3902 # Struct for transform: {'$1': COALESCE(arr1, [])[__i + 1], ...} 3903 # COALESCE wrapping handles NULL arrays - prevents invalid NULL[i] syntax 3904 index = exp.column("__i") + 1 3905 transform_struct = exp.func( 3906 "STRUCT", 3907 *[ 3908 exp.PropertyEQ( 3909 this=exp.Literal.string(f"${i + 1}"), 3910 expression=exp.func("COALESCE", arg, exp.array())[index], 3911 ) 3912 for i, arg in enumerate(args) 3913 ], 3914 ) 3915 3916 result = exp.replace_placeholders( 3917 self.ARRAYS_ZIP_TEMPLATE.copy(), 3918 null_check=exp.or_(*[arg.is_(exp.Null()) for arg in args]), 3919 all_empty_check=exp.and_( 3920 *[ 3921 exp.EQ(this=exp.Length(this=arg), expression=exp.Literal.number(0)) 3922 for arg in args 3923 ] 3924 ), 3925 empty_struct=empty_struct, 3926 max_len=max_len, 3927 transform_struct=transform_struct, 3928 ) 3929 return self.sql(result)
3975 def stuff_sql(self, expression: exp.Stuff) -> str: 3976 base = expression.this 3977 start = expression.args["start"] 3978 length = expression.args["length"] 3979 insertion = expression.expression 3980 is_binary = _is_binary(base) 3981 3982 if is_binary: 3983 # DuckDB's SUBSTRING doesn't accept BLOB; operate on the HEX string instead 3984 # (each byte = 2 hex chars), then UNHEX back to BLOB 3985 base = exp.Hex(this=base) 3986 insertion = exp.Hex(this=insertion) 3987 left = exp.Substring( 3988 this=base.copy(), 3989 start=exp.Literal.number(1), 3990 length=(start.copy() - exp.Literal.number(1)) * exp.Literal.number(2), 3991 ) 3992 right = exp.Substring( 3993 this=base.copy(), 3994 start=((start + length) - exp.Literal.number(1)) * exp.Literal.number(2) 3995 + exp.Literal.number(1), 3996 ) 3997 else: 3998 left = exp.Substring( 3999 this=base.copy(), 4000 start=exp.Literal.number(1), 4001 length=start.copy() - exp.Literal.number(1), 4002 ) 4003 right = exp.Substring(this=base.copy(), start=start + length) 4004 result: exp.Expr = exp.DPipe( 4005 this=exp.DPipe(this=left, expression=insertion), expression=right 4006 ) 4007 4008 if is_binary: 4009 result = exp.Unhex(this=result) 4010 4011 return self.sql(result)
4013 def rand_sql(self, expression: exp.Rand) -> str: 4014 seed = expression.this 4015 if seed is not None: 4016 self.unsupported("RANDOM with seed is not supported in DuckDB") 4017 4018 lower = expression.args.get("lower") 4019 upper = expression.args.get("upper") 4020 4021 if lower and upper: 4022 # Build 64 random bits in integer arithmetic to preserve the low bits and 4023 # avoid overflow when the inclusive range spans signed BIGINT's limits. 4024 random_bits = exp.cast(exp.Floor(this=exp.Rand() * (1 << 32)), exp.DType.INT128) 4025 random = random_bits * (1 << 32) + random_bits.copy() 4026 lower = exp.cast(lower, exp.DType.INT128) 4027 upper = exp.cast(upper, exp.DType.INT128) 4028 return self.sql(exp.cast(random % (upper - lower + 1) + lower, exp.DType.BIGINT)) 4029 4030 # Default DuckDB behavior - just return RANDOM() as float 4031 return "RANDOM()"
4033 def bytelength_sql(self, expression: exp.ByteLength) -> str: 4034 arg = expression.this 4035 4036 # Check if it's a text type (handles both literals and annotated expressions) 4037 if arg.is_type(*exp.DataType.TEXT_TYPES): 4038 return self.func("OCTET_LENGTH", exp.Encode(this=arg)) 4039 4040 # Default: pass through as-is (conservative for DuckDB, handles binary and unannotated) 4041 return self.func("OCTET_LENGTH", arg)
4043 def base64encode_sql(self, expression: exp.Base64Encode) -> str: 4044 # DuckDB TO_BASE64 requires BLOB input 4045 # Snowflake BASE64_ENCODE accepts both VARCHAR and BINARY - for VARCHAR it implicitly 4046 # encodes UTF-8 bytes. We add ENCODE unless the input is a binary type. 4047 result = expression.this 4048 4049 # Check if input is a string type - ENCODE only accepts VARCHAR 4050 if result.is_type(*exp.DataType.TEXT_TYPES): 4051 result = exp.Encode(this=result) 4052 4053 result = exp.ToBase64(this=result) 4054 4055 max_line_length = expression.args.get("max_line_length") 4056 alphabet = expression.args.get("alphabet") 4057 4058 # Handle custom alphabet by replacing standard chars with custom ones 4059 result = _apply_base64_alphabet_replacements(result, alphabet) 4060 4061 # Handle max_line_length by inserting newlines every N characters 4062 line_length = ( 4063 t.cast(int, max_line_length.to_py()) 4064 if isinstance(max_line_length, exp.Literal) and max_line_length.is_number 4065 else 0 4066 ) 4067 if line_length > 0: 4068 newline = exp.Chr(expressions=[exp.Literal.number(10)]) 4069 result = exp.Trim( 4070 this=exp.RegexpReplace( 4071 this=result, 4072 expression=exp.Literal.string(f"(.{{{line_length}}})"), 4073 replacement=exp.Concat(expressions=[exp.Literal.string("\\1"), newline.copy()]), 4074 ), 4075 expression=newline, 4076 position="TRAILING", 4077 ) 4078 4079 return self.sql(result)
4081 def hex_sql(self, expression: exp.Hex) -> str: 4082 case = expression.args.get("case") 4083 4084 if not case: 4085 return self.func("HEX", expression.this) 4086 4087 hex_expr = exp.Hex(this=expression.this) 4088 return self.sql( 4089 exp.case() 4090 .when(case.is_(exp.null()), exp.null()) 4091 .when(case.copy().eq(0), exp.Lower(this=hex_expr.copy())) 4092 .else_(hex_expr) 4093 )
4095 def replace_sql(self, expression: exp.Replace) -> str: 4096 result_sql = self.func( 4097 "REPLACE", 4098 _cast_to_varchar(expression.this), 4099 _cast_to_varchar(expression.expression), 4100 _cast_to_varchar(expression.args.get("replacement")), 4101 ) 4102 return _gen_with_cast_to_blob(self, expression, result_sql)
4114 def objectinsert_sql(self, expression: exp.ObjectInsert) -> str: 4115 this = expression.this 4116 key = expression.args.get("key") 4117 key_sql = key.name if isinstance(key, exp.Expr) else "" 4118 value_sql = self.sql(expression, "value") 4119 4120 kv_sql = f"{key_sql} := {value_sql}" 4121 4122 # If the input struct is empty e.g. transpiling OBJECT_INSERT(OBJECT_CONSTRUCT(), key, value) from Snowflake 4123 # then we can generate STRUCT_PACK which will build it since STRUCT_INSERT({}, key := value) is not valid DuckDB 4124 if isinstance(this, exp.Struct) and not this.expressions: 4125 return self.func("STRUCT_PACK", kv_sql) 4126 4127 return self.func("STRUCT_INSERT", this, kv_sql)
4142 def mapdelete_sql(self, expression: exp.MapDelete) -> str: 4143 map_arg = expression.this 4144 keys_to_delete = expression.expressions 4145 4146 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4147 4148 lambda_expr = exp.Lambda( 4149 this=exp.In(this=x_dot_key, expressions=keys_to_delete).not_(), 4150 expressions=[exp.to_identifier("x")], 4151 ) 4152 result = exp.func( 4153 "MAP_FROM_ENTRIES", 4154 exp.ArrayFilter(this=exp.func("MAP_ENTRIES", map_arg), expression=lambda_expr), 4155 ) 4156 return self.sql(result)
4158 def mappick_sql(self, expression: exp.MapPick) -> str: 4159 map_arg = expression.this 4160 keys_to_pick = expression.expressions 4161 4162 x_dot_key = exp.Dot(this=exp.to_identifier("x"), expression=exp.to_identifier("key")) 4163 4164 if len(keys_to_pick) == 1 and keys_to_pick[0].is_type(exp.DType.ARRAY): 4165 lambda_expr = exp.Lambda( 4166 this=exp.func("ARRAY_CONTAINS", keys_to_pick[0], x_dot_key), 4167 expressions=[exp.to_identifier("x")], 4168 ) 4169 else: 4170 lambda_expr = exp.Lambda( 4171 this=exp.In(this=x_dot_key, expressions=keys_to_pick), 4172 expressions=[exp.to_identifier("x")], 4173 ) 4174 4175 result = exp.func( 4176 "MAP_FROM_ENTRIES", 4177 exp.func("LIST_FILTER", exp.func("MAP_ENTRIES", map_arg), lambda_expr), 4178 ) 4179 return self.sql(result)
4184 @unsupported_args("update_flag") 4185 def mapinsert_sql(self, expression: exp.MapInsert) -> str: 4186 map_arg = expression.this 4187 key = expression.args.get("key") 4188 value = expression.args.get("value") 4189 4190 map_type = map_arg.type 4191 4192 if value is not None: 4193 if map_type and map_type.expressions and len(map_type.expressions) > 1: 4194 # Extract the value type from MAP(key_type, value_type) 4195 value_type = map_type.expressions[1] 4196 # Cast value to match the map's value type to avoid type conflicts 4197 value = exp.cast(value, value_type) 4198 # else: polymorphic MAP case - no type parameters available, use value as-is 4199 4200 # Create a single-entry map for the new key-value pair 4201 new_entry_struct = exp.Struct(expressions=[exp.PropertyEQ(this=key, expression=value)]) 4202 new_entry: exp.Expression = exp.ToMap(this=new_entry_struct) 4203 4204 # Use MAP_CONCAT to merge the original map with the new entry 4205 # This automatically handles both insert and update cases 4206 result = exp.func("MAP_CONCAT", map_arg, new_entry) 4207 4208 return self.sql(result)
4226 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 4227 # For GENERATOR, unwrap TABLE() - just emit the Generator (becomes RANGE) 4228 if isinstance(expression.this, exp.Generator): 4229 # Preserve alias, joins, and other table-level args 4230 table = exp.Table( 4231 this=expression.this, 4232 alias=expression.args.get("alias"), 4233 joins=expression.args.get("joins"), 4234 ) 4235 return self.sql(table) 4236 4237 return super().tablefromrows_sql(expression)
4239 def unnest_sql(self, expression: exp.Unnest) -> str: 4240 explode_array = expression.args.get("explode_array") 4241 if explode_array: 4242 # In BigQuery, UNNESTing a nested array leads to explosion of the top-level array & struct 4243 # This is transpiled to DDB by transforming "FROM UNNEST(...)" to "FROM (SELECT UNNEST(..., max_depth => 2))" 4244 expression.expressions.append( 4245 exp.Kwarg(this=exp.var("max_depth"), expression=exp.Literal.number(2)) 4246 ) 4247 4248 # If BQ's UNNEST is aliased, we transform it from a column alias to a table alias in DDB 4249 alias = expression.args.get("alias") 4250 if isinstance(alias, exp.TableAlias): 4251 expression.set("alias", None) 4252 if alias.columns: 4253 alias = exp.TableAlias(this=seq_get(alias.columns, 0)) 4254 4255 unnest_sql = super().unnest_sql(expression) 4256 select = exp.Select(expressions=[unnest_sql]).subquery(alias) 4257 return self.sql(select) 4258 4259 if query := transforms.unnest_with_offset(expression): 4260 return self.sql(query) 4261 4262 return super().unnest_sql(expression)
4270 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 4271 this = expression.this 4272 4273 if isinstance(this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4274 # DuckDB should render IGNORE NULLS only for the general-purpose 4275 # window functions that accept it e.g. FIRST_VALUE(... IGNORE NULLS) OVER (...) 4276 return super().ignorenulls_sql(expression) 4277 4278 # For ARRAY_AGG(expr IGNORE NULLS ...), convert IGNORE NULLS to a 4279 # FILTER(WHERE expr IS NOT NULL) clause by setting nulls_excluded on 4280 # the ArrayAgg. The existing _add_arrayagg_null_filter method will 4281 # emit the FILTER clause during arrayagg_sql / withingroup_sql. 4282 if isinstance(this, exp.ArrayAgg): 4283 this.set("nulls_excluded", True) 4284 return self.sql(this) 4285 4286 if isinstance(this, exp.First): 4287 this = exp.AnyValue(this=this.this) 4288 4289 if not isinstance(this, (exp.AnyValue, exp.ApproxQuantiles)): 4290 self.unsupported("IGNORE NULLS is not supported for non-window functions.") 4291 4292 return self.sql(this)
4294 def split_sql(self, expression: exp.Split) -> str: 4295 base_func = exp.func("STR_SPLIT", expression.this, expression.expression) 4296 4297 case_expr = exp.case().else_(base_func) 4298 needs_case = False 4299 4300 if expression.args.get("null_returns_null"): 4301 case_expr = case_expr.when(expression.expression.is_(exp.null()), exp.null()) 4302 needs_case = True 4303 4304 if expression.args.get("empty_delimiter_returns_whole"): 4305 # When delimiter is empty string, return input string as single array element 4306 array_with_input = exp.array(expression.this) 4307 case_expr = case_expr.when( 4308 expression.expression.eq(exp.Literal.string("")), array_with_input 4309 ) 4310 needs_case = True 4311 4312 return self.sql(case_expr if needs_case else base_func)
4314 def splitpart_sql(self, expression: exp.SplitPart) -> str: 4315 string_arg = expression.this 4316 delimiter_arg = expression.args.get("delimiter") 4317 part_index_arg = expression.args.get("part_index") 4318 4319 if delimiter_arg and part_index_arg: 4320 # Handle Snowflake's "index 0 and 1 both return first element" behavior 4321 if expression.args.get("part_index_zero_as_one"): 4322 # Convert 0 to 1 for compatibility 4323 4324 part_index_arg = exp.Paren( 4325 this=exp.case() 4326 .when(part_index_arg.eq(exp.Literal.number("0")), exp.Literal.number("1")) 4327 .else_(part_index_arg) 4328 ) 4329 4330 # Use Anonymous to avoid recursion 4331 base_func_expr: exp.Expr = exp.Anonymous( 4332 this="SPLIT_PART", expressions=[string_arg, delimiter_arg, part_index_arg] 4333 ) 4334 needs_case_transform = False 4335 case_expr = exp.case().else_(base_func_expr) 4336 4337 if expression.args.get("empty_delimiter_returns_whole"): 4338 # When delimiter is empty string: 4339 # - Return whole string if part_index is 1 or -1 4340 # - Return empty string otherwise 4341 empty_case = exp.Paren( 4342 this=exp.case() 4343 .when( 4344 exp.or_( 4345 part_index_arg.eq(exp.Literal.number("1")), 4346 part_index_arg.eq(exp.Literal.number("-1")), 4347 ), 4348 string_arg, 4349 ) 4350 .else_(exp.Literal.string("")) 4351 ) 4352 4353 case_expr = case_expr.when(delimiter_arg.eq(exp.Literal.string("")), empty_case) 4354 needs_case_transform = True 4355 4356 """ 4357 Output looks something like this: 4358 4359 CASE 4360 WHEN delimiter is '' THEN 4361 ( 4362 CASE 4363 WHEN adjusted_part_index = 1 OR adjusted_part_index = -1 THEN input 4364 ELSE '' END 4365 ) 4366 ELSE SPLIT_PART(input, delimiter, adjusted_part_index) 4367 END 4368 4369 """ 4370 return self.sql(case_expr if needs_case_transform else base_func_expr) 4371 4372 return self.function_fallback_sql(expression)
4374 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 4375 if isinstance(expression.this, self.IGNORE_RESPECT_NULLS_WINDOW_FUNCTIONS): 4376 # DuckDB should render RESPECT NULLS only for the general-purpose 4377 # window functions that accept it e.g. FIRST_VALUE(... RESPECT NULLS) OVER (...) 4378 return super().respectnulls_sql(expression) 4379 4380 self.unsupported("RESPECT NULLS is not supported for non-window functions.") 4381 return self.sql(expression, "this")
4383 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 4384 null = expression.args.get("null") 4385 4386 if expression.args.get("null_is_empty"): 4387 x = exp.to_identifier("x") 4388 list_transform = exp.Transform( 4389 this=expression.this.copy(), 4390 expression=exp.Lambda( 4391 this=exp.Coalesce( 4392 this=exp.cast(x, "TEXT"), expressions=[exp.Literal.string("")] 4393 ), 4394 expressions=[x], 4395 ), 4396 ) 4397 array_to_string = exp.ArrayToString( 4398 this=list_transform, expression=expression.expression 4399 ) 4400 if expression.args.get("null_delim_is_null"): 4401 return self.sql( 4402 exp.case() 4403 .when(expression.expression.copy().is_(exp.null()), exp.null()) 4404 .else_(array_to_string) 4405 ) 4406 return self.sql(array_to_string) 4407 4408 if null: 4409 x = exp.to_identifier("x") 4410 return self.sql( 4411 exp.ArrayToString( 4412 this=exp.Transform( 4413 this=expression.this, 4414 expression=exp.Lambda( 4415 this=exp.Coalesce(this=exp.cast(x, "TEXT"), expressions=[null]), 4416 expressions=[x], 4417 ), 4418 ), 4419 expression=expression.expression, 4420 ) 4421 ) 4422 4423 return self.func("ARRAY_TO_STRING", expression.this, expression.expression)
4425 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4426 # DuckDB-specific: handle binary types using DPipe (||) operator 4427 separator = seq_get(expression.expressions, 0) 4428 args = expression.expressions[1:] 4429 4430 if any(_is_binary(arg) for arg in [separator, *args]): 4431 result = args[0] 4432 for arg in args[1:]: 4433 result = exp.DPipe( 4434 this=exp.DPipe(this=result, expression=separator), expression=arg 4435 ) 4436 return self.sql(result) 4437 4438 if expression.args.get("flatten") and any( 4439 isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY) for arg in args 4440 ): 4441 arrays = [] 4442 for arg in args: 4443 if isinstance(arg, exp.Array) or arg.is_type(exp.DType.ARRAY): 4444 arg = exp.cast(arg, "TEXT[]") 4445 else: 4446 if (not arg.type or arg.is_type(exp.DType.UNKNOWN)) and not isinstance( 4447 arg, exp.CONSTANTS 4448 ): 4449 self.unsupported( 4450 "Cannot transpile CONCAT_WS with unknown argument types to DuckDB." 4451 ) 4452 arg = exp.array(exp.cast(arg, exp.DType.TEXT)) 4453 4454 arrays.append(arg) 4455 4456 array = ( 4457 exp.ArrayConcat(this=arrays[0], expressions=arrays[1:]) 4458 if len(arrays) > 1 4459 else arrays[0] 4460 ) 4461 return self.func("CONCAT_WS", separator, self.func("ARRAY_TO_STRING", array, separator)) 4462 4463 return super().concatws_sql(expression)
4543 def regexpinstr_sql(self, expression: exp.RegexpInstr) -> str: 4544 this = expression.this 4545 pattern = expression.expression 4546 position = expression.args.get("position") 4547 orig_occ = expression.args.get("occurrence") 4548 occurrence = orig_occ or exp.Literal.number(1) 4549 option = expression.args.get("option") 4550 parameters = expression.args.get("parameters") 4551 4552 validated_flags = self._validate_regexp_flags(parameters, supported_flags="ims") 4553 # Checked before the flags are embedded, which would make the pattern non-empty 4554 is_empty = pattern.copy().eq(exp.Literal.string("")) 4555 if validated_flags: 4556 pattern = exp.Concat(expressions=[exp.Literal.string(f"(?{validated_flags})"), pattern]) 4557 4558 # Handle starting position offset 4559 pos_offset: exp.Expr = exp.Literal.number(0) 4560 if position and (not position.is_int or position.to_py() > 1): 4561 this = exp.Substring(this=this, start=position) 4562 pos_offset = position - exp.Literal.number(1) 4563 4564 # Helper: LIST_SUM(LIST_TRANSFORM(list[1:end], x -> LENGTH(x))) 4565 def sum_lengths(func_name: str, end: exp.Expr) -> exp.Expr: 4566 lst = exp.Bracket( 4567 this=exp.Anonymous(this=func_name, expressions=[this, pattern]), 4568 expressions=[exp.Slice(this=exp.Literal.number(1), expression=end)], 4569 offset=1, 4570 ) 4571 transform = exp.Anonymous( 4572 this="LIST_TRANSFORM", 4573 expressions=[ 4574 lst, 4575 exp.Lambda( 4576 this=exp.Length(this=exp.to_identifier("x")), 4577 expressions=[exp.to_identifier("x")], 4578 ), 4579 ], 4580 ) 4581 return exp.Coalesce( 4582 this=exp.Anonymous(this="LIST_SUM", expressions=[transform]), 4583 expressions=[exp.Literal.number(0)], 4584 ) 4585 4586 # Position = 1 + sum(split_lengths[1:occ]) + sum(match_lengths[1:occ-1]) + offset 4587 base_pos: exp.Expr = ( 4588 exp.Literal.number(1) 4589 + sum_lengths("STRING_SPLIT_REGEX", occurrence) 4590 + sum_lengths("REGEXP_EXTRACT_ALL", occurrence - exp.Literal.number(1)) 4591 + pos_offset 4592 ) 4593 4594 # option=1: add match length for end position 4595 if option and option.is_int and option.to_py() == 1: 4596 match_at_occ = exp.Bracket( 4597 this=exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]), 4598 expressions=[occurrence], 4599 offset=1, 4600 ) 4601 base_pos = base_pos + exp.Coalesce( 4602 this=exp.Length(this=match_at_occ), expressions=[exp.Literal.number(0)] 4603 ) 4604 4605 # NULL checks for all provided arguments 4606 # .copy() is used strictly because .is_() alters the node's parent pointer, mutating the parsed AST 4607 null_args = [ 4608 expression.this, 4609 expression.expression, 4610 position, 4611 orig_occ, 4612 option, 4613 parameters, 4614 ] 4615 null_checks = [arg.copy().is_(exp.Null()) for arg in null_args if arg] 4616 4617 matches = exp.Anonymous(this="REGEXP_EXTRACT_ALL", expressions=[this, pattern]) 4618 4619 return self.sql( 4620 exp.case() 4621 .when(exp.or_(*null_checks), exp.Null()) 4622 .when(is_empty, exp.Literal.number(0)) 4623 .when(exp.Length(this=matches) < occurrence, exp.Literal.number(0)) 4624 .else_(base_pos) 4625 )
4627 @unsupported_args("culture") 4628 def numbertostr_sql(self, expression: exp.NumberToStr) -> str: 4629 fmt = expression.args.get("format") 4630 if fmt and fmt.is_int: 4631 return self.func("FORMAT", f"'{{:,.{fmt.name}f}}'", expression.this) 4632 4633 self.unsupported("Only integer formats are supported by NumberToStr") 4634 return self.function_fallback_sql(expression)
4653 def posexplode_sql(self, expression: exp.Posexplode) -> str: 4654 this = expression.this 4655 parent = expression.parent 4656 4657 # The default Spark aliases are "pos" and "col", unless specified otherwise 4658 pos, col = exp.to_identifier("pos"), exp.to_identifier("col") 4659 4660 if isinstance(parent, exp.Aliases): 4661 # Column case: SELECT POSEXPLODE(col) [AS (a, b)] 4662 pos, col = parent.expressions 4663 elif isinstance(parent, exp.Table): 4664 # Table case: SELECT * FROM POSEXPLODE(col) [AS (a, b)] 4665 alias = parent.args.get("alias") 4666 if alias: 4667 pos, col = alias.columns or [pos, col] 4668 alias.pop() 4669 4670 # Translate POSEXPLODE to UNNEST + GENERATE_SUBSCRIPTS 4671 # Note: In Spark pos is 0-indexed, but in DuckDB it's 1-indexed, so we subtract 1 from GENERATE_SUBSCRIPTS 4672 unnest_sql = self.sql(exp.Unnest(expressions=[this], alias=col)) 4673 gen_subscripts = self.sql( 4674 exp.Alias( 4675 this=exp.Anonymous( 4676 this="GENERATE_SUBSCRIPTS", expressions=[this, exp.Literal.number(1)] 4677 ) 4678 - exp.Literal.number(1), 4679 alias=pos, 4680 ) 4681 ) 4682 4683 posexplode_sql = self.format_args(gen_subscripts, unnest_sql) 4684 4685 if isinstance(parent, exp.From) or (parent and isinstance(parent.parent, exp.From)): 4686 # SELECT * FROM POSEXPLODE(col) -> SELECT * FROM (SELECT GENERATE_SUBSCRIPTS(...), UNNEST(...)) 4687 return self.sql(exp.Subquery(this=exp.Select(expressions=[posexplode_sql]))) 4688 4689 return posexplode_sql
4691 def addmonths_sql(self, expression: exp.AddMonths) -> str: 4692 """ 4693 Handles three key issues: 4694 1. Float/decimal months: e.g., Snowflake rounds, whereas DuckDB INTERVAL requires integers 4695 2. End-of-month preservation: If input is last day of month, result is last day of result month 4696 3. Type preservation: Maintains DATE/TIMESTAMPTZ types (DuckDB defaults to TIMESTAMP) 4697 """ 4698 from sqlglot.optimizer.annotate_types import annotate_types 4699 4700 this = expression.this 4701 if not this.type: 4702 this = annotate_types(this, dialect=self.dialect) 4703 4704 if this.is_type(*exp.DataType.TEXT_TYPES): 4705 this = exp.Cast(this=this, to=exp.DataType(this=exp.DType.TIMESTAMP)) 4706 4707 # Detect float/decimal months to apply rounding (Snowflake behavior) 4708 # DuckDB INTERVAL syntax doesn't support non-integer expressions, so use TO_MONTHS 4709 months_expr = expression.expression 4710 if not months_expr.type: 4711 months_expr = annotate_types(months_expr, dialect=self.dialect) 4712 4713 # Build interval or to_months expression based on type 4714 # Float/decimal case: Round and use TO_MONTHS(CAST(ROUND(value) AS INT)) 4715 interval_or_to_months = ( 4716 exp.func("TO_MONTHS", exp.cast(exp.func("ROUND", months_expr), "INT")) 4717 if months_expr.is_type( 4718 exp.DType.FLOAT, 4719 exp.DType.DOUBLE, 4720 exp.DType.DECIMAL, 4721 ) 4722 # Integer case: standard INTERVAL N MONTH syntax 4723 else exp.Interval(this=months_expr, unit=exp.var("MONTH")) 4724 ) 4725 4726 date_add_expr = exp.Add(this=this, expression=interval_or_to_months) 4727 4728 # Apply end-of-month preservation if Snowflake flag is set 4729 # CASE WHEN LAST_DAY(date) = date THEN LAST_DAY(result) ELSE result END 4730 preserve_eom = expression.args.get("preserve_end_of_month") 4731 result_expr = ( 4732 exp.case() 4733 .when( 4734 exp.EQ(this=exp.func("LAST_DAY", this), expression=this), 4735 exp.func("LAST_DAY", date_add_expr), 4736 ) 4737 .else_(date_add_expr) 4738 if preserve_eom 4739 else date_add_expr 4740 ) 4741 4742 # DuckDB's DATE_ADD function returns TIMESTAMP/DATETIME by default, even when the input is DATE 4743 # To match for example Snowflake's ADD_MONTHS behavior (which preserves the input type) 4744 # We need to cast the result back to the original type when the input is DATE or TIMESTAMPTZ 4745 # Example: ADD_MONTHS('2023-01-31'::date, 1) should return DATE, not TIMESTAMP 4746 if this.is_type(exp.DType.DATE, exp.DType.TIMESTAMPTZ): 4747 return self.sql(exp.Cast(this=result_expr, to=this.type)) 4748 return self.sql(result_expr)
Handles three key issues:
- Float/decimal months: e.g., Snowflake rounds, whereas DuckDB INTERVAL requires integers
- End-of-month preservation: If input is last day of month, result is last day of result month
- Type preservation: Maintains DATE/TIMESTAMPTZ types (DuckDB defaults to TIMESTAMP)
4750 def format_sql(self, expression: exp.Format) -> str: 4751 if expression.args.get("is_fmt"): 4752 return self.func("FORMAT", expression.this, *expression.expressions) 4753 4754 fmt = expression.name 4755 if expression.this.is_string and fmt == "%S" and len(expression.expressions) == 1: 4756 return self.func( 4757 "UPPER", self.func("FORMAT", exp.Literal.string("{}"), expression.expressions[0]) 4758 ) 4759 4760 if expression.this.is_string and "%s" in fmt and "%" not in re.sub(r"%%|%s", "", fmt): 4761 # Use brace formatting to support non-string %s arguments, as in PostgreSQL. 4762 fmt = fmt.replace("{", "{{").replace("}", "}}") 4763 fmt = re.sub(r"%%|%s", lambda m: "%" if m[0] == "%%" else "{}", fmt) 4764 return self.func("FORMAT", exp.Literal.string(fmt), *expression.expressions) 4765 4766 return self.func("PRINTF", expression.this, *expression.expressions)
4774 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 4775 unit = expression.args.get("unit") 4776 date = expression.this 4777 4778 week_start = _week_trunc_start_dow(unit) 4779 unit = ( 4780 unit_to_str(expression) 4781 if week_start 4782 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4783 ) 4784 4785 if week_start: 4786 result = self.sql( 4787 _build_week_trunc_expression(date, week_start, preserve_start_day=True) 4788 ) 4789 else: 4790 result = self.func("DATE_TRUNC", unit, date) 4791 4792 if expression.args.get("input_type_preserved") and date.is_type( 4793 *exp.DataType.TEMPORAL_TYPES 4794 ): 4795 return self.sql(exp.Cast(this=result, to=date.type)) 4796 4797 return result
4799 def datetimetrunc_sql(self, expression: exp.DatetimeTrunc) -> str: 4800 this = exp.cast(expression.this, exp.DType.DATETIME) 4801 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4802 if week_start: 4803 return self.sql( 4804 _build_week_trunc_expression( 4805 this, week_start, preserve_start_day=True, cast_to_date=False 4806 ) 4807 ) 4808 4809 return self.func("DATE_TRUNC", unit_to_str(expression), this)
4811 def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str: 4812 zone = expression.args.get("zone") 4813 timestamp = expression.this 4814 week_start = _week_trunc_start_dow(expression.args.get("unit")) 4815 4816 # The week start emulation below is exact, so avoid weekstart_unit_to_str's degrade warning 4817 unit = ( 4818 unit_to_str(expression) 4819 if week_start 4820 else weekstart_unit_to_str(self, expression, century_from_zero=True) 4821 ) 4822 date_unit = is_date_unit(unit) or bool(week_start) 4823 4824 def _trunc_expr(this: exp.Expr) -> exp.Expr: 4825 if week_start: 4826 return _build_week_trunc_expression( 4827 this, week_start, preserve_start_day=True, cast_to_date=False 4828 ) 4829 return exp.DateTrunc( 4830 unit=unit, 4831 this=this, 4832 century_from_zero=expression.args.get("century_from_zero"), 4833 ) 4834 4835 if date_unit and zone: 4836 # BigQuery's TIMESTAMP_TRUNC with timezone truncates in the target timezone and returns as UTC. 4837 # Double AT TIME ZONE needed for BigQuery compatibility: 4838 # 1. First AT TIME ZONE: ensures truncation happens in the target timezone 4839 # 2. Second AT TIME ZONE: converts the DATE result back to TIMESTAMPTZ (preserving time component) 4840 timestamp = exp.AtTimeZone(this=timestamp, zone=zone) 4841 trunced = _trunc_expr(timestamp) 4842 if isinstance(trunced, exp.DateAdd): 4843 # Parenthesize so the trailing AT TIME ZONE binds to the whole shifted expression 4844 trunced = exp.Paren(this=trunced) 4845 return self.sql(exp.AtTimeZone(this=trunced, zone=zone)) 4846 4847 result = self.sql(_trunc_expr(timestamp)) 4848 if expression.args.get("input_type_preserved"): 4849 if timestamp.type and timestamp.is_type(exp.DType.TIME, exp.DType.TIMETZ): 4850 dummy_date = exp.Cast( 4851 this=exp.Literal.string("1970-01-01"), 4852 to=exp.DataType(this=exp.DType.DATE), 4853 ) 4854 date_time = exp.Add(this=dummy_date, expression=timestamp) 4855 result = self.func("DATE_TRUNC", unit, date_time) 4856 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4857 4858 if timestamp.is_type(*exp.DataType.TEMPORAL_TYPES): 4859 return self.sql(exp.Cast(this=result, to=timestamp.type)) 4860 4861 return result
4863 def timestampdiff_sql(self, expression: exp.TimestampDiff) -> str: 4864 unit = expression.unit 4865 4866 if _is_nanosecond_unit(unit): 4867 return _handle_nanosecond_diff(self, expression.this, expression.expression) 4868 4869 unit_str = unit.name.upper() if isinstance(unit, (exp.Var, exp.Literal)) else "" 4870 4871 if expression.args.get("boundary_for_date") and all( 4872 arg.is_type(exp.DType.DATE, exp.DType.DATETIME, exp.DType.TIMESTAMP) 4873 for arg in (expression.this, expression.expression) 4874 ): 4875 return _date_diff_sql( 4876 self, 4877 exp.DateDiff( 4878 this=expression.this, 4879 expression=expression.expression, 4880 unit=unit, 4881 date_part_boundary=True, 4882 ), 4883 ) 4884 4885 # Cast untyped args (bare NULLs, string literals) so DuckDB can resolve the overload 4886 this = ( 4887 exp.cast(expression.this, exp.DType.TIMESTAMPTZ) 4888 if isinstance(expression.this, (exp.Null, exp.Literal)) 4889 else expression.this 4890 ) 4891 expr = ( 4892 exp.cast(expression.expression, exp.DType.TIMESTAMPTZ) 4893 if isinstance(expression.expression, (exp.Null, exp.Literal)) 4894 else expression.expression 4895 ) 4896 4897 if unit_str == "DAY": 4898 date_sub = exp.func( 4899 "DATE_SUB", exp.Literal.string("HOUR"), expr, this, dialect="duckdb" 4900 ) 4901 return self.sql(exp.IntDiv(this=date_sub, expression=exp.Literal.number(24))) 4902 4903 return self.func("DATE_SUB", unit_to_str(expression), expr, this)
4905 def trim_sql(self, expression: exp.Trim) -> str: 4906 expression.this.replace(_cast_to_varchar(expression.this)) 4907 if expression.expression: 4908 expression.expression.replace(_cast_to_varchar(expression.expression)) 4909 4910 result_sql = super().trim_sql(expression) 4911 return _gen_with_cast_to_blob(self, expression, result_sql)
4913 def round_sql(self, expression: exp.Round) -> str: 4914 this = expression.this 4915 decimals = expression.args.get("decimals") 4916 truncate = expression.args.get("truncate") 4917 4918 if decimals is not None and expression.args.get("negative_decimals_are_zero"): 4919 if decimals.is_int: 4920 decimals = exp.Literal.number(max(0, decimals.to_py())) 4921 else: 4922 # DuckDB's DECIMAL overload requires constant precision; SQLite rounds doubles. 4923 this = exp.cast(this, exp.DType.DOUBLE) 4924 # Preserve NULL precision, which GREATEST(decimals, 0) would replace with 0. 4925 decimals = exp.If( 4926 this=decimals < 0, true=exp.Literal.number(0), false=decimals.copy() 4927 ) 4928 4929 # DuckDB requires the scale (decimals) argument to be an INT 4930 # Some dialects (e.g., Snowflake) allow non-integer scales and cast to an integer internally 4931 if decimals is not None and expression.args.get("casts_non_integer_decimals"): 4932 if not (decimals.is_int or decimals.is_type(*_ROUND_SCALE_INTEGER_TYPES)): 4933 decimals = exp.cast(decimals, exp.DType.INT) 4934 4935 func = "ROUND" 4936 if truncate: 4937 # BigQuery uses ROUND_HALF_EVEN; Snowflake uses HALF_TO_EVEN 4938 if truncate.this in ("ROUND_HALF_EVEN", "HALF_TO_EVEN"): 4939 func = "ROUND_EVEN" 4940 truncate = None 4941 # BigQuery uses ROUND_HALF_AWAY_FROM_ZERO; Snowflake uses HALF_AWAY_FROM_ZERO 4942 elif truncate.this in ("ROUND_HALF_AWAY_FROM_ZERO", "HALF_AWAY_FROM_ZERO"): 4943 truncate = None 4944 4945 return self.func(func, this, decimals, truncate)
4947 def trycast_sql(self, expression: exp.TryCast) -> str: 4948 to = expression.to 4949 to_type = to.this 4950 src = expression.this 4951 4952 if ( 4953 expression.args.get("null_on_text_overflow") 4954 and to_type in exp.DataType.TEXT_TYPES 4955 and to.expressions 4956 ): 4957 return self.sql( 4958 exp.case() 4959 .when( 4960 exp.LTE(this=exp.func("LENGTH", src), expression=to.expressions[0].this), 4961 exp.cast(src, "TEXT"), 4962 ) 4963 .else_(exp.Null()) 4964 ) 4965 elif to_type == exp.DType.DATE and expression.args.get("probe_date_format"): 4966 slash_strptime = exp.cast( 4967 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_SLASH_FMT)), 4968 "DATE", 4969 ) 4970 mon_strptime = exp.cast( 4971 exp.func("TRY_STRPTIME", src, exp.Literal.string(self._TRYCAST_DATE_MON_FMT)), 4972 "DATE", 4973 ) 4974 return self.sql( 4975 exp.case() 4976 .when(exp.func("CONTAINS", src, exp.Literal.string("/")), slash_strptime) 4977 .when( 4978 exp.RegexpLike(this=src, expression=exp.Literal.string("[A-Za-z]")), 4979 mon_strptime, 4980 ) 4981 .else_(exp.TryCast(this=src, to=to)) 4982 ) 4983 elif ( 4984 isinstance(to_type, exp.Interval) 4985 and (unit := to_type.unit) 4986 and expression.args.get("requires_string") 4987 ): 4988 interval_type = exp.DataType.build("INTERVAL") 4989 if isinstance(unit, exp.IntervalSpan): 4990 self.unsupported( 4991 "TRY_CAST to INTERVAL with span (e.g. HOUR TO MINUTE) is not supported in DuckDB" 4992 ) 4993 return self.sql(exp.TryCast(this=src, to=interval_type)) 4994 return self.sql( 4995 exp.TryCast( 4996 this=exp.DPipe(this=src, expression=exp.Literal.string(f" {unit.name}")), 4997 to=interval_type, 4998 ) 4999 ) 5000 5001 return super().trycast_sql(expression)
5003 def strtok_sql(self, expression: exp.Strtok) -> str: 5004 string_arg = expression.this 5005 delimiter_arg = expression.args.get("delimiter") 5006 part_index_arg = expression.args.get("part_index") 5007 5008 if delimiter_arg and part_index_arg: 5009 # Escape regex chars and build character class at runtime using REGEXP_REPLACE 5010 escaped_delimiter = exp.Anonymous( 5011 this="REGEXP_REPLACE", 5012 expressions=[ 5013 delimiter_arg, 5014 exp.Literal.string( 5015 r"([\[\]^.\-*+?(){}|$\\])" 5016 ), # Escape problematic regex chars 5017 exp.Literal.string( 5018 r"\\\1" 5019 ), # Replace with escaped version using $1 backreference 5020 exp.Literal.string("g"), # Global flag 5021 ], 5022 ) 5023 # CASE WHEN delimiter = '' THEN '' ELSE CONCAT('[', escaped_delimiter, ']') END 5024 regex_pattern = ( 5025 exp.case() 5026 .when(delimiter_arg.eq(exp.Literal.string("")), exp.Literal.string("")) 5027 .else_( 5028 exp.func( 5029 "CONCAT", 5030 exp.Literal.string("["), 5031 escaped_delimiter, 5032 exp.Literal.string("]"), 5033 ) 5034 ) 5035 ) 5036 5037 # STRTOK skips empty strings, so we need to filter them out 5038 # LIST_FILTER(REGEXP_SPLIT_TO_ARRAY(string, pattern), x -> x != '')[index] 5039 split_array = exp.func("REGEXP_SPLIT_TO_ARRAY", string_arg, regex_pattern) 5040 x = exp.to_identifier("x") 5041 is_empty = x.eq(exp.Literal.string("")) 5042 filtered_array = exp.func( 5043 "LIST_FILTER", 5044 split_array, 5045 exp.Lambda(this=exp.not_(is_empty.copy()), expressions=[x.copy()]), 5046 ) 5047 base_func = exp.Bracket( 5048 this=filtered_array, 5049 expressions=[part_index_arg], 5050 offset=1, 5051 ) 5052 5053 # Use template with the built regex pattern 5054 result = exp.replace_placeholders( 5055 self.STRTOK_TEMPLATE.copy(), 5056 string=string_arg, 5057 delimiter=delimiter_arg, 5058 part_index=part_index_arg, 5059 base_func=base_func, 5060 ) 5061 5062 return self.sql(result) 5063 5064 return self.function_fallback_sql(expression)
5066 def strtoktoarray_sql(self, expression: exp.StrtokToArray) -> str: 5067 string_arg = expression.this 5068 delimiter_arg = expression.args.get("expression") or exp.Literal.string(" ") 5069 5070 escaped = exp.RegexpReplace( 5071 this=delimiter_arg.copy(), 5072 expression=exp.Literal.string(r"([\[\]^.\-*+?(){}|$\\])"), 5073 replacement=exp.Literal.string(r"\\\1"), 5074 modifiers=exp.Literal.string("g"), 5075 ) 5076 return self.sql( 5077 exp.replace_placeholders( 5078 self.STRTOK_TO_ARRAY_TEMPLATE.copy(), 5079 string=string_arg, 5080 delimiter=delimiter_arg, 5081 escaped=escaped, 5082 ) 5083 )
5085 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 5086 result = self.func("APPROX_QUANTILE", expression.this, expression.args.get("quantile")) 5087 5088 # DuckDB returns the input's type, e.g. an integer or DECIMAL, so cast when a float is expected 5089 if expression.is_type(*exp.DataType.FLOAT_TYPES): 5090 result = f"CAST({result} AS DOUBLE)" 5091 5092 return result
5094 def approxquantiles_sql(self, expression: exp.ApproxQuantiles) -> str: 5095 """ 5096 BigQuery's APPROX_QUANTILES(expr, n) returns an array of n+1 approximate quantile values 5097 dividing the input distribution into n equal-sized buckets. 5098 5099 Both BigQuery and DuckDB use approximate algorithms for quantile estimation, but BigQuery 5100 does not document the specific algorithm used so results may differ. DuckDB does not 5101 support RESPECT NULLS. 5102 """ 5103 this = expression.this 5104 if isinstance(this, exp.Distinct): 5105 # APPROX_QUANTILES requires 2 args and DISTINCT node grabs both 5106 if len(this.expressions) < 2: 5107 self.unsupported("APPROX_QUANTILES requires a bucket count argument") 5108 return self.function_fallback_sql(expression) 5109 num_quantiles_expr = this.expressions[1].pop() 5110 else: 5111 num_quantiles_expr = expression.expression 5112 5113 if not isinstance(num_quantiles_expr, exp.Literal) or not num_quantiles_expr.is_int: 5114 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5115 return self.function_fallback_sql(expression) 5116 5117 num_quantiles = t.cast(int, num_quantiles_expr.to_py()) 5118 if num_quantiles <= 0: 5119 self.unsupported("APPROX_QUANTILES bucket count must be a positive integer") 5120 return self.function_fallback_sql(expression) 5121 5122 quantiles = [ 5123 exp.Literal.number(Decimal(i) / Decimal(num_quantiles)) 5124 for i in range(num_quantiles + 1) 5125 ] 5126 5127 return self.sql(exp.ApproxQuantile(this=this, quantile=exp.Array(expressions=quantiles)))
BigQuery's APPROX_QUANTILES(expr, n) returns an array of n+1 approximate quantile values dividing the input distribution into n equal-sized buckets.
Both BigQuery and DuckDB use approximate algorithms for quantile estimation, but BigQuery does not document the specific algorithm used so results may differ. DuckDB does not support RESPECT NULLS.
5129 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 5130 if expression.args.get("scalar_only"): 5131 json_value = exp.JSONExtractScalar( 5132 this=rename_func("JSON_VALUE")(self, expression), expression="'$'" 5133 ) 5134 5135 # `->>` binds looser than most operators, so the wrap logic needs the parent 5136 json_value.parent = expression.parent 5137 expression = json_value 5138 5139 return _arrow_json_extract_sql(self, expression)
5141 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 5142 this = expression.this 5143 5144 if _is_binary(this): 5145 expression.type = exp.DType.BINARY.into_expr() 5146 5147 arg = _cast_to_bit(this) 5148 5149 if isinstance(this, exp.Neg): 5150 arg = exp.Paren(this=arg) 5151 5152 expression.set("this", arg) 5153 5154 result_sql = f"~{self.sql(expression, 'this')}" 5155 5156 return _gen_with_cast_to_blob(self, expression, result_sql)
5158 def window_sql(self, expression: exp.Window) -> str: 5159 this = expression.this 5160 if isinstance(this, exp.Corr) or ( 5161 isinstance(this, exp.Filter) and isinstance(this.this, exp.Corr) 5162 ): 5163 return self._corr_sql(expression) 5164 5165 return self._arg_max_or_min_with_count_sql(expression) or super().window_sql(expression)
5212 def uuid_sql(self, expression: exp.Uuid) -> str: 5213 namespace = expression.this 5214 name = expression.args.get("name") 5215 5216 # UUID v5 (namespace + name) - Emulate using SHA1 5217 if namespace and name: 5218 result = exp.replace_placeholders( 5219 self.UUID_V5_TEMPLATE.copy(), 5220 namespace=namespace, 5221 name=name, 5222 ) 5223 return self.sql(result) 5224 5225 return super().uuid_sql(expression)
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- WINDOW_FUNCS_WITH_NULL_ORDERING
- WINDOW_FUNCS_REQUIRING_ORDER
- LOCKING_READS_SUPPORTED
- EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- MERGE_SCHEMA_EVOLUTION_MIN_VERSION
- MERGE_ALL_BY_NAME
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- AUTO_REFRESH_BARE_INTERVALS
- LIMIT_ONLY_LITERALS
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- DIRECTED_JOINS
- SUPPORTS_MATCH_CONDITION
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- VALUES_AS_TABLE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- ALTER_TABLE_ADD_COLUMNS_WRAPPED
- UNNEST_WITH_ORDINALITY
- COMPUTED_COLUMN_WITH_TYPE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_WITH_METHOD
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- SUPPORTS_SINGLE_ARG_CONCAT
- SUPPORTS_TABLE_ALIAS_COLUMNS
- SUPPORTS_NAMED_CTE_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- PIVOT_ALIAS_WITH_AS
- INSERT_OVERWRITE
- SUPPORTS_SELECT_INTO
- SUPPORTS_OPTIMIZE
- SUPPORTS_EXECUTE_IMMEDIATE
- SUPPORTS_UNLOGGED_TABLES
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- SUPPORTS_ALTER_COLUMN_NULLABILITY
- SUPPORTS_ALTER_COLUMN_IF_EXISTS
- LIKE_PROPERTY_INSIDE_SCHEMA
- JSON_TYPE_REQUIRED_FOR_EXTRACTION
- SUPPORTS_NESTED_JSON_SELECT
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- SET_OP_MODIFIERS
- SET_OP_LIMITS
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_PARAMS_ARE_WRAPPED
- COPY_PARAMS_EQ_REQUIRED
- TRY_SUPPORTED
- SUPPORTS_UESCAPE
- UNICODE_SUBSTITUTE
- HEX_FUNC
- BYTE_STRING_FUNCTION
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- SUPPORTS_EXPLODING_PROJECTIONS
- ARRAY_CONCAT_IS_VAR_LEN
- SUPPORTS_CONVERT_TIMEZONE
- SUPPORTS_MEDIAN
- SUPPORTS_UNIX_SECONDS
- ALTER_SET_WRAPPED
- PARSE_JSON_NAME
- ARRAY_SIZE_NAME
- VARIANCE_NAME
- VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
- ALTER_SET_TYPE
- SUPPORTS_BETWEEN_FLAGS
- MATCH_AGAINST_TABLE_PREFIX
- DECLARE_DEFAULT_ASSIGNMENT
- UPDATE_STATEMENT_SUPPORTS_FROM
- STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
- UNSUPPORTED_TYPES
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- PARAMETERIZABLE_TEXT_TYPES
- EXPRESSIONS_WITHOUT_NESTED_CTES
- RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
- MOD_OPERATOR
- BARE_OPERATORS
- MOD_PAREN_PARENT_TYPES
- ALTER_PARTITION_OPTIONS
- SAFE_JSON_PATH_KEY_RE
- SENTINEL_LINE_BREAK
- pretty
- identify
- normalize
- pad
- unsupported_level
- max_unsupported
- leading_comma
- max_text_width
- comments
- dialect
- normalize_functions
- unsupported_messages
- generate
- preprocess
- unsupported
- sep
- seg
- sanitize_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_parts
- column_sql
- pseudocolumn_sql
- columnposition_sql
- columndef_sql
- columnconstraint_sql
- computedcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- createable_sql
- create_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- describe_sql
- heredoc_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_param_bound_limiter
- directory_sql
- delete_sql
- drop_sql
- set_operation
- set_operations
- fetch_sql
- limitoptions_sql
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- dynamicidentifier_sql
- identifier_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_name
- property_sql
- uuidproperty_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- moduleproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- lockingstatement_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tableargument_sql
- pivot_sql
- version_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- groupingsets_sql
- rollup_sql
- rollupindex_sql
- rollupproperty_sql
- cube_sql
- group_sql
- having_sql
- connectto_sql
- disconnect_sql
- connect_sql
- prior_sql
- nearest_sql
- lateral_op
- lateral_sql
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- queryband_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- boolean_sql
- booland_sql
- boolor_sql
- order_sql
- withfill_sql
- cluster_sql
- clusterproperty_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognizemeasure_sql
- matchrecognize_sql
- query_modifiers
- options_modifier
- forclause_sql
- queryoption_sql
- offset_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- subquery_sql
- qualify_sql
- prewhere_sql
- where_sql
- partition_by_sql
- partitionbyexcluding_sql
- windowspec_sql
- between_sql
- bracket_offset_expressions
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- dayofweek_sql
- extract_date_part
- convert_concat_args
- concat_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- timeserieskey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- jsonpath_sql
- json_path_part
- formatjson_sql
- formatphrase_sql
- teradataconversion_sql
- teradatatitle_sql
- teradatanamed_sql
- jsonarray_sql
- jsonarrayagg_sql
- jsoncolumndef_sql
- jsonschema_sql
- jsontable_sql
- openjsoncolumndef_sql
- openjson_sql
- in_unnest_op
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- pos_sql
- neg_sql
- not_sql
- alias_sql
- pivotalias_sql
- atindex_sql
- attimezone_sql
- fromtimezone_sql
- fromiso8601date_sql
- fromiso8601timestamp_sql
- fromiso8601timestampnanos_sql
- add_sql
- and_sql
- or_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwiseor_sql
- bitwiserightshift_sql
- cast_sql
- command_sql
- optimize_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- transaction_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- modifycolumn_sql
- alterindex_sql
- alterdiststyle_sql
- altersortkey_sql
- alterrename_sql
- renamecolumn_sql
- alterset_sql
- alter_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- replacecolumns_sql
- addpartition_sql
- distinct_sql
- havingmax_sql
- intdiv_sql
- dpipe_sql
- nullif_zero_divisor
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_sql
- nestedjsonselect_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- is_sql
- like_sql
- ilike_sql
- match_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- sub_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- function_name
- func
- format_args
- too_wide
- format_time
- expressions
- op_expressions
- naked_property
- tag_sql
- token_sql
- userdefinedfunction_sql
- macrooverloads_sql
- macrooverload_sql
- joinhint_sql
- kwarg_sql
- when_sql
- whens_sql
- merge_sql
- tochar_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_sql
- aggregatekeyproperty_sql
- duplicatekeyproperty_sql
- uniquekeyproperty_sql
- distributedbyproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- checkcolumnconstraint_sql
- indexcolumnconstraint_sql
- nvl2_sql
- nthvalue_sql
- comprehension_sql
- columnprefix_sql
- opclass_sql
- predict_sql
- generateembedding_sql
- generatetext_sql
- generatetable_sql
- generatebool_sql
- generateint_sql
- generatedouble_sql
- mltranslate_sql
- mlforecast_sql
- aiforecast_sql
- featuresattime_sql
- vectorsearch_sql
- forin_sql
- refresh_sql
- toarray_sql
- tsordstotimestamp_sql
- tsordstodatetime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql
- dateadd_sql
- arrayinsert_sql
- arrayany_sql
- struct_sql
- partitionrange_sql
- truncatetable_sql
- convert_sql
- copyparameter_sql
- credentials_sql
- copy_sql
- semicolon_sql
- datadeletionproperty_sql
- maskingpolicycolumnconstraint_sql
- gapfill_sql
- scope_resolution
- scoperesolution_sql
- changes_sql
- summarize_sql
- explodinggenerateseries_sql
- converttimezone_sql
- json_sql
- jsonvalue_sql
- skipjsoncolumn_sql
- conditionalinsert_sql
- multitableinserts_sql
- oncondition_sql
- jsonextractquote_sql
- jsonexists_sql
- min_sql
- max_sql
- slice_sql
- apply_sql
- grant_sql
- revoke_sql
- grantprivilege_sql
- grantprincipal_sql
- columns_sql
- overlay_sql
- todouble_sql
- string_sql
- median_sql
- overflowtruncatebehavior_sql
- unixseconds_sql
- arraysort_sql
- variance_sql
- arraysize_sql
- attach_sql
- detach_sql
- attachoption_sql
- watermarkcolumnconstraint_sql
- encodeproperty_sql
- includeproperty_sql
- xmlelement_sql
- xmlkeyvalueoption_sql
- partitionbyrangeproperty_sql
- partitionbyrangepropertydynamic_sql
- unpivotcolumns_sql
- analyzesample_sql
- analyzestatistics_sql
- analyzehistogram_sql
- analyzedelete_sql
- analyzelistchainedrows_sql
- analyzevalidate_sql
- analyze_sql
- xmltable_sql
- xmlnamespace_sql
- export_sql
- declare_sql
- declareitem_sql
- recursivewithsearch_sql
- parameterizedagg_sql
- anonymousaggfunc_sql
- combinedaggfunc_sql
- combinedparameterizedagg_sql
- liststage_sql
- get_put_sql
- translatecharacters_sql
- decodecase_sql
- semanticview_sql
- getextract_sql
- datefromunixdate_sql
- buildproperty_sql
- refreshtriggerproperty_sql
- modelattribute_sql
- directorystage_sql
- initcap_sql
- localtime_sql
- localtimestamp_sql
- weekstart_name
- weekstart_sql
- weightstring_sql
- block_sql
- functionspecification_sql
- storedprocedure_sql
- ifblock_sql
- casestatement_sql
- whileblock_sql
- loopblock_sql
- repeatblock_sql
- leave_sql
- iterate_sql
- execute_sql
- executesql_sql
- executeimmediate_sql
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql