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 206 # To avoid generating all these default values, we set group to None if 207 # it's 0 (also default value) which doesn't trigger the following chain 208 if group and group.name == "0": 209 group = None 210 211 parameters = expression.args.get("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 orig_expression = expression.copy() 259 260 for unnest in unnests: 261 if not isinstance(unnest.parent, (exp.From, exp.Join)): 262 continue 263 264 # Try to infer column names produced by an unnest operator. This is only possible 265 # when we can peek into the (statically known) contents of the unnested value. 266 unnest_columns: set[str] = set() 267 for unnest_expr in unnest.expressions: 268 if not isinstance(unnest_expr, exp.Array): 269 continue 270 271 for array_expr in unnest_expr.expressions: 272 if not ( 273 isinstance(array_expr, exp.Struct) 274 and array_expr.expressions 275 and all( 276 isinstance(struct_expr, exp.PropertyEQ) 277 for struct_expr in array_expr.expressions 278 ) 279 ): 280 continue 281 282 unnest_columns.update( 283 struct_expr.this.name.lower() for struct_expr in array_expr.expressions 284 ) 285 break 286 287 if unnest_columns: 288 break 289 290 unnest_alias = unnest.args.get("alias") 291 if not unnest_alias: 292 alias_name = find_new_name(taken_source_names, "value") 293 taken_source_names.add(alias_name) 294 295 # Produce a `TableAlias` AST similar to what is produced for BigQuery. This 296 # will be corrected later, when we generate SQL for the `Unnest` AST node. 297 aliased_unnest = exp.alias_(unnest, None, table=[alias_name]) 298 scope.replace(unnest, aliased_unnest) 299 300 unnest_identifier = aliased_unnest.args["alias"].columns[0] 301 else: 302 alias_columns = getattr(unnest_alias, "columns", []) 303 unnest_identifier = unnest_alias.this or seq_get(alias_columns, 0) 304 305 if not isinstance(unnest_identifier, exp.Identifier): 306 return orig_expression 307 308 unnest_to_identifier[unnest] = unnest_identifier 309 column_source.update({c.lower(): unnest_identifier for c in unnest_columns}) 310 311 for column in scope.columns: 312 if column.table: 313 continue 314 315 table = column_source.get(column.name.lower()) 316 if ( 317 unnest_identifier 318 and not table 319 and len(scope.sources) == 1 320 and column.name.lower() != unnest_identifier.name.lower() 321 ): 322 unnest_ancestor = column.find_ancestor(exp.Unnest, exp.Select) 323 if isinstance(unnest_ancestor, exp.Unnest): 324 ancestor_identifier = unnest_to_identifier.get(unnest_ancestor) 325 if ( 326 ancestor_identifier 327 and ancestor_identifier.name.lower() == unnest_identifier.name.lower() 328 ): 329 continue 330 331 table = unnest_identifier 332 333 column.set("table", table and table.copy()) 334 335 return expression 336 337 338def _eliminate_dot_variant_lookup(expression: exp.Expr) -> exp.Expr: 339 if isinstance(expression, exp.Select): 340 # This transformation is used to facilitate transpilation of BigQuery `UNNEST` operations 341 # to Snowflake. It should not affect roundtrip because `Unnest` nodes cannot be produced 342 # by Snowflake's parser. 343 # 344 # Additionally, at the time of writing this, BigQuery is the only dialect that produces a 345 # `TableAlias` node that only fills `columns` and not `this`, due to `UNNEST_COLUMN_ONLY`. 346 unnest_aliases = set() 347 for unnest in find_all_in_scope(expression, exp.Unnest): 348 unnest_alias = unnest.args.get("alias") 349 if ( 350 isinstance(unnest_alias, exp.TableAlias) 351 and not unnest_alias.this 352 and len(unnest_alias.columns) == 1 353 ): 354 unnest_aliases.add(unnest_alias.columns[0].name) 355 356 if unnest_aliases: 357 for c in find_all_in_scope(expression, exp.Column): 358 if c.table in unnest_aliases: 359 bracket_lhs = c.args["table"] 360 bracket_rhs = exp.Literal.string(c.name) 361 bracket = exp.Bracket(this=bracket_lhs, expressions=[bracket_rhs]) 362 363 if c.parent is expression: 364 # Retain column projection names by using aliases 365 c.replace(exp.alias_(bracket, c.this.copy())) 366 else: 367 c.replace(bracket) 368 369 return expression 370 371 372class SnowflakeGenerator(generator.Generator): 373 BYTE_STRING_FUNCTION = "HEX_DECODE_BINARY" 374 SELECT_KINDS: tuple[str, ...] = () 375 PARAMETER_TOKEN = "$" 376 MATCHED_BY_SOURCE = False 377 SINGLE_STRING_INTERVAL = True 378 CAST_TO_INT_ROUNDS = True 379 JOIN_HINTS = False 380 TABLE_HINTS = False 381 QUERY_HINTS = False 382 SUPPORTS_TABLE_COPY = False 383 COLLATE_IS_FUNC = True 384 LIMIT_ONLY_LITERALS = True 385 JSON_KEY_VALUE_PAIR_SEP = "," 386 INSERT_OVERWRITE = " OVERWRITE INTO" 387 STRUCT_DELIMITER = ("(", ")") 388 COPY_PARAMS_ARE_WRAPPED = False 389 COPY_PARAMS_EQ_REQUIRED = True 390 STAR_EXCEPT = "EXCLUDE" 391 SUPPORTS_EXPLODING_PROJECTIONS = False 392 ARRAY_CONCAT_IS_VAR_LEN = False 393 SUPPORTS_CONVERT_TIMEZONE = True 394 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 395 SUPPORTS_MEDIAN = True 396 ARRAY_SIZE_NAME = "ARRAY_SIZE" 397 SUPPORTS_DECODE_CASE = True 398 399 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 400 401 IS_BOOL_ALLOWED = False 402 DIRECTED_JOINS = True 403 SUPPORTS_UESCAPE = False 404 TRY_SUPPORTED = False 405 406 TRANSFORMS = { 407 **generator.Generator.TRANSFORMS, 408 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 409 exp.ArgMax: rename_func("MAX_BY"), 410 exp.ArgMin: rename_func("MIN_BY"), 411 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 412 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 413 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 414 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 415 exp.ArrayContains: lambda self, e: self.func( 416 "ARRAY_CONTAINS", 417 e.expression 418 if e.args.get("ensure_variant") is False 419 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 420 e.this, 421 ), 422 exp.ArrayPosition: lambda self, e: self.func( 423 "ARRAY_POSITION", 424 e.expression, 425 e.this, 426 ), 427 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 428 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 429 exp.ArraySort: _array_sort_sql, 430 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 431 exp.BitwiseOr: rename_func("BITOR"), 432 exp.BitwiseXor: rename_func("BITXOR"), 433 exp.BitwiseAnd: rename_func("BITAND"), 434 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 435 exp.BitwiseOrAgg: rename_func("BITORAGG"), 436 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 437 exp.BitwiseNot: rename_func("BITNOT"), 438 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 439 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 440 exp.CurrentTimestamp: lambda self, e: ( 441 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 442 ), 443 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 444 exp.Localtime: lambda self, e: ( 445 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 446 ), 447 exp.Localtimestamp: lambda self, e: ( 448 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 449 ), 450 exp.DateAdd: date_delta_sql("DATEADD"), 451 exp.DateDiff: date_delta_sql("DATEDIFF"), 452 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 453 exp.DatetimeDiff: timestampdiff_sql, 454 exp.DateStrToDate: datestrtodate_sql, 455 exp.Decrypt: lambda self, e: self.func( 456 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 457 e.this, 458 e.args.get("passphrase"), 459 e.args.get("aad"), 460 e.args.get("encryption_method"), 461 ), 462 exp.DecryptRaw: lambda self, e: self.func( 463 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 464 e.this, 465 e.args.get("key"), 466 e.args.get("iv"), 467 e.args.get("aad"), 468 e.args.get("encryption_method"), 469 e.args.get("aead"), 470 ), 471 exp.DayOfMonth: rename_func("DAYOFMONTH"), 472 exp.DayOfWeek: rename_func("DAYOFWEEK"), 473 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 474 exp.DayOfYear: rename_func("DAYOFYEAR"), 475 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 476 exp.Explode: rename_func("FLATTEN"), 477 exp.Extract: lambda self, e: self.func( 478 "DATE_PART", map_date_part(e.this, self.dialect), e.expression 479 ), 480 exp.Filter: no_filter_sql, 481 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 482 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 483 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 484 exp.FileFormatProperty: lambda self, e: ( 485 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 486 ), 487 exp.FromTimeZone: lambda self, e: self.func( 488 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 489 ), 490 exp.GenerateSeries: lambda self, e: self.func( 491 "ARRAY_GENERATE_RANGE", 492 e.args["start"], 493 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 494 e.args.get("step"), 495 ), 496 exp.GetExtract: rename_func("GET"), 497 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 498 exp.If: if_sql(name="IFF", false_value="NULL"), 499 exp.JSONArray: lambda self, e: self.func( 500 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 501 ), 502 exp.JSONExtractArray: _json_extract_value_array_sql, 503 exp.JSONExtractScalar: lambda self, e: self.func( 504 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 505 ), 506 exp.JSONKeys: rename_func("OBJECT_KEYS"), 507 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 508 exp.JSONPathRoot: lambda *_: "", 509 exp.JSONValueArray: _json_extract_value_array_sql, 510 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 511 rename_func("EDITDISTANCE") 512 ), 513 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 514 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 515 exp.LogicalOr: rename_func("BOOLOR_AGG"), 516 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 517 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 518 exp.MakeInterval: no_make_interval_sql, 519 exp.Max: max_or_greatest, 520 exp.Min: min_or_least, 521 exp.NthValue: nth_value_from_sql, 522 exp.ParseJSON: lambda self, e: self.func( 523 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 524 ), 525 exp.ToBinary: lambda self, e: self.func( 526 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 527 ), 528 exp.ToBoolean: lambda self, e: self.func( 529 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 530 ), 531 exp.ToDouble: lambda self, e: self.func( 532 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 533 ), 534 exp.ToFile: lambda self, e: self.func( 535 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 536 ), 537 exp.JSONFormat: rename_func("TO_JSON"), 538 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 539 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 540 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 541 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 542 exp.RegexpExtract: _regexpextract_sql, 543 exp.RegexpExtractAll: _regexpextract_sql, 544 exp.RegexpILike: _regexpilike_sql, 545 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 546 exp.Select: transforms.preprocess( 547 [ 548 transforms.eliminate_window_clause, 549 transforms.eliminate_distinct_on, 550 transforms.explode_projection_to_unnest(), 551 transforms.eliminate_semi_and_anti_joins, 552 _transform_generate_date_array, 553 _qualify_unnested_columns, 554 _eliminate_dot_variant_lookup, 555 ] 556 ), 557 exp.SHA: rename_func("SHA1"), 558 exp.SHA1Digest: rename_func("SHA1_BINARY"), 559 exp.MD5Digest: rename_func("MD5_BINARY"), 560 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 561 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 562 exp.Hex: rename_func("HEX_ENCODE"), 563 exp.LowerHex: rename_func("TO_CHAR"), 564 exp.Skewness: rename_func("SKEW"), 565 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 566 exp.StartsWith: rename_func("STARTSWITH"), 567 exp.EndsWith: rename_func("ENDSWITH"), 568 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 569 exp.StrPosition: lambda self, e: strposition_sql( 570 self, e, func_name="CHARINDEX", supports_position=True 571 ), 572 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 573 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 574 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 575 exp.Stuff: rename_func("INSERT"), 576 exp.StPoint: rename_func("ST_MAKEPOINT"), 577 exp.TimeAdd: date_delta_sql("TIMEADD"), 578 exp.TimeSlice: lambda self, e: self.func( 579 "TIME_SLICE", 580 e.this, 581 e.expression, 582 unit_to_str(e), 583 e.args.get("kind"), 584 ), 585 exp.Timestamp: no_timestamp_sql, 586 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 587 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 588 exp.TimestampTrunc: timestamptrunc_sql(), 589 exp.TimeStrToTime: timestrtotime_sql, 590 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 591 exp.ToArray: rename_func("TO_ARRAY"), 592 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 593 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 594 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 595 exp.TsOrDsToDate: lambda self, e: self.func( 596 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 597 ), 598 exp.TsOrDsToTime: lambda self, e: self.func( 599 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 600 ), 601 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 602 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 603 exp.Uuid: rename_func("UUID_STRING"), 604 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 605 exp.Booland: rename_func("BOOLAND"), 606 exp.Boolor: rename_func("BOOLOR"), 607 exp.WeekOfYear: rename_func("WEEKISO"), 608 exp.YearOfWeek: rename_func("YEAROFWEEK"), 609 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 610 exp.Xor: rename_func("BOOLXOR"), 611 exp.ByteLength: rename_func("OCTET_LENGTH"), 612 exp.Flatten: rename_func("ARRAY_FLATTEN"), 613 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 614 exp.SHA2Digest: lambda self, e: self.func( 615 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 616 ), 617 } 618 619 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 620 this = self.func("IDENTIFIER", expression.this) 621 if "expressions" in expression.args: 622 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 623 return self.func(this, *expression.expressions, normalize=False) 624 return this 625 626 SUPPORTED_JSON_PATH_PARTS = { 627 exp.JSONPathKey, 628 exp.JSONPathRoot, 629 exp.JSONPathSubscript, 630 } 631 632 TYPE_MAPPING = { 633 **generator.Generator.TYPE_MAPPING, 634 exp.DType.BIGDECIMAL: "DOUBLE", 635 exp.DType.JSON: "VARIANT", 636 exp.DType.NESTED: "OBJECT", 637 exp.DType.STRUCT: "OBJECT", 638 exp.DType.TEXT: "VARCHAR", 639 } 640 641 TOKEN_MAPPING = { 642 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 643 } 644 645 PROPERTIES_LOCATION = { 646 **generator.Generator.PROPERTIES_LOCATION, 647 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 648 exp.LocationProperty: exp.Properties.Location.POST_WITH, 649 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 650 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 651 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 652 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 653 } 654 655 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 656 exp.Map, 657 exp.StarMap, 658 exp.Struct, 659 exp.VarMap, 660 } 661 662 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 663 664 def with_properties(self, properties: exp.Properties) -> str: 665 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 666 667 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 668 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 669 values_as_table = False 670 671 return super().values_sql(expression, values_as_table=values_as_table) 672 673 def datatype_sql(self, expression: exp.DataType) -> str: 674 # Check if this is a FLOAT type nested inside a VECTOR type 675 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 676 # https://docs.snowflake.com/en/sql-reference/data-types-vector 677 if expression.is_type(exp.DType.DOUBLE): 678 parent = expression.parent 679 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 680 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 681 return "FLOAT" 682 683 expressions = expression.expressions 684 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 685 for field_type in expressions: 686 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 687 if isinstance(field_type, exp.DataType): 688 return "OBJECT" 689 if ( 690 isinstance(field_type, exp.ColumnDef) 691 and field_type.this 692 and field_type.this.is_string 693 ): 694 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 695 # converting 'foo' into an identifier, we also need to quote it because these 696 # keys are case-sensitive. For example: 697 # 698 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 699 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 700 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 701 702 return super().datatype_sql(expression) 703 704 def tonumber_sql(self, expression: exp.ToNumber) -> str: 705 precision = expression.args.get("precision") 706 scale = expression.args.get("scale") 707 708 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 709 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 710 711 if default_precision and default_scale: 712 precision = None 713 scale = None 714 elif default_scale: 715 scale = None 716 717 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 718 719 return self.func( 720 func_name, 721 expression.this, 722 expression.args.get("format"), 723 precision, 724 scale, 725 ) 726 727 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 728 milli = expression.args.get("milli") 729 if milli is not None: 730 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 731 expression.set("nano", milli_to_nano) 732 733 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 734 735 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 736 if expression.is_type(exp.DType.GEOGRAPHY): 737 return self.func("TO_GEOGRAPHY", expression.this) 738 if expression.is_type(exp.DType.GEOMETRY): 739 return self.func("TO_GEOMETRY", expression.this) 740 741 return super().cast_sql(expression, safe_prefix=safe_prefix) 742 743 def trycast_sql(self, expression: exp.TryCast) -> str: 744 value = expression.this 745 746 if value.type is None: 747 from sqlglot.optimizer.annotate_types import annotate_types 748 749 value = annotate_types(value, dialect=self.dialect) 750 751 # Snowflake requires that TRY_CAST's value be a string 752 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 753 # if we can deduce that the value is a string, then we can generate TRY_CAST 754 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 755 return super().trycast_sql(expression) 756 757 return self.cast_sql(expression) 758 759 def log_sql(self, expression: exp.Log) -> str: 760 if not expression.expression: 761 return self.func("LN", expression.this) 762 763 return super().log_sql(expression) 764 765 def greatest_sql(self, expression: exp.Greatest) -> str: 766 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 767 return self.func(name, expression.this, *expression.expressions) 768 769 def least_sql(self, expression: exp.Least) -> str: 770 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 771 return self.func(name, expression.this, *expression.expressions) 772 773 def generator_sql(self, expression: exp.Generator) -> str: 774 args = [] 775 rowcount = expression.args.get("rowcount") 776 timelimit = expression.args.get("timelimit") 777 778 if rowcount: 779 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 780 if timelimit: 781 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 782 783 return self.func("GENERATOR", *args) 784 785 def unnest_sql(self, expression: exp.Unnest) -> str: 786 unnest_alias = expression.args.get("alias") 787 offset = expression.args.get("offset") 788 789 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 790 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 791 792 columns = [ 793 exp.to_identifier("seq"), 794 exp.to_identifier("key"), 795 exp.to_identifier("path"), 796 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 797 value, 798 exp.to_identifier("this"), 799 ] 800 801 if unnest_alias: 802 unnest_alias.set("columns", columns) 803 else: 804 unnest_alias = exp.TableAlias(this="_u", columns=columns) 805 806 table_input = self.sql(expression.expressions[0]) 807 if not table_input.startswith("INPUT =>"): 808 table_input = f"INPUT => {table_input}" 809 810 expression_parent = expression.parent 811 812 explode = ( 813 f"FLATTEN({table_input})" 814 if isinstance(expression_parent, exp.Lateral) 815 else f"TABLE(FLATTEN({table_input}))" 816 ) 817 alias = self.sql(unnest_alias) 818 alias = f" AS {alias}" if alias else "" 819 value = ( 820 "" 821 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 822 else f"{value} FROM " 823 ) 824 825 return f"{value}{explode}{alias}" 826 827 def undrop_sql(self, expression: exp.Undrop) -> str: 828 this = self.sql(expression, "this") 829 kind = expression.kind 830 rename = self.sql(expression, "rename") 831 rename = f" RENAME TO {rename}" if rename else "" 832 return f"UNDROP {kind} {this}{rename}" 833 834 def show_sql(self, expression: exp.Show) -> str: 835 terse = "TERSE " if expression.args.get("terse") else "" 836 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 837 history = " HISTORY" if expression.args.get("history") else "" 838 like = self.sql(expression, "like") 839 like = f" LIKE {like}" if like else "" 840 841 scope = self.sql(expression, "scope") 842 scope = f" {scope}" if scope else "" 843 844 scope_kind = self.sql(expression, "scope_kind") 845 if scope_kind: 846 scope_kind = f" IN {scope_kind}" 847 848 starts_with = self.sql(expression, "starts_with") 849 if starts_with: 850 starts_with = f" STARTS WITH {starts_with}" 851 852 limit = self.sql(expression, "limit") 853 854 from_ = self.sql(expression, "from_") 855 if from_: 856 from_ = f" FROM {from_}" 857 858 privileges = self.expressions(expression, key="privileges", flat=True) 859 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 860 861 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 862 863 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 864 if not expression.this: 865 return "ROW ACCESS" 866 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 867 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 868 869 def describe_sql(self, expression: exp.Describe) -> str: 870 kind_value = expression.args.get("kind") or "TABLE" 871 872 properties = expression.args.get("properties") 873 if properties: 874 qualifier = self.expressions(properties, sep=" ") 875 kind = f" {qualifier} {kind_value}" 876 else: 877 kind = f" {kind_value}" 878 879 this = f" {self.sql(expression, 'this')}" 880 expressions = self.expressions(expression, flat=True) 881 expressions = f" {expressions}" if expressions else "" 882 return f"DESCRIBE{kind}{this}{expressions}" 883 884 def generatedasidentitycolumnconstraint_sql( 885 self, expression: exp.GeneratedAsIdentityColumnConstraint 886 ) -> str: 887 start = expression.args.get("start") 888 start = f" START {start}" if start else "" 889 increment = expression.args.get("increment") 890 increment = f" INCREMENT {increment}" if increment else "" 891 892 order = expression.args.get("order") 893 if order is not None: 894 order_clause = " ORDER" if order else " NOORDER" 895 else: 896 order_clause = "" 897 898 return f"AUTOINCREMENT{start}{increment}{order_clause}" 899 900 def struct_sql(self, expression: exp.Struct) -> str: 901 if len(expression.expressions) == 1: 902 arg = expression.expressions[0] 903 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 904 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 905 return f"{{{self.sql(expression.expressions[0])}}}" 906 907 keys = [] 908 values = [] 909 910 for i, e in enumerate(expression.expressions): 911 if isinstance(e, exp.PropertyEQ): 912 keys.append( 913 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 914 ) 915 values.append(e.expression) 916 else: 917 keys.append(exp.Literal.string(f"_{i}")) 918 values.append(e) 919 920 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 921 922 @unsupported_args("weight", "accuracy") 923 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 924 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 925 926 def alterset_sql(self, expression: exp.AlterSet) -> str: 927 exprs = self.expressions(expression, flat=True) 928 exprs = f" {exprs}" if exprs else "" 929 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 930 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 931 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 932 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 933 tag = self.expressions(expression, key="tag", flat=True) 934 tag = f" TAG {tag}" if tag else "" 935 936 return f"SET{exprs}{file_format}{copy_options}{tag}" 937 938 def strtotime_sql(self, expression: exp.StrToTime): 939 # target_type is stored as a DataType instance 940 target_type = expression.args.get("target_type") 941 942 # Get the type enum from DataType instance or from type annotation 943 if isinstance(target_type, exp.DataType): 944 type_enum = target_type.this 945 elif expression.type: 946 type_enum = expression.type.this 947 else: 948 type_enum = exp.DType.TIMESTAMP 949 950 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 951 952 return self.func( 953 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 954 expression.this, 955 self.format_time(expression), 956 ) 957 958 def timestampsub_sql(self, expression: exp.TimestampSub): 959 return self.sql( 960 exp.TimestampAdd( 961 this=expression.this, 962 expression=expression.expression * -1, 963 unit=expression.unit, 964 ) 965 ) 966 967 def jsonextract_sql(self, expression: exp.JSONExtract): 968 this = expression.this 969 970 # JSON strings are valid coming from other dialects such as BQ so 971 # for these cases we PARSE_JSON preemptively 972 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 973 "requires_json" 974 ): 975 this = exp.ParseJSON(this=this) 976 977 return self.func( 978 "GET_PATH", 979 this, 980 expression.expression, 981 ) 982 983 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 984 this = expression.this 985 if this.is_string: 986 this = exp.cast(this, exp.DType.TIMESTAMP) 987 988 return self.func("TO_CHAR", this, self.format_time(expression)) 989 990 def datesub_sql(self, expression: exp.DateSub) -> str: 991 value = expression.expression 992 if value: 993 value.replace(value * (-1)) 994 else: 995 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 996 997 return date_delta_sql("DATEADD")(self, expression) 998 999 def select_sql(self, expression: exp.Select) -> str: 1000 limit = expression.args.get("limit") 1001 offset = expression.args.get("offset") 1002 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1003 expression.limit(exp.Null(), copy=False) 1004 return super().select_sql(expression) 1005 1006 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1007 is_materialized = expression.find(exp.MaterializedProperty) 1008 copy_grants_property = expression.find(exp.CopyGrantsProperty) 1009 1010 if expression.kind == "VIEW" and is_materialized and copy_grants_property: 1011 # For materialized views, COPY GRANTS is located *before* the columns list 1012 # This is in contrast to normal views where COPY GRANTS is located *after* the columns list 1013 # We default CopyGrantsProperty to POST_SCHEMA which means we need to output it POST_NAME if a materialized view is detected 1014 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1015 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1016 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1017 post_schema_properties.pop(post_schema_properties.index(copy_grants_property)) 1018 1019 this_name = self.sql(expression.this, "this") 1020 copy_grants = self.sql(copy_grants_property) 1021 this_schema = self.schema_columns_sql(expression.this) 1022 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1023 1024 return f"{this_name}{self.sep()}{copy_grants}{this_schema}" 1025 1026 return super().createable_sql(expression, locations) 1027 1028 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1029 this = expression.this 1030 1031 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1032 # and add it later as part of the WITHIN GROUP clause 1033 order = this if isinstance(this, exp.Order) else None 1034 if order: 1035 expression.set("this", order.this.pop()) 1036 1037 expr_sql = super().arrayagg_sql(expression) 1038 1039 if order: 1040 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1041 1042 return expr_sql 1043 1044 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1045 if expression.args.get("check_null"): 1046 return self.func("ARRAY_DISTINCT", expression.this) 1047 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1048 1049 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1050 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1051 1052 def array_sql(self, expression: exp.Array) -> str: 1053 expressions = expression.expressions 1054 1055 first_expr = seq_get(expressions, 0) 1056 if isinstance(first_expr, exp.Select): 1057 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1058 if first_expr.text("kind").upper() == "STRUCT": 1059 object_construct_args = [] 1060 for expr in first_expr.expressions: 1061 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1062 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1063 name = expr.this if isinstance(expr, exp.Alias) else expr 1064 1065 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1066 1067 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1068 1069 first_expr.set("kind", None) 1070 first_expr.set("expressions", [array_agg]) 1071 1072 return self.sql(first_expr.subquery()) 1073 1074 return inline_array_sql(self, expression) 1075 1076 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1077 zone = self.sql(expression, "this") 1078 if not zone: 1079 return super().currentdate_sql(expression) 1080 1081 expr = exp.Cast( 1082 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1083 to=exp.DataType(this=exp.DType.DATE), 1084 ) 1085 return self.sql(expr) 1086 1087 def dot_sql(self, expression: exp.Dot) -> str: 1088 this = expression.this 1089 1090 if not this.type: 1091 from sqlglot.optimizer.annotate_types import annotate_types 1092 1093 this = annotate_types(this, dialect=self.dialect) 1094 1095 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1096 # Generate colon notation for the top level STRUCT 1097 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1098 1099 return super().dot_sql(expression) 1100 1101 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1102 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1103 1104 def format_sql(self, expression: exp.Format) -> str: 1105 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1106 return self.func("TO_CHAR", expression.expressions[0]) 1107 1108 return self.function_fallback_sql(expression) 1109 1110 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1111 # Set part_index to 1 if missing 1112 if not expression.args.get("delimiter"): 1113 expression.set("delimiter", exp.Literal.string(" ")) 1114 1115 if not expression.args.get("part_index"): 1116 expression.set("part_index", exp.Literal.number(1)) 1117 1118 return rename_func("SPLIT_PART")(self, expression) 1119 1120 def uniform_sql(self, expression: exp.Uniform) -> str: 1121 gen = expression.args.get("gen") 1122 seed = expression.args.get("seed") 1123 1124 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1125 if seed: 1126 gen = exp.Rand(this=seed) 1127 1128 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1129 if not gen: 1130 gen = exp.Rand() 1131 1132 return self.func("UNIFORM", expression.this, expression.expression, gen) 1133 1134 def window_sql(self, expression: exp.Window) -> str: 1135 spec = expression.args.get("spec") 1136 this = expression.this 1137 1138 if ( 1139 ( 1140 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1141 or ( 1142 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1143 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1144 ) 1145 ) 1146 and spec 1147 and ( 1148 spec.text("kind").upper() == "ROWS" 1149 and spec.text("start").upper() == "UNBOUNDED" 1150 and spec.text("start_side").upper() == "PRECEDING" 1151 and spec.text("end").upper() == "UNBOUNDED" 1152 and spec.text("end_side").upper() == "FOLLOWING" 1153 ) 1154 ): 1155 # omit the default window from window ranking functions 1156 expression.set("spec", None) 1157 return super().window_sql(expression) 1158 1159 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1160 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1161 # accepts the value to aggregate as an argument: MODE(<expr>) 1162 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1163 order = expression.expression 1164 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1165 return self.sql(exp.Mode(this=order.expressions[0].this)) 1166 1167 return super().withingroup_sql(expression)
373class SnowflakeGenerator(generator.Generator): 374 BYTE_STRING_FUNCTION = "HEX_DECODE_BINARY" 375 SELECT_KINDS: tuple[str, ...] = () 376 PARAMETER_TOKEN = "$" 377 MATCHED_BY_SOURCE = False 378 SINGLE_STRING_INTERVAL = True 379 CAST_TO_INT_ROUNDS = True 380 JOIN_HINTS = False 381 TABLE_HINTS = False 382 QUERY_HINTS = False 383 SUPPORTS_TABLE_COPY = False 384 COLLATE_IS_FUNC = True 385 LIMIT_ONLY_LITERALS = True 386 JSON_KEY_VALUE_PAIR_SEP = "," 387 INSERT_OVERWRITE = " OVERWRITE INTO" 388 STRUCT_DELIMITER = ("(", ")") 389 COPY_PARAMS_ARE_WRAPPED = False 390 COPY_PARAMS_EQ_REQUIRED = True 391 STAR_EXCEPT = "EXCLUDE" 392 SUPPORTS_EXPLODING_PROJECTIONS = False 393 ARRAY_CONCAT_IS_VAR_LEN = False 394 SUPPORTS_CONVERT_TIMEZONE = True 395 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 396 SUPPORTS_MEDIAN = True 397 ARRAY_SIZE_NAME = "ARRAY_SIZE" 398 SUPPORTS_DECODE_CASE = True 399 400 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 401 402 IS_BOOL_ALLOWED = False 403 DIRECTED_JOINS = True 404 SUPPORTS_UESCAPE = False 405 TRY_SUPPORTED = False 406 407 TRANSFORMS = { 408 **generator.Generator.TRANSFORMS, 409 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 410 exp.ArgMax: rename_func("MAX_BY"), 411 exp.ArgMin: rename_func("MIN_BY"), 412 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 413 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 414 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 415 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 416 exp.ArrayContains: lambda self, e: self.func( 417 "ARRAY_CONTAINS", 418 e.expression 419 if e.args.get("ensure_variant") is False 420 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 421 e.this, 422 ), 423 exp.ArrayPosition: lambda self, e: self.func( 424 "ARRAY_POSITION", 425 e.expression, 426 e.this, 427 ), 428 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 429 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 430 exp.ArraySort: _array_sort_sql, 431 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 432 exp.BitwiseOr: rename_func("BITOR"), 433 exp.BitwiseXor: rename_func("BITXOR"), 434 exp.BitwiseAnd: rename_func("BITAND"), 435 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 436 exp.BitwiseOrAgg: rename_func("BITORAGG"), 437 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 438 exp.BitwiseNot: rename_func("BITNOT"), 439 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 440 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 441 exp.CurrentTimestamp: lambda self, e: ( 442 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 443 ), 444 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 445 exp.Localtime: lambda self, e: ( 446 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 447 ), 448 exp.Localtimestamp: lambda self, e: ( 449 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 450 ), 451 exp.DateAdd: date_delta_sql("DATEADD"), 452 exp.DateDiff: date_delta_sql("DATEDIFF"), 453 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 454 exp.DatetimeDiff: timestampdiff_sql, 455 exp.DateStrToDate: datestrtodate_sql, 456 exp.Decrypt: lambda self, e: self.func( 457 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 458 e.this, 459 e.args.get("passphrase"), 460 e.args.get("aad"), 461 e.args.get("encryption_method"), 462 ), 463 exp.DecryptRaw: lambda self, e: self.func( 464 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 465 e.this, 466 e.args.get("key"), 467 e.args.get("iv"), 468 e.args.get("aad"), 469 e.args.get("encryption_method"), 470 e.args.get("aead"), 471 ), 472 exp.DayOfMonth: rename_func("DAYOFMONTH"), 473 exp.DayOfWeek: rename_func("DAYOFWEEK"), 474 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 475 exp.DayOfYear: rename_func("DAYOFYEAR"), 476 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 477 exp.Explode: rename_func("FLATTEN"), 478 exp.Extract: lambda self, e: self.func( 479 "DATE_PART", map_date_part(e.this, self.dialect), e.expression 480 ), 481 exp.Filter: no_filter_sql, 482 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 483 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 484 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 485 exp.FileFormatProperty: lambda self, e: ( 486 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 487 ), 488 exp.FromTimeZone: lambda self, e: self.func( 489 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 490 ), 491 exp.GenerateSeries: lambda self, e: self.func( 492 "ARRAY_GENERATE_RANGE", 493 e.args["start"], 494 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 495 e.args.get("step"), 496 ), 497 exp.GetExtract: rename_func("GET"), 498 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 499 exp.If: if_sql(name="IFF", false_value="NULL"), 500 exp.JSONArray: lambda self, e: self.func( 501 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 502 ), 503 exp.JSONExtractArray: _json_extract_value_array_sql, 504 exp.JSONExtractScalar: lambda self, e: self.func( 505 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 506 ), 507 exp.JSONKeys: rename_func("OBJECT_KEYS"), 508 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 509 exp.JSONPathRoot: lambda *_: "", 510 exp.JSONValueArray: _json_extract_value_array_sql, 511 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 512 rename_func("EDITDISTANCE") 513 ), 514 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 515 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 516 exp.LogicalOr: rename_func("BOOLOR_AGG"), 517 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 518 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 519 exp.MakeInterval: no_make_interval_sql, 520 exp.Max: max_or_greatest, 521 exp.Min: min_or_least, 522 exp.NthValue: nth_value_from_sql, 523 exp.ParseJSON: lambda self, e: self.func( 524 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 525 ), 526 exp.ToBinary: lambda self, e: self.func( 527 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 528 ), 529 exp.ToBoolean: lambda self, e: self.func( 530 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 531 ), 532 exp.ToDouble: lambda self, e: self.func( 533 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 534 ), 535 exp.ToFile: lambda self, e: self.func( 536 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 537 ), 538 exp.JSONFormat: rename_func("TO_JSON"), 539 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 540 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 541 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 542 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 543 exp.RegexpExtract: _regexpextract_sql, 544 exp.RegexpExtractAll: _regexpextract_sql, 545 exp.RegexpILike: _regexpilike_sql, 546 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 547 exp.Select: transforms.preprocess( 548 [ 549 transforms.eliminate_window_clause, 550 transforms.eliminate_distinct_on, 551 transforms.explode_projection_to_unnest(), 552 transforms.eliminate_semi_and_anti_joins, 553 _transform_generate_date_array, 554 _qualify_unnested_columns, 555 _eliminate_dot_variant_lookup, 556 ] 557 ), 558 exp.SHA: rename_func("SHA1"), 559 exp.SHA1Digest: rename_func("SHA1_BINARY"), 560 exp.MD5Digest: rename_func("MD5_BINARY"), 561 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 562 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 563 exp.Hex: rename_func("HEX_ENCODE"), 564 exp.LowerHex: rename_func("TO_CHAR"), 565 exp.Skewness: rename_func("SKEW"), 566 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 567 exp.StartsWith: rename_func("STARTSWITH"), 568 exp.EndsWith: rename_func("ENDSWITH"), 569 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 570 exp.StrPosition: lambda self, e: strposition_sql( 571 self, e, func_name="CHARINDEX", supports_position=True 572 ), 573 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 574 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 575 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 576 exp.Stuff: rename_func("INSERT"), 577 exp.StPoint: rename_func("ST_MAKEPOINT"), 578 exp.TimeAdd: date_delta_sql("TIMEADD"), 579 exp.TimeSlice: lambda self, e: self.func( 580 "TIME_SLICE", 581 e.this, 582 e.expression, 583 unit_to_str(e), 584 e.args.get("kind"), 585 ), 586 exp.Timestamp: no_timestamp_sql, 587 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 588 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 589 exp.TimestampTrunc: timestamptrunc_sql(), 590 exp.TimeStrToTime: timestrtotime_sql, 591 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 592 exp.ToArray: rename_func("TO_ARRAY"), 593 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 594 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 595 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 596 exp.TsOrDsToDate: lambda self, e: self.func( 597 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 598 ), 599 exp.TsOrDsToTime: lambda self, e: self.func( 600 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 601 ), 602 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 603 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 604 exp.Uuid: rename_func("UUID_STRING"), 605 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 606 exp.Booland: rename_func("BOOLAND"), 607 exp.Boolor: rename_func("BOOLOR"), 608 exp.WeekOfYear: rename_func("WEEKISO"), 609 exp.YearOfWeek: rename_func("YEAROFWEEK"), 610 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 611 exp.Xor: rename_func("BOOLXOR"), 612 exp.ByteLength: rename_func("OCTET_LENGTH"), 613 exp.Flatten: rename_func("ARRAY_FLATTEN"), 614 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 615 exp.SHA2Digest: lambda self, e: self.func( 616 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 617 ), 618 } 619 620 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 621 this = self.func("IDENTIFIER", expression.this) 622 if "expressions" in expression.args: 623 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 624 return self.func(this, *expression.expressions, normalize=False) 625 return this 626 627 SUPPORTED_JSON_PATH_PARTS = { 628 exp.JSONPathKey, 629 exp.JSONPathRoot, 630 exp.JSONPathSubscript, 631 } 632 633 TYPE_MAPPING = { 634 **generator.Generator.TYPE_MAPPING, 635 exp.DType.BIGDECIMAL: "DOUBLE", 636 exp.DType.JSON: "VARIANT", 637 exp.DType.NESTED: "OBJECT", 638 exp.DType.STRUCT: "OBJECT", 639 exp.DType.TEXT: "VARCHAR", 640 } 641 642 TOKEN_MAPPING = { 643 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 644 } 645 646 PROPERTIES_LOCATION = { 647 **generator.Generator.PROPERTIES_LOCATION, 648 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 649 exp.LocationProperty: exp.Properties.Location.POST_WITH, 650 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 651 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 652 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 653 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 654 } 655 656 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 657 exp.Map, 658 exp.StarMap, 659 exp.Struct, 660 exp.VarMap, 661 } 662 663 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 664 665 def with_properties(self, properties: exp.Properties) -> str: 666 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 667 668 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 669 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 670 values_as_table = False 671 672 return super().values_sql(expression, values_as_table=values_as_table) 673 674 def datatype_sql(self, expression: exp.DataType) -> str: 675 # Check if this is a FLOAT type nested inside a VECTOR type 676 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 677 # https://docs.snowflake.com/en/sql-reference/data-types-vector 678 if expression.is_type(exp.DType.DOUBLE): 679 parent = expression.parent 680 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 681 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 682 return "FLOAT" 683 684 expressions = expression.expressions 685 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 686 for field_type in expressions: 687 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 688 if isinstance(field_type, exp.DataType): 689 return "OBJECT" 690 if ( 691 isinstance(field_type, exp.ColumnDef) 692 and field_type.this 693 and field_type.this.is_string 694 ): 695 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 696 # converting 'foo' into an identifier, we also need to quote it because these 697 # keys are case-sensitive. For example: 698 # 699 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 700 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 701 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 702 703 return super().datatype_sql(expression) 704 705 def tonumber_sql(self, expression: exp.ToNumber) -> str: 706 precision = expression.args.get("precision") 707 scale = expression.args.get("scale") 708 709 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 710 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 711 712 if default_precision and default_scale: 713 precision = None 714 scale = None 715 elif default_scale: 716 scale = None 717 718 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 719 720 return self.func( 721 func_name, 722 expression.this, 723 expression.args.get("format"), 724 precision, 725 scale, 726 ) 727 728 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 729 milli = expression.args.get("milli") 730 if milli is not None: 731 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 732 expression.set("nano", milli_to_nano) 733 734 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 735 736 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 737 if expression.is_type(exp.DType.GEOGRAPHY): 738 return self.func("TO_GEOGRAPHY", expression.this) 739 if expression.is_type(exp.DType.GEOMETRY): 740 return self.func("TO_GEOMETRY", expression.this) 741 742 return super().cast_sql(expression, safe_prefix=safe_prefix) 743 744 def trycast_sql(self, expression: exp.TryCast) -> str: 745 value = expression.this 746 747 if value.type is None: 748 from sqlglot.optimizer.annotate_types import annotate_types 749 750 value = annotate_types(value, dialect=self.dialect) 751 752 # Snowflake requires that TRY_CAST's value be a string 753 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 754 # if we can deduce that the value is a string, then we can generate TRY_CAST 755 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 756 return super().trycast_sql(expression) 757 758 return self.cast_sql(expression) 759 760 def log_sql(self, expression: exp.Log) -> str: 761 if not expression.expression: 762 return self.func("LN", expression.this) 763 764 return super().log_sql(expression) 765 766 def greatest_sql(self, expression: exp.Greatest) -> str: 767 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 768 return self.func(name, expression.this, *expression.expressions) 769 770 def least_sql(self, expression: exp.Least) -> str: 771 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 772 return self.func(name, expression.this, *expression.expressions) 773 774 def generator_sql(self, expression: exp.Generator) -> str: 775 args = [] 776 rowcount = expression.args.get("rowcount") 777 timelimit = expression.args.get("timelimit") 778 779 if rowcount: 780 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 781 if timelimit: 782 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 783 784 return self.func("GENERATOR", *args) 785 786 def unnest_sql(self, expression: exp.Unnest) -> str: 787 unnest_alias = expression.args.get("alias") 788 offset = expression.args.get("offset") 789 790 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 791 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 792 793 columns = [ 794 exp.to_identifier("seq"), 795 exp.to_identifier("key"), 796 exp.to_identifier("path"), 797 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 798 value, 799 exp.to_identifier("this"), 800 ] 801 802 if unnest_alias: 803 unnest_alias.set("columns", columns) 804 else: 805 unnest_alias = exp.TableAlias(this="_u", columns=columns) 806 807 table_input = self.sql(expression.expressions[0]) 808 if not table_input.startswith("INPUT =>"): 809 table_input = f"INPUT => {table_input}" 810 811 expression_parent = expression.parent 812 813 explode = ( 814 f"FLATTEN({table_input})" 815 if isinstance(expression_parent, exp.Lateral) 816 else f"TABLE(FLATTEN({table_input}))" 817 ) 818 alias = self.sql(unnest_alias) 819 alias = f" AS {alias}" if alias else "" 820 value = ( 821 "" 822 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 823 else f"{value} FROM " 824 ) 825 826 return f"{value}{explode}{alias}" 827 828 def undrop_sql(self, expression: exp.Undrop) -> str: 829 this = self.sql(expression, "this") 830 kind = expression.kind 831 rename = self.sql(expression, "rename") 832 rename = f" RENAME TO {rename}" if rename else "" 833 return f"UNDROP {kind} {this}{rename}" 834 835 def show_sql(self, expression: exp.Show) -> str: 836 terse = "TERSE " if expression.args.get("terse") else "" 837 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 838 history = " HISTORY" if expression.args.get("history") else "" 839 like = self.sql(expression, "like") 840 like = f" LIKE {like}" if like else "" 841 842 scope = self.sql(expression, "scope") 843 scope = f" {scope}" if scope else "" 844 845 scope_kind = self.sql(expression, "scope_kind") 846 if scope_kind: 847 scope_kind = f" IN {scope_kind}" 848 849 starts_with = self.sql(expression, "starts_with") 850 if starts_with: 851 starts_with = f" STARTS WITH {starts_with}" 852 853 limit = self.sql(expression, "limit") 854 855 from_ = self.sql(expression, "from_") 856 if from_: 857 from_ = f" FROM {from_}" 858 859 privileges = self.expressions(expression, key="privileges", flat=True) 860 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 861 862 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 863 864 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 865 if not expression.this: 866 return "ROW ACCESS" 867 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 868 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 869 870 def describe_sql(self, expression: exp.Describe) -> str: 871 kind_value = expression.args.get("kind") or "TABLE" 872 873 properties = expression.args.get("properties") 874 if properties: 875 qualifier = self.expressions(properties, sep=" ") 876 kind = f" {qualifier} {kind_value}" 877 else: 878 kind = f" {kind_value}" 879 880 this = f" {self.sql(expression, 'this')}" 881 expressions = self.expressions(expression, flat=True) 882 expressions = f" {expressions}" if expressions else "" 883 return f"DESCRIBE{kind}{this}{expressions}" 884 885 def generatedasidentitycolumnconstraint_sql( 886 self, expression: exp.GeneratedAsIdentityColumnConstraint 887 ) -> str: 888 start = expression.args.get("start") 889 start = f" START {start}" if start else "" 890 increment = expression.args.get("increment") 891 increment = f" INCREMENT {increment}" if increment else "" 892 893 order = expression.args.get("order") 894 if order is not None: 895 order_clause = " ORDER" if order else " NOORDER" 896 else: 897 order_clause = "" 898 899 return f"AUTOINCREMENT{start}{increment}{order_clause}" 900 901 def struct_sql(self, expression: exp.Struct) -> str: 902 if len(expression.expressions) == 1: 903 arg = expression.expressions[0] 904 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 905 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 906 return f"{{{self.sql(expression.expressions[0])}}}" 907 908 keys = [] 909 values = [] 910 911 for i, e in enumerate(expression.expressions): 912 if isinstance(e, exp.PropertyEQ): 913 keys.append( 914 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 915 ) 916 values.append(e.expression) 917 else: 918 keys.append(exp.Literal.string(f"_{i}")) 919 values.append(e) 920 921 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 922 923 @unsupported_args("weight", "accuracy") 924 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 925 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 926 927 def alterset_sql(self, expression: exp.AlterSet) -> str: 928 exprs = self.expressions(expression, flat=True) 929 exprs = f" {exprs}" if exprs else "" 930 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 931 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 932 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 933 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 934 tag = self.expressions(expression, key="tag", flat=True) 935 tag = f" TAG {tag}" if tag else "" 936 937 return f"SET{exprs}{file_format}{copy_options}{tag}" 938 939 def strtotime_sql(self, expression: exp.StrToTime): 940 # target_type is stored as a DataType instance 941 target_type = expression.args.get("target_type") 942 943 # Get the type enum from DataType instance or from type annotation 944 if isinstance(target_type, exp.DataType): 945 type_enum = target_type.this 946 elif expression.type: 947 type_enum = expression.type.this 948 else: 949 type_enum = exp.DType.TIMESTAMP 950 951 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 952 953 return self.func( 954 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 955 expression.this, 956 self.format_time(expression), 957 ) 958 959 def timestampsub_sql(self, expression: exp.TimestampSub): 960 return self.sql( 961 exp.TimestampAdd( 962 this=expression.this, 963 expression=expression.expression * -1, 964 unit=expression.unit, 965 ) 966 ) 967 968 def jsonextract_sql(self, expression: exp.JSONExtract): 969 this = expression.this 970 971 # JSON strings are valid coming from other dialects such as BQ so 972 # for these cases we PARSE_JSON preemptively 973 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 974 "requires_json" 975 ): 976 this = exp.ParseJSON(this=this) 977 978 return self.func( 979 "GET_PATH", 980 this, 981 expression.expression, 982 ) 983 984 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 985 this = expression.this 986 if this.is_string: 987 this = exp.cast(this, exp.DType.TIMESTAMP) 988 989 return self.func("TO_CHAR", this, self.format_time(expression)) 990 991 def datesub_sql(self, expression: exp.DateSub) -> str: 992 value = expression.expression 993 if value: 994 value.replace(value * (-1)) 995 else: 996 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 997 998 return date_delta_sql("DATEADD")(self, expression) 999 1000 def select_sql(self, expression: exp.Select) -> str: 1001 limit = expression.args.get("limit") 1002 offset = expression.args.get("offset") 1003 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1004 expression.limit(exp.Null(), copy=False) 1005 return super().select_sql(expression) 1006 1007 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1008 is_materialized = expression.find(exp.MaterializedProperty) 1009 copy_grants_property = expression.find(exp.CopyGrantsProperty) 1010 1011 if expression.kind == "VIEW" and is_materialized and copy_grants_property: 1012 # For materialized views, COPY GRANTS is located *before* the columns list 1013 # This is in contrast to normal views where COPY GRANTS is located *after* the columns list 1014 # We default CopyGrantsProperty to POST_SCHEMA which means we need to output it POST_NAME if a materialized view is detected 1015 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1016 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1017 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1018 post_schema_properties.pop(post_schema_properties.index(copy_grants_property)) 1019 1020 this_name = self.sql(expression.this, "this") 1021 copy_grants = self.sql(copy_grants_property) 1022 this_schema = self.schema_columns_sql(expression.this) 1023 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1024 1025 return f"{this_name}{self.sep()}{copy_grants}{this_schema}" 1026 1027 return super().createable_sql(expression, locations) 1028 1029 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1030 this = expression.this 1031 1032 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1033 # and add it later as part of the WITHIN GROUP clause 1034 order = this if isinstance(this, exp.Order) else None 1035 if order: 1036 expression.set("this", order.this.pop()) 1037 1038 expr_sql = super().arrayagg_sql(expression) 1039 1040 if order: 1041 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1042 1043 return expr_sql 1044 1045 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1046 if expression.args.get("check_null"): 1047 return self.func("ARRAY_DISTINCT", expression.this) 1048 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1049 1050 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1051 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1052 1053 def array_sql(self, expression: exp.Array) -> str: 1054 expressions = expression.expressions 1055 1056 first_expr = seq_get(expressions, 0) 1057 if isinstance(first_expr, exp.Select): 1058 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1059 if first_expr.text("kind").upper() == "STRUCT": 1060 object_construct_args = [] 1061 for expr in first_expr.expressions: 1062 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1063 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1064 name = expr.this if isinstance(expr, exp.Alias) else expr 1065 1066 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1067 1068 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1069 1070 first_expr.set("kind", None) 1071 first_expr.set("expressions", [array_agg]) 1072 1073 return self.sql(first_expr.subquery()) 1074 1075 return inline_array_sql(self, expression) 1076 1077 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1078 zone = self.sql(expression, "this") 1079 if not zone: 1080 return super().currentdate_sql(expression) 1081 1082 expr = exp.Cast( 1083 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1084 to=exp.DataType(this=exp.DType.DATE), 1085 ) 1086 return self.sql(expr) 1087 1088 def dot_sql(self, expression: exp.Dot) -> str: 1089 this = expression.this 1090 1091 if not this.type: 1092 from sqlglot.optimizer.annotate_types import annotate_types 1093 1094 this = annotate_types(this, dialect=self.dialect) 1095 1096 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1097 # Generate colon notation for the top level STRUCT 1098 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1099 1100 return super().dot_sql(expression) 1101 1102 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1103 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1104 1105 def format_sql(self, expression: exp.Format) -> str: 1106 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1107 return self.func("TO_CHAR", expression.expressions[0]) 1108 1109 return self.function_fallback_sql(expression) 1110 1111 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1112 # Set part_index to 1 if missing 1113 if not expression.args.get("delimiter"): 1114 expression.set("delimiter", exp.Literal.string(" ")) 1115 1116 if not expression.args.get("part_index"): 1117 expression.set("part_index", exp.Literal.number(1)) 1118 1119 return rename_func("SPLIT_PART")(self, expression) 1120 1121 def uniform_sql(self, expression: exp.Uniform) -> str: 1122 gen = expression.args.get("gen") 1123 seed = expression.args.get("seed") 1124 1125 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1126 if seed: 1127 gen = exp.Rand(this=seed) 1128 1129 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1130 if not gen: 1131 gen = exp.Rand() 1132 1133 return self.func("UNIFORM", expression.this, expression.expression, gen) 1134 1135 def window_sql(self, expression: exp.Window) -> str: 1136 spec = expression.args.get("spec") 1137 this = expression.this 1138 1139 if ( 1140 ( 1141 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1142 or ( 1143 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1144 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1145 ) 1146 ) 1147 and spec 1148 and ( 1149 spec.text("kind").upper() == "ROWS" 1150 and spec.text("start").upper() == "UNBOUNDED" 1151 and spec.text("start_side").upper() == "PRECEDING" 1152 and spec.text("end").upper() == "UNBOUNDED" 1153 and spec.text("end_side").upper() == "FOLLOWING" 1154 ) 1155 ): 1156 # omit the default window from window ranking functions 1157 expression.set("spec", None) 1158 return super().window_sql(expression) 1159 1160 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1161 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1162 # accepts the value to aggregate as an argument: MODE(<expr>) 1163 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1164 order = expression.expression 1165 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1166 return self.sql(exp.Mode(this=order.expressions[0].this)) 1167 1168 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.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.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 Generator.<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.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.DayOfWeek'>: <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.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>>}
620 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 621 this = self.func("IDENTIFIER", expression.this) 622 if "expressions" in expression.args: 623 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 624 return self.func(this, *expression.expressions, normalize=False) 625 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.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.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.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.POST_SCHEMA: 'POST_SCHEMA'>, <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.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>}
UNSUPPORTED_VALUES_EXPRESSIONS: ClassVar =
{<class 'sqlglot.expressions.array.Map'>, <class 'sqlglot.expressions.array.Struct'>, <class 'sqlglot.expressions.array.VarMap'>, <class 'sqlglot.expressions.array.StarMap'>}
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS =
(<class 'sqlglot.expressions.aggregate.ArrayAgg'>,)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
674 def datatype_sql(self, expression: exp.DataType) -> str: 675 # Check if this is a FLOAT type nested inside a VECTOR type 676 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 677 # https://docs.snowflake.com/en/sql-reference/data-types-vector 678 if expression.is_type(exp.DType.DOUBLE): 679 parent = expression.parent 680 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 681 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 682 return "FLOAT" 683 684 expressions = expression.expressions 685 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 686 for field_type in expressions: 687 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 688 if isinstance(field_type, exp.DataType): 689 return "OBJECT" 690 if ( 691 isinstance(field_type, exp.ColumnDef) 692 and field_type.this 693 and field_type.this.is_string 694 ): 695 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 696 # converting 'foo' into an identifier, we also need to quote it because these 697 # keys are case-sensitive. For example: 698 # 699 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 700 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 701 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 702 703 return super().datatype_sql(expression)
705 def tonumber_sql(self, expression: exp.ToNumber) -> str: 706 precision = expression.args.get("precision") 707 scale = expression.args.get("scale") 708 709 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 710 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 711 712 if default_precision and default_scale: 713 precision = None 714 scale = None 715 elif default_scale: 716 scale = None 717 718 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 719 720 return self.func( 721 func_name, 722 expression.this, 723 expression.args.get("format"), 724 precision, 725 scale, 726 )
def
timestampfromparts_sql(self, expression: sqlglot.expressions.temporal.TimestampFromParts) -> str:
728 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 729 milli = expression.args.get("milli") 730 if milli is not None: 731 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 732 expression.set("nano", milli_to_nano) 733 734 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
736 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 737 if expression.is_type(exp.DType.GEOGRAPHY): 738 return self.func("TO_GEOGRAPHY", expression.this) 739 if expression.is_type(exp.DType.GEOMETRY): 740 return self.func("TO_GEOMETRY", expression.this) 741 742 return super().cast_sql(expression, safe_prefix=safe_prefix)
744 def trycast_sql(self, expression: exp.TryCast) -> str: 745 value = expression.this 746 747 if value.type is None: 748 from sqlglot.optimizer.annotate_types import annotate_types 749 750 value = annotate_types(value, dialect=self.dialect) 751 752 # Snowflake requires that TRY_CAST's value be a string 753 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 754 # if we can deduce that the value is a string, then we can generate TRY_CAST 755 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 756 return super().trycast_sql(expression) 757 758 return self.cast_sql(expression)
774 def generator_sql(self, expression: exp.Generator) -> str: 775 args = [] 776 rowcount = expression.args.get("rowcount") 777 timelimit = expression.args.get("timelimit") 778 779 if rowcount: 780 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 781 if timelimit: 782 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 783 784 return self.func("GENERATOR", *args)
786 def unnest_sql(self, expression: exp.Unnest) -> str: 787 unnest_alias = expression.args.get("alias") 788 offset = expression.args.get("offset") 789 790 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 791 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 792 793 columns = [ 794 exp.to_identifier("seq"), 795 exp.to_identifier("key"), 796 exp.to_identifier("path"), 797 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 798 value, 799 exp.to_identifier("this"), 800 ] 801 802 if unnest_alias: 803 unnest_alias.set("columns", columns) 804 else: 805 unnest_alias = exp.TableAlias(this="_u", columns=columns) 806 807 table_input = self.sql(expression.expressions[0]) 808 if not table_input.startswith("INPUT =>"): 809 table_input = f"INPUT => {table_input}" 810 811 expression_parent = expression.parent 812 813 explode = ( 814 f"FLATTEN({table_input})" 815 if isinstance(expression_parent, exp.Lateral) 816 else f"TABLE(FLATTEN({table_input}))" 817 ) 818 alias = self.sql(unnest_alias) 819 alias = f" AS {alias}" if alias else "" 820 value = ( 821 "" 822 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 823 else f"{value} FROM " 824 ) 825 826 return f"{value}{explode}{alias}"
835 def show_sql(self, expression: exp.Show) -> str: 836 terse = "TERSE " if expression.args.get("terse") else "" 837 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 838 history = " HISTORY" if expression.args.get("history") else "" 839 like = self.sql(expression, "like") 840 like = f" LIKE {like}" if like else "" 841 842 scope = self.sql(expression, "scope") 843 scope = f" {scope}" if scope else "" 844 845 scope_kind = self.sql(expression, "scope_kind") 846 if scope_kind: 847 scope_kind = f" IN {scope_kind}" 848 849 starts_with = self.sql(expression, "starts_with") 850 if starts_with: 851 starts_with = f" STARTS WITH {starts_with}" 852 853 limit = self.sql(expression, "limit") 854 855 from_ = self.sql(expression, "from_") 856 if from_: 857 from_ = f" FROM {from_}" 858 859 privileges = self.expressions(expression, key="privileges", flat=True) 860 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 861 862 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:
870 def describe_sql(self, expression: exp.Describe) -> str: 871 kind_value = expression.args.get("kind") or "TABLE" 872 873 properties = expression.args.get("properties") 874 if properties: 875 qualifier = self.expressions(properties, sep=" ") 876 kind = f" {qualifier} {kind_value}" 877 else: 878 kind = f" {kind_value}" 879 880 this = f" {self.sql(expression, 'this')}" 881 expressions = self.expressions(expression, flat=True) 882 expressions = f" {expressions}" if expressions else "" 883 return f"DESCRIBE{kind}{this}{expressions}"
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint) -> str:
885 def generatedasidentitycolumnconstraint_sql( 886 self, expression: exp.GeneratedAsIdentityColumnConstraint 887 ) -> str: 888 start = expression.args.get("start") 889 start = f" START {start}" if start else "" 890 increment = expression.args.get("increment") 891 increment = f" INCREMENT {increment}" if increment else "" 892 893 order = expression.args.get("order") 894 if order is not None: 895 order_clause = " ORDER" if order else " NOORDER" 896 else: 897 order_clause = "" 898 899 return f"AUTOINCREMENT{start}{increment}{order_clause}"
901 def struct_sql(self, expression: exp.Struct) -> str: 902 if len(expression.expressions) == 1: 903 arg = expression.expressions[0] 904 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 905 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 906 return f"{{{self.sql(expression.expressions[0])}}}" 907 908 keys = [] 909 values = [] 910 911 for i, e in enumerate(expression.expressions): 912 if isinstance(e, exp.PropertyEQ): 913 keys.append( 914 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 915 ) 916 values.append(e.expression) 917 else: 918 keys.append(exp.Literal.string(f"_{i}")) 919 values.append(e) 920 921 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values)))
@unsupported_args('weight', 'accuracy')
def
approxquantile_sql(self, expression: sqlglot.expressions.aggregate.ApproxQuantile) -> str:
927 def alterset_sql(self, expression: exp.AlterSet) -> str: 928 exprs = self.expressions(expression, flat=True) 929 exprs = f" {exprs}" if exprs else "" 930 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 931 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 932 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 933 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 934 tag = self.expressions(expression, key="tag", flat=True) 935 tag = f" TAG {tag}" if tag else "" 936 937 return f"SET{exprs}{file_format}{copy_options}{tag}"
939 def strtotime_sql(self, expression: exp.StrToTime): 940 # target_type is stored as a DataType instance 941 target_type = expression.args.get("target_type") 942 943 # Get the type enum from DataType instance or from type annotation 944 if isinstance(target_type, exp.DataType): 945 type_enum = target_type.this 946 elif expression.type: 947 type_enum = expression.type.this 948 else: 949 type_enum = exp.DType.TIMESTAMP 950 951 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 952 953 return self.func( 954 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 955 expression.this, 956 self.format_time(expression), 957 )
968 def jsonextract_sql(self, expression: exp.JSONExtract): 969 this = expression.this 970 971 # JSON strings are valid coming from other dialects such as BQ so 972 # for these cases we PARSE_JSON preemptively 973 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 974 "requires_json" 975 ): 976 this = exp.ParseJSON(this=this) 977 978 return self.func( 979 "GET_PATH", 980 this, 981 expression.expression, 982 )
1000 def select_sql(self, expression: exp.Select) -> str: 1001 limit = expression.args.get("limit") 1002 offset = expression.args.get("offset") 1003 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1004 expression.limit(exp.Null(), copy=False) 1005 return super().select_sql(expression)
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
1007 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1008 is_materialized = expression.find(exp.MaterializedProperty) 1009 copy_grants_property = expression.find(exp.CopyGrantsProperty) 1010 1011 if expression.kind == "VIEW" and is_materialized and copy_grants_property: 1012 # For materialized views, COPY GRANTS is located *before* the columns list 1013 # This is in contrast to normal views where COPY GRANTS is located *after* the columns list 1014 # We default CopyGrantsProperty to POST_SCHEMA which means we need to output it POST_NAME if a materialized view is detected 1015 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1016 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1017 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1018 post_schema_properties.pop(post_schema_properties.index(copy_grants_property)) 1019 1020 this_name = self.sql(expression.this, "this") 1021 copy_grants = self.sql(copy_grants_property) 1022 this_schema = self.schema_columns_sql(expression.this) 1023 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1024 1025 return f"{this_name}{self.sep()}{copy_grants}{this_schema}" 1026 1027 return super().createable_sql(expression, locations)
1029 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1030 this = expression.this 1031 1032 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1033 # and add it later as part of the WITHIN GROUP clause 1034 order = this if isinstance(this, exp.Order) else None 1035 if order: 1036 expression.set("this", order.this.pop()) 1037 1038 expr_sql = super().arrayagg_sql(expression) 1039 1040 if order: 1041 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1042 1043 return expr_sql
1053 def array_sql(self, expression: exp.Array) -> str: 1054 expressions = expression.expressions 1055 1056 first_expr = seq_get(expressions, 0) 1057 if isinstance(first_expr, exp.Select): 1058 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1059 if first_expr.text("kind").upper() == "STRUCT": 1060 object_construct_args = [] 1061 for expr in first_expr.expressions: 1062 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1063 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1064 name = expr.this if isinstance(expr, exp.Alias) else expr 1065 1066 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1067 1068 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1069 1070 first_expr.set("kind", None) 1071 first_expr.set("expressions", [array_agg]) 1072 1073 return self.sql(first_expr.subquery()) 1074 1075 return inline_array_sql(self, expression)
1077 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1078 zone = self.sql(expression, "this") 1079 if not zone: 1080 return super().currentdate_sql(expression) 1081 1082 expr = exp.Cast( 1083 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1084 to=exp.DataType(this=exp.DType.DATE), 1085 ) 1086 return self.sql(expr)
1088 def dot_sql(self, expression: exp.Dot) -> str: 1089 this = expression.this 1090 1091 if not this.type: 1092 from sqlglot.optimizer.annotate_types import annotate_types 1093 1094 this = annotate_types(this, dialect=self.dialect) 1095 1096 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1097 # Generate colon notation for the top level STRUCT 1098 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1099 1100 return super().dot_sql(expression)
1111 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1112 # Set part_index to 1 if missing 1113 if not expression.args.get("delimiter"): 1114 expression.set("delimiter", exp.Literal.string(" ")) 1115 1116 if not expression.args.get("part_index"): 1117 expression.set("part_index", exp.Literal.number(1)) 1118 1119 return rename_func("SPLIT_PART")(self, expression)
1121 def uniform_sql(self, expression: exp.Uniform) -> str: 1122 gen = expression.args.get("gen") 1123 seed = expression.args.get("seed") 1124 1125 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1126 if seed: 1127 gen = exp.Rand(this=seed) 1128 1129 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1130 if not gen: 1131 gen = exp.Rand() 1132 1133 return self.func("UNIFORM", expression.this, expression.expression, gen)
1135 def window_sql(self, expression: exp.Window) -> str: 1136 spec = expression.args.get("spec") 1137 this = expression.this 1138 1139 if ( 1140 ( 1141 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1142 or ( 1143 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1144 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1145 ) 1146 ) 1147 and spec 1148 and ( 1149 spec.text("kind").upper() == "ROWS" 1150 and spec.text("start").upper() == "UNBOUNDED" 1151 and spec.text("start_side").upper() == "PRECEDING" 1152 and spec.text("end").upper() == "UNBOUNDED" 1153 and spec.text("end_side").upper() == "FOLLOWING" 1154 ) 1155 ): 1156 # omit the default window from window ranking functions 1157 expression.set("spec", None) 1158 return super().window_sql(expression)
1160 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1161 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1162 # accepts the value to aggregate as an argument: MODE(<expr>) 1163 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1164 order = expression.expression 1165 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1166 return self.sql(exp.Mode(this=order.expressions[0].this)) 1167 1168 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
- 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
- QUERY_HINT_SEP
- SAFE_INT_DIVISION
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- NVL2_SUPPORTED
- VALUES_AS_TABLE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- 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_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
- 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
- NORMALIZE_EXTRACT_DATE_PARTS
- PARSE_JSON_NAME
- 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
- 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
- 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
- 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
- connect_sql
- prior_sql
- join_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
- 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
- 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
- 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
- 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
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_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
- 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
- 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
- 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
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql