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 any_value_to_max_sql, 11 max_or_greatest, 12 min_or_least, 13 parse_date_delta, 14 rename_func, 15 timestrtotime_sql, 16) 17from sqlglot.expressions import DataType 18from sqlglot.helper import seq_get 19from sqlglot.time import format_time 20from sqlglot.tokens import TokenType 21 22if t.TYPE_CHECKING: 23 from sqlglot._typing import E 24 25FULL_FORMAT_TIME_MAPPING = { 26 "weekday": "%A", 27 "dw": "%A", 28 "w": "%A", 29 "month": "%B", 30 "mm": "%B", 31 "m": "%B", 32} 33 34DATE_DELTA_INTERVAL = { 35 "year": "year", 36 "yyyy": "year", 37 "yy": "year", 38 "quarter": "quarter", 39 "qq": "quarter", 40 "q": "quarter", 41 "month": "month", 42 "mm": "month", 43 "m": "month", 44 "week": "week", 45 "ww": "week", 46 "wk": "week", 47 "day": "day", 48 "dd": "day", 49 "d": "day", 50} 51 52 53DATE_FMT_RE = re.compile("([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})") 54 55# N = Numeric, C=Currency 56TRANSPILE_SAFE_NUMBER_FMT = {"N", "C"} 57 58DEFAULT_START_DATE = datetime.date(1900, 1, 1) 59 60BIT_TYPES = {exp.EQ, exp.NEQ, exp.Is, exp.In, exp.Select, exp.Alias} 61 62 63def _format_time_lambda( 64 exp_class: t.Type[E], full_format_mapping: t.Optional[bool] = None 65) -> t.Callable[[t.List], E]: 66 def _format_time(args: t.List) -> E: 67 assert len(args) == 2 68 69 return exp_class( 70 this=exp.cast(args[1], "datetime"), 71 format=exp.Literal.string( 72 format_time( 73 args[0].name.lower(), 74 {**TSQL.TIME_MAPPING, **FULL_FORMAT_TIME_MAPPING} 75 if full_format_mapping 76 else TSQL.TIME_MAPPING, 77 ) 78 ), 79 ) 80 81 return _format_time 82 83 84def _parse_format(args: t.List) -> exp.Expression: 85 this = seq_get(args, 0) 86 fmt = seq_get(args, 1) 87 culture = seq_get(args, 2) 88 89 number_fmt = fmt and (fmt.name in TRANSPILE_SAFE_NUMBER_FMT or not DATE_FMT_RE.search(fmt.name)) 90 91 if number_fmt: 92 return exp.NumberToStr(this=this, format=fmt, culture=culture) 93 94 if fmt: 95 fmt = exp.Literal.string( 96 format_time(fmt.name, TSQL.FORMAT_TIME_MAPPING) 97 if len(fmt.name) == 1 98 else format_time(fmt.name, TSQL.TIME_MAPPING) 99 ) 100 101 return exp.TimeToStr(this=this, format=fmt, culture=culture) 102 103 104def _parse_eomonth(args: t.List) -> exp.Expression: 105 date = seq_get(args, 0) 106 month_lag = seq_get(args, 1) 107 unit = DATE_DELTA_INTERVAL.get("month") 108 109 if month_lag is None: 110 return exp.LastDateOfMonth(this=date) 111 112 # Remove month lag argument in parser as its compared with the number of arguments of the resulting class 113 args.remove(month_lag) 114 115 return exp.LastDateOfMonth(this=exp.DateAdd(this=date, expression=month_lag, unit=unit)) 116 117 118def _parse_hashbytes(args: t.List) -> exp.Expression: 119 kind, data = args 120 kind = kind.name.upper() if kind.is_string else "" 121 122 if kind == "MD5": 123 args.pop(0) 124 return exp.MD5(this=data) 125 if kind in ("SHA", "SHA1"): 126 args.pop(0) 127 return exp.SHA(this=data) 128 if kind == "SHA2_256": 129 return exp.SHA2(this=data, length=exp.Literal.number(256)) 130 if kind == "SHA2_512": 131 return exp.SHA2(this=data, length=exp.Literal.number(512)) 132 133 return exp.func("HASHBYTES", *args) 134 135 136def generate_date_delta_with_unit_sql( 137 self: TSQL.Generator, expression: exp.DateAdd | exp.DateDiff 138) -> str: 139 func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF" 140 return self.func(func, expression.text("unit"), expression.expression, expression.this) 141 142 143def _format_sql(self: TSQL.Generator, expression: exp.NumberToStr | exp.TimeToStr) -> str: 144 fmt = ( 145 expression.args["format"] 146 if isinstance(expression, exp.NumberToStr) 147 else exp.Literal.string( 148 format_time( 149 expression.text("format"), 150 t.cast(t.Dict[str, str], TSQL.INVERSE_TIME_MAPPING), 151 ) 152 ) 153 ) 154 return self.func("FORMAT", expression.this, fmt, expression.args.get("culture")) 155 156 157def _string_agg_sql(self: TSQL.Generator, expression: exp.GroupConcat) -> str: 158 expression = expression.copy() 159 160 this = expression.this 161 distinct = expression.find(exp.Distinct) 162 if distinct: 163 # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression 164 self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.") 165 this = distinct.pop().expressions[0] 166 167 order = "" 168 if isinstance(expression.this, exp.Order): 169 if expression.this.this: 170 this = expression.this.this.pop() 171 order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})" # Order has a leading space 172 173 separator = expression.args.get("separator") or exp.Literal.string(",") 174 return f"STRING_AGG({self.format_args(this, separator)}){order}" 175 176 177def _parse_date_delta( 178 exp_class: t.Type[E], unit_mapping: t.Optional[t.Dict[str, str]] = None 179) -> t.Callable[[t.List], E]: 180 def inner_func(args: t.List) -> E: 181 unit = seq_get(args, 0) 182 if unit and unit_mapping: 183 unit = exp.var(unit_mapping.get(unit.name.lower(), unit.name)) 184 185 start_date = seq_get(args, 1) 186 if start_date and start_date.is_number: 187 # Numeric types are valid DATETIME values 188 if start_date.is_int: 189 adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this)) 190 start_date = exp.Literal.string(adds.strftime("%F")) 191 else: 192 # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs. 193 # This is not a problem when generating T-SQL code, it is when transpiling to other dialects. 194 return exp_class(this=seq_get(args, 2), expression=start_date, unit=unit) 195 196 return exp_class( 197 this=exp.TimeStrToTime(this=seq_get(args, 2)), 198 expression=exp.TimeStrToTime(this=start_date), 199 unit=unit, 200 ) 201 202 return inner_func 203 204 205class TSQL(Dialect): 206 RESOLVES_IDENTIFIERS_AS_UPPERCASE = None 207 NULL_ORDERING = "nulls_are_small" 208 TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'" 209 210 TIME_MAPPING = { 211 "year": "%Y", 212 "qq": "%q", 213 "q": "%q", 214 "quarter": "%q", 215 "dayofyear": "%j", 216 "day": "%d", 217 "dy": "%d", 218 "y": "%Y", 219 "week": "%W", 220 "ww": "%W", 221 "wk": "%W", 222 "hour": "%h", 223 "hh": "%I", 224 "minute": "%M", 225 "mi": "%M", 226 "n": "%M", 227 "second": "%S", 228 "ss": "%S", 229 "s": "%-S", 230 "millisecond": "%f", 231 "ms": "%f", 232 "weekday": "%W", 233 "dw": "%W", 234 "month": "%m", 235 "mm": "%M", 236 "m": "%-M", 237 "Y": "%Y", 238 "YYYY": "%Y", 239 "YY": "%y", 240 "MMMM": "%B", 241 "MMM": "%b", 242 "MM": "%m", 243 "M": "%-m", 244 "dd": "%d", 245 "d": "%-d", 246 "HH": "%H", 247 "H": "%-H", 248 "h": "%-I", 249 "S": "%f", 250 "yyyy": "%Y", 251 "yy": "%y", 252 } 253 254 CONVERT_FORMAT_MAPPING = { 255 "0": "%b %d %Y %-I:%M%p", 256 "1": "%m/%d/%y", 257 "2": "%y.%m.%d", 258 "3": "%d/%m/%y", 259 "4": "%d.%m.%y", 260 "5": "%d-%m-%y", 261 "6": "%d %b %y", 262 "7": "%b %d, %y", 263 "8": "%H:%M:%S", 264 "9": "%b %d %Y %-I:%M:%S:%f%p", 265 "10": "mm-dd-yy", 266 "11": "yy/mm/dd", 267 "12": "yymmdd", 268 "13": "%d %b %Y %H:%M:ss:%f", 269 "14": "%H:%M:%S:%f", 270 "20": "%Y-%m-%d %H:%M:%S", 271 "21": "%Y-%m-%d %H:%M:%S.%f", 272 "22": "%m/%d/%y %-I:%M:%S %p", 273 "23": "%Y-%m-%d", 274 "24": "%H:%M:%S", 275 "25": "%Y-%m-%d %H:%M:%S.%f", 276 "100": "%b %d %Y %-I:%M%p", 277 "101": "%m/%d/%Y", 278 "102": "%Y.%m.%d", 279 "103": "%d/%m/%Y", 280 "104": "%d.%m.%Y", 281 "105": "%d-%m-%Y", 282 "106": "%d %b %Y", 283 "107": "%b %d, %Y", 284 "108": "%H:%M:%S", 285 "109": "%b %d %Y %-I:%M:%S:%f%p", 286 "110": "%m-%d-%Y", 287 "111": "%Y/%m/%d", 288 "112": "%Y%m%d", 289 "113": "%d %b %Y %H:%M:%S:%f", 290 "114": "%H:%M:%S:%f", 291 "120": "%Y-%m-%d %H:%M:%S", 292 "121": "%Y-%m-%d %H:%M:%S.%f", 293 } 294 295 FORMAT_TIME_MAPPING = { 296 "y": "%B %Y", 297 "d": "%m/%d/%Y", 298 "H": "%-H", 299 "h": "%-I", 300 "s": "%Y-%m-%d %H:%M:%S", 301 "D": "%A,%B,%Y", 302 "f": "%A,%B,%Y %-I:%M %p", 303 "F": "%A,%B,%Y %-I:%M:%S %p", 304 "g": "%m/%d/%Y %-I:%M %p", 305 "G": "%m/%d/%Y %-I:%M:%S %p", 306 "M": "%B %-d", 307 "m": "%B %-d", 308 "O": "%Y-%m-%dT%H:%M:%S", 309 "u": "%Y-%M-%D %H:%M:%S%z", 310 "U": "%A, %B %D, %Y %H:%M:%S%z", 311 "T": "%-I:%M:%S %p", 312 "t": "%-I:%M", 313 "Y": "%a %Y", 314 } 315 316 class Tokenizer(tokens.Tokenizer): 317 IDENTIFIERS = ['"', ("[", "]")] 318 QUOTES = ["'", '"'] 319 HEX_STRINGS = [("0x", ""), ("0X", "")] 320 321 KEYWORDS = { 322 **tokens.Tokenizer.KEYWORDS, 323 "DATETIME2": TokenType.DATETIME, 324 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 325 "DECLARE": TokenType.COMMAND, 326 "IMAGE": TokenType.IMAGE, 327 "MONEY": TokenType.MONEY, 328 "NTEXT": TokenType.TEXT, 329 "NVARCHAR(MAX)": TokenType.TEXT, 330 "PRINT": TokenType.COMMAND, 331 "PROC": TokenType.PROCEDURE, 332 "REAL": TokenType.FLOAT, 333 "ROWVERSION": TokenType.ROWVERSION, 334 "SMALLDATETIME": TokenType.DATETIME, 335 "SMALLMONEY": TokenType.SMALLMONEY, 336 "SQL_VARIANT": TokenType.VARIANT, 337 "TOP": TokenType.TOP, 338 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 339 "UPDATE STATISTICS": TokenType.COMMAND, 340 "VARCHAR(MAX)": TokenType.TEXT, 341 "XML": TokenType.XML, 342 "OUTPUT": TokenType.RETURNING, 343 "SYSTEM_USER": TokenType.CURRENT_USER, 344 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 345 } 346 347 class Parser(parser.Parser): 348 FUNCTIONS = { 349 **parser.Parser.FUNCTIONS, 350 "CHARINDEX": lambda args: exp.StrPosition( 351 this=seq_get(args, 1), 352 substr=seq_get(args, 0), 353 position=seq_get(args, 2), 354 ), 355 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 356 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 357 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 358 "DATEPART": _format_time_lambda(exp.TimeToStr), 359 "EOMONTH": _parse_eomonth, 360 "FORMAT": _parse_format, 361 "GETDATE": exp.CurrentTimestamp.from_arg_list, 362 "HASHBYTES": _parse_hashbytes, 363 "IIF": exp.If.from_arg_list, 364 "ISNULL": exp.Coalesce.from_arg_list, 365 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 366 "LEN": exp.Length.from_arg_list, 367 "REPLICATE": exp.Repeat.from_arg_list, 368 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 369 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 370 "SUSER_NAME": exp.CurrentUser.from_arg_list, 371 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 372 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 373 } 374 375 JOIN_HINTS = { 376 "LOOP", 377 "HASH", 378 "MERGE", 379 "REMOTE", 380 } 381 382 VAR_LENGTH_DATATYPES = { 383 DataType.Type.NVARCHAR, 384 DataType.Type.VARCHAR, 385 DataType.Type.CHAR, 386 DataType.Type.NCHAR, 387 } 388 389 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 390 TokenType.TABLE, 391 *parser.Parser.TYPE_TOKENS, 392 } 393 394 STATEMENT_PARSERS = { 395 **parser.Parser.STATEMENT_PARSERS, 396 TokenType.END: lambda self: self._parse_command(), 397 } 398 399 LOG_BASE_FIRST = False 400 LOG_DEFAULTS_TO_LN = True 401 402 CONCAT_NULL_OUTPUTS_STRING = True 403 404 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 405 406 def _parse_projections(self) -> t.List[exp.Expression]: 407 """ 408 T-SQL supports the syntax alias = expression in the SELECT's projection list, 409 so we transform all parsed Selects to convert their EQ projections into Aliases. 410 411 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 412 """ 413 return [ 414 exp.alias_(projection.expression, projection.this.this, copy=False) 415 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 416 else projection 417 for projection in super()._parse_projections() 418 ] 419 420 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 421 """Applies to SQL Server and Azure SQL Database 422 COMMIT [ { TRAN | TRANSACTION } 423 [ transaction_name | @tran_name_variable ] ] 424 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 425 426 ROLLBACK { TRAN | TRANSACTION } 427 [ transaction_name | @tran_name_variable 428 | savepoint_name | @savepoint_variable ] 429 """ 430 rollback = self._prev.token_type == TokenType.ROLLBACK 431 432 self._match_texts({"TRAN", "TRANSACTION"}) 433 this = self._parse_id_var() 434 435 if rollback: 436 return self.expression(exp.Rollback, this=this) 437 438 durability = None 439 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 440 self._match_text_seq("DELAYED_DURABILITY") 441 self._match(TokenType.EQ) 442 443 if self._match_text_seq("OFF"): 444 durability = False 445 else: 446 self._match(TokenType.ON) 447 durability = True 448 449 self._match_r_paren() 450 451 return self.expression(exp.Commit, this=this, durability=durability) 452 453 def _parse_transaction(self) -> exp.Transaction | exp.Command: 454 """Applies to SQL Server and Azure SQL Database 455 BEGIN { TRAN | TRANSACTION } 456 [ { transaction_name | @tran_name_variable } 457 [ WITH MARK [ 'description' ] ] 458 ] 459 """ 460 if self._match_texts(("TRAN", "TRANSACTION")): 461 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 462 if self._match_text_seq("WITH", "MARK"): 463 transaction.set("mark", self._parse_string()) 464 465 return transaction 466 467 return self._parse_as_command(self._prev) 468 469 def _parse_returns(self) -> exp.ReturnsProperty: 470 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 471 returns = super()._parse_returns() 472 returns.set("table", table) 473 return returns 474 475 def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]: 476 to = self._parse_types() 477 self._match(TokenType.COMMA) 478 this = self._parse_conjunction() 479 480 if not to or not this: 481 return None 482 483 # Retrieve length of datatype and override to default if not specified 484 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 485 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 486 487 # Check whether a conversion with format is applicable 488 if self._match(TokenType.COMMA): 489 format_val = self._parse_number() 490 format_val_name = format_val.name if format_val else "" 491 492 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 493 raise ValueError( 494 f"CONVERT function at T-SQL does not support format style {format_val_name}" 495 ) 496 497 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 498 499 # Check whether the convert entails a string to date format 500 if to.this == DataType.Type.DATE: 501 return self.expression(exp.StrToDate, this=this, format=format_norm) 502 # Check whether the convert entails a string to datetime format 503 elif to.this == DataType.Type.DATETIME: 504 return self.expression(exp.StrToTime, this=this, format=format_norm) 505 # Check whether the convert entails a date to string format 506 elif to.this in self.VAR_LENGTH_DATATYPES: 507 return self.expression( 508 exp.Cast if strict else exp.TryCast, 509 to=to, 510 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 511 ) 512 elif to.this == DataType.Type.TEXT: 513 return self.expression(exp.TimeToStr, this=this, format=format_norm) 514 515 # Entails a simple cast without any format requirement 516 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to) 517 518 def _parse_user_defined_function( 519 self, kind: t.Optional[TokenType] = None 520 ) -> t.Optional[exp.Expression]: 521 this = super()._parse_user_defined_function(kind=kind) 522 523 if ( 524 kind == TokenType.FUNCTION 525 or isinstance(this, exp.UserDefinedFunction) 526 or self._match(TokenType.ALIAS, advance=False) 527 ): 528 return this 529 530 expressions = self._parse_csv(self._parse_function_parameter) 531 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 532 533 def _parse_id_var( 534 self, 535 any_token: bool = True, 536 tokens: t.Optional[t.Collection[TokenType]] = None, 537 ) -> t.Optional[exp.Expression]: 538 is_temporary = self._match(TokenType.HASH) 539 is_global = is_temporary and self._match(TokenType.HASH) 540 541 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 542 if this: 543 if is_global: 544 this.set("global", True) 545 elif is_temporary: 546 this.set("temporary", True) 547 548 return this 549 550 def _parse_create(self) -> exp.Create | exp.Command: 551 create = super()._parse_create() 552 553 if isinstance(create, exp.Create): 554 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 555 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 556 if not create.args.get("properties"): 557 create.set("properties", exp.Properties(expressions=[])) 558 559 create.args["properties"].append("expressions", exp.TemporaryProperty()) 560 561 return create 562 563 def _parse_if(self) -> t.Optional[exp.Expression]: 564 index = self._index 565 566 if self._match_text_seq("OBJECT_ID"): 567 self._parse_wrapped_csv(self._parse_string) 568 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 569 return self._parse_drop(exists=True) 570 self._retreat(index) 571 572 return super()._parse_if() 573 574 def _parse_unique(self) -> exp.UniqueColumnConstraint: 575 return self.expression( 576 exp.UniqueColumnConstraint, 577 this=None 578 if self._curr and self._curr.text.upper() in {"CLUSTERED", "NONCLUSTERED"} 579 else self._parse_schema(self._parse_id_var(any_token=False)), 580 ) 581 582 class Generator(generator.Generator): 583 LOCKING_READS_SUPPORTED = True 584 LIMIT_IS_TOP = True 585 QUERY_HINTS = False 586 RETURNING_END = False 587 NVL2_SUPPORTED = False 588 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 589 LIMIT_FETCH = "FETCH" 590 591 TYPE_MAPPING = { 592 **generator.Generator.TYPE_MAPPING, 593 exp.DataType.Type.BOOLEAN: "BIT", 594 exp.DataType.Type.DECIMAL: "NUMERIC", 595 exp.DataType.Type.DATETIME: "DATETIME2", 596 exp.DataType.Type.INT: "INTEGER", 597 exp.DataType.Type.TIMESTAMP: "DATETIME2", 598 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 599 exp.DataType.Type.VARIANT: "SQL_VARIANT", 600 } 601 602 TRANSFORMS = { 603 **generator.Generator.TRANSFORMS, 604 exp.AnyValue: any_value_to_max_sql, 605 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 606 exp.DateAdd: generate_date_delta_with_unit_sql, 607 exp.DateDiff: generate_date_delta_with_unit_sql, 608 exp.CurrentDate: rename_func("GETDATE"), 609 exp.CurrentTimestamp: rename_func("GETDATE"), 610 exp.Extract: rename_func("DATEPART"), 611 exp.GroupConcat: _string_agg_sql, 612 exp.If: rename_func("IIF"), 613 exp.Max: max_or_greatest, 614 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 615 exp.Min: min_or_least, 616 exp.NumberToStr: _format_sql, 617 exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]), 618 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 619 exp.SHA2: lambda self, e: self.func( 620 "HASHBYTES", 621 exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), 622 e.this, 623 ), 624 exp.TemporaryProperty: lambda self, e: "", 625 exp.TimeStrToTime: timestrtotime_sql, 626 exp.TimeToStr: _format_sql, 627 } 628 629 TRANSFORMS.pop(exp.ReturnsProperty) 630 631 PROPERTIES_LOCATION = { 632 **generator.Generator.PROPERTIES_LOCATION, 633 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 634 } 635 636 def boolean_sql(self, expression: exp.Boolean) -> str: 637 if type(expression.parent) in BIT_TYPES: 638 return "1" if expression.this else "0" 639 640 return "(1 = 1)" if expression.this else "(1 = 0)" 641 642 def is_sql(self, expression: exp.Is) -> str: 643 if isinstance(expression.expression, exp.Boolean): 644 return self.binary(expression, "=") 645 return self.binary(expression, "IS") 646 647 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 648 sql = self.sql(expression, "this") 649 properties = expression.args.get("properties") 650 651 if sql[:1] != "#" and any( 652 isinstance(prop, exp.TemporaryProperty) 653 for prop in (properties.expressions if properties else []) 654 ): 655 sql = f"#{sql}" 656 657 return sql 658 659 def create_sql(self, expression: exp.Create) -> str: 660 expression = expression.copy() 661 kind = self.sql(expression, "kind").upper() 662 exists = expression.args.pop("exists", None) 663 sql = super().create_sql(expression) 664 665 if exists: 666 table = expression.find(exp.Table) 667 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 668 if kind == "SCHEMA": 669 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')""" 670 elif kind == "TABLE": 671 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')""" 672 elif kind == "INDEX": 673 index = self.sql(exp.Literal.string(expression.this.text("this"))) 674 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')""" 675 elif expression.args.get("replace"): 676 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 677 678 return sql 679 680 def offset_sql(self, expression: exp.Offset) -> str: 681 return f"{super().offset_sql(expression)} ROWS" 682 683 def version_sql(self, expression: exp.Version) -> str: 684 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 685 this = f"FOR {name}" 686 expr = expression.expression 687 kind = expression.text("kind") 688 if kind in ("FROM", "BETWEEN"): 689 args = expr.expressions 690 sep = "TO" if kind == "FROM" else "AND" 691 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 692 else: 693 expr_sql = self.sql(expr) 694 695 expr_sql = f" {expr_sql}" if expr_sql else "" 696 return f"{this} {kind}{expr_sql}" 697 698 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 699 table = expression.args.get("table") 700 table = f"{table} " if table else "" 701 return f"RETURNS {table}{self.sql(expression, 'this')}" 702 703 def returning_sql(self, expression: exp.Returning) -> str: 704 into = self.sql(expression, "into") 705 into = self.seg(f"INTO {into}") if into else "" 706 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 707 708 def transaction_sql(self, expression: exp.Transaction) -> str: 709 this = self.sql(expression, "this") 710 this = f" {this}" if this else "" 711 mark = self.sql(expression, "mark") 712 mark = f" WITH MARK {mark}" if mark else "" 713 return f"BEGIN TRANSACTION{this}{mark}" 714 715 def commit_sql(self, expression: exp.Commit) -> str: 716 this = self.sql(expression, "this") 717 this = f" {this}" if this else "" 718 durability = expression.args.get("durability") 719 durability = ( 720 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 721 if durability is not None 722 else "" 723 ) 724 return f"COMMIT TRANSACTION{this}{durability}" 725 726 def rollback_sql(self, expression: exp.Rollback) -> str: 727 this = self.sql(expression, "this") 728 this = f" {this}" if this else "" 729 return f"ROLLBACK TRANSACTION{this}" 730 731 def identifier_sql(self, expression: exp.Identifier) -> str: 732 identifier = super().identifier_sql(expression) 733 734 if expression.args.get("global"): 735 identifier = f"##{identifier}" 736 elif expression.args.get("temporary"): 737 identifier = f"#{identifier}" 738 739 return identifier 740 741 def constraint_sql(self, expression: exp.Constraint) -> str: 742 this = self.sql(expression, "this") 743 expressions = self.expressions(expression, flat=True, sep=" ") 744 return f"CONSTRAINT {this} {expressions}" 745 746 # https://learn.microsoft.com/en-us/answers/questions/448821/create-table-in-sql-server 747 def generatedasidentitycolumnconstraint_sql( 748 self, expression: exp.GeneratedAsIdentityColumnConstraint 749 ) -> str: 750 start = self.sql(expression, "start") or "1" 751 increment = self.sql(expression, "increment") or "1" 752 return f"IDENTITY({start}, {increment})"
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 =
{'C', 'N'}
DEFAULT_START_DATE =
datetime.date(1900, 1, 1)
BIT_TYPES =
{<class 'sqlglot.expressions.In'>, <class 'sqlglot.expressions.NEQ'>, <class 'sqlglot.expressions.Is'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.EQ'>, <class 'sqlglot.expressions.Alias'>}
def
generate_date_delta_with_unit_sql( self: TSQL.Generator, expression: sqlglot.expressions.DateAdd | sqlglot.expressions.DateDiff) -> str:
206class TSQL(Dialect): 207 RESOLVES_IDENTIFIERS_AS_UPPERCASE = None 208 NULL_ORDERING = "nulls_are_small" 209 TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'" 210 211 TIME_MAPPING = { 212 "year": "%Y", 213 "qq": "%q", 214 "q": "%q", 215 "quarter": "%q", 216 "dayofyear": "%j", 217 "day": "%d", 218 "dy": "%d", 219 "y": "%Y", 220 "week": "%W", 221 "ww": "%W", 222 "wk": "%W", 223 "hour": "%h", 224 "hh": "%I", 225 "minute": "%M", 226 "mi": "%M", 227 "n": "%M", 228 "second": "%S", 229 "ss": "%S", 230 "s": "%-S", 231 "millisecond": "%f", 232 "ms": "%f", 233 "weekday": "%W", 234 "dw": "%W", 235 "month": "%m", 236 "mm": "%M", 237 "m": "%-M", 238 "Y": "%Y", 239 "YYYY": "%Y", 240 "YY": "%y", 241 "MMMM": "%B", 242 "MMM": "%b", 243 "MM": "%m", 244 "M": "%-m", 245 "dd": "%d", 246 "d": "%-d", 247 "HH": "%H", 248 "H": "%-H", 249 "h": "%-I", 250 "S": "%f", 251 "yyyy": "%Y", 252 "yy": "%y", 253 } 254 255 CONVERT_FORMAT_MAPPING = { 256 "0": "%b %d %Y %-I:%M%p", 257 "1": "%m/%d/%y", 258 "2": "%y.%m.%d", 259 "3": "%d/%m/%y", 260 "4": "%d.%m.%y", 261 "5": "%d-%m-%y", 262 "6": "%d %b %y", 263 "7": "%b %d, %y", 264 "8": "%H:%M:%S", 265 "9": "%b %d %Y %-I:%M:%S:%f%p", 266 "10": "mm-dd-yy", 267 "11": "yy/mm/dd", 268 "12": "yymmdd", 269 "13": "%d %b %Y %H:%M:ss:%f", 270 "14": "%H:%M:%S:%f", 271 "20": "%Y-%m-%d %H:%M:%S", 272 "21": "%Y-%m-%d %H:%M:%S.%f", 273 "22": "%m/%d/%y %-I:%M:%S %p", 274 "23": "%Y-%m-%d", 275 "24": "%H:%M:%S", 276 "25": "%Y-%m-%d %H:%M:%S.%f", 277 "100": "%b %d %Y %-I:%M%p", 278 "101": "%m/%d/%Y", 279 "102": "%Y.%m.%d", 280 "103": "%d/%m/%Y", 281 "104": "%d.%m.%Y", 282 "105": "%d-%m-%Y", 283 "106": "%d %b %Y", 284 "107": "%b %d, %Y", 285 "108": "%H:%M:%S", 286 "109": "%b %d %Y %-I:%M:%S:%f%p", 287 "110": "%m-%d-%Y", 288 "111": "%Y/%m/%d", 289 "112": "%Y%m%d", 290 "113": "%d %b %Y %H:%M:%S:%f", 291 "114": "%H:%M:%S:%f", 292 "120": "%Y-%m-%d %H:%M:%S", 293 "121": "%Y-%m-%d %H:%M:%S.%f", 294 } 295 296 FORMAT_TIME_MAPPING = { 297 "y": "%B %Y", 298 "d": "%m/%d/%Y", 299 "H": "%-H", 300 "h": "%-I", 301 "s": "%Y-%m-%d %H:%M:%S", 302 "D": "%A,%B,%Y", 303 "f": "%A,%B,%Y %-I:%M %p", 304 "F": "%A,%B,%Y %-I:%M:%S %p", 305 "g": "%m/%d/%Y %-I:%M %p", 306 "G": "%m/%d/%Y %-I:%M:%S %p", 307 "M": "%B %-d", 308 "m": "%B %-d", 309 "O": "%Y-%m-%dT%H:%M:%S", 310 "u": "%Y-%M-%D %H:%M:%S%z", 311 "U": "%A, %B %D, %Y %H:%M:%S%z", 312 "T": "%-I:%M:%S %p", 313 "t": "%-I:%M", 314 "Y": "%a %Y", 315 } 316 317 class Tokenizer(tokens.Tokenizer): 318 IDENTIFIERS = ['"', ("[", "]")] 319 QUOTES = ["'", '"'] 320 HEX_STRINGS = [("0x", ""), ("0X", "")] 321 322 KEYWORDS = { 323 **tokens.Tokenizer.KEYWORDS, 324 "DATETIME2": TokenType.DATETIME, 325 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 326 "DECLARE": TokenType.COMMAND, 327 "IMAGE": TokenType.IMAGE, 328 "MONEY": TokenType.MONEY, 329 "NTEXT": TokenType.TEXT, 330 "NVARCHAR(MAX)": TokenType.TEXT, 331 "PRINT": TokenType.COMMAND, 332 "PROC": TokenType.PROCEDURE, 333 "REAL": TokenType.FLOAT, 334 "ROWVERSION": TokenType.ROWVERSION, 335 "SMALLDATETIME": TokenType.DATETIME, 336 "SMALLMONEY": TokenType.SMALLMONEY, 337 "SQL_VARIANT": TokenType.VARIANT, 338 "TOP": TokenType.TOP, 339 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 340 "UPDATE STATISTICS": TokenType.COMMAND, 341 "VARCHAR(MAX)": TokenType.TEXT, 342 "XML": TokenType.XML, 343 "OUTPUT": TokenType.RETURNING, 344 "SYSTEM_USER": TokenType.CURRENT_USER, 345 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 346 } 347 348 class Parser(parser.Parser): 349 FUNCTIONS = { 350 **parser.Parser.FUNCTIONS, 351 "CHARINDEX": lambda args: exp.StrPosition( 352 this=seq_get(args, 1), 353 substr=seq_get(args, 0), 354 position=seq_get(args, 2), 355 ), 356 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 357 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 358 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 359 "DATEPART": _format_time_lambda(exp.TimeToStr), 360 "EOMONTH": _parse_eomonth, 361 "FORMAT": _parse_format, 362 "GETDATE": exp.CurrentTimestamp.from_arg_list, 363 "HASHBYTES": _parse_hashbytes, 364 "IIF": exp.If.from_arg_list, 365 "ISNULL": exp.Coalesce.from_arg_list, 366 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 367 "LEN": exp.Length.from_arg_list, 368 "REPLICATE": exp.Repeat.from_arg_list, 369 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 370 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 371 "SUSER_NAME": exp.CurrentUser.from_arg_list, 372 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 373 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 374 } 375 376 JOIN_HINTS = { 377 "LOOP", 378 "HASH", 379 "MERGE", 380 "REMOTE", 381 } 382 383 VAR_LENGTH_DATATYPES = { 384 DataType.Type.NVARCHAR, 385 DataType.Type.VARCHAR, 386 DataType.Type.CHAR, 387 DataType.Type.NCHAR, 388 } 389 390 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 391 TokenType.TABLE, 392 *parser.Parser.TYPE_TOKENS, 393 } 394 395 STATEMENT_PARSERS = { 396 **parser.Parser.STATEMENT_PARSERS, 397 TokenType.END: lambda self: self._parse_command(), 398 } 399 400 LOG_BASE_FIRST = False 401 LOG_DEFAULTS_TO_LN = True 402 403 CONCAT_NULL_OUTPUTS_STRING = True 404 405 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 406 407 def _parse_projections(self) -> t.List[exp.Expression]: 408 """ 409 T-SQL supports the syntax alias = expression in the SELECT's projection list, 410 so we transform all parsed Selects to convert their EQ projections into Aliases. 411 412 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 413 """ 414 return [ 415 exp.alias_(projection.expression, projection.this.this, copy=False) 416 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 417 else projection 418 for projection in super()._parse_projections() 419 ] 420 421 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 422 """Applies to SQL Server and Azure SQL Database 423 COMMIT [ { TRAN | TRANSACTION } 424 [ transaction_name | @tran_name_variable ] ] 425 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 426 427 ROLLBACK { TRAN | TRANSACTION } 428 [ transaction_name | @tran_name_variable 429 | savepoint_name | @savepoint_variable ] 430 """ 431 rollback = self._prev.token_type == TokenType.ROLLBACK 432 433 self._match_texts({"TRAN", "TRANSACTION"}) 434 this = self._parse_id_var() 435 436 if rollback: 437 return self.expression(exp.Rollback, this=this) 438 439 durability = None 440 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 441 self._match_text_seq("DELAYED_DURABILITY") 442 self._match(TokenType.EQ) 443 444 if self._match_text_seq("OFF"): 445 durability = False 446 else: 447 self._match(TokenType.ON) 448 durability = True 449 450 self._match_r_paren() 451 452 return self.expression(exp.Commit, this=this, durability=durability) 453 454 def _parse_transaction(self) -> exp.Transaction | exp.Command: 455 """Applies to SQL Server and Azure SQL Database 456 BEGIN { TRAN | TRANSACTION } 457 [ { transaction_name | @tran_name_variable } 458 [ WITH MARK [ 'description' ] ] 459 ] 460 """ 461 if self._match_texts(("TRAN", "TRANSACTION")): 462 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 463 if self._match_text_seq("WITH", "MARK"): 464 transaction.set("mark", self._parse_string()) 465 466 return transaction 467 468 return self._parse_as_command(self._prev) 469 470 def _parse_returns(self) -> exp.ReturnsProperty: 471 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 472 returns = super()._parse_returns() 473 returns.set("table", table) 474 return returns 475 476 def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]: 477 to = self._parse_types() 478 self._match(TokenType.COMMA) 479 this = self._parse_conjunction() 480 481 if not to or not this: 482 return None 483 484 # Retrieve length of datatype and override to default if not specified 485 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 486 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 487 488 # Check whether a conversion with format is applicable 489 if self._match(TokenType.COMMA): 490 format_val = self._parse_number() 491 format_val_name = format_val.name if format_val else "" 492 493 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 494 raise ValueError( 495 f"CONVERT function at T-SQL does not support format style {format_val_name}" 496 ) 497 498 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 499 500 # Check whether the convert entails a string to date format 501 if to.this == DataType.Type.DATE: 502 return self.expression(exp.StrToDate, this=this, format=format_norm) 503 # Check whether the convert entails a string to datetime format 504 elif to.this == DataType.Type.DATETIME: 505 return self.expression(exp.StrToTime, this=this, format=format_norm) 506 # Check whether the convert entails a date to string format 507 elif to.this in self.VAR_LENGTH_DATATYPES: 508 return self.expression( 509 exp.Cast if strict else exp.TryCast, 510 to=to, 511 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 512 ) 513 elif to.this == DataType.Type.TEXT: 514 return self.expression(exp.TimeToStr, this=this, format=format_norm) 515 516 # Entails a simple cast without any format requirement 517 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to) 518 519 def _parse_user_defined_function( 520 self, kind: t.Optional[TokenType] = None 521 ) -> t.Optional[exp.Expression]: 522 this = super()._parse_user_defined_function(kind=kind) 523 524 if ( 525 kind == TokenType.FUNCTION 526 or isinstance(this, exp.UserDefinedFunction) 527 or self._match(TokenType.ALIAS, advance=False) 528 ): 529 return this 530 531 expressions = self._parse_csv(self._parse_function_parameter) 532 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 533 534 def _parse_id_var( 535 self, 536 any_token: bool = True, 537 tokens: t.Optional[t.Collection[TokenType]] = None, 538 ) -> t.Optional[exp.Expression]: 539 is_temporary = self._match(TokenType.HASH) 540 is_global = is_temporary and self._match(TokenType.HASH) 541 542 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 543 if this: 544 if is_global: 545 this.set("global", True) 546 elif is_temporary: 547 this.set("temporary", True) 548 549 return this 550 551 def _parse_create(self) -> exp.Create | exp.Command: 552 create = super()._parse_create() 553 554 if isinstance(create, exp.Create): 555 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 556 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 557 if not create.args.get("properties"): 558 create.set("properties", exp.Properties(expressions=[])) 559 560 create.args["properties"].append("expressions", exp.TemporaryProperty()) 561 562 return create 563 564 def _parse_if(self) -> t.Optional[exp.Expression]: 565 index = self._index 566 567 if self._match_text_seq("OBJECT_ID"): 568 self._parse_wrapped_csv(self._parse_string) 569 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 570 return self._parse_drop(exists=True) 571 self._retreat(index) 572 573 return super()._parse_if() 574 575 def _parse_unique(self) -> exp.UniqueColumnConstraint: 576 return self.expression( 577 exp.UniqueColumnConstraint, 578 this=None 579 if self._curr and self._curr.text.upper() in {"CLUSTERED", "NONCLUSTERED"} 580 else self._parse_schema(self._parse_id_var(any_token=False)), 581 ) 582 583 class Generator(generator.Generator): 584 LOCKING_READS_SUPPORTED = True 585 LIMIT_IS_TOP = True 586 QUERY_HINTS = False 587 RETURNING_END = False 588 NVL2_SUPPORTED = False 589 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 590 LIMIT_FETCH = "FETCH" 591 592 TYPE_MAPPING = { 593 **generator.Generator.TYPE_MAPPING, 594 exp.DataType.Type.BOOLEAN: "BIT", 595 exp.DataType.Type.DECIMAL: "NUMERIC", 596 exp.DataType.Type.DATETIME: "DATETIME2", 597 exp.DataType.Type.INT: "INTEGER", 598 exp.DataType.Type.TIMESTAMP: "DATETIME2", 599 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 600 exp.DataType.Type.VARIANT: "SQL_VARIANT", 601 } 602 603 TRANSFORMS = { 604 **generator.Generator.TRANSFORMS, 605 exp.AnyValue: any_value_to_max_sql, 606 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 607 exp.DateAdd: generate_date_delta_with_unit_sql, 608 exp.DateDiff: generate_date_delta_with_unit_sql, 609 exp.CurrentDate: rename_func("GETDATE"), 610 exp.CurrentTimestamp: rename_func("GETDATE"), 611 exp.Extract: rename_func("DATEPART"), 612 exp.GroupConcat: _string_agg_sql, 613 exp.If: rename_func("IIF"), 614 exp.Max: max_or_greatest, 615 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 616 exp.Min: min_or_least, 617 exp.NumberToStr: _format_sql, 618 exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]), 619 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 620 exp.SHA2: lambda self, e: self.func( 621 "HASHBYTES", 622 exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), 623 e.this, 624 ), 625 exp.TemporaryProperty: lambda self, e: "", 626 exp.TimeStrToTime: timestrtotime_sql, 627 exp.TimeToStr: _format_sql, 628 } 629 630 TRANSFORMS.pop(exp.ReturnsProperty) 631 632 PROPERTIES_LOCATION = { 633 **generator.Generator.PROPERTIES_LOCATION, 634 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 635 } 636 637 def boolean_sql(self, expression: exp.Boolean) -> str: 638 if type(expression.parent) in BIT_TYPES: 639 return "1" if expression.this else "0" 640 641 return "(1 = 1)" if expression.this else "(1 = 0)" 642 643 def is_sql(self, expression: exp.Is) -> str: 644 if isinstance(expression.expression, exp.Boolean): 645 return self.binary(expression, "=") 646 return self.binary(expression, "IS") 647 648 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 649 sql = self.sql(expression, "this") 650 properties = expression.args.get("properties") 651 652 if sql[:1] != "#" and any( 653 isinstance(prop, exp.TemporaryProperty) 654 for prop in (properties.expressions if properties else []) 655 ): 656 sql = f"#{sql}" 657 658 return sql 659 660 def create_sql(self, expression: exp.Create) -> str: 661 expression = expression.copy() 662 kind = self.sql(expression, "kind").upper() 663 exists = expression.args.pop("exists", None) 664 sql = super().create_sql(expression) 665 666 if exists: 667 table = expression.find(exp.Table) 668 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 669 if kind == "SCHEMA": 670 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')""" 671 elif kind == "TABLE": 672 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')""" 673 elif kind == "INDEX": 674 index = self.sql(exp.Literal.string(expression.this.text("this"))) 675 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')""" 676 elif expression.args.get("replace"): 677 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 678 679 return sql 680 681 def offset_sql(self, expression: exp.Offset) -> str: 682 return f"{super().offset_sql(expression)} ROWS" 683 684 def version_sql(self, expression: exp.Version) -> str: 685 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 686 this = f"FOR {name}" 687 expr = expression.expression 688 kind = expression.text("kind") 689 if kind in ("FROM", "BETWEEN"): 690 args = expr.expressions 691 sep = "TO" if kind == "FROM" else "AND" 692 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 693 else: 694 expr_sql = self.sql(expr) 695 696 expr_sql = f" {expr_sql}" if expr_sql else "" 697 return f"{this} {kind}{expr_sql}" 698 699 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 700 table = expression.args.get("table") 701 table = f"{table} " if table else "" 702 return f"RETURNS {table}{self.sql(expression, 'this')}" 703 704 def returning_sql(self, expression: exp.Returning) -> str: 705 into = self.sql(expression, "into") 706 into = self.seg(f"INTO {into}") if into else "" 707 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 708 709 def transaction_sql(self, expression: exp.Transaction) -> str: 710 this = self.sql(expression, "this") 711 this = f" {this}" if this else "" 712 mark = self.sql(expression, "mark") 713 mark = f" WITH MARK {mark}" if mark else "" 714 return f"BEGIN TRANSACTION{this}{mark}" 715 716 def commit_sql(self, expression: exp.Commit) -> str: 717 this = self.sql(expression, "this") 718 this = f" {this}" if this else "" 719 durability = expression.args.get("durability") 720 durability = ( 721 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 722 if durability is not None 723 else "" 724 ) 725 return f"COMMIT TRANSACTION{this}{durability}" 726 727 def rollback_sql(self, expression: exp.Rollback) -> str: 728 this = self.sql(expression, "this") 729 this = f" {this}" if this else "" 730 return f"ROLLBACK TRANSACTION{this}" 731 732 def identifier_sql(self, expression: exp.Identifier) -> str: 733 identifier = super().identifier_sql(expression) 734 735 if expression.args.get("global"): 736 identifier = f"##{identifier}" 737 elif expression.args.get("temporary"): 738 identifier = f"#{identifier}" 739 740 return identifier 741 742 def constraint_sql(self, expression: exp.Constraint) -> str: 743 this = self.sql(expression, "this") 744 expressions = self.expressions(expression, flat=True, sep=" ") 745 return f"CONSTRAINT {this} {expressions}" 746 747 # https://learn.microsoft.com/en-us/answers/questions/448821/create-table-in-sql-server 748 def generatedasidentitycolumnconstraint_sql( 749 self, expression: exp.GeneratedAsIdentityColumnConstraint 750 ) -> str: 751 start = self.sql(expression, "start") or "1" 752 increment = self.sql(expression, "increment") or "1" 753 return f"IDENTITY({start}, {increment})"
TIME_MAPPING: Dict[str, str] =
{'year': '%Y', 'qq': '%q', 'q': '%q', 'quarter': '%q', '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', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
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}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {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}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {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', '%q': 'quarter', '%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', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict =
{'%': {'Y': {0: True}, 'q': {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}, 'H': {0: True}}}
Inherited Members
- sqlglot.dialects.dialect.Dialect
- INDEX_OFFSET
- UNNEST_COLUMN_ONLY
- ALIAS_POST_TABLESAMPLE
- IDENTIFIERS_CAN_START_WITH_DIGIT
- DPIPE_IS_STRING_CONCAT
- STRICT_STRING_CONCAT
- NORMALIZE_FUNCTIONS
- DATE_FORMAT
- DATEINT_FORMAT
- FORMAT_MAPPING
- PSEUDOCOLUMNS
- get_or_raise
- format_time
- normalize_identifier
- case_sensitive
- can_identify
- quote_identifier
- parse
- parse_into
- generate
- transpile
- tokenize
- tokenizer
- parser
- generator
317 class Tokenizer(tokens.Tokenizer): 318 IDENTIFIERS = ['"', ("[", "]")] 319 QUOTES = ["'", '"'] 320 HEX_STRINGS = [("0x", ""), ("0X", "")] 321 322 KEYWORDS = { 323 **tokens.Tokenizer.KEYWORDS, 324 "DATETIME2": TokenType.DATETIME, 325 "DATETIMEOFFSET": TokenType.TIMESTAMPTZ, 326 "DECLARE": TokenType.COMMAND, 327 "IMAGE": TokenType.IMAGE, 328 "MONEY": TokenType.MONEY, 329 "NTEXT": TokenType.TEXT, 330 "NVARCHAR(MAX)": TokenType.TEXT, 331 "PRINT": TokenType.COMMAND, 332 "PROC": TokenType.PROCEDURE, 333 "REAL": TokenType.FLOAT, 334 "ROWVERSION": TokenType.ROWVERSION, 335 "SMALLDATETIME": TokenType.DATETIME, 336 "SMALLMONEY": TokenType.SMALLMONEY, 337 "SQL_VARIANT": TokenType.VARIANT, 338 "TOP": TokenType.TOP, 339 "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER, 340 "UPDATE STATISTICS": TokenType.COMMAND, 341 "VARCHAR(MAX)": TokenType.TEXT, 342 "XML": TokenType.XML, 343 "OUTPUT": TokenType.RETURNING, 344 "SYSTEM_USER": TokenType.CURRENT_USER, 345 "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT, 346 }
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.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'>, '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'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.BIGINT: 'BIGINT'>, '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'>, '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'>}
348 class Parser(parser.Parser): 349 FUNCTIONS = { 350 **parser.Parser.FUNCTIONS, 351 "CHARINDEX": lambda args: exp.StrPosition( 352 this=seq_get(args, 1), 353 substr=seq_get(args, 0), 354 position=seq_get(args, 2), 355 ), 356 "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL), 357 "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL), 358 "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True), 359 "DATEPART": _format_time_lambda(exp.TimeToStr), 360 "EOMONTH": _parse_eomonth, 361 "FORMAT": _parse_format, 362 "GETDATE": exp.CurrentTimestamp.from_arg_list, 363 "HASHBYTES": _parse_hashbytes, 364 "IIF": exp.If.from_arg_list, 365 "ISNULL": exp.Coalesce.from_arg_list, 366 "JSON_VALUE": exp.JSONExtractScalar.from_arg_list, 367 "LEN": exp.Length.from_arg_list, 368 "REPLICATE": exp.Repeat.from_arg_list, 369 "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)), 370 "SYSDATETIME": exp.CurrentTimestamp.from_arg_list, 371 "SUSER_NAME": exp.CurrentUser.from_arg_list, 372 "SUSER_SNAME": exp.CurrentUser.from_arg_list, 373 "SYSTEM_USER": exp.CurrentUser.from_arg_list, 374 } 375 376 JOIN_HINTS = { 377 "LOOP", 378 "HASH", 379 "MERGE", 380 "REMOTE", 381 } 382 383 VAR_LENGTH_DATATYPES = { 384 DataType.Type.NVARCHAR, 385 DataType.Type.VARCHAR, 386 DataType.Type.CHAR, 387 DataType.Type.NCHAR, 388 } 389 390 RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - { 391 TokenType.TABLE, 392 *parser.Parser.TYPE_TOKENS, 393 } 394 395 STATEMENT_PARSERS = { 396 **parser.Parser.STATEMENT_PARSERS, 397 TokenType.END: lambda self: self._parse_command(), 398 } 399 400 LOG_BASE_FIRST = False 401 LOG_DEFAULTS_TO_LN = True 402 403 CONCAT_NULL_OUTPUTS_STRING = True 404 405 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 406 407 def _parse_projections(self) -> t.List[exp.Expression]: 408 """ 409 T-SQL supports the syntax alias = expression in the SELECT's projection list, 410 so we transform all parsed Selects to convert their EQ projections into Aliases. 411 412 See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax 413 """ 414 return [ 415 exp.alias_(projection.expression, projection.this.this, copy=False) 416 if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column) 417 else projection 418 for projection in super()._parse_projections() 419 ] 420 421 def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback: 422 """Applies to SQL Server and Azure SQL Database 423 COMMIT [ { TRAN | TRANSACTION } 424 [ transaction_name | @tran_name_variable ] ] 425 [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ] 426 427 ROLLBACK { TRAN | TRANSACTION } 428 [ transaction_name | @tran_name_variable 429 | savepoint_name | @savepoint_variable ] 430 """ 431 rollback = self._prev.token_type == TokenType.ROLLBACK 432 433 self._match_texts({"TRAN", "TRANSACTION"}) 434 this = self._parse_id_var() 435 436 if rollback: 437 return self.expression(exp.Rollback, this=this) 438 439 durability = None 440 if self._match_pair(TokenType.WITH, TokenType.L_PAREN): 441 self._match_text_seq("DELAYED_DURABILITY") 442 self._match(TokenType.EQ) 443 444 if self._match_text_seq("OFF"): 445 durability = False 446 else: 447 self._match(TokenType.ON) 448 durability = True 449 450 self._match_r_paren() 451 452 return self.expression(exp.Commit, this=this, durability=durability) 453 454 def _parse_transaction(self) -> exp.Transaction | exp.Command: 455 """Applies to SQL Server and Azure SQL Database 456 BEGIN { TRAN | TRANSACTION } 457 [ { transaction_name | @tran_name_variable } 458 [ WITH MARK [ 'description' ] ] 459 ] 460 """ 461 if self._match_texts(("TRAN", "TRANSACTION")): 462 transaction = self.expression(exp.Transaction, this=self._parse_id_var()) 463 if self._match_text_seq("WITH", "MARK"): 464 transaction.set("mark", self._parse_string()) 465 466 return transaction 467 468 return self._parse_as_command(self._prev) 469 470 def _parse_returns(self) -> exp.ReturnsProperty: 471 table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS) 472 returns = super()._parse_returns() 473 returns.set("table", table) 474 return returns 475 476 def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]: 477 to = self._parse_types() 478 self._match(TokenType.COMMA) 479 this = self._parse_conjunction() 480 481 if not to or not this: 482 return None 483 484 # Retrieve length of datatype and override to default if not specified 485 if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES: 486 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 487 488 # Check whether a conversion with format is applicable 489 if self._match(TokenType.COMMA): 490 format_val = self._parse_number() 491 format_val_name = format_val.name if format_val else "" 492 493 if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING: 494 raise ValueError( 495 f"CONVERT function at T-SQL does not support format style {format_val_name}" 496 ) 497 498 format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name]) 499 500 # Check whether the convert entails a string to date format 501 if to.this == DataType.Type.DATE: 502 return self.expression(exp.StrToDate, this=this, format=format_norm) 503 # Check whether the convert entails a string to datetime format 504 elif to.this == DataType.Type.DATETIME: 505 return self.expression(exp.StrToTime, this=this, format=format_norm) 506 # Check whether the convert entails a date to string format 507 elif to.this in self.VAR_LENGTH_DATATYPES: 508 return self.expression( 509 exp.Cast if strict else exp.TryCast, 510 to=to, 511 this=self.expression(exp.TimeToStr, this=this, format=format_norm), 512 ) 513 elif to.this == DataType.Type.TEXT: 514 return self.expression(exp.TimeToStr, this=this, format=format_norm) 515 516 # Entails a simple cast without any format requirement 517 return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to) 518 519 def _parse_user_defined_function( 520 self, kind: t.Optional[TokenType] = None 521 ) -> t.Optional[exp.Expression]: 522 this = super()._parse_user_defined_function(kind=kind) 523 524 if ( 525 kind == TokenType.FUNCTION 526 or isinstance(this, exp.UserDefinedFunction) 527 or self._match(TokenType.ALIAS, advance=False) 528 ): 529 return this 530 531 expressions = self._parse_csv(self._parse_function_parameter) 532 return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions) 533 534 def _parse_id_var( 535 self, 536 any_token: bool = True, 537 tokens: t.Optional[t.Collection[TokenType]] = None, 538 ) -> t.Optional[exp.Expression]: 539 is_temporary = self._match(TokenType.HASH) 540 is_global = is_temporary and self._match(TokenType.HASH) 541 542 this = super()._parse_id_var(any_token=any_token, tokens=tokens) 543 if this: 544 if is_global: 545 this.set("global", True) 546 elif is_temporary: 547 this.set("temporary", True) 548 549 return this 550 551 def _parse_create(self) -> exp.Create | exp.Command: 552 create = super()._parse_create() 553 554 if isinstance(create, exp.Create): 555 table = create.this.this if isinstance(create.this, exp.Schema) else create.this 556 if isinstance(table, exp.Table) and table.this.args.get("temporary"): 557 if not create.args.get("properties"): 558 create.set("properties", exp.Properties(expressions=[])) 559 560 create.args["properties"].append("expressions", exp.TemporaryProperty()) 561 562 return create 563 564 def _parse_if(self) -> t.Optional[exp.Expression]: 565 index = self._index 566 567 if self._match_text_seq("OBJECT_ID"): 568 self._parse_wrapped_csv(self._parse_string) 569 if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP): 570 return self._parse_drop(exists=True) 571 self._retreat(index) 572 573 return super()._parse_if() 574 575 def _parse_unique(self) -> exp.UniqueColumnConstraint: 576 return self.expression( 577 exp.UniqueColumnConstraint, 578 this=None 579 if self._curr and self._curr.text.upper() in {"CLUSTERED", "NONCLUSTERED"} 580 else self._parse_schema(self._parse_id_var(any_token=False)), 581 )
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'>>, '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'>>, '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'>>, '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'>>, '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'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, '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'>>, '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'>>, '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'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, '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'>>, '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_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_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_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log'>>, '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'>>, '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'>>, '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'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, '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_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SET_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SetAgg'>>, '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_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_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_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_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'>>, '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_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, '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>, '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.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.SET: 'SET'>, <TokenType.DIV: 'DIV'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TRUE: 'TRUE'>, <TokenType.VAR: 'VAR'>, <TokenType.IS: 'IS'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SOME: 'SOME'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.CASE: 'CASE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.ROW: 'ROW'>, <TokenType.END: 'END'>, <TokenType.ALL: 'ALL'>, <TokenType.FILTER: 'FILTER'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.DESC: 'DESC'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ANTI: 'ANTI'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.LEFT: 'LEFT'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.APPLY: 'APPLY'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FALSE: 'FALSE'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.KEEP: 'KEEP'>, <TokenType.ANY: 'ANY'>, <TokenType.RANGE: 'RANGE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.CACHE: 'CACHE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.SHOW: 'SHOW'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.ASC: 'ASC'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.TOP: 'TOP'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.NEXT: 'NEXT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.VIEW: 'VIEW'>, <TokenType.INDEX: 'INDEX'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.FULL: 'FULL'>}
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.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <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>>}
SET_TRIE: Dict =
{'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
FORMAT_TRIE: Dict =
{'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {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}}
TIME_MAPPING: Dict[str, str] =
{'year': '%Y', 'qq': '%q', 'q': '%q', 'quarter': '%q', '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', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
TIME_TRIE: Dict =
{'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {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}}
Inherited Members
- sqlglot.parser.Parser
- Parser
- NO_PAREN_FUNCTIONS
- STRUCT_TYPE_TOKENS
- NESTED_TYPE_TOKENS
- ENUM_TYPE_TOKENS
- TYPE_TOKENS
- SIGNED_TO_UNSIGNED_TYPE_TOKEN
- SUBQUERY_PREDICATES
- RESERVED_KEYWORDS
- DB_CREATABLES
- CREATABLES
- ID_VAR_TOKENS
- INTERVAL_VARS
- TABLE_ALIAS_TOKENS
- COMMENT_TABLE_ALIAS_TOKENS
- UPDATE_ALIAS_TOKENS
- TRIM_TYPES
- FUNC_TOKENS
- CONJUNCTION
- EQUALITY
- COMPARISON
- BITWISE
- TERM
- FACTOR
- 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_KINDS
- TABLE_INDEX_HINT_TOKENS
- WINDOW_ALIAS_TOKENS
- WINDOW_BEFORE_PAREN_TOKENS
- WINDOW_SIDES
- ADD_CONSTRAINT_TOKENS
- DISTINCT_TOKENS
- STRICT_CAST
- PREFIXED_PIVOT_COLUMNS
- IDENTIFY_PIVOT_STRINGS
- SUPPORTS_USER_DEFINED_TYPES
- TABLESAMPLE_CSV
- INDEX_OFFSET
- UNNEST_COLUMN_ONLY
- ALIAS_POST_TABLESAMPLE
- STRICT_STRING_CONCAT
- NORMALIZE_FUNCTIONS
- FORMAT_MAPPING
- error_level
- error_message_context
- max_errors
- reset
- parse
- parse_into
- check_errors
- raise_error
- expression
- validate_expression
- errors
- sql
583 class Generator(generator.Generator): 584 LOCKING_READS_SUPPORTED = True 585 LIMIT_IS_TOP = True 586 QUERY_HINTS = False 587 RETURNING_END = False 588 NVL2_SUPPORTED = False 589 ALTER_TABLE_ADD_COLUMN_KEYWORD = False 590 LIMIT_FETCH = "FETCH" 591 592 TYPE_MAPPING = { 593 **generator.Generator.TYPE_MAPPING, 594 exp.DataType.Type.BOOLEAN: "BIT", 595 exp.DataType.Type.DECIMAL: "NUMERIC", 596 exp.DataType.Type.DATETIME: "DATETIME2", 597 exp.DataType.Type.INT: "INTEGER", 598 exp.DataType.Type.TIMESTAMP: "DATETIME2", 599 exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET", 600 exp.DataType.Type.VARIANT: "SQL_VARIANT", 601 } 602 603 TRANSFORMS = { 604 **generator.Generator.TRANSFORMS, 605 exp.AnyValue: any_value_to_max_sql, 606 exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY", 607 exp.DateAdd: generate_date_delta_with_unit_sql, 608 exp.DateDiff: generate_date_delta_with_unit_sql, 609 exp.CurrentDate: rename_func("GETDATE"), 610 exp.CurrentTimestamp: rename_func("GETDATE"), 611 exp.Extract: rename_func("DATEPART"), 612 exp.GroupConcat: _string_agg_sql, 613 exp.If: rename_func("IIF"), 614 exp.Max: max_or_greatest, 615 exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this), 616 exp.Min: min_or_least, 617 exp.NumberToStr: _format_sql, 618 exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]), 619 exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this), 620 exp.SHA2: lambda self, e: self.func( 621 "HASHBYTES", 622 exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), 623 e.this, 624 ), 625 exp.TemporaryProperty: lambda self, e: "", 626 exp.TimeStrToTime: timestrtotime_sql, 627 exp.TimeToStr: _format_sql, 628 } 629 630 TRANSFORMS.pop(exp.ReturnsProperty) 631 632 PROPERTIES_LOCATION = { 633 **generator.Generator.PROPERTIES_LOCATION, 634 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 635 } 636 637 def boolean_sql(self, expression: exp.Boolean) -> str: 638 if type(expression.parent) in BIT_TYPES: 639 return "1" if expression.this else "0" 640 641 return "(1 = 1)" if expression.this else "(1 = 0)" 642 643 def is_sql(self, expression: exp.Is) -> str: 644 if isinstance(expression.expression, exp.Boolean): 645 return self.binary(expression, "=") 646 return self.binary(expression, "IS") 647 648 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 649 sql = self.sql(expression, "this") 650 properties = expression.args.get("properties") 651 652 if sql[:1] != "#" and any( 653 isinstance(prop, exp.TemporaryProperty) 654 for prop in (properties.expressions if properties else []) 655 ): 656 sql = f"#{sql}" 657 658 return sql 659 660 def create_sql(self, expression: exp.Create) -> str: 661 expression = expression.copy() 662 kind = self.sql(expression, "kind").upper() 663 exists = expression.args.pop("exists", None) 664 sql = super().create_sql(expression) 665 666 if exists: 667 table = expression.find(exp.Table) 668 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 669 if kind == "SCHEMA": 670 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')""" 671 elif kind == "TABLE": 672 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')""" 673 elif kind == "INDEX": 674 index = self.sql(exp.Literal.string(expression.this.text("this"))) 675 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')""" 676 elif expression.args.get("replace"): 677 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 678 679 return sql 680 681 def offset_sql(self, expression: exp.Offset) -> str: 682 return f"{super().offset_sql(expression)} ROWS" 683 684 def version_sql(self, expression: exp.Version) -> str: 685 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 686 this = f"FOR {name}" 687 expr = expression.expression 688 kind = expression.text("kind") 689 if kind in ("FROM", "BETWEEN"): 690 args = expr.expressions 691 sep = "TO" if kind == "FROM" else "AND" 692 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 693 else: 694 expr_sql = self.sql(expr) 695 696 expr_sql = f" {expr_sql}" if expr_sql else "" 697 return f"{this} {kind}{expr_sql}" 698 699 def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str: 700 table = expression.args.get("table") 701 table = f"{table} " if table else "" 702 return f"RETURNS {table}{self.sql(expression, 'this')}" 703 704 def returning_sql(self, expression: exp.Returning) -> str: 705 into = self.sql(expression, "into") 706 into = self.seg(f"INTO {into}") if into else "" 707 return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}" 708 709 def transaction_sql(self, expression: exp.Transaction) -> str: 710 this = self.sql(expression, "this") 711 this = f" {this}" if this else "" 712 mark = self.sql(expression, "mark") 713 mark = f" WITH MARK {mark}" if mark else "" 714 return f"BEGIN TRANSACTION{this}{mark}" 715 716 def commit_sql(self, expression: exp.Commit) -> str: 717 this = self.sql(expression, "this") 718 this = f" {this}" if this else "" 719 durability = expression.args.get("durability") 720 durability = ( 721 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 722 if durability is not None 723 else "" 724 ) 725 return f"COMMIT TRANSACTION{this}{durability}" 726 727 def rollback_sql(self, expression: exp.Rollback) -> str: 728 this = self.sql(expression, "this") 729 this = f" {this}" if this else "" 730 return f"ROLLBACK TRANSACTION{this}" 731 732 def identifier_sql(self, expression: exp.Identifier) -> str: 733 identifier = super().identifier_sql(expression) 734 735 if expression.args.get("global"): 736 identifier = f"##{identifier}" 737 elif expression.args.get("temporary"): 738 identifier = f"#{identifier}" 739 740 return identifier 741 742 def constraint_sql(self, expression: exp.Constraint) -> str: 743 this = self.sql(expression, "this") 744 expressions = self.expressions(expression, flat=True, sep=" ") 745 return f"CONSTRAINT {this} {expressions}" 746 747 # https://learn.microsoft.com/en-us/answers/questions/448821/create-table-in-sql-server 748 def generatedasidentitycolumnconstraint_sql( 749 self, expression: exp.GeneratedAsIdentityColumnConstraint 750 ) -> str: 751 start = self.sql(expression, "start") or "1" 752 increment = self.sql(expression, "increment") or "1" 753 return f"IDENTITY({start}, {increment})"
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
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.INT: 'INT'>: 'INTEGER', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS =
{<class 'sqlglot.expressions.DateAdd'>: <function generate_date_delta_with_unit_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function Generator.<lambda>>, <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.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.InlineLengthColumnConstraint'>: <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.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <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.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 generate_date_delta_with_unit_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.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<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.Select'>: <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>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <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.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.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <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.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.SortKeyProperty'>: <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.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'>}
648 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 649 sql = self.sql(expression, "this") 650 properties = expression.args.get("properties") 651 652 if sql[:1] != "#" and any( 653 isinstance(prop, exp.TemporaryProperty) 654 for prop in (properties.expressions if properties else []) 655 ): 656 sql = f"#{sql}" 657 658 return sql
660 def create_sql(self, expression: exp.Create) -> str: 661 expression = expression.copy() 662 kind = self.sql(expression, "kind").upper() 663 exists = expression.args.pop("exists", None) 664 sql = super().create_sql(expression) 665 666 if exists: 667 table = expression.find(exp.Table) 668 identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else "")) 669 if kind == "SCHEMA": 670 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')""" 671 elif kind == "TABLE": 672 sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')""" 673 elif kind == "INDEX": 674 index = self.sql(exp.Literal.string(expression.this.text("this"))) 675 sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')""" 676 elif expression.args.get("replace"): 677 sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1) 678 679 return sql
684 def version_sql(self, expression: exp.Version) -> str: 685 name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name 686 this = f"FOR {name}" 687 expr = expression.expression 688 kind = expression.text("kind") 689 if kind in ("FROM", "BETWEEN"): 690 args = expr.expressions 691 sep = "TO" if kind == "FROM" else "AND" 692 expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}" 693 else: 694 expr_sql = self.sql(expr) 695 696 expr_sql = f" {expr_sql}" if expr_sql else "" 697 return f"{this} {kind}{expr_sql}"
716 def commit_sql(self, expression: exp.Commit) -> str: 717 this = self.sql(expression, "this") 718 this = f" {this}" if this else "" 719 durability = expression.args.get("durability") 720 durability = ( 721 f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})" 722 if durability is not None 723 else "" 724 ) 725 return f"COMMIT TRANSACTION{this}{durability}"
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
INVERSE_TIME_MAPPING: Dict[str, str] =
{'%Y': 'yyyy', '%q': 'quarter', '%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', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict =
{'%': {'Y': {0: True}, 'q': {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}, 'H': {0: True}}}
@classmethod
def
can_identify(text: str, identify: str | bool = 'safe') -> bool:
257 @classmethod 258 def can_identify(cls, text: str, identify: str | bool = "safe") -> bool: 259 """Checks if text can be identified given an identify option. 260 261 Args: 262 text: The text to check. 263 identify: 264 "always" or `True`: Always returns true. 265 "safe": True if the identifier is case-insensitive. 266 267 Returns: 268 Whether or not the given text can be identified. 269 """ 270 if identify is True or identify == "always": 271 return True 272 273 if identify == "safe": 274 return not cls.case_sensitive(text) 275 276 return False
Checks if text can be identified given an identify option.
Arguments:
- text: The text to check.
- identify: "always" or
True
: Always returns true. "safe": True if the identifier is case-insensitive.
Returns:
Whether or not the given text can be identified.
TOKENIZER_CLASS =
<class 'TSQL.Tokenizer'>
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- EXPLICIT_UNION
- WRAP_DERIVED_VALUES
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- TABLESAMPLE_WITH_METHOD
- TABLESAMPLE_SIZE_IS_PERCENT
- 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
- STAR_MAPPING
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- STRUCT_DELIMITER
- PARAMETER_TOKEN
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- SENTINEL_LINE_BREAK
- INDEX_OFFSET
- UNNEST_COLUMN_ONLY
- ALIAS_POST_TABLESAMPLE
- IDENTIFIERS_CAN_START_WITH_DIGIT
- STRICT_STRING_CONCAT
- NORMALIZE_FUNCTIONS
- ESCAPE_LINE_BREAK
- pretty
- identify
- normalize
- pad
- unsupported_level
- max_unsupported
- leading_comma
- max_text_width
- comments
- normalize_functions
- unsupported_messages
- generate
- 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
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- clone_sql
- describe_sql
- prepend_ctes
- with_sql
- cte_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- bytestring_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_sql
- likeproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- lockingproperty_sql
- withdataproperty_sql
- insert_sql
- intersect_sql
- intersect_op
- introducer_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_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
- setitem_sql
- set_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- order_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
- safebracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- nextvaluefor_sql
- extract_sql
- trim_sql
- safeconcat_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- formatjson_sql
- jsonobject_sql
- jsonarray_sql
- jsonarrayagg_sql
- jsoncolumndef_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
- aliases_sql
- attimezone_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
- altertable_sql
- droppartition_sql
- addconstraint_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- intdiv_sql
- dpipe_sql
- safedpipe_sql
- div_sql
- overlaps_sql
- distance_sql
- dot_sql
- eq_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
- use_sql
- binary
- function_fallback_sql
- func
- format_args
- text_width
- format_time
- expressions
- op_expressions
- naked_property
- set_operation
- 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