Edit on GitHub

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    max_or_greatest,
 11    min_or_least,
 12    parse_date_delta,
 13    rename_func,
 14    timestrtotime_sql,
 15)
 16from sqlglot.expressions import DataType
 17from sqlglot.helper import seq_get
 18from sqlglot.time import format_time
 19from sqlglot.tokens import TokenType
 20
 21if t.TYPE_CHECKING:
 22    from sqlglot._typing import E
 23
 24FULL_FORMAT_TIME_MAPPING = {
 25    "weekday": "%A",
 26    "dw": "%A",
 27    "w": "%A",
 28    "month": "%B",
 29    "mm": "%B",
 30    "m": "%B",
 31}
 32
 33DATE_DELTA_INTERVAL = {
 34    "year": "year",
 35    "yyyy": "year",
 36    "yy": "year",
 37    "quarter": "quarter",
 38    "qq": "quarter",
 39    "q": "quarter",
 40    "month": "month",
 41    "mm": "month",
 42    "m": "month",
 43    "week": "week",
 44    "ww": "week",
 45    "wk": "week",
 46    "day": "day",
 47    "dd": "day",
 48    "d": "day",
 49}
 50
 51
 52DATE_FMT_RE = re.compile("([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})")
 53
 54# N = Numeric, C=Currency
 55TRANSPILE_SAFE_NUMBER_FMT = {"N", "C"}
 56
 57DEFAULT_START_DATE = datetime.date(1900, 1, 1)
 58
 59
 60def _format_time_lambda(
 61    exp_class: t.Type[E], full_format_mapping: t.Optional[bool] = None
 62) -> t.Callable[[t.List], E]:
 63    def _format_time(args: t.List) -> E:
 64        assert len(args) == 2
 65
 66        return exp_class(
 67            this=exp.cast(args[1], "datetime"),
 68            format=exp.Literal.string(
 69                format_time(
 70                    args[0].name.lower(),
 71                    {**TSQL.TIME_MAPPING, **FULL_FORMAT_TIME_MAPPING}
 72                    if full_format_mapping
 73                    else TSQL.TIME_MAPPING,
 74                )
 75            ),
 76        )
 77
 78    return _format_time
 79
 80
 81def _parse_format(args: t.List) -> exp.Expression:
 82    assert len(args) == 2
 83
 84    fmt = args[1]
 85    number_fmt = fmt.name in TRANSPILE_SAFE_NUMBER_FMT or not DATE_FMT_RE.search(fmt.name)
 86
 87    if number_fmt:
 88        return exp.NumberToStr(this=args[0], format=fmt)
 89
 90    return exp.TimeToStr(
 91        this=args[0],
 92        format=exp.Literal.string(
 93            format_time(fmt.name, TSQL.FORMAT_TIME_MAPPING)
 94            if len(fmt.name) == 1
 95            else format_time(fmt.name, TSQL.TIME_MAPPING)
 96        ),
 97    )
 98
 99
100def _parse_eomonth(args: t.List) -> exp.Expression:
101    date = seq_get(args, 0)
102    month_lag = seq_get(args, 1)
103    unit = DATE_DELTA_INTERVAL.get("month")
104
105    if month_lag is None:
106        return exp.LastDateOfMonth(this=date)
107
108    # Remove month lag argument in parser as its compared with the number of arguments of the resulting class
109    args.remove(month_lag)
110
111    return exp.LastDateOfMonth(this=exp.DateAdd(this=date, expression=month_lag, unit=unit))
112
113
114def _parse_hashbytes(args: t.List) -> exp.Expression:
115    kind, data = args
116    kind = kind.name.upper() if kind.is_string else ""
117
118    if kind == "MD5":
119        args.pop(0)
120        return exp.MD5(this=data)
121    if kind in ("SHA", "SHA1"):
122        args.pop(0)
123        return exp.SHA(this=data)
124    if kind == "SHA2_256":
125        return exp.SHA2(this=data, length=exp.Literal.number(256))
126    if kind == "SHA2_512":
127        return exp.SHA2(this=data, length=exp.Literal.number(512))
128
129    return exp.func("HASHBYTES", *args)
130
131
132def generate_date_delta_with_unit_sql(
133    self: generator.Generator, expression: exp.DateAdd | exp.DateDiff
134) -> str:
135    func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF"
136    return self.func(func, expression.text("unit"), expression.expression, expression.this)
137
138
139def _format_sql(self: generator.Generator, expression: exp.NumberToStr | exp.TimeToStr) -> str:
140    fmt = (
141        expression.args["format"]
142        if isinstance(expression, exp.NumberToStr)
143        else exp.Literal.string(
144            format_time(
145                expression.text("format"),
146                t.cast(t.Dict[str, str], TSQL.INVERSE_TIME_MAPPING),
147            )
148        )
149    )
150    return self.func("FORMAT", expression.this, fmt)
151
152
153def _string_agg_sql(self: generator.Generator, expression: exp.GroupConcat) -> str:
154    expression = expression.copy()
155
156    this = expression.this
157    distinct = expression.find(exp.Distinct)
158    if distinct:
159        # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression
160        self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.")
161        this = distinct.pop().expressions[0]
162
163    order = ""
164    if isinstance(expression.this, exp.Order):
165        if expression.this.this:
166            this = expression.this.this.pop()
167        order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})"  # Order has a leading space
168
169    separator = expression.args.get("separator") or exp.Literal.string(",")
170    return f"STRING_AGG({self.format_args(this, separator)}){order}"
171
172
173def _parse_date_delta(
174    exp_class: t.Type[E], unit_mapping: t.Optional[t.Dict[str, str]] = None
175) -> t.Callable[[t.List], E]:
176    def inner_func(args: t.List) -> E:
177        unit = seq_get(args, 0)
178        if unit and unit_mapping:
179            unit = exp.var(unit_mapping.get(unit.name.lower(), unit.name))
180
181        start_date = seq_get(args, 1)
182        if start_date and start_date.is_number:
183            # Numeric types are valid DATETIME values
184            if start_date.is_int:
185                adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this))
186                start_date = exp.Literal.string(adds.strftime("%F"))
187            else:
188                # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs.
189                # This is not a problem when generating T-SQL code, it is when transpiling to other dialects.
190                return exp_class(this=seq_get(args, 2), expression=start_date, unit=unit)
191
192        return exp_class(
193            this=exp.TimeStrToTime(this=seq_get(args, 2)),
194            expression=exp.TimeStrToTime(this=start_date),
195            unit=unit,
196        )
197
198    return inner_func
199
200
201class TSQL(Dialect):
202    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
203    NULL_ORDERING = "nulls_are_small"
204    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
205
206    TIME_MAPPING = {
207        "year": "%Y",
208        "qq": "%q",
209        "q": "%q",
210        "quarter": "%q",
211        "dayofyear": "%j",
212        "day": "%d",
213        "dy": "%d",
214        "y": "%Y",
215        "week": "%W",
216        "ww": "%W",
217        "wk": "%W",
218        "hour": "%h",
219        "hh": "%I",
220        "minute": "%M",
221        "mi": "%M",
222        "n": "%M",
223        "second": "%S",
224        "ss": "%S",
225        "s": "%-S",
226        "millisecond": "%f",
227        "ms": "%f",
228        "weekday": "%W",
229        "dw": "%W",
230        "month": "%m",
231        "mm": "%M",
232        "m": "%-M",
233        "Y": "%Y",
234        "YYYY": "%Y",
235        "YY": "%y",
236        "MMMM": "%B",
237        "MMM": "%b",
238        "MM": "%m",
239        "M": "%-m",
240        "dd": "%d",
241        "d": "%-d",
242        "HH": "%H",
243        "H": "%-H",
244        "h": "%-I",
245        "S": "%f",
246        "yyyy": "%Y",
247        "yy": "%y",
248    }
249
250    CONVERT_FORMAT_MAPPING = {
251        "0": "%b %d %Y %-I:%M%p",
252        "1": "%m/%d/%y",
253        "2": "%y.%m.%d",
254        "3": "%d/%m/%y",
255        "4": "%d.%m.%y",
256        "5": "%d-%m-%y",
257        "6": "%d %b %y",
258        "7": "%b %d, %y",
259        "8": "%H:%M:%S",
260        "9": "%b %d %Y %-I:%M:%S:%f%p",
261        "10": "mm-dd-yy",
262        "11": "yy/mm/dd",
263        "12": "yymmdd",
264        "13": "%d %b %Y %H:%M:ss:%f",
265        "14": "%H:%M:%S:%f",
266        "20": "%Y-%m-%d %H:%M:%S",
267        "21": "%Y-%m-%d %H:%M:%S.%f",
268        "22": "%m/%d/%y %-I:%M:%S %p",
269        "23": "%Y-%m-%d",
270        "24": "%H:%M:%S",
271        "25": "%Y-%m-%d %H:%M:%S.%f",
272        "100": "%b %d %Y %-I:%M%p",
273        "101": "%m/%d/%Y",
274        "102": "%Y.%m.%d",
275        "103": "%d/%m/%Y",
276        "104": "%d.%m.%Y",
277        "105": "%d-%m-%Y",
278        "106": "%d %b %Y",
279        "107": "%b %d, %Y",
280        "108": "%H:%M:%S",
281        "109": "%b %d %Y %-I:%M:%S:%f%p",
282        "110": "%m-%d-%Y",
283        "111": "%Y/%m/%d",
284        "112": "%Y%m%d",
285        "113": "%d %b %Y %H:%M:%S:%f",
286        "114": "%H:%M:%S:%f",
287        "120": "%Y-%m-%d %H:%M:%S",
288        "121": "%Y-%m-%d %H:%M:%S.%f",
289    }
290
291    FORMAT_TIME_MAPPING = {
292        "y": "%B %Y",
293        "d": "%m/%d/%Y",
294        "H": "%-H",
295        "h": "%-I",
296        "s": "%Y-%m-%d %H:%M:%S",
297        "D": "%A,%B,%Y",
298        "f": "%A,%B,%Y %-I:%M %p",
299        "F": "%A,%B,%Y %-I:%M:%S %p",
300        "g": "%m/%d/%Y %-I:%M %p",
301        "G": "%m/%d/%Y %-I:%M:%S %p",
302        "M": "%B %-d",
303        "m": "%B %-d",
304        "O": "%Y-%m-%dT%H:%M:%S",
305        "u": "%Y-%M-%D %H:%M:%S%z",
306        "U": "%A, %B %D, %Y %H:%M:%S%z",
307        "T": "%-I:%M:%S %p",
308        "t": "%-I:%M",
309        "Y": "%a %Y",
310    }
311
312    class Tokenizer(tokens.Tokenizer):
313        IDENTIFIERS = ['"', ("[", "]")]
314        QUOTES = ["'", '"']
315        HEX_STRINGS = [("0x", ""), ("0X", "")]
316
317        KEYWORDS = {
318            **tokens.Tokenizer.KEYWORDS,
319            "DATETIME2": TokenType.DATETIME,
320            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
321            "DECLARE": TokenType.COMMAND,
322            "IMAGE": TokenType.IMAGE,
323            "MONEY": TokenType.MONEY,
324            "NTEXT": TokenType.TEXT,
325            "NVARCHAR(MAX)": TokenType.TEXT,
326            "PRINT": TokenType.COMMAND,
327            "PROC": TokenType.PROCEDURE,
328            "REAL": TokenType.FLOAT,
329            "ROWVERSION": TokenType.ROWVERSION,
330            "SMALLDATETIME": TokenType.DATETIME,
331            "SMALLMONEY": TokenType.SMALLMONEY,
332            "SQL_VARIANT": TokenType.VARIANT,
333            "TOP": TokenType.TOP,
334            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
335            "VARCHAR(MAX)": TokenType.TEXT,
336            "XML": TokenType.XML,
337            "OUTPUT": TokenType.RETURNING,
338            "SYSTEM_USER": TokenType.CURRENT_USER,
339        }
340
341    class Parser(parser.Parser):
342        FUNCTIONS = {
343            **parser.Parser.FUNCTIONS,
344            "CHARINDEX": lambda args: exp.StrPosition(
345                this=seq_get(args, 1),
346                substr=seq_get(args, 0),
347                position=seq_get(args, 2),
348            ),
349            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
350            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
351            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
352            "DATEPART": _format_time_lambda(exp.TimeToStr),
353            "EOMONTH": _parse_eomonth,
354            "FORMAT": _parse_format,
355            "GETDATE": exp.CurrentTimestamp.from_arg_list,
356            "HASHBYTES": _parse_hashbytes,
357            "IIF": exp.If.from_arg_list,
358            "ISNULL": exp.Coalesce.from_arg_list,
359            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
360            "LEN": exp.Length.from_arg_list,
361            "REPLICATE": exp.Repeat.from_arg_list,
362            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
363            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
364            "SUSER_NAME": exp.CurrentUser.from_arg_list,
365            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
366            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
367        }
368
369        JOIN_HINTS = {
370            "LOOP",
371            "HASH",
372            "MERGE",
373            "REMOTE",
374        }
375
376        VAR_LENGTH_DATATYPES = {
377            DataType.Type.NVARCHAR,
378            DataType.Type.VARCHAR,
379            DataType.Type.CHAR,
380            DataType.Type.NCHAR,
381        }
382
383        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
384            TokenType.TABLE,
385            *parser.Parser.TYPE_TOKENS,
386        }
387
388        STATEMENT_PARSERS = {
389            **parser.Parser.STATEMENT_PARSERS,
390            TokenType.END: lambda self: self._parse_command(),
391        }
392
393        LOG_BASE_FIRST = False
394        LOG_DEFAULTS_TO_LN = True
395
396        CONCAT_NULL_OUTPUTS_STRING = True
397
398        def _parse_projections(self) -> t.List[t.Optional[exp.Expression]]:
399            """
400            T-SQL supports the syntax alias = expression in the SELECT's projection list,
401            so we transform all parsed Selects to convert their EQ projections into Aliases.
402
403            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
404            """
405            return [
406                exp.alias_(projection.expression, projection.this.this, copy=False)
407                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
408                else projection
409                for projection in super()._parse_projections()
410            ]
411
412        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
413            """Applies to SQL Server and Azure SQL Database
414            COMMIT [ { TRAN | TRANSACTION }
415                [ transaction_name | @tran_name_variable ] ]
416                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
417
418            ROLLBACK { TRAN | TRANSACTION }
419                [ transaction_name | @tran_name_variable
420                | savepoint_name | @savepoint_variable ]
421            """
422            rollback = self._prev.token_type == TokenType.ROLLBACK
423
424            self._match_texts({"TRAN", "TRANSACTION"})
425            this = self._parse_id_var()
426
427            if rollback:
428                return self.expression(exp.Rollback, this=this)
429
430            durability = None
431            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
432                self._match_text_seq("DELAYED_DURABILITY")
433                self._match(TokenType.EQ)
434
435                if self._match_text_seq("OFF"):
436                    durability = False
437                else:
438                    self._match(TokenType.ON)
439                    durability = True
440
441                self._match_r_paren()
442
443            return self.expression(exp.Commit, this=this, durability=durability)
444
445        def _parse_transaction(self) -> exp.Transaction | exp.Command:
446            """Applies to SQL Server and Azure SQL Database
447            BEGIN { TRAN | TRANSACTION }
448            [ { transaction_name | @tran_name_variable }
449            [ WITH MARK [ 'description' ] ]
450            ]
451            """
452            if self._match_texts(("TRAN", "TRANSACTION")):
453                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
454                if self._match_text_seq("WITH", "MARK"):
455                    transaction.set("mark", self._parse_string())
456
457                return transaction
458
459            return self._parse_as_command(self._prev)
460
461        def _parse_system_time(self) -> t.Optional[exp.Expression]:
462            if not self._match_text_seq("FOR", "SYSTEM_TIME"):
463                return None
464
465            if self._match_text_seq("AS", "OF"):
466                system_time = self.expression(
467                    exp.SystemTime, this=self._parse_bitwise(), kind="AS OF"
468                )
469            elif self._match_set((TokenType.FROM, TokenType.BETWEEN)):
470                kind = self._prev.text
471                this = self._parse_bitwise()
472                self._match_texts(("TO", "AND"))
473                expression = self._parse_bitwise()
474                system_time = self.expression(
475                    exp.SystemTime, this=this, expression=expression, kind=kind
476                )
477            elif self._match_text_seq("CONTAINED", "IN"):
478                args = self._parse_wrapped_csv(self._parse_bitwise)
479                system_time = self.expression(
480                    exp.SystemTime,
481                    this=seq_get(args, 0),
482                    expression=seq_get(args, 1),
483                    kind="CONTAINED IN",
484                )
485            elif self._match(TokenType.ALL):
486                system_time = self.expression(exp.SystemTime, kind="ALL")
487            else:
488                system_time = None
489                self.raise_error("Unable to parse FOR SYSTEM_TIME clause")
490
491            return system_time
492
493        def _parse_table_parts(self, schema: bool = False) -> exp.Table:
494            table = super()._parse_table_parts(schema=schema)
495            table.set("system_time", self._parse_system_time())
496            return table
497
498        def _parse_returns(self) -> exp.ReturnsProperty:
499            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
500            returns = super()._parse_returns()
501            returns.set("table", table)
502            return returns
503
504        def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]:
505            to = self._parse_types()
506            self._match(TokenType.COMMA)
507            this = self._parse_conjunction()
508
509            if not to or not this:
510                return None
511
512            # Retrieve length of datatype and override to default if not specified
513            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
514                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
515
516            # Check whether a conversion with format is applicable
517            if self._match(TokenType.COMMA):
518                format_val = self._parse_number()
519                format_val_name = format_val.name if format_val else ""
520
521                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
522                    raise ValueError(
523                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
524                    )
525
526                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
527
528                # Check whether the convert entails a string to date format
529                if to.this == DataType.Type.DATE:
530                    return self.expression(exp.StrToDate, this=this, format=format_norm)
531                # Check whether the convert entails a string to datetime format
532                elif to.this == DataType.Type.DATETIME:
533                    return self.expression(exp.StrToTime, this=this, format=format_norm)
534                # Check whether the convert entails a date to string format
535                elif to.this in self.VAR_LENGTH_DATATYPES:
536                    return self.expression(
537                        exp.Cast if strict else exp.TryCast,
538                        to=to,
539                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
540                    )
541                elif to.this == DataType.Type.TEXT:
542                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
543
544            # Entails a simple cast without any format requirement
545            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to)
546
547        def _parse_user_defined_function(
548            self, kind: t.Optional[TokenType] = None
549        ) -> t.Optional[exp.Expression]:
550            this = super()._parse_user_defined_function(kind=kind)
551
552            if (
553                kind == TokenType.FUNCTION
554                or isinstance(this, exp.UserDefinedFunction)
555                or self._match(TokenType.ALIAS, advance=False)
556            ):
557                return this
558
559            expressions = self._parse_csv(self._parse_function_parameter)
560            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
561
562        def _parse_id_var(
563            self,
564            any_token: bool = True,
565            tokens: t.Optional[t.Collection[TokenType]] = None,
566        ) -> t.Optional[exp.Expression]:
567            is_temporary = self._match(TokenType.HASH)
568            is_global = is_temporary and self._match(TokenType.HASH)
569
570            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
571            if this:
572                if is_global:
573                    this.set("global", True)
574                elif is_temporary:
575                    this.set("temporary", True)
576
577            return this
578
579        def _parse_create(self) -> exp.Create | exp.Command:
580            create = super()._parse_create()
581
582            if isinstance(create, exp.Create):
583                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
584                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
585                    if not create.args.get("properties"):
586                        create.set("properties", exp.Properties(expressions=[]))
587
588                    create.args["properties"].append("expressions", exp.TemporaryProperty())
589
590            return create
591
592    class Generator(generator.Generator):
593        LOCKING_READS_SUPPORTED = True
594        LIMIT_IS_TOP = True
595        QUERY_HINTS = False
596        RETURNING_END = False
597
598        TYPE_MAPPING = {
599            **generator.Generator.TYPE_MAPPING,
600            exp.DataType.Type.DECIMAL: "NUMERIC",
601            exp.DataType.Type.DATETIME: "DATETIME2",
602            exp.DataType.Type.INT: "INTEGER",
603            exp.DataType.Type.TIMESTAMP: "DATETIME2",
604            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
605            exp.DataType.Type.VARIANT: "SQL_VARIANT",
606        }
607
608        TRANSFORMS = {
609            **generator.Generator.TRANSFORMS,
610            exp.DateAdd: generate_date_delta_with_unit_sql,
611            exp.DateDiff: generate_date_delta_with_unit_sql,
612            exp.CurrentDate: rename_func("GETDATE"),
613            exp.CurrentTimestamp: rename_func("GETDATE"),
614            exp.Extract: rename_func("DATEPART"),
615            exp.GroupConcat: _string_agg_sql,
616            exp.If: rename_func("IIF"),
617            exp.Max: max_or_greatest,
618            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
619            exp.Min: min_or_least,
620            exp.NumberToStr: _format_sql,
621            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
622            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
623            exp.SHA2: lambda self, e: self.func(
624                "HASHBYTES",
625                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
626                e.this,
627            ),
628            exp.TemporaryProperty: lambda self, e: "",
629            exp.TimeStrToTime: timestrtotime_sql,
630            exp.TimeToStr: _format_sql,
631        }
632
633        TRANSFORMS.pop(exp.ReturnsProperty)
634
635        PROPERTIES_LOCATION = {
636            **generator.Generator.PROPERTIES_LOCATION,
637            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
638        }
639
640        LIMIT_FETCH = "FETCH"
641
642        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
643            sql = self.sql(expression, "this")
644            properties = expression.args.get("properties")
645
646            if sql[:1] != "#" and any(
647                isinstance(prop, exp.TemporaryProperty)
648                for prop in (properties.expressions if properties else [])
649            ):
650                sql = f"#{sql}"
651
652            return sql
653
654        def offset_sql(self, expression: exp.Offset) -> str:
655            return f"{super().offset_sql(expression)} ROWS"
656
657        def systemtime_sql(self, expression: exp.SystemTime) -> str:
658            kind = expression.args["kind"]
659            if kind == "ALL":
660                return "FOR SYSTEM_TIME ALL"
661
662            start = self.sql(expression, "this")
663            if kind == "AS OF":
664                return f"FOR SYSTEM_TIME AS OF {start}"
665
666            end = self.sql(expression, "expression")
667            if kind == "FROM":
668                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
669            if kind == "BETWEEN":
670                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
671
672            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
673
674        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
675            table = expression.args.get("table")
676            table = f"{table} " if table else ""
677            return f"RETURNS {table}{self.sql(expression, 'this')}"
678
679        def returning_sql(self, expression: exp.Returning) -> str:
680            into = self.sql(expression, "into")
681            into = self.seg(f"INTO {into}") if into else ""
682            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
683
684        def transaction_sql(self, expression: exp.Transaction) -> str:
685            this = self.sql(expression, "this")
686            this = f" {this}" if this else ""
687            mark = self.sql(expression, "mark")
688            mark = f" WITH MARK {mark}" if mark else ""
689            return f"BEGIN TRANSACTION{this}{mark}"
690
691        def commit_sql(self, expression: exp.Commit) -> str:
692            this = self.sql(expression, "this")
693            this = f" {this}" if this else ""
694            durability = expression.args.get("durability")
695            durability = (
696                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
697                if durability is not None
698                else ""
699            )
700            return f"COMMIT TRANSACTION{this}{durability}"
701
702        def rollback_sql(self, expression: exp.Rollback) -> str:
703            this = self.sql(expression, "this")
704            this = f" {this}" if this else ""
705            return f"ROLLBACK TRANSACTION{this}"
706
707        def identifier_sql(self, expression: exp.Identifier) -> str:
708            identifier = super().identifier_sql(expression)
709
710            if expression.args.get("global"):
711                identifier = f"##{identifier}"
712            elif expression.args.get("temporary"):
713                identifier = f"#{identifier}"
714
715            return identifier
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)
def generate_date_delta_with_unit_sql( self: sqlglot.generator.Generator, expression: sqlglot.expressions.DateAdd | sqlglot.expressions.DateDiff) -> str:
133def generate_date_delta_with_unit_sql(
134    self: generator.Generator, expression: exp.DateAdd | exp.DateDiff
135) -> str:
136    func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF"
137    return self.func(func, expression.text("unit"), expression.expression, expression.this)
class TSQL(sqlglot.dialects.dialect.Dialect):
202class TSQL(Dialect):
203    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
204    NULL_ORDERING = "nulls_are_small"
205    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
206
207    TIME_MAPPING = {
208        "year": "%Y",
209        "qq": "%q",
210        "q": "%q",
211        "quarter": "%q",
212        "dayofyear": "%j",
213        "day": "%d",
214        "dy": "%d",
215        "y": "%Y",
216        "week": "%W",
217        "ww": "%W",
218        "wk": "%W",
219        "hour": "%h",
220        "hh": "%I",
221        "minute": "%M",
222        "mi": "%M",
223        "n": "%M",
224        "second": "%S",
225        "ss": "%S",
226        "s": "%-S",
227        "millisecond": "%f",
228        "ms": "%f",
229        "weekday": "%W",
230        "dw": "%W",
231        "month": "%m",
232        "mm": "%M",
233        "m": "%-M",
234        "Y": "%Y",
235        "YYYY": "%Y",
236        "YY": "%y",
237        "MMMM": "%B",
238        "MMM": "%b",
239        "MM": "%m",
240        "M": "%-m",
241        "dd": "%d",
242        "d": "%-d",
243        "HH": "%H",
244        "H": "%-H",
245        "h": "%-I",
246        "S": "%f",
247        "yyyy": "%Y",
248        "yy": "%y",
249    }
250
251    CONVERT_FORMAT_MAPPING = {
252        "0": "%b %d %Y %-I:%M%p",
253        "1": "%m/%d/%y",
254        "2": "%y.%m.%d",
255        "3": "%d/%m/%y",
256        "4": "%d.%m.%y",
257        "5": "%d-%m-%y",
258        "6": "%d %b %y",
259        "7": "%b %d, %y",
260        "8": "%H:%M:%S",
261        "9": "%b %d %Y %-I:%M:%S:%f%p",
262        "10": "mm-dd-yy",
263        "11": "yy/mm/dd",
264        "12": "yymmdd",
265        "13": "%d %b %Y %H:%M:ss:%f",
266        "14": "%H:%M:%S:%f",
267        "20": "%Y-%m-%d %H:%M:%S",
268        "21": "%Y-%m-%d %H:%M:%S.%f",
269        "22": "%m/%d/%y %-I:%M:%S %p",
270        "23": "%Y-%m-%d",
271        "24": "%H:%M:%S",
272        "25": "%Y-%m-%d %H:%M:%S.%f",
273        "100": "%b %d %Y %-I:%M%p",
274        "101": "%m/%d/%Y",
275        "102": "%Y.%m.%d",
276        "103": "%d/%m/%Y",
277        "104": "%d.%m.%Y",
278        "105": "%d-%m-%Y",
279        "106": "%d %b %Y",
280        "107": "%b %d, %Y",
281        "108": "%H:%M:%S",
282        "109": "%b %d %Y %-I:%M:%S:%f%p",
283        "110": "%m-%d-%Y",
284        "111": "%Y/%m/%d",
285        "112": "%Y%m%d",
286        "113": "%d %b %Y %H:%M:%S:%f",
287        "114": "%H:%M:%S:%f",
288        "120": "%Y-%m-%d %H:%M:%S",
289        "121": "%Y-%m-%d %H:%M:%S.%f",
290    }
291
292    FORMAT_TIME_MAPPING = {
293        "y": "%B %Y",
294        "d": "%m/%d/%Y",
295        "H": "%-H",
296        "h": "%-I",
297        "s": "%Y-%m-%d %H:%M:%S",
298        "D": "%A,%B,%Y",
299        "f": "%A,%B,%Y %-I:%M %p",
300        "F": "%A,%B,%Y %-I:%M:%S %p",
301        "g": "%m/%d/%Y %-I:%M %p",
302        "G": "%m/%d/%Y %-I:%M:%S %p",
303        "M": "%B %-d",
304        "m": "%B %-d",
305        "O": "%Y-%m-%dT%H:%M:%S",
306        "u": "%Y-%M-%D %H:%M:%S%z",
307        "U": "%A, %B %D, %Y %H:%M:%S%z",
308        "T": "%-I:%M:%S %p",
309        "t": "%-I:%M",
310        "Y": "%a %Y",
311    }
312
313    class Tokenizer(tokens.Tokenizer):
314        IDENTIFIERS = ['"', ("[", "]")]
315        QUOTES = ["'", '"']
316        HEX_STRINGS = [("0x", ""), ("0X", "")]
317
318        KEYWORDS = {
319            **tokens.Tokenizer.KEYWORDS,
320            "DATETIME2": TokenType.DATETIME,
321            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
322            "DECLARE": TokenType.COMMAND,
323            "IMAGE": TokenType.IMAGE,
324            "MONEY": TokenType.MONEY,
325            "NTEXT": TokenType.TEXT,
326            "NVARCHAR(MAX)": TokenType.TEXT,
327            "PRINT": TokenType.COMMAND,
328            "PROC": TokenType.PROCEDURE,
329            "REAL": TokenType.FLOAT,
330            "ROWVERSION": TokenType.ROWVERSION,
331            "SMALLDATETIME": TokenType.DATETIME,
332            "SMALLMONEY": TokenType.SMALLMONEY,
333            "SQL_VARIANT": TokenType.VARIANT,
334            "TOP": TokenType.TOP,
335            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
336            "VARCHAR(MAX)": TokenType.TEXT,
337            "XML": TokenType.XML,
338            "OUTPUT": TokenType.RETURNING,
339            "SYSTEM_USER": TokenType.CURRENT_USER,
340        }
341
342    class Parser(parser.Parser):
343        FUNCTIONS = {
344            **parser.Parser.FUNCTIONS,
345            "CHARINDEX": lambda args: exp.StrPosition(
346                this=seq_get(args, 1),
347                substr=seq_get(args, 0),
348                position=seq_get(args, 2),
349            ),
350            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
351            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
352            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
353            "DATEPART": _format_time_lambda(exp.TimeToStr),
354            "EOMONTH": _parse_eomonth,
355            "FORMAT": _parse_format,
356            "GETDATE": exp.CurrentTimestamp.from_arg_list,
357            "HASHBYTES": _parse_hashbytes,
358            "IIF": exp.If.from_arg_list,
359            "ISNULL": exp.Coalesce.from_arg_list,
360            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
361            "LEN": exp.Length.from_arg_list,
362            "REPLICATE": exp.Repeat.from_arg_list,
363            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
364            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
365            "SUSER_NAME": exp.CurrentUser.from_arg_list,
366            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
367            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
368        }
369
370        JOIN_HINTS = {
371            "LOOP",
372            "HASH",
373            "MERGE",
374            "REMOTE",
375        }
376
377        VAR_LENGTH_DATATYPES = {
378            DataType.Type.NVARCHAR,
379            DataType.Type.VARCHAR,
380            DataType.Type.CHAR,
381            DataType.Type.NCHAR,
382        }
383
384        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
385            TokenType.TABLE,
386            *parser.Parser.TYPE_TOKENS,
387        }
388
389        STATEMENT_PARSERS = {
390            **parser.Parser.STATEMENT_PARSERS,
391            TokenType.END: lambda self: self._parse_command(),
392        }
393
394        LOG_BASE_FIRST = False
395        LOG_DEFAULTS_TO_LN = True
396
397        CONCAT_NULL_OUTPUTS_STRING = True
398
399        def _parse_projections(self) -> t.List[t.Optional[exp.Expression]]:
400            """
401            T-SQL supports the syntax alias = expression in the SELECT's projection list,
402            so we transform all parsed Selects to convert their EQ projections into Aliases.
403
404            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
405            """
406            return [
407                exp.alias_(projection.expression, projection.this.this, copy=False)
408                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
409                else projection
410                for projection in super()._parse_projections()
411            ]
412
413        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
414            """Applies to SQL Server and Azure SQL Database
415            COMMIT [ { TRAN | TRANSACTION }
416                [ transaction_name | @tran_name_variable ] ]
417                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
418
419            ROLLBACK { TRAN | TRANSACTION }
420                [ transaction_name | @tran_name_variable
421                | savepoint_name | @savepoint_variable ]
422            """
423            rollback = self._prev.token_type == TokenType.ROLLBACK
424
425            self._match_texts({"TRAN", "TRANSACTION"})
426            this = self._parse_id_var()
427
428            if rollback:
429                return self.expression(exp.Rollback, this=this)
430
431            durability = None
432            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
433                self._match_text_seq("DELAYED_DURABILITY")
434                self._match(TokenType.EQ)
435
436                if self._match_text_seq("OFF"):
437                    durability = False
438                else:
439                    self._match(TokenType.ON)
440                    durability = True
441
442                self._match_r_paren()
443
444            return self.expression(exp.Commit, this=this, durability=durability)
445
446        def _parse_transaction(self) -> exp.Transaction | exp.Command:
447            """Applies to SQL Server and Azure SQL Database
448            BEGIN { TRAN | TRANSACTION }
449            [ { transaction_name | @tran_name_variable }
450            [ WITH MARK [ 'description' ] ]
451            ]
452            """
453            if self._match_texts(("TRAN", "TRANSACTION")):
454                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
455                if self._match_text_seq("WITH", "MARK"):
456                    transaction.set("mark", self._parse_string())
457
458                return transaction
459
460            return self._parse_as_command(self._prev)
461
462        def _parse_system_time(self) -> t.Optional[exp.Expression]:
463            if not self._match_text_seq("FOR", "SYSTEM_TIME"):
464                return None
465
466            if self._match_text_seq("AS", "OF"):
467                system_time = self.expression(
468                    exp.SystemTime, this=self._parse_bitwise(), kind="AS OF"
469                )
470            elif self._match_set((TokenType.FROM, TokenType.BETWEEN)):
471                kind = self._prev.text
472                this = self._parse_bitwise()
473                self._match_texts(("TO", "AND"))
474                expression = self._parse_bitwise()
475                system_time = self.expression(
476                    exp.SystemTime, this=this, expression=expression, kind=kind
477                )
478            elif self._match_text_seq("CONTAINED", "IN"):
479                args = self._parse_wrapped_csv(self._parse_bitwise)
480                system_time = self.expression(
481                    exp.SystemTime,
482                    this=seq_get(args, 0),
483                    expression=seq_get(args, 1),
484                    kind="CONTAINED IN",
485                )
486            elif self._match(TokenType.ALL):
487                system_time = self.expression(exp.SystemTime, kind="ALL")
488            else:
489                system_time = None
490                self.raise_error("Unable to parse FOR SYSTEM_TIME clause")
491
492            return system_time
493
494        def _parse_table_parts(self, schema: bool = False) -> exp.Table:
495            table = super()._parse_table_parts(schema=schema)
496            table.set("system_time", self._parse_system_time())
497            return table
498
499        def _parse_returns(self) -> exp.ReturnsProperty:
500            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
501            returns = super()._parse_returns()
502            returns.set("table", table)
503            return returns
504
505        def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]:
506            to = self._parse_types()
507            self._match(TokenType.COMMA)
508            this = self._parse_conjunction()
509
510            if not to or not this:
511                return None
512
513            # Retrieve length of datatype and override to default if not specified
514            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
515                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
516
517            # Check whether a conversion with format is applicable
518            if self._match(TokenType.COMMA):
519                format_val = self._parse_number()
520                format_val_name = format_val.name if format_val else ""
521
522                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
523                    raise ValueError(
524                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
525                    )
526
527                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
528
529                # Check whether the convert entails a string to date format
530                if to.this == DataType.Type.DATE:
531                    return self.expression(exp.StrToDate, this=this, format=format_norm)
532                # Check whether the convert entails a string to datetime format
533                elif to.this == DataType.Type.DATETIME:
534                    return self.expression(exp.StrToTime, this=this, format=format_norm)
535                # Check whether the convert entails a date to string format
536                elif to.this in self.VAR_LENGTH_DATATYPES:
537                    return self.expression(
538                        exp.Cast if strict else exp.TryCast,
539                        to=to,
540                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
541                    )
542                elif to.this == DataType.Type.TEXT:
543                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
544
545            # Entails a simple cast without any format requirement
546            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to)
547
548        def _parse_user_defined_function(
549            self, kind: t.Optional[TokenType] = None
550        ) -> t.Optional[exp.Expression]:
551            this = super()._parse_user_defined_function(kind=kind)
552
553            if (
554                kind == TokenType.FUNCTION
555                or isinstance(this, exp.UserDefinedFunction)
556                or self._match(TokenType.ALIAS, advance=False)
557            ):
558                return this
559
560            expressions = self._parse_csv(self._parse_function_parameter)
561            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
562
563        def _parse_id_var(
564            self,
565            any_token: bool = True,
566            tokens: t.Optional[t.Collection[TokenType]] = None,
567        ) -> t.Optional[exp.Expression]:
568            is_temporary = self._match(TokenType.HASH)
569            is_global = is_temporary and self._match(TokenType.HASH)
570
571            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
572            if this:
573                if is_global:
574                    this.set("global", True)
575                elif is_temporary:
576                    this.set("temporary", True)
577
578            return this
579
580        def _parse_create(self) -> exp.Create | exp.Command:
581            create = super()._parse_create()
582
583            if isinstance(create, exp.Create):
584                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
585                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
586                    if not create.args.get("properties"):
587                        create.set("properties", exp.Properties(expressions=[]))
588
589                    create.args["properties"].append("expressions", exp.TemporaryProperty())
590
591            return create
592
593    class Generator(generator.Generator):
594        LOCKING_READS_SUPPORTED = True
595        LIMIT_IS_TOP = True
596        QUERY_HINTS = False
597        RETURNING_END = False
598
599        TYPE_MAPPING = {
600            **generator.Generator.TYPE_MAPPING,
601            exp.DataType.Type.DECIMAL: "NUMERIC",
602            exp.DataType.Type.DATETIME: "DATETIME2",
603            exp.DataType.Type.INT: "INTEGER",
604            exp.DataType.Type.TIMESTAMP: "DATETIME2",
605            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
606            exp.DataType.Type.VARIANT: "SQL_VARIANT",
607        }
608
609        TRANSFORMS = {
610            **generator.Generator.TRANSFORMS,
611            exp.DateAdd: generate_date_delta_with_unit_sql,
612            exp.DateDiff: generate_date_delta_with_unit_sql,
613            exp.CurrentDate: rename_func("GETDATE"),
614            exp.CurrentTimestamp: rename_func("GETDATE"),
615            exp.Extract: rename_func("DATEPART"),
616            exp.GroupConcat: _string_agg_sql,
617            exp.If: rename_func("IIF"),
618            exp.Max: max_or_greatest,
619            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
620            exp.Min: min_or_least,
621            exp.NumberToStr: _format_sql,
622            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
623            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
624            exp.SHA2: lambda self, e: self.func(
625                "HASHBYTES",
626                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
627                e.this,
628            ),
629            exp.TemporaryProperty: lambda self, e: "",
630            exp.TimeStrToTime: timestrtotime_sql,
631            exp.TimeToStr: _format_sql,
632        }
633
634        TRANSFORMS.pop(exp.ReturnsProperty)
635
636        PROPERTIES_LOCATION = {
637            **generator.Generator.PROPERTIES_LOCATION,
638            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
639        }
640
641        LIMIT_FETCH = "FETCH"
642
643        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
644            sql = self.sql(expression, "this")
645            properties = expression.args.get("properties")
646
647            if sql[:1] != "#" and any(
648                isinstance(prop, exp.TemporaryProperty)
649                for prop in (properties.expressions if properties else [])
650            ):
651                sql = f"#{sql}"
652
653            return sql
654
655        def offset_sql(self, expression: exp.Offset) -> str:
656            return f"{super().offset_sql(expression)} ROWS"
657
658        def systemtime_sql(self, expression: exp.SystemTime) -> str:
659            kind = expression.args["kind"]
660            if kind == "ALL":
661                return "FOR SYSTEM_TIME ALL"
662
663            start = self.sql(expression, "this")
664            if kind == "AS OF":
665                return f"FOR SYSTEM_TIME AS OF {start}"
666
667            end = self.sql(expression, "expression")
668            if kind == "FROM":
669                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
670            if kind == "BETWEEN":
671                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
672
673            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
674
675        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
676            table = expression.args.get("table")
677            table = f"{table} " if table else ""
678            return f"RETURNS {table}{self.sql(expression, 'this')}"
679
680        def returning_sql(self, expression: exp.Returning) -> str:
681            into = self.sql(expression, "into")
682            into = self.seg(f"INTO {into}") if into else ""
683            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
684
685        def transaction_sql(self, expression: exp.Transaction) -> str:
686            this = self.sql(expression, "this")
687            this = f" {this}" if this else ""
688            mark = self.sql(expression, "mark")
689            mark = f" WITH MARK {mark}" if mark else ""
690            return f"BEGIN TRANSACTION{this}{mark}"
691
692        def commit_sql(self, expression: exp.Commit) -> str:
693            this = self.sql(expression, "this")
694            this = f" {this}" if this else ""
695            durability = expression.args.get("durability")
696            durability = (
697                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
698                if durability is not None
699                else ""
700            )
701            return f"COMMIT TRANSACTION{this}{durability}"
702
703        def rollback_sql(self, expression: exp.Rollback) -> str:
704            this = self.sql(expression, "this")
705            this = f" {this}" if this else ""
706            return f"ROLLBACK TRANSACTION{this}"
707
708        def identifier_sql(self, expression: exp.Identifier) -> str:
709            identifier = super().identifier_sql(expression)
710
711            if expression.args.get("global"):
712                identifier = f"##{identifier}"
713            elif expression.args.get("temporary"):
714                identifier = f"#{identifier}"
715
716            return identifier
RESOLVES_IDENTIFIERS_AS_UPPERCASE: Optional[bool] = None
NULL_ORDERING = 'nulls_are_small'
TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
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 'sqlglot.dialects.tsql.TSQL.Tokenizer'>
parser_class = <class 'sqlglot.dialects.tsql.TSQL.Parser'>
generator_class = <class 'sqlglot.dialects.tsql.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}}}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
BIT_START = None
BIT_END = None
HEX_START = '0x'
HEX_END = ''
BYTE_START = None
BYTE_END = None
class TSQL.Tokenizer(sqlglot.tokens.Tokenizer):
313    class Tokenizer(tokens.Tokenizer):
314        IDENTIFIERS = ['"', ("[", "]")]
315        QUOTES = ["'", '"']
316        HEX_STRINGS = [("0x", ""), ("0X", "")]
317
318        KEYWORDS = {
319            **tokens.Tokenizer.KEYWORDS,
320            "DATETIME2": TokenType.DATETIME,
321            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
322            "DECLARE": TokenType.COMMAND,
323            "IMAGE": TokenType.IMAGE,
324            "MONEY": TokenType.MONEY,
325            "NTEXT": TokenType.TEXT,
326            "NVARCHAR(MAX)": TokenType.TEXT,
327            "PRINT": TokenType.COMMAND,
328            "PROC": TokenType.PROCEDURE,
329            "REAL": TokenType.FLOAT,
330            "ROWVERSION": TokenType.ROWVERSION,
331            "SMALLDATETIME": TokenType.DATETIME,
332            "SMALLMONEY": TokenType.SMALLMONEY,
333            "SQL_VARIANT": TokenType.VARIANT,
334            "TOP": TokenType.TOP,
335            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
336            "VARCHAR(MAX)": TokenType.TEXT,
337            "XML": TokenType.XML,
338            "OUTPUT": TokenType.RETURNING,
339            "SYSTEM_USER": TokenType.CURRENT_USER,
340        }
IDENTIFIERS = ['"', ('[', ']')]
QUOTES = ["'", '"']
HEX_STRINGS = [('0x', ''), ('0X', '')]
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'>, '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'>, 'IF': <TokenType.IF: 'IF'>, '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'>, 'NEXT VALUE FOR': <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>, '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'>, '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'>, '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'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, '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'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, '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'>, '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'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>}
class TSQL.Parser(sqlglot.parser.Parser):
342    class Parser(parser.Parser):
343        FUNCTIONS = {
344            **parser.Parser.FUNCTIONS,
345            "CHARINDEX": lambda args: exp.StrPosition(
346                this=seq_get(args, 1),
347                substr=seq_get(args, 0),
348                position=seq_get(args, 2),
349            ),
350            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
351            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
352            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
353            "DATEPART": _format_time_lambda(exp.TimeToStr),
354            "EOMONTH": _parse_eomonth,
355            "FORMAT": _parse_format,
356            "GETDATE": exp.CurrentTimestamp.from_arg_list,
357            "HASHBYTES": _parse_hashbytes,
358            "IIF": exp.If.from_arg_list,
359            "ISNULL": exp.Coalesce.from_arg_list,
360            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
361            "LEN": exp.Length.from_arg_list,
362            "REPLICATE": exp.Repeat.from_arg_list,
363            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
364            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
365            "SUSER_NAME": exp.CurrentUser.from_arg_list,
366            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
367            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
368        }
369
370        JOIN_HINTS = {
371            "LOOP",
372            "HASH",
373            "MERGE",
374            "REMOTE",
375        }
376
377        VAR_LENGTH_DATATYPES = {
378            DataType.Type.NVARCHAR,
379            DataType.Type.VARCHAR,
380            DataType.Type.CHAR,
381            DataType.Type.NCHAR,
382        }
383
384        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
385            TokenType.TABLE,
386            *parser.Parser.TYPE_TOKENS,
387        }
388
389        STATEMENT_PARSERS = {
390            **parser.Parser.STATEMENT_PARSERS,
391            TokenType.END: lambda self: self._parse_command(),
392        }
393
394        LOG_BASE_FIRST = False
395        LOG_DEFAULTS_TO_LN = True
396
397        CONCAT_NULL_OUTPUTS_STRING = True
398
399        def _parse_projections(self) -> t.List[t.Optional[exp.Expression]]:
400            """
401            T-SQL supports the syntax alias = expression in the SELECT's projection list,
402            so we transform all parsed Selects to convert their EQ projections into Aliases.
403
404            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
405            """
406            return [
407                exp.alias_(projection.expression, projection.this.this, copy=False)
408                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
409                else projection
410                for projection in super()._parse_projections()
411            ]
412
413        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
414            """Applies to SQL Server and Azure SQL Database
415            COMMIT [ { TRAN | TRANSACTION }
416                [ transaction_name | @tran_name_variable ] ]
417                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
418
419            ROLLBACK { TRAN | TRANSACTION }
420                [ transaction_name | @tran_name_variable
421                | savepoint_name | @savepoint_variable ]
422            """
423            rollback = self._prev.token_type == TokenType.ROLLBACK
424
425            self._match_texts({"TRAN", "TRANSACTION"})
426            this = self._parse_id_var()
427
428            if rollback:
429                return self.expression(exp.Rollback, this=this)
430
431            durability = None
432            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
433                self._match_text_seq("DELAYED_DURABILITY")
434                self._match(TokenType.EQ)
435
436                if self._match_text_seq("OFF"):
437                    durability = False
438                else:
439                    self._match(TokenType.ON)
440                    durability = True
441
442                self._match_r_paren()
443
444            return self.expression(exp.Commit, this=this, durability=durability)
445
446        def _parse_transaction(self) -> exp.Transaction | exp.Command:
447            """Applies to SQL Server and Azure SQL Database
448            BEGIN { TRAN | TRANSACTION }
449            [ { transaction_name | @tran_name_variable }
450            [ WITH MARK [ 'description' ] ]
451            ]
452            """
453            if self._match_texts(("TRAN", "TRANSACTION")):
454                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
455                if self._match_text_seq("WITH", "MARK"):
456                    transaction.set("mark", self._parse_string())
457
458                return transaction
459
460            return self._parse_as_command(self._prev)
461
462        def _parse_system_time(self) -> t.Optional[exp.Expression]:
463            if not self._match_text_seq("FOR", "SYSTEM_TIME"):
464                return None
465
466            if self._match_text_seq("AS", "OF"):
467                system_time = self.expression(
468                    exp.SystemTime, this=self._parse_bitwise(), kind="AS OF"
469                )
470            elif self._match_set((TokenType.FROM, TokenType.BETWEEN)):
471                kind = self._prev.text
472                this = self._parse_bitwise()
473                self._match_texts(("TO", "AND"))
474                expression = self._parse_bitwise()
475                system_time = self.expression(
476                    exp.SystemTime, this=this, expression=expression, kind=kind
477                )
478            elif self._match_text_seq("CONTAINED", "IN"):
479                args = self._parse_wrapped_csv(self._parse_bitwise)
480                system_time = self.expression(
481                    exp.SystemTime,
482                    this=seq_get(args, 0),
483                    expression=seq_get(args, 1),
484                    kind="CONTAINED IN",
485                )
486            elif self._match(TokenType.ALL):
487                system_time = self.expression(exp.SystemTime, kind="ALL")
488            else:
489                system_time = None
490                self.raise_error("Unable to parse FOR SYSTEM_TIME clause")
491
492            return system_time
493
494        def _parse_table_parts(self, schema: bool = False) -> exp.Table:
495            table = super()._parse_table_parts(schema=schema)
496            table.set("system_time", self._parse_system_time())
497            return table
498
499        def _parse_returns(self) -> exp.ReturnsProperty:
500            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
501            returns = super()._parse_returns()
502            returns.set("table", table)
503            return returns
504
505        def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]:
506            to = self._parse_types()
507            self._match(TokenType.COMMA)
508            this = self._parse_conjunction()
509
510            if not to or not this:
511                return None
512
513            # Retrieve length of datatype and override to default if not specified
514            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
515                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
516
517            # Check whether a conversion with format is applicable
518            if self._match(TokenType.COMMA):
519                format_val = self._parse_number()
520                format_val_name = format_val.name if format_val else ""
521
522                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
523                    raise ValueError(
524                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
525                    )
526
527                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
528
529                # Check whether the convert entails a string to date format
530                if to.this == DataType.Type.DATE:
531                    return self.expression(exp.StrToDate, this=this, format=format_norm)
532                # Check whether the convert entails a string to datetime format
533                elif to.this == DataType.Type.DATETIME:
534                    return self.expression(exp.StrToTime, this=this, format=format_norm)
535                # Check whether the convert entails a date to string format
536                elif to.this in self.VAR_LENGTH_DATATYPES:
537                    return self.expression(
538                        exp.Cast if strict else exp.TryCast,
539                        to=to,
540                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
541                    )
542                elif to.this == DataType.Type.TEXT:
543                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
544
545            # Entails a simple cast without any format requirement
546            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to)
547
548        def _parse_user_defined_function(
549            self, kind: t.Optional[TokenType] = None
550        ) -> t.Optional[exp.Expression]:
551            this = super()._parse_user_defined_function(kind=kind)
552
553            if (
554                kind == TokenType.FUNCTION
555                or isinstance(this, exp.UserDefinedFunction)
556                or self._match(TokenType.ALIAS, advance=False)
557            ):
558                return this
559
560            expressions = self._parse_csv(self._parse_function_parameter)
561            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
562
563        def _parse_id_var(
564            self,
565            any_token: bool = True,
566            tokens: t.Optional[t.Collection[TokenType]] = None,
567        ) -> t.Optional[exp.Expression]:
568            is_temporary = self._match(TokenType.HASH)
569            is_global = is_temporary and self._match(TokenType.HASH)
570
571            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
572            if this:
573                if is_global:
574                    this.set("global", True)
575                elif is_temporary:
576                    this.set("temporary", True)
577
578            return this
579
580        def _parse_create(self) -> exp.Create | exp.Command:
581            create = super()._parse_create()
582
583            if isinstance(create, exp.Create):
584                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
585                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
586                    if not create.args.get("properties"):
587                        create.set("properties", exp.Properties(expressions=[]))
588
589                    create.args["properties"].append("expressions", exp.TemporaryProperty())
590
591            return create

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_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'>>, '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'>>, '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'>>, '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_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'>>, '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'>>}
JOIN_HINTS = {'HASH', 'MERGE', 'REMOTE', 'LOOP'}
VAR_LENGTH_DATATYPES = {<Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.VIEW: 'VIEW'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.CACHE: 'CACHE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ALL: 'ALL'>, <TokenType.APPLY: 'APPLY'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.ROW: 'ROW'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.END: 'END'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.ROWS: 'ROWS'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.LEFT: 'LEFT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FIRST: 'FIRST'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.TOP: 'TOP'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.SET: 'SET'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.ANTI: 'ANTI'>, <TokenType.SOME: 'SOME'>, <TokenType.IF: 'IF'>, <TokenType.VAR: 'VAR'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.LOAD: 'LOAD'>, <TokenType.KEEP: 'KEEP'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.FULL: 'FULL'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.DELETE: 'DELETE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.FALSE: 'FALSE'>, <TokenType.CASE: 'CASE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.FILTER: 'FILTER'>, <TokenType.ANY: 'ANY'>, <TokenType.IS: 'IS'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.ASC: 'ASC'>, <TokenType.SEMI: 'SEMI'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.NEXT: 'NEXT'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.DIV: 'DIV'>, <TokenType.DESC: 'DESC'>}
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.FROM: 'FROM'>: <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>>}
LOG_BASE_FIRST = False
LOG_DEFAULTS_TO_LN = True
CONCAT_NULL_OUTPUTS_STRING = True
NULL_ORDERING: str = 'nulls_are_small'
SHOW_TRIE: Dict = {}
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}}
class TSQL.Generator(sqlglot.generator.Generator):
593    class Generator(generator.Generator):
594        LOCKING_READS_SUPPORTED = True
595        LIMIT_IS_TOP = True
596        QUERY_HINTS = False
597        RETURNING_END = False
598
599        TYPE_MAPPING = {
600            **generator.Generator.TYPE_MAPPING,
601            exp.DataType.Type.DECIMAL: "NUMERIC",
602            exp.DataType.Type.DATETIME: "DATETIME2",
603            exp.DataType.Type.INT: "INTEGER",
604            exp.DataType.Type.TIMESTAMP: "DATETIME2",
605            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
606            exp.DataType.Type.VARIANT: "SQL_VARIANT",
607        }
608
609        TRANSFORMS = {
610            **generator.Generator.TRANSFORMS,
611            exp.DateAdd: generate_date_delta_with_unit_sql,
612            exp.DateDiff: generate_date_delta_with_unit_sql,
613            exp.CurrentDate: rename_func("GETDATE"),
614            exp.CurrentTimestamp: rename_func("GETDATE"),
615            exp.Extract: rename_func("DATEPART"),
616            exp.GroupConcat: _string_agg_sql,
617            exp.If: rename_func("IIF"),
618            exp.Max: max_or_greatest,
619            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
620            exp.Min: min_or_least,
621            exp.NumberToStr: _format_sql,
622            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
623            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
624            exp.SHA2: lambda self, e: self.func(
625                "HASHBYTES",
626                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
627                e.this,
628            ),
629            exp.TemporaryProperty: lambda self, e: "",
630            exp.TimeStrToTime: timestrtotime_sql,
631            exp.TimeToStr: _format_sql,
632        }
633
634        TRANSFORMS.pop(exp.ReturnsProperty)
635
636        PROPERTIES_LOCATION = {
637            **generator.Generator.PROPERTIES_LOCATION,
638            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
639        }
640
641        LIMIT_FETCH = "FETCH"
642
643        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
644            sql = self.sql(expression, "this")
645            properties = expression.args.get("properties")
646
647            if sql[:1] != "#" and any(
648                isinstance(prop, exp.TemporaryProperty)
649                for prop in (properties.expressions if properties else [])
650            ):
651                sql = f"#{sql}"
652
653            return sql
654
655        def offset_sql(self, expression: exp.Offset) -> str:
656            return f"{super().offset_sql(expression)} ROWS"
657
658        def systemtime_sql(self, expression: exp.SystemTime) -> str:
659            kind = expression.args["kind"]
660            if kind == "ALL":
661                return "FOR SYSTEM_TIME ALL"
662
663            start = self.sql(expression, "this")
664            if kind == "AS OF":
665                return f"FOR SYSTEM_TIME AS OF {start}"
666
667            end = self.sql(expression, "expression")
668            if kind == "FROM":
669                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
670            if kind == "BETWEEN":
671                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
672
673            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
674
675        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
676            table = expression.args.get("table")
677            table = f"{table} " if table else ""
678            return f"RETURNS {table}{self.sql(expression, 'this')}"
679
680        def returning_sql(self, expression: exp.Returning) -> str:
681            into = self.sql(expression, "into")
682            into = self.seg(f"INTO {into}") if into else ""
683            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
684
685        def transaction_sql(self, expression: exp.Transaction) -> str:
686            this = self.sql(expression, "this")
687            this = f" {this}" if this else ""
688            mark = self.sql(expression, "mark")
689            mark = f" WITH MARK {mark}" if mark else ""
690            return f"BEGIN TRANSACTION{this}{mark}"
691
692        def commit_sql(self, expression: exp.Commit) -> str:
693            this = self.sql(expression, "this")
694            this = f" {this}" if this else ""
695            durability = expression.args.get("durability")
696            durability = (
697                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
698                if durability is not None
699                else ""
700            )
701            return f"COMMIT TRANSACTION{this}{durability}"
702
703        def rollback_sql(self, expression: exp.Rollback) -> str:
704            this = self.sql(expression, "this")
705            this = f" {this}" if this else ""
706            return f"ROLLBACK TRANSACTION{this}"
707
708        def identifier_sql(self, expression: exp.Identifier) -> str:
709            identifier = super().identifier_sql(expression)
710
711            if expression.args.get("global"):
712                identifier = f"##{identifier}"
713            elif expression.args.get("temporary"):
714                identifier = f"#{identifier}"
715
716            return identifier

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
LOCKING_READS_SUPPORTED = True
LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <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.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.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.OnCommitProperty'>: <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.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.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'>}
LIMIT_FETCH = 'FETCH'
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
643        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
644            sql = self.sql(expression, "this")
645            properties = expression.args.get("properties")
646
647            if sql[:1] != "#" and any(
648                isinstance(prop, exp.TemporaryProperty)
649                for prop in (properties.expressions if properties else [])
650            ):
651                sql = f"#{sql}"
652
653            return sql
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
655        def offset_sql(self, expression: exp.Offset) -> str:
656            return f"{super().offset_sql(expression)} ROWS"
def systemtime_sql(self, expression: sqlglot.expressions.SystemTime) -> str:
658        def systemtime_sql(self, expression: exp.SystemTime) -> str:
659            kind = expression.args["kind"]
660            if kind == "ALL":
661                return "FOR SYSTEM_TIME ALL"
662
663            start = self.sql(expression, "this")
664            if kind == "AS OF":
665                return f"FOR SYSTEM_TIME AS OF {start}"
666
667            end = self.sql(expression, "expression")
668            if kind == "FROM":
669                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
670            if kind == "BETWEEN":
671                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
672
673            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
def returnsproperty_sql(self, expression: sqlglot.expressions.ReturnsProperty) -> str:
675        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
676            table = expression.args.get("table")
677            table = f"{table} " if table else ""
678            return f"RETURNS {table}{self.sql(expression, 'this')}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
680        def returning_sql(self, expression: exp.Returning) -> str:
681            into = self.sql(expression, "into")
682            into = self.seg(f"INTO {into}") if into else ""
683            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
685        def transaction_sql(self, expression: exp.Transaction) -> str:
686            this = self.sql(expression, "this")
687            this = f" {this}" if this else ""
688            mark = self.sql(expression, "mark")
689            mark = f" WITH MARK {mark}" if mark else ""
690            return f"BEGIN TRANSACTION{this}{mark}"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
692        def commit_sql(self, expression: exp.Commit) -> str:
693            this = self.sql(expression, "this")
694            this = f" {this}" if this else ""
695            durability = expression.args.get("durability")
696            durability = (
697                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
698                if durability is not None
699                else ""
700            )
701            return f"COMMIT TRANSACTION{this}{durability}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
703        def rollback_sql(self, expression: exp.Rollback) -> str:
704            this = self.sql(expression, "this")
705            this = f" {this}" if this else ""
706            return f"ROLLBACK TRANSACTION{this}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
708        def identifier_sql(self, expression: exp.Identifier) -> str:
709            identifier = super().identifier_sql(expression)
710
711            if expression.args.get("global"):
712                identifier = f"##{identifier}"
713            elif expression.args.get("temporary"):
714                identifier = f"#{identifier}"
715
716            return identifier
SELECT_KINDS: Tuple[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}}}
NULL_ORDERING = 'nulls_are_small'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool:
253    @classmethod
254    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
255        """Checks if text can be identified given an identify option.
256
257        Args:
258            text: The text to check.
259            identify:
260                "always" or `True`: Always returns true.
261                "safe": True if the identifier is case-insensitive.
262
263        Returns:
264            Whether or not the given text can be identified.
265        """
266        if identify is True or identify == "always":
267            return True
268
269        if identify == "safe":
270            return not cls.case_sensitive(text)
271
272        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.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
STRING_ESCAPE = "'"
IDENTIFIER_ESCAPE = '"'
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
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
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
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
create_sql
clone_sql
describe_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
rawstring_sql
datatypesize_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
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
join_sql
lambda_sql
lateral_sql
limit_sql
setitem_sql
set_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_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
constraint_sql
nextvaluefor_sql
extract_sql
trim_sql
safeconcat_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonobject_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
is_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