sqlglot.dialects.tsql
1from __future__ import annotations 2 3import datetime 4import re 5import typing as t 6 7from sqlglot import exp, generator, parser, tokens, transforms 8from sqlglot.dialects.dialect import ( 9 Dialect, 10 NormalizationStrategy, 11 any_value_to_max_sql, 12 date_delta_sql, 13 generatedasidentitycolumnconstraint_sql, 14 max_or_greatest, 15 min_or_least, 16 parse_date_delta, 17 path_to_jsonpath, 18 rename_func, 19 timestrtotime_sql, 20 trim_sql, 21) 22from sqlglot.expressions import DataType 23from sqlglot.helper import seq_get 24from sqlglot.time import format_time 25from sqlglot.tokens import TokenType 26 27if t.TYPE_CHECKING: 28 from sqlglot._typing import E 29 30FULL_FORMAT_TIME_MAPPING = { 31 "weekday": "%A", 32 "dw": "%A", 33 "w": "%A", 34 "month": "%B", 35 "mm": "%B", 36 "m": "%B", 37} 38 39DATE_DELTA_INTERVAL = { 40 "year": "year", 41 "yyyy": "year", 42 "yy": "year", 43 "quarter": "quarter", 44 "qq": "quarter", 45 "q": "quarter", 46 "month": "month", 47 "mm": "month", 48 "m": "month", 49 "week": "week", 50 "ww": "week", 51 "wk": "week", 52 "day": "day", 53 "dd": "day", 54 "d": "day", 55} 56 57 58DATE_FMT_RE = re.compile("([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})") 59 60# N = Numeric, C=Currency 61TRANSPILE_SAFE_NUMBER_FMT = {"N", "C"} 62 63DEFAULT_START_DATE = datetime.date(1900, 1, 1) 64 65BIT_TYPES = {exp.EQ, exp.NEQ, exp.Is, exp.In, exp.Select, exp.Alias} 66 67 68def _format_time_lambda( 69 exp_class: t.Type[E], full_format_mapping: t.Optional[bool] = None 70) -> t.Callable[[t.List], E]: 71 def _format_time(args: t.List) -> E: 72 assert len(args) == 2 73 74 return exp_class( 75 this=exp.cast(args[1], "datetime"), 76 format=exp.Literal.string( 77 format_time( 78 args[0].name.lower(), 79 ( 80 {**TSQL.TIME_MAPPING, **FULL_FORMAT_TIME_MAPPING} 81 if full_format_mapping 82 else TSQL.TIME_MAPPING 83 ), 84 ) 85 ), 86 ) 87 88 return _format_time 89 90 91def _parse_format(args: t.List) -> exp.Expression: 92 this = seq_get(args, 0) 93 fmt = seq_get(args, 1) 94 culture = seq_get(args, 2) 95 96 number_fmt = fmt and (fmt.name in TRANSPILE_SAFE_NUMBER_FMT or not DATE_FMT_RE.search(fmt.name)) 97 98 if number_fmt: 99 return exp.NumberToStr(this=this, format=fmt, culture=culture) 100 101 if fmt: 102 fmt = exp.Literal.string( 103 format_time(fmt.name, TSQL.FORMAT_TIME_MAPPING) 104 if len(fmt.name) == 1 105 else format_time(fmt.name, TSQL.TIME_MAPPING) 106 ) 107 108 return exp.TimeToStr(this=this, format=fmt, culture=culture) 109 110 111def _parse_eomonth(args: t.List) -> exp.LastDay: 112 date = exp.TsOrDsToDate(this=seq_get(args, 0)) 113 month_lag = seq_get(args, 1) 114 115 if month_lag is None: 116 this: exp.Expression = date 117 else: 118 unit = DATE_DELTA_INTERVAL.get("month") 119 this = exp.DateAdd(this=date, expression=month_lag, unit=unit and exp.var(unit)) 120 121 return exp.LastDay(this=this) 122 123 124def _parse_hashbytes(args: t.List) -> exp.Expression: 125 kind, data = args 126 kind = kind.name.upper() if kind.is_string else "" 127 128 if kind == "MD5": 129 args.pop(0) 130 return exp.MD5(this=data) 131 if kind in ("SHA", "SHA1"): 132 args.pop(0) 133 return exp.SHA(this=data) 134 if kind == "SHA2_256": 135 return exp.SHA2(this=data, length=exp.Literal.number(256)) 136 if kind == "SHA2_512": 137 return exp.SHA2(this=data, length=exp.Literal.number(512)) 138 139 return exp.func("HASHBYTES", *args) 140 141 142DATEPART_ONLY_FORMATS = {"DW", "HOUR", "QUARTER"} 143 144 145def _format_sql(self: TSQL.Generator, expression: exp.NumberToStr | exp.TimeToStr) -> str: 146 fmt = expression.args["format"] 147 148 if not isinstance(expression, exp.NumberToStr): 149 if fmt.is_string: 150 mapped_fmt = format_time(fmt.name, TSQL.INVERSE_TIME_MAPPING) 151 152 name = (mapped_fmt or "").upper() 153 if name in DATEPART_ONLY_FORMATS: 154 return self.func("DATEPART", name, expression.this) 155 156 fmt_sql = self.sql(exp.Literal.string(mapped_fmt)) 157 else: 158 fmt_sql = self.format_time(expression) or self.sql(fmt) 159 else: 160 fmt_sql = self.sql(fmt) 161 162 return self.func("FORMAT", expression.this, fmt_sql, expression.args.get("culture")) 163 164 165def _string_agg_sql(self: TSQL.Generator, expression: exp.GroupConcat) -> str: 166 this = expression.this 167 distinct = expression.find(exp.Distinct) 168 if distinct: 169 # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression 170 self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.") 171 this = distinct.pop().expressions[0] 172 173 order = "" 174 if isinstance(expression.this, exp.Order): 175 if expression.this.this: 176 this = expression.this.this.pop() 177 order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})" # Order has a leading space 178 179 separator = expression.args.get("separator") or exp.Literal.string(",") 180 return f"STRING_AGG({self.format_args(this, separator)}){order}" 181 182 183def _parse_date_delta( 184 exp_class: t.Type[E], unit_mapping: t.Optional[t.Dict[str, str]] = None 185) -> t.Callable[[t.List], E]: 186 def inner_func(args: t.List) -> E: 187 unit = seq_get(args, 0) 188 if unit and unit_mapping: 189 unit = exp.var(unit_mapping.get(unit.name.lower(), unit.name)) 190 191 start_date = seq_get(args, 1) 192 if start_date and start_date.is_number: 193 # Numeric types are valid DATETIME values 194 if start_date.is_int: 195 adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this)) 196 start_date = exp.Literal.string(adds.strftime("%F")) 197 else: 198 # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs. 199 # This is not a problem when generating T-SQL code, it is when transpiling to other dialects. 200 return exp_class(this=seq_get(args, 2), expression=start_date, unit=unit) 201 202 return exp_class( 203 this=exp.TimeStrToTime(this=seq_get(args, 2)), 204 expression=exp.TimeStrToTime(this=start_date), 205 unit=unit, 206 ) 207 208 return inner_func 209 210 211def qualify_derived_table_outputs(expression: exp.Expression) -> exp.Expression: 212 """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.""" 213 alias = expression.args.get("alias") 214 215 if ( 216 isinstance(expression, (exp.CTE, exp.Subquery)) 217 and isinstance(alias, exp.TableAlias) 218 and not alias.columns 219 ): 220 from sqlglot.optimizer.qualify_columns import qualify_outputs 221 222 # We keep track of the unaliased column projection indexes instead of the expressions 223 # themselves, because the latter are going to be replaced by new nodes when the aliases 224 # are added and hence we won't be able to reach these newly added Alias parents 225 subqueryable = expression.this 226 unaliased_column_indexes = ( 227 i 228 for i, c in enumerate(subqueryable.selects) 229 if isinstance(c, exp.Column) and not c.alias 230 ) 231 232 qualify_outputs(subqueryable) 233 234 # Preserve the quoting information of columns for newly added Alias nodes 235 subqueryable_selects = subqueryable.selects 236 for select_index in unaliased_column_indexes: 237 alias = subqueryable_selects[select_index] 238 column = alias.this 239 if isinstance(column.this, exp.Identifier): 240 alias.args["alias"].set("quoted", column.this.quoted) 241 242 return expression 243 244 245# https://learn.microsoft.com/en-us/sql/t-sql/functions/datetimefromparts-transact-sql?view=sql-server-ver16#syntax 246def _parse_datetimefromparts(args: t.List) -> exp.TimestampFromParts: 247 return exp.TimestampFromParts( 248 year=seq_get(args, 0), 249 month=seq_get(args, 1), 250 day=seq_get(args, 2), 251 hour=seq_get(args, 3), 252 min=seq_get(args, 4), 253 sec=seq_get(args, 5), 254 milli=seq_get(args, 6), 255 ) 256 257 258# https://learn.microsoft.com/en-us/sql/t-sql/functions/timefromparts-transact-sql?view=sql-server-ver16#syntax 259def _parse_timefromparts(args: t.List) -> exp.TimeFromParts: 260 return exp.TimeFromParts( 261 hour=seq_get(args, 0), 262 min=seq_get(args, 1), 263 sec=seq_get(args, 2), 264 fractions=seq_get(args, 3), 265 precision=seq_get(args, 4), 266 ) 267 268 269def _parse_len(args: t.List) -> exp.Length: 270 this = seq_get(args, 0) 271 272 if this and not this.is_string: 273 this = exp.cast(this, exp.DataType.Type.TEXT) 274 275 return exp.Length(this=this) 276 277 278class TSQL(Dialect): 279 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 280 TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'" 281 SUPPORTS_SEMI_ANTI_JOIN = False 282 LOG_BASE_FIRST = False 283 TYPED_DIVISION = True 284 CONCAT_COALESCE = True 285 286 TIME_MAPPING = { 287 "year": "%Y", 288 "dayofyear": "%j", 289 "day": "%d", 290 "dy": "%d", 291 "y": "%Y", 292 "week": "%W", 293 "ww": "%W", 294 "wk": "%W", 295 "hour": "%h", 296 "hh": "%I", 297 "minute": "%M", 298 "mi": "%M", 299 "n": "%M", 300 "second": "%S", 301 "ss": "%S", 302 "s": "%-S", 303 "millisecond": "%f", 304 "ms": "%f", 305 "weekday": "%W", 306 "dw": "%W", 307 "month": "%m", 308 "mm": "%M", 309 "m": "%-M", 310 "Y": "%Y", 311 "YYYY": "%Y", 312 "YY": "%y", 313 "MMMM": "%B", 314 "MMM": "%b", 315 "MM": "%m", 316 "M": "%-m", 317 "dddd": "%A", 318 "dd": "%d", 319 "d": "%-d", 320 "HH": "%H", 321 "H": "%-H", 322 "h": "%-I", 323 "S": "%f", 324 "yyyy": "%Y", 325 "yy": "%y", 326 } 327 328 CONVERT_FORMAT_MAPPING = { 329 "0": "%b %d %Y %-I:%M%p", 330 "1": "%m/%d/%y", 331 "2": "%y.%m.%d", 332 "3": "%d/%m/%y", 333 "4": "%d.%m.%y", 334 "5": "%d-%m-%y", 335 "6": "%d %b %y", 336 "7": "%b %d, %y", 337 "8": "%H:%M:%S", 338 "9": "%b %d %Y %-I:%M:%S:%f%p", 339 "10": "mm-dd-yy", 340 "11": "yy/mm/dd", 341 "12": "yymmdd", 342 "13": "%d %b %Y %H:%M:ss:%f", 343 "14": "%H:%M:%S:%f", 344 "20": "%Y-%m-%d %H:%M:%S", 345 "21": "%Y-%m-%d %H:%M:%S.%f", 346 "22": "%m/%d/%y %-I:%M:%S %p", 347 "23": "%Y-%m-%d", 348 "24": "%H:%M:%S", 349 "25": "%Y-%m-%d %H:%M:%S.%f", 350 "100": "%b %d %Y %-I:%M%p", 351 "101": "%m/%d/%Y", 352 "102": "%Y.%m.%d", 353 "103": "%d/%m/%Y", 354 "104": "%d.%m.%Y", 355 "105": "%d-%m-%Y", 356 "106": "%d %b %Y", 357 "107": "%b %d, %Y", 358 "108": "%H:%M:%S", 359 "109": "%b %d %Y %-I:%M:%S:%f%p", 360 "110": "%m-%d-%Y", 361 "111": "%Y/%m/%d", 362 "112": "%Y%m%d", 363 "113": "%d %b %Y %H:%M:%S:%f", 364 "114": "%H:%M:%S:%f", 365 "120": "%Y-%m-%d %H:%M:%S", 366 "121": "%Y-%m-%d %H:%M:%S.%f", 367 } 368 369 FORMAT_TIME_MAPPING = { 370 "y": "%B %Y", 371 "d": "%m/%d/%Y", 372 "H": "%-H", 373 "h": "%-I", 374 "s": "%Y-%m-%d %H:%M:%S", 375 "D": "%A,%B,%Y", 376 "f": "%A,%B,%Y %-I:%M %p", 377 "F": "%A,%B,%Y %-I:%M:%S %p", 378 "g": "%m/%d/%Y %-I:%M %p", 379 "G": "%m/%d/%Y %-I:%M:%S %p", 380 "M": "%B %-d", 381 "m": "%B %-d", 382 "O": "%Y-%m-%dT%H:%M:%S", 383 "u": "%Y-%M-%D %H:%M:%S%z", 384 "U": "%A, %B %D, %Y %H:%M:%S%z", 385 "T": "%-I:%M:%S %p", 386 "t": "%-I:%M", 387 "Y": "%a %Y", 388 } 389 390 class Tokenizer(tokens.Tokenizer): 391 IDENTIFIERS = [("[", "]"), '"'] 392 QUOTES = ["'", '"'] 393 HEX_STRINGS = [("0x", ""), ("0X", "")] 394 VAR_SINGLE_TOKENS = {"@", "$", "#"} 395 396 KEYWORDS = { 397 **tokens.Tokenizer.KEYWORDS, 398 "DATETIME2": TokenType.DATETIME, 399 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 400 "DECLARE": TokenType.COMMAND, 401 "EXEC": TokenType.COMMAND, 402 "IMAGE": TokenType.IMAGE, 403 "MONEY": TokenType.MONEY, 404 "NTEXT": TokenType.TEXT, 405 "NVARCHAR(MAX)": TokenType.TEXT, 406 "PRINT": TokenType.COMMAND, 407 "PROC": TokenType.PROCEDURE, 408 "REAL": TokenType.FLOAT, 409 "ROWVERSION": TokenType.ROWVERSION, 410 "SMALLDATETIME": TokenType.DATETIME, 411 "SMALLMONEY": TokenType.SMALLMONEY, 412 "SQL_VARIANT": TokenType.VARIANT, 413 "TOP": TokenType.TOP, 414 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 415 "UPDATE STATISTICS": TokenType.COMMAND, 416 "VARCHAR(MAX)": TokenType.TEXT, 417 "XML": TokenType.XML, 418 "OUTPUT": TokenType.RETURNING, 419 "SYSTEM_USER": TokenType.CURRENT_USER, 420 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 421 } 422 423 class Parser(parser.Parser): 424 SET_REQUIRES_ASSIGNMENT_DELIMITER = False 425 426 FUNCTIONS = { 427 **parser.Parser.FUNCTIONS, 428 "CHARINDEX": lambda args: exp.StrPosition( 429 this=seq_get(args, 1), 430 substr=seq_get(args, 0), 431 position=seq_get(args, 2), 432 ), 433 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 434 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 435 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 436 "DATEPART": _format_time_lambda(exp.TimeToStr), 437 "DATETIMEFROMPARTS": _parse_datetimefromparts, 438 "EOMONTH": _parse_eomonth, 439 "FORMAT": _parse_format, 440 "GETDATE": exp.CurrentTimestamp.from_arg_list, 441 "HASHBYTES": _parse_hashbytes, 442 "IIF": exp.If.from_arg_list, 443 "ISNULL": exp.Coalesce.from_arg_list, 444 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 445 "LEN": _parse_len, 446 "REPLICATE": exp.Repeat.from_arg_list, 447 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 448 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 449 "SUSER_NAME": exp.CurrentUser.from_arg_list, 450 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 451 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 452 "TIMEFROMPARTS": _parse_timefromparts, 453 } 454 455 JOIN_HINTS = { 456 "LOOP", 457 "HASH", 458 "MERGE", 459 "REMOTE", 460 } 461 462 VAR_LENGTH_DATATYPES = { 463 DataType.Type.NVARCHAR, 464 DataType.Type.VARCHAR, 465 DataType.Type.CHAR, 466 DataType.Type.NCHAR, 467 } 468 469 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 470 TokenType.TABLE, 471 *parser.Parser.TYPE_TOKENS, 472 } 473 474 STATEMENT_PARSERS = { 475 **parser.Parser.STATEMENT_PARSERS, 476 TokenType.END: lambda self: self._parse_command(), 477 } 478 479 LOG_DEFAULTS_TO_LN = True 480 481 ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False 482 STRING_ALIASES = True 483 NO_PAREN_IF_COMMANDS = False 484 485 def _parse_projections(self) -> t.List[exp.Expression]: 486 """ 487 T-SQL supports the syntax alias = expression in the SELECT's projection list, 488 so we transform all parsed Selects to convert their EQ projections into Aliases. 489 490 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 491 """ 492 return [ 493 ( 494 exp.alias_(projection.expression, projection.this.this, copy=False) 495 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 496 else projection 497 ) 498 for projection in super()._parse_projections() 499 ] 500 501 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 502 """Applies to SQL Server and Azure SQL Database 503 COMMIT [ { TRAN | TRANSACTION } 504 [ transaction_name | @tran_name_variable ] ] 505 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 506 507 ROLLBACK { TRAN | TRANSACTION } 508 [ transaction_name | @tran_name_variable 509 | savepoint_name | @savepoint_variable ] 510 """ 511 rollback = self._prev.token_type == TokenType.ROLLBACK 512 513 self._match_texts(("TRAN", "TRANSACTION")) 514 this = self._parse_id_var() 515 516 if rollback: 517 return self.expression(exp.Rollback, this=this) 518 519 durability = None 520 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 521 self._match_text_seq("DELAYED_DURABILITY") 522 self._match(TokenType.EQ) 523 524 if self._match_text_seq("OFF"): 525 durability = False 526 else: 527 self._match(TokenType.ON) 528 durability = True 529 530 self._match_r_paren() 531 532 return self.expression(exp.Commit, this=this, durability=durability) 533 534 def _parse_transaction(self) -> exp.Transaction | exp.Command: 535 """Applies to SQL Server and Azure SQL Database 536 BEGIN { TRAN | TRANSACTION } 537 [ { transaction_name | @tran_name_variable } 538 [ WITH MARK [ 'description' ] ] 539 ] 540 """ 541 if self._match_texts(("TRAN", "TRANSACTION")): 542 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 543 if self._match_text_seq("WITH", "MARK"): 544 transaction.set("mark", self._parse_string()) 545 546 return transaction 547 548 return self._parse_as_command(self._prev) 549 550 def _parse_returns(self) -> exp.ReturnsProperty: 551 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 552 returns = super()._parse_returns() 553 returns.set("table", table) 554 return returns 555 556 def _parse_convert( 557 self, strict: bool, safe: t.Optional[bool] = None 558 ) -> t.Optional[exp.Expression]: 559 to = self._parse_types() 560 self._match(TokenType.COMMA) 561 this = self._parse_conjunction() 562 563 if not to or not this: 564 return None 565 566 # Retrieve length of datatype and override to default if not specified 567 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 568 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 569 570 # Check whether a conversion with format is applicable 571 if self._match(TokenType.COMMA): 572 format_val = self._parse_number() 573 format_val_name = format_val.name if format_val else "" 574 575 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 576 raise ValueError( 577 f"CONVERT function at T-SQL does not support format style {format_val_name}" 578 ) 579 580 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 581 582 # Check whether the convert entails a string to date format 583 if to.this == DataType.Type.DATE: 584 return self.expression(exp.StrToDate, this=this, format=format_norm) 585 # Check whether the convert entails a string to datetime format 586 elif to.this == DataType.Type.DATETIME: 587 return self.expression(exp.StrToTime, this=this, format=format_norm) 588 # Check whether the convert entails a date to string format 589 elif to.this in self.VAR_LENGTH_DATATYPES: 590 return self.expression( 591 exp.Cast if strict else exp.TryCast, 592 to=to, 593 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 594 safe=safe, 595 ) 596 elif to.this == DataType.Type.TEXT: 597 return self.expression(exp.TimeToStr, this=this, format=format_norm) 598 599 # Entails a simple cast without any format requirement 600 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe) 601 602 def _parse_user_defined_function( 603 self, kind: t.Optional[TokenType] = None 604 ) -> t.Optional[exp.Expression]: 605 this = super()._parse_user_defined_function(kind=kind) 606 607 if ( 608 kind == TokenType.FUNCTION 609 or isinstance(this, exp.UserDefinedFunction) 610 or self._match(TokenType.ALIAS, advance=False) 611 ): 612 return this 613 614 expressions = self._parse_csv(self._parse_function_parameter) 615 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 616 617 def _parse_id_var( 618 self, 619 any_token: bool = True, 620 tokens: t.Optional[t.Collection[TokenType]] = None, 621 ) -> t.Optional[exp.Expression]: 622 is_temporary = self._match(TokenType.HASH) 623 is_global = is_temporary and self._match(TokenType.HASH) 624 625 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 626 if this: 627 if is_global: 628 this.set("global", True) 629 elif is_temporary: 630 this.set("temporary", True) 631 632 return this 633 634 def _parse_create(self) -> exp.Create | exp.Command: 635 create = super()._parse_create() 636 637 if isinstance(create, exp.Create): 638 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 639 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 640 if not create.args.get("properties"): 641 create.set("properties", exp.Properties(expressions=[])) 642 643 create.args["properties"].append("expressions", exp.TemporaryProperty()) 644 645 return create 646 647 def _parse_if(self) -> t.Optional[exp.Expression]: 648 index = self._index 649 650 if self._match_text_seq("OBJECT_ID"): 651 self._parse_wrapped_csv(self._parse_string) 652 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 653 return self._parse_drop(exists=True) 654 self._retreat(index) 655 656 return super()._parse_if() 657 658 def _parse_unique(self) -> exp.UniqueColumnConstraint: 659 if self._match_texts(("CLUSTERED", "NONCLUSTERED")): 660 this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self) 661 else: 662 this = self._parse_schema(self._parse_id_var(any_token=False)) 663 664 return self.expression(exp.UniqueColumnConstraint, this=this) 665 666 class Generator(generator.Generator): 667 LIMIT_IS_TOP = True 668 QUERY_HINTS = False 669 RETURNING_END = False 670 NVL2_SUPPORTED = False 671 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 672 LIMIT_FETCH = "FETCH" 673 COMPUTED_COLUMN_WITH_TYPE = False 674 CTE_RECURSIVE_KEYWORD_REQUIRED = False 675 ENSURE_BOOLS = True 676 NULL_ORDERING_SUPPORTED = None 677 SUPPORTS_SINGLE_ARG_CONCAT = False 678 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 679 SUPPORTS_SELECT_INTO = True 680 681 EXPRESSIONS_WITHOUT_NESTED_CTES = { 682 exp.Delete, 683 exp.Insert, 684 exp.Merge, 685 exp.Select, 686 exp.Subquery, 687 exp.Union, 688 exp.Update, 689 } 690 691 TYPE_MAPPING = { 692 **generator.Generator.TYPE_MAPPING, 693 exp.DataType.Type.BOOLEAN: "BIT", 694 exp.DataType.Type.DECIMAL: "NUMERIC", 695 exp.DataType.Type.DATETIME: "DATETIME2", 696 exp.DataType.Type.DOUBLE: "FLOAT", 697 exp.DataType.Type.INT: "INTEGER", 698 exp.DataType.Type.TEXT: "VARCHAR(MAX)", 699 exp.DataType.Type.TIMESTAMP: "DATETIME2", 700 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 701 exp.DataType.Type.VARIANT: "SQL_VARIANT", 702 } 703 704 TRANSFORMS = { 705 **generator.Generator.TRANSFORMS, 706 exp.AnyValue: any_value_to_max_sql, 707 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 708 exp.DateAdd: date_delta_sql("DATEADD"), 709 exp.DateDiff: date_delta_sql("DATEDIFF"), 710 exp.CTE: transforms.preprocess([qualify_derived_table_outputs]), 711 exp.CurrentDate: rename_func("GETDATE"), 712 exp.CurrentTimestamp: rename_func("GETDATE"), 713 exp.Extract: rename_func("DATEPART"), 714 exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql, 715 exp.GetPath: path_to_jsonpath("JSON_VALUE"), 716 exp.GroupConcat: _string_agg_sql, 717 exp.If: rename_func("IIF"), 718 exp.LastDay: lambda self, e: self.func("EOMONTH", e.this), 719 exp.Max: max_or_greatest, 720 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 721 exp.Min: min_or_least, 722 exp.NumberToStr: _format_sql, 723 exp.ParseJSON: lambda self, e: self.sql(e, "this"), 724 exp.Select: transforms.preprocess( 725 [ 726 transforms.eliminate_distinct_on, 727 transforms.eliminate_semi_and_anti_joins, 728 transforms.eliminate_qualify, 729 ] 730 ), 731 exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]), 732 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 733 exp.SHA2: lambda self, e: self.func( 734 "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this 735 ), 736 exp.TemporaryProperty: lambda self, e: "", 737 exp.TimeStrToTime: timestrtotime_sql, 738 exp.TimeToStr: _format_sql, 739 exp.Trim: trim_sql, 740 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 741 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 742 } 743 744 TRANSFORMS.pop(exp.ReturnsProperty) 745 746 PROPERTIES_LOCATION = { 747 **generator.Generator.PROPERTIES_LOCATION, 748 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 749 } 750 751 def lateral_op(self, expression: exp.Lateral) -> str: 752 cross_apply = expression.args.get("cross_apply") 753 if cross_apply is True: 754 return "CROSS APPLY" 755 if cross_apply is False: 756 return "OUTER APPLY" 757 758 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 759 self.unsupported("LATERAL clause is not supported.") 760 return "LATERAL" 761 762 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 763 nano = expression.args.get("nano") 764 if nano is not None: 765 nano.pop() 766 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 767 768 if expression.args.get("fractions") is None: 769 expression.set("fractions", exp.Literal.number(0)) 770 if expression.args.get("precision") is None: 771 expression.set("precision", exp.Literal.number(0)) 772 773 return rename_func("TIMEFROMPARTS")(self, expression) 774 775 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 776 zone = expression.args.get("zone") 777 if zone is not None: 778 zone.pop() 779 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 780 781 nano = expression.args.get("nano") 782 if nano is not None: 783 nano.pop() 784 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 785 786 if expression.args.get("milli") is None: 787 expression.set("milli", exp.Literal.number(0)) 788 789 return rename_func("DATETIMEFROMPARTS")(self, expression) 790 791 def set_operation(self, expression: exp.Union, op: str) -> str: 792 limit = expression.args.get("limit") 793 if limit: 794 return self.sql(expression.limit(limit.pop(), copy=False)) 795 796 return super().set_operation(expression, op) 797 798 def setitem_sql(self, expression: exp.SetItem) -> str: 799 this = expression.this 800 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 801 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 802 return f"{self.sql(this.left)} {self.sql(this.right)}" 803 804 return super().setitem_sql(expression) 805 806 def boolean_sql(self, expression: exp.Boolean) -> str: 807 if type(expression.parent) in BIT_TYPES: 808 return "1" if expression.this else "0" 809 810 return "(1 = 1)" if expression.this else "(1 = 0)" 811 812 def is_sql(self, expression: exp.Is) -> str: 813 if isinstance(expression.expression, exp.Boolean): 814 return self.binary(expression, "=") 815 return self.binary(expression, "IS") 816 817 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 818 sql = self.sql(expression, "this") 819 properties = expression.args.get("properties") 820 821 if sql[:1] != "#" and any( 822 isinstance(prop, exp.TemporaryProperty) 823 for prop in (properties.expressions if properties else []) 824 ): 825 sql = f"#{sql}" 826 827 return sql 828 829 def create_sql(self, expression: exp.Create) -> str: 830 kind = self.sql(expression, "kind").upper() 831 exists = expression.args.pop("exists", None) 832 sql = super().create_sql(expression) 833 834 table = expression.find(exp.Table) 835 836 # Convert CTAS statement to SELECT .. INTO .. 837 if kind == "TABLE" and expression.expression: 838 ctas_with = expression.expression.args.get("with") 839 if ctas_with: 840 ctas_with = ctas_with.pop() 841 842 subquery = expression.expression 843 if isinstance(subquery, exp.Subqueryable): 844 subquery = subquery.subquery() 845 846 select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True)) 847 select_into.set("into", exp.Into(this=table)) 848 select_into.set("with", ctas_with) 849 850 sql = self.sql(select_into) 851 852 if exists: 853 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 854 sql = self.sql(exp.Literal.string(sql)) 855 if kind == "SCHEMA": 856 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})""" 857 elif kind == "TABLE": 858 assert table 859 where = exp.and_( 860 exp.column("table_name").eq(table.name), 861 exp.column("table_schema").eq(table.db) if table.db else None, 862 exp.column("table_catalog").eq(table.catalog) if table.catalog else None, 863 ) 864 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})""" 865 elif kind == "INDEX": 866 index = self.sql(exp.Literal.string(expression.this.text("this"))) 867 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})""" 868 elif expression.args.get("replace"): 869 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 870 871 return self.prepend_ctes(expression, sql) 872 873 def offset_sql(self, expression: exp.Offset) -> str: 874 return f"{super().offset_sql(expression)} ROWS" 875 876 def version_sql(self, expression: exp.Version) -> str: 877 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 878 this = f"FOR {name}" 879 expr = expression.expression 880 kind = expression.text("kind") 881 if kind in ("FROM", "BETWEEN"): 882 args = expr.expressions 883 sep = "TO" if kind == "FROM" else "AND" 884 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 885 else: 886 expr_sql = self.sql(expr) 887 888 expr_sql = f" {expr_sql}" if expr_sql else "" 889 return f"{this} {kind}{expr_sql}" 890 891 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 892 table = expression.args.get("table") 893 table = f"{table} " if table else "" 894 return f"RETURNS {table}{self.sql(expression, 'this')}" 895 896 def returning_sql(self, expression: exp.Returning) -> str: 897 into = self.sql(expression, "into") 898 into = self.seg(f"INTO {into}") if into else "" 899 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 900 901 def transaction_sql(self, expression: exp.Transaction) -> str: 902 this = self.sql(expression, "this") 903 this = f" {this}" if this else "" 904 mark = self.sql(expression, "mark") 905 mark = f" WITH MARK {mark}" if mark else "" 906 return f"BEGIN TRANSACTION{this}{mark}" 907 908 def commit_sql(self, expression: exp.Commit) -> str: 909 this = self.sql(expression, "this") 910 this = f" {this}" if this else "" 911 durability = expression.args.get("durability") 912 durability = ( 913 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 914 if durability is not None 915 else "" 916 ) 917 return f"COMMIT TRANSACTION{this}{durability}" 918 919 def rollback_sql(self, expression: exp.Rollback) -> str: 920 this = self.sql(expression, "this") 921 this = f" {this}" if this else "" 922 return f"ROLLBACK TRANSACTION{this}" 923 924 def identifier_sql(self, expression: exp.Identifier) -> str: 925 identifier = super().identifier_sql(expression) 926 927 if expression.args.get("global"): 928 identifier = f"##{identifier}" 929 elif expression.args.get("temporary"): 930 identifier = f"#{identifier}" 931 932 return identifier 933 934 def constraint_sql(self, expression: exp.Constraint) -> str: 935 this = self.sql(expression, "this") 936 expressions = self.expressions(expression, flat=True, sep=" ") 937 return f"CONSTRAINT {this} {expressions}" 938 939 def length_sql(self, expression: exp.Length) -> str: 940 this = expression.this 941 if isinstance(this, exp.Cast) and this.is_type(exp.DataType.Type.TEXT): 942 this_sql = self.sql(this, "this") 943 else: 944 this_sql = self.sql(this) 945 return self.func("LEN", this_sql)
FULL_FORMAT_TIME_MAPPING =
{'weekday': '%A', 'dw': '%A', 'w': '%A', 'month': '%B', 'mm': '%B', 'm': '%B'}
DATE_DELTA_INTERVAL =
{'year': 'year', 'yyyy': 'year', 'yy': 'year', 'quarter': 'quarter', 'qq': 'quarter', 'q': 'quarter', 'month': 'month', 'mm': 'month', 'm': 'month', 'week': 'week', 'ww': 'week', 'wk': 'week', 'day': 'day', 'dd': 'day', 'd': 'day'}
DATE_FMT_RE =
re.compile('([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})')
TRANSPILE_SAFE_NUMBER_FMT =
{'N', 'C'}
DEFAULT_START_DATE =
datetime.date(1900, 1, 1)
BIT_TYPES =
{<class 'sqlglot.expressions.NEQ'>, <class 'sqlglot.expressions.EQ'>, <class 'sqlglot.expressions.In'>, <class 'sqlglot.expressions.Alias'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Is'>}
DATEPART_ONLY_FORMATS =
{'HOUR', 'QUARTER', 'DW'}
def
qualify_derived_table_outputs( expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression:
212def qualify_derived_table_outputs(expression: exp.Expression) -> exp.Expression: 213 """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.""" 214 alias = expression.args.get("alias") 215 216 if ( 217 isinstance(expression, (exp.CTE, exp.Subquery)) 218 and isinstance(alias, exp.TableAlias) 219 and not alias.columns 220 ): 221 from sqlglot.optimizer.qualify_columns import qualify_outputs 222 223 # We keep track of the unaliased column projection indexes instead of the expressions 224 # themselves, because the latter are going to be replaced by new nodes when the aliases 225 # are added and hence we won't be able to reach these newly added Alias parents 226 subqueryable = expression.this 227 unaliased_column_indexes = ( 228 i 229 for i, c in enumerate(subqueryable.selects) 230 if isinstance(c, exp.Column) and not c.alias 231 ) 232 233 qualify_outputs(subqueryable) 234 235 # Preserve the quoting information of columns for newly added Alias nodes 236 subqueryable_selects = subqueryable.selects 237 for select_index in unaliased_column_indexes: 238 alias = subqueryable_selects[select_index] 239 column = alias.this 240 if isinstance(column.this, exp.Identifier): 241 alias.args["alias"].set("quoted", column.this.quoted) 242 243 return expression
Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.
279class TSQL(Dialect): 280 NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE 281 TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'" 282 SUPPORTS_SEMI_ANTI_JOIN = False 283 LOG_BASE_FIRST = False 284 TYPED_DIVISION = True 285 CONCAT_COALESCE = True 286 287 TIME_MAPPING = { 288 "year": "%Y", 289 "dayofyear": "%j", 290 "day": "%d", 291 "dy": "%d", 292 "y": "%Y", 293 "week": "%W", 294 "ww": "%W", 295 "wk": "%W", 296 "hour": "%h", 297 "hh": "%I", 298 "minute": "%M", 299 "mi": "%M", 300 "n": "%M", 301 "second": "%S", 302 "ss": "%S", 303 "s": "%-S", 304 "millisecond": "%f", 305 "ms": "%f", 306 "weekday": "%W", 307 "dw": "%W", 308 "month": "%m", 309 "mm": "%M", 310 "m": "%-M", 311 "Y": "%Y", 312 "YYYY": "%Y", 313 "YY": "%y", 314 "MMMM": "%B", 315 "MMM": "%b", 316 "MM": "%m", 317 "M": "%-m", 318 "dddd": "%A", 319 "dd": "%d", 320 "d": "%-d", 321 "HH": "%H", 322 "H": "%-H", 323 "h": "%-I", 324 "S": "%f", 325 "yyyy": "%Y", 326 "yy": "%y", 327 } 328 329 CONVERT_FORMAT_MAPPING = { 330 "0": "%b %d %Y %-I:%M%p", 331 "1": "%m/%d/%y", 332 "2": "%y.%m.%d", 333 "3": "%d/%m/%y", 334 "4": "%d.%m.%y", 335 "5": "%d-%m-%y", 336 "6": "%d %b %y", 337 "7": "%b %d, %y", 338 "8": "%H:%M:%S", 339 "9": "%b %d %Y %-I:%M:%S:%f%p", 340 "10": "mm-dd-yy", 341 "11": "yy/mm/dd", 342 "12": "yymmdd", 343 "13": "%d %b %Y %H:%M:ss:%f", 344 "14": "%H:%M:%S:%f", 345 "20": "%Y-%m-%d %H:%M:%S", 346 "21": "%Y-%m-%d %H:%M:%S.%f", 347 "22": "%m/%d/%y %-I:%M:%S %p", 348 "23": "%Y-%m-%d", 349 "24": "%H:%M:%S", 350 "25": "%Y-%m-%d %H:%M:%S.%f", 351 "100": "%b %d %Y %-I:%M%p", 352 "101": "%m/%d/%Y", 353 "102": "%Y.%m.%d", 354 "103": "%d/%m/%Y", 355 "104": "%d.%m.%Y", 356 "105": "%d-%m-%Y", 357 "106": "%d %b %Y", 358 "107": "%b %d, %Y", 359 "108": "%H:%M:%S", 360 "109": "%b %d %Y %-I:%M:%S:%f%p", 361 "110": "%m-%d-%Y", 362 "111": "%Y/%m/%d", 363 "112": "%Y%m%d", 364 "113": "%d %b %Y %H:%M:%S:%f", 365 "114": "%H:%M:%S:%f", 366 "120": "%Y-%m-%d %H:%M:%S", 367 "121": "%Y-%m-%d %H:%M:%S.%f", 368 } 369 370 FORMAT_TIME_MAPPING = { 371 "y": "%B %Y", 372 "d": "%m/%d/%Y", 373 "H": "%-H", 374 "h": "%-I", 375 "s": "%Y-%m-%d %H:%M:%S", 376 "D": "%A,%B,%Y", 377 "f": "%A,%B,%Y %-I:%M %p", 378 "F": "%A,%B,%Y %-I:%M:%S %p", 379 "g": "%m/%d/%Y %-I:%M %p", 380 "G": "%m/%d/%Y %-I:%M:%S %p", 381 "M": "%B %-d", 382 "m": "%B %-d", 383 "O": "%Y-%m-%dT%H:%M:%S", 384 "u": "%Y-%M-%D %H:%M:%S%z", 385 "U": "%A, %B %D, %Y %H:%M:%S%z", 386 "T": "%-I:%M:%S %p", 387 "t": "%-I:%M", 388 "Y": "%a %Y", 389 } 390 391 class Tokenizer(tokens.Tokenizer): 392 IDENTIFIERS = [("[", "]"), '"'] 393 QUOTES = ["'", '"'] 394 HEX_STRINGS = [("0x", ""), ("0X", "")] 395 VAR_SINGLE_TOKENS = {"@", "$", "#"} 396 397 KEYWORDS = { 398 **tokens.Tokenizer.KEYWORDS, 399 "DATETIME2": TokenType.DATETIME, 400 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 401 "DECLARE": TokenType.COMMAND, 402 "EXEC": TokenType.COMMAND, 403 "IMAGE": TokenType.IMAGE, 404 "MONEY": TokenType.MONEY, 405 "NTEXT": TokenType.TEXT, 406 "NVARCHAR(MAX)": TokenType.TEXT, 407 "PRINT": TokenType.COMMAND, 408 "PROC": TokenType.PROCEDURE, 409 "REAL": TokenType.FLOAT, 410 "ROWVERSION": TokenType.ROWVERSION, 411 "SMALLDATETIME": TokenType.DATETIME, 412 "SMALLMONEY": TokenType.SMALLMONEY, 413 "SQL_VARIANT": TokenType.VARIANT, 414 "TOP": TokenType.TOP, 415 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 416 "UPDATE STATISTICS": TokenType.COMMAND, 417 "VARCHAR(MAX)": TokenType.TEXT, 418 "XML": TokenType.XML, 419 "OUTPUT": TokenType.RETURNING, 420 "SYSTEM_USER": TokenType.CURRENT_USER, 421 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 422 } 423 424 class Parser(parser.Parser): 425 SET_REQUIRES_ASSIGNMENT_DELIMITER = False 426 427 FUNCTIONS = { 428 **parser.Parser.FUNCTIONS, 429 "CHARINDEX": lambda args: exp.StrPosition( 430 this=seq_get(args, 1), 431 substr=seq_get(args, 0), 432 position=seq_get(args, 2), 433 ), 434 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 435 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 436 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 437 "DATEPART": _format_time_lambda(exp.TimeToStr), 438 "DATETIMEFROMPARTS": _parse_datetimefromparts, 439 "EOMONTH": _parse_eomonth, 440 "FORMAT": _parse_format, 441 "GETDATE": exp.CurrentTimestamp.from_arg_list, 442 "HASHBYTES": _parse_hashbytes, 443 "IIF": exp.If.from_arg_list, 444 "ISNULL": exp.Coalesce.from_arg_list, 445 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 446 "LEN": _parse_len, 447 "REPLICATE": exp.Repeat.from_arg_list, 448 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 449 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 450 "SUSER_NAME": exp.CurrentUser.from_arg_list, 451 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 452 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 453 "TIMEFROMPARTS": _parse_timefromparts, 454 } 455 456 JOIN_HINTS = { 457 "LOOP", 458 "HASH", 459 "MERGE", 460 "REMOTE", 461 } 462 463 VAR_LENGTH_DATATYPES = { 464 DataType.Type.NVARCHAR, 465 DataType.Type.VARCHAR, 466 DataType.Type.CHAR, 467 DataType.Type.NCHAR, 468 } 469 470 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 471 TokenType.TABLE, 472 *parser.Parser.TYPE_TOKENS, 473 } 474 475 STATEMENT_PARSERS = { 476 **parser.Parser.STATEMENT_PARSERS, 477 TokenType.END: lambda self: self._parse_command(), 478 } 479 480 LOG_DEFAULTS_TO_LN = True 481 482 ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False 483 STRING_ALIASES = True 484 NO_PAREN_IF_COMMANDS = False 485 486 def _parse_projections(self) -> t.List[exp.Expression]: 487 """ 488 T-SQL supports the syntax alias = expression in the SELECT's projection list, 489 so we transform all parsed Selects to convert their EQ projections into Aliases. 490 491 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 492 """ 493 return [ 494 ( 495 exp.alias_(projection.expression, projection.this.this, copy=False) 496 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 497 else projection 498 ) 499 for projection in super()._parse_projections() 500 ] 501 502 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 503 """Applies to SQL Server and Azure SQL Database 504 COMMIT [ { TRAN | TRANSACTION } 505 [ transaction_name | @tran_name_variable ] ] 506 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 507 508 ROLLBACK { TRAN | TRANSACTION } 509 [ transaction_name | @tran_name_variable 510 | savepoint_name | @savepoint_variable ] 511 """ 512 rollback = self._prev.token_type == TokenType.ROLLBACK 513 514 self._match_texts(("TRAN", "TRANSACTION")) 515 this = self._parse_id_var() 516 517 if rollback: 518 return self.expression(exp.Rollback, this=this) 519 520 durability = None 521 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 522 self._match_text_seq("DELAYED_DURABILITY") 523 self._match(TokenType.EQ) 524 525 if self._match_text_seq("OFF"): 526 durability = False 527 else: 528 self._match(TokenType.ON) 529 durability = True 530 531 self._match_r_paren() 532 533 return self.expression(exp.Commit, this=this, durability=durability) 534 535 def _parse_transaction(self) -> exp.Transaction | exp.Command: 536 """Applies to SQL Server and Azure SQL Database 537 BEGIN { TRAN | TRANSACTION } 538 [ { transaction_name | @tran_name_variable } 539 [ WITH MARK [ 'description' ] ] 540 ] 541 """ 542 if self._match_texts(("TRAN", "TRANSACTION")): 543 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 544 if self._match_text_seq("WITH", "MARK"): 545 transaction.set("mark", self._parse_string()) 546 547 return transaction 548 549 return self._parse_as_command(self._prev) 550 551 def _parse_returns(self) -> exp.ReturnsProperty: 552 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 553 returns = super()._parse_returns() 554 returns.set("table", table) 555 return returns 556 557 def _parse_convert( 558 self, strict: bool, safe: t.Optional[bool] = None 559 ) -> t.Optional[exp.Expression]: 560 to = self._parse_types() 561 self._match(TokenType.COMMA) 562 this = self._parse_conjunction() 563 564 if not to or not this: 565 return None 566 567 # Retrieve length of datatype and override to default if not specified 568 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 569 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 570 571 # Check whether a conversion with format is applicable 572 if self._match(TokenType.COMMA): 573 format_val = self._parse_number() 574 format_val_name = format_val.name if format_val else "" 575 576 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 577 raise ValueError( 578 f"CONVERT function at T-SQL does not support format style {format_val_name}" 579 ) 580 581 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 582 583 # Check whether the convert entails a string to date format 584 if to.this == DataType.Type.DATE: 585 return self.expression(exp.StrToDate, this=this, format=format_norm) 586 # Check whether the convert entails a string to datetime format 587 elif to.this == DataType.Type.DATETIME: 588 return self.expression(exp.StrToTime, this=this, format=format_norm) 589 # Check whether the convert entails a date to string format 590 elif to.this in self.VAR_LENGTH_DATATYPES: 591 return self.expression( 592 exp.Cast if strict else exp.TryCast, 593 to=to, 594 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 595 safe=safe, 596 ) 597 elif to.this == DataType.Type.TEXT: 598 return self.expression(exp.TimeToStr, this=this, format=format_norm) 599 600 # Entails a simple cast without any format requirement 601 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe) 602 603 def _parse_user_defined_function( 604 self, kind: t.Optional[TokenType] = None 605 ) -> t.Optional[exp.Expression]: 606 this = super()._parse_user_defined_function(kind=kind) 607 608 if ( 609 kind == TokenType.FUNCTION 610 or isinstance(this, exp.UserDefinedFunction) 611 or self._match(TokenType.ALIAS, advance=False) 612 ): 613 return this 614 615 expressions = self._parse_csv(self._parse_function_parameter) 616 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 617 618 def _parse_id_var( 619 self, 620 any_token: bool = True, 621 tokens: t.Optional[t.Collection[TokenType]] = None, 622 ) -> t.Optional[exp.Expression]: 623 is_temporary = self._match(TokenType.HASH) 624 is_global = is_temporary and self._match(TokenType.HASH) 625 626 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 627 if this: 628 if is_global: 629 this.set("global", True) 630 elif is_temporary: 631 this.set("temporary", True) 632 633 return this 634 635 def _parse_create(self) -> exp.Create | exp.Command: 636 create = super()._parse_create() 637 638 if isinstance(create, exp.Create): 639 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 640 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 641 if not create.args.get("properties"): 642 create.set("properties", exp.Properties(expressions=[])) 643 644 create.args["properties"].append("expressions", exp.TemporaryProperty()) 645 646 return create 647 648 def _parse_if(self) -> t.Optional[exp.Expression]: 649 index = self._index 650 651 if self._match_text_seq("OBJECT_ID"): 652 self._parse_wrapped_csv(self._parse_string) 653 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 654 return self._parse_drop(exists=True) 655 self._retreat(index) 656 657 return super()._parse_if() 658 659 def _parse_unique(self) -> exp.UniqueColumnConstraint: 660 if self._match_texts(("CLUSTERED", "NONCLUSTERED")): 661 this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self) 662 else: 663 this = self._parse_schema(self._parse_id_var(any_token=False)) 664 665 return self.expression(exp.UniqueColumnConstraint, this=this) 666 667 class Generator(generator.Generator): 668 LIMIT_IS_TOP = True 669 QUERY_HINTS = False 670 RETURNING_END = False 671 NVL2_SUPPORTED = False 672 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 673 LIMIT_FETCH = "FETCH" 674 COMPUTED_COLUMN_WITH_TYPE = False 675 CTE_RECURSIVE_KEYWORD_REQUIRED = False 676 ENSURE_BOOLS = True 677 NULL_ORDERING_SUPPORTED = None 678 SUPPORTS_SINGLE_ARG_CONCAT = False 679 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 680 SUPPORTS_SELECT_INTO = True 681 682 EXPRESSIONS_WITHOUT_NESTED_CTES = { 683 exp.Delete, 684 exp.Insert, 685 exp.Merge, 686 exp.Select, 687 exp.Subquery, 688 exp.Union, 689 exp.Update, 690 } 691 692 TYPE_MAPPING = { 693 **generator.Generator.TYPE_MAPPING, 694 exp.DataType.Type.BOOLEAN: "BIT", 695 exp.DataType.Type.DECIMAL: "NUMERIC", 696 exp.DataType.Type.DATETIME: "DATETIME2", 697 exp.DataType.Type.DOUBLE: "FLOAT", 698 exp.DataType.Type.INT: "INTEGER", 699 exp.DataType.Type.TEXT: "VARCHAR(MAX)", 700 exp.DataType.Type.TIMESTAMP: "DATETIME2", 701 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 702 exp.DataType.Type.VARIANT: "SQL_VARIANT", 703 } 704 705 TRANSFORMS = { 706 **generator.Generator.TRANSFORMS, 707 exp.AnyValue: any_value_to_max_sql, 708 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 709 exp.DateAdd: date_delta_sql("DATEADD"), 710 exp.DateDiff: date_delta_sql("DATEDIFF"), 711 exp.CTE: transforms.preprocess([qualify_derived_table_outputs]), 712 exp.CurrentDate: rename_func("GETDATE"), 713 exp.CurrentTimestamp: rename_func("GETDATE"), 714 exp.Extract: rename_func("DATEPART"), 715 exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql, 716 exp.GetPath: path_to_jsonpath("JSON_VALUE"), 717 exp.GroupConcat: _string_agg_sql, 718 exp.If: rename_func("IIF"), 719 exp.LastDay: lambda self, e: self.func("EOMONTH", e.this), 720 exp.Max: max_or_greatest, 721 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 722 exp.Min: min_or_least, 723 exp.NumberToStr: _format_sql, 724 exp.ParseJSON: lambda self, e: self.sql(e, "this"), 725 exp.Select: transforms.preprocess( 726 [ 727 transforms.eliminate_distinct_on, 728 transforms.eliminate_semi_and_anti_joins, 729 transforms.eliminate_qualify, 730 ] 731 ), 732 exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]), 733 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 734 exp.SHA2: lambda self, e: self.func( 735 "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this 736 ), 737 exp.TemporaryProperty: lambda self, e: "", 738 exp.TimeStrToTime: timestrtotime_sql, 739 exp.TimeToStr: _format_sql, 740 exp.Trim: trim_sql, 741 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 742 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 743 } 744 745 TRANSFORMS.pop(exp.ReturnsProperty) 746 747 PROPERTIES_LOCATION = { 748 **generator.Generator.PROPERTIES_LOCATION, 749 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 750 } 751 752 def lateral_op(self, expression: exp.Lateral) -> str: 753 cross_apply = expression.args.get("cross_apply") 754 if cross_apply is True: 755 return "CROSS APPLY" 756 if cross_apply is False: 757 return "OUTER APPLY" 758 759 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 760 self.unsupported("LATERAL clause is not supported.") 761 return "LATERAL" 762 763 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 764 nano = expression.args.get("nano") 765 if nano is not None: 766 nano.pop() 767 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 768 769 if expression.args.get("fractions") is None: 770 expression.set("fractions", exp.Literal.number(0)) 771 if expression.args.get("precision") is None: 772 expression.set("precision", exp.Literal.number(0)) 773 774 return rename_func("TIMEFROMPARTS")(self, expression) 775 776 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 777 zone = expression.args.get("zone") 778 if zone is not None: 779 zone.pop() 780 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 781 782 nano = expression.args.get("nano") 783 if nano is not None: 784 nano.pop() 785 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 786 787 if expression.args.get("milli") is None: 788 expression.set("milli", exp.Literal.number(0)) 789 790 return rename_func("DATETIMEFROMPARTS")(self, expression) 791 792 def set_operation(self, expression: exp.Union, op: str) -> str: 793 limit = expression.args.get("limit") 794 if limit: 795 return self.sql(expression.limit(limit.pop(), copy=False)) 796 797 return super().set_operation(expression, op) 798 799 def setitem_sql(self, expression: exp.SetItem) -> str: 800 this = expression.this 801 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 802 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 803 return f"{self.sql(this.left)} {self.sql(this.right)}" 804 805 return super().setitem_sql(expression) 806 807 def boolean_sql(self, expression: exp.Boolean) -> str: 808 if type(expression.parent) in BIT_TYPES: 809 return "1" if expression.this else "0" 810 811 return "(1 = 1)" if expression.this else "(1 = 0)" 812 813 def is_sql(self, expression: exp.Is) -> str: 814 if isinstance(expression.expression, exp.Boolean): 815 return self.binary(expression, "=") 816 return self.binary(expression, "IS") 817 818 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 819 sql = self.sql(expression, "this") 820 properties = expression.args.get("properties") 821 822 if sql[:1] != "#" and any( 823 isinstance(prop, exp.TemporaryProperty) 824 for prop in (properties.expressions if properties else []) 825 ): 826 sql = f"#{sql}" 827 828 return sql 829 830 def create_sql(self, expression: exp.Create) -> str: 831 kind = self.sql(expression, "kind").upper() 832 exists = expression.args.pop("exists", None) 833 sql = super().create_sql(expression) 834 835 table = expression.find(exp.Table) 836 837 # Convert CTAS statement to SELECT .. INTO .. 838 if kind == "TABLE" and expression.expression: 839 ctas_with = expression.expression.args.get("with") 840 if ctas_with: 841 ctas_with = ctas_with.pop() 842 843 subquery = expression.expression 844 if isinstance(subquery, exp.Subqueryable): 845 subquery = subquery.subquery() 846 847 select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True)) 848 select_into.set("into", exp.Into(this=table)) 849 select_into.set("with", ctas_with) 850 851 sql = self.sql(select_into) 852 853 if exists: 854 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 855 sql = self.sql(exp.Literal.string(sql)) 856 if kind == "SCHEMA": 857 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})""" 858 elif kind == "TABLE": 859 assert table 860 where = exp.and_( 861 exp.column("table_name").eq(table.name), 862 exp.column("table_schema").eq(table.db) if table.db else None, 863 exp.column("table_catalog").eq(table.catalog) if table.catalog else None, 864 ) 865 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})""" 866 elif kind == "INDEX": 867 index = self.sql(exp.Literal.string(expression.this.text("this"))) 868 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})""" 869 elif expression.args.get("replace"): 870 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 871 872 return self.prepend_ctes(expression, sql) 873 874 def offset_sql(self, expression: exp.Offset) -> str: 875 return f"{super().offset_sql(expression)} ROWS" 876 877 def version_sql(self, expression: exp.Version) -> str: 878 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 879 this = f"FOR {name}" 880 expr = expression.expression 881 kind = expression.text("kind") 882 if kind in ("FROM", "BETWEEN"): 883 args = expr.expressions 884 sep = "TO" if kind == "FROM" else "AND" 885 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 886 else: 887 expr_sql = self.sql(expr) 888 889 expr_sql = f" {expr_sql}" if expr_sql else "" 890 return f"{this} {kind}{expr_sql}" 891 892 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 893 table = expression.args.get("table") 894 table = f"{table} " if table else "" 895 return f"RETURNS {table}{self.sql(expression, 'this')}" 896 897 def returning_sql(self, expression: exp.Returning) -> str: 898 into = self.sql(expression, "into") 899 into = self.seg(f"INTO {into}") if into else "" 900 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 901 902 def transaction_sql(self, expression: exp.Transaction) -> str: 903 this = self.sql(expression, "this") 904 this = f" {this}" if this else "" 905 mark = self.sql(expression, "mark") 906 mark = f" WITH MARK {mark}" if mark else "" 907 return f"BEGIN TRANSACTION{this}{mark}" 908 909 def commit_sql(self, expression: exp.Commit) -> str: 910 this = self.sql(expression, "this") 911 this = f" {this}" if this else "" 912 durability = expression.args.get("durability") 913 durability = ( 914 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 915 if durability is not None 916 else "" 917 ) 918 return f"COMMIT TRANSACTION{this}{durability}" 919 920 def rollback_sql(self, expression: exp.Rollback) -> str: 921 this = self.sql(expression, "this") 922 this = f" {this}" if this else "" 923 return f"ROLLBACK TRANSACTION{this}" 924 925 def identifier_sql(self, expression: exp.Identifier) -> str: 926 identifier = super().identifier_sql(expression) 927 928 if expression.args.get("global"): 929 identifier = f"##{identifier}" 930 elif expression.args.get("temporary"): 931 identifier = f"#{identifier}" 932 933 return identifier 934 935 def constraint_sql(self, expression: exp.Constraint) -> str: 936 this = self.sql(expression, "this") 937 expressions = self.expressions(expression, flat=True, sep=" ") 938 return f"CONSTRAINT {this} {expressions}" 939 940 def length_sql(self, expression: exp.Length) -> str: 941 this = expression.this 942 if isinstance(this, exp.Cast) and this.is_type(exp.DataType.Type.TEXT): 943 this_sql = self.sql(this, "this") 944 else: 945 this_sql = self.sql(this) 946 return self.func("LEN", this_sql)
NORMALIZATION_STRATEGY =
<NormalizationStrategy.CASE_INSENSITIVE: 'CASE_INSENSITIVE'>
Specifies the strategy according to which identifiers should be normalized.
TYPED_DIVISION =
True
Whether the behavior of a / b
depends on the types of a
and b
.
False means a / b
is always float division.
True means a / b
is integer division if both a
and b
are integers.
CONCAT_COALESCE =
True
A NULL
arg in CONCAT
yields NULL
by default, but in some dialects it yields an empty string.
TIME_MAPPING: Dict[str, str] =
{'year': '%Y', 'dayofyear': '%j', 'day': '%d', 'dy': '%d', 'y': '%Y', 'week': '%W', 'ww': '%W', 'wk': '%W', 'hour': '%h', 'hh': '%I', 'minute': '%M', 'mi': '%M', 'n': '%M', 'second': '%S', 'ss': '%S', 's': '%-S', 'millisecond': '%f', 'ms': '%f', 'weekday': '%W', 'dw': '%W', 'month': '%m', 'mm': '%M', 'm': '%-M', 'Y': '%Y', 'YYYY': '%Y', 'YY': '%y', 'MMMM': '%B', 'MMM': '%b', 'MM': '%m', 'M': '%-m', 'dddd': '%A', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
Associates this dialect's time formats with their equivalent Python strftime
format.
CONVERT_FORMAT_MAPPING =
{'0': '%b %d %Y %-I:%M%p', '1': '%m/%d/%y', '2': '%y.%m.%d', '3': '%d/%m/%y', '4': '%d.%m.%y', '5': '%d-%m-%y', '6': '%d %b %y', '7': '%b %d, %y', '8': '%H:%M:%S', '9': '%b %d %Y %-I:%M:%S:%f%p', '10': 'mm-dd-yy', '11': 'yy/mm/dd', '12': 'yymmdd', '13': '%d %b %Y %H:%M:ss:%f', '14': '%H:%M:%S:%f', '20': '%Y-%m-%d %H:%M:%S', '21': '%Y-%m-%d %H:%M:%S.%f', '22': '%m/%d/%y %-I:%M:%S %p', '23': '%Y-%m-%d', '24': '%H:%M:%S', '25': '%Y-%m-%d %H:%M:%S.%f', '100': '%b %d %Y %-I:%M%p', '101': '%m/%d/%Y', '102': '%Y.%m.%d', '103': '%d/%m/%Y', '104': '%d.%m.%Y', '105': '%d-%m-%Y', '106': '%d %b %Y', '107': '%b %d, %Y', '108': '%H:%M:%S', '109': '%b %d %Y %-I:%M:%S:%f%p', '110': '%m-%d-%Y', '111': '%Y/%m/%d', '112': '%Y%m%d', '113': '%d %b %Y %H:%M:%S:%f', '114': '%H:%M:%S:%f', '120': '%Y-%m-%d %H:%M:%S', '121': '%Y-%m-%d %H:%M:%S.%f'}
FORMAT_TIME_MAPPING =
{'y': '%B %Y', 'd': '%m/%d/%Y', 'H': '%-H', 'h': '%-I', 's': '%Y-%m-%d %H:%M:%S', 'D': '%A,%B,%Y', 'f': '%A,%B,%Y %-I:%M %p', 'F': '%A,%B,%Y %-I:%M:%S %p', 'g': '%m/%d/%Y %-I:%M %p', 'G': '%m/%d/%Y %-I:%M:%S %p', 'M': '%B %-d', 'm': '%B %-d', 'O': '%Y-%m-%dT%H:%M:%S', 'u': '%Y-%M-%D %H:%M:%S%z', 'U': '%A, %B %D, %Y %H:%M:%S%z', 'T': '%-I:%M:%S %p', 't': '%-I:%M', 'Y': '%a %Y'}
tokenizer_class =
<class 'TSQL.Tokenizer'>
parser_class =
<class 'TSQL.Parser'>
generator_class =
<class 'TSQL.Generator'>
TIME_TRIE: Dict =
{'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
FORMAT_TRIE: Dict =
{'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
INVERSE_TIME_MAPPING: Dict[str, str] =
{'%Y': 'yyyy', '%j': 'dayofyear', '%d': 'dd', '%W': 'dw', '%h': 'hour', '%I': 'hh', '%M': 'mm', '%S': 'ss', '%-S': 's', '%f': 'S', '%m': 'MM', '%-M': 'm', '%y': 'yy', '%B': 'MMMM', '%b': 'MMM', '%-m': 'M', '%A': 'dddd', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict =
{'%': {'Y': {0: True}, 'j': {0: True}, 'd': {0: True}, 'W': {0: True}, 'h': {0: True}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, '-': {'S': {0: True}, 'M': {0: True}, 'm': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'f': {0: True}, 'm': {0: True}, 'y': {0: True}, 'B': {0: True}, 'b': {0: True}, 'A': {0: True}, 'H': {0: True}}}
Inherited Members
- sqlglot.dialects.dialect.Dialect
- Dialect
- INDEX_OFFSET
- WEEK_OFFSET
- UNNEST_COLUMN_ONLY
- ALIAS_POST_TABLESAMPLE
- TABLESAMPLE_SIZE_IS_PERCENT
- IDENTIFIERS_CAN_START_WITH_DIGIT
- DPIPE_IS_STRING_CONCAT
- STRICT_STRING_CONCAT
- SUPPORTS_USER_DEFINED_TYPES
- NORMALIZE_FUNCTIONS
- NULL_ORDERING
- SAFE_DIVISION
- DATE_FORMAT
- DATEINT_FORMAT
- FORMAT_MAPPING
- ESCAPE_SEQUENCES
- PSEUDOCOLUMNS
- PREFER_CTE_ALIAS_COLUMN
- get_or_raise
- format_time
- normalize_identifier
- case_sensitive
- can_identify
- quote_identifier
- parse
- parse_into
- generate
- transpile
- tokenize
- tokenizer
- parser
- generator
391 class Tokenizer(tokens.Tokenizer): 392 IDENTIFIERS = [("[", "]"), '"'] 393 QUOTES = ["'", '"'] 394 HEX_STRINGS = [("0x", ""), ("0X", "")] 395 VAR_SINGLE_TOKENS = {"@", "$", "#"} 396 397 KEYWORDS = { 398 **tokens.Tokenizer.KEYWORDS, 399 "DATETIME2": TokenType.DATETIME, 400 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 401 "DECLARE": TokenType.COMMAND, 402 "EXEC": TokenType.COMMAND, 403 "IMAGE": TokenType.IMAGE, 404 "MONEY": TokenType.MONEY, 405 "NTEXT": TokenType.TEXT, 406 "NVARCHAR(MAX)": TokenType.TEXT, 407 "PRINT": TokenType.COMMAND, 408 "PROC": TokenType.PROCEDURE, 409 "REAL": TokenType.FLOAT, 410 "ROWVERSION": TokenType.ROWVERSION, 411 "SMALLDATETIME": TokenType.DATETIME, 412 "SMALLMONEY": TokenType.SMALLMONEY, 413 "SQL_VARIANT": TokenType.VARIANT, 414 "TOP": TokenType.TOP, 415 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 416 "UPDATE STATISTICS": TokenType.COMMAND, 417 "VARCHAR(MAX)": TokenType.TEXT, 418 "XML": TokenType.XML, 419 "OUTPUT": TokenType.RETURNING, 420 "SYSTEM_USER": TokenType.CURRENT_USER, 421 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 422 }
KEYWORDS =
{'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'EXEC': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, 'NVARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'PRINT': <TokenType.COMMAND: 'COMMAND'>, 'PROC': <TokenType.PROCEDURE: 'PROCEDURE'>, 'ROWVERSION': <TokenType.ROWVERSION: 'ROWVERSION'>, 'SMALLDATETIME': <TokenType.DATETIME: 'DATETIME'>, 'SMALLMONEY': <TokenType.SMALLMONEY: 'SMALLMONEY'>, 'SQL_VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'TOP': <TokenType.TOP: 'TOP'>, 'UNIQUEIDENTIFIER': <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, 'UPDATE STATISTICS': <TokenType.COMMAND: 'COMMAND'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'FOR SYSTEM_TIME': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
424 class Parser(parser.Parser): 425 SET_REQUIRES_ASSIGNMENT_DELIMITER = False 426 427 FUNCTIONS = { 428 **parser.Parser.FUNCTIONS, 429 "CHARINDEX": lambda args: exp.StrPosition( 430 this=seq_get(args, 1), 431 substr=seq_get(args, 0), 432 position=seq_get(args, 2), 433 ), 434 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 435 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 436 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 437 "DATEPART": _format_time_lambda(exp.TimeToStr), 438 "DATETIMEFROMPARTS": _parse_datetimefromparts, 439 "EOMONTH": _parse_eomonth, 440 "FORMAT": _parse_format, 441 "GETDATE": exp.CurrentTimestamp.from_arg_list, 442 "HASHBYTES": _parse_hashbytes, 443 "IIF": exp.If.from_arg_list, 444 "ISNULL": exp.Coalesce.from_arg_list, 445 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 446 "LEN": _parse_len, 447 "REPLICATE": exp.Repeat.from_arg_list, 448 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 449 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 450 "SUSER_NAME": exp.CurrentUser.from_arg_list, 451 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 452 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 453 "TIMEFROMPARTS": _parse_timefromparts, 454 } 455 456 JOIN_HINTS = { 457 "LOOP", 458 "HASH", 459 "MERGE", 460 "REMOTE", 461 } 462 463 VAR_LENGTH_DATATYPES = { 464 DataType.Type.NVARCHAR, 465 DataType.Type.VARCHAR, 466 DataType.Type.CHAR, 467 DataType.Type.NCHAR, 468 } 469 470 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 471 TokenType.TABLE, 472 *parser.Parser.TYPE_TOKENS, 473 } 474 475 STATEMENT_PARSERS = { 476 **parser.Parser.STATEMENT_PARSERS, 477 TokenType.END: lambda self: self._parse_command(), 478 } 479 480 LOG_DEFAULTS_TO_LN = True 481 482 ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False 483 STRING_ALIASES = True 484 NO_PAREN_IF_COMMANDS = False 485 486 def _parse_projections(self) -> t.List[exp.Expression]: 487 """ 488 T-SQL supports the syntax alias = expression in the SELECT's projection list, 489 so we transform all parsed Selects to convert their EQ projections into Aliases. 490 491 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 492 """ 493 return [ 494 ( 495 exp.alias_(projection.expression, projection.this.this, copy=False) 496 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 497 else projection 498 ) 499 for projection in super()._parse_projections() 500 ] 501 502 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 503 """Applies to SQL Server and Azure SQL Database 504 COMMIT [ { TRAN | TRANSACTION } 505 [ transaction_name | @tran_name_variable ] ] 506 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 507 508 ROLLBACK { TRAN | TRANSACTION } 509 [ transaction_name | @tran_name_variable 510 | savepoint_name | @savepoint_variable ] 511 """ 512 rollback = self._prev.token_type == TokenType.ROLLBACK 513 514 self._match_texts(("TRAN", "TRANSACTION")) 515 this = self._parse_id_var() 516 517 if rollback: 518 return self.expression(exp.Rollback, this=this) 519 520 durability = None 521 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 522 self._match_text_seq("DELAYED_DURABILITY") 523 self._match(TokenType.EQ) 524 525 if self._match_text_seq("OFF"): 526 durability = False 527 else: 528 self._match(TokenType.ON) 529 durability = True 530 531 self._match_r_paren() 532 533 return self.expression(exp.Commit, this=this, durability=durability) 534 535 def _parse_transaction(self) -> exp.Transaction | exp.Command: 536 """Applies to SQL Server and Azure SQL Database 537 BEGIN { TRAN | TRANSACTION } 538 [ { transaction_name | @tran_name_variable } 539 [ WITH MARK [ 'description' ] ] 540 ] 541 """ 542 if self._match_texts(("TRAN", "TRANSACTION")): 543 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 544 if self._match_text_seq("WITH", "MARK"): 545 transaction.set("mark", self._parse_string()) 546 547 return transaction 548 549 return self._parse_as_command(self._prev) 550 551 def _parse_returns(self) -> exp.ReturnsProperty: 552 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 553 returns = super()._parse_returns() 554 returns.set("table", table) 555 return returns 556 557 def _parse_convert( 558 self, strict: bool, safe: t.Optional[bool] = None 559 ) -> t.Optional[exp.Expression]: 560 to = self._parse_types() 561 self._match(TokenType.COMMA) 562 this = self._parse_conjunction() 563 564 if not to or not this: 565 return None 566 567 # Retrieve length of datatype and override to default if not specified 568 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 569 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 570 571 # Check whether a conversion with format is applicable 572 if self._match(TokenType.COMMA): 573 format_val = self._parse_number() 574 format_val_name = format_val.name if format_val else "" 575 576 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 577 raise ValueError( 578 f"CONVERT function at T-SQL does not support format style {format_val_name}" 579 ) 580 581 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 582 583 # Check whether the convert entails a string to date format 584 if to.this == DataType.Type.DATE: 585 return self.expression(exp.StrToDate, this=this, format=format_norm) 586 # Check whether the convert entails a string to datetime format 587 elif to.this == DataType.Type.DATETIME: 588 return self.expression(exp.StrToTime, this=this, format=format_norm) 589 # Check whether the convert entails a date to string format 590 elif to.this in self.VAR_LENGTH_DATATYPES: 591 return self.expression( 592 exp.Cast if strict else exp.TryCast, 593 to=to, 594 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 595 safe=safe, 596 ) 597 elif to.this == DataType.Type.TEXT: 598 return self.expression(exp.TimeToStr, this=this, format=format_norm) 599 600 # Entails a simple cast without any format requirement 601 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe) 602 603 def _parse_user_defined_function( 604 self, kind: t.Optional[TokenType] = None 605 ) -> t.Optional[exp.Expression]: 606 this = super()._parse_user_defined_function(kind=kind) 607 608 if ( 609 kind == TokenType.FUNCTION 610 or isinstance(this, exp.UserDefinedFunction) 611 or self._match(TokenType.ALIAS, advance=False) 612 ): 613 return this 614 615 expressions = self._parse_csv(self._parse_function_parameter) 616 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 617 618 def _parse_id_var( 619 self, 620 any_token: bool = True, 621 tokens: t.Optional[t.Collection[TokenType]] = None, 622 ) -> t.Optional[exp.Expression]: 623 is_temporary = self._match(TokenType.HASH) 624 is_global = is_temporary and self._match(TokenType.HASH) 625 626 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 627 if this: 628 if is_global: 629 this.set("global", True) 630 elif is_temporary: 631 this.set("temporary", True) 632 633 return this 634 635 def _parse_create(self) -> exp.Create | exp.Command: 636 create = super()._parse_create() 637 638 if isinstance(create, exp.Create): 639 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 640 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 641 if not create.args.get("properties"): 642 create.set("properties", exp.Properties(expressions=[])) 643 644 create.args["properties"].append("expressions", exp.TemporaryProperty()) 645 646 return create 647 648 def _parse_if(self) -> t.Optional[exp.Expression]: 649 index = self._index 650 651 if self._match_text_seq("OBJECT_ID"): 652 self._parse_wrapped_csv(self._parse_string) 653 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 654 return self._parse_drop(exists=True) 655 self._retreat(index) 656 657 return super()._parse_if() 658 659 def _parse_unique(self) -> exp.UniqueColumnConstraint: 660 if self._match_texts(("CLUSTERED", "NONCLUSTERED")): 661 this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self) 662 else: 663 this = self._parse_schema(self._parse_id_var(any_token=False)) 664 665 return self.expression(exp.UniqueColumnConstraint, this=this)
Parser consumes a list of tokens produced by the Tokenizer and produces a parsed syntax tree.
Arguments:
- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
FUNCTIONS =
{'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANONYMOUS_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnonymousAggFunc'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'ARRAY_UNIQUE_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUniqueAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'COMBINED_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedAggFunc'>>, 'COMBINED_PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedParameterizedAgg'>>, 'CONCAT': <function Parser.<lambda>>, 'CONCAT_WS': <function Parser.<lambda>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'COUNTIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GET_PATH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GetPath'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_INF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'ISINF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'J_S_O_N_OBJECT_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObjectAgg'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <function _parse_len>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <function parse_logarithm>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NULLIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nullif'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RAND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDOM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Randn'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeFromParts'>>, 'TIMEFROMPARTS': <function _parse_timefromparts>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMPFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToArray'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsDiff'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'TS_OR_DS_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToTime'>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixDate'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'DATETIMEFROMPARTS': <function _parse_datetimefromparts>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
VAR_LENGTH_DATATYPES =
{<Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>}
RETURNS_TABLE_TOKENS =
{<TokenType.TOP: 'TOP'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.ANTI: 'ANTI'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.VAR: 'VAR'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.DIV: 'DIV'>, <TokenType.FALSE: 'FALSE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.MODEL: 'MODEL'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.ALL: 'ALL'>, <TokenType.SEMI: 'SEMI'>, <TokenType.FIRST: 'FIRST'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.NEXT: 'NEXT'>, <TokenType.ROW: 'ROW'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.KEEP: 'KEEP'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.VIEW: 'VIEW'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.SOME: 'SOME'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.CASE: 'CASE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.END: 'END'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.ASC: 'ASC'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.APPLY: 'APPLY'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.ROWS: 'ROWS'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.LOAD: 'LOAD'>, <TokenType.USE: 'USE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CACHE: 'CACHE'>, <TokenType.KILL: 'KILL'>, <TokenType.SET: 'SET'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.DELETE: 'DELETE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.DESC: 'DESC'>, <TokenType.FULL: 'FULL'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.LEFT: 'LEFT'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.FINAL: 'FINAL'>, <TokenType.IS: 'IS'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ANY: 'ANY'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.FILTER: 'FILTER'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>}
STATEMENT_PARSERS =
{<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.REFRESH: 'REFRESH'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
TABLE_ALIAS_TOKENS =
{<TokenType.TOP: 'TOP'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.BINARY: 'BINARY'>, <TokenType.ANTI: 'ANTI'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.VAR: 'VAR'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.DIV: 'DIV'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.FALSE: 'FALSE'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.MODEL: 'MODEL'>, <TokenType.BIT: 'BIT'>, <TokenType.UUID: 'UUID'>, <TokenType.DATE32: 'DATE32'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.IPV4: 'IPV4'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.UINT: 'UINT'>, <TokenType.ALL: 'ALL'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.NULL: 'NULL'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.SEMI: 'SEMI'>, <TokenType.FIRST: 'FIRST'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.NEXT: 'NEXT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.ROW: 'ROW'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.KEEP: 'KEEP'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.ENUM: 'ENUM'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.TABLE: 'TABLE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.SUPER: 'SUPER'>, <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.VIEW: 'VIEW'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.XML: 'XML'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.JSON: 'JSON'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.SOME: 'SOME'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.CASE: 'CASE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.TRUE: 'TRUE'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.INT128: 'INT128'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.INT: 'INT'>, <TokenType.TEXT: 'TEXT'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.END: 'END'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.IPV6: 'IPV6'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.ASC: 'ASC'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.LOAD: 'LOAD'>, <TokenType.USE: 'USE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.INDEX: 'INDEX'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CACHE: 'CACHE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.KILL: 'KILL'>, <TokenType.SET: 'SET'>, <TokenType.JSONB: 'JSONB'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.NESTED: 'NESTED'>, <TokenType.TIME: 'TIME'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.DELETE: 'DELETE'>, <TokenType.INET: 'INET'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.DESC: 'DESC'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.DATE: 'DATE'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.MAP: 'MAP'>, <TokenType.FINAL: 'FINAL'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.UINT256: 'UINT256'>, <TokenType.IS: 'IS'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.INT256: 'INT256'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.MONEY: 'MONEY'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ANY: 'ANY'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.YEAR: 'YEAR'>, <TokenType.CHAR: 'CHAR'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.FILTER: 'FILTER'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>}
SET_TRIE: Dict =
{'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
Inherited Members
- sqlglot.parser.Parser
- Parser
- NO_PAREN_FUNCTIONS
- STRUCT_TYPE_TOKENS
- NESTED_TYPE_TOKENS
- ENUM_TYPE_TOKENS
- AGGREGATE_TYPE_TOKENS
- TYPE_TOKENS
- SIGNED_TO_UNSIGNED_TYPE_TOKEN
- SUBQUERY_PREDICATES
- RESERVED_TOKENS
- DB_CREATABLES
- CREATABLES
- ID_VAR_TOKENS
- INTERVAL_VARS
- COMMENT_TABLE_ALIAS_TOKENS
- UPDATE_ALIAS_TOKENS
- TRIM_TYPES
- FUNC_TOKENS
- CONJUNCTION
- EQUALITY
- COMPARISON
- BITWISE
- TERM
- FACTOR
- EXPONENT
- TIMES
- TIMESTAMPS
- SET_OPERATIONS
- JOIN_METHODS
- JOIN_SIDES
- JOIN_KINDS
- LAMBDAS
- COLUMN_OPERATORS
- EXPRESSION_PARSERS
- UNARY_PARSERS
- PRIMARY_PARSERS
- PLACEHOLDER_PARSERS
- RANGE_PARSERS
- PROPERTY_PARSERS
- CONSTRAINT_PARSERS
- ALTER_PARSERS
- SCHEMA_UNNAMED_CONSTRAINTS
- NO_PAREN_FUNCTION_PARSERS
- INVALID_FUNC_NAME_TOKENS
- FUNCTIONS_WITH_ALIASED_ARGS
- FUNCTION_PARSERS
- QUERY_MODIFIER_PARSERS
- SET_PARSERS
- SHOW_PARSERS
- TYPE_LITERAL_PARSERS
- MODIFIABLES
- DDL_SELECT_TOKENS
- PRE_VOLATILE_TOKENS
- TRANSACTION_KIND
- TRANSACTION_CHARACTERISTICS
- INSERT_ALTERNATIVES
- CLONE_KEYWORDS
- HISTORICAL_DATA_KIND
- OPCLASS_FOLLOW_KEYWORDS
- OPTYPE_FOLLOW_TOKENS
- TABLE_INDEX_HINT_TOKENS
- WINDOW_ALIAS_TOKENS
- WINDOW_BEFORE_PAREN_TOKENS
- WINDOW_SIDES
- JSON_KEY_VALUE_SEPARATOR_TOKENS
- FETCH_TOKENS
- ADD_CONSTRAINT_TOKENS
- DISTINCT_TOKENS
- NULL_TOKENS
- UNNEST_OFFSET_ALIAS_TOKENS
- STRICT_CAST
- PREFIXED_PIVOT_COLUMNS
- IDENTIFY_PIVOT_STRINGS
- TABLESAMPLE_CSV
- TRIM_PATTERN_FIRST
- MODIFIERS_ATTACHED_TO_UNION
- UNION_MODIFIERS
- error_level
- error_message_context
- max_errors
- dialect
- reset
- parse
- parse_into
- check_errors
- raise_error
- expression
- validate_expression
- errors
- sql
667 class Generator(generator.Generator): 668 LIMIT_IS_TOP = True 669 QUERY_HINTS = False 670 RETURNING_END = False 671 NVL2_SUPPORTED = False 672 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False 673 LIMIT_FETCH = "FETCH" 674 COMPUTED_COLUMN_WITH_TYPE = False 675 CTE_RECURSIVE_KEYWORD_REQUIRED = False 676 ENSURE_BOOLS = True 677 NULL_ORDERING_SUPPORTED = None 678 SUPPORTS_SINGLE_ARG_CONCAT = False 679 TABLESAMPLE_SEED_KEYWORD = "REPEATABLE" 680 SUPPORTS_SELECT_INTO = True 681 682 EXPRESSIONS_WITHOUT_NESTED_CTES = { 683 exp.Delete, 684 exp.Insert, 685 exp.Merge, 686 exp.Select, 687 exp.Subquery, 688 exp.Union, 689 exp.Update, 690 } 691 692 TYPE_MAPPING = { 693 **generator.Generator.TYPE_MAPPING, 694 exp.DataType.Type.BOOLEAN: "BIT", 695 exp.DataType.Type.DECIMAL: "NUMERIC", 696 exp.DataType.Type.DATETIME: "DATETIME2", 697 exp.DataType.Type.DOUBLE: "FLOAT", 698 exp.DataType.Type.INT: "INTEGER", 699 exp.DataType.Type.TEXT: "VARCHAR(MAX)", 700 exp.DataType.Type.TIMESTAMP: "DATETIME2", 701 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 702 exp.DataType.Type.VARIANT: "SQL_VARIANT", 703 } 704 705 TRANSFORMS = { 706 **generator.Generator.TRANSFORMS, 707 exp.AnyValue: any_value_to_max_sql, 708 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 709 exp.DateAdd: date_delta_sql("DATEADD"), 710 exp.DateDiff: date_delta_sql("DATEDIFF"), 711 exp.CTE: transforms.preprocess([qualify_derived_table_outputs]), 712 exp.CurrentDate: rename_func("GETDATE"), 713 exp.CurrentTimestamp: rename_func("GETDATE"), 714 exp.Extract: rename_func("DATEPART"), 715 exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql, 716 exp.GetPath: path_to_jsonpath("JSON_VALUE"), 717 exp.GroupConcat: _string_agg_sql, 718 exp.If: rename_func("IIF"), 719 exp.LastDay: lambda self, e: self.func("EOMONTH", e.this), 720 exp.Max: max_or_greatest, 721 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 722 exp.Min: min_or_least, 723 exp.NumberToStr: _format_sql, 724 exp.ParseJSON: lambda self, e: self.sql(e, "this"), 725 exp.Select: transforms.preprocess( 726 [ 727 transforms.eliminate_distinct_on, 728 transforms.eliminate_semi_and_anti_joins, 729 transforms.eliminate_qualify, 730 ] 731 ), 732 exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]), 733 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 734 exp.SHA2: lambda self, e: self.func( 735 "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this 736 ), 737 exp.TemporaryProperty: lambda self, e: "", 738 exp.TimeStrToTime: timestrtotime_sql, 739 exp.TimeToStr: _format_sql, 740 exp.Trim: trim_sql, 741 exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), 742 exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), 743 } 744 745 TRANSFORMS.pop(exp.ReturnsProperty) 746 747 PROPERTIES_LOCATION = { 748 **generator.Generator.PROPERTIES_LOCATION, 749 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 750 } 751 752 def lateral_op(self, expression: exp.Lateral) -> str: 753 cross_apply = expression.args.get("cross_apply") 754 if cross_apply is True: 755 return "CROSS APPLY" 756 if cross_apply is False: 757 return "OUTER APPLY" 758 759 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 760 self.unsupported("LATERAL clause is not supported.") 761 return "LATERAL" 762 763 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 764 nano = expression.args.get("nano") 765 if nano is not None: 766 nano.pop() 767 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 768 769 if expression.args.get("fractions") is None: 770 expression.set("fractions", exp.Literal.number(0)) 771 if expression.args.get("precision") is None: 772 expression.set("precision", exp.Literal.number(0)) 773 774 return rename_func("TIMEFROMPARTS")(self, expression) 775 776 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 777 zone = expression.args.get("zone") 778 if zone is not None: 779 zone.pop() 780 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 781 782 nano = expression.args.get("nano") 783 if nano is not None: 784 nano.pop() 785 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 786 787 if expression.args.get("milli") is None: 788 expression.set("milli", exp.Literal.number(0)) 789 790 return rename_func("DATETIMEFROMPARTS")(self, expression) 791 792 def set_operation(self, expression: exp.Union, op: str) -> str: 793 limit = expression.args.get("limit") 794 if limit: 795 return self.sql(expression.limit(limit.pop(), copy=False)) 796 797 return super().set_operation(expression, op) 798 799 def setitem_sql(self, expression: exp.SetItem) -> str: 800 this = expression.this 801 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 802 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 803 return f"{self.sql(this.left)} {self.sql(this.right)}" 804 805 return super().setitem_sql(expression) 806 807 def boolean_sql(self, expression: exp.Boolean) -> str: 808 if type(expression.parent) in BIT_TYPES: 809 return "1" if expression.this else "0" 810 811 return "(1 = 1)" if expression.this else "(1 = 0)" 812 813 def is_sql(self, expression: exp.Is) -> str: 814 if isinstance(expression.expression, exp.Boolean): 815 return self.binary(expression, "=") 816 return self.binary(expression, "IS") 817 818 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 819 sql = self.sql(expression, "this") 820 properties = expression.args.get("properties") 821 822 if sql[:1] != "#" and any( 823 isinstance(prop, exp.TemporaryProperty) 824 for prop in (properties.expressions if properties else []) 825 ): 826 sql = f"#{sql}" 827 828 return sql 829 830 def create_sql(self, expression: exp.Create) -> str: 831 kind = self.sql(expression, "kind").upper() 832 exists = expression.args.pop("exists", None) 833 sql = super().create_sql(expression) 834 835 table = expression.find(exp.Table) 836 837 # Convert CTAS statement to SELECT .. INTO .. 838 if kind == "TABLE" and expression.expression: 839 ctas_with = expression.expression.args.get("with") 840 if ctas_with: 841 ctas_with = ctas_with.pop() 842 843 subquery = expression.expression 844 if isinstance(subquery, exp.Subqueryable): 845 subquery = subquery.subquery() 846 847 select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True)) 848 select_into.set("into", exp.Into(this=table)) 849 select_into.set("with", ctas_with) 850 851 sql = self.sql(select_into) 852 853 if exists: 854 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 855 sql = self.sql(exp.Literal.string(sql)) 856 if kind == "SCHEMA": 857 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})""" 858 elif kind == "TABLE": 859 assert table 860 where = exp.and_( 861 exp.column("table_name").eq(table.name), 862 exp.column("table_schema").eq(table.db) if table.db else None, 863 exp.column("table_catalog").eq(table.catalog) if table.catalog else None, 864 ) 865 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})""" 866 elif kind == "INDEX": 867 index = self.sql(exp.Literal.string(expression.this.text("this"))) 868 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})""" 869 elif expression.args.get("replace"): 870 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 871 872 return self.prepend_ctes(expression, sql) 873 874 def offset_sql(self, expression: exp.Offset) -> str: 875 return f"{super().offset_sql(expression)} ROWS" 876 877 def version_sql(self, expression: exp.Version) -> str: 878 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 879 this = f"FOR {name}" 880 expr = expression.expression 881 kind = expression.text("kind") 882 if kind in ("FROM", "BETWEEN"): 883 args = expr.expressions 884 sep = "TO" if kind == "FROM" else "AND" 885 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 886 else: 887 expr_sql = self.sql(expr) 888 889 expr_sql = f" {expr_sql}" if expr_sql else "" 890 return f"{this} {kind}{expr_sql}" 891 892 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 893 table = expression.args.get("table") 894 table = f"{table} " if table else "" 895 return f"RETURNS {table}{self.sql(expression, 'this')}" 896 897 def returning_sql(self, expression: exp.Returning) -> str: 898 into = self.sql(expression, "into") 899 into = self.seg(f"INTO {into}") if into else "" 900 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 901 902 def transaction_sql(self, expression: exp.Transaction) -> str: 903 this = self.sql(expression, "this") 904 this = f" {this}" if this else "" 905 mark = self.sql(expression, "mark") 906 mark = f" WITH MARK {mark}" if mark else "" 907 return f"BEGIN TRANSACTION{this}{mark}" 908 909 def commit_sql(self, expression: exp.Commit) -> str: 910 this = self.sql(expression, "this") 911 this = f" {this}" if this else "" 912 durability = expression.args.get("durability") 913 durability = ( 914 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 915 if durability is not None 916 else "" 917 ) 918 return f"COMMIT TRANSACTION{this}{durability}" 919 920 def rollback_sql(self, expression: exp.Rollback) -> str: 921 this = self.sql(expression, "this") 922 this = f" {this}" if this else "" 923 return f"ROLLBACK TRANSACTION{this}" 924 925 def identifier_sql(self, expression: exp.Identifier) -> str: 926 identifier = super().identifier_sql(expression) 927 928 if expression.args.get("global"): 929 identifier = f"##{identifier}" 930 elif expression.args.get("temporary"): 931 identifier = f"#{identifier}" 932 933 return identifier 934 935 def constraint_sql(self, expression: exp.Constraint) -> str: 936 this = self.sql(expression, "this") 937 expressions = self.expressions(expression, flat=True, sep=" ") 938 return f"CONSTRAINT {this} {expressions}" 939 940 def length_sql(self, expression: exp.Length) -> str: 941 this = expression.this 942 if isinstance(this, exp.Cast) and this.is_type(exp.DataType.Type.TEXT): 943 this_sql = self.sql(this, "this") 944 else: 945 this_sql = self.sql(this) 946 return self.func("LEN", this_sql)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether or not 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 or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all 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: Determines whether or not 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 or not to preserve comments in the output SQL code. Default: True
EXPRESSIONS_WITHOUT_NESTED_CTES =
{<class 'sqlglot.expressions.Merge'>, <class 'sqlglot.expressions.Union'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Subquery'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Delete'>}
TYPE_MAPPING =
{<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.BOOLEAN: 'BOOLEAN'>: 'BIT', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.DOUBLE: 'DOUBLE'>: 'FLOAT', <Type.INT: 'INT'>: 'INTEGER', <Type.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS =
{<class 'sqlglot.expressions.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.AutoIncrementColumnConstraint'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Extract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.GetPath'>: <function path_to_jsonpath.<locals>._transform>, <class 'sqlglot.expressions.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.LastDay'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.MD5'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Min'>: <function min_or_least>, <class 'sqlglot.expressions.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.ParseJSON'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.SHA'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.SHA2'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
752 def lateral_op(self, expression: exp.Lateral) -> str: 753 cross_apply = expression.args.get("cross_apply") 754 if cross_apply is True: 755 return "CROSS APPLY" 756 if cross_apply is False: 757 return "OUTER APPLY" 758 759 # TODO: perhaps we can check if the parent is a Join and transpile it appropriately 760 self.unsupported("LATERAL clause is not supported.") 761 return "LATERAL"
763 def timefromparts_sql(self, expression: exp.TimeFromParts) -> str: 764 nano = expression.args.get("nano") 765 if nano is not None: 766 nano.pop() 767 self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.") 768 769 if expression.args.get("fractions") is None: 770 expression.set("fractions", exp.Literal.number(0)) 771 if expression.args.get("precision") is None: 772 expression.set("precision", exp.Literal.number(0)) 773 774 return rename_func("TIMEFROMPARTS")(self, expression)
776 def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str: 777 zone = expression.args.get("zone") 778 if zone is not None: 779 zone.pop() 780 self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.") 781 782 nano = expression.args.get("nano") 783 if nano is not None: 784 nano.pop() 785 self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.") 786 787 if expression.args.get("milli") is None: 788 expression.set("milli", exp.Literal.number(0)) 789 790 return rename_func("DATETIMEFROMPARTS")(self, expression)
799 def setitem_sql(self, expression: exp.SetItem) -> str: 800 this = expression.this 801 if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter): 802 # T-SQL does not use '=' in SET command, except when the LHS is a variable. 803 return f"{self.sql(this.left)} {self.sql(this.right)}" 804 805 return super().setitem_sql(expression)
818 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 819 sql = self.sql(expression, "this") 820 properties = expression.args.get("properties") 821 822 if sql[:1] != "#" and any( 823 isinstance(prop, exp.TemporaryProperty) 824 for prop in (properties.expressions if properties else []) 825 ): 826 sql = f"#{sql}" 827 828 return sql
830 def create_sql(self, expression: exp.Create) -> str: 831 kind = self.sql(expression, "kind").upper() 832 exists = expression.args.pop("exists", None) 833 sql = super().create_sql(expression) 834 835 table = expression.find(exp.Table) 836 837 # Convert CTAS statement to SELECT .. INTO .. 838 if kind == "TABLE" and expression.expression: 839 ctas_with = expression.expression.args.get("with") 840 if ctas_with: 841 ctas_with = ctas_with.pop() 842 843 subquery = expression.expression 844 if isinstance(subquery, exp.Subqueryable): 845 subquery = subquery.subquery() 846 847 select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True)) 848 select_into.set("into", exp.Into(this=table)) 849 select_into.set("with", ctas_with) 850 851 sql = self.sql(select_into) 852 853 if exists: 854 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 855 sql = self.sql(exp.Literal.string(sql)) 856 if kind == "SCHEMA": 857 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})""" 858 elif kind == "TABLE": 859 assert table 860 where = exp.and_( 861 exp.column("table_name").eq(table.name), 862 exp.column("table_schema").eq(table.db) if table.db else None, 863 exp.column("table_catalog").eq(table.catalog) if table.catalog else None, 864 ) 865 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})""" 866 elif kind == "INDEX": 867 index = self.sql(exp.Literal.string(expression.this.text("this"))) 868 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})""" 869 elif expression.args.get("replace"): 870 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 871 872 return self.prepend_ctes(expression, sql)
877 def version_sql(self, expression: exp.Version) -> str: 878 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 879 this = f"FOR {name}" 880 expr = expression.expression 881 kind = expression.text("kind") 882 if kind in ("FROM", "BETWEEN"): 883 args = expr.expressions 884 sep = "TO" if kind == "FROM" else "AND" 885 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 886 else: 887 expr_sql = self.sql(expr) 888 889 expr_sql = f" {expr_sql}" if expr_sql else "" 890 return f"{this} {kind}{expr_sql}"
909 def commit_sql(self, expression: exp.Commit) -> str: 910 this = self.sql(expression, "this") 911 this = f" {this}" if this else "" 912 durability = expression.args.get("durability") 913 durability = ( 914 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 915 if durability is not None 916 else "" 917 ) 918 return f"COMMIT TRANSACTION{this}{durability}"
Inherited Members
- sqlglot.generator.Generator
- Generator
- LOCKING_READS_SUPPORTED
- EXPLICIT_UNION
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- LIMIT_ONLY_LITERALS
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- INDEX_ON
- JOIN_HINTS
- TABLE_HINTS
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- DUPLICATE_KEY_UPDATE_WITH_SET
- COLUMN_JOIN_MARKS_SUPPORTED
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- VALUES_AS_TABLE
- UNNEST_WITH_ORDINALITY
- AGGREGATE_FILTER_SUPPORTED
- SEMI_ANTI_JOIN_WITH_SIDE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_KEYWORDS
- TABLESAMPLE_WITH_METHOD
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- LAST_DAY_SUPPORTS_DATE_PART
- SUPPORTS_TABLE_ALIAS_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- JSON_KEY_VALUE_PAIR_SEP
- INSERT_OVERWRITE
- SUPPORTS_UNLOGGED_TABLES
- STAR_MAPPING
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- STRUCT_DELIMITER
- PARAMETER_TOKEN
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- KEY_VALUE_DEFINITIONS
- 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
- pad_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_sql
- columnposition_sql
- columndef_sql
- columnconstraint_sql
- computedcolumnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- transformcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_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_sql
- directory_sql
- delete_sql
- drop_sql
- except_sql
- except_op
- fetch_sql
- filter_sql
- hint_sql
- index_sql
- inputoutputformat_sql
- national_sql
- partition_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_name
- property_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- intersect_sql
- intersect_op
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_sql
- tablesample_sql
- pivot_sql
- tuple_sql
- update_sql
- values_sql
- var_sql
- into_sql
- from_sql
- group_sql
- having_sql
- connect_sql
- prior_sql
- join_sql
- lambda_sql
- lateral_sql
- limit_sql
- set_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- order_sql
- withfill_sql
- cluster_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognize_sql
- query_modifiers
- offset_limit_modifiers
- after_having_modifiers
- after_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- union_sql
- union_op
- unnest_sql
- where_sql
- window_sql
- partition_by_sql
- windowspec_sql
- withingroup_sql
- between_sql
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- nextvaluefor_sql
- extract_sql
- trim_sql
- convert_concat_args
- concat_sql
- concatws_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- formatjson_sql
- jsonobject_sql
- jsonobjectagg_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
- add_sql
- and_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- cast_sql
- currentdate_sql
- collate_sql
- command_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- altercolumn_sql
- renametable_sql
- renamecolumn_sql
- altertable_sql
- add_column_sql
- droppartition_sql
- addconstraint_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- intdiv_sql
- dpipe_sql
- div_sql
- overlaps_sql
- distance_sql
- dot_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- ilike_sql
- ilikeany_sql
- like_sql
- likeany_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- or_sql
- slice_sql
- sub_sql
- trycast_sql
- log_sql
- use_sql
- binary
- function_fallback_sql
- func
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- tag_sql
- token_sql
- userdefinedfunction_sql
- joinhint_sql
- kwarg_sql
- when_sql
- merge_sql
- tochar_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- indexcolumnconstraint_sql
- nvl2_sql
- comprehension_sql
- columnprefix_sql
- opclass_sql
- predict_sql
- forin_sql
- refresh_sql
- operator_sql
- toarray_sql
- tsordstotime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql