sqlglot.generators.tsql
1from __future__ import annotations 2 3from functools import reduce 4 5from sqlglot import exp, generator, transforms 6from sqlglot.dialects.dialect import ( 7 any_value_to_max_sql, 8 date_delta_sql, 9 datestrtodate_sql, 10 generatedasidentitycolumnconstraint_sql, 11 max_or_greatest, 12 min_or_least, 13 remove_ts_or_ds_to_date, 14 rename_func, 15 strposition_sql, 16 timestrtotime_sql, 17 trim_sql, 18) 19from sqlglot.helper import seq_get 20from sqlglot.optimizer.scope import find_in_scope 21from sqlglot.parsers.tsql import OPTIONS_THAT_REQUIRE_EQUAL 22from sqlglot.time import format_time 23from collections import defaultdict 24 25DATE_PART_UNMAPPING = { 26 "WEEKISO": "ISO_WEEK", 27 "DAYOFWEEK": "WEEKDAY", 28 "TIMEZONE_MINUTE": "TZOFFSET", 29} 30 31BIT_TYPES = {exp.EQ, exp.NEQ, exp.Is, exp.In, exp.Select, exp.Alias} 32 33SET_OP_MODIFIERS = ("limit", "offset", "order", "for_", "options") 34 35 36def _format_sql(self: TSQLGenerator, expression: exp.NumberToStr | exp.TimeToStr) -> str: 37 fmt = expression.args["format"] 38 39 if not isinstance(expression, exp.NumberToStr): 40 if fmt.is_string: 41 from sqlglot.dialects.tsql import TSQL 42 43 mapped_fmt = format_time(fmt.name, TSQL.INVERSE_TIME_MAPPING) 44 fmt_sql = self.sql(exp.Literal.string(mapped_fmt)) 45 else: 46 fmt_sql = self.format_time(expression) or self.sql(fmt) 47 else: 48 fmt_sql = self.sql(fmt) 49 50 return self.func("FORMAT", expression.this, fmt_sql, expression.args.get("culture")) 51 52 53def _string_agg_sql(self: TSQLGenerator, expression: exp.GroupConcat) -> str: 54 this = expression.this 55 distinct = find_in_scope(expression, exp.Distinct) 56 if distinct: 57 # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression 58 self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.") 59 this = distinct.pop().expressions[0] 60 61 order = "" 62 if isinstance(expression.this, exp.Order): 63 if expression.this.this: 64 this = expression.this.this.pop() 65 # Order has a leading space 66 order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})" 67 68 separator = expression.args.get("separator") or exp.Literal.string(",") 69 return f"STRING_AGG({self.format_args(this, separator)}){order}" 70 71 72def qualify_derived_table_outputs(expression: exp.Expr) -> exp.Expr: 73 """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.""" 74 alias = expression.args.get("alias") 75 76 if ( 77 isinstance(expression, (exp.CTE, exp.Subquery)) 78 and isinstance(alias, exp.TableAlias) 79 and not alias.columns 80 ): 81 from sqlglot.dialects.tsql import TSQL 82 from sqlglot.optimizer.qualify_columns import qualify_outputs 83 84 # We keep track of the unaliased column projection indexes instead of the expressions 85 # themselves, because the latter are going to be replaced by new nodes when the aliases 86 # are added and hence we won't be able to reach these newly added Alias parents 87 query = expression.this 88 unaliased_column_indexes = ( 89 i for i, c in enumerate(query.selects) if isinstance(c, exp.Column) and not c.alias 90 ) 91 92 qualify_outputs(query, dialect=TSQL()) 93 94 # Preserve the quoting information of columns for newly added Alias nodes 95 query_selects = query.selects 96 for select_index in unaliased_column_indexes: 97 alias = query_selects[select_index] 98 column = alias.this 99 if isinstance(column.this, exp.Identifier): 100 alias.args["alias"].set("quoted", column.this.quoted) 101 102 return expression 103 104 105def _json_extract_sql( 106 self: TSQLGenerator, expression: exp.JSONExtract | exp.JSONExtractScalar 107) -> str: 108 # JSON_QUERY returns objects and arrays, JSON_VALUE returns scalars. A scalar-only 109 # extraction maps to JSON_VALUE; a source that also returns non-scalar values as 110 # text (e.g. SQLite's ->>) needs to try both, like a generic JSONExtract does 111 if isinstance(expression, exp.JSONExtractScalar) and expression.args.get("scalar_only"): 112 return self.func("JSON_VALUE", expression.this, expression.expression) 113 114 json_query = self.func("JSON_QUERY", expression.this, expression.expression) 115 if expression.args.get("json_query"): 116 return json_query 117 118 json_value = self.func("JSON_VALUE", expression.this, expression.expression) 119 return self.func("ISNULL", json_query, json_value) 120 121 122def _timestrtotime_sql(self: TSQLGenerator, expression: exp.TimeStrToTime): 123 sql = timestrtotime_sql(self, expression) 124 if expression.args.get("zone"): 125 # If there is a timezone, produce an expression like: 126 # CAST('2020-01-01 12:13:14-08:00' AS DATETIMEOFFSET) AT TIME ZONE 'UTC' 127 # If you dont have AT TIME ZONE 'UTC', wrapping that expression in another cast back to DATETIME2 just drops the timezone information 128 return self.sql(exp.AtTimeZone(this=sql, zone=exp.Literal.string("UTC"))) 129 return sql 130 131 132class TSQLGenerator(generator.Generator): 133 SELECT_KINDS: tuple[str, ...] = () 134 TRY_SUPPORTED = False 135 SUPPORTS_UESCAPE = False 136 SUPPORTS_DECODE_CASE = False 137 138 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 139 140 LIMIT_IS_TOP = True 141 SET_OP_LIMITS = True 142 QUERY_HINTS = False 143 RETURNING_END = False 144 NVL2_SUPPORTED = False 145 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 146 LIMIT_FETCH = "FETCH" 147 COMPUTED_COLUMN_WITH_TYPE = False 148 CTE_RECURSIVE_KEYWORD_REQUIRED = False 149 ENSURE_BOOLS = True 150 NULL_ORDERING_SUPPORTED: bool | None = None 151 SUPPORTS_SINGLE_ARG_CONCAT = False 152 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 153 SUPPORTS_SELECT_INTO = True 154 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 155 SUPPORTS_TO_NUMBER = False 156 COPY_PARAMS_EQ_REQUIRED = True 157 PARSE_JSON_NAME: str | None = None 158 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 159 ALTER_SET_WRAPPED = True 160 ALTER_SET_TYPE = "" 161 SUPPORTS_ALTER_COLUMN_NULLABILITY = True 162 163 EXPRESSIONS_WITHOUT_NESTED_CTES = { 164 exp.Create, 165 exp.Delete, 166 exp.Insert, 167 exp.Intersect, 168 exp.Except, 169 exp.Merge, 170 exp.Select, 171 exp.Subquery, 172 exp.Union, 173 exp.Update, 174 } 175 176 SUPPORTED_JSON_PATH_PARTS = { 177 exp.JSONPathKey, 178 exp.JSONPathRoot, 179 exp.JSONPathSubscript, 180 } 181 182 TYPE_MAPPING = { 183 **{ 184 k: v 185 for k, v in generator.Generator.TYPE_MAPPING.items() 186 if k not in (exp.DType.NCHAR, exp.DType.NVARCHAR) 187 }, 188 exp.DType.BOOLEAN: "BIT", 189 exp.DType.DATETIME2: "DATETIME2", 190 exp.DType.DECIMAL: "NUMERIC", 191 exp.DType.DOUBLE: "FLOAT", 192 exp.DType.INT: "INTEGER", 193 exp.DType.ROWVERSION: "ROWVERSION", 194 exp.DType.TEXT: "VARCHAR(MAX)", 195 exp.DType.TIMESTAMP: "DATETIME2", 196 exp.DType.TIMESTAMPNTZ: "DATETIME2", 197 exp.DType.TIMESTAMPTZ: "DATETIMEOFFSET", 198 exp.DType.SMALLDATETIME: "SMALLDATETIME", 199 exp.DType.UTINYINT: "TINYINT", 200 exp.DType.VARIANT: "SQL_VARIANT", 201 exp.DType.UUID: "UNIQUEIDENTIFIER", 202 } 203 204 TRANSFORMS = { 205 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.ReturnsProperty}, 206 exp.AnyValue: any_value_to_max_sql, 207 exp.Atan2: rename_func("ATN2"), 208 exp.ArrayToString: rename_func("STRING_AGG"), 209 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 210 exp.Ceil: rename_func("CEILING"), 211 exp.Chr: rename_func("CHAR"), 212 exp.DateAdd: date_delta_sql("DATEADD"), 213 exp.CTE: transforms.preprocess([qualify_derived_table_outputs]), 214 exp.CurrentDate: rename_func("GETDATE"), 215 exp.CurrentTimestamp: rename_func("GETDATE"), 216 exp.CurrentTimestampLTZ: rename_func("SYSDATETIMEOFFSET"), 217 exp.DateStrToDate: datestrtodate_sql, 218 exp.Day: remove_ts_or_ds_to_date(), 219 exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql, 220 exp.GroupConcat: _string_agg_sql, 221 exp.If: rename_func("IIF"), 222 exp.JSONExtract: _json_extract_sql, 223 exp.JSONExtractScalar: _json_extract_sql, 224 exp.LastDay: lambda self, e: self.func("EOMONTH", e.this), 225 exp.Ln: rename_func("LOG"), 226 exp.Max: max_or_greatest, 227 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 228 exp.Min: min_or_least, 229 exp.Month: remove_ts_or_ds_to_date(), 230 exp.NumberToStr: _format_sql, 231 exp.Repeat: rename_func("REPLICATE"), 232 exp.CurrentSchema: rename_func("SCHEMA_NAME"), 233 exp.Select: transforms.preprocess( 234 [ 235 transforms.eliminate_distinct_on, 236 transforms.eliminate_semi_and_anti_joins, 237 transforms.eliminate_qualify, 238 transforms.unnest_generate_date_array_using_recursive_cte, 239 ] 240 ), 241 exp.Stddev: rename_func("STDEV"), 242 exp.StrPosition: lambda self, e: strposition_sql( 243 self, e, func_name="CHARINDEX", supports_position=True 244 ), 245 exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]), 246 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 247 exp.SHA1Digest: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 248 exp.SHA2: lambda self, e: self.func( 249 "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this 250 ), 251 exp.TemporaryProperty: lambda self, e: "", 252 exp.TimeStrToTime: _timestrtotime_sql, 253 exp.TimeToStr: _format_sql, 254 exp.TimestampAdd: date_delta_sql("DATEADD"), 255 exp.Trim: trim_sql, 256 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 257 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 258 exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this), 259 exp.Trunc: lambda self, e: self.func( 260 "ROUND", 261 e.this, 262 e.args.get("decimals") or exp.Literal.number(0), 263 exp.Literal.number(1), 264 ), 265 exp.Uuid: lambda *_: "NEWID()", 266 exp.Year: remove_ts_or_ds_to_date(), 267 exp.DateFromParts: rename_func("DATEFROMPARTS"), 268 } 269 270 PROPERTIES_LOCATION = { 271 **generator.Generator.PROPERTIES_LOCATION, 272 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 273 } 274 275 def scope_resolution(self, rhs: str, scope_name: str) -> str: 276 return f"{scope_name}::{rhs}" 277 278 def select_sql(self, expression: exp.Select) -> str: 279 self._prepare_limit_offset(expression) 280 281 # Handles transpiling a query like the following to T-SQL: 282 # SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x 283 if isinstance(expression.parent, exp.SetOperation) and isinstance( 284 expression.args.get("limit"), exp.Fetch 285 ): 286 return self.sql( 287 exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False) 288 ) 289 290 return super().select_sql(expression) 291 292 def set_operations(self, expression: exp.SetOperation) -> str: 293 limit = expression.args.get("limit") 294 offset = expression.args.get("offset") 295 order = expression.args.get("order") 296 297 # Set operations cannot order by the CASE used to emulate null ordering, 298 # or by expressions that aren't in their select list. 299 wrap_order = False 300 if order: 301 selects = {select.unalias().unnest() for select in expression.selects} 302 for ordered in order.expressions: 303 this = ordered.this.unnest() 304 if this.is_int: 305 continue 306 307 desc = ordered.args.get("desc") 308 nulls_first = ordered.args.get("nulls_first") 309 310 emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first) 311 if emulate_null_ordering or ( 312 not isinstance(this, exp.Column) and this not in selects 313 ): 314 wrap_order = True 315 break 316 317 if ( 318 wrap_order 319 or (isinstance(limit, exp.Limit) and not offset) 320 or (not order and (offset or isinstance(limit, exp.Fetch))) 321 ): 322 select = self._move_ctes_to_top_level( 323 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 324 ) 325 for arg in SET_OP_MODIFIERS: 326 value = expression.args.get(arg) 327 if value: 328 expression.set(arg, None) 329 select.set(arg, value) 330 331 return self.sql(select) 332 333 self._prepare_limit_offset(expression) 334 return super().set_operations(expression) 335 336 def _prepare_limit_offset(self, expression: exp.Query) -> None: 337 limit = expression.args.get("limit") 338 offset = expression.args.get("offset") 339 340 if isinstance(limit, exp.Fetch) and not offset: 341 # Dialects like Oracle can FETCH directly from a row set but 342 # T-SQL requires an ORDER BY + OFFSET clause in order to FETCH 343 offset = exp.Offset(expression=exp.Literal.number(0)) 344 expression.set("offset", offset) 345 346 if offset: 347 if not expression.args.get("order"): 348 # ORDER BY is required in order to use OFFSET in a query, so we use 349 # a noop order by, since we don't really care about the order. 350 # See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819 351 expression.order_by(exp.select(exp.null()).subquery(), copy=False) 352 353 if isinstance(limit, exp.Limit): 354 # TOP and OFFSET can't be combined, we need use FETCH instead of TOP 355 # we replace here because otherwise TOP would be generated in select_sql 356 limit.replace(exp.Fetch(direction="FIRST", count=limit.expression)) 357 358 def convert_sql(self, expression: exp.Convert) -> str: 359 name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT" 360 return self.func(name, expression.this, expression.expression, expression.args.get("style")) 361 362 def queryoption_sql(self, expression: exp.QueryOption) -> str: 363 option = self.sql(expression, "this") 364 value = self.sql(expression, "expression") 365 if value: 366 optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else "" 367 return f"{option} {optional_equal_sign}{value}" 368 return option 369 370 def lateral_op(self, expression: exp.Lateral) -> str: 371 cross_apply = expression.args.get("cross_apply") 372 if cross_apply is True: 373 return "CROSS APPLY" 374 if cross_apply is False: 375 return "OUTER APPLY" 376 377 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 378 self.unsupported("LATERAL clause is not supported.") 379 return "LATERAL" 380 381 def splitpart_sql(self, expression: exp.SplitPart) -> str: 382 this = expression.this 383 split_count = len(this.name.split(".")) 384 delimiter = expression.args.get("delimiter") 385 part_index = expression.args.get("part_index") 386 387 if ( 388 not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index)) 389 or (delimiter and delimiter.name != ".") 390 or not part_index 391 or split_count > 4 392 ): 393 self.unsupported( 394 "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values" 395 ) 396 return "" 397 398 return self.func( 399 "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py()) 400 ) 401 402 def extract_sql(self, expression: exp.Extract) -> str: 403 part = expression.this 404 name = DATE_PART_UNMAPPING.get(part.name.upper()) or part 405 406 return self.func("DATEPART", name, expression.expression) 407 408 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 409 nano = expression.args.get("nano") 410 if nano is not None: 411 nano.pop() 412 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 413 414 if expression.args.get("fractions") is None: 415 expression.set("fractions", exp.Literal.number(0)) 416 if expression.args.get("precision") is None: 417 expression.set("precision", exp.Literal.number(0)) 418 419 return rename_func("TIMEFROMPARTS")(self, expression) 420 421 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 422 zone = expression.args.get("zone") 423 if zone is not None: 424 zone.pop() 425 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 426 427 nano = expression.args.get("nano") 428 if nano is not None: 429 nano.pop() 430 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 431 432 if expression.args.get("milli") is None: 433 expression.set("milli", exp.Literal.number(0)) 434 435 return rename_func("DATETIMEFROMPARTS")(self, expression) 436 437 def setitem_sql(self, expression: exp.SetItem) -> str: 438 this = expression.this 439 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 440 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 441 return f"{self.sql(this.left)} {self.sql(this.right)}" 442 443 return super().setitem_sql(expression) 444 445 def boolean_sql(self, expression: exp.Boolean) -> str: 446 if type(expression.parent) in BIT_TYPES or isinstance( 447 expression.find_ancestor(exp.Values, exp.Select), exp.Values 448 ): 449 return "1" if expression.this else "0" 450 451 return "(1 = 1)" if expression.this else "(1 = 0)" 452 453 def is_sql(self, expression: exp.Is) -> str: 454 negate = expression.args.get("negate") 455 if isinstance(expression.expression, exp.Boolean): 456 return self.binary(expression, "<>" if negate else "=") 457 return self.binary(expression, "IS NOT" if negate else "IS") 458 459 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 460 sql = self.sql(expression, "this") 461 properties = expression.args.get("properties") 462 463 start = self._identifier_start 464 if ( 465 not sql.startswith("#") 466 and not sql.startswith(f"{start}#") 467 and any( 468 isinstance(prop, exp.TemporaryProperty) 469 for prop in (properties.expressions if properties else []) 470 ) 471 ): 472 sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}" 473 474 return sql 475 476 def create_sql(self, expression: exp.Create) -> str: 477 kind = expression.kind 478 exists = expression.args.get("exists") 479 expression.set("exists", None) 480 481 like_property = expression.find(exp.LikeProperty) 482 if like_property: 483 ctas_expression = like_property.this 484 else: 485 ctas_expression = expression.expression 486 487 if kind == "VIEW": 488 expression.this.set("catalog", None) 489 with_ = expression.args.get("with_") 490 if ctas_expression and with_: 491 # We've already preprocessed the Create expression to bubble up any nested CTEs, 492 # but CREATE VIEW actually requires the WITH clause to come after it so we need 493 # to amend the AST by moving the CTEs to the CREATE VIEW statement's query. 494 ctas_expression.set("with_", with_.pop()) 495 elif ( 496 kind == "FUNCTION" 497 and isinstance(ctas_expression, exp.Return) 498 and isinstance(body := ctas_expression.this.unnest(), exp.Query) 499 and (with_ := expression.args.get("with_")) 500 ): 501 # Similar to the VIEW branch, the table-valued functions require the WITH clause 502 # to stay inside the RETURN body, so we move back any CTEs that were bubbled up. 503 body.set("with_", with_.pop()) 504 505 table = expression.find(exp.Table) 506 507 # Convert CTAS statement to SELECT .. INTO .. 508 if kind == "TABLE" and ctas_expression: 509 if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES): 510 ctas_expression = ctas_expression.subquery() 511 512 properties = expression.args.get("properties") or exp.Properties() 513 is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions) 514 515 select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True)) 516 select_into.set("into", exp.Into(this=table, temporary=is_temp)) 517 518 if like_property: 519 select_into.limit(0, copy=False) 520 521 sql = self.sql(select_into) 522 else: 523 sql = super().create_sql(expression) 524 525 if exists: 526 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 527 sql_with_ctes = self.prepend_ctes(expression, sql) 528 sql_literal = self.sql(exp.Literal.string(sql_with_ctes)) 529 if kind == "SCHEMA": 530 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})""" 531 elif kind == "TABLE": 532 assert table 533 where = exp.and_( 534 exp.column("TABLE_NAME").eq(table.name), 535 exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None, 536 exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None, 537 ) 538 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})""" 539 elif kind == "INDEX": 540 index = self.sql(exp.Literal.string(expression.this.text("this"))) 541 return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})""" 542 elif expression.args.get("replace"): 543 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 544 545 return self.prepend_ctes(expression, sql) 546 547 @generator.unsupported_args("unlogged", "expressions") 548 def into_sql(self, expression: exp.Into) -> str: 549 if expression.args.get("temporary"): 550 # If the Into expression has a temporary property, push this down to the Identifier 551 table = expression.find(exp.Table) 552 if table and isinstance(table.this, exp.Identifier): 553 table.this.set("temporary", True) 554 555 return f"{self.seg('INTO')} {self.sql(expression, 'this')}" 556 557 def count_sql(self, expression: exp.Count) -> str: 558 func_name = "COUNT_BIG" if expression.args.get("big_int") else "COUNT" 559 return rename_func(func_name)(self, expression) 560 561 def datediff_sql(self, expression: exp.DateDiff) -> str: 562 func_name = "DATEDIFF_BIG" if expression.args.get("big_int") else "DATEDIFF" 563 return date_delta_sql(func_name)(self, expression) 564 565 def offset_sql(self, expression: exp.Offset) -> str: 566 return f"{super().offset_sql(expression)} ROWS" 567 568 def version_sql(self, expression: exp.Version) -> str: 569 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 570 this = f"FOR {name}" 571 expr = expression.expression 572 kind = expression.text("kind") 573 if kind in ("FROM", "BETWEEN"): 574 args = expr.expressions 575 sep = "TO" if kind == "FROM" else "AND" 576 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 577 else: 578 expr_sql = self.sql(expr) 579 580 expr_sql = f" {expr_sql}" if expr_sql else "" 581 return f"{this} {kind}{expr_sql}" 582 583 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 584 table = expression.args.get("table") 585 table = f"{table} " if table else "" 586 return f"RETURNS {table}{self.sql(expression, 'this')}" 587 588 def returning_sql(self, expression: exp.Returning) -> str: 589 into = self.sql(expression, "into") 590 into = self.seg(f"INTO {into}") if into else "" 591 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 592 593 def transaction_sql(self, expression: exp.Transaction) -> str: 594 this = self.sql(expression, "this") 595 this = f" {this}" if this else "" 596 mark = self.sql(expression, "mark") 597 mark = f" WITH MARK {mark}" if mark else "" 598 return f"BEGIN TRANSACTION{this}{mark}" 599 600 def commit_sql(self, expression: exp.Commit) -> str: 601 this = self.sql(expression, "this") 602 this = f" {this}" if this else "" 603 durability = expression.args.get("durability") 604 durability = ( 605 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 606 if durability is not None 607 else "" 608 ) 609 return f"COMMIT TRANSACTION{this}{durability}" 610 611 def rollback_sql(self, expression: exp.Rollback) -> str: 612 this = self.sql(expression, "this") 613 this = f" {this}" if this else "" 614 return f"ROLLBACK TRANSACTION{this}" 615 616 def identifier_sql(self, expression: exp.Identifier) -> str: 617 identifier = super().identifier_sql(expression) 618 619 if expression.args.get("global_"): 620 prefix = "##" 621 elif expression.args.get("temporary"): 622 prefix = "#" 623 else: 624 return identifier 625 626 start = self._identifier_start 627 if expression.quoted and identifier.startswith(start): 628 return f"{start}{prefix}{identifier[len(start) :]}" 629 630 return f"{prefix}{identifier}" 631 632 def constraint_sql(self, expression: exp.Constraint) -> str: 633 this = self.sql(expression, "this") 634 expressions = self.expressions(expression, flat=True, sep=" ") 635 return f"CONSTRAINT {this} {expressions}" 636 637 def length_sql(self, expression: exp.Length) -> str: 638 return self._uncast_text(expression, "LEN") 639 640 def right_sql(self, expression: exp.Right) -> str: 641 return self._uncast_text(expression, "RIGHT") 642 643 def left_sql(self, expression: exp.Left) -> str: 644 return self._uncast_text(expression, "LEFT") 645 646 def _uncast_text(self, expression: exp.Expr, name: str) -> str: 647 this = expression.this 648 if isinstance(this, exp.Cast) and this.is_type(exp.DType.TEXT): 649 this_sql = self.sql(this, "this") 650 else: 651 this_sql = self.sql(this) 652 expression_sql = self.sql(expression, "expression") 653 return self.func(name, this_sql, expression_sql if expression_sql else None) 654 655 def partition_sql(self, expression: exp.Partition) -> str: 656 return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))" 657 658 def alter_sql(self, expression: exp.Alter) -> str: 659 action = seq_get(expression.args.get("actions") or [], 0) 660 if isinstance(action, exp.AlterRename): 661 return f"EXEC sp_rename '{self.sql(expression.this)}', '{action.this.name}'" 662 return super().alter_sql(expression) 663 664 def drop_sql(self, expression: exp.Drop) -> str: 665 if expression.args["kind"] == "VIEW": 666 for table in expression.args.get("tables") or []: 667 table.set("catalog", None) 668 return super().drop_sql(expression) 669 670 def options_modifier(self, expression: exp.Expr) -> str: 671 options = self.expressions(expression, key="options") 672 return f" OPTION{self.wrap(options)}" if options else "" 673 674 def dpipe_sql(self, expression: exp.DPipe) -> str: 675 return self.sql(reduce(lambda x, y: exp.Add(this=x, expression=y), expression.flatten())) 676 677 def isascii_sql(self, expression: exp.IsAscii) -> str: 678 return f"(PATINDEX(CONVERT(VARCHAR(MAX), 0x255b5e002d7f5d25) COLLATE Latin1_General_BIN, {self.sql(expression.this)}) = 0)" 679 680 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 681 this = super().columndef_sql(expression, sep) 682 default = self.sql(expression, "default") 683 default = f" = {default}" if default else "" 684 output = self.sql(expression, "output") 685 output = f" {output}" if output else "" 686 return f"{this}{default}{output}" 687 688 def coalesce_sql(self, expression: exp.Coalesce) -> str: 689 func_name = "ISNULL" if expression.args.get("is_null") else "COALESCE" 690 return rename_func(func_name)(self, expression) 691 692 def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str: 693 this = self.sql(expression, "this") 694 expressions = self.expressions(expression) 695 expressions = ( 696 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 697 ) 698 return f"{this}{expressions}" if expressions.strip() != "" else this 699 700 def ifblock_sql(self, expression: exp.IfBlock) -> str: 701 this = self.sql(expression, "this") 702 true = self.sql(expression, "true") 703 true = f" {true}" if true else " " 704 false = self.sql(expression, "false") 705 false = f"; ELSE BEGIN {false}" if false else "" 706 return f"IF {this} BEGIN{true}{false}" 707 708 def whileblock_sql(self, expression: exp.WhileBlock) -> str: 709 this = self.sql(expression, "this") 710 body = self.sql(expression, "body") 711 body = f" {body}" if body else " " 712 return f"WHILE {this} BEGIN{body}" 713 714 def execute_sql(self, expression: exp.Execute) -> str: 715 this = self.sql(expression, "this") 716 expressions = self.expressions(expression) 717 expressions = f" {expressions}" if expressions else "" 718 return_status = self.sql(expression, "return_status") 719 return_status = f"{return_status} = " if return_status else "" 720 return f"EXECUTE {return_status}{this}{expressions}" 721 722 def executesql_sql(self, expression: exp.ExecuteSql) -> str: 723 return self.execute_sql(expression)
DATE_PART_UNMAPPING =
{'WEEKISO': 'ISO_WEEK', 'DAYOFWEEK': 'WEEKDAY', 'TIMEZONE_MINUTE': 'TZOFFSET'}
BIT_TYPES =
{<class 'sqlglot.expressions.core.Alias'>, <class 'sqlglot.expressions.core.EQ'>, <class 'sqlglot.expressions.core.In'>, <class 'sqlglot.expressions.core.Is'>, <class 'sqlglot.expressions.core.NEQ'>, <class 'sqlglot.expressions.query.Select'>}
SET_OP_MODIFIERS =
('limit', 'offset', 'order', 'for_', 'options')
def
qualify_derived_table_outputs( expression: sqlglot.expressions.core.Expr) -> sqlglot.expressions.core.Expr:
73def qualify_derived_table_outputs(expression: exp.Expr) -> exp.Expr: 74 """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.""" 75 alias = expression.args.get("alias") 76 77 if ( 78 isinstance(expression, (exp.CTE, exp.Subquery)) 79 and isinstance(alias, exp.TableAlias) 80 and not alias.columns 81 ): 82 from sqlglot.dialects.tsql import TSQL 83 from sqlglot.optimizer.qualify_columns import qualify_outputs 84 85 # We keep track of the unaliased column projection indexes instead of the expressions 86 # themselves, because the latter are going to be replaced by new nodes when the aliases 87 # are added and hence we won't be able to reach these newly added Alias parents 88 query = expression.this 89 unaliased_column_indexes = ( 90 i for i, c in enumerate(query.selects) if isinstance(c, exp.Column) and not c.alias 91 ) 92 93 qualify_outputs(query, dialect=TSQL()) 94 95 # Preserve the quoting information of columns for newly added Alias nodes 96 query_selects = query.selects 97 for select_index in unaliased_column_indexes: 98 alias = query_selects[select_index] 99 column = alias.this 100 if isinstance(column.this, exp.Identifier): 101 alias.args["alias"].set("quoted", column.this.quoted) 102 103 return expression
Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.
133class TSQLGenerator(generator.Generator): 134 SELECT_KINDS: tuple[str, ...] = () 135 TRY_SUPPORTED = False 136 SUPPORTS_UESCAPE = False 137 SUPPORTS_DECODE_CASE = False 138 139 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 140 141 LIMIT_IS_TOP = True 142 SET_OP_LIMITS = True 143 QUERY_HINTS = False 144 RETURNING_END = False 145 NVL2_SUPPORTED = False 146 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 147 LIMIT_FETCH = "FETCH" 148 COMPUTED_COLUMN_WITH_TYPE = False 149 CTE_RECURSIVE_KEYWORD_REQUIRED = False 150 ENSURE_BOOLS = True 151 NULL_ORDERING_SUPPORTED: bool | None = None 152 SUPPORTS_SINGLE_ARG_CONCAT = False 153 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 154 SUPPORTS_SELECT_INTO = True 155 JSON_PATH_BRACKETED_KEY_SUPPORTED = False 156 SUPPORTS_TO_NUMBER = False 157 COPY_PARAMS_EQ_REQUIRED = True 158 PARSE_JSON_NAME: str | None = None 159 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = False 160 ALTER_SET_WRAPPED = True 161 ALTER_SET_TYPE = "" 162 SUPPORTS_ALTER_COLUMN_NULLABILITY = True 163 164 EXPRESSIONS_WITHOUT_NESTED_CTES = { 165 exp.Create, 166 exp.Delete, 167 exp.Insert, 168 exp.Intersect, 169 exp.Except, 170 exp.Merge, 171 exp.Select, 172 exp.Subquery, 173 exp.Union, 174 exp.Update, 175 } 176 177 SUPPORTED_JSON_PATH_PARTS = { 178 exp.JSONPathKey, 179 exp.JSONPathRoot, 180 exp.JSONPathSubscript, 181 } 182 183 TYPE_MAPPING = { 184 **{ 185 k: v 186 for k, v in generator.Generator.TYPE_MAPPING.items() 187 if k not in (exp.DType.NCHAR, exp.DType.NVARCHAR) 188 }, 189 exp.DType.BOOLEAN: "BIT", 190 exp.DType.DATETIME2: "DATETIME2", 191 exp.DType.DECIMAL: "NUMERIC", 192 exp.DType.DOUBLE: "FLOAT", 193 exp.DType.INT: "INTEGER", 194 exp.DType.ROWVERSION: "ROWVERSION", 195 exp.DType.TEXT: "VARCHAR(MAX)", 196 exp.DType.TIMESTAMP: "DATETIME2", 197 exp.DType.TIMESTAMPNTZ: "DATETIME2", 198 exp.DType.TIMESTAMPTZ: "DATETIMEOFFSET", 199 exp.DType.SMALLDATETIME: "SMALLDATETIME", 200 exp.DType.UTINYINT: "TINYINT", 201 exp.DType.VARIANT: "SQL_VARIANT", 202 exp.DType.UUID: "UNIQUEIDENTIFIER", 203 } 204 205 TRANSFORMS = { 206 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.ReturnsProperty}, 207 exp.AnyValue: any_value_to_max_sql, 208 exp.Atan2: rename_func("ATN2"), 209 exp.ArrayToString: rename_func("STRING_AGG"), 210 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 211 exp.Ceil: rename_func("CEILING"), 212 exp.Chr: rename_func("CHAR"), 213 exp.DateAdd: date_delta_sql("DATEADD"), 214 exp.CTE: transforms.preprocess([qualify_derived_table_outputs]), 215 exp.CurrentDate: rename_func("GETDATE"), 216 exp.CurrentTimestamp: rename_func("GETDATE"), 217 exp.CurrentTimestampLTZ: rename_func("SYSDATETIMEOFFSET"), 218 exp.DateStrToDate: datestrtodate_sql, 219 exp.Day: remove_ts_or_ds_to_date(), 220 exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql, 221 exp.GroupConcat: _string_agg_sql, 222 exp.If: rename_func("IIF"), 223 exp.JSONExtract: _json_extract_sql, 224 exp.JSONExtractScalar: _json_extract_sql, 225 exp.LastDay: lambda self, e: self.func("EOMONTH", e.this), 226 exp.Ln: rename_func("LOG"), 227 exp.Max: max_or_greatest, 228 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 229 exp.Min: min_or_least, 230 exp.Month: remove_ts_or_ds_to_date(), 231 exp.NumberToStr: _format_sql, 232 exp.Repeat: rename_func("REPLICATE"), 233 exp.CurrentSchema: rename_func("SCHEMA_NAME"), 234 exp.Select: transforms.preprocess( 235 [ 236 transforms.eliminate_distinct_on, 237 transforms.eliminate_semi_and_anti_joins, 238 transforms.eliminate_qualify, 239 transforms.unnest_generate_date_array_using_recursive_cte, 240 ] 241 ), 242 exp.Stddev: rename_func("STDEV"), 243 exp.StrPosition: lambda self, e: strposition_sql( 244 self, e, func_name="CHARINDEX", supports_position=True 245 ), 246 exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]), 247 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 248 exp.SHA1Digest: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 249 exp.SHA2: lambda self, e: self.func( 250 "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this 251 ), 252 exp.TemporaryProperty: lambda self, e: "", 253 exp.TimeStrToTime: _timestrtotime_sql, 254 exp.TimeToStr: _format_sql, 255 exp.TimestampAdd: date_delta_sql("DATEADD"), 256 exp.Trim: trim_sql, 257 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 258 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 259 exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this), 260 exp.Trunc: lambda self, e: self.func( 261 "ROUND", 262 e.this, 263 e.args.get("decimals") or exp.Literal.number(0), 264 exp.Literal.number(1), 265 ), 266 exp.Uuid: lambda *_: "NEWID()", 267 exp.Year: remove_ts_or_ds_to_date(), 268 exp.DateFromParts: rename_func("DATEFROMPARTS"), 269 } 270 271 PROPERTIES_LOCATION = { 272 **generator.Generator.PROPERTIES_LOCATION, 273 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 274 } 275 276 def scope_resolution(self, rhs: str, scope_name: str) -> str: 277 return f"{scope_name}::{rhs}" 278 279 def select_sql(self, expression: exp.Select) -> str: 280 self._prepare_limit_offset(expression) 281 282 # Handles transpiling a query like the following to T-SQL: 283 # SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x 284 if isinstance(expression.parent, exp.SetOperation) and isinstance( 285 expression.args.get("limit"), exp.Fetch 286 ): 287 return self.sql( 288 exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False) 289 ) 290 291 return super().select_sql(expression) 292 293 def set_operations(self, expression: exp.SetOperation) -> str: 294 limit = expression.args.get("limit") 295 offset = expression.args.get("offset") 296 order = expression.args.get("order") 297 298 # Set operations cannot order by the CASE used to emulate null ordering, 299 # or by expressions that aren't in their select list. 300 wrap_order = False 301 if order: 302 selects = {select.unalias().unnest() for select in expression.selects} 303 for ordered in order.expressions: 304 this = ordered.this.unnest() 305 if this.is_int: 306 continue 307 308 desc = ordered.args.get("desc") 309 nulls_first = ordered.args.get("nulls_first") 310 311 emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first) 312 if emulate_null_ordering or ( 313 not isinstance(this, exp.Column) and this not in selects 314 ): 315 wrap_order = True 316 break 317 318 if ( 319 wrap_order 320 or (isinstance(limit, exp.Limit) and not offset) 321 or (not order and (offset or isinstance(limit, exp.Fetch))) 322 ): 323 select = self._move_ctes_to_top_level( 324 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 325 ) 326 for arg in SET_OP_MODIFIERS: 327 value = expression.args.get(arg) 328 if value: 329 expression.set(arg, None) 330 select.set(arg, value) 331 332 return self.sql(select) 333 334 self._prepare_limit_offset(expression) 335 return super().set_operations(expression) 336 337 def _prepare_limit_offset(self, expression: exp.Query) -> None: 338 limit = expression.args.get("limit") 339 offset = expression.args.get("offset") 340 341 if isinstance(limit, exp.Fetch) and not offset: 342 # Dialects like Oracle can FETCH directly from a row set but 343 # T-SQL requires an ORDER BY + OFFSET clause in order to FETCH 344 offset = exp.Offset(expression=exp.Literal.number(0)) 345 expression.set("offset", offset) 346 347 if offset: 348 if not expression.args.get("order"): 349 # ORDER BY is required in order to use OFFSET in a query, so we use 350 # a noop order by, since we don't really care about the order. 351 # See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819 352 expression.order_by(exp.select(exp.null()).subquery(), copy=False) 353 354 if isinstance(limit, exp.Limit): 355 # TOP and OFFSET can't be combined, we need use FETCH instead of TOP 356 # we replace here because otherwise TOP would be generated in select_sql 357 limit.replace(exp.Fetch(direction="FIRST", count=limit.expression)) 358 359 def convert_sql(self, expression: exp.Convert) -> str: 360 name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT" 361 return self.func(name, expression.this, expression.expression, expression.args.get("style")) 362 363 def queryoption_sql(self, expression: exp.QueryOption) -> str: 364 option = self.sql(expression, "this") 365 value = self.sql(expression, "expression") 366 if value: 367 optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else "" 368 return f"{option} {optional_equal_sign}{value}" 369 return option 370 371 def lateral_op(self, expression: exp.Lateral) -> str: 372 cross_apply = expression.args.get("cross_apply") 373 if cross_apply is True: 374 return "CROSS APPLY" 375 if cross_apply is False: 376 return "OUTER APPLY" 377 378 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 379 self.unsupported("LATERAL clause is not supported.") 380 return "LATERAL" 381 382 def splitpart_sql(self, expression: exp.SplitPart) -> str: 383 this = expression.this 384 split_count = len(this.name.split(".")) 385 delimiter = expression.args.get("delimiter") 386 part_index = expression.args.get("part_index") 387 388 if ( 389 not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index)) 390 or (delimiter and delimiter.name != ".") 391 or not part_index 392 or split_count > 4 393 ): 394 self.unsupported( 395 "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values" 396 ) 397 return "" 398 399 return self.func( 400 "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py()) 401 ) 402 403 def extract_sql(self, expression: exp.Extract) -> str: 404 part = expression.this 405 name = DATE_PART_UNMAPPING.get(part.name.upper()) or part 406 407 return self.func("DATEPART", name, expression.expression) 408 409 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 410 nano = expression.args.get("nano") 411 if nano is not None: 412 nano.pop() 413 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 414 415 if expression.args.get("fractions") is None: 416 expression.set("fractions", exp.Literal.number(0)) 417 if expression.args.get("precision") is None: 418 expression.set("precision", exp.Literal.number(0)) 419 420 return rename_func("TIMEFROMPARTS")(self, expression) 421 422 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 423 zone = expression.args.get("zone") 424 if zone is not None: 425 zone.pop() 426 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 427 428 nano = expression.args.get("nano") 429 if nano is not None: 430 nano.pop() 431 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 432 433 if expression.args.get("milli") is None: 434 expression.set("milli", exp.Literal.number(0)) 435 436 return rename_func("DATETIMEFROMPARTS")(self, expression) 437 438 def setitem_sql(self, expression: exp.SetItem) -> str: 439 this = expression.this 440 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 441 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 442 return f"{self.sql(this.left)} {self.sql(this.right)}" 443 444 return super().setitem_sql(expression) 445 446 def boolean_sql(self, expression: exp.Boolean) -> str: 447 if type(expression.parent) in BIT_TYPES or isinstance( 448 expression.find_ancestor(exp.Values, exp.Select), exp.Values 449 ): 450 return "1" if expression.this else "0" 451 452 return "(1 = 1)" if expression.this else "(1 = 0)" 453 454 def is_sql(self, expression: exp.Is) -> str: 455 negate = expression.args.get("negate") 456 if isinstance(expression.expression, exp.Boolean): 457 return self.binary(expression, "<>" if negate else "=") 458 return self.binary(expression, "IS NOT" if negate else "IS") 459 460 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 461 sql = self.sql(expression, "this") 462 properties = expression.args.get("properties") 463 464 start = self._identifier_start 465 if ( 466 not sql.startswith("#") 467 and not sql.startswith(f"{start}#") 468 and any( 469 isinstance(prop, exp.TemporaryProperty) 470 for prop in (properties.expressions if properties else []) 471 ) 472 ): 473 sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}" 474 475 return sql 476 477 def create_sql(self, expression: exp.Create) -> str: 478 kind = expression.kind 479 exists = expression.args.get("exists") 480 expression.set("exists", None) 481 482 like_property = expression.find(exp.LikeProperty) 483 if like_property: 484 ctas_expression = like_property.this 485 else: 486 ctas_expression = expression.expression 487 488 if kind == "VIEW": 489 expression.this.set("catalog", None) 490 with_ = expression.args.get("with_") 491 if ctas_expression and with_: 492 # We've already preprocessed the Create expression to bubble up any nested CTEs, 493 # but CREATE VIEW actually requires the WITH clause to come after it so we need 494 # to amend the AST by moving the CTEs to the CREATE VIEW statement's query. 495 ctas_expression.set("with_", with_.pop()) 496 elif ( 497 kind == "FUNCTION" 498 and isinstance(ctas_expression, exp.Return) 499 and isinstance(body := ctas_expression.this.unnest(), exp.Query) 500 and (with_ := expression.args.get("with_")) 501 ): 502 # Similar to the VIEW branch, the table-valued functions require the WITH clause 503 # to stay inside the RETURN body, so we move back any CTEs that were bubbled up. 504 body.set("with_", with_.pop()) 505 506 table = expression.find(exp.Table) 507 508 # Convert CTAS statement to SELECT .. INTO .. 509 if kind == "TABLE" and ctas_expression: 510 if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES): 511 ctas_expression = ctas_expression.subquery() 512 513 properties = expression.args.get("properties") or exp.Properties() 514 is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions) 515 516 select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True)) 517 select_into.set("into", exp.Into(this=table, temporary=is_temp)) 518 519 if like_property: 520 select_into.limit(0, copy=False) 521 522 sql = self.sql(select_into) 523 else: 524 sql = super().create_sql(expression) 525 526 if exists: 527 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 528 sql_with_ctes = self.prepend_ctes(expression, sql) 529 sql_literal = self.sql(exp.Literal.string(sql_with_ctes)) 530 if kind == "SCHEMA": 531 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})""" 532 elif kind == "TABLE": 533 assert table 534 where = exp.and_( 535 exp.column("TABLE_NAME").eq(table.name), 536 exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None, 537 exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None, 538 ) 539 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})""" 540 elif kind == "INDEX": 541 index = self.sql(exp.Literal.string(expression.this.text("this"))) 542 return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})""" 543 elif expression.args.get("replace"): 544 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 545 546 return self.prepend_ctes(expression, sql) 547 548 @generator.unsupported_args("unlogged", "expressions") 549 def into_sql(self, expression: exp.Into) -> str: 550 if expression.args.get("temporary"): 551 # If the Into expression has a temporary property, push this down to the Identifier 552 table = expression.find(exp.Table) 553 if table and isinstance(table.this, exp.Identifier): 554 table.this.set("temporary", True) 555 556 return f"{self.seg('INTO')} {self.sql(expression, 'this')}" 557 558 def count_sql(self, expression: exp.Count) -> str: 559 func_name = "COUNT_BIG" if expression.args.get("big_int") else "COUNT" 560 return rename_func(func_name)(self, expression) 561 562 def datediff_sql(self, expression: exp.DateDiff) -> str: 563 func_name = "DATEDIFF_BIG" if expression.args.get("big_int") else "DATEDIFF" 564 return date_delta_sql(func_name)(self, expression) 565 566 def offset_sql(self, expression: exp.Offset) -> str: 567 return f"{super().offset_sql(expression)} ROWS" 568 569 def version_sql(self, expression: exp.Version) -> str: 570 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 571 this = f"FOR {name}" 572 expr = expression.expression 573 kind = expression.text("kind") 574 if kind in ("FROM", "BETWEEN"): 575 args = expr.expressions 576 sep = "TO" if kind == "FROM" else "AND" 577 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 578 else: 579 expr_sql = self.sql(expr) 580 581 expr_sql = f" {expr_sql}" if expr_sql else "" 582 return f"{this} {kind}{expr_sql}" 583 584 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 585 table = expression.args.get("table") 586 table = f"{table} " if table else "" 587 return f"RETURNS {table}{self.sql(expression, 'this')}" 588 589 def returning_sql(self, expression: exp.Returning) -> str: 590 into = self.sql(expression, "into") 591 into = self.seg(f"INTO {into}") if into else "" 592 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 593 594 def transaction_sql(self, expression: exp.Transaction) -> str: 595 this = self.sql(expression, "this") 596 this = f" {this}" if this else "" 597 mark = self.sql(expression, "mark") 598 mark = f" WITH MARK {mark}" if mark else "" 599 return f"BEGIN TRANSACTION{this}{mark}" 600 601 def commit_sql(self, expression: exp.Commit) -> str: 602 this = self.sql(expression, "this") 603 this = f" {this}" if this else "" 604 durability = expression.args.get("durability") 605 durability = ( 606 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 607 if durability is not None 608 else "" 609 ) 610 return f"COMMIT TRANSACTION{this}{durability}" 611 612 def rollback_sql(self, expression: exp.Rollback) -> str: 613 this = self.sql(expression, "this") 614 this = f" {this}" if this else "" 615 return f"ROLLBACK TRANSACTION{this}" 616 617 def identifier_sql(self, expression: exp.Identifier) -> str: 618 identifier = super().identifier_sql(expression) 619 620 if expression.args.get("global_"): 621 prefix = "##" 622 elif expression.args.get("temporary"): 623 prefix = "#" 624 else: 625 return identifier 626 627 start = self._identifier_start 628 if expression.quoted and identifier.startswith(start): 629 return f"{start}{prefix}{identifier[len(start) :]}" 630 631 return f"{prefix}{identifier}" 632 633 def constraint_sql(self, expression: exp.Constraint) -> str: 634 this = self.sql(expression, "this") 635 expressions = self.expressions(expression, flat=True, sep=" ") 636 return f"CONSTRAINT {this} {expressions}" 637 638 def length_sql(self, expression: exp.Length) -> str: 639 return self._uncast_text(expression, "LEN") 640 641 def right_sql(self, expression: exp.Right) -> str: 642 return self._uncast_text(expression, "RIGHT") 643 644 def left_sql(self, expression: exp.Left) -> str: 645 return self._uncast_text(expression, "LEFT") 646 647 def _uncast_text(self, expression: exp.Expr, name: str) -> str: 648 this = expression.this 649 if isinstance(this, exp.Cast) and this.is_type(exp.DType.TEXT): 650 this_sql = self.sql(this, "this") 651 else: 652 this_sql = self.sql(this) 653 expression_sql = self.sql(expression, "expression") 654 return self.func(name, this_sql, expression_sql if expression_sql else None) 655 656 def partition_sql(self, expression: exp.Partition) -> str: 657 return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))" 658 659 def alter_sql(self, expression: exp.Alter) -> str: 660 action = seq_get(expression.args.get("actions") or [], 0) 661 if isinstance(action, exp.AlterRename): 662 return f"EXEC sp_rename '{self.sql(expression.this)}', '{action.this.name}'" 663 return super().alter_sql(expression) 664 665 def drop_sql(self, expression: exp.Drop) -> str: 666 if expression.args["kind"] == "VIEW": 667 for table in expression.args.get("tables") or []: 668 table.set("catalog", None) 669 return super().drop_sql(expression) 670 671 def options_modifier(self, expression: exp.Expr) -> str: 672 options = self.expressions(expression, key="options") 673 return f" OPTION{self.wrap(options)}" if options else "" 674 675 def dpipe_sql(self, expression: exp.DPipe) -> str: 676 return self.sql(reduce(lambda x, y: exp.Add(this=x, expression=y), expression.flatten())) 677 678 def isascii_sql(self, expression: exp.IsAscii) -> str: 679 return f"(PATINDEX(CONVERT(VARCHAR(MAX), 0x255b5e002d7f5d25) COLLATE Latin1_General_BIN, {self.sql(expression.this)}) = 0)" 680 681 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 682 this = super().columndef_sql(expression, sep) 683 default = self.sql(expression, "default") 684 default = f" = {default}" if default else "" 685 output = self.sql(expression, "output") 686 output = f" {output}" if output else "" 687 return f"{this}{default}{output}" 688 689 def coalesce_sql(self, expression: exp.Coalesce) -> str: 690 func_name = "ISNULL" if expression.args.get("is_null") else "COALESCE" 691 return rename_func(func_name)(self, expression) 692 693 def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str: 694 this = self.sql(expression, "this") 695 expressions = self.expressions(expression) 696 expressions = ( 697 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 698 ) 699 return f"{this}{expressions}" if expressions.strip() != "" else this 700 701 def ifblock_sql(self, expression: exp.IfBlock) -> str: 702 this = self.sql(expression, "this") 703 true = self.sql(expression, "true") 704 true = f" {true}" if true else " " 705 false = self.sql(expression, "false") 706 false = f"; ELSE BEGIN {false}" if false else "" 707 return f"IF {this} BEGIN{true}{false}" 708 709 def whileblock_sql(self, expression: exp.WhileBlock) -> str: 710 this = self.sql(expression, "this") 711 body = self.sql(expression, "body") 712 body = f" {body}" if body else " " 713 return f"WHILE {this} BEGIN{body}" 714 715 def execute_sql(self, expression: exp.Execute) -> str: 716 this = self.sql(expression, "this") 717 expressions = self.expressions(expression) 718 expressions = f" {expressions}" if expressions else "" 719 return_status = self.sql(expression, "return_status") 720 return_status = f"{return_status} = " if return_status else "" 721 return f"EXECUTE {return_status}{this}{expressions}" 722 723 def executesql_sql(self, expression: exp.ExecuteSql) -> str: 724 return self.execute_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
EXPRESSIONS_WITHOUT_NESTED_CTES =
{<class 'sqlglot.expressions.query.Subquery'>, <class 'sqlglot.expressions.query.Intersect'>, <class 'sqlglot.expressions.dml.Merge'>, <class 'sqlglot.expressions.query.Except'>, <class 'sqlglot.expressions.dml.Update'>, <class 'sqlglot.expressions.query.Union'>, <class 'sqlglot.expressions.ddl.Create'>, <class 'sqlglot.expressions.dml.Delete'>, <class 'sqlglot.expressions.query.Select'>, <class 'sqlglot.expressions.dml.Insert'>}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathKey'>, <class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>}
TYPE_MAPPING =
{<DType.DATETIME2: 'DATETIME2'>: 'DATETIME2', <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'>: 'ROWVERSION', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'SMALLDATETIME', <DType.BOOLEAN: 'BOOLEAN'>: 'BIT', <DType.DECIMAL: 'DECIMAL'>: 'NUMERIC', <DType.DOUBLE: 'DOUBLE'>: 'FLOAT', <DType.INT: 'INT'>: 'INTEGER', <DType.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <DType.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME2', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <DType.UTINYINT: 'UTINYINT'>: 'TINYINT', <DType.VARIANT: 'VARIANT'>: 'SQL_VARIANT', <DType.UUID: 'UUID'>: 'UNIQUEIDENTIFIER'}
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <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 Generator.<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 rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<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.RowAccessProperty'>: <function Generator.<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 TSQLGenerator.<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 Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.math.Atan2'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayToString'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.AutoIncrementColumnConstraint'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.Chr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.query.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentTimestampLTZ'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.Day'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.functions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONExtract'>: <function _json_extract_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function _json_extract_sql>, <class 'sqlglot.expressions.temporal.LastDay'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.math.Ln'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.string.MD5'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.temporal.Month'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.string.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.string.Repeat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.CurrentSchema'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.aggregate.Stddev'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.query.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.SHA'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function _timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.string.Trim'>: <function trim_sql>, <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.TimestampTrunc'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.math.Trunc'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Uuid'>: <function TSQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Year'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DateFromParts'>: <function rename_func.<locals>.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.UNSUPPORTED: 'UNSUPPORTED'>, <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.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.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.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>}
279 def select_sql(self, expression: exp.Select) -> str: 280 self._prepare_limit_offset(expression) 281 282 # Handles transpiling a query like the following to T-SQL: 283 # SELECT 1 AS x ORDER BY x NULLS FIRST FETCH FIRST 1 ROWS ONLY UNION ALL SELECT 2 AS x 284 if isinstance(expression.parent, exp.SetOperation) and isinstance( 285 expression.args.get("limit"), exp.Fetch 286 ): 287 return self.sql( 288 exp.select("*").from_(expression.subquery("_l_0", copy=False), copy=False) 289 ) 290 291 return super().select_sql(expression)
293 def set_operations(self, expression: exp.SetOperation) -> str: 294 limit = expression.args.get("limit") 295 offset = expression.args.get("offset") 296 order = expression.args.get("order") 297 298 # Set operations cannot order by the CASE used to emulate null ordering, 299 # or by expressions that aren't in their select list. 300 wrap_order = False 301 if order: 302 selects = {select.unalias().unnest() for select in expression.selects} 303 for ordered in order.expressions: 304 this = ordered.this.unnest() 305 if this.is_int: 306 continue 307 308 desc = ordered.args.get("desc") 309 nulls_first = ordered.args.get("nulls_first") 310 311 emulate_null_ordering = (desc and nulls_first) or (not desc and not nulls_first) 312 if emulate_null_ordering or ( 313 not isinstance(this, exp.Column) and this not in selects 314 ): 315 wrap_order = True 316 break 317 318 if ( 319 wrap_order 320 or (isinstance(limit, exp.Limit) and not offset) 321 or (not order and (offset or isinstance(limit, exp.Fetch))) 322 ): 323 select = self._move_ctes_to_top_level( 324 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 325 ) 326 for arg in SET_OP_MODIFIERS: 327 value = expression.args.get(arg) 328 if value: 329 expression.set(arg, None) 330 select.set(arg, value) 331 332 return self.sql(select) 333 334 self._prepare_limit_offset(expression) 335 return super().set_operations(expression)
363 def queryoption_sql(self, expression: exp.QueryOption) -> str: 364 option = self.sql(expression, "this") 365 value = self.sql(expression, "expression") 366 if value: 367 optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else "" 368 return f"{option} {optional_equal_sign}{value}" 369 return option
371 def lateral_op(self, expression: exp.Lateral) -> str: 372 cross_apply = expression.args.get("cross_apply") 373 if cross_apply is True: 374 return "CROSS APPLY" 375 if cross_apply is False: 376 return "OUTER APPLY" 377 378 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 379 self.unsupported("LATERAL clause is not supported.") 380 return "LATERAL"
382 def splitpart_sql(self, expression: exp.SplitPart) -> str: 383 this = expression.this 384 split_count = len(this.name.split(".")) 385 delimiter = expression.args.get("delimiter") 386 part_index = expression.args.get("part_index") 387 388 if ( 389 not all(isinstance(arg, exp.Literal) for arg in (this, delimiter, part_index)) 390 or (delimiter and delimiter.name != ".") 391 or not part_index 392 or split_count > 4 393 ): 394 self.unsupported( 395 "SPLIT_PART can be transpiled to PARSENAME only for '.' delimiter and literal values" 396 ) 397 return "" 398 399 return self.func( 400 "PARSENAME", this, exp.Literal.number(split_count + 1 - part_index.to_py()) 401 )
409 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 410 nano = expression.args.get("nano") 411 if nano is not None: 412 nano.pop() 413 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 414 415 if expression.args.get("fractions") is None: 416 expression.set("fractions", exp.Literal.number(0)) 417 if expression.args.get("precision") is None: 418 expression.set("precision", exp.Literal.number(0)) 419 420 return rename_func("TIMEFROMPARTS")(self, expression)
def
timestampfromparts_sql(self, expression: sqlglot.expressions.temporal.TimestampFromParts) -> str:
422 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 423 zone = expression.args.get("zone") 424 if zone is not None: 425 zone.pop() 426 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 427 428 nano = expression.args.get("nano") 429 if nano is not None: 430 nano.pop() 431 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 432 433 if expression.args.get("milli") is None: 434 expression.set("milli", exp.Literal.number(0)) 435 436 return rename_func("DATETIMEFROMPARTS")(self, expression)
438 def setitem_sql(self, expression: exp.SetItem) -> str: 439 this = expression.this 440 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 441 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 442 return f"{self.sql(this.left)} {self.sql(this.right)}" 443 444 return super().setitem_sql(expression)
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
460 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 461 sql = self.sql(expression, "this") 462 properties = expression.args.get("properties") 463 464 start = self._identifier_start 465 if ( 466 not sql.startswith("#") 467 and not sql.startswith(f"{start}#") 468 and any( 469 isinstance(prop, exp.TemporaryProperty) 470 for prop in (properties.expressions if properties else []) 471 ) 472 ): 473 sql = f"{start}#{sql[len(start) :]}" if sql.startswith(start) else f"#{sql}" 474 475 return sql
477 def create_sql(self, expression: exp.Create) -> str: 478 kind = expression.kind 479 exists = expression.args.get("exists") 480 expression.set("exists", None) 481 482 like_property = expression.find(exp.LikeProperty) 483 if like_property: 484 ctas_expression = like_property.this 485 else: 486 ctas_expression = expression.expression 487 488 if kind == "VIEW": 489 expression.this.set("catalog", None) 490 with_ = expression.args.get("with_") 491 if ctas_expression and with_: 492 # We've already preprocessed the Create expression to bubble up any nested CTEs, 493 # but CREATE VIEW actually requires the WITH clause to come after it so we need 494 # to amend the AST by moving the CTEs to the CREATE VIEW statement's query. 495 ctas_expression.set("with_", with_.pop()) 496 elif ( 497 kind == "FUNCTION" 498 and isinstance(ctas_expression, exp.Return) 499 and isinstance(body := ctas_expression.this.unnest(), exp.Query) 500 and (with_ := expression.args.get("with_")) 501 ): 502 # Similar to the VIEW branch, the table-valued functions require the WITH clause 503 # to stay inside the RETURN body, so we move back any CTEs that were bubbled up. 504 body.set("with_", with_.pop()) 505 506 table = expression.find(exp.Table) 507 508 # Convert CTAS statement to SELECT .. INTO .. 509 if kind == "TABLE" and ctas_expression: 510 if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES): 511 ctas_expression = ctas_expression.subquery() 512 513 properties = expression.args.get("properties") or exp.Properties() 514 is_temp = any(isinstance(p, exp.TemporaryProperty) for p in properties.expressions) 515 516 select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True)) 517 select_into.set("into", exp.Into(this=table, temporary=is_temp)) 518 519 if like_property: 520 select_into.limit(0, copy=False) 521 522 sql = self.sql(select_into) 523 else: 524 sql = super().create_sql(expression) 525 526 if exists: 527 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 528 sql_with_ctes = self.prepend_ctes(expression, sql) 529 sql_literal = self.sql(exp.Literal.string(sql_with_ctes)) 530 if kind == "SCHEMA": 531 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = {identifier}) EXEC({sql_literal})""" 532 elif kind == "TABLE": 533 assert table 534 where = exp.and_( 535 exp.column("TABLE_NAME").eq(table.name), 536 exp.column("TABLE_SCHEMA").eq(table.db) if table.db else None, 537 exp.column("TABLE_CATALOG").eq(table.catalog) if table.catalog else None, 538 ) 539 return f"""IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE {where}) EXEC({sql_literal})""" 540 elif kind == "INDEX": 541 index = self.sql(exp.Literal.string(expression.this.text("this"))) 542 return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})""" 543 elif expression.args.get("replace"): 544 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 545 546 return self.prepend_ctes(expression, sql)
@generator.unsupported_args('unlogged', 'expressions')
def
into_sql(self, expression: sqlglot.expressions.query.Into) -> str:
548 @generator.unsupported_args("unlogged", "expressions") 549 def into_sql(self, expression: exp.Into) -> str: 550 if expression.args.get("temporary"): 551 # If the Into expression has a temporary property, push this down to the Identifier 552 table = expression.find(exp.Table) 553 if table and isinstance(table.this, exp.Identifier): 554 table.this.set("temporary", True) 555 556 return f"{self.seg('INTO')} {self.sql(expression, 'this')}"
569 def version_sql(self, expression: exp.Version) -> str: 570 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 571 this = f"FOR {name}" 572 expr = expression.expression 573 kind = expression.text("kind") 574 if kind in ("FROM", "BETWEEN"): 575 args = expr.expressions 576 sep = "TO" if kind == "FROM" else "AND" 577 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 578 else: 579 expr_sql = self.sql(expr) 580 581 expr_sql = f" {expr_sql}" if expr_sql else "" 582 return f"{this} {kind}{expr_sql}"
601 def commit_sql(self, expression: exp.Commit) -> str: 602 this = self.sql(expression, "this") 603 this = f" {this}" if this else "" 604 durability = expression.args.get("durability") 605 durability = ( 606 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 607 if durability is not None 608 else "" 609 ) 610 return f"COMMIT TRANSACTION{this}{durability}"
617 def identifier_sql(self, expression: exp.Identifier) -> str: 618 identifier = super().identifier_sql(expression) 619 620 if expression.args.get("global_"): 621 prefix = "##" 622 elif expression.args.get("temporary"): 623 prefix = "#" 624 else: 625 return identifier 626 627 start = self._identifier_start 628 if expression.quoted and identifier.startswith(start): 629 return f"{start}{prefix}{identifier[len(start) :]}" 630 631 return f"{prefix}{identifier}"
681 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 682 this = super().columndef_sql(expression, sep) 683 default = self.sql(expression, "default") 684 default = f" = {default}" if default else "" 685 output = self.sql(expression, "output") 686 output = f" {output}" if output else "" 687 return f"{this}{default}{output}"
693 def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str: 694 this = self.sql(expression, "this") 695 expressions = self.expressions(expression) 696 expressions = ( 697 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 698 ) 699 return f"{this}{expressions}" if expressions.strip() != "" else this
701 def ifblock_sql(self, expression: exp.IfBlock) -> str: 702 this = self.sql(expression, "this") 703 true = self.sql(expression, "true") 704 true = f" {true}" if true else " " 705 false = self.sql(expression, "false") 706 false = f"; ELSE BEGIN {false}" if false else "" 707 return f"IF {this} BEGIN{true}{false}"
715 def execute_sql(self, expression: exp.Execute) -> str: 716 this = self.sql(expression, "this") 717 expressions = self.expressions(expression) 718 expressions = f" {expressions}" if expressions else "" 719 return_status = self.sql(expression, "return_status") 720 return_status = f"{return_status} = " if return_status else "" 721 return f"EXECUTE {return_status}{this}{expressions}"
Inherited Members
- sqlglot.generator.Generator
- Generator
- WINDOW_FUNCS_WITH_NULL_ORDERING
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- LOCKING_READS_SUPPORTED
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- AUTO_REFRESH_BARE_INTERVALS
- LIMIT_ONLY_LITERALS
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- JOIN_HINTS
- DIRECTED_JOINS
- TABLE_HINTS
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- DUPLICATE_KEY_UPDATE_WITH_SET
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- VALUES_AS_TABLE
- UNNEST_WITH_ORDINALITY
- SEMI_ANTI_JOIN_WITH_SIDE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_KEYWORDS
- TABLESAMPLE_WITH_METHOD
- HISTORICAL_DATA_POST_ALIAS
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- LAST_DAY_SUPPORTS_DATE_PART
- SUPPORTS_TABLE_ALIAS_COLUMNS
- SUPPORTS_NAMED_CTE_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- PIVOT_ALIAS_WITH_AS
- JSON_KEY_VALUE_PAIR_SEP
- INSERT_OVERWRITE
- SUPPORTS_UNLOGGED_TABLES
- SUPPORTS_CREATE_TABLE_LIKE
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- SUPPORTS_ALTER_COLUMN_IF_EXISTS
- LIKE_PROPERTY_INSIDE_SCHEMA
- MULTI_ARG_DISTINCT
- JSON_TYPE_REQUIRED_FOR_EXTRACTION
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- CAN_IMPLEMENT_ARRAY_ANY
- SUPPORTS_WINDOW_EXCLUDE
- SET_OP_MODIFIERS
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_PARAMS_ARE_WRAPPED
- COPY_HAS_INTO_KEYWORD
- UNICODE_SUBSTITUTE
- STAR_EXCEPT
- HEX_FUNC
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- PAD_FILL_PATTERN_IS_REQUIRED
- SUPPORTS_EXPLODING_PROJECTIONS
- ARRAY_CONCAT_IS_VAR_LEN
- SUPPORTS_CONVERT_TIMEZONE
- SUPPORTS_MEDIAN
- SUPPORTS_UNIX_SECONDS
- NORMALIZE_EXTRACT_DATE_PARTS
- ARRAY_SIZE_NAME
- 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
- TOKEN_MAPPING
- STRUCT_DELIMITER
- PARAMETER_TOKEN
- NAMED_PLACEHOLDER_TOKEN
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- PARAMETERIZABLE_TEXT_TYPES
- RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
- MOD_OPERATOR
- MOD_PAREN_PARENT_TYPES
- 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
- columnconstraint_sql
- computedcolumnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- describe_sql
- heredoc_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- bytestring_sql
- unicodestring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_param_bound_limiter
- datatype_sql
- directory_sql
- delete_sql
- set_operation
- fetch_sql
- limitoptions_sql
- filter_sql
- hint_sql
- indexparameters_sql
- index_sql
- dynamicidentifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_name
- property_sql
- uuidproperty_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- moduleproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tablefromrows_sql
- tablesample_sql
- pivot_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- from_sql
- groupingsets_sql
- rollup_sql
- rollupindex_sql
- rollupproperty_sql
- cube_sql
- group_sql
- having_sql
- connect_sql
- prior_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- set_sql
- queryband_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_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
- forclause_sql
- offset_limit_modifiers
- after_limit_modifiers
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- unnest_sql
- prewhere_sql
- where_sql
- window_sql
- partition_by_sql
- windowspec_sql
- withingroup_sql
- between_sql
- bracket_offset_expressions
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- nextvaluefor_sql
- trim_sql
- convert_concat_args
- concat_sql
- concatws_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- timeserieskey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- jsonpath_sql
- json_path_part
- formatjson_sql
- formatphrase_sql
- jsonarray_sql
- jsonarrayagg_sql
- jsoncolumndef_sql
- jsonschema_sql
- jsontable_sql
- openjsoncolumndef_sql
- openjson_sql
- in_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- pivotalias_sql
- aliases_sql
- atindex_sql
- attimezone_sql
- fromtimezone_sql
- fromiso8601date_sql
- fromiso8601timestamp_sql
- fromiso8601timestampnanos_sql
- add_sql
- and_sql
- or_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- strtotime_sql
- strtodate_sql
- parsedatetime_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- altercolumn_sql
- modifycolumn_sql
- alterindex_sql
- alterdiststyle_sql
- altersortkey_sql
- alterrename_sql
- renamecolumn_sql
- alterset_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- addpartition_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- havingmax_sql
- intdiv_sql
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_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
- trycast_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- 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
- tonumber_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_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
- struct_sql
- partitionrange_sql
- truncatetable_sql
- copyparameter_sql
- credentials_sql
- copy_sql
- semicolon_sql
- datadeletionproperty_sql
- maskingpolicycolumnconstraint_sql
- gapfill_sql
- 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
- arrayagg_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
- 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
- show_sql
- install_sql
- get_put_sql
- translatecharacters_sql
- decodecase_sql
- semanticview_sql
- getextract_sql
- datefromunixdate_sql
- space_sql
- buildproperty_sql
- refreshtriggerproperty_sql
- modelattribute_sql
- directorystage_sql
- uuid_sql
- initcap_sql
- localtime_sql
- localtimestamp_sql
- weekstart_name
- weekstart_sql
- chr_sql
- block_sql
- functionspecification_sql
- casestatement_sql
- loopblock_sql
- repeatblock_sql
- leave_sql
- iterate_sql
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql