sqlglot.generators.snowflake
1from __future__ import annotations 2 3import typing as t 4from collections import defaultdict 5 6from sqlglot import exp, generator, transforms 7from sqlglot.dialects.dialect import ( 8 array_append_sql, 9 array_concat_sql, 10 date_delta_sql, 11 datestrtodate_sql, 12 groupconcat_sql, 13 if_sql, 14 inline_array_sql, 15 map_date_part, 16 max_or_greatest, 17 min_or_least, 18 no_filter_sql, 19 no_make_interval_sql, 20 no_timestamp_sql, 21 nth_value_from_sql, 22 rename_func, 23 strposition_sql, 24 timestampdiff_sql, 25 timestamptrunc_sql, 26 timestrtotime_sql, 27 unit_to_str, 28 var_map_sql, 29) 30from sqlglot.generator import unsupported_args 31from sqlglot.helper import find_new_name, flatten, seq_get 32from sqlglot.optimizer.scope import build_scope, find_all_in_scope 33from sqlglot.parsers.snowflake import ( 34 RANKING_WINDOW_FUNCTIONS_WITH_FRAME, 35 TIMESTAMP_TYPES, 36 SnowflakeParser, 37 build_object_construct, 38) 39from sqlglot.tokens import TokenType 40 41if t.TYPE_CHECKING: 42 from sqlglot._typing import E 43 44 45def _build_datediff(args: list) -> exp.DateDiff: 46 return exp.DateDiff( 47 this=seq_get(args, 2), 48 expression=seq_get(args, 1), 49 unit=map_date_part(seq_get(args, 0)), 50 date_part_boundary=True, 51 ) 52 53 54def _build_date_time_add(expr_type: type[E]) -> t.Callable[[list], E]: 55 def _builder(args: list) -> E: 56 return expr_type( 57 this=seq_get(args, 2), 58 expression=seq_get(args, 1), 59 unit=map_date_part(seq_get(args, 0)), 60 ) 61 62 return _builder 63 64 65def _regexpilike_sql(self: SnowflakeGenerator, expression: exp.RegexpILike) -> str: 66 flag = expression.text("flag") 67 68 if "i" not in flag: 69 flag += "i" 70 71 return self.func( 72 "REGEXP_LIKE", expression.this, expression.expression, exp.Literal.string(flag) 73 ) 74 75 76def _unqualify_pivot_columns(expression: exp.Expr) -> exp.Expr: 77 """ 78 Snowflake doesn't allow columns referenced in UNPIVOT to be qualified, 79 so we need to unqualify them. Same goes for ANY ORDER BY <column>. 80 81 Example: 82 >>> from sqlglot import parse_one 83 >>> expr = parse_one("SELECT * FROM m_sales UNPIVOT(sales FOR month IN (m_sales.jan, feb, mar, april))") 84 >>> print(_unqualify_pivot_columns(expr).sql(dialect="snowflake")) 85 SELECT * FROM m_sales UNPIVOT(sales FOR month IN (jan, feb, mar, april)) 86 """ 87 if isinstance(expression, exp.Pivot): 88 if expression.unpivot: 89 expression = transforms.unqualify_columns(expression) 90 else: 91 for field in expression.fields: 92 field_expr = seq_get(field.expressions if field else [], 0) 93 94 if isinstance(field_expr, exp.PivotAny): 95 unqualified_field_expr = transforms.unqualify_columns(field_expr) 96 t.cast(exp.Expr, field).set("expressions", unqualified_field_expr, 0) 97 98 return expression 99 100 101def _unnest_generate_date_array(unnest: exp.Unnest) -> None: 102 generate_date_array = unnest.expressions[0] 103 start = generate_date_array.args.get("start") 104 end = generate_date_array.args.get("end") 105 step = generate_date_array.args.get("step") 106 107 if not start or not end or not isinstance(step, exp.Interval) or step.name != "1": 108 return 109 110 unit = step.args.get("unit") 111 112 unnest_alias = unnest.args.get("alias") 113 if unnest_alias: 114 unnest_alias = unnest_alias.copy() 115 sequence_value_name = seq_get(unnest_alias.columns, 0) or "value" 116 else: 117 sequence_value_name = "value" 118 119 # We'll add the next sequence value to the starting date and project the result 120 date_add = _build_date_time_add(exp.DateAdd)( 121 [unit, exp.cast(sequence_value_name, "int"), exp.cast(start, "date")] 122 ) 123 124 # We use DATEDIFF to compute the number of sequence values needed 125 number_sequence = SnowflakeParser.FUNCTIONS["ARRAY_GENERATE_RANGE"]( 126 [exp.Literal.number(0), _build_datediff([unit, start, end]) + 1] 127 ) 128 129 unnest.set("expressions", [number_sequence]) 130 131 unnest_parent = unnest.parent 132 if isinstance(unnest_parent, exp.Join): 133 select = unnest_parent.parent 134 if isinstance(select, exp.Select): 135 replace_column_name = ( 136 sequence_value_name 137 if isinstance(sequence_value_name, str) 138 else sequence_value_name.name 139 ) 140 141 scope = build_scope(select) 142 if scope: 143 for column in scope.columns: 144 if column.name.lower() == replace_column_name.lower(): 145 column.replace( 146 date_add.as_(replace_column_name) 147 if isinstance(column.parent, exp.Select) 148 else date_add 149 ) 150 151 lateral = exp.Lateral(this=unnest_parent.this.pop()) 152 unnest_parent.replace(exp.Join(this=lateral)) 153 else: 154 unnest.replace( 155 exp.select(date_add.as_(sequence_value_name)) 156 .from_(unnest.copy()) 157 .subquery(unnest_alias) 158 ) 159 160 161def _transform_generate_date_array(expression: exp.Expr) -> exp.Expr: 162 if isinstance(expression, exp.Select): 163 for generate_date_array in expression.find_all(exp.GenerateDateArray): 164 parent = generate_date_array.parent 165 166 # If GENERATE_DATE_ARRAY is used directly as an array (e.g passed into ARRAY_LENGTH), the transformed Snowflake 167 # query is the following (it'll be unnested properly on the next iteration due to copy): 168 # SELECT ref(GENERATE_DATE_ARRAY(...)) -> SELECT ref((SELECT ARRAY_AGG(*) FROM UNNEST(GENERATE_DATE_ARRAY(...)))) 169 if not isinstance(parent, exp.Unnest): 170 unnest = exp.Unnest(expressions=[generate_date_array.copy()]) 171 generate_date_array.replace( 172 exp.select(exp.ArrayAgg(this=exp.Star())).from_(unnest).subquery() 173 ) 174 175 if ( 176 isinstance(parent, exp.Unnest) 177 and isinstance(parent.parent, (exp.From, exp.Join)) 178 and len(parent.expressions) == 1 179 ): 180 _unnest_generate_date_array(parent) 181 182 return expression 183 184 185@unsupported_args(("expression", "Snowflake's ARRAY_SORT does not support a comparator.")) 186def _array_sort_sql(self: SnowflakeGenerator, expression: exp.ArraySort) -> str: 187 # NULLs default to last when ascending and first when descending 188 asc = expression.args.get("asc") 189 nulls_first = expression.args.get("nulls_first") 190 if asc is None and nulls_first == exp.false(): 191 nulls_first = None 192 elif asc is None and nulls_first is not None: 193 asc = exp.true() 194 elif asc == exp.false() and nulls_first == exp.true(): 195 nulls_first = None 196 return self.func("ARRAY_SORT", expression.this, asc, nulls_first) 197 198 199def _regexpextract_sql( 200 self: SnowflakeGenerator, expression: exp.RegexpExtract | exp.RegexpExtractAll 201) -> str: 202 # Other dialects don't support all of the following parameters, so we need to 203 # generate default values as necessary to ensure the transpilation is correct 204 group = expression.args.get("group") 205 parameters = expression.args.get("parameters") 206 207 has_e = parameters and parameters.is_string and "e" in parameters.name 208 if expression.args.get("inferred_group") or (group and not has_e and group.name == "0"): 209 group = None 210 211 parameters = parameters or (group and exp.Literal.string("c")) 212 occurrence = expression.args.get("occurrence") or (parameters and exp.Literal.number(1)) 213 position = expression.args.get("position") or (occurrence and exp.Literal.number(1)) 214 215 return self.func( 216 "REGEXP_SUBSTR" if isinstance(expression, exp.RegexpExtract) else "REGEXP_SUBSTR_ALL", 217 expression.this, 218 expression.expression, 219 position, 220 occurrence, 221 parameters, 222 group, 223 ) 224 225 226def _json_extract_value_array_sql( 227 self: SnowflakeGenerator, expression: exp.JSONValueArray | exp.JSONExtractArray 228) -> str: 229 json_extract = exp.JSONExtract(this=expression.this, expression=expression.expression) 230 ident = exp.to_identifier("x") 231 232 if isinstance(expression, exp.JSONValueArray): 233 this: exp.Expr = exp.cast(ident, to=exp.DType.VARCHAR) 234 else: 235 this = exp.ParseJSON(this=f"TO_JSON({ident})") 236 237 transform_lambda = exp.Lambda(expressions=[ident], this=this) 238 239 return self.func("TRANSFORM", json_extract, transform_lambda) 240 241 242def _qualify_unnested_columns(expression: exp.Expr) -> exp.Expr: 243 if isinstance(expression, exp.Select): 244 scope = build_scope(expression) 245 if not scope: 246 return expression 247 248 unnests = list(scope.find_all(exp.Unnest)) 249 250 if not unnests: 251 return expression 252 253 taken_source_names = set(scope.sources) 254 column_source: dict[str, exp.Identifier] = {} 255 unnest_to_identifier: dict[exp.Unnest, exp.Identifier] = {} 256 257 unnest_identifier: exp.Identifier | None = None 258 offset_name = "" 259 orig_expression = expression.copy() 260 261 for unnest in unnests: 262 if not isinstance(unnest.parent, (exp.From, exp.Join)): 263 continue 264 265 # Try to infer column names produced by an unnest operator. This is only possible 266 # when we can peek into the (statically known) contents of the unnested value. 267 unnest_columns: set[str] = set() 268 for unnest_expr in unnest.expressions: 269 if not isinstance(unnest_expr, exp.Array): 270 continue 271 272 for array_expr in unnest_expr.expressions: 273 if not ( 274 isinstance(array_expr, exp.Struct) 275 and array_expr.expressions 276 and all( 277 isinstance(struct_expr, exp.PropertyEQ) 278 for struct_expr in array_expr.expressions 279 ) 280 ): 281 continue 282 283 unnest_columns.update( 284 struct_expr.this.name.lower() for struct_expr in array_expr.expressions 285 ) 286 break 287 288 if unnest_columns: 289 break 290 291 unnest_alias = unnest.args.get("alias") 292 if not unnest_alias: 293 alias_name = find_new_name(taken_source_names, "value") 294 taken_source_names.add(alias_name) 295 296 # Produce a `TableAlias` AST similar to what is produced for BigQuery. This 297 # will be corrected later, when we generate SQL for the `Unnest` AST node. 298 aliased_unnest = exp.alias_(unnest, None, table=[alias_name]) 299 scope.replace(unnest, aliased_unnest) 300 301 unnest_identifier = aliased_unnest.args["alias"].columns[0] 302 else: 303 alias_columns = getattr(unnest_alias, "columns", []) 304 unnest_identifier = unnest_alias.this or seq_get(alias_columns, 0) 305 306 if not isinstance(unnest_identifier, exp.Identifier): 307 return orig_expression 308 309 # An offset alias takes precedence over an implicit struct field of the same name. 310 offset_name = unnest.text("offset").lower() 311 unnest_columns.discard(offset_name) 312 unnest_to_identifier[unnest] = unnest_identifier 313 column_source.update({c.lower(): unnest_identifier for c in unnest_columns}) 314 315 for column in scope.columns: 316 if column.table: 317 continue 318 319 column_name = column.name.lower() 320 table = column_source.get(column_name) 321 if ( 322 unnest_identifier 323 and not table 324 and len(scope.sources) == 1 325 and column_name not in (unnest_identifier.name.lower(), offset_name) 326 ): 327 unnest_ancestor = column.find_ancestor(exp.Unnest, exp.Select) 328 if isinstance(unnest_ancestor, exp.Unnest): 329 ancestor_identifier = unnest_to_identifier.get(unnest_ancestor) 330 if ( 331 ancestor_identifier 332 and ancestor_identifier.name.lower() == unnest_identifier.name.lower() 333 ): 334 continue 335 336 table = unnest_identifier 337 338 column.set("table", table and table.copy()) 339 340 return expression 341 342 343def _eliminate_dot_variant_lookup(expression: exp.Expr) -> exp.Expr: 344 if isinstance(expression, exp.Select): 345 # This transformation is used to facilitate transpilation of BigQuery `UNNEST` operations 346 # to Snowflake. It should not affect roundtrip because `Unnest` nodes cannot be produced 347 # by Snowflake's parser. 348 # 349 # Additionally, at the time of writing this, BigQuery is the only dialect that produces a 350 # `TableAlias` node that only fills `columns` and not `this`, due to `UNNEST_COLUMN_ONLY`. 351 unnest_aliases = set() 352 for unnest in find_all_in_scope(expression, exp.Unnest): 353 unnest_alias = unnest.args.get("alias") 354 if ( 355 isinstance(unnest_alias, exp.TableAlias) 356 and not unnest_alias.this 357 and len(unnest_alias.columns) == 1 358 ): 359 unnest_aliases.add(unnest_alias.columns[0].name) 360 361 if unnest_aliases: 362 for c in find_all_in_scope(expression, exp.Column, include_udtfs=True): 363 if c.table in unnest_aliases: 364 bracket_lhs = c.args["table"] 365 bracket_rhs = exp.Literal.string(c.name) 366 bracket = exp.Bracket(this=bracket_lhs, expressions=[bracket_rhs]) 367 368 if c.parent is expression: 369 # Retain column projection names by using aliases 370 c.replace(exp.alias_(bracket, c.this.copy())) 371 else: 372 c.replace(bracket) 373 374 return expression 375 376 377class SnowflakeGenerator(generator.Generator): 378 DAYOFWEEK_NAME = "DAYOFWEEK" 379 DAYOFWEEK_ZERO_BASED = True 380 BYTE_STRING_FUNCTION = "HEX_DECODE_BINARY" 381 SELECT_KINDS = () 382 PARAMETER_TOKEN = "$" 383 MATCHED_BY_SOURCE = False 384 SUPPORTS_MULTI_ARG_CHR = False 385 MERGE_ALL_BY_NAME = True 386 SINGLE_STRING_INTERVAL = True 387 CAST_TO_INT_ROUNDS = True 388 JOIN_HINTS = False 389 TABLE_HINTS = False 390 QUERY_HINTS = False 391 SUPPORTS_TABLE_COPY = False 392 COLLATE_IS_FUNC = True 393 LIMIT_ONLY_LITERALS = True 394 JSON_KEY_VALUE_PAIR_SEP = "," 395 INSERT_OVERWRITE = " OVERWRITE INTO" 396 STRUCT_DELIMITER = ("(", ")") 397 COPY_PARAMS_ARE_WRAPPED = False 398 COPY_PARAMS_EQ_REQUIRED = True 399 STAR_EXCEPT = "EXCLUDE" 400 SUPPORTS_EXPLODING_PROJECTIONS = False 401 ARRAY_CONCAT_IS_VAR_LEN = False 402 SUPPORTS_CONVERT_TIMEZONE = True 403 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 404 SUPPORTS_MEDIAN = True 405 ARRAY_SIZE_NAME = "ARRAY_SIZE" 406 NORMALIZE_EXTRACT_DATE_PARTS = True 407 SUPPORTS_DECODE_CASE = True 408 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 409 ALTER_TABLE_ADD_COLUMNS_WRAPPED = False 410 411 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 412 413 IS_BOOL_ALLOWED = False 414 DIRECTED_JOINS = True 415 SUPPORTS_MATCH_CONDITION = True 416 SUPPORTS_UESCAPE = False 417 TRY_SUPPORTED = False 418 419 TRANSFORMS = { 420 **generator.Generator.TRANSFORMS, 421 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 422 exp.ArgMax: rename_func("MAX_BY"), 423 exp.ArgMin: rename_func("MIN_BY"), 424 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 425 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 426 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 427 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 428 exp.ArrayContains: lambda self, e: self.func( 429 "ARRAY_CONTAINS", 430 e.expression 431 if e.args.get("ensure_variant") is False 432 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 433 e.this, 434 ), 435 exp.ArrayPosition: lambda self, e: self.func( 436 "ARRAY_POSITION", 437 e.expression, 438 e.this, 439 ), 440 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 441 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 442 exp.ArraySort: _array_sort_sql, 443 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 444 exp.BitwiseOr: rename_func("BITOR"), 445 exp.BitwiseXor: rename_func("BITXOR"), 446 exp.BitwiseAnd: rename_func("BITAND"), 447 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 448 exp.BitwiseOrAgg: rename_func("BITORAGG"), 449 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 450 exp.BitwiseNot: rename_func("BITNOT"), 451 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 452 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 453 exp.CurrentTimestamp: lambda self, e: ( 454 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 455 ), 456 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 457 exp.Localtime: lambda self, e: ( 458 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 459 ), 460 exp.Localtimestamp: lambda self, e: ( 461 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 462 ), 463 exp.DateAdd: date_delta_sql("DATEADD"), 464 exp.DateDiff: date_delta_sql("DATEDIFF"), 465 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 466 exp.DatetimeDiff: timestampdiff_sql, 467 exp.DateStrToDate: datestrtodate_sql, 468 exp.Decrypt: lambda self, e: self.func( 469 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 470 e.this, 471 e.args.get("passphrase"), 472 e.args.get("aad"), 473 e.args.get("encryption_method"), 474 ), 475 exp.DecryptRaw: lambda self, e: self.func( 476 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 477 e.this, 478 e.args.get("key"), 479 e.args.get("iv"), 480 e.args.get("aad"), 481 e.args.get("encryption_method"), 482 e.args.get("aead"), 483 ), 484 exp.DayOfMonth: rename_func("DAYOFMONTH"), 485 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 486 exp.DayOfYear: rename_func("DAYOFYEAR"), 487 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 488 exp.Explode: rename_func("FLATTEN"), 489 exp.Extract: lambda self, e: self.func( 490 "DATE_PART", self.extract_date_part(e.this), e.expression 491 ), 492 exp.Filter: no_filter_sql, 493 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 494 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 495 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 496 exp.FileFormatProperty: lambda self, e: ( 497 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 498 ), 499 exp.FromTimeZone: lambda self, e: self.func( 500 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 501 ), 502 exp.GenerateSeries: lambda self, e: self.func( 503 "ARRAY_GENERATE_RANGE", 504 e.args["start"], 505 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 506 e.args.get("step"), 507 ), 508 exp.GetExtract: rename_func("GET"), 509 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 510 exp.If: if_sql(name="IFF", false_value="NULL"), 511 exp.InteractiveProperty: lambda *_: "INTERACTIVE", 512 exp.JSONArray: lambda self, e: self.func( 513 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 514 ), 515 exp.JSONExtractArray: _json_extract_value_array_sql, 516 exp.JSONExtractScalar: lambda self, e: self.func( 517 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 518 ), 519 exp.JSONKeys: rename_func("OBJECT_KEYS"), 520 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 521 exp.JSONPathRoot: lambda *_: "", 522 exp.JSONValueArray: _json_extract_value_array_sql, 523 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 524 rename_func("EDITDISTANCE") 525 ), 526 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 527 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 528 exp.LogicalOr: rename_func("BOOLOR_AGG"), 529 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 530 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 531 exp.MakeInterval: no_make_interval_sql, 532 exp.Max: max_or_greatest, 533 exp.Min: min_or_least, 534 exp.NthValue: nth_value_from_sql, 535 exp.ParseJSON: lambda self, e: self.func( 536 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 537 ), 538 exp.ToBinary: lambda self, e: self.func( 539 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 540 ), 541 exp.ToBoolean: lambda self, e: self.func( 542 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 543 ), 544 exp.ToDouble: lambda self, e: self.func( 545 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 546 ), 547 exp.ToFile: lambda self, e: self.func( 548 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 549 ), 550 exp.JSONFormat: rename_func("TO_JSON"), 551 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 552 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 553 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 554 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 555 exp.RegexpExtract: _regexpextract_sql, 556 exp.RegexpExtractAll: _regexpextract_sql, 557 exp.RegexpILike: _regexpilike_sql, 558 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 559 exp.Select: transforms.preprocess( 560 [ 561 transforms.eliminate_window_clause, 562 transforms.eliminate_distinct_on, 563 transforms.explode_projection_to_unnest(), 564 transforms.eliminate_semi_and_anti_joins, 565 _transform_generate_date_array, 566 _qualify_unnested_columns, 567 _eliminate_dot_variant_lookup, 568 ] 569 ), 570 exp.SHA: rename_func("SHA1"), 571 exp.SHA1Digest: rename_func("SHA1_BINARY"), 572 exp.MD5Digest: rename_func("MD5_BINARY"), 573 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 574 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 575 exp.Hex: rename_func("HEX_ENCODE"), 576 exp.LowerHex: rename_func("TO_CHAR"), 577 exp.Skewness: rename_func("SKEW"), 578 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 579 exp.StartsWith: rename_func("STARTSWITH"), 580 exp.EndsWith: rename_func("ENDSWITH"), 581 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 582 exp.StrPosition: lambda self, e: strposition_sql( 583 self, e, func_name="CHARINDEX", supports_position=True 584 ), 585 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 586 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 587 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 588 exp.Stuff: rename_func("INSERT"), 589 exp.StPoint: rename_func("ST_MAKEPOINT"), 590 exp.TemporaryProperty: lambda _, e: ( 591 "SCOPED TEMPORARY" if e.args.get("scoped") else "TEMPORARY" 592 ), 593 exp.TimeAdd: date_delta_sql("TIMEADD"), 594 exp.TimeSlice: lambda self, e: self.func( 595 "TIME_SLICE", 596 e.this, 597 e.expression, 598 unit_to_str(e), 599 e.args.get("kind"), 600 ), 601 exp.Timestamp: no_timestamp_sql, 602 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 603 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 604 exp.TimestampTrunc: timestamptrunc_sql(), 605 exp.TimeStrToTime: timestrtotime_sql, 606 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 607 exp.ToArray: rename_func("TO_ARRAY"), 608 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 609 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 610 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 611 exp.TsOrDsToDate: lambda self, e: self.func( 612 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 613 ), 614 exp.TsOrDsToTime: lambda self, e: self.func( 615 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 616 ), 617 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 618 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 619 exp.Uuid: rename_func("UUID_STRING"), 620 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 621 exp.Booland: rename_func("BOOLAND"), 622 exp.Boolor: rename_func("BOOLOR"), 623 exp.WeekOfYear: rename_func("WEEKISO"), 624 exp.YearOfWeek: rename_func("YEAROFWEEK"), 625 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 626 exp.Xor: rename_func("BOOLXOR"), 627 exp.ByteLength: rename_func("OCTET_LENGTH"), 628 exp.Flatten: rename_func("ARRAY_FLATTEN"), 629 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 630 exp.SHA2Digest: lambda self, e: self.func( 631 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 632 ), 633 } 634 635 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 636 this = self.func("IDENTIFIER", expression.this) 637 if "expressions" in expression.args: 638 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 639 return self.func(this, *expression.expressions, normalize=False) 640 return this 641 642 SUPPORTED_JSON_PATH_PARTS = { 643 exp.JSONPathKey, 644 exp.JSONPathRoot, 645 exp.JSONPathSubscript, 646 } 647 648 TYPE_MAPPING = { 649 **generator.Generator.TYPE_MAPPING, 650 exp.DType.BIGDECIMAL: "DOUBLE", 651 exp.DType.JSON: "VARIANT", 652 exp.DType.NESTED: "OBJECT", 653 exp.DType.STRUCT: "OBJECT", 654 exp.DType.TEXT: "VARCHAR", 655 } 656 657 TOKEN_MAPPING = { 658 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 659 } 660 661 PROPERTIES_LOCATION = { 662 **generator.Generator.PROPERTIES_LOCATION, 663 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 664 exp.InteractiveProperty: exp.Properties.Location.POST_CREATE, 665 exp.LocationProperty: exp.Properties.Location.POST_WITH, 666 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 667 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 668 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 669 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 670 } 671 672 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 673 exp.Map, 674 exp.StarMap, 675 exp.Struct, 676 exp.VarMap, 677 } 678 679 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 680 681 WINDOW_FUNCS_REQUIRING_ORDER = ( 682 exp.CumeDist, 683 exp.DenseRank, 684 exp.FirstValue, 685 exp.LastValue, 686 exp.NthValue, 687 exp.Ntile, 688 exp.PercentRank, 689 exp.Rank, 690 exp.RowNumber, 691 ) 692 693 def with_properties(self, properties: exp.Properties) -> str: 694 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 695 696 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 697 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 698 values_as_table = False 699 700 return super().values_sql(expression, values_as_table=values_as_table) 701 702 def datatype_sql(self, expression: exp.DataType) -> str: 703 # Check if this is a FLOAT type nested inside a VECTOR type 704 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 705 # https://docs.snowflake.com/en/sql-reference/data-types-vector 706 if expression.is_type(exp.DType.DOUBLE): 707 parent = expression.parent 708 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 709 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 710 return "FLOAT" 711 712 expressions = expression.expressions 713 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 714 for field_type in expressions: 715 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 716 if isinstance(field_type, exp.DataType): 717 return "OBJECT" 718 if ( 719 isinstance(field_type, exp.ColumnDef) 720 and field_type.this 721 and field_type.this.is_string 722 ): 723 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 724 # converting 'foo' into an identifier, we also need to quote it because these 725 # keys are case-sensitive. For example: 726 # 727 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 728 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 729 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 730 731 return super().datatype_sql(expression) 732 733 def tonumber_sql(self, expression: exp.ToNumber) -> str: 734 precision = expression.args.get("precision") 735 scale = expression.args.get("scale") 736 737 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 738 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 739 740 if default_precision and default_scale: 741 precision = None 742 scale = None 743 elif default_scale: 744 scale = None 745 746 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 747 748 return self.func( 749 func_name, 750 expression.this, 751 expression.args.get("format"), 752 precision, 753 scale, 754 ) 755 756 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 757 milli = expression.args.get("milli") 758 if milli is not None: 759 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 760 expression.set("nano", milli_to_nano) 761 762 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 763 764 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 765 if expression.is_type(exp.DType.GEOGRAPHY): 766 return self.func("TO_GEOGRAPHY", expression.this) 767 if expression.is_type(exp.DType.GEOMETRY): 768 return self.func("TO_GEOMETRY", expression.this) 769 770 return super().cast_sql(expression, safe_prefix=safe_prefix) 771 772 def trycast_sql(self, expression: exp.TryCast) -> str: 773 value = expression.this 774 775 if value.type is None: 776 from sqlglot.optimizer.annotate_types import annotate_types 777 778 value = annotate_types(value, dialect=self.dialect) 779 780 # Snowflake requires that TRY_CAST's value be a string 781 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 782 # if we can deduce that the value is a string, then we can generate TRY_CAST 783 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 784 return super().trycast_sql(expression) 785 786 return self.cast_sql(expression) 787 788 def log_sql(self, expression: exp.Log) -> str: 789 if not expression.expression: 790 return self.func("LN", expression.this) 791 792 return super().log_sql(expression) 793 794 def greatest_sql(self, expression: exp.Greatest) -> str: 795 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 796 return self.func(name, expression.this, *expression.expressions) 797 798 def least_sql(self, expression: exp.Least) -> str: 799 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 800 return self.func(name, expression.this, *expression.expressions) 801 802 def generator_sql(self, expression: exp.Generator) -> str: 803 args = [] 804 rowcount = expression.args.get("rowcount") 805 timelimit = expression.args.get("timelimit") 806 807 if rowcount: 808 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 809 if timelimit: 810 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 811 812 return self.func("GENERATOR", *args) 813 814 def unnest_sql(self, expression: exp.Unnest) -> str: 815 unnest_alias = expression.args.get("alias") 816 offset = expression.args.get("offset") 817 818 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 819 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 820 821 columns = [ 822 exp.to_identifier("seq"), 823 exp.to_identifier("key"), 824 exp.to_identifier("path"), 825 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 826 value, 827 exp.to_identifier("this"), 828 ] 829 830 if unnest_alias: 831 unnest_alias.set("columns", columns) 832 else: 833 unnest_alias = exp.TableAlias(this="_u", columns=columns) 834 835 table_input = self.sql(expression.expressions[0]) 836 if not table_input.startswith("INPUT =>"): 837 table_input = f"INPUT => {table_input}" 838 839 expression_parent = expression.parent 840 841 explode = ( 842 f"FLATTEN({table_input})" 843 if isinstance(expression_parent, exp.Lateral) 844 else f"TABLE(FLATTEN({table_input}))" 845 ) 846 alias = self.sql(unnest_alias) 847 alias = f" AS {alias}" if alias else "" 848 value = ( 849 "" 850 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 851 else f"{value} FROM " 852 ) 853 854 return f"{value}{explode}{alias}" 855 856 def undrop_sql(self, expression: exp.Undrop) -> str: 857 this = self.sql(expression, "this") 858 kind = expression.kind 859 rename = self.sql(expression, "rename") 860 rename = f" RENAME TO {rename}" if rename else "" 861 return f"UNDROP {kind} {this}{rename}" 862 863 def show_sql(self, expression: exp.Show) -> str: 864 terse = "TERSE " if expression.args.get("terse") else "" 865 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 866 history = " HISTORY" if expression.args.get("history") else "" 867 like = self.sql(expression, "like") 868 like = f" LIKE {like}" if like else "" 869 870 scope = self.sql(expression, "scope") 871 scope = f" {scope}" if scope else "" 872 873 scope_kind = self.sql(expression, "scope_kind") 874 if scope_kind: 875 scope_kind = f" IN {scope_kind}" 876 877 starts_with = self.sql(expression, "starts_with") 878 if starts_with: 879 starts_with = f" STARTS WITH {starts_with}" 880 881 limit = self.sql(expression, "limit") 882 883 from_ = self.sql(expression, "from_") 884 if from_: 885 from_ = f" FROM {from_}" 886 887 privileges = self.expressions(expression, key="privileges", flat=True) 888 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 889 890 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 891 892 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 893 if not expression.this: 894 return "ROW ACCESS" 895 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 896 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 897 898 def describe_sql(self, expression: exp.Describe) -> str: 899 kind_value = expression.args.get("kind") or "TABLE" 900 901 properties = expression.args.get("properties") 902 if properties: 903 qualifier = self.expressions(properties, sep=" ") 904 kind = f" {qualifier} {kind_value}" 905 else: 906 kind = f" {kind_value}" 907 908 this = f" {self.sql(expression, 'this')}" 909 expressions = self.expressions(expression, flat=True) 910 expressions = f" {expressions}" if expressions else "" 911 return f"DESCRIBE{kind}{this}{expressions}" 912 913 def generatedasidentitycolumnconstraint_sql( 914 self, expression: exp.GeneratedAsIdentityColumnConstraint 915 ) -> str: 916 start = expression.args.get("start") 917 start = f" START {start}" if start else "" 918 increment = expression.args.get("increment") 919 increment = f" INCREMENT {increment}" if increment else "" 920 921 order = expression.args.get("order") 922 if order is not None: 923 order_clause = " ORDER" if order else " NOORDER" 924 else: 925 order_clause = "" 926 927 return f"AUTOINCREMENT{start}{increment}{order_clause}" 928 929 def struct_sql(self, expression: exp.Struct) -> str: 930 if len(expression.expressions) == 1: 931 arg = expression.expressions[0] 932 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 933 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 934 return f"{{{self.sql(expression.expressions[0])}}}" 935 936 keys = [] 937 values = [] 938 939 for i, e in enumerate(expression.expressions): 940 if isinstance(e, exp.PropertyEQ): 941 keys.append( 942 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 943 ) 944 values.append(e.expression) 945 else: 946 keys.append(exp.Literal.string(f"_{i}")) 947 values.append(e) 948 949 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 950 951 @unsupported_args("weight", "accuracy") 952 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 953 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 954 955 def alterset_sql(self, expression: exp.AlterSet) -> str: 956 exprs = self.expressions(expression, flat=True) 957 exprs = f" {exprs}" if exprs else "" 958 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 959 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 960 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 961 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 962 tag = self.expressions(expression, key="tag", flat=True) 963 tag = f" TAG {tag}" if tag else "" 964 965 return f"SET{exprs}{file_format}{copy_options}{tag}" 966 967 def strtotime_sql(self, expression: exp.StrToTime): 968 # target_type is stored as a DataType instance 969 target_type = expression.args.get("target_type") 970 971 # Get the type enum from DataType instance or from type annotation 972 if isinstance(target_type, exp.DataType): 973 type_enum = target_type.this 974 elif expression.type: 975 type_enum = expression.type.this 976 else: 977 type_enum = exp.DType.TIMESTAMP 978 979 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 980 981 return self.func( 982 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 983 expression.this, 984 self.format_time(expression), 985 ) 986 987 def timestampsub_sql(self, expression: exp.TimestampSub): 988 return self.sql( 989 exp.TimestampAdd( 990 this=expression.this, 991 expression=expression.expression * -1, 992 unit=expression.unit, 993 ) 994 ) 995 996 def jsonextract_sql(self, expression: exp.JSONExtract): 997 this = expression.this 998 999 # JSON strings are valid coming from other dialects such as BQ so 1000 # for these cases we PARSE_JSON preemptively 1001 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 1002 "requires_json" 1003 ): 1004 this = exp.ParseJSON(this=this) 1005 1006 return self.func( 1007 "GET_PATH", 1008 this, 1009 expression.expression, 1010 ) 1011 1012 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 1013 this = expression.this 1014 if this.is_string: 1015 this = exp.cast(this, exp.DType.TIMESTAMP) 1016 1017 return self.func("TO_CHAR", this, self.format_time(expression)) 1018 1019 def datesub_sql(self, expression: exp.DateSub) -> str: 1020 value = expression.expression 1021 if value: 1022 value.replace(value * (-1)) 1023 else: 1024 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1025 1026 return date_delta_sql("DATEADD")(self, expression) 1027 1028 def select_sql(self, expression: exp.Select) -> str: 1029 limit = expression.args.get("limit") 1030 offset = expression.args.get("offset") 1031 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1032 expression.limit(exp.Null(), copy=False) 1033 return super().select_sql(expression) 1034 1035 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1036 is_materialized = expression.find(exp.MaterializedProperty) 1037 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1038 1039 if expression.kind == "VIEW" and is_materialized and grants_property: 1040 # Materialized views require COPY/IGNORE GRANTS before the column list, 1041 # whereas normal views use the default POST_SCHEMA location. 1042 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1043 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1044 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1045 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1046 1047 this_name = self.sql(expression.this, "this") 1048 grants = self.sql(grants_property) 1049 this_schema = self.schema_columns_sql(expression.this) 1050 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1051 1052 return f"{this_name}{self.sep()}{grants}{this_schema}" 1053 1054 return super().createable_sql(expression, locations) 1055 1056 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1057 this = expression.this 1058 1059 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1060 # and add it later as part of the WITHIN GROUP clause 1061 order = this if isinstance(this, exp.Order) else None 1062 if order: 1063 expression.set("this", order.this.pop()) 1064 1065 expr_sql = super().arrayagg_sql(expression) 1066 1067 if order: 1068 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1069 1070 return expr_sql 1071 1072 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1073 if expression.args.get("check_null"): 1074 return self.func("ARRAY_DISTINCT", expression.this) 1075 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1076 1077 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1078 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1079 1080 def array_sql(self, expression: exp.Array) -> str: 1081 expressions = expression.expressions 1082 1083 first_expr = seq_get(expressions, 0) 1084 if isinstance(first_expr, exp.Select): 1085 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1086 if first_expr.text("kind").upper() == "STRUCT": 1087 object_construct_args = [] 1088 for expr in first_expr.expressions: 1089 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1090 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1091 name = expr.this if isinstance(expr, exp.Alias) else expr 1092 1093 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1094 1095 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1096 1097 first_expr.set("kind", None) 1098 first_expr.set("expressions", [array_agg]) 1099 1100 return self.sql(first_expr.subquery()) 1101 1102 return inline_array_sql(self, expression) 1103 1104 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1105 zone = self.sql(expression, "this") 1106 if not zone: 1107 return super().currentdate_sql(expression) 1108 1109 expr = exp.Cast( 1110 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1111 to=exp.DataType(this=exp.DType.DATE), 1112 ) 1113 return self.sql(expr) 1114 1115 def dot_sql(self, expression: exp.Dot) -> str: 1116 this = expression.this 1117 1118 if not this.type: 1119 from sqlglot.optimizer.annotate_types import annotate_types 1120 1121 this = annotate_types(this, dialect=self.dialect) 1122 1123 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1124 # Generate colon notation for the top level STRUCT 1125 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1126 1127 return super().dot_sql(expression) 1128 1129 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1130 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1131 1132 def format_sql(self, expression: exp.Format) -> str: 1133 if expression.args.get("is_fmt"): 1134 return super().format_sql(expression) 1135 1136 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1137 return self.func("TO_CHAR", expression.expressions[0]) 1138 1139 return self.function_fallback_sql(expression) 1140 1141 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1142 # Set part_index to 1 if missing 1143 if not expression.args.get("delimiter"): 1144 expression.set("delimiter", exp.Literal.string(" ")) 1145 1146 if not expression.args.get("part_index"): 1147 expression.set("part_index", exp.Literal.number(1)) 1148 1149 return rename_func("SPLIT_PART")(self, expression) 1150 1151 def uniform_sql(self, expression: exp.Uniform) -> str: 1152 gen = expression.args.get("gen") 1153 seed = expression.args.get("seed") 1154 1155 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1156 if seed: 1157 gen = exp.Rand(this=seed) 1158 1159 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1160 if not gen: 1161 gen = exp.Rand() 1162 1163 return self.func("UNIFORM", expression.this, expression.expression, gen) 1164 1165 def window_sql(self, expression: exp.Window) -> str: 1166 spec = expression.args.get("spec") 1167 this = expression.this 1168 1169 if ( 1170 ( 1171 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1172 or ( 1173 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1174 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1175 ) 1176 ) 1177 and spec 1178 and ( 1179 spec.text("kind").upper() == "ROWS" 1180 and spec.text("start").upper() == "UNBOUNDED" 1181 and spec.text("start_side").upper() == "PRECEDING" 1182 and spec.text("end").upper() == "UNBOUNDED" 1183 and spec.text("end_side").upper() == "FOLLOWING" 1184 ) 1185 ): 1186 # omit the default window from window ranking functions 1187 expression.set("spec", None) 1188 return super().window_sql(expression) 1189 1190 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1191 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1192 # accepts the value to aggregate as an argument: MODE(<expr>) 1193 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1194 order = expression.expression 1195 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1196 return self.sql(exp.Mode(this=order.expressions[0].this)) 1197 1198 return super().withingroup_sql(expression)
378class SnowflakeGenerator(generator.Generator): 379 DAYOFWEEK_NAME = "DAYOFWEEK" 380 DAYOFWEEK_ZERO_BASED = True 381 BYTE_STRING_FUNCTION = "HEX_DECODE_BINARY" 382 SELECT_KINDS = () 383 PARAMETER_TOKEN = "$" 384 MATCHED_BY_SOURCE = False 385 SUPPORTS_MULTI_ARG_CHR = False 386 MERGE_ALL_BY_NAME = True 387 SINGLE_STRING_INTERVAL = True 388 CAST_TO_INT_ROUNDS = True 389 JOIN_HINTS = False 390 TABLE_HINTS = False 391 QUERY_HINTS = False 392 SUPPORTS_TABLE_COPY = False 393 COLLATE_IS_FUNC = True 394 LIMIT_ONLY_LITERALS = True 395 JSON_KEY_VALUE_PAIR_SEP = "," 396 INSERT_OVERWRITE = " OVERWRITE INTO" 397 STRUCT_DELIMITER = ("(", ")") 398 COPY_PARAMS_ARE_WRAPPED = False 399 COPY_PARAMS_EQ_REQUIRED = True 400 STAR_EXCEPT = "EXCLUDE" 401 SUPPORTS_EXPLODING_PROJECTIONS = False 402 ARRAY_CONCAT_IS_VAR_LEN = False 403 SUPPORTS_CONVERT_TIMEZONE = True 404 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 405 SUPPORTS_MEDIAN = True 406 ARRAY_SIZE_NAME = "ARRAY_SIZE" 407 NORMALIZE_EXTRACT_DATE_PARTS = True 408 SUPPORTS_DECODE_CASE = True 409 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 410 ALTER_TABLE_ADD_COLUMNS_WRAPPED = False 411 412 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 413 414 IS_BOOL_ALLOWED = False 415 DIRECTED_JOINS = True 416 SUPPORTS_MATCH_CONDITION = True 417 SUPPORTS_UESCAPE = False 418 TRY_SUPPORTED = False 419 420 TRANSFORMS = { 421 **generator.Generator.TRANSFORMS, 422 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 423 exp.ArgMax: rename_func("MAX_BY"), 424 exp.ArgMin: rename_func("MIN_BY"), 425 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 426 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 427 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 428 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 429 exp.ArrayContains: lambda self, e: self.func( 430 "ARRAY_CONTAINS", 431 e.expression 432 if e.args.get("ensure_variant") is False 433 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 434 e.this, 435 ), 436 exp.ArrayPosition: lambda self, e: self.func( 437 "ARRAY_POSITION", 438 e.expression, 439 e.this, 440 ), 441 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 442 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 443 exp.ArraySort: _array_sort_sql, 444 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 445 exp.BitwiseOr: rename_func("BITOR"), 446 exp.BitwiseXor: rename_func("BITXOR"), 447 exp.BitwiseAnd: rename_func("BITAND"), 448 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 449 exp.BitwiseOrAgg: rename_func("BITORAGG"), 450 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 451 exp.BitwiseNot: rename_func("BITNOT"), 452 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 453 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 454 exp.CurrentTimestamp: lambda self, e: ( 455 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 456 ), 457 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 458 exp.Localtime: lambda self, e: ( 459 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 460 ), 461 exp.Localtimestamp: lambda self, e: ( 462 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 463 ), 464 exp.DateAdd: date_delta_sql("DATEADD"), 465 exp.DateDiff: date_delta_sql("DATEDIFF"), 466 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 467 exp.DatetimeDiff: timestampdiff_sql, 468 exp.DateStrToDate: datestrtodate_sql, 469 exp.Decrypt: lambda self, e: self.func( 470 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 471 e.this, 472 e.args.get("passphrase"), 473 e.args.get("aad"), 474 e.args.get("encryption_method"), 475 ), 476 exp.DecryptRaw: lambda self, e: self.func( 477 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 478 e.this, 479 e.args.get("key"), 480 e.args.get("iv"), 481 e.args.get("aad"), 482 e.args.get("encryption_method"), 483 e.args.get("aead"), 484 ), 485 exp.DayOfMonth: rename_func("DAYOFMONTH"), 486 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 487 exp.DayOfYear: rename_func("DAYOFYEAR"), 488 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 489 exp.Explode: rename_func("FLATTEN"), 490 exp.Extract: lambda self, e: self.func( 491 "DATE_PART", self.extract_date_part(e.this), e.expression 492 ), 493 exp.Filter: no_filter_sql, 494 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 495 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 496 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 497 exp.FileFormatProperty: lambda self, e: ( 498 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 499 ), 500 exp.FromTimeZone: lambda self, e: self.func( 501 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 502 ), 503 exp.GenerateSeries: lambda self, e: self.func( 504 "ARRAY_GENERATE_RANGE", 505 e.args["start"], 506 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 507 e.args.get("step"), 508 ), 509 exp.GetExtract: rename_func("GET"), 510 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 511 exp.If: if_sql(name="IFF", false_value="NULL"), 512 exp.InteractiveProperty: lambda *_: "INTERACTIVE", 513 exp.JSONArray: lambda self, e: self.func( 514 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 515 ), 516 exp.JSONExtractArray: _json_extract_value_array_sql, 517 exp.JSONExtractScalar: lambda self, e: self.func( 518 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 519 ), 520 exp.JSONKeys: rename_func("OBJECT_KEYS"), 521 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 522 exp.JSONPathRoot: lambda *_: "", 523 exp.JSONValueArray: _json_extract_value_array_sql, 524 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 525 rename_func("EDITDISTANCE") 526 ), 527 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 528 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 529 exp.LogicalOr: rename_func("BOOLOR_AGG"), 530 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 531 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 532 exp.MakeInterval: no_make_interval_sql, 533 exp.Max: max_or_greatest, 534 exp.Min: min_or_least, 535 exp.NthValue: nth_value_from_sql, 536 exp.ParseJSON: lambda self, e: self.func( 537 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 538 ), 539 exp.ToBinary: lambda self, e: self.func( 540 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 541 ), 542 exp.ToBoolean: lambda self, e: self.func( 543 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 544 ), 545 exp.ToDouble: lambda self, e: self.func( 546 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 547 ), 548 exp.ToFile: lambda self, e: self.func( 549 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 550 ), 551 exp.JSONFormat: rename_func("TO_JSON"), 552 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 553 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 554 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 555 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 556 exp.RegexpExtract: _regexpextract_sql, 557 exp.RegexpExtractAll: _regexpextract_sql, 558 exp.RegexpILike: _regexpilike_sql, 559 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 560 exp.Select: transforms.preprocess( 561 [ 562 transforms.eliminate_window_clause, 563 transforms.eliminate_distinct_on, 564 transforms.explode_projection_to_unnest(), 565 transforms.eliminate_semi_and_anti_joins, 566 _transform_generate_date_array, 567 _qualify_unnested_columns, 568 _eliminate_dot_variant_lookup, 569 ] 570 ), 571 exp.SHA: rename_func("SHA1"), 572 exp.SHA1Digest: rename_func("SHA1_BINARY"), 573 exp.MD5Digest: rename_func("MD5_BINARY"), 574 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 575 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 576 exp.Hex: rename_func("HEX_ENCODE"), 577 exp.LowerHex: rename_func("TO_CHAR"), 578 exp.Skewness: rename_func("SKEW"), 579 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 580 exp.StartsWith: rename_func("STARTSWITH"), 581 exp.EndsWith: rename_func("ENDSWITH"), 582 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 583 exp.StrPosition: lambda self, e: strposition_sql( 584 self, e, func_name="CHARINDEX", supports_position=True 585 ), 586 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 587 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 588 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 589 exp.Stuff: rename_func("INSERT"), 590 exp.StPoint: rename_func("ST_MAKEPOINT"), 591 exp.TemporaryProperty: lambda _, e: ( 592 "SCOPED TEMPORARY" if e.args.get("scoped") else "TEMPORARY" 593 ), 594 exp.TimeAdd: date_delta_sql("TIMEADD"), 595 exp.TimeSlice: lambda self, e: self.func( 596 "TIME_SLICE", 597 e.this, 598 e.expression, 599 unit_to_str(e), 600 e.args.get("kind"), 601 ), 602 exp.Timestamp: no_timestamp_sql, 603 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 604 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 605 exp.TimestampTrunc: timestamptrunc_sql(), 606 exp.TimeStrToTime: timestrtotime_sql, 607 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 608 exp.ToArray: rename_func("TO_ARRAY"), 609 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 610 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 611 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 612 exp.TsOrDsToDate: lambda self, e: self.func( 613 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 614 ), 615 exp.TsOrDsToTime: lambda self, e: self.func( 616 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 617 ), 618 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 619 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 620 exp.Uuid: rename_func("UUID_STRING"), 621 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 622 exp.Booland: rename_func("BOOLAND"), 623 exp.Boolor: rename_func("BOOLOR"), 624 exp.WeekOfYear: rename_func("WEEKISO"), 625 exp.YearOfWeek: rename_func("YEAROFWEEK"), 626 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 627 exp.Xor: rename_func("BOOLXOR"), 628 exp.ByteLength: rename_func("OCTET_LENGTH"), 629 exp.Flatten: rename_func("ARRAY_FLATTEN"), 630 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 631 exp.SHA2Digest: lambda self, e: self.func( 632 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 633 ), 634 } 635 636 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 637 this = self.func("IDENTIFIER", expression.this) 638 if "expressions" in expression.args: 639 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 640 return self.func(this, *expression.expressions, normalize=False) 641 return this 642 643 SUPPORTED_JSON_PATH_PARTS = { 644 exp.JSONPathKey, 645 exp.JSONPathRoot, 646 exp.JSONPathSubscript, 647 } 648 649 TYPE_MAPPING = { 650 **generator.Generator.TYPE_MAPPING, 651 exp.DType.BIGDECIMAL: "DOUBLE", 652 exp.DType.JSON: "VARIANT", 653 exp.DType.NESTED: "OBJECT", 654 exp.DType.STRUCT: "OBJECT", 655 exp.DType.TEXT: "VARCHAR", 656 } 657 658 TOKEN_MAPPING = { 659 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 660 } 661 662 PROPERTIES_LOCATION = { 663 **generator.Generator.PROPERTIES_LOCATION, 664 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 665 exp.InteractiveProperty: exp.Properties.Location.POST_CREATE, 666 exp.LocationProperty: exp.Properties.Location.POST_WITH, 667 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 668 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 669 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 670 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 671 } 672 673 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 674 exp.Map, 675 exp.StarMap, 676 exp.Struct, 677 exp.VarMap, 678 } 679 680 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 681 682 WINDOW_FUNCS_REQUIRING_ORDER = ( 683 exp.CumeDist, 684 exp.DenseRank, 685 exp.FirstValue, 686 exp.LastValue, 687 exp.NthValue, 688 exp.Ntile, 689 exp.PercentRank, 690 exp.Rank, 691 exp.RowNumber, 692 ) 693 694 def with_properties(self, properties: exp.Properties) -> str: 695 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 696 697 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 698 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 699 values_as_table = False 700 701 return super().values_sql(expression, values_as_table=values_as_table) 702 703 def datatype_sql(self, expression: exp.DataType) -> str: 704 # Check if this is a FLOAT type nested inside a VECTOR type 705 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 706 # https://docs.snowflake.com/en/sql-reference/data-types-vector 707 if expression.is_type(exp.DType.DOUBLE): 708 parent = expression.parent 709 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 710 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 711 return "FLOAT" 712 713 expressions = expression.expressions 714 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 715 for field_type in expressions: 716 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 717 if isinstance(field_type, exp.DataType): 718 return "OBJECT" 719 if ( 720 isinstance(field_type, exp.ColumnDef) 721 and field_type.this 722 and field_type.this.is_string 723 ): 724 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 725 # converting 'foo' into an identifier, we also need to quote it because these 726 # keys are case-sensitive. For example: 727 # 728 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 729 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 730 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 731 732 return super().datatype_sql(expression) 733 734 def tonumber_sql(self, expression: exp.ToNumber) -> str: 735 precision = expression.args.get("precision") 736 scale = expression.args.get("scale") 737 738 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 739 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 740 741 if default_precision and default_scale: 742 precision = None 743 scale = None 744 elif default_scale: 745 scale = None 746 747 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 748 749 return self.func( 750 func_name, 751 expression.this, 752 expression.args.get("format"), 753 precision, 754 scale, 755 ) 756 757 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 758 milli = expression.args.get("milli") 759 if milli is not None: 760 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 761 expression.set("nano", milli_to_nano) 762 763 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 764 765 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 766 if expression.is_type(exp.DType.GEOGRAPHY): 767 return self.func("TO_GEOGRAPHY", expression.this) 768 if expression.is_type(exp.DType.GEOMETRY): 769 return self.func("TO_GEOMETRY", expression.this) 770 771 return super().cast_sql(expression, safe_prefix=safe_prefix) 772 773 def trycast_sql(self, expression: exp.TryCast) -> str: 774 value = expression.this 775 776 if value.type is None: 777 from sqlglot.optimizer.annotate_types import annotate_types 778 779 value = annotate_types(value, dialect=self.dialect) 780 781 # Snowflake requires that TRY_CAST's value be a string 782 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 783 # if we can deduce that the value is a string, then we can generate TRY_CAST 784 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 785 return super().trycast_sql(expression) 786 787 return self.cast_sql(expression) 788 789 def log_sql(self, expression: exp.Log) -> str: 790 if not expression.expression: 791 return self.func("LN", expression.this) 792 793 return super().log_sql(expression) 794 795 def greatest_sql(self, expression: exp.Greatest) -> str: 796 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 797 return self.func(name, expression.this, *expression.expressions) 798 799 def least_sql(self, expression: exp.Least) -> str: 800 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 801 return self.func(name, expression.this, *expression.expressions) 802 803 def generator_sql(self, expression: exp.Generator) -> str: 804 args = [] 805 rowcount = expression.args.get("rowcount") 806 timelimit = expression.args.get("timelimit") 807 808 if rowcount: 809 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 810 if timelimit: 811 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 812 813 return self.func("GENERATOR", *args) 814 815 def unnest_sql(self, expression: exp.Unnest) -> str: 816 unnest_alias = expression.args.get("alias") 817 offset = expression.args.get("offset") 818 819 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 820 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 821 822 columns = [ 823 exp.to_identifier("seq"), 824 exp.to_identifier("key"), 825 exp.to_identifier("path"), 826 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 827 value, 828 exp.to_identifier("this"), 829 ] 830 831 if unnest_alias: 832 unnest_alias.set("columns", columns) 833 else: 834 unnest_alias = exp.TableAlias(this="_u", columns=columns) 835 836 table_input = self.sql(expression.expressions[0]) 837 if not table_input.startswith("INPUT =>"): 838 table_input = f"INPUT => {table_input}" 839 840 expression_parent = expression.parent 841 842 explode = ( 843 f"FLATTEN({table_input})" 844 if isinstance(expression_parent, exp.Lateral) 845 else f"TABLE(FLATTEN({table_input}))" 846 ) 847 alias = self.sql(unnest_alias) 848 alias = f" AS {alias}" if alias else "" 849 value = ( 850 "" 851 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 852 else f"{value} FROM " 853 ) 854 855 return f"{value}{explode}{alias}" 856 857 def undrop_sql(self, expression: exp.Undrop) -> str: 858 this = self.sql(expression, "this") 859 kind = expression.kind 860 rename = self.sql(expression, "rename") 861 rename = f" RENAME TO {rename}" if rename else "" 862 return f"UNDROP {kind} {this}{rename}" 863 864 def show_sql(self, expression: exp.Show) -> str: 865 terse = "TERSE " if expression.args.get("terse") else "" 866 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 867 history = " HISTORY" if expression.args.get("history") else "" 868 like = self.sql(expression, "like") 869 like = f" LIKE {like}" if like else "" 870 871 scope = self.sql(expression, "scope") 872 scope = f" {scope}" if scope else "" 873 874 scope_kind = self.sql(expression, "scope_kind") 875 if scope_kind: 876 scope_kind = f" IN {scope_kind}" 877 878 starts_with = self.sql(expression, "starts_with") 879 if starts_with: 880 starts_with = f" STARTS WITH {starts_with}" 881 882 limit = self.sql(expression, "limit") 883 884 from_ = self.sql(expression, "from_") 885 if from_: 886 from_ = f" FROM {from_}" 887 888 privileges = self.expressions(expression, key="privileges", flat=True) 889 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 890 891 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 892 893 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 894 if not expression.this: 895 return "ROW ACCESS" 896 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 897 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 898 899 def describe_sql(self, expression: exp.Describe) -> str: 900 kind_value = expression.args.get("kind") or "TABLE" 901 902 properties = expression.args.get("properties") 903 if properties: 904 qualifier = self.expressions(properties, sep=" ") 905 kind = f" {qualifier} {kind_value}" 906 else: 907 kind = f" {kind_value}" 908 909 this = f" {self.sql(expression, 'this')}" 910 expressions = self.expressions(expression, flat=True) 911 expressions = f" {expressions}" if expressions else "" 912 return f"DESCRIBE{kind}{this}{expressions}" 913 914 def generatedasidentitycolumnconstraint_sql( 915 self, expression: exp.GeneratedAsIdentityColumnConstraint 916 ) -> str: 917 start = expression.args.get("start") 918 start = f" START {start}" if start else "" 919 increment = expression.args.get("increment") 920 increment = f" INCREMENT {increment}" if increment else "" 921 922 order = expression.args.get("order") 923 if order is not None: 924 order_clause = " ORDER" if order else " NOORDER" 925 else: 926 order_clause = "" 927 928 return f"AUTOINCREMENT{start}{increment}{order_clause}" 929 930 def struct_sql(self, expression: exp.Struct) -> str: 931 if len(expression.expressions) == 1: 932 arg = expression.expressions[0] 933 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 934 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 935 return f"{{{self.sql(expression.expressions[0])}}}" 936 937 keys = [] 938 values = [] 939 940 for i, e in enumerate(expression.expressions): 941 if isinstance(e, exp.PropertyEQ): 942 keys.append( 943 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 944 ) 945 values.append(e.expression) 946 else: 947 keys.append(exp.Literal.string(f"_{i}")) 948 values.append(e) 949 950 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 951 952 @unsupported_args("weight", "accuracy") 953 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 954 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 955 956 def alterset_sql(self, expression: exp.AlterSet) -> str: 957 exprs = self.expressions(expression, flat=True) 958 exprs = f" {exprs}" if exprs else "" 959 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 960 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 961 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 962 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 963 tag = self.expressions(expression, key="tag", flat=True) 964 tag = f" TAG {tag}" if tag else "" 965 966 return f"SET{exprs}{file_format}{copy_options}{tag}" 967 968 def strtotime_sql(self, expression: exp.StrToTime): 969 # target_type is stored as a DataType instance 970 target_type = expression.args.get("target_type") 971 972 # Get the type enum from DataType instance or from type annotation 973 if isinstance(target_type, exp.DataType): 974 type_enum = target_type.this 975 elif expression.type: 976 type_enum = expression.type.this 977 else: 978 type_enum = exp.DType.TIMESTAMP 979 980 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 981 982 return self.func( 983 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 984 expression.this, 985 self.format_time(expression), 986 ) 987 988 def timestampsub_sql(self, expression: exp.TimestampSub): 989 return self.sql( 990 exp.TimestampAdd( 991 this=expression.this, 992 expression=expression.expression * -1, 993 unit=expression.unit, 994 ) 995 ) 996 997 def jsonextract_sql(self, expression: exp.JSONExtract): 998 this = expression.this 999 1000 # JSON strings are valid coming from other dialects such as BQ so 1001 # for these cases we PARSE_JSON preemptively 1002 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 1003 "requires_json" 1004 ): 1005 this = exp.ParseJSON(this=this) 1006 1007 return self.func( 1008 "GET_PATH", 1009 this, 1010 expression.expression, 1011 ) 1012 1013 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 1014 this = expression.this 1015 if this.is_string: 1016 this = exp.cast(this, exp.DType.TIMESTAMP) 1017 1018 return self.func("TO_CHAR", this, self.format_time(expression)) 1019 1020 def datesub_sql(self, expression: exp.DateSub) -> str: 1021 value = expression.expression 1022 if value: 1023 value.replace(value * (-1)) 1024 else: 1025 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1026 1027 return date_delta_sql("DATEADD")(self, expression) 1028 1029 def select_sql(self, expression: exp.Select) -> str: 1030 limit = expression.args.get("limit") 1031 offset = expression.args.get("offset") 1032 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1033 expression.limit(exp.Null(), copy=False) 1034 return super().select_sql(expression) 1035 1036 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1037 is_materialized = expression.find(exp.MaterializedProperty) 1038 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1039 1040 if expression.kind == "VIEW" and is_materialized and grants_property: 1041 # Materialized views require COPY/IGNORE GRANTS before the column list, 1042 # whereas normal views use the default POST_SCHEMA location. 1043 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1044 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1045 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1046 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1047 1048 this_name = self.sql(expression.this, "this") 1049 grants = self.sql(grants_property) 1050 this_schema = self.schema_columns_sql(expression.this) 1051 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1052 1053 return f"{this_name}{self.sep()}{grants}{this_schema}" 1054 1055 return super().createable_sql(expression, locations) 1056 1057 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1058 this = expression.this 1059 1060 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1061 # and add it later as part of the WITHIN GROUP clause 1062 order = this if isinstance(this, exp.Order) else None 1063 if order: 1064 expression.set("this", order.this.pop()) 1065 1066 expr_sql = super().arrayagg_sql(expression) 1067 1068 if order: 1069 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1070 1071 return expr_sql 1072 1073 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1074 if expression.args.get("check_null"): 1075 return self.func("ARRAY_DISTINCT", expression.this) 1076 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1077 1078 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1079 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1080 1081 def array_sql(self, expression: exp.Array) -> str: 1082 expressions = expression.expressions 1083 1084 first_expr = seq_get(expressions, 0) 1085 if isinstance(first_expr, exp.Select): 1086 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1087 if first_expr.text("kind").upper() == "STRUCT": 1088 object_construct_args = [] 1089 for expr in first_expr.expressions: 1090 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1091 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1092 name = expr.this if isinstance(expr, exp.Alias) else expr 1093 1094 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1095 1096 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1097 1098 first_expr.set("kind", None) 1099 first_expr.set("expressions", [array_agg]) 1100 1101 return self.sql(first_expr.subquery()) 1102 1103 return inline_array_sql(self, expression) 1104 1105 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1106 zone = self.sql(expression, "this") 1107 if not zone: 1108 return super().currentdate_sql(expression) 1109 1110 expr = exp.Cast( 1111 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1112 to=exp.DataType(this=exp.DType.DATE), 1113 ) 1114 return self.sql(expr) 1115 1116 def dot_sql(self, expression: exp.Dot) -> str: 1117 this = expression.this 1118 1119 if not this.type: 1120 from sqlglot.optimizer.annotate_types import annotate_types 1121 1122 this = annotate_types(this, dialect=self.dialect) 1123 1124 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1125 # Generate colon notation for the top level STRUCT 1126 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1127 1128 return super().dot_sql(expression) 1129 1130 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1131 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1132 1133 def format_sql(self, expression: exp.Format) -> str: 1134 if expression.args.get("is_fmt"): 1135 return super().format_sql(expression) 1136 1137 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1138 return self.func("TO_CHAR", expression.expressions[0]) 1139 1140 return self.function_fallback_sql(expression) 1141 1142 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1143 # Set part_index to 1 if missing 1144 if not expression.args.get("delimiter"): 1145 expression.set("delimiter", exp.Literal.string(" ")) 1146 1147 if not expression.args.get("part_index"): 1148 expression.set("part_index", exp.Literal.number(1)) 1149 1150 return rename_func("SPLIT_PART")(self, expression) 1151 1152 def uniform_sql(self, expression: exp.Uniform) -> str: 1153 gen = expression.args.get("gen") 1154 seed = expression.args.get("seed") 1155 1156 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1157 if seed: 1158 gen = exp.Rand(this=seed) 1159 1160 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1161 if not gen: 1162 gen = exp.Rand() 1163 1164 return self.func("UNIFORM", expression.this, expression.expression, gen) 1165 1166 def window_sql(self, expression: exp.Window) -> str: 1167 spec = expression.args.get("spec") 1168 this = expression.this 1169 1170 if ( 1171 ( 1172 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1173 or ( 1174 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1175 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1176 ) 1177 ) 1178 and spec 1179 and ( 1180 spec.text("kind").upper() == "ROWS" 1181 and spec.text("start").upper() == "UNBOUNDED" 1182 and spec.text("start_side").upper() == "PRECEDING" 1183 and spec.text("end").upper() == "UNBOUNDED" 1184 and spec.text("end_side").upper() == "FOLLOWING" 1185 ) 1186 ): 1187 # omit the default window from window ranking functions 1188 expression.set("spec", None) 1189 return super().window_sql(expression) 1190 1191 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1192 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1193 # accepts the value to aggregate as an argument: MODE(<expr>) 1194 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1195 order = expression.expression 1196 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1197 return self.sql(exp.Mode(this=order.expressions[0].this)) 1198 1199 return super().withingroup_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
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMax'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMin'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Array'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function array_concat_sql.<locals>._array_concat_sql>, <class 'sqlglot.expressions.array.ArrayAppend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayPrepend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayContains'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ArrayPosition'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ArrayIntersect'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySort'>: <function _array_sort_sql>, <class 'sqlglot.expressions.core.AtTimeZone'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.BitwiseOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseXor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseNot'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseLeftShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseRightShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentSchemas'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Localtime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Localtimestamp'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DatetimeAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DatetimeDiff'>: <function timestampdiff_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.string.Decrypt'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.DecryptRaw'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.DotProduct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Explode'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.Extract'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.Filter'>: <function no_filter_sql>, <class 'sqlglot.expressions.math.CosineDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.EuclideanDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.FromTimeZone'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.GenerateSeries'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.GetExtract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.If'>: <function if_sql.<locals>._if_sql>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONArray'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONExtractArray'>: <function _json_extract_value_array_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONKeys'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.JSONValueArray'>: <function _json_extract_value_array_sql>, <class 'sqlglot.expressions.string.Levenshtein'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Map'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.math.ManhattanDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.MakeInterval'>: <function no_make_interval_sql>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.aggregate.NthValue'>: <function nth_value_from_sql>, <class 'sqlglot.expressions.json.ParseJSON'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToBinary'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.ToBoolean'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToDouble'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToFile'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONFormat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.PercentileCont'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.aggregate.PercentileDisc'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.query.Pivot'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function _regexpextract_sql>, <class 'sqlglot.expressions.string.RegexpExtractAll'>: <function _regexpextract_sql>, <class 'sqlglot.expressions.string.RegexpILike'>: <function _regexpilike_sql>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5NumberLower64'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5NumberUpper64'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Hex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.LowerHex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Skewness'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StarMap'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StartsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.EndsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.Rand'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.StringToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StrtokToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Stuff'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StPoint'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimeAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimeSlice'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Timestamp'>: <function no_timestamp_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimestampDiff'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ToChar'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsToDate'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToTime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.Unhex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Uuid'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.Booland'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.Boolor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.WeekOfYear'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.YearOfWeek'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.YearOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ByteLength'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Flatten'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArrayConcatAgg'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function SnowflakeGenerator.<lambda>>}
636 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 637 this = self.func("IDENTIFIER", expression.this) 638 if "expressions" in expression.args: 639 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 640 return self.func(this, *expression.expressions, normalize=False) 641 return this
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathKey'>}
TYPE_MAPPING =
{<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'VARBINARY', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.BIGDECIMAL: 'BIGDECIMAL'>: 'DOUBLE', <DType.JSON: 'JSON'>: 'VARIANT', <DType.NESTED: 'NESTED'>: 'OBJECT', <DType.STRUCT: 'STRUCT'>: 'OBJECT', <DType.TEXT: 'TEXT'>: 'VARCHAR'}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>}
UNSUPPORTED_VALUES_EXPRESSIONS: ClassVar =
{<class 'sqlglot.expressions.array.Struct'>, <class 'sqlglot.expressions.array.Map'>, <class 'sqlglot.expressions.array.VarMap'>, <class 'sqlglot.expressions.array.StarMap'>}
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS =
(<class 'sqlglot.expressions.aggregate.ArrayAgg'>,)
WINDOW_FUNCS_REQUIRING_ORDER =
(<class 'sqlglot.expressions.aggregate.CumeDist'>, <class 'sqlglot.expressions.aggregate.DenseRank'>, <class 'sqlglot.expressions.aggregate.FirstValue'>, <class 'sqlglot.expressions.aggregate.LastValue'>, <class 'sqlglot.expressions.aggregate.NthValue'>, <class 'sqlglot.expressions.aggregate.Ntile'>, <class 'sqlglot.expressions.aggregate.PercentRank'>, <class 'sqlglot.expressions.aggregate.Rank'>, <class 'sqlglot.expressions.aggregate.RowNumber'>)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
703 def datatype_sql(self, expression: exp.DataType) -> str: 704 # Check if this is a FLOAT type nested inside a VECTOR type 705 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 706 # https://docs.snowflake.com/en/sql-reference/data-types-vector 707 if expression.is_type(exp.DType.DOUBLE): 708 parent = expression.parent 709 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 710 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 711 return "FLOAT" 712 713 expressions = expression.expressions 714 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 715 for field_type in expressions: 716 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 717 if isinstance(field_type, exp.DataType): 718 return "OBJECT" 719 if ( 720 isinstance(field_type, exp.ColumnDef) 721 and field_type.this 722 and field_type.this.is_string 723 ): 724 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 725 # converting 'foo' into an identifier, we also need to quote it because these 726 # keys are case-sensitive. For example: 727 # 728 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 729 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 730 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 731 732 return super().datatype_sql(expression)
734 def tonumber_sql(self, expression: exp.ToNumber) -> str: 735 precision = expression.args.get("precision") 736 scale = expression.args.get("scale") 737 738 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 739 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 740 741 if default_precision and default_scale: 742 precision = None 743 scale = None 744 elif default_scale: 745 scale = None 746 747 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 748 749 return self.func( 750 func_name, 751 expression.this, 752 expression.args.get("format"), 753 precision, 754 scale, 755 )
def
timestampfromparts_sql(self, expression: sqlglot.expressions.temporal.TimestampFromParts) -> str:
757 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 758 milli = expression.args.get("milli") 759 if milli is not None: 760 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 761 expression.set("nano", milli_to_nano) 762 763 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
765 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 766 if expression.is_type(exp.DType.GEOGRAPHY): 767 return self.func("TO_GEOGRAPHY", expression.this) 768 if expression.is_type(exp.DType.GEOMETRY): 769 return self.func("TO_GEOMETRY", expression.this) 770 771 return super().cast_sql(expression, safe_prefix=safe_prefix)
773 def trycast_sql(self, expression: exp.TryCast) -> str: 774 value = expression.this 775 776 if value.type is None: 777 from sqlglot.optimizer.annotate_types import annotate_types 778 779 value = annotate_types(value, dialect=self.dialect) 780 781 # Snowflake requires that TRY_CAST's value be a string 782 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 783 # if we can deduce that the value is a string, then we can generate TRY_CAST 784 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 785 return super().trycast_sql(expression) 786 787 return self.cast_sql(expression)
803 def generator_sql(self, expression: exp.Generator) -> str: 804 args = [] 805 rowcount = expression.args.get("rowcount") 806 timelimit = expression.args.get("timelimit") 807 808 if rowcount: 809 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 810 if timelimit: 811 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 812 813 return self.func("GENERATOR", *args)
815 def unnest_sql(self, expression: exp.Unnest) -> str: 816 unnest_alias = expression.args.get("alias") 817 offset = expression.args.get("offset") 818 819 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 820 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 821 822 columns = [ 823 exp.to_identifier("seq"), 824 exp.to_identifier("key"), 825 exp.to_identifier("path"), 826 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 827 value, 828 exp.to_identifier("this"), 829 ] 830 831 if unnest_alias: 832 unnest_alias.set("columns", columns) 833 else: 834 unnest_alias = exp.TableAlias(this="_u", columns=columns) 835 836 table_input = self.sql(expression.expressions[0]) 837 if not table_input.startswith("INPUT =>"): 838 table_input = f"INPUT => {table_input}" 839 840 expression_parent = expression.parent 841 842 explode = ( 843 f"FLATTEN({table_input})" 844 if isinstance(expression_parent, exp.Lateral) 845 else f"TABLE(FLATTEN({table_input}))" 846 ) 847 alias = self.sql(unnest_alias) 848 alias = f" AS {alias}" if alias else "" 849 value = ( 850 "" 851 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 852 else f"{value} FROM " 853 ) 854 855 return f"{value}{explode}{alias}"
864 def show_sql(self, expression: exp.Show) -> str: 865 terse = "TERSE " if expression.args.get("terse") else "" 866 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 867 history = " HISTORY" if expression.args.get("history") else "" 868 like = self.sql(expression, "like") 869 like = f" LIKE {like}" if like else "" 870 871 scope = self.sql(expression, "scope") 872 scope = f" {scope}" if scope else "" 873 874 scope_kind = self.sql(expression, "scope_kind") 875 if scope_kind: 876 scope_kind = f" IN {scope_kind}" 877 878 starts_with = self.sql(expression, "starts_with") 879 if starts_with: 880 starts_with = f" STARTS WITH {starts_with}" 881 882 limit = self.sql(expression, "limit") 883 884 from_ = self.sql(expression, "from_") 885 if from_: 886 from_ = f" FROM {from_}" 887 888 privileges = self.expressions(expression, key="privileges", flat=True) 889 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 890 891 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}"
def
rowaccessproperty_sql( self, expression: sqlglot.expressions.properties.RowAccessProperty) -> str:
899 def describe_sql(self, expression: exp.Describe) -> str: 900 kind_value = expression.args.get("kind") or "TABLE" 901 902 properties = expression.args.get("properties") 903 if properties: 904 qualifier = self.expressions(properties, sep=" ") 905 kind = f" {qualifier} {kind_value}" 906 else: 907 kind = f" {kind_value}" 908 909 this = f" {self.sql(expression, 'this')}" 910 expressions = self.expressions(expression, flat=True) 911 expressions = f" {expressions}" if expressions else "" 912 return f"DESCRIBE{kind}{this}{expressions}"
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint) -> str:
914 def generatedasidentitycolumnconstraint_sql( 915 self, expression: exp.GeneratedAsIdentityColumnConstraint 916 ) -> str: 917 start = expression.args.get("start") 918 start = f" START {start}" if start else "" 919 increment = expression.args.get("increment") 920 increment = f" INCREMENT {increment}" if increment else "" 921 922 order = expression.args.get("order") 923 if order is not None: 924 order_clause = " ORDER" if order else " NOORDER" 925 else: 926 order_clause = "" 927 928 return f"AUTOINCREMENT{start}{increment}{order_clause}"
930 def struct_sql(self, expression: exp.Struct) -> str: 931 if len(expression.expressions) == 1: 932 arg = expression.expressions[0] 933 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 934 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 935 return f"{{{self.sql(expression.expressions[0])}}}" 936 937 keys = [] 938 values = [] 939 940 for i, e in enumerate(expression.expressions): 941 if isinstance(e, exp.PropertyEQ): 942 keys.append( 943 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 944 ) 945 values.append(e.expression) 946 else: 947 keys.append(exp.Literal.string(f"_{i}")) 948 values.append(e) 949 950 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values)))
@unsupported_args('weight', 'accuracy')
def
approxquantile_sql(self, expression: sqlglot.expressions.aggregate.ApproxQuantile) -> str:
956 def alterset_sql(self, expression: exp.AlterSet) -> str: 957 exprs = self.expressions(expression, flat=True) 958 exprs = f" {exprs}" if exprs else "" 959 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 960 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 961 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 962 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 963 tag = self.expressions(expression, key="tag", flat=True) 964 tag = f" TAG {tag}" if tag else "" 965 966 return f"SET{exprs}{file_format}{copy_options}{tag}"
968 def strtotime_sql(self, expression: exp.StrToTime): 969 # target_type is stored as a DataType instance 970 target_type = expression.args.get("target_type") 971 972 # Get the type enum from DataType instance or from type annotation 973 if isinstance(target_type, exp.DataType): 974 type_enum = target_type.this 975 elif expression.type: 976 type_enum = expression.type.this 977 else: 978 type_enum = exp.DType.TIMESTAMP 979 980 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 981 982 return self.func( 983 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 984 expression.this, 985 self.format_time(expression), 986 )
997 def jsonextract_sql(self, expression: exp.JSONExtract): 998 this = expression.this 999 1000 # JSON strings are valid coming from other dialects such as BQ so 1001 # for these cases we PARSE_JSON preemptively 1002 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 1003 "requires_json" 1004 ): 1005 this = exp.ParseJSON(this=this) 1006 1007 return self.func( 1008 "GET_PATH", 1009 this, 1010 expression.expression, 1011 )
1020 def datesub_sql(self, expression: exp.DateSub) -> str: 1021 value = expression.expression 1022 if value: 1023 value.replace(value * (-1)) 1024 else: 1025 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1026 1027 return date_delta_sql("DATEADD")(self, expression)
1029 def select_sql(self, expression: exp.Select) -> str: 1030 limit = expression.args.get("limit") 1031 offset = expression.args.get("offset") 1032 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1033 expression.limit(exp.Null(), copy=False) 1034 return super().select_sql(expression)
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
1036 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1037 is_materialized = expression.find(exp.MaterializedProperty) 1038 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1039 1040 if expression.kind == "VIEW" and is_materialized and grants_property: 1041 # Materialized views require COPY/IGNORE GRANTS before the column list, 1042 # whereas normal views use the default POST_SCHEMA location. 1043 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1044 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1045 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1046 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1047 1048 this_name = self.sql(expression.this, "this") 1049 grants = self.sql(grants_property) 1050 this_schema = self.schema_columns_sql(expression.this) 1051 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1052 1053 return f"{this_name}{self.sep()}{grants}{this_schema}" 1054 1055 return super().createable_sql(expression, locations)
1057 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1058 this = expression.this 1059 1060 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1061 # and add it later as part of the WITHIN GROUP clause 1062 order = this if isinstance(this, exp.Order) else None 1063 if order: 1064 expression.set("this", order.this.pop()) 1065 1066 expr_sql = super().arrayagg_sql(expression) 1067 1068 if order: 1069 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1070 1071 return expr_sql
1081 def array_sql(self, expression: exp.Array) -> str: 1082 expressions = expression.expressions 1083 1084 first_expr = seq_get(expressions, 0) 1085 if isinstance(first_expr, exp.Select): 1086 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1087 if first_expr.text("kind").upper() == "STRUCT": 1088 object_construct_args = [] 1089 for expr in first_expr.expressions: 1090 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1091 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1092 name = expr.this if isinstance(expr, exp.Alias) else expr 1093 1094 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1095 1096 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1097 1098 first_expr.set("kind", None) 1099 first_expr.set("expressions", [array_agg]) 1100 1101 return self.sql(first_expr.subquery()) 1102 1103 return inline_array_sql(self, expression)
1105 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1106 zone = self.sql(expression, "this") 1107 if not zone: 1108 return super().currentdate_sql(expression) 1109 1110 expr = exp.Cast( 1111 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1112 to=exp.DataType(this=exp.DType.DATE), 1113 ) 1114 return self.sql(expr)
1116 def dot_sql(self, expression: exp.Dot) -> str: 1117 this = expression.this 1118 1119 if not this.type: 1120 from sqlglot.optimizer.annotate_types import annotate_types 1121 1122 this = annotate_types(this, dialect=self.dialect) 1123 1124 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1125 # Generate colon notation for the top level STRUCT 1126 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1127 1128 return super().dot_sql(expression)
1133 def format_sql(self, expression: exp.Format) -> str: 1134 if expression.args.get("is_fmt"): 1135 return super().format_sql(expression) 1136 1137 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1138 return self.func("TO_CHAR", expression.expressions[0]) 1139 1140 return self.function_fallback_sql(expression)
1142 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1143 # Set part_index to 1 if missing 1144 if not expression.args.get("delimiter"): 1145 expression.set("delimiter", exp.Literal.string(" ")) 1146 1147 if not expression.args.get("part_index"): 1148 expression.set("part_index", exp.Literal.number(1)) 1149 1150 return rename_func("SPLIT_PART")(self, expression)
1152 def uniform_sql(self, expression: exp.Uniform) -> str: 1153 gen = expression.args.get("gen") 1154 seed = expression.args.get("seed") 1155 1156 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1157 if seed: 1158 gen = exp.Rand(this=seed) 1159 1160 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1161 if not gen: 1162 gen = exp.Rand() 1163 1164 return self.func("UNIFORM", expression.this, expression.expression, gen)
1166 def window_sql(self, expression: exp.Window) -> str: 1167 spec = expression.args.get("spec") 1168 this = expression.this 1169 1170 if ( 1171 ( 1172 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1173 or ( 1174 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1175 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1176 ) 1177 ) 1178 and spec 1179 and ( 1180 spec.text("kind").upper() == "ROWS" 1181 and spec.text("start").upper() == "UNBOUNDED" 1182 and spec.text("start_side").upper() == "PRECEDING" 1183 and spec.text("end").upper() == "UNBOUNDED" 1184 and spec.text("end_side").upper() == "FOLLOWING" 1185 ) 1186 ): 1187 # omit the default window from window ranking functions 1188 expression.set("spec", None) 1189 return super().window_sql(expression)
1191 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1192 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1193 # accepts the value to aggregate as an argument: MODE(<expr>) 1194 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1195 order = expression.expression 1196 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1197 return self.sql(exp.Mode(this=order.expressions[0].this)) 1198 1199 return super().withingroup_sql(expression)
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- WINDOW_FUNCS_WITH_NULL_ORDERING
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- LOCKING_READS_SUPPORTED
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- SUPPORTS_MERGE_WHERE
- MERGE_SCHEMA_EVOLUTION_MIN_VERSION
- INTERVAL_ALLOWS_PLURAL_FORM
- AUTO_REFRESH_BARE_INTERVALS
- LIMIT_FETCH
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- SUPPORTS_NEAREST_JOIN
- MATCH_CONDITION_IN_ON
- QUERY_HINT_SEP
- SAFE_INT_DIVISION
- INT_DIV_OPERATOR
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- NVL2_SUPPORTED
- VALUES_AS_TABLE
- UNNEST_WITH_ORDINALITY
- SEMI_ANTI_JOIN_WITH_SIDE
- COMPUTED_COLUMN_WITH_TYPE
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_KEYWORDS
- TABLESAMPLE_WITH_METHOD
- TABLESAMPLE_SEED_KEYWORD
- HISTORICAL_DATA_POST_ALIAS
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- SUPPORTS_SINGLE_ARG_CONCAT
- LAST_DAY_SUPPORTS_DATE_PART
- SUPPORTS_TABLE_ALIAS_COLUMNS
- SUPPORTS_NAMED_CTE_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- PIVOT_ALIAS_WITH_AS
- SUPPORTS_SELECT_INTO
- SUPPORTS_OPTIMIZE
- SUPPORTS_EXECUTE_IMMEDIATE
- SUPPORTS_UNLOGGED_TABLES
- SUPPORTS_CREATE_TABLE_LIKE
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- SUPPORTS_ALTER_COLUMN_NULLABILITY
- SUPPORTS_ALTER_COLUMN_IF_EXISTS
- LIKE_PROPERTY_INSIDE_SCHEMA
- MULTI_ARG_DISTINCT
- JSON_TYPE_REQUIRED_FOR_EXTRACTION
- SUPPORTS_NESTED_JSON_SELECT
- JSON_PATH_BRACKETED_KEY_SUPPORTED
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- CAN_IMPLEMENT_ARRAY_ANY
- SUPPORTS_TO_NUMBER
- SUPPORTS_WINDOW_EXCLUDE
- SET_OP_MODIFIERS
- SET_OP_LIMITS
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_HAS_INTO_KEYWORD
- UNICODE_SUBSTITUTE
- HEX_FUNC
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- PAD_FILL_PATTERN_IS_REQUIRED
- SUPPORTS_UNIX_SECONDS
- ALTER_SET_WRAPPED
- PARSE_JSON_NAME
- VARIANCE_NAME
- VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
- ALTER_SET_TYPE
- ARRAY_SIZE_DIM_REQUIRED
- SUPPORTS_BETWEEN_FLAGS
- SUPPORTS_LIKE_QUANTIFIERS
- MATCH_AGAINST_TABLE_PREFIX
- SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
- DECLARE_DEFAULT_ASSIGNMENT
- UPDATE_STATEMENT_SUPPORTS_FROM
- STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
- SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
- UNSUPPORTED_TYPES
- TYPE_PARAM_SETTINGS
- TIME_PART_SINGULARS
- NAMED_PLACEHOLDER_TOKEN
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- PARAMETERIZABLE_TEXT_TYPES
- EXPRESSIONS_WITHOUT_NESTED_CTES
- 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
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- create_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- heredoc_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- bytestring_sql
- unicodestring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_param_bound_limiter
- directory_sql
- delete_sql
- drop_sql
- set_operation
- set_operations
- fetch_sql
- limitoptions_sql
- filter_sql
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- identifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- 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
- onconflict_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tableargument_sql
- tablefromrows_sql
- tablesample_sql
- pivot_sql
- version_sql
- tuple_sql
- update_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
- join_sql
- nearest_sql
- lambda_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
- after_limit_modifiers
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- prewhere_sql
- where_sql
- partition_by_sql
- partitionbyexcluding_sql
- windowspec_sql
- between_sql
- bracket_offset_expressions
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- dayofweek_sql
- extract_date_part
- extract_sql
- trim_sql
- convert_concat_args
- concat_sql
- concatws_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_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- pos_sql
- neg_sql
- not_sql
- alias_sql
- pivotalias_sql
- aliases_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
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- strtodate_sql
- parsedatetime_sql
- collate_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
- alter_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- replacecolumns_sql
- addpartition_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- havingmax_sql
- intdiv_sql
- dpipe_sql
- nullif_zero_divisor
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- nestedjsonselect_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- is_sql
- like_sql
- ilike_sql
- match_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- sub_sql
- jsoncast_sql
- try_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
- tsordstotime_sql
- tsordstotimestamp_sql
- tsordstodatetime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql
- dateadd_sql
- arrayinsert_sql
- arrayany_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
- parsejson_sql
- rand_sql
- changes_sql
- pad_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
- timeslice_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
- install_sql
- liststage_sql
- get_put_sql
- translatecharacters_sql
- decodecase_sql
- semanticview_sql
- getextract_sql
- datefromunixdate_sql
- space_sql
- buildproperty_sql
- refreshtriggerproperty_sql
- directorystage_sql
- uuid_sql
- initcap_sql
- localtime_sql
- localtimestamp_sql
- weekstart_name
- weekstart_sql
- datetrunc_sql
- chr_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