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 MERGE_ALL_BY_NAME = True 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 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 400 ALTER_TABLE_ADD_COLUMNS_WRAPPED = False 401 402 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 403 404 IS_BOOL_ALLOWED = False 405 DIRECTED_JOINS = True 406 SUPPORTS_UESCAPE = False 407 TRY_SUPPORTED = False 408 409 TRANSFORMS = { 410 **generator.Generator.TRANSFORMS, 411 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 412 exp.ArgMax: rename_func("MAX_BY"), 413 exp.ArgMin: rename_func("MIN_BY"), 414 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 415 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 416 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 417 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 418 exp.ArrayContains: lambda self, e: self.func( 419 "ARRAY_CONTAINS", 420 e.expression 421 if e.args.get("ensure_variant") is False 422 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 423 e.this, 424 ), 425 exp.ArrayPosition: lambda self, e: self.func( 426 "ARRAY_POSITION", 427 e.expression, 428 e.this, 429 ), 430 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 431 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 432 exp.ArraySort: _array_sort_sql, 433 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 434 exp.BitwiseOr: rename_func("BITOR"), 435 exp.BitwiseXor: rename_func("BITXOR"), 436 exp.BitwiseAnd: rename_func("BITAND"), 437 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 438 exp.BitwiseOrAgg: rename_func("BITORAGG"), 439 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 440 exp.BitwiseNot: rename_func("BITNOT"), 441 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 442 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 443 exp.CurrentTimestamp: lambda self, e: ( 444 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 445 ), 446 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 447 exp.Localtime: lambda self, e: ( 448 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 449 ), 450 exp.Localtimestamp: lambda self, e: ( 451 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 452 ), 453 exp.DateAdd: date_delta_sql("DATEADD"), 454 exp.DateDiff: date_delta_sql("DATEDIFF"), 455 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 456 exp.DatetimeDiff: timestampdiff_sql, 457 exp.DateStrToDate: datestrtodate_sql, 458 exp.Decrypt: lambda self, e: self.func( 459 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 460 e.this, 461 e.args.get("passphrase"), 462 e.args.get("aad"), 463 e.args.get("encryption_method"), 464 ), 465 exp.DecryptRaw: lambda self, e: self.func( 466 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 467 e.this, 468 e.args.get("key"), 469 e.args.get("iv"), 470 e.args.get("aad"), 471 e.args.get("encryption_method"), 472 e.args.get("aead"), 473 ), 474 exp.DayOfMonth: rename_func("DAYOFMONTH"), 475 exp.DayOfWeek: rename_func("DAYOFWEEK"), 476 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 477 exp.DayOfYear: rename_func("DAYOFYEAR"), 478 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 479 exp.Explode: rename_func("FLATTEN"), 480 exp.Extract: lambda self, e: self.func( 481 "DATE_PART", map_date_part(e.this, self.dialect), e.expression 482 ), 483 exp.Filter: no_filter_sql, 484 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 485 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 486 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 487 exp.FileFormatProperty: lambda self, e: ( 488 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 489 ), 490 exp.FromTimeZone: lambda self, e: self.func( 491 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 492 ), 493 exp.GenerateSeries: lambda self, e: self.func( 494 "ARRAY_GENERATE_RANGE", 495 e.args["start"], 496 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 497 e.args.get("step"), 498 ), 499 exp.GetExtract: rename_func("GET"), 500 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 501 exp.If: if_sql(name="IFF", false_value="NULL"), 502 exp.InteractiveProperty: lambda *_: "INTERACTIVE", 503 exp.JSONArray: lambda self, e: self.func( 504 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 505 ), 506 exp.JSONExtractArray: _json_extract_value_array_sql, 507 exp.JSONExtractScalar: lambda self, e: self.func( 508 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 509 ), 510 exp.JSONKeys: rename_func("OBJECT_KEYS"), 511 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 512 exp.JSONPathRoot: lambda *_: "", 513 exp.JSONValueArray: _json_extract_value_array_sql, 514 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 515 rename_func("EDITDISTANCE") 516 ), 517 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 518 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 519 exp.LogicalOr: rename_func("BOOLOR_AGG"), 520 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 521 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 522 exp.MakeInterval: no_make_interval_sql, 523 exp.Max: max_or_greatest, 524 exp.Min: min_or_least, 525 exp.NthValue: nth_value_from_sql, 526 exp.ParseJSON: lambda self, e: self.func( 527 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 528 ), 529 exp.ToBinary: lambda self, e: self.func( 530 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 531 ), 532 exp.ToBoolean: lambda self, e: self.func( 533 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 534 ), 535 exp.ToDouble: lambda self, e: self.func( 536 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 537 ), 538 exp.ToFile: lambda self, e: self.func( 539 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 540 ), 541 exp.JSONFormat: rename_func("TO_JSON"), 542 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 543 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 544 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 545 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 546 exp.RegexpExtract: _regexpextract_sql, 547 exp.RegexpExtractAll: _regexpextract_sql, 548 exp.RegexpILike: _regexpilike_sql, 549 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 550 exp.Select: transforms.preprocess( 551 [ 552 transforms.eliminate_window_clause, 553 transforms.eliminate_distinct_on, 554 transforms.explode_projection_to_unnest(), 555 transforms.eliminate_semi_and_anti_joins, 556 _transform_generate_date_array, 557 _qualify_unnested_columns, 558 _eliminate_dot_variant_lookup, 559 ] 560 ), 561 exp.SHA: rename_func("SHA1"), 562 exp.SHA1Digest: rename_func("SHA1_BINARY"), 563 exp.MD5Digest: rename_func("MD5_BINARY"), 564 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 565 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 566 exp.Hex: rename_func("HEX_ENCODE"), 567 exp.LowerHex: rename_func("TO_CHAR"), 568 exp.Skewness: rename_func("SKEW"), 569 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 570 exp.StartsWith: rename_func("STARTSWITH"), 571 exp.EndsWith: rename_func("ENDSWITH"), 572 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 573 exp.StrPosition: lambda self, e: strposition_sql( 574 self, e, func_name="CHARINDEX", supports_position=True 575 ), 576 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 577 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 578 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 579 exp.Stuff: rename_func("INSERT"), 580 exp.StPoint: rename_func("ST_MAKEPOINT"), 581 exp.TemporaryProperty: lambda _, e: ( 582 "SCOPED TEMPORARY" if e.args.get("scoped") else "TEMPORARY" 583 ), 584 exp.TimeAdd: date_delta_sql("TIMEADD"), 585 exp.TimeSlice: lambda self, e: self.func( 586 "TIME_SLICE", 587 e.this, 588 e.expression, 589 unit_to_str(e), 590 e.args.get("kind"), 591 ), 592 exp.Timestamp: no_timestamp_sql, 593 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 594 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 595 exp.TimestampTrunc: timestamptrunc_sql(), 596 exp.TimeStrToTime: timestrtotime_sql, 597 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 598 exp.ToArray: rename_func("TO_ARRAY"), 599 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 600 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 601 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 602 exp.TsOrDsToDate: lambda self, e: self.func( 603 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 604 ), 605 exp.TsOrDsToTime: lambda self, e: self.func( 606 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 607 ), 608 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 609 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 610 exp.Uuid: rename_func("UUID_STRING"), 611 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 612 exp.Booland: rename_func("BOOLAND"), 613 exp.Boolor: rename_func("BOOLOR"), 614 exp.WeekOfYear: rename_func("WEEKISO"), 615 exp.YearOfWeek: rename_func("YEAROFWEEK"), 616 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 617 exp.Xor: rename_func("BOOLXOR"), 618 exp.ByteLength: rename_func("OCTET_LENGTH"), 619 exp.Flatten: rename_func("ARRAY_FLATTEN"), 620 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 621 exp.SHA2Digest: lambda self, e: self.func( 622 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 623 ), 624 } 625 626 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 627 this = self.func("IDENTIFIER", expression.this) 628 if "expressions" in expression.args: 629 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 630 return self.func(this, *expression.expressions, normalize=False) 631 return this 632 633 SUPPORTED_JSON_PATH_PARTS = { 634 exp.JSONPathKey, 635 exp.JSONPathRoot, 636 exp.JSONPathSubscript, 637 } 638 639 TYPE_MAPPING = { 640 **generator.Generator.TYPE_MAPPING, 641 exp.DType.BIGDECIMAL: "DOUBLE", 642 exp.DType.JSON: "VARIANT", 643 exp.DType.NESTED: "OBJECT", 644 exp.DType.STRUCT: "OBJECT", 645 exp.DType.TEXT: "VARCHAR", 646 } 647 648 TOKEN_MAPPING = { 649 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 650 } 651 652 PROPERTIES_LOCATION = { 653 **generator.Generator.PROPERTIES_LOCATION, 654 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 655 exp.InteractiveProperty: exp.Properties.Location.POST_CREATE, 656 exp.LocationProperty: exp.Properties.Location.POST_WITH, 657 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 658 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 659 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 660 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 661 } 662 663 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 664 exp.Map, 665 exp.StarMap, 666 exp.Struct, 667 exp.VarMap, 668 } 669 670 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 671 672 def with_properties(self, properties: exp.Properties) -> str: 673 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 674 675 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 676 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 677 values_as_table = False 678 679 return super().values_sql(expression, values_as_table=values_as_table) 680 681 def datatype_sql(self, expression: exp.DataType) -> str: 682 # Check if this is a FLOAT type nested inside a VECTOR type 683 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 684 # https://docs.snowflake.com/en/sql-reference/data-types-vector 685 if expression.is_type(exp.DType.DOUBLE): 686 parent = expression.parent 687 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 688 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 689 return "FLOAT" 690 691 expressions = expression.expressions 692 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 693 for field_type in expressions: 694 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 695 if isinstance(field_type, exp.DataType): 696 return "OBJECT" 697 if ( 698 isinstance(field_type, exp.ColumnDef) 699 and field_type.this 700 and field_type.this.is_string 701 ): 702 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 703 # converting 'foo' into an identifier, we also need to quote it because these 704 # keys are case-sensitive. For example: 705 # 706 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 707 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 708 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 709 710 return super().datatype_sql(expression) 711 712 def tonumber_sql(self, expression: exp.ToNumber) -> str: 713 precision = expression.args.get("precision") 714 scale = expression.args.get("scale") 715 716 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 717 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 718 719 if default_precision and default_scale: 720 precision = None 721 scale = None 722 elif default_scale: 723 scale = None 724 725 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 726 727 return self.func( 728 func_name, 729 expression.this, 730 expression.args.get("format"), 731 precision, 732 scale, 733 ) 734 735 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 736 milli = expression.args.get("milli") 737 if milli is not None: 738 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 739 expression.set("nano", milli_to_nano) 740 741 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 742 743 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 744 if expression.is_type(exp.DType.GEOGRAPHY): 745 return self.func("TO_GEOGRAPHY", expression.this) 746 if expression.is_type(exp.DType.GEOMETRY): 747 return self.func("TO_GEOMETRY", expression.this) 748 749 return super().cast_sql(expression, safe_prefix=safe_prefix) 750 751 def trycast_sql(self, expression: exp.TryCast) -> str: 752 value = expression.this 753 754 if value.type is None: 755 from sqlglot.optimizer.annotate_types import annotate_types 756 757 value = annotate_types(value, dialect=self.dialect) 758 759 # Snowflake requires that TRY_CAST's value be a string 760 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 761 # if we can deduce that the value is a string, then we can generate TRY_CAST 762 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 763 return super().trycast_sql(expression) 764 765 return self.cast_sql(expression) 766 767 def log_sql(self, expression: exp.Log) -> str: 768 if not expression.expression: 769 return self.func("LN", expression.this) 770 771 return super().log_sql(expression) 772 773 def greatest_sql(self, expression: exp.Greatest) -> str: 774 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 775 return self.func(name, expression.this, *expression.expressions) 776 777 def least_sql(self, expression: exp.Least) -> str: 778 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 779 return self.func(name, expression.this, *expression.expressions) 780 781 def generator_sql(self, expression: exp.Generator) -> str: 782 args = [] 783 rowcount = expression.args.get("rowcount") 784 timelimit = expression.args.get("timelimit") 785 786 if rowcount: 787 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 788 if timelimit: 789 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 790 791 return self.func("GENERATOR", *args) 792 793 def unnest_sql(self, expression: exp.Unnest) -> str: 794 unnest_alias = expression.args.get("alias") 795 offset = expression.args.get("offset") 796 797 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 798 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 799 800 columns = [ 801 exp.to_identifier("seq"), 802 exp.to_identifier("key"), 803 exp.to_identifier("path"), 804 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 805 value, 806 exp.to_identifier("this"), 807 ] 808 809 if unnest_alias: 810 unnest_alias.set("columns", columns) 811 else: 812 unnest_alias = exp.TableAlias(this="_u", columns=columns) 813 814 table_input = self.sql(expression.expressions[0]) 815 if not table_input.startswith("INPUT =>"): 816 table_input = f"INPUT => {table_input}" 817 818 expression_parent = expression.parent 819 820 explode = ( 821 f"FLATTEN({table_input})" 822 if isinstance(expression_parent, exp.Lateral) 823 else f"TABLE(FLATTEN({table_input}))" 824 ) 825 alias = self.sql(unnest_alias) 826 alias = f" AS {alias}" if alias else "" 827 value = ( 828 "" 829 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 830 else f"{value} FROM " 831 ) 832 833 return f"{value}{explode}{alias}" 834 835 def undrop_sql(self, expression: exp.Undrop) -> str: 836 this = self.sql(expression, "this") 837 kind = expression.kind 838 rename = self.sql(expression, "rename") 839 rename = f" RENAME TO {rename}" if rename else "" 840 return f"UNDROP {kind} {this}{rename}" 841 842 def show_sql(self, expression: exp.Show) -> str: 843 terse = "TERSE " if expression.args.get("terse") else "" 844 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 845 history = " HISTORY" if expression.args.get("history") else "" 846 like = self.sql(expression, "like") 847 like = f" LIKE {like}" if like else "" 848 849 scope = self.sql(expression, "scope") 850 scope = f" {scope}" if scope else "" 851 852 scope_kind = self.sql(expression, "scope_kind") 853 if scope_kind: 854 scope_kind = f" IN {scope_kind}" 855 856 starts_with = self.sql(expression, "starts_with") 857 if starts_with: 858 starts_with = f" STARTS WITH {starts_with}" 859 860 limit = self.sql(expression, "limit") 861 862 from_ = self.sql(expression, "from_") 863 if from_: 864 from_ = f" FROM {from_}" 865 866 privileges = self.expressions(expression, key="privileges", flat=True) 867 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 868 869 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 870 871 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 872 if not expression.this: 873 return "ROW ACCESS" 874 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 875 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 876 877 def describe_sql(self, expression: exp.Describe) -> str: 878 kind_value = expression.args.get("kind") or "TABLE" 879 880 properties = expression.args.get("properties") 881 if properties: 882 qualifier = self.expressions(properties, sep=" ") 883 kind = f" {qualifier} {kind_value}" 884 else: 885 kind = f" {kind_value}" 886 887 this = f" {self.sql(expression, 'this')}" 888 expressions = self.expressions(expression, flat=True) 889 expressions = f" {expressions}" if expressions else "" 890 return f"DESCRIBE{kind}{this}{expressions}" 891 892 def generatedasidentitycolumnconstraint_sql( 893 self, expression: exp.GeneratedAsIdentityColumnConstraint 894 ) -> str: 895 start = expression.args.get("start") 896 start = f" START {start}" if start else "" 897 increment = expression.args.get("increment") 898 increment = f" INCREMENT {increment}" if increment else "" 899 900 order = expression.args.get("order") 901 if order is not None: 902 order_clause = " ORDER" if order else " NOORDER" 903 else: 904 order_clause = "" 905 906 return f"AUTOINCREMENT{start}{increment}{order_clause}" 907 908 def struct_sql(self, expression: exp.Struct) -> str: 909 if len(expression.expressions) == 1: 910 arg = expression.expressions[0] 911 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 912 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 913 return f"{{{self.sql(expression.expressions[0])}}}" 914 915 keys = [] 916 values = [] 917 918 for i, e in enumerate(expression.expressions): 919 if isinstance(e, exp.PropertyEQ): 920 keys.append( 921 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 922 ) 923 values.append(e.expression) 924 else: 925 keys.append(exp.Literal.string(f"_{i}")) 926 values.append(e) 927 928 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 929 930 @unsupported_args("weight", "accuracy") 931 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 932 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 933 934 def alterset_sql(self, expression: exp.AlterSet) -> str: 935 exprs = self.expressions(expression, flat=True) 936 exprs = f" {exprs}" if exprs else "" 937 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 938 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 939 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 940 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 941 tag = self.expressions(expression, key="tag", flat=True) 942 tag = f" TAG {tag}" if tag else "" 943 944 return f"SET{exprs}{file_format}{copy_options}{tag}" 945 946 def strtotime_sql(self, expression: exp.StrToTime): 947 # target_type is stored as a DataType instance 948 target_type = expression.args.get("target_type") 949 950 # Get the type enum from DataType instance or from type annotation 951 if isinstance(target_type, exp.DataType): 952 type_enum = target_type.this 953 elif expression.type: 954 type_enum = expression.type.this 955 else: 956 type_enum = exp.DType.TIMESTAMP 957 958 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 959 960 return self.func( 961 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 962 expression.this, 963 self.format_time(expression), 964 ) 965 966 def timestampsub_sql(self, expression: exp.TimestampSub): 967 return self.sql( 968 exp.TimestampAdd( 969 this=expression.this, 970 expression=expression.expression * -1, 971 unit=expression.unit, 972 ) 973 ) 974 975 def jsonextract_sql(self, expression: exp.JSONExtract): 976 this = expression.this 977 978 # JSON strings are valid coming from other dialects such as BQ so 979 # for these cases we PARSE_JSON preemptively 980 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 981 "requires_json" 982 ): 983 this = exp.ParseJSON(this=this) 984 985 return self.func( 986 "GET_PATH", 987 this, 988 expression.expression, 989 ) 990 991 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 992 this = expression.this 993 if this.is_string: 994 this = exp.cast(this, exp.DType.TIMESTAMP) 995 996 return self.func("TO_CHAR", this, self.format_time(expression)) 997 998 def datesub_sql(self, expression: exp.DateSub) -> str: 999 value = expression.expression 1000 if value: 1001 value.replace(value * (-1)) 1002 else: 1003 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1004 1005 return date_delta_sql("DATEADD")(self, expression) 1006 1007 def select_sql(self, expression: exp.Select) -> str: 1008 limit = expression.args.get("limit") 1009 offset = expression.args.get("offset") 1010 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1011 expression.limit(exp.Null(), copy=False) 1012 return super().select_sql(expression) 1013 1014 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1015 is_materialized = expression.find(exp.MaterializedProperty) 1016 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1017 1018 if expression.kind == "VIEW" and is_materialized and grants_property: 1019 # Materialized views require COPY/IGNORE GRANTS before the column list, 1020 # whereas normal views use the default POST_SCHEMA location. 1021 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1022 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1023 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1024 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1025 1026 this_name = self.sql(expression.this, "this") 1027 grants = self.sql(grants_property) 1028 this_schema = self.schema_columns_sql(expression.this) 1029 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1030 1031 return f"{this_name}{self.sep()}{grants}{this_schema}" 1032 1033 return super().createable_sql(expression, locations) 1034 1035 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1036 this = expression.this 1037 1038 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1039 # and add it later as part of the WITHIN GROUP clause 1040 order = this if isinstance(this, exp.Order) else None 1041 if order: 1042 expression.set("this", order.this.pop()) 1043 1044 expr_sql = super().arrayagg_sql(expression) 1045 1046 if order: 1047 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1048 1049 return expr_sql 1050 1051 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1052 if expression.args.get("check_null"): 1053 return self.func("ARRAY_DISTINCT", expression.this) 1054 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1055 1056 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1057 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1058 1059 def array_sql(self, expression: exp.Array) -> str: 1060 expressions = expression.expressions 1061 1062 first_expr = seq_get(expressions, 0) 1063 if isinstance(first_expr, exp.Select): 1064 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1065 if first_expr.text("kind").upper() == "STRUCT": 1066 object_construct_args = [] 1067 for expr in first_expr.expressions: 1068 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1069 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1070 name = expr.this if isinstance(expr, exp.Alias) else expr 1071 1072 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1073 1074 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1075 1076 first_expr.set("kind", None) 1077 first_expr.set("expressions", [array_agg]) 1078 1079 return self.sql(first_expr.subquery()) 1080 1081 return inline_array_sql(self, expression) 1082 1083 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1084 zone = self.sql(expression, "this") 1085 if not zone: 1086 return super().currentdate_sql(expression) 1087 1088 expr = exp.Cast( 1089 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1090 to=exp.DataType(this=exp.DType.DATE), 1091 ) 1092 return self.sql(expr) 1093 1094 def dot_sql(self, expression: exp.Dot) -> str: 1095 this = expression.this 1096 1097 if not this.type: 1098 from sqlglot.optimizer.annotate_types import annotate_types 1099 1100 this = annotate_types(this, dialect=self.dialect) 1101 1102 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1103 # Generate colon notation for the top level STRUCT 1104 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1105 1106 return super().dot_sql(expression) 1107 1108 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1109 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1110 1111 def format_sql(self, expression: exp.Format) -> str: 1112 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1113 return self.func("TO_CHAR", expression.expressions[0]) 1114 1115 return self.function_fallback_sql(expression) 1116 1117 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1118 # Set part_index to 1 if missing 1119 if not expression.args.get("delimiter"): 1120 expression.set("delimiter", exp.Literal.string(" ")) 1121 1122 if not expression.args.get("part_index"): 1123 expression.set("part_index", exp.Literal.number(1)) 1124 1125 return rename_func("SPLIT_PART")(self, expression) 1126 1127 def uniform_sql(self, expression: exp.Uniform) -> str: 1128 gen = expression.args.get("gen") 1129 seed = expression.args.get("seed") 1130 1131 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1132 if seed: 1133 gen = exp.Rand(this=seed) 1134 1135 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1136 if not gen: 1137 gen = exp.Rand() 1138 1139 return self.func("UNIFORM", expression.this, expression.expression, gen) 1140 1141 def window_sql(self, expression: exp.Window) -> str: 1142 spec = expression.args.get("spec") 1143 this = expression.this 1144 1145 if ( 1146 ( 1147 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1148 or ( 1149 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1150 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1151 ) 1152 ) 1153 and spec 1154 and ( 1155 spec.text("kind").upper() == "ROWS" 1156 and spec.text("start").upper() == "UNBOUNDED" 1157 and spec.text("start_side").upper() == "PRECEDING" 1158 and spec.text("end").upper() == "UNBOUNDED" 1159 and spec.text("end_side").upper() == "FOLLOWING" 1160 ) 1161 ): 1162 # omit the default window from window ranking functions 1163 expression.set("spec", None) 1164 return super().window_sql(expression) 1165 1166 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1167 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1168 # accepts the value to aggregate as an argument: MODE(<expr>) 1169 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1170 order = expression.expression 1171 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1172 return self.sql(exp.Mode(this=order.expressions[0].this)) 1173 1174 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 MERGE_ALL_BY_NAME = True 379 SINGLE_STRING_INTERVAL = True 380 CAST_TO_INT_ROUNDS = True 381 JOIN_HINTS = False 382 TABLE_HINTS = False 383 QUERY_HINTS = False 384 SUPPORTS_TABLE_COPY = False 385 COLLATE_IS_FUNC = True 386 LIMIT_ONLY_LITERALS = True 387 JSON_KEY_VALUE_PAIR_SEP = "," 388 INSERT_OVERWRITE = " OVERWRITE INTO" 389 STRUCT_DELIMITER = ("(", ")") 390 COPY_PARAMS_ARE_WRAPPED = False 391 COPY_PARAMS_EQ_REQUIRED = True 392 STAR_EXCEPT = "EXCLUDE" 393 SUPPORTS_EXPLODING_PROJECTIONS = False 394 ARRAY_CONCAT_IS_VAR_LEN = False 395 SUPPORTS_CONVERT_TIMEZONE = True 396 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 397 SUPPORTS_MEDIAN = True 398 ARRAY_SIZE_NAME = "ARRAY_SIZE" 399 SUPPORTS_DECODE_CASE = True 400 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 401 ALTER_TABLE_ADD_COLUMNS_WRAPPED = False 402 403 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 404 405 IS_BOOL_ALLOWED = False 406 DIRECTED_JOINS = True 407 SUPPORTS_UESCAPE = False 408 TRY_SUPPORTED = False 409 410 TRANSFORMS = { 411 **generator.Generator.TRANSFORMS, 412 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 413 exp.ArgMax: rename_func("MAX_BY"), 414 exp.ArgMin: rename_func("MIN_BY"), 415 exp.Array: transforms.preprocess([transforms.inherit_struct_field_names]), 416 exp.ArrayConcat: array_concat_sql("ARRAY_CAT"), 417 exp.ArrayAppend: array_append_sql("ARRAY_APPEND"), 418 exp.ArrayPrepend: array_append_sql("ARRAY_PREPEND"), 419 exp.ArrayContains: lambda self, e: self.func( 420 "ARRAY_CONTAINS", 421 e.expression 422 if e.args.get("ensure_variant") is False 423 else exp.cast(e.expression, exp.DType.VARIANT, copy=False), 424 e.this, 425 ), 426 exp.ArrayPosition: lambda self, e: self.func( 427 "ARRAY_POSITION", 428 e.expression, 429 e.this, 430 ), 431 exp.ArrayIntersect: rename_func("ARRAY_INTERSECTION"), 432 exp.ArrayOverlaps: rename_func("ARRAYS_OVERLAP"), 433 exp.ArraySort: _array_sort_sql, 434 exp.AtTimeZone: lambda self, e: self.func("CONVERT_TIMEZONE", e.args.get("zone"), e.this), 435 exp.BitwiseOr: rename_func("BITOR"), 436 exp.BitwiseXor: rename_func("BITXOR"), 437 exp.BitwiseAnd: rename_func("BITAND"), 438 exp.BitwiseAndAgg: rename_func("BITANDAGG"), 439 exp.BitwiseOrAgg: rename_func("BITORAGG"), 440 exp.BitwiseXorAgg: rename_func("BITXORAGG"), 441 exp.BitwiseNot: rename_func("BITNOT"), 442 exp.BitwiseLeftShift: rename_func("BITSHIFTLEFT"), 443 exp.BitwiseRightShift: rename_func("BITSHIFTRIGHT"), 444 exp.CurrentTimestamp: lambda self, e: ( 445 self.func("SYSDATE") if e.args.get("sysdate") else self.function_fallback_sql(e) 446 ), 447 exp.CurrentSchemas: lambda self, e: self.func("CURRENT_SCHEMAS"), 448 exp.Localtime: lambda self, e: ( 449 self.func("CURRENT_TIME", e.this) if e.this else "CURRENT_TIME" 450 ), 451 exp.Localtimestamp: lambda self, e: ( 452 self.func("CURRENT_TIMESTAMP", e.this) if e.this else "CURRENT_TIMESTAMP" 453 ), 454 exp.DateAdd: date_delta_sql("DATEADD"), 455 exp.DateDiff: date_delta_sql("DATEDIFF"), 456 exp.DatetimeAdd: date_delta_sql("TIMESTAMPADD"), 457 exp.DatetimeDiff: timestampdiff_sql, 458 exp.DateStrToDate: datestrtodate_sql, 459 exp.Decrypt: lambda self, e: self.func( 460 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT", 461 e.this, 462 e.args.get("passphrase"), 463 e.args.get("aad"), 464 e.args.get("encryption_method"), 465 ), 466 exp.DecryptRaw: lambda self, e: self.func( 467 f"{'TRY_' if e.args.get('safe') else ''}DECRYPT_RAW", 468 e.this, 469 e.args.get("key"), 470 e.args.get("iv"), 471 e.args.get("aad"), 472 e.args.get("encryption_method"), 473 e.args.get("aead"), 474 ), 475 exp.DayOfMonth: rename_func("DAYOFMONTH"), 476 exp.DayOfWeek: rename_func("DAYOFWEEK"), 477 exp.DayOfWeekIso: rename_func("DAYOFWEEKISO"), 478 exp.DayOfYear: rename_func("DAYOFYEAR"), 479 exp.DotProduct: rename_func("VECTOR_INNER_PRODUCT"), 480 exp.Explode: rename_func("FLATTEN"), 481 exp.Extract: lambda self, e: self.func( 482 "DATE_PART", map_date_part(e.this, self.dialect), e.expression 483 ), 484 exp.Filter: no_filter_sql, 485 exp.CosineDistance: rename_func("VECTOR_COSINE_SIMILARITY"), 486 exp.EuclideanDistance: rename_func("VECTOR_L2_DISTANCE"), 487 exp.HandlerProperty: lambda self, e: f"HANDLER = {self.sql(e, 'this')}", 488 exp.FileFormatProperty: lambda self, e: ( 489 f"FILE_FORMAT=({self.expressions(e, 'expressions', sep=' ')})" 490 ), 491 exp.FromTimeZone: lambda self, e: self.func( 492 "CONVERT_TIMEZONE", e.args.get("zone"), "'UTC'", e.this 493 ), 494 exp.GenerateSeries: lambda self, e: self.func( 495 "ARRAY_GENERATE_RANGE", 496 e.args["start"], 497 e.args["end"] if e.args.get("is_end_exclusive") else e.args["end"] + 1, 498 e.args.get("step"), 499 ), 500 exp.GetExtract: rename_func("GET"), 501 exp.GroupConcat: lambda self, e: groupconcat_sql(self, e, sep=""), 502 exp.If: if_sql(name="IFF", false_value="NULL"), 503 exp.InteractiveProperty: lambda *_: "INTERACTIVE", 504 exp.JSONArray: lambda self, e: self.func( 505 "TO_VARIANT", self.func("ARRAY_CONSTRUCT", *e.expressions) 506 ), 507 exp.JSONExtractArray: _json_extract_value_array_sql, 508 exp.JSONExtractScalar: lambda self, e: self.func( 509 "JSON_EXTRACT_PATH_TEXT", e.this, e.expression 510 ), 511 exp.JSONKeys: rename_func("OBJECT_KEYS"), 512 exp.JSONObject: lambda self, e: self.func("OBJECT_CONSTRUCT_KEEP_NULL", *e.expressions), 513 exp.JSONPathRoot: lambda *_: "", 514 exp.JSONValueArray: _json_extract_value_array_sql, 515 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost")( 516 rename_func("EDITDISTANCE") 517 ), 518 exp.LocationProperty: lambda self, e: f"LOCATION={self.sql(e, 'this')}", 519 exp.LogicalAnd: rename_func("BOOLAND_AGG"), 520 exp.LogicalOr: rename_func("BOOLOR_AGG"), 521 exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 522 exp.ManhattanDistance: rename_func("VECTOR_L1_DISTANCE"), 523 exp.MakeInterval: no_make_interval_sql, 524 exp.Max: max_or_greatest, 525 exp.Min: min_or_least, 526 exp.NthValue: nth_value_from_sql, 527 exp.ParseJSON: lambda self, e: self.func( 528 f"{'TRY_' if e.args.get('safe') else ''}PARSE_JSON", e.this 529 ), 530 exp.ToBinary: lambda self, e: self.func( 531 f"{'TRY_' if e.args.get('safe') else ''}TO_BINARY", e.this, e.args.get("format") 532 ), 533 exp.ToBoolean: lambda self, e: self.func( 534 f"{'TRY_' if e.args.get('safe') else ''}TO_BOOLEAN", e.this 535 ), 536 exp.ToDouble: lambda self, e: self.func( 537 f"{'TRY_' if e.args.get('safe') else ''}TO_DOUBLE", e.this, e.args.get("format") 538 ), 539 exp.ToFile: lambda self, e: self.func( 540 f"{'TRY_' if e.args.get('safe') else ''}TO_FILE", e.this, e.args.get("path") 541 ), 542 exp.JSONFormat: rename_func("TO_JSON"), 543 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 544 exp.PercentileCont: transforms.preprocess([transforms.add_within_group_for_percentiles]), 545 exp.PercentileDisc: transforms.preprocess([transforms.add_within_group_for_percentiles]), 546 exp.Pivot: transforms.preprocess([_unqualify_pivot_columns]), 547 exp.RegexpExtract: _regexpextract_sql, 548 exp.RegexpExtractAll: _regexpextract_sql, 549 exp.RegexpILike: _regexpilike_sql, 550 exp.RowAccessProperty: lambda self, e: self.rowaccessproperty_sql(e), 551 exp.Select: transforms.preprocess( 552 [ 553 transforms.eliminate_window_clause, 554 transforms.eliminate_distinct_on, 555 transforms.explode_projection_to_unnest(), 556 transforms.eliminate_semi_and_anti_joins, 557 _transform_generate_date_array, 558 _qualify_unnested_columns, 559 _eliminate_dot_variant_lookup, 560 ] 561 ), 562 exp.SHA: rename_func("SHA1"), 563 exp.SHA1Digest: rename_func("SHA1_BINARY"), 564 exp.MD5Digest: rename_func("MD5_BINARY"), 565 exp.MD5NumberLower64: rename_func("MD5_NUMBER_LOWER64"), 566 exp.MD5NumberUpper64: rename_func("MD5_NUMBER_UPPER64"), 567 exp.Hex: rename_func("HEX_ENCODE"), 568 exp.LowerHex: rename_func("TO_CHAR"), 569 exp.Skewness: rename_func("SKEW"), 570 exp.StarMap: rename_func("OBJECT_CONSTRUCT"), 571 exp.StartsWith: rename_func("STARTSWITH"), 572 exp.EndsWith: rename_func("ENDSWITH"), 573 exp.Rand: lambda self, e: self.func("RANDOM", e.this), 574 exp.StrPosition: lambda self, e: strposition_sql( 575 self, e, func_name="CHARINDEX", supports_position=True 576 ), 577 exp.StrToDate: lambda self, e: self.func("DATE", e.this, self.format_time(e)), 578 exp.StringToArray: rename_func("STRTOK_TO_ARRAY"), 579 exp.StrtokToArray: rename_func("STRTOK_TO_ARRAY"), 580 exp.Stuff: rename_func("INSERT"), 581 exp.StPoint: rename_func("ST_MAKEPOINT"), 582 exp.TemporaryProperty: lambda _, e: ( 583 "SCOPED TEMPORARY" if e.args.get("scoped") else "TEMPORARY" 584 ), 585 exp.TimeAdd: date_delta_sql("TIMEADD"), 586 exp.TimeSlice: lambda self, e: self.func( 587 "TIME_SLICE", 588 e.this, 589 e.expression, 590 unit_to_str(e), 591 e.args.get("kind"), 592 ), 593 exp.Timestamp: no_timestamp_sql, 594 exp.TimestampAdd: date_delta_sql("TIMESTAMPADD"), 595 exp.TimestampDiff: lambda self, e: self.func("TIMESTAMPDIFF", e.unit, e.expression, e.this), 596 exp.TimestampTrunc: timestamptrunc_sql(), 597 exp.TimeStrToTime: timestrtotime_sql, 598 exp.TimeToUnix: lambda self, e: f"EXTRACT(epoch_second FROM {self.sql(e, 'this')})", 599 exp.ToArray: rename_func("TO_ARRAY"), 600 exp.ToChar: lambda self, e: self.function_fallback_sql(e), 601 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 602 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 603 exp.TsOrDsToDate: lambda self, e: self.func( 604 f"{'TRY_' if e.args.get('safe') else ''}TO_DATE", e.this, self.format_time(e) 605 ), 606 exp.TsOrDsToTime: lambda self, e: self.func( 607 f"{'TRY_' if e.args.get('safe') else ''}TO_TIME", e.this, self.format_time(e) 608 ), 609 exp.Unhex: rename_func("HEX_DECODE_BINARY"), 610 exp.UnixToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, e.args.get("scale")), 611 exp.Uuid: rename_func("UUID_STRING"), 612 exp.VarMap: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"), 613 exp.Booland: rename_func("BOOLAND"), 614 exp.Boolor: rename_func("BOOLOR"), 615 exp.WeekOfYear: rename_func("WEEKISO"), 616 exp.YearOfWeek: rename_func("YEAROFWEEK"), 617 exp.YearOfWeekIso: rename_func("YEAROFWEEKISO"), 618 exp.Xor: rename_func("BOOLXOR"), 619 exp.ByteLength: rename_func("OCTET_LENGTH"), 620 exp.Flatten: rename_func("ARRAY_FLATTEN"), 621 exp.ArrayConcatAgg: lambda self, e: self.func("ARRAY_FLATTEN", exp.ArrayAgg(this=e.this)), 622 exp.SHA2Digest: lambda self, e: self.func( 623 "SHA2_BINARY", e.this, e.args.get("length") or exp.Literal.number(256) 624 ), 625 } 626 627 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 628 this = self.func("IDENTIFIER", expression.this) 629 if "expressions" in expression.args: 630 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 631 return self.func(this, *expression.expressions, normalize=False) 632 return this 633 634 SUPPORTED_JSON_PATH_PARTS = { 635 exp.JSONPathKey, 636 exp.JSONPathRoot, 637 exp.JSONPathSubscript, 638 } 639 640 TYPE_MAPPING = { 641 **generator.Generator.TYPE_MAPPING, 642 exp.DType.BIGDECIMAL: "DOUBLE", 643 exp.DType.JSON: "VARIANT", 644 exp.DType.NESTED: "OBJECT", 645 exp.DType.STRUCT: "OBJECT", 646 exp.DType.TEXT: "VARCHAR", 647 } 648 649 TOKEN_MAPPING = { 650 TokenType.AUTO_INCREMENT: "AUTOINCREMENT", 651 } 652 653 PROPERTIES_LOCATION = { 654 **generator.Generator.PROPERTIES_LOCATION, 655 exp.CredentialsProperty: exp.Properties.Location.POST_WITH, 656 exp.InteractiveProperty: exp.Properties.Location.POST_CREATE, 657 exp.LocationProperty: exp.Properties.Location.POST_WITH, 658 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 659 exp.RowAccessProperty: exp.Properties.Location.POST_SCHEMA, 660 exp.SetProperty: exp.Properties.Location.UNSUPPORTED, 661 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 662 } 663 664 UNSUPPORTED_VALUES_EXPRESSIONS: t.ClassVar = { 665 exp.Map, 666 exp.StarMap, 667 exp.Struct, 668 exp.VarMap, 669 } 670 671 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS = (exp.ArrayAgg,) 672 673 def with_properties(self, properties: exp.Properties) -> str: 674 return self.properties(properties, wrapped=False, prefix=self.sep(""), sep=" ") 675 676 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 677 if expression.find(*self.UNSUPPORTED_VALUES_EXPRESSIONS): 678 values_as_table = False 679 680 return super().values_sql(expression, values_as_table=values_as_table) 681 682 def datatype_sql(self, expression: exp.DataType) -> str: 683 # Check if this is a FLOAT type nested inside a VECTOR type 684 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 685 # https://docs.snowflake.com/en/sql-reference/data-types-vector 686 if expression.is_type(exp.DType.DOUBLE): 687 parent = expression.parent 688 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 689 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 690 return "FLOAT" 691 692 expressions = expression.expressions 693 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 694 for field_type in expressions: 695 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 696 if isinstance(field_type, exp.DataType): 697 return "OBJECT" 698 if ( 699 isinstance(field_type, exp.ColumnDef) 700 and field_type.this 701 and field_type.this.is_string 702 ): 703 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 704 # converting 'foo' into an identifier, we also need to quote it because these 705 # keys are case-sensitive. For example: 706 # 707 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 708 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 709 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 710 711 return super().datatype_sql(expression) 712 713 def tonumber_sql(self, expression: exp.ToNumber) -> str: 714 precision = expression.args.get("precision") 715 scale = expression.args.get("scale") 716 717 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 718 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 719 720 if default_precision and default_scale: 721 precision = None 722 scale = None 723 elif default_scale: 724 scale = None 725 726 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 727 728 return self.func( 729 func_name, 730 expression.this, 731 expression.args.get("format"), 732 precision, 733 scale, 734 ) 735 736 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 737 milli = expression.args.get("milli") 738 if milli is not None: 739 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 740 expression.set("nano", milli_to_nano) 741 742 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression) 743 744 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 745 if expression.is_type(exp.DType.GEOGRAPHY): 746 return self.func("TO_GEOGRAPHY", expression.this) 747 if expression.is_type(exp.DType.GEOMETRY): 748 return self.func("TO_GEOMETRY", expression.this) 749 750 return super().cast_sql(expression, safe_prefix=safe_prefix) 751 752 def trycast_sql(self, expression: exp.TryCast) -> str: 753 value = expression.this 754 755 if value.type is None: 756 from sqlglot.optimizer.annotate_types import annotate_types 757 758 value = annotate_types(value, dialect=self.dialect) 759 760 # Snowflake requires that TRY_CAST's value be a string 761 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 762 # if we can deduce that the value is a string, then we can generate TRY_CAST 763 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 764 return super().trycast_sql(expression) 765 766 return self.cast_sql(expression) 767 768 def log_sql(self, expression: exp.Log) -> str: 769 if not expression.expression: 770 return self.func("LN", expression.this) 771 772 return super().log_sql(expression) 773 774 def greatest_sql(self, expression: exp.Greatest) -> str: 775 name = "GREATEST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "GREATEST" 776 return self.func(name, expression.this, *expression.expressions) 777 778 def least_sql(self, expression: exp.Least) -> str: 779 name = "LEAST_IGNORE_NULLS" if expression.args.get("ignore_nulls") else "LEAST" 780 return self.func(name, expression.this, *expression.expressions) 781 782 def generator_sql(self, expression: exp.Generator) -> str: 783 args = [] 784 rowcount = expression.args.get("rowcount") 785 timelimit = expression.args.get("timelimit") 786 787 if rowcount: 788 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 789 if timelimit: 790 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 791 792 return self.func("GENERATOR", *args) 793 794 def unnest_sql(self, expression: exp.Unnest) -> str: 795 unnest_alias = expression.args.get("alias") 796 offset = expression.args.get("offset") 797 798 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 799 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 800 801 columns = [ 802 exp.to_identifier("seq"), 803 exp.to_identifier("key"), 804 exp.to_identifier("path"), 805 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 806 value, 807 exp.to_identifier("this"), 808 ] 809 810 if unnest_alias: 811 unnest_alias.set("columns", columns) 812 else: 813 unnest_alias = exp.TableAlias(this="_u", columns=columns) 814 815 table_input = self.sql(expression.expressions[0]) 816 if not table_input.startswith("INPUT =>"): 817 table_input = f"INPUT => {table_input}" 818 819 expression_parent = expression.parent 820 821 explode = ( 822 f"FLATTEN({table_input})" 823 if isinstance(expression_parent, exp.Lateral) 824 else f"TABLE(FLATTEN({table_input}))" 825 ) 826 alias = self.sql(unnest_alias) 827 alias = f" AS {alias}" if alias else "" 828 value = ( 829 "" 830 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 831 else f"{value} FROM " 832 ) 833 834 return f"{value}{explode}{alias}" 835 836 def undrop_sql(self, expression: exp.Undrop) -> str: 837 this = self.sql(expression, "this") 838 kind = expression.kind 839 rename = self.sql(expression, "rename") 840 rename = f" RENAME TO {rename}" if rename else "" 841 return f"UNDROP {kind} {this}{rename}" 842 843 def show_sql(self, expression: exp.Show) -> str: 844 terse = "TERSE " if expression.args.get("terse") else "" 845 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 846 history = " HISTORY" if expression.args.get("history") else "" 847 like = self.sql(expression, "like") 848 like = f" LIKE {like}" if like else "" 849 850 scope = self.sql(expression, "scope") 851 scope = f" {scope}" if scope else "" 852 853 scope_kind = self.sql(expression, "scope_kind") 854 if scope_kind: 855 scope_kind = f" IN {scope_kind}" 856 857 starts_with = self.sql(expression, "starts_with") 858 if starts_with: 859 starts_with = f" STARTS WITH {starts_with}" 860 861 limit = self.sql(expression, "limit") 862 863 from_ = self.sql(expression, "from_") 864 if from_: 865 from_ = f" FROM {from_}" 866 867 privileges = self.expressions(expression, key="privileges", flat=True) 868 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 869 870 return f"SHOW {terse}{iceberg}{expression.name}{history}{like}{scope_kind}{scope}{starts_with}{limit}{from_}{privileges}" 871 872 def rowaccessproperty_sql(self, expression: exp.RowAccessProperty) -> str: 873 if not expression.this: 874 return "ROW ACCESS" 875 on = f" ON ({self.expressions(expression, flat=True)})" if expression.expressions else "" 876 return f"WITH ROW ACCESS POLICY {self.sql(expression, 'this')}{on}" 877 878 def describe_sql(self, expression: exp.Describe) -> str: 879 kind_value = expression.args.get("kind") or "TABLE" 880 881 properties = expression.args.get("properties") 882 if properties: 883 qualifier = self.expressions(properties, sep=" ") 884 kind = f" {qualifier} {kind_value}" 885 else: 886 kind = f" {kind_value}" 887 888 this = f" {self.sql(expression, 'this')}" 889 expressions = self.expressions(expression, flat=True) 890 expressions = f" {expressions}" if expressions else "" 891 return f"DESCRIBE{kind}{this}{expressions}" 892 893 def generatedasidentitycolumnconstraint_sql( 894 self, expression: exp.GeneratedAsIdentityColumnConstraint 895 ) -> str: 896 start = expression.args.get("start") 897 start = f" START {start}" if start else "" 898 increment = expression.args.get("increment") 899 increment = f" INCREMENT {increment}" if increment else "" 900 901 order = expression.args.get("order") 902 if order is not None: 903 order_clause = " ORDER" if order else " NOORDER" 904 else: 905 order_clause = "" 906 907 return f"AUTOINCREMENT{start}{increment}{order_clause}" 908 909 def struct_sql(self, expression: exp.Struct) -> str: 910 if len(expression.expressions) == 1: 911 arg = expression.expressions[0] 912 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 913 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 914 return f"{{{self.sql(expression.expressions[0])}}}" 915 916 keys = [] 917 values = [] 918 919 for i, e in enumerate(expression.expressions): 920 if isinstance(e, exp.PropertyEQ): 921 keys.append( 922 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 923 ) 924 values.append(e.expression) 925 else: 926 keys.append(exp.Literal.string(f"_{i}")) 927 values.append(e) 928 929 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values))) 930 931 @unsupported_args("weight", "accuracy") 932 def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str: 933 return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile")) 934 935 def alterset_sql(self, expression: exp.AlterSet) -> str: 936 exprs = self.expressions(expression, flat=True) 937 exprs = f" {exprs}" if exprs else "" 938 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 939 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 940 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 941 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 942 tag = self.expressions(expression, key="tag", flat=True) 943 tag = f" TAG {tag}" if tag else "" 944 945 return f"SET{exprs}{file_format}{copy_options}{tag}" 946 947 def strtotime_sql(self, expression: exp.StrToTime): 948 # target_type is stored as a DataType instance 949 target_type = expression.args.get("target_type") 950 951 # Get the type enum from DataType instance or from type annotation 952 if isinstance(target_type, exp.DataType): 953 type_enum = target_type.this 954 elif expression.type: 955 type_enum = expression.type.this 956 else: 957 type_enum = exp.DType.TIMESTAMP 958 959 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 960 961 return self.func( 962 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 963 expression.this, 964 self.format_time(expression), 965 ) 966 967 def timestampsub_sql(self, expression: exp.TimestampSub): 968 return self.sql( 969 exp.TimestampAdd( 970 this=expression.this, 971 expression=expression.expression * -1, 972 unit=expression.unit, 973 ) 974 ) 975 976 def jsonextract_sql(self, expression: exp.JSONExtract): 977 this = expression.this 978 979 # JSON strings are valid coming from other dialects such as BQ so 980 # for these cases we PARSE_JSON preemptively 981 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 982 "requires_json" 983 ): 984 this = exp.ParseJSON(this=this) 985 986 return self.func( 987 "GET_PATH", 988 this, 989 expression.expression, 990 ) 991 992 def timetostr_sql(self, expression: exp.TimeToStr) -> str: 993 this = expression.this 994 if this.is_string: 995 this = exp.cast(this, exp.DType.TIMESTAMP) 996 997 return self.func("TO_CHAR", this, self.format_time(expression)) 998 999 def datesub_sql(self, expression: exp.DateSub) -> str: 1000 value = expression.expression 1001 if value: 1002 value.replace(value * (-1)) 1003 else: 1004 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1005 1006 return date_delta_sql("DATEADD")(self, expression) 1007 1008 def select_sql(self, expression: exp.Select) -> str: 1009 limit = expression.args.get("limit") 1010 offset = expression.args.get("offset") 1011 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1012 expression.limit(exp.Null(), copy=False) 1013 return super().select_sql(expression) 1014 1015 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1016 is_materialized = expression.find(exp.MaterializedProperty) 1017 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1018 1019 if expression.kind == "VIEW" and is_materialized and grants_property: 1020 # Materialized views require COPY/IGNORE GRANTS before the column list, 1021 # whereas normal views use the default POST_SCHEMA location. 1022 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1023 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1024 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1025 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1026 1027 this_name = self.sql(expression.this, "this") 1028 grants = self.sql(grants_property) 1029 this_schema = self.schema_columns_sql(expression.this) 1030 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1031 1032 return f"{this_name}{self.sep()}{grants}{this_schema}" 1033 1034 return super().createable_sql(expression, locations) 1035 1036 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1037 this = expression.this 1038 1039 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1040 # and add it later as part of the WITHIN GROUP clause 1041 order = this if isinstance(this, exp.Order) else None 1042 if order: 1043 expression.set("this", order.this.pop()) 1044 1045 expr_sql = super().arrayagg_sql(expression) 1046 1047 if order: 1048 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1049 1050 return expr_sql 1051 1052 def arraydistinct_sql(self, expression: exp.ArrayDistinct) -> str: 1053 if expression.args.get("check_null"): 1054 return self.func("ARRAY_DISTINCT", expression.this) 1055 return self.func("ARRAY_DISTINCT", exp.ArrayCompact(this=expression.this)) 1056 1057 def arraytostring_sql(self, expression: exp.ArrayToString) -> str: 1058 return self.func("ARRAY_TO_STRING", expression.this, expression.expression) 1059 1060 def array_sql(self, expression: exp.Array) -> str: 1061 expressions = expression.expressions 1062 1063 first_expr = seq_get(expressions, 0) 1064 if isinstance(first_expr, exp.Select): 1065 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1066 if first_expr.text("kind").upper() == "STRUCT": 1067 object_construct_args = [] 1068 for expr in first_expr.expressions: 1069 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1070 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1071 name = expr.this if isinstance(expr, exp.Alias) else expr 1072 1073 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1074 1075 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1076 1077 first_expr.set("kind", None) 1078 first_expr.set("expressions", [array_agg]) 1079 1080 return self.sql(first_expr.subquery()) 1081 1082 return inline_array_sql(self, expression) 1083 1084 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1085 zone = self.sql(expression, "this") 1086 if not zone: 1087 return super().currentdate_sql(expression) 1088 1089 expr = exp.Cast( 1090 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1091 to=exp.DataType(this=exp.DType.DATE), 1092 ) 1093 return self.sql(expr) 1094 1095 def dot_sql(self, expression: exp.Dot) -> str: 1096 this = expression.this 1097 1098 if not this.type: 1099 from sqlglot.optimizer.annotate_types import annotate_types 1100 1101 this = annotate_types(this, dialect=self.dialect) 1102 1103 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1104 # Generate colon notation for the top level STRUCT 1105 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1106 1107 return super().dot_sql(expression) 1108 1109 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 1110 return f"{self.sql(expression, 'this')}!{self.sql(expression, 'expression')}" 1111 1112 def format_sql(self, expression: exp.Format) -> str: 1113 if expression.name.lower() == "%s" and len(expression.expressions) == 1: 1114 return self.func("TO_CHAR", expression.expressions[0]) 1115 1116 return self.function_fallback_sql(expression) 1117 1118 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1119 # Set part_index to 1 if missing 1120 if not expression.args.get("delimiter"): 1121 expression.set("delimiter", exp.Literal.string(" ")) 1122 1123 if not expression.args.get("part_index"): 1124 expression.set("part_index", exp.Literal.number(1)) 1125 1126 return rename_func("SPLIT_PART")(self, expression) 1127 1128 def uniform_sql(self, expression: exp.Uniform) -> str: 1129 gen = expression.args.get("gen") 1130 seed = expression.args.get("seed") 1131 1132 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1133 if seed: 1134 gen = exp.Rand(this=seed) 1135 1136 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1137 if not gen: 1138 gen = exp.Rand() 1139 1140 return self.func("UNIFORM", expression.this, expression.expression, gen) 1141 1142 def window_sql(self, expression: exp.Window) -> str: 1143 spec = expression.args.get("spec") 1144 this = expression.this 1145 1146 if ( 1147 ( 1148 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1149 or ( 1150 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1151 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1152 ) 1153 ) 1154 and spec 1155 and ( 1156 spec.text("kind").upper() == "ROWS" 1157 and spec.text("start").upper() == "UNBOUNDED" 1158 and spec.text("start_side").upper() == "PRECEDING" 1159 and spec.text("end").upper() == "UNBOUNDED" 1160 and spec.text("end_side").upper() == "FOLLOWING" 1161 ) 1162 ): 1163 # omit the default window from window ranking functions 1164 expression.set("spec", None) 1165 return super().window_sql(expression) 1166 1167 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1168 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1169 # accepts the value to aggregate as an argument: MODE(<expr>) 1170 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1171 order = expression.expression 1172 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1173 return self.sql(exp.Mode(this=order.expressions[0].this)) 1174 1175 return super().withingroup_sql(expression)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMax'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMin'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Array'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function array_concat_sql.<locals>._array_concat_sql>, <class 'sqlglot.expressions.array.ArrayAppend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayPrepend'>: <function array_append_sql.<locals>._array_append_sql>, <class 'sqlglot.expressions.array.ArrayContains'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ArrayPosition'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ArrayIntersect'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySort'>: <function _array_sort_sql>, <class 'sqlglot.expressions.core.AtTimeZone'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.core.BitwiseOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseXor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseNot'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseLeftShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.BitwiseRightShift'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentSchemas'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Localtime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Localtimestamp'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DatetimeAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DatetimeDiff'>: <function timestampdiff_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.string.Decrypt'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.DecryptRaw'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.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.properties.InteractiveProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONArray'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONExtractArray'>: <function _json_extract_value_array_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONKeys'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.JSONValueArray'>: <function _json_extract_value_array_sql>, <class 'sqlglot.expressions.string.Levenshtein'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Map'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.math.ManhattanDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.MakeInterval'>: <function no_make_interval_sql>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.aggregate.NthValue'>: <function nth_value_from_sql>, <class 'sqlglot.expressions.json.ParseJSON'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToBinary'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.ToBoolean'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToDouble'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.ToFile'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONFormat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.PercentileCont'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.aggregate.PercentileDisc'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.query.Pivot'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function _regexpextract_sql>, <class 'sqlglot.expressions.string.RegexpExtractAll'>: <function _regexpextract_sql>, <class 'sqlglot.expressions.string.RegexpILike'>: <function _regexpilike_sql>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5NumberLower64'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5NumberUpper64'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Hex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.LowerHex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Skewness'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StarMap'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StartsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.EndsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.Rand'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.StringToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StrtokToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Stuff'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.StPoint'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimeAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimeSlice'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Timestamp'>: <function no_timestamp_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimestampDiff'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.array.ToArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ToChar'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TsOrDsToDate'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToTime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.Unhex'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Uuid'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.Booland'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.Boolor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.WeekOfYear'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.YearOfWeek'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.YearOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.ByteLength'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Flatten'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArrayConcatAgg'>: <function SnowflakeGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function SnowflakeGenerator.<lambda>>}
627 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 628 this = self.func("IDENTIFIER", expression.this) 629 if "expressions" in expression.args: 630 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 631 return self.func(this, *expression.expressions, normalize=False) 632 return this
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathKey'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathRoot'>}
TYPE_MAPPING =
{<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'VARBINARY', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP', <DType.BIGDECIMAL: 'BIGDECIMAL'>: 'DOUBLE', <DType.JSON: 'JSON'>: 'VARIANT', <DType.NESTED: 'NESTED'>: 'OBJECT', <DType.STRUCT: 'STRUCT'>: 'OBJECT', <DType.TEXT: 'TEXT'>: 'VARCHAR'}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>}
UNSUPPORTED_VALUES_EXPRESSIONS: ClassVar =
{<class 'sqlglot.expressions.array.Struct'>, <class 'sqlglot.expressions.array.Map'>, <class 'sqlglot.expressions.array.VarMap'>, <class 'sqlglot.expressions.array.StarMap'>}
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS =
(<class 'sqlglot.expressions.aggregate.ArrayAgg'>,)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
682 def datatype_sql(self, expression: exp.DataType) -> str: 683 # Check if this is a FLOAT type nested inside a VECTOR type 684 # VECTOR only accepts FLOAT (not DOUBLE), INT, and STRING as element types 685 # https://docs.snowflake.com/en/sql-reference/data-types-vector 686 if expression.is_type(exp.DType.DOUBLE): 687 parent = expression.parent 688 if isinstance(parent, exp.DataType) and parent.is_type(exp.DType.VECTOR): 689 # Preserve FLOAT for VECTOR types instead of mapping to synonym DOUBLE 690 return "FLOAT" 691 692 expressions = expression.expressions 693 if expressions and expression.is_type(*exp.DataType.STRUCT_TYPES): 694 for field_type in expressions: 695 # The correct syntax is OBJECT [ (<key> <value_type [NOT NULL] [, ...]) ] 696 if isinstance(field_type, exp.DataType): 697 return "OBJECT" 698 if ( 699 isinstance(field_type, exp.ColumnDef) 700 and field_type.this 701 and field_type.this.is_string 702 ): 703 # Doing OBJECT('foo' VARCHAR) is invalid snowflake Syntax. Moreover, besides 704 # converting 'foo' into an identifier, we also need to quote it because these 705 # keys are case-sensitive. For example: 706 # 707 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:x FROM t -- correct 708 # WITH t AS (SELECT OBJECT_CONSTRUCT('x', 'y') AS c) SELECT c:X FROM t -- incorrect, returns NULL 709 field_type.this.replace(exp.to_identifier(field_type.name, quoted=True)) 710 711 return super().datatype_sql(expression)
713 def tonumber_sql(self, expression: exp.ToNumber) -> str: 714 precision = expression.args.get("precision") 715 scale = expression.args.get("scale") 716 717 default_precision = isinstance(precision, exp.Literal) and precision.name == "38" 718 default_scale = isinstance(scale, exp.Literal) and scale.name == "0" 719 720 if default_precision and default_scale: 721 precision = None 722 scale = None 723 elif default_scale: 724 scale = None 725 726 func_name = "TRY_TO_NUMBER" if expression.args.get("safe") else "TO_NUMBER" 727 728 return self.func( 729 func_name, 730 expression.this, 731 expression.args.get("format"), 732 precision, 733 scale, 734 )
def
timestampfromparts_sql(self, expression: sqlglot.expressions.temporal.TimestampFromParts) -> str:
736 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 737 milli = expression.args.get("milli") 738 if milli is not None: 739 milli_to_nano = milli.pop() * exp.Literal.number(1000000) 740 expression.set("nano", milli_to_nano) 741 742 return rename_func("TIMESTAMP_FROM_PARTS")(self, expression)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
744 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 745 if expression.is_type(exp.DType.GEOGRAPHY): 746 return self.func("TO_GEOGRAPHY", expression.this) 747 if expression.is_type(exp.DType.GEOMETRY): 748 return self.func("TO_GEOMETRY", expression.this) 749 750 return super().cast_sql(expression, safe_prefix=safe_prefix)
752 def trycast_sql(self, expression: exp.TryCast) -> str: 753 value = expression.this 754 755 if value.type is None: 756 from sqlglot.optimizer.annotate_types import annotate_types 757 758 value = annotate_types(value, dialect=self.dialect) 759 760 # Snowflake requires that TRY_CAST's value be a string 761 # If TRY_CAST is being roundtripped (since Snowflake is the only dialect that sets "requires_string") or 762 # if we can deduce that the value is a string, then we can generate TRY_CAST 763 if expression.args.get("requires_string") or value.is_type(*exp.DataType.TEXT_TYPES): 764 return super().trycast_sql(expression) 765 766 return self.cast_sql(expression)
782 def generator_sql(self, expression: exp.Generator) -> str: 783 args = [] 784 rowcount = expression.args.get("rowcount") 785 timelimit = expression.args.get("timelimit") 786 787 if rowcount: 788 args.append(exp.Kwarg(this=exp.var("ROWCOUNT"), expression=rowcount)) 789 if timelimit: 790 args.append(exp.Kwarg(this=exp.var("TIMELIMIT"), expression=timelimit)) 791 792 return self.func("GENERATOR", *args)
794 def unnest_sql(self, expression: exp.Unnest) -> str: 795 unnest_alias = expression.args.get("alias") 796 offset = expression.args.get("offset") 797 798 unnest_alias_columns = unnest_alias.columns if unnest_alias else [] 799 value = seq_get(unnest_alias_columns, 0) or exp.to_identifier("value") 800 801 columns = [ 802 exp.to_identifier("seq"), 803 exp.to_identifier("key"), 804 exp.to_identifier("path"), 805 offset.pop() if isinstance(offset, exp.Expr) else exp.to_identifier("index"), 806 value, 807 exp.to_identifier("this"), 808 ] 809 810 if unnest_alias: 811 unnest_alias.set("columns", columns) 812 else: 813 unnest_alias = exp.TableAlias(this="_u", columns=columns) 814 815 table_input = self.sql(expression.expressions[0]) 816 if not table_input.startswith("INPUT =>"): 817 table_input = f"INPUT => {table_input}" 818 819 expression_parent = expression.parent 820 821 explode = ( 822 f"FLATTEN({table_input})" 823 if isinstance(expression_parent, exp.Lateral) 824 else f"TABLE(FLATTEN({table_input}))" 825 ) 826 alias = self.sql(unnest_alias) 827 alias = f" AS {alias}" if alias else "" 828 value = ( 829 "" 830 if isinstance(expression_parent, (exp.From, exp.Join, exp.Lateral)) 831 else f"{value} FROM " 832 ) 833 834 return f"{value}{explode}{alias}"
843 def show_sql(self, expression: exp.Show) -> str: 844 terse = "TERSE " if expression.args.get("terse") else "" 845 iceberg = "ICEBERG " if expression.args.get("iceberg") else "" 846 history = " HISTORY" if expression.args.get("history") else "" 847 like = self.sql(expression, "like") 848 like = f" LIKE {like}" if like else "" 849 850 scope = self.sql(expression, "scope") 851 scope = f" {scope}" if scope else "" 852 853 scope_kind = self.sql(expression, "scope_kind") 854 if scope_kind: 855 scope_kind = f" IN {scope_kind}" 856 857 starts_with = self.sql(expression, "starts_with") 858 if starts_with: 859 starts_with = f" STARTS WITH {starts_with}" 860 861 limit = self.sql(expression, "limit") 862 863 from_ = self.sql(expression, "from_") 864 if from_: 865 from_ = f" FROM {from_}" 866 867 privileges = self.expressions(expression, key="privileges", flat=True) 868 privileges = f" WITH PRIVILEGES {privileges}" if privileges else "" 869 870 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:
878 def describe_sql(self, expression: exp.Describe) -> str: 879 kind_value = expression.args.get("kind") or "TABLE" 880 881 properties = expression.args.get("properties") 882 if properties: 883 qualifier = self.expressions(properties, sep=" ") 884 kind = f" {qualifier} {kind_value}" 885 else: 886 kind = f" {kind_value}" 887 888 this = f" {self.sql(expression, 'this')}" 889 expressions = self.expressions(expression, flat=True) 890 expressions = f" {expressions}" if expressions else "" 891 return f"DESCRIBE{kind}{this}{expressions}"
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint) -> str:
893 def generatedasidentitycolumnconstraint_sql( 894 self, expression: exp.GeneratedAsIdentityColumnConstraint 895 ) -> str: 896 start = expression.args.get("start") 897 start = f" START {start}" if start else "" 898 increment = expression.args.get("increment") 899 increment = f" INCREMENT {increment}" if increment else "" 900 901 order = expression.args.get("order") 902 if order is not None: 903 order_clause = " ORDER" if order else " NOORDER" 904 else: 905 order_clause = "" 906 907 return f"AUTOINCREMENT{start}{increment}{order_clause}"
909 def struct_sql(self, expression: exp.Struct) -> str: 910 if len(expression.expressions) == 1: 911 arg = expression.expressions[0] 912 if arg.is_star or (isinstance(arg, exp.ILike) and arg.left.is_star): 913 # Wildcard syntax: https://docs.snowflake.com/en/sql-reference/data-types-semistructured#object 914 return f"{{{self.sql(expression.expressions[0])}}}" 915 916 keys = [] 917 values = [] 918 919 for i, e in enumerate(expression.expressions): 920 if isinstance(e, exp.PropertyEQ): 921 keys.append( 922 exp.Literal.string(e.name) if isinstance(e.this, exp.Identifier) else e.this 923 ) 924 values.append(e.expression) 925 else: 926 keys.append(exp.Literal.string(f"_{i}")) 927 values.append(e) 928 929 return self.func("OBJECT_CONSTRUCT", *flatten(zip(keys, values)))
@unsupported_args('weight', 'accuracy')
def
approxquantile_sql(self, expression: sqlglot.expressions.aggregate.ApproxQuantile) -> str:
935 def alterset_sql(self, expression: exp.AlterSet) -> str: 936 exprs = self.expressions(expression, flat=True) 937 exprs = f" {exprs}" if exprs else "" 938 file_format = self.expressions(expression, key="file_format", flat=True, sep=" ") 939 file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else "" 940 copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ") 941 copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else "" 942 tag = self.expressions(expression, key="tag", flat=True) 943 tag = f" TAG {tag}" if tag else "" 944 945 return f"SET{exprs}{file_format}{copy_options}{tag}"
947 def strtotime_sql(self, expression: exp.StrToTime): 948 # target_type is stored as a DataType instance 949 target_type = expression.args.get("target_type") 950 951 # Get the type enum from DataType instance or from type annotation 952 if isinstance(target_type, exp.DataType): 953 type_enum = target_type.this 954 elif expression.type: 955 type_enum = expression.type.this 956 else: 957 type_enum = exp.DType.TIMESTAMP 958 959 func_name = TIMESTAMP_TYPES.get(type_enum, "TO_TIMESTAMP") 960 961 return self.func( 962 f"{'TRY_' if expression.args.get('safe') else ''}{func_name}", 963 expression.this, 964 self.format_time(expression), 965 )
976 def jsonextract_sql(self, expression: exp.JSONExtract): 977 this = expression.this 978 979 # JSON strings are valid coming from other dialects such as BQ so 980 # for these cases we PARSE_JSON preemptively 981 if not isinstance(this, (exp.ParseJSON, exp.JSONExtract)) and not expression.args.get( 982 "requires_json" 983 ): 984 this = exp.ParseJSON(this=this) 985 986 return self.func( 987 "GET_PATH", 988 this, 989 expression.expression, 990 )
999 def datesub_sql(self, expression: exp.DateSub) -> str: 1000 value = expression.expression 1001 if value: 1002 value.replace(value * (-1)) 1003 else: 1004 self.unsupported("DateSub cannot be transpiled if the subtracted count is unknown") 1005 1006 return date_delta_sql("DATEADD")(self, expression)
1008 def select_sql(self, expression: exp.Select) -> str: 1009 limit = expression.args.get("limit") 1010 offset = expression.args.get("offset") 1011 if offset and (not limit or (isinstance(limit, exp.Limit) and limit.is_limit_all)): 1012 expression.limit(exp.Null(), copy=False) 1013 return super().select_sql(expression)
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
1015 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1016 is_materialized = expression.find(exp.MaterializedProperty) 1017 grants_property = expression.find(exp.CopyGrantsProperty, exp.IgnoreGrantsProperty) 1018 1019 if expression.kind == "VIEW" and is_materialized and grants_property: 1020 # Materialized views require COPY/IGNORE GRANTS before the column list, 1021 # whereas normal views use the default POST_SCHEMA location. 1022 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax 1023 # ref: https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax 1024 post_schema_properties = locations[exp.Properties.Location.POST_SCHEMA] 1025 post_schema_properties.pop(post_schema_properties.index(grants_property)) 1026 1027 this_name = self.sql(expression.this, "this") 1028 grants = self.sql(grants_property) 1029 this_schema = self.schema_columns_sql(expression.this) 1030 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 1031 1032 return f"{this_name}{self.sep()}{grants}{this_schema}" 1033 1034 return super().createable_sql(expression, locations)
1036 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 1037 this = expression.this 1038 1039 # If an ORDER BY clause is present, we need to remove it from ARRAY_AGG 1040 # and add it later as part of the WITHIN GROUP clause 1041 order = this if isinstance(this, exp.Order) else None 1042 if order: 1043 expression.set("this", order.this.pop()) 1044 1045 expr_sql = super().arrayagg_sql(expression) 1046 1047 if order: 1048 expr_sql = self.sql(exp.WithinGroup(this=expr_sql, expression=order)) 1049 1050 return expr_sql
1060 def array_sql(self, expression: exp.Array) -> str: 1061 expressions = expression.expressions 1062 1063 first_expr = seq_get(expressions, 0) 1064 if isinstance(first_expr, exp.Select): 1065 # SELECT AS STRUCT foo AS alias_foo -> ARRAY_AGG(OBJECT_CONSTRUCT('alias_foo', foo)) 1066 if first_expr.text("kind").upper() == "STRUCT": 1067 object_construct_args = [] 1068 for expr in first_expr.expressions: 1069 # Alias case: SELECT AS STRUCT foo AS alias_foo -> OBJECT_CONSTRUCT('alias_foo', foo) 1070 # Column case: SELECT AS STRUCT foo -> OBJECT_CONSTRUCT('foo', foo) 1071 name = expr.this if isinstance(expr, exp.Alias) else expr 1072 1073 object_construct_args.extend([exp.Literal.string(expr.alias_or_name), name]) 1074 1075 array_agg = exp.ArrayAgg(this=build_object_construct(args=object_construct_args)) 1076 1077 first_expr.set("kind", None) 1078 first_expr.set("expressions", [array_agg]) 1079 1080 return self.sql(first_expr.subquery()) 1081 1082 return inline_array_sql(self, expression)
1084 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1085 zone = self.sql(expression, "this") 1086 if not zone: 1087 return super().currentdate_sql(expression) 1088 1089 expr = exp.Cast( 1090 this=exp.ConvertTimezone(target_tz=zone, timestamp=exp.CurrentTimestamp()), 1091 to=exp.DataType(this=exp.DType.DATE), 1092 ) 1093 return self.sql(expr)
1095 def dot_sql(self, expression: exp.Dot) -> str: 1096 this = expression.this 1097 1098 if not this.type: 1099 from sqlglot.optimizer.annotate_types import annotate_types 1100 1101 this = annotate_types(this, dialect=self.dialect) 1102 1103 if not isinstance(this, exp.Dot) and this.is_type(exp.DType.STRUCT): 1104 # Generate colon notation for the top level STRUCT 1105 return f"{self.sql(this)}:{self.sql(expression, 'expression')}" 1106 1107 return super().dot_sql(expression)
1118 def splitpart_sql(self, expression: exp.SplitPart) -> str: 1119 # Set part_index to 1 if missing 1120 if not expression.args.get("delimiter"): 1121 expression.set("delimiter", exp.Literal.string(" ")) 1122 1123 if not expression.args.get("part_index"): 1124 expression.set("part_index", exp.Literal.number(1)) 1125 1126 return rename_func("SPLIT_PART")(self, expression)
1128 def uniform_sql(self, expression: exp.Uniform) -> str: 1129 gen = expression.args.get("gen") 1130 seed = expression.args.get("seed") 1131 1132 # From Databricks UNIFORM(min, max, seed) -> Wrap gen in RANDOM(seed) 1133 if seed: 1134 gen = exp.Rand(this=seed) 1135 1136 # No gen argument (from Databricks 2-arg UNIFORM(min, max)) -> Add RANDOM() 1137 if not gen: 1138 gen = exp.Rand() 1139 1140 return self.func("UNIFORM", expression.this, expression.expression, gen)
1142 def window_sql(self, expression: exp.Window) -> str: 1143 spec = expression.args.get("spec") 1144 this = expression.this 1145 1146 if ( 1147 ( 1148 isinstance(this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1149 or ( 1150 isinstance(this, (exp.RespectNulls, exp.IgnoreNulls)) 1151 and isinstance(this.this, RANKING_WINDOW_FUNCTIONS_WITH_FRAME) 1152 ) 1153 ) 1154 and spec 1155 and ( 1156 spec.text("kind").upper() == "ROWS" 1157 and spec.text("start").upper() == "UNBOUNDED" 1158 and spec.text("start_side").upper() == "PRECEDING" 1159 and spec.text("end").upper() == "UNBOUNDED" 1160 and spec.text("end_side").upper() == "FOLLOWING" 1161 ) 1162 ): 1163 # omit the default window from window ranking functions 1164 expression.set("spec", None) 1165 return super().window_sql(expression)
1167 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1168 # Snowflake's MODE doesn't support the ordered-set syntax, i.e. it only 1169 # accepts the value to aggregate as an argument: MODE(<expr>) 1170 if isinstance(expression.this, exp.Mode) and not expression.this.this: 1171 order = expression.expression 1172 if isinstance(order, exp.Order) and len(order.expressions) == 1: 1173 return self.sql(exp.Mode(this=order.expressions[0].this)) 1174 1175 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
- SUPPORTS_NEAREST_JOIN
- 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
- 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
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- identifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- locate_properties
- property_name
- property_sql
- uuidproperty_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- moduleproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- lockingstatement_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tablefromrows_sql
- tablesample_sql
- pivot_sql
- version_sql
- tuple_sql
- update_sql
- var_sql
- into_sql
- from_sql
- groupingsets_sql
- rollup_sql
- rollupindex_sql
- rollupproperty_sql
- cube_sql
- group_sql
- having_sql
- connectto_sql
- disconnect_sql
- connect_sql
- prior_sql
- join_sql
- nearest_sql
- lambda_sql
- lateral_op
- lateral_sql
- limit_sql
- offset_sql
- setitem_sql
- set_sql
- queryband_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- boolean_sql
- booland_sql
- boolor_sql
- order_sql
- withfill_sql
- cluster_sql
- clusterproperty_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognizemeasure_sql
- matchrecognize_sql
- query_modifiers
- options_modifier
- forclause_sql
- queryoption_sql
- offset_limit_modifiers
- after_limit_modifiers
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- prewhere_sql
- where_sql
- partition_by_sql
- partitionbyexcluding_sql
- windowspec_sql
- between_sql
- bracket_offset_expressions
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- 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
- teradatatitle_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
- nullif_zero_divisor
- 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
- min_sql
- max_sql
- timeslice_sql
- slice_sql
- apply_sql
- grant_sql
- revoke_sql
- grantprivilege_sql
- grantprincipal_sql
- columns_sql
- overlay_sql
- todouble_sql
- string_sql
- median_sql
- overflowtruncatebehavior_sql
- unixseconds_sql
- arraysort_sql
- 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