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    NormalizationStrategy,
 11    any_value_to_max_sql,
 12    date_delta_sql,
 13    generatedasidentitycolumnconstraint_sql,
 14    max_or_greatest,
 15    min_or_least,
 16    parse_date_delta,
 17    path_to_jsonpath,
 18    rename_func,
 19    timestrtotime_sql,
 20    trim_sql,
 21)
 22from sqlglot.expressions import DataType
 23from sqlglot.helper import seq_get
 24from sqlglot.time import format_time
 25from sqlglot.tokens import TokenType
 26
 27if t.TYPE_CHECKING:
 28    from sqlglot._typing import E
 29
 30FULL_FORMAT_TIME_MAPPING = {
 31    "weekday": "%A",
 32    "dw": "%A",
 33    "w": "%A",
 34    "month": "%B",
 35    "mm": "%B",
 36    "m": "%B",
 37}
 38
 39DATE_DELTA_INTERVAL = {
 40    "year": "year",
 41    "yyyy": "year",
 42    "yy": "year",
 43    "quarter": "quarter",
 44    "qq": "quarter",
 45    "q": "quarter",
 46    "month": "month",
 47    "mm": "month",
 48    "m": "month",
 49    "week": "week",
 50    "ww": "week",
 51    "wk": "week",
 52    "day": "day",
 53    "dd": "day",
 54    "d": "day",
 55}
 56
 57
 58DATE_FMT_RE = re.compile("([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})")
 59
 60# N = Numeric, C=Currency
 61TRANSPILE_SAFE_NUMBER_FMT = {"N", "C"}
 62
 63DEFAULT_START_DATE = datetime.date(1900, 1, 1)
 64
 65BIT_TYPES = {exp.EQ, exp.NEQ, exp.Is, exp.In, exp.Select, exp.Alias}
 66
 67
 68def _format_time_lambda(
 69    exp_class: t.Type[E], full_format_mapping: t.Optional[bool] = None
 70) -> t.Callable[[t.List], E]:
 71    def _format_time(args: t.List) -> E:
 72        assert len(args) == 2
 73
 74        return exp_class(
 75            this=exp.cast(args[1], "datetime"),
 76            format=exp.Literal.string(
 77                format_time(
 78                    args[0].name.lower(),
 79                    {**TSQL.TIME_MAPPING, **FULL_FORMAT_TIME_MAPPING}
 80                    if full_format_mapping
 81                    else TSQL.TIME_MAPPING,
 82                )
 83            ),
 84        )
 85
 86    return _format_time
 87
 88
 89def _parse_format(args: t.List) -> exp.Expression:
 90    this = seq_get(args, 0)
 91    fmt = seq_get(args, 1)
 92    culture = seq_get(args, 2)
 93
 94    number_fmt = fmt and (fmt.name in TRANSPILE_SAFE_NUMBER_FMT or not DATE_FMT_RE.search(fmt.name))
 95
 96    if number_fmt:
 97        return exp.NumberToStr(this=this, format=fmt, culture=culture)
 98
 99    if fmt:
100        fmt = exp.Literal.string(
101            format_time(fmt.name, TSQL.FORMAT_TIME_MAPPING)
102            if len(fmt.name) == 1
103            else format_time(fmt.name, TSQL.TIME_MAPPING)
104        )
105
106    return exp.TimeToStr(this=this, format=fmt, culture=culture)
107
108
109def _parse_eomonth(args: t.List) -> exp.LastDay:
110    date = exp.TsOrDsToDate(this=seq_get(args, 0))
111    month_lag = seq_get(args, 1)
112
113    if month_lag is None:
114        this: exp.Expression = date
115    else:
116        unit = DATE_DELTA_INTERVAL.get("month")
117        this = exp.DateAdd(this=date, expression=month_lag, unit=unit and exp.var(unit))
118
119    return exp.LastDay(this=this)
120
121
122def _parse_hashbytes(args: t.List) -> exp.Expression:
123    kind, data = args
124    kind = kind.name.upper() if kind.is_string else ""
125
126    if kind == "MD5":
127        args.pop(0)
128        return exp.MD5(this=data)
129    if kind in ("SHA", "SHA1"):
130        args.pop(0)
131        return exp.SHA(this=data)
132    if kind == "SHA2_256":
133        return exp.SHA2(this=data, length=exp.Literal.number(256))
134    if kind == "SHA2_512":
135        return exp.SHA2(this=data, length=exp.Literal.number(512))
136
137    return exp.func("HASHBYTES", *args)
138
139
140DATEPART_ONLY_FORMATS = {"DW", "HOUR", "QUARTER"}
141
142
143def _format_sql(self: TSQL.Generator, expression: exp.NumberToStr | exp.TimeToStr) -> str:
144    fmt = expression.args["format"]
145
146    if not isinstance(expression, exp.NumberToStr):
147        if fmt.is_string:
148            mapped_fmt = format_time(fmt.name, TSQL.INVERSE_TIME_MAPPING)
149
150            name = (mapped_fmt or "").upper()
151            if name in DATEPART_ONLY_FORMATS:
152                return self.func("DATEPART", name, expression.this)
153
154            fmt_sql = self.sql(exp.Literal.string(mapped_fmt))
155        else:
156            fmt_sql = self.format_time(expression) or self.sql(fmt)
157    else:
158        fmt_sql = self.sql(fmt)
159
160    return self.func("FORMAT", expression.this, fmt_sql, expression.args.get("culture"))
161
162
163def _string_agg_sql(self: TSQL.Generator, expression: exp.GroupConcat) -> str:
164    this = expression.this
165    distinct = expression.find(exp.Distinct)
166    if distinct:
167        # exp.Distinct can appear below an exp.Order or an exp.GroupConcat expression
168        self.unsupported("T-SQL STRING_AGG doesn't support DISTINCT.")
169        this = distinct.pop().expressions[0]
170
171    order = ""
172    if isinstance(expression.this, exp.Order):
173        if expression.this.this:
174            this = expression.this.this.pop()
175        order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})"  # Order has a leading space
176
177    separator = expression.args.get("separator") or exp.Literal.string(",")
178    return f"STRING_AGG({self.format_args(this, separator)}){order}"
179
180
181def _parse_date_delta(
182    exp_class: t.Type[E], unit_mapping: t.Optional[t.Dict[str, str]] = None
183) -> t.Callable[[t.List], E]:
184    def inner_func(args: t.List) -> E:
185        unit = seq_get(args, 0)
186        if unit and unit_mapping:
187            unit = exp.var(unit_mapping.get(unit.name.lower(), unit.name))
188
189        start_date = seq_get(args, 1)
190        if start_date and start_date.is_number:
191            # Numeric types are valid DATETIME values
192            if start_date.is_int:
193                adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this))
194                start_date = exp.Literal.string(adds.strftime("%F"))
195            else:
196                # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs.
197                # This is not a problem when generating T-SQL code, it is when transpiling to other dialects.
198                return exp_class(this=seq_get(args, 2), expression=start_date, unit=unit)
199
200        return exp_class(
201            this=exp.TimeStrToTime(this=seq_get(args, 2)),
202            expression=exp.TimeStrToTime(this=start_date),
203            unit=unit,
204        )
205
206    return inner_func
207
208
209def qualify_derived_table_outputs(expression: exp.Expression) -> exp.Expression:
210    """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries."""
211    alias = expression.args.get("alias")
212
213    if (
214        isinstance(expression, (exp.CTE, exp.Subquery))
215        and isinstance(alias, exp.TableAlias)
216        and not alias.columns
217    ):
218        from sqlglot.optimizer.qualify_columns import qualify_outputs
219
220        # We keep track of the unaliased column projection indexes instead of the expressions
221        # themselves, because the latter are going to be replaced by new nodes when the aliases
222        # are added and hence we won't be able to reach these newly added Alias parents
223        subqueryable = expression.this
224        unaliased_column_indexes = (
225            i
226            for i, c in enumerate(subqueryable.selects)
227            if isinstance(c, exp.Column) and not c.alias
228        )
229
230        qualify_outputs(subqueryable)
231
232        # Preserve the quoting information of columns for newly added Alias nodes
233        subqueryable_selects = subqueryable.selects
234        for select_index in unaliased_column_indexes:
235            alias = subqueryable_selects[select_index]
236            column = alias.this
237            if isinstance(column.this, exp.Identifier):
238                alias.args["alias"].set("quoted", column.this.quoted)
239
240    return expression
241
242
243# https://learn.microsoft.com/en-us/sql/t-sql/functions/datetimefromparts-transact-sql?view=sql-server-ver16#syntax
244def _parse_datetimefromparts(args: t.List) -> exp.TimestampFromParts:
245    return exp.TimestampFromParts(
246        year=seq_get(args, 0),
247        month=seq_get(args, 1),
248        day=seq_get(args, 2),
249        hour=seq_get(args, 3),
250        min=seq_get(args, 4),
251        sec=seq_get(args, 5),
252        milli=seq_get(args, 6),
253    )
254
255
256# https://learn.microsoft.com/en-us/sql/t-sql/functions/timefromparts-transact-sql?view=sql-server-ver16#syntax
257def _parse_timefromparts(args: t.List) -> exp.TimeFromParts:
258    return exp.TimeFromParts(
259        hour=seq_get(args, 0),
260        min=seq_get(args, 1),
261        sec=seq_get(args, 2),
262        fractions=seq_get(args, 3),
263        precision=seq_get(args, 4),
264    )
265
266
267class TSQL(Dialect):
268    NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
269    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
270    SUPPORTS_SEMI_ANTI_JOIN = False
271    LOG_BASE_FIRST = False
272    TYPED_DIVISION = True
273    CONCAT_COALESCE = True
274
275    TIME_MAPPING = {
276        "year": "%Y",
277        "dayofyear": "%j",
278        "day": "%d",
279        "dy": "%d",
280        "y": "%Y",
281        "week": "%W",
282        "ww": "%W",
283        "wk": "%W",
284        "hour": "%h",
285        "hh": "%I",
286        "minute": "%M",
287        "mi": "%M",
288        "n": "%M",
289        "second": "%S",
290        "ss": "%S",
291        "s": "%-S",
292        "millisecond": "%f",
293        "ms": "%f",
294        "weekday": "%W",
295        "dw": "%W",
296        "month": "%m",
297        "mm": "%M",
298        "m": "%-M",
299        "Y": "%Y",
300        "YYYY": "%Y",
301        "YY": "%y",
302        "MMMM": "%B",
303        "MMM": "%b",
304        "MM": "%m",
305        "M": "%-m",
306        "dddd": "%A",
307        "dd": "%d",
308        "d": "%-d",
309        "HH": "%H",
310        "H": "%-H",
311        "h": "%-I",
312        "S": "%f",
313        "yyyy": "%Y",
314        "yy": "%y",
315    }
316
317    CONVERT_FORMAT_MAPPING = {
318        "0": "%b %d %Y %-I:%M%p",
319        "1": "%m/%d/%y",
320        "2": "%y.%m.%d",
321        "3": "%d/%m/%y",
322        "4": "%d.%m.%y",
323        "5": "%d-%m-%y",
324        "6": "%d %b %y",
325        "7": "%b %d, %y",
326        "8": "%H:%M:%S",
327        "9": "%b %d %Y %-I:%M:%S:%f%p",
328        "10": "mm-dd-yy",
329        "11": "yy/mm/dd",
330        "12": "yymmdd",
331        "13": "%d %b %Y %H:%M:ss:%f",
332        "14": "%H:%M:%S:%f",
333        "20": "%Y-%m-%d %H:%M:%S",
334        "21": "%Y-%m-%d %H:%M:%S.%f",
335        "22": "%m/%d/%y %-I:%M:%S %p",
336        "23": "%Y-%m-%d",
337        "24": "%H:%M:%S",
338        "25": "%Y-%m-%d %H:%M:%S.%f",
339        "100": "%b %d %Y %-I:%M%p",
340        "101": "%m/%d/%Y",
341        "102": "%Y.%m.%d",
342        "103": "%d/%m/%Y",
343        "104": "%d.%m.%Y",
344        "105": "%d-%m-%Y",
345        "106": "%d %b %Y",
346        "107": "%b %d, %Y",
347        "108": "%H:%M:%S",
348        "109": "%b %d %Y %-I:%M:%S:%f%p",
349        "110": "%m-%d-%Y",
350        "111": "%Y/%m/%d",
351        "112": "%Y%m%d",
352        "113": "%d %b %Y %H:%M:%S:%f",
353        "114": "%H:%M:%S:%f",
354        "120": "%Y-%m-%d %H:%M:%S",
355        "121": "%Y-%m-%d %H:%M:%S.%f",
356    }
357
358    FORMAT_TIME_MAPPING = {
359        "y": "%B %Y",
360        "d": "%m/%d/%Y",
361        "H": "%-H",
362        "h": "%-I",
363        "s": "%Y-%m-%d %H:%M:%S",
364        "D": "%A,%B,%Y",
365        "f": "%A,%B,%Y %-I:%M %p",
366        "F": "%A,%B,%Y %-I:%M:%S %p",
367        "g": "%m/%d/%Y %-I:%M %p",
368        "G": "%m/%d/%Y %-I:%M:%S %p",
369        "M": "%B %-d",
370        "m": "%B %-d",
371        "O": "%Y-%m-%dT%H:%M:%S",
372        "u": "%Y-%M-%D %H:%M:%S%z",
373        "U": "%A, %B %D, %Y %H:%M:%S%z",
374        "T": "%-I:%M:%S %p",
375        "t": "%-I:%M",
376        "Y": "%a %Y",
377    }
378
379    class Tokenizer(tokens.Tokenizer):
380        IDENTIFIERS = [("[", "]"), '"']
381        QUOTES = ["'", '"']
382        HEX_STRINGS = [("0x", ""), ("0X", "")]
383        VAR_SINGLE_TOKENS = {"@", "$", "#"}
384
385        KEYWORDS = {
386            **tokens.Tokenizer.KEYWORDS,
387            "DATETIME2": TokenType.DATETIME,
388            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
389            "DECLARE": TokenType.COMMAND,
390            "EXEC": TokenType.COMMAND,
391            "IMAGE": TokenType.IMAGE,
392            "MONEY": TokenType.MONEY,
393            "NTEXT": TokenType.TEXT,
394            "NVARCHAR(MAX)": TokenType.TEXT,
395            "PRINT": TokenType.COMMAND,
396            "PROC": TokenType.PROCEDURE,
397            "REAL": TokenType.FLOAT,
398            "ROWVERSION": TokenType.ROWVERSION,
399            "SMALLDATETIME": TokenType.DATETIME,
400            "SMALLMONEY": TokenType.SMALLMONEY,
401            "SQL_VARIANT": TokenType.VARIANT,
402            "TOP": TokenType.TOP,
403            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
404            "UPDATE STATISTICS": TokenType.COMMAND,
405            "VARCHAR(MAX)": TokenType.TEXT,
406            "XML": TokenType.XML,
407            "OUTPUT": TokenType.RETURNING,
408            "SYSTEM_USER": TokenType.CURRENT_USER,
409            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
410        }
411
412    class Parser(parser.Parser):
413        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
414
415        FUNCTIONS = {
416            **parser.Parser.FUNCTIONS,
417            "CHARINDEX": lambda args: exp.StrPosition(
418                this=seq_get(args, 1),
419                substr=seq_get(args, 0),
420                position=seq_get(args, 2),
421            ),
422            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
423            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
424            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
425            "DATEPART": _format_time_lambda(exp.TimeToStr),
426            "DATETIMEFROMPARTS": _parse_datetimefromparts,
427            "EOMONTH": _parse_eomonth,
428            "FORMAT": _parse_format,
429            "GETDATE": exp.CurrentTimestamp.from_arg_list,
430            "HASHBYTES": _parse_hashbytes,
431            "IIF": exp.If.from_arg_list,
432            "ISNULL": exp.Coalesce.from_arg_list,
433            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
434            "LEN": exp.Length.from_arg_list,
435            "REPLICATE": exp.Repeat.from_arg_list,
436            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
437            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
438            "SUSER_NAME": exp.CurrentUser.from_arg_list,
439            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
440            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
441            "TIMEFROMPARTS": _parse_timefromparts,
442        }
443
444        JOIN_HINTS = {
445            "LOOP",
446            "HASH",
447            "MERGE",
448            "REMOTE",
449        }
450
451        VAR_LENGTH_DATATYPES = {
452            DataType.Type.NVARCHAR,
453            DataType.Type.VARCHAR,
454            DataType.Type.CHAR,
455            DataType.Type.NCHAR,
456        }
457
458        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
459            TokenType.TABLE,
460            *parser.Parser.TYPE_TOKENS,
461        }
462
463        STATEMENT_PARSERS = {
464            **parser.Parser.STATEMENT_PARSERS,
465            TokenType.END: lambda self: self._parse_command(),
466        }
467
468        LOG_DEFAULTS_TO_LN = True
469
470        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
471        STRING_ALIASES = True
472
473        def _parse_projections(self) -> t.List[exp.Expression]:
474            """
475            T-SQL supports the syntax alias = expression in the SELECT's projection list,
476            so we transform all parsed Selects to convert their EQ projections into Aliases.
477
478            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
479            """
480            return [
481                exp.alias_(projection.expression, projection.this.this, copy=False)
482                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
483                else projection
484                for projection in super()._parse_projections()
485            ]
486
487        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
488            """Applies to SQL Server and Azure SQL Database
489            COMMIT [ { TRAN | TRANSACTION }
490                [ transaction_name | @tran_name_variable ] ]
491                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
492
493            ROLLBACK { TRAN | TRANSACTION }
494                [ transaction_name | @tran_name_variable
495                | savepoint_name | @savepoint_variable ]
496            """
497            rollback = self._prev.token_type == TokenType.ROLLBACK
498
499            self._match_texts(("TRAN", "TRANSACTION"))
500            this = self._parse_id_var()
501
502            if rollback:
503                return self.expression(exp.Rollback, this=this)
504
505            durability = None
506            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
507                self._match_text_seq("DELAYED_DURABILITY")
508                self._match(TokenType.EQ)
509
510                if self._match_text_seq("OFF"):
511                    durability = False
512                else:
513                    self._match(TokenType.ON)
514                    durability = True
515
516                self._match_r_paren()
517
518            return self.expression(exp.Commit, this=this, durability=durability)
519
520        def _parse_transaction(self) -> exp.Transaction | exp.Command:
521            """Applies to SQL Server and Azure SQL Database
522            BEGIN { TRAN | TRANSACTION }
523            [ { transaction_name | @tran_name_variable }
524            [ WITH MARK [ 'description' ] ]
525            ]
526            """
527            if self._match_texts(("TRAN", "TRANSACTION")):
528                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
529                if self._match_text_seq("WITH", "MARK"):
530                    transaction.set("mark", self._parse_string())
531
532                return transaction
533
534            return self._parse_as_command(self._prev)
535
536        def _parse_returns(self) -> exp.ReturnsProperty:
537            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
538            returns = super()._parse_returns()
539            returns.set("table", table)
540            return returns
541
542        def _parse_convert(
543            self, strict: bool, safe: t.Optional[bool] = None
544        ) -> t.Optional[exp.Expression]:
545            to = self._parse_types()
546            self._match(TokenType.COMMA)
547            this = self._parse_conjunction()
548
549            if not to or not this:
550                return None
551
552            # Retrieve length of datatype and override to default if not specified
553            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
554                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
555
556            # Check whether a conversion with format is applicable
557            if self._match(TokenType.COMMA):
558                format_val = self._parse_number()
559                format_val_name = format_val.name if format_val else ""
560
561                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
562                    raise ValueError(
563                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
564                    )
565
566                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
567
568                # Check whether the convert entails a string to date format
569                if to.this == DataType.Type.DATE:
570                    return self.expression(exp.StrToDate, this=this, format=format_norm)
571                # Check whether the convert entails a string to datetime format
572                elif to.this == DataType.Type.DATETIME:
573                    return self.expression(exp.StrToTime, this=this, format=format_norm)
574                # Check whether the convert entails a date to string format
575                elif to.this in self.VAR_LENGTH_DATATYPES:
576                    return self.expression(
577                        exp.Cast if strict else exp.TryCast,
578                        to=to,
579                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
580                        safe=safe,
581                    )
582                elif to.this == DataType.Type.TEXT:
583                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
584
585            # Entails a simple cast without any format requirement
586            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
587
588        def _parse_user_defined_function(
589            self, kind: t.Optional[TokenType] = None
590        ) -> t.Optional[exp.Expression]:
591            this = super()._parse_user_defined_function(kind=kind)
592
593            if (
594                kind == TokenType.FUNCTION
595                or isinstance(this, exp.UserDefinedFunction)
596                or self._match(TokenType.ALIAS, advance=False)
597            ):
598                return this
599
600            expressions = self._parse_csv(self._parse_function_parameter)
601            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
602
603        def _parse_id_var(
604            self,
605            any_token: bool = True,
606            tokens: t.Optional[t.Collection[TokenType]] = None,
607        ) -> t.Optional[exp.Expression]:
608            is_temporary = self._match(TokenType.HASH)
609            is_global = is_temporary and self._match(TokenType.HASH)
610
611            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
612            if this:
613                if is_global:
614                    this.set("global", True)
615                elif is_temporary:
616                    this.set("temporary", True)
617
618            return this
619
620        def _parse_create(self) -> exp.Create | exp.Command:
621            create = super()._parse_create()
622
623            if isinstance(create, exp.Create):
624                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
625                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
626                    if not create.args.get("properties"):
627                        create.set("properties", exp.Properties(expressions=[]))
628
629                    create.args["properties"].append("expressions", exp.TemporaryProperty())
630
631            return create
632
633        def _parse_if(self) -> t.Optional[exp.Expression]:
634            index = self._index
635
636            if self._match_text_seq("OBJECT_ID"):
637                self._parse_wrapped_csv(self._parse_string)
638                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
639                    return self._parse_drop(exists=True)
640                self._retreat(index)
641
642            return super()._parse_if()
643
644        def _parse_unique(self) -> exp.UniqueColumnConstraint:
645            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
646                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
647            else:
648                this = self._parse_schema(self._parse_id_var(any_token=False))
649
650            return self.expression(exp.UniqueColumnConstraint, this=this)
651
652    class Generator(generator.Generator):
653        LIMIT_IS_TOP = True
654        QUERY_HINTS = False
655        RETURNING_END = False
656        NVL2_SUPPORTED = False
657        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
658        LIMIT_FETCH = "FETCH"
659        COMPUTED_COLUMN_WITH_TYPE = False
660        CTE_RECURSIVE_KEYWORD_REQUIRED = False
661        ENSURE_BOOLS = True
662        NULL_ORDERING_SUPPORTED = False
663        SUPPORTS_SINGLE_ARG_CONCAT = False
664        TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
665
666        EXPRESSIONS_WITHOUT_NESTED_CTES = {
667            exp.Delete,
668            exp.Insert,
669            exp.Merge,
670            exp.Select,
671            exp.Subquery,
672            exp.Union,
673            exp.Update,
674        }
675
676        TYPE_MAPPING = {
677            **generator.Generator.TYPE_MAPPING,
678            exp.DataType.Type.BOOLEAN: "BIT",
679            exp.DataType.Type.DECIMAL: "NUMERIC",
680            exp.DataType.Type.DATETIME: "DATETIME2",
681            exp.DataType.Type.DOUBLE: "FLOAT",
682            exp.DataType.Type.INT: "INTEGER",
683            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
684            exp.DataType.Type.TIMESTAMP: "DATETIME2",
685            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
686            exp.DataType.Type.VARIANT: "SQL_VARIANT",
687        }
688
689        TRANSFORMS = {
690            **generator.Generator.TRANSFORMS,
691            exp.AnyValue: any_value_to_max_sql,
692            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
693            exp.DateAdd: date_delta_sql("DATEADD"),
694            exp.DateDiff: date_delta_sql("DATEDIFF"),
695            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
696            exp.CurrentDate: rename_func("GETDATE"),
697            exp.CurrentTimestamp: rename_func("GETDATE"),
698            exp.Extract: rename_func("DATEPART"),
699            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
700            exp.GetPath: path_to_jsonpath("JSON_VALUE"),
701            exp.GroupConcat: _string_agg_sql,
702            exp.If: rename_func("IIF"),
703            exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
704            exp.Length: rename_func("LEN"),
705            exp.Max: max_or_greatest,
706            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
707            exp.Min: min_or_least,
708            exp.NumberToStr: _format_sql,
709            exp.ParseJSON: lambda self, e: self.sql(e, "this"),
710            exp.Select: transforms.preprocess(
711                [
712                    transforms.eliminate_distinct_on,
713                    transforms.eliminate_semi_and_anti_joins,
714                    transforms.eliminate_qualify,
715                ]
716            ),
717            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
718            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
719            exp.SHA2: lambda self, e: self.func(
720                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
721            ),
722            exp.TemporaryProperty: lambda self, e: "",
723            exp.TimeStrToTime: timestrtotime_sql,
724            exp.TimeToStr: _format_sql,
725            exp.Trim: trim_sql,
726            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
727            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
728        }
729
730        TRANSFORMS.pop(exp.ReturnsProperty)
731
732        PROPERTIES_LOCATION = {
733            **generator.Generator.PROPERTIES_LOCATION,
734            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
735        }
736
737        def lateral_op(self, expression: exp.Lateral) -> str:
738            cross_apply = expression.args.get("cross_apply")
739            if cross_apply is True:
740                return "CROSS APPLY"
741            if cross_apply is False:
742                return "OUTER APPLY"
743
744            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
745            self.unsupported("LATERAL clause is not supported.")
746            return "LATERAL"
747
748        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
749            nano = expression.args.get("nano")
750            if nano is not None:
751                nano.pop()
752                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
753
754            if expression.args.get("fractions") is None:
755                expression.set("fractions", exp.Literal.number(0))
756            if expression.args.get("precision") is None:
757                expression.set("precision", exp.Literal.number(0))
758
759            return rename_func("TIMEFROMPARTS")(self, expression)
760
761        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
762            zone = expression.args.get("zone")
763            if zone is not None:
764                zone.pop()
765                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
766
767            nano = expression.args.get("nano")
768            if nano is not None:
769                nano.pop()
770                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
771
772            if expression.args.get("milli") is None:
773                expression.set("milli", exp.Literal.number(0))
774
775            return rename_func("DATETIMEFROMPARTS")(self, expression)
776
777        def set_operation(self, expression: exp.Union, op: str) -> str:
778            limit = expression.args.get("limit")
779            if limit:
780                return self.sql(expression.limit(limit.pop(), copy=False))
781
782            return super().set_operation(expression, op)
783
784        def setitem_sql(self, expression: exp.SetItem) -> str:
785            this = expression.this
786            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
787                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
788                return f"{self.sql(this.left)} {self.sql(this.right)}"
789
790            return super().setitem_sql(expression)
791
792        def boolean_sql(self, expression: exp.Boolean) -> str:
793            if type(expression.parent) in BIT_TYPES:
794                return "1" if expression.this else "0"
795
796            return "(1 = 1)" if expression.this else "(1 = 0)"
797
798        def is_sql(self, expression: exp.Is) -> str:
799            if isinstance(expression.expression, exp.Boolean):
800                return self.binary(expression, "=")
801            return self.binary(expression, "IS")
802
803        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
804            sql = self.sql(expression, "this")
805            properties = expression.args.get("properties")
806
807            if sql[:1] != "#" and any(
808                isinstance(prop, exp.TemporaryProperty)
809                for prop in (properties.expressions if properties else [])
810            ):
811                sql = f"#{sql}"
812
813            return sql
814
815        def create_sql(self, expression: exp.Create) -> str:
816            kind = self.sql(expression, "kind").upper()
817            exists = expression.args.pop("exists", None)
818            sql = super().create_sql(expression)
819
820            table = expression.find(exp.Table)
821
822            # Convert CTAS statement to SELECT .. INTO ..
823            if kind == "TABLE" and expression.expression:
824                ctas_with = expression.expression.args.get("with")
825                if ctas_with:
826                    ctas_with = ctas_with.pop()
827
828                subquery = expression.expression
829                if isinstance(subquery, exp.Subqueryable):
830                    subquery = subquery.subquery()
831
832                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
833                select_into.set("into", exp.Into(this=table))
834                select_into.set("with", ctas_with)
835
836                sql = self.sql(select_into)
837
838            if exists:
839                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
840                sql = self.sql(exp.Literal.string(sql))
841                if kind == "SCHEMA":
842                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
843                elif kind == "TABLE":
844                    assert table
845                    where = exp.and_(
846                        exp.column("table_name").eq(table.name),
847                        exp.column("table_schema").eq(table.db) if table.db else None,
848                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
849                    )
850                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
851                elif kind == "INDEX":
852                    index = self.sql(exp.Literal.string(expression.this.text("this")))
853                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
854            elif expression.args.get("replace"):
855                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
856
857            return self.prepend_ctes(expression, sql)
858
859        def offset_sql(self, expression: exp.Offset) -> str:
860            return f"{super().offset_sql(expression)} ROWS"
861
862        def version_sql(self, expression: exp.Version) -> str:
863            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
864            this = f"FOR {name}"
865            expr = expression.expression
866            kind = expression.text("kind")
867            if kind in ("FROM", "BETWEEN"):
868                args = expr.expressions
869                sep = "TO" if kind == "FROM" else "AND"
870                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
871            else:
872                expr_sql = self.sql(expr)
873
874            expr_sql = f" {expr_sql}" if expr_sql else ""
875            return f"{this} {kind}{expr_sql}"
876
877        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
878            table = expression.args.get("table")
879            table = f"{table} " if table else ""
880            return f"RETURNS {table}{self.sql(expression, 'this')}"
881
882        def returning_sql(self, expression: exp.Returning) -> str:
883            into = self.sql(expression, "into")
884            into = self.seg(f"INTO {into}") if into else ""
885            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
886
887        def transaction_sql(self, expression: exp.Transaction) -> str:
888            this = self.sql(expression, "this")
889            this = f" {this}" if this else ""
890            mark = self.sql(expression, "mark")
891            mark = f" WITH MARK {mark}" if mark else ""
892            return f"BEGIN TRANSACTION{this}{mark}"
893
894        def commit_sql(self, expression: exp.Commit) -> str:
895            this = self.sql(expression, "this")
896            this = f" {this}" if this else ""
897            durability = expression.args.get("durability")
898            durability = (
899                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
900                if durability is not None
901                else ""
902            )
903            return f"COMMIT TRANSACTION{this}{durability}"
904
905        def rollback_sql(self, expression: exp.Rollback) -> str:
906            this = self.sql(expression, "this")
907            this = f" {this}" if this else ""
908            return f"ROLLBACK TRANSACTION{this}"
909
910        def identifier_sql(self, expression: exp.Identifier) -> str:
911            identifier = super().identifier_sql(expression)
912
913            if expression.args.get("global"):
914                identifier = f"##{identifier}"
915            elif expression.args.get("temporary"):
916                identifier = f"#{identifier}"
917
918            return identifier
919
920        def constraint_sql(self, expression: exp.Constraint) -> str:
921            this = self.sql(expression, "this")
922            expressions = self.expressions(expression, flat=True, sep=" ")
923            return f"CONSTRAINT {this} {expressions}"
FULL_FORMAT_TIME_MAPPING = {'weekday': '%A', 'dw': '%A', 'w': '%A', 'month': '%B', 'mm': '%B', 'm': '%B'}
DATE_DELTA_INTERVAL = {'year': 'year', 'yyyy': 'year', 'yy': 'year', 'quarter': 'quarter', 'qq': 'quarter', 'q': 'quarter', 'month': 'month', 'mm': 'month', 'm': 'month', 'week': 'week', 'ww': 'week', 'wk': 'week', 'day': 'day', 'dd': 'day', 'd': 'day'}
DATE_FMT_RE = re.compile('([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})')
TRANSPILE_SAFE_NUMBER_FMT = {'N', 'C'}
DEFAULT_START_DATE = datetime.date(1900, 1, 1)
DATEPART_ONLY_FORMATS = {'QUARTER', 'DW', 'HOUR'}
def qualify_derived_table_outputs( expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression:
210def qualify_derived_table_outputs(expression: exp.Expression) -> exp.Expression:
211    """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries."""
212    alias = expression.args.get("alias")
213
214    if (
215        isinstance(expression, (exp.CTE, exp.Subquery))
216        and isinstance(alias, exp.TableAlias)
217        and not alias.columns
218    ):
219        from sqlglot.optimizer.qualify_columns import qualify_outputs
220
221        # We keep track of the unaliased column projection indexes instead of the expressions
222        # themselves, because the latter are going to be replaced by new nodes when the aliases
223        # are added and hence we won't be able to reach these newly added Alias parents
224        subqueryable = expression.this
225        unaliased_column_indexes = (
226            i
227            for i, c in enumerate(subqueryable.selects)
228            if isinstance(c, exp.Column) and not c.alias
229        )
230
231        qualify_outputs(subqueryable)
232
233        # Preserve the quoting information of columns for newly added Alias nodes
234        subqueryable_selects = subqueryable.selects
235        for select_index in unaliased_column_indexes:
236            alias = subqueryable_selects[select_index]
237            column = alias.this
238            if isinstance(column.this, exp.Identifier):
239                alias.args["alias"].set("quoted", column.this.quoted)
240
241    return expression

Ensures all (unnamed) output columns are aliased for CTEs and Subqueries.

class TSQL(sqlglot.dialects.dialect.Dialect):
268class TSQL(Dialect):
269    NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
270    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
271    SUPPORTS_SEMI_ANTI_JOIN = False
272    LOG_BASE_FIRST = False
273    TYPED_DIVISION = True
274    CONCAT_COALESCE = True
275
276    TIME_MAPPING = {
277        "year": "%Y",
278        "dayofyear": "%j",
279        "day": "%d",
280        "dy": "%d",
281        "y": "%Y",
282        "week": "%W",
283        "ww": "%W",
284        "wk": "%W",
285        "hour": "%h",
286        "hh": "%I",
287        "minute": "%M",
288        "mi": "%M",
289        "n": "%M",
290        "second": "%S",
291        "ss": "%S",
292        "s": "%-S",
293        "millisecond": "%f",
294        "ms": "%f",
295        "weekday": "%W",
296        "dw": "%W",
297        "month": "%m",
298        "mm": "%M",
299        "m": "%-M",
300        "Y": "%Y",
301        "YYYY": "%Y",
302        "YY": "%y",
303        "MMMM": "%B",
304        "MMM": "%b",
305        "MM": "%m",
306        "M": "%-m",
307        "dddd": "%A",
308        "dd": "%d",
309        "d": "%-d",
310        "HH": "%H",
311        "H": "%-H",
312        "h": "%-I",
313        "S": "%f",
314        "yyyy": "%Y",
315        "yy": "%y",
316    }
317
318    CONVERT_FORMAT_MAPPING = {
319        "0": "%b %d %Y %-I:%M%p",
320        "1": "%m/%d/%y",
321        "2": "%y.%m.%d",
322        "3": "%d/%m/%y",
323        "4": "%d.%m.%y",
324        "5": "%d-%m-%y",
325        "6": "%d %b %y",
326        "7": "%b %d, %y",
327        "8": "%H:%M:%S",
328        "9": "%b %d %Y %-I:%M:%S:%f%p",
329        "10": "mm-dd-yy",
330        "11": "yy/mm/dd",
331        "12": "yymmdd",
332        "13": "%d %b %Y %H:%M:ss:%f",
333        "14": "%H:%M:%S:%f",
334        "20": "%Y-%m-%d %H:%M:%S",
335        "21": "%Y-%m-%d %H:%M:%S.%f",
336        "22": "%m/%d/%y %-I:%M:%S %p",
337        "23": "%Y-%m-%d",
338        "24": "%H:%M:%S",
339        "25": "%Y-%m-%d %H:%M:%S.%f",
340        "100": "%b %d %Y %-I:%M%p",
341        "101": "%m/%d/%Y",
342        "102": "%Y.%m.%d",
343        "103": "%d/%m/%Y",
344        "104": "%d.%m.%Y",
345        "105": "%d-%m-%Y",
346        "106": "%d %b %Y",
347        "107": "%b %d, %Y",
348        "108": "%H:%M:%S",
349        "109": "%b %d %Y %-I:%M:%S:%f%p",
350        "110": "%m-%d-%Y",
351        "111": "%Y/%m/%d",
352        "112": "%Y%m%d",
353        "113": "%d %b %Y %H:%M:%S:%f",
354        "114": "%H:%M:%S:%f",
355        "120": "%Y-%m-%d %H:%M:%S",
356        "121": "%Y-%m-%d %H:%M:%S.%f",
357    }
358
359    FORMAT_TIME_MAPPING = {
360        "y": "%B %Y",
361        "d": "%m/%d/%Y",
362        "H": "%-H",
363        "h": "%-I",
364        "s": "%Y-%m-%d %H:%M:%S",
365        "D": "%A,%B,%Y",
366        "f": "%A,%B,%Y %-I:%M %p",
367        "F": "%A,%B,%Y %-I:%M:%S %p",
368        "g": "%m/%d/%Y %-I:%M %p",
369        "G": "%m/%d/%Y %-I:%M:%S %p",
370        "M": "%B %-d",
371        "m": "%B %-d",
372        "O": "%Y-%m-%dT%H:%M:%S",
373        "u": "%Y-%M-%D %H:%M:%S%z",
374        "U": "%A, %B %D, %Y %H:%M:%S%z",
375        "T": "%-I:%M:%S %p",
376        "t": "%-I:%M",
377        "Y": "%a %Y",
378    }
379
380    class Tokenizer(tokens.Tokenizer):
381        IDENTIFIERS = [("[", "]"), '"']
382        QUOTES = ["'", '"']
383        HEX_STRINGS = [("0x", ""), ("0X", "")]
384        VAR_SINGLE_TOKENS = {"@", "$", "#"}
385
386        KEYWORDS = {
387            **tokens.Tokenizer.KEYWORDS,
388            "DATETIME2": TokenType.DATETIME,
389            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
390            "DECLARE": TokenType.COMMAND,
391            "EXEC": TokenType.COMMAND,
392            "IMAGE": TokenType.IMAGE,
393            "MONEY": TokenType.MONEY,
394            "NTEXT": TokenType.TEXT,
395            "NVARCHAR(MAX)": TokenType.TEXT,
396            "PRINT": TokenType.COMMAND,
397            "PROC": TokenType.PROCEDURE,
398            "REAL": TokenType.FLOAT,
399            "ROWVERSION": TokenType.ROWVERSION,
400            "SMALLDATETIME": TokenType.DATETIME,
401            "SMALLMONEY": TokenType.SMALLMONEY,
402            "SQL_VARIANT": TokenType.VARIANT,
403            "TOP": TokenType.TOP,
404            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
405            "UPDATE STATISTICS": TokenType.COMMAND,
406            "VARCHAR(MAX)": TokenType.TEXT,
407            "XML": TokenType.XML,
408            "OUTPUT": TokenType.RETURNING,
409            "SYSTEM_USER": TokenType.CURRENT_USER,
410            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
411        }
412
413    class Parser(parser.Parser):
414        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
415
416        FUNCTIONS = {
417            **parser.Parser.FUNCTIONS,
418            "CHARINDEX": lambda args: exp.StrPosition(
419                this=seq_get(args, 1),
420                substr=seq_get(args, 0),
421                position=seq_get(args, 2),
422            ),
423            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
424            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
425            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
426            "DATEPART": _format_time_lambda(exp.TimeToStr),
427            "DATETIMEFROMPARTS": _parse_datetimefromparts,
428            "EOMONTH": _parse_eomonth,
429            "FORMAT": _parse_format,
430            "GETDATE": exp.CurrentTimestamp.from_arg_list,
431            "HASHBYTES": _parse_hashbytes,
432            "IIF": exp.If.from_arg_list,
433            "ISNULL": exp.Coalesce.from_arg_list,
434            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
435            "LEN": exp.Length.from_arg_list,
436            "REPLICATE": exp.Repeat.from_arg_list,
437            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
438            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
439            "SUSER_NAME": exp.CurrentUser.from_arg_list,
440            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
441            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
442            "TIMEFROMPARTS": _parse_timefromparts,
443        }
444
445        JOIN_HINTS = {
446            "LOOP",
447            "HASH",
448            "MERGE",
449            "REMOTE",
450        }
451
452        VAR_LENGTH_DATATYPES = {
453            DataType.Type.NVARCHAR,
454            DataType.Type.VARCHAR,
455            DataType.Type.CHAR,
456            DataType.Type.NCHAR,
457        }
458
459        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
460            TokenType.TABLE,
461            *parser.Parser.TYPE_TOKENS,
462        }
463
464        STATEMENT_PARSERS = {
465            **parser.Parser.STATEMENT_PARSERS,
466            TokenType.END: lambda self: self._parse_command(),
467        }
468
469        LOG_DEFAULTS_TO_LN = True
470
471        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
472        STRING_ALIASES = True
473
474        def _parse_projections(self) -> t.List[exp.Expression]:
475            """
476            T-SQL supports the syntax alias = expression in the SELECT's projection list,
477            so we transform all parsed Selects to convert their EQ projections into Aliases.
478
479            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
480            """
481            return [
482                exp.alias_(projection.expression, projection.this.this, copy=False)
483                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
484                else projection
485                for projection in super()._parse_projections()
486            ]
487
488        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
489            """Applies to SQL Server and Azure SQL Database
490            COMMIT [ { TRAN | TRANSACTION }
491                [ transaction_name | @tran_name_variable ] ]
492                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
493
494            ROLLBACK { TRAN | TRANSACTION }
495                [ transaction_name | @tran_name_variable
496                | savepoint_name | @savepoint_variable ]
497            """
498            rollback = self._prev.token_type == TokenType.ROLLBACK
499
500            self._match_texts(("TRAN", "TRANSACTION"))
501            this = self._parse_id_var()
502
503            if rollback:
504                return self.expression(exp.Rollback, this=this)
505
506            durability = None
507            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
508                self._match_text_seq("DELAYED_DURABILITY")
509                self._match(TokenType.EQ)
510
511                if self._match_text_seq("OFF"):
512                    durability = False
513                else:
514                    self._match(TokenType.ON)
515                    durability = True
516
517                self._match_r_paren()
518
519            return self.expression(exp.Commit, this=this, durability=durability)
520
521        def _parse_transaction(self) -> exp.Transaction | exp.Command:
522            """Applies to SQL Server and Azure SQL Database
523            BEGIN { TRAN | TRANSACTION }
524            [ { transaction_name | @tran_name_variable }
525            [ WITH MARK [ 'description' ] ]
526            ]
527            """
528            if self._match_texts(("TRAN", "TRANSACTION")):
529                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
530                if self._match_text_seq("WITH", "MARK"):
531                    transaction.set("mark", self._parse_string())
532
533                return transaction
534
535            return self._parse_as_command(self._prev)
536
537        def _parse_returns(self) -> exp.ReturnsProperty:
538            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
539            returns = super()._parse_returns()
540            returns.set("table", table)
541            return returns
542
543        def _parse_convert(
544            self, strict: bool, safe: t.Optional[bool] = None
545        ) -> t.Optional[exp.Expression]:
546            to = self._parse_types()
547            self._match(TokenType.COMMA)
548            this = self._parse_conjunction()
549
550            if not to or not this:
551                return None
552
553            # Retrieve length of datatype and override to default if not specified
554            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
555                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
556
557            # Check whether a conversion with format is applicable
558            if self._match(TokenType.COMMA):
559                format_val = self._parse_number()
560                format_val_name = format_val.name if format_val else ""
561
562                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
563                    raise ValueError(
564                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
565                    )
566
567                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
568
569                # Check whether the convert entails a string to date format
570                if to.this == DataType.Type.DATE:
571                    return self.expression(exp.StrToDate, this=this, format=format_norm)
572                # Check whether the convert entails a string to datetime format
573                elif to.this == DataType.Type.DATETIME:
574                    return self.expression(exp.StrToTime, this=this, format=format_norm)
575                # Check whether the convert entails a date to string format
576                elif to.this in self.VAR_LENGTH_DATATYPES:
577                    return self.expression(
578                        exp.Cast if strict else exp.TryCast,
579                        to=to,
580                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
581                        safe=safe,
582                    )
583                elif to.this == DataType.Type.TEXT:
584                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
585
586            # Entails a simple cast without any format requirement
587            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
588
589        def _parse_user_defined_function(
590            self, kind: t.Optional[TokenType] = None
591        ) -> t.Optional[exp.Expression]:
592            this = super()._parse_user_defined_function(kind=kind)
593
594            if (
595                kind == TokenType.FUNCTION
596                or isinstance(this, exp.UserDefinedFunction)
597                or self._match(TokenType.ALIAS, advance=False)
598            ):
599                return this
600
601            expressions = self._parse_csv(self._parse_function_parameter)
602            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
603
604        def _parse_id_var(
605            self,
606            any_token: bool = True,
607            tokens: t.Optional[t.Collection[TokenType]] = None,
608        ) -> t.Optional[exp.Expression]:
609            is_temporary = self._match(TokenType.HASH)
610            is_global = is_temporary and self._match(TokenType.HASH)
611
612            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
613            if this:
614                if is_global:
615                    this.set("global", True)
616                elif is_temporary:
617                    this.set("temporary", True)
618
619            return this
620
621        def _parse_create(self) -> exp.Create | exp.Command:
622            create = super()._parse_create()
623
624            if isinstance(create, exp.Create):
625                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
626                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
627                    if not create.args.get("properties"):
628                        create.set("properties", exp.Properties(expressions=[]))
629
630                    create.args["properties"].append("expressions", exp.TemporaryProperty())
631
632            return create
633
634        def _parse_if(self) -> t.Optional[exp.Expression]:
635            index = self._index
636
637            if self._match_text_seq("OBJECT_ID"):
638                self._parse_wrapped_csv(self._parse_string)
639                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
640                    return self._parse_drop(exists=True)
641                self._retreat(index)
642
643            return super()._parse_if()
644
645        def _parse_unique(self) -> exp.UniqueColumnConstraint:
646            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
647                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
648            else:
649                this = self._parse_schema(self._parse_id_var(any_token=False))
650
651            return self.expression(exp.UniqueColumnConstraint, this=this)
652
653    class Generator(generator.Generator):
654        LIMIT_IS_TOP = True
655        QUERY_HINTS = False
656        RETURNING_END = False
657        NVL2_SUPPORTED = False
658        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
659        LIMIT_FETCH = "FETCH"
660        COMPUTED_COLUMN_WITH_TYPE = False
661        CTE_RECURSIVE_KEYWORD_REQUIRED = False
662        ENSURE_BOOLS = True
663        NULL_ORDERING_SUPPORTED = False
664        SUPPORTS_SINGLE_ARG_CONCAT = False
665        TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
666
667        EXPRESSIONS_WITHOUT_NESTED_CTES = {
668            exp.Delete,
669            exp.Insert,
670            exp.Merge,
671            exp.Select,
672            exp.Subquery,
673            exp.Union,
674            exp.Update,
675        }
676
677        TYPE_MAPPING = {
678            **generator.Generator.TYPE_MAPPING,
679            exp.DataType.Type.BOOLEAN: "BIT",
680            exp.DataType.Type.DECIMAL: "NUMERIC",
681            exp.DataType.Type.DATETIME: "DATETIME2",
682            exp.DataType.Type.DOUBLE: "FLOAT",
683            exp.DataType.Type.INT: "INTEGER",
684            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
685            exp.DataType.Type.TIMESTAMP: "DATETIME2",
686            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
687            exp.DataType.Type.VARIANT: "SQL_VARIANT",
688        }
689
690        TRANSFORMS = {
691            **generator.Generator.TRANSFORMS,
692            exp.AnyValue: any_value_to_max_sql,
693            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
694            exp.DateAdd: date_delta_sql("DATEADD"),
695            exp.DateDiff: date_delta_sql("DATEDIFF"),
696            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
697            exp.CurrentDate: rename_func("GETDATE"),
698            exp.CurrentTimestamp: rename_func("GETDATE"),
699            exp.Extract: rename_func("DATEPART"),
700            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
701            exp.GetPath: path_to_jsonpath("JSON_VALUE"),
702            exp.GroupConcat: _string_agg_sql,
703            exp.If: rename_func("IIF"),
704            exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
705            exp.Length: rename_func("LEN"),
706            exp.Max: max_or_greatest,
707            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
708            exp.Min: min_or_least,
709            exp.NumberToStr: _format_sql,
710            exp.ParseJSON: lambda self, e: self.sql(e, "this"),
711            exp.Select: transforms.preprocess(
712                [
713                    transforms.eliminate_distinct_on,
714                    transforms.eliminate_semi_and_anti_joins,
715                    transforms.eliminate_qualify,
716                ]
717            ),
718            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
719            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
720            exp.SHA2: lambda self, e: self.func(
721                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
722            ),
723            exp.TemporaryProperty: lambda self, e: "",
724            exp.TimeStrToTime: timestrtotime_sql,
725            exp.TimeToStr: _format_sql,
726            exp.Trim: trim_sql,
727            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
728            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
729        }
730
731        TRANSFORMS.pop(exp.ReturnsProperty)
732
733        PROPERTIES_LOCATION = {
734            **generator.Generator.PROPERTIES_LOCATION,
735            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
736        }
737
738        def lateral_op(self, expression: exp.Lateral) -> str:
739            cross_apply = expression.args.get("cross_apply")
740            if cross_apply is True:
741                return "CROSS APPLY"
742            if cross_apply is False:
743                return "OUTER APPLY"
744
745            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
746            self.unsupported("LATERAL clause is not supported.")
747            return "LATERAL"
748
749        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
750            nano = expression.args.get("nano")
751            if nano is not None:
752                nano.pop()
753                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
754
755            if expression.args.get("fractions") is None:
756                expression.set("fractions", exp.Literal.number(0))
757            if expression.args.get("precision") is None:
758                expression.set("precision", exp.Literal.number(0))
759
760            return rename_func("TIMEFROMPARTS")(self, expression)
761
762        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
763            zone = expression.args.get("zone")
764            if zone is not None:
765                zone.pop()
766                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
767
768            nano = expression.args.get("nano")
769            if nano is not None:
770                nano.pop()
771                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
772
773            if expression.args.get("milli") is None:
774                expression.set("milli", exp.Literal.number(0))
775
776            return rename_func("DATETIMEFROMPARTS")(self, expression)
777
778        def set_operation(self, expression: exp.Union, op: str) -> str:
779            limit = expression.args.get("limit")
780            if limit:
781                return self.sql(expression.limit(limit.pop(), copy=False))
782
783            return super().set_operation(expression, op)
784
785        def setitem_sql(self, expression: exp.SetItem) -> str:
786            this = expression.this
787            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
788                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
789                return f"{self.sql(this.left)} {self.sql(this.right)}"
790
791            return super().setitem_sql(expression)
792
793        def boolean_sql(self, expression: exp.Boolean) -> str:
794            if type(expression.parent) in BIT_TYPES:
795                return "1" if expression.this else "0"
796
797            return "(1 = 1)" if expression.this else "(1 = 0)"
798
799        def is_sql(self, expression: exp.Is) -> str:
800            if isinstance(expression.expression, exp.Boolean):
801                return self.binary(expression, "=")
802            return self.binary(expression, "IS")
803
804        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
805            sql = self.sql(expression, "this")
806            properties = expression.args.get("properties")
807
808            if sql[:1] != "#" and any(
809                isinstance(prop, exp.TemporaryProperty)
810                for prop in (properties.expressions if properties else [])
811            ):
812                sql = f"#{sql}"
813
814            return sql
815
816        def create_sql(self, expression: exp.Create) -> str:
817            kind = self.sql(expression, "kind").upper()
818            exists = expression.args.pop("exists", None)
819            sql = super().create_sql(expression)
820
821            table = expression.find(exp.Table)
822
823            # Convert CTAS statement to SELECT .. INTO ..
824            if kind == "TABLE" and expression.expression:
825                ctas_with = expression.expression.args.get("with")
826                if ctas_with:
827                    ctas_with = ctas_with.pop()
828
829                subquery = expression.expression
830                if isinstance(subquery, exp.Subqueryable):
831                    subquery = subquery.subquery()
832
833                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
834                select_into.set("into", exp.Into(this=table))
835                select_into.set("with", ctas_with)
836
837                sql = self.sql(select_into)
838
839            if exists:
840                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
841                sql = self.sql(exp.Literal.string(sql))
842                if kind == "SCHEMA":
843                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
844                elif kind == "TABLE":
845                    assert table
846                    where = exp.and_(
847                        exp.column("table_name").eq(table.name),
848                        exp.column("table_schema").eq(table.db) if table.db else None,
849                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
850                    )
851                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
852                elif kind == "INDEX":
853                    index = self.sql(exp.Literal.string(expression.this.text("this")))
854                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
855            elif expression.args.get("replace"):
856                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
857
858            return self.prepend_ctes(expression, sql)
859
860        def offset_sql(self, expression: exp.Offset) -> str:
861            return f"{super().offset_sql(expression)} ROWS"
862
863        def version_sql(self, expression: exp.Version) -> str:
864            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
865            this = f"FOR {name}"
866            expr = expression.expression
867            kind = expression.text("kind")
868            if kind in ("FROM", "BETWEEN"):
869                args = expr.expressions
870                sep = "TO" if kind == "FROM" else "AND"
871                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
872            else:
873                expr_sql = self.sql(expr)
874
875            expr_sql = f" {expr_sql}" if expr_sql else ""
876            return f"{this} {kind}{expr_sql}"
877
878        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
879            table = expression.args.get("table")
880            table = f"{table} " if table else ""
881            return f"RETURNS {table}{self.sql(expression, 'this')}"
882
883        def returning_sql(self, expression: exp.Returning) -> str:
884            into = self.sql(expression, "into")
885            into = self.seg(f"INTO {into}") if into else ""
886            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
887
888        def transaction_sql(self, expression: exp.Transaction) -> str:
889            this = self.sql(expression, "this")
890            this = f" {this}" if this else ""
891            mark = self.sql(expression, "mark")
892            mark = f" WITH MARK {mark}" if mark else ""
893            return f"BEGIN TRANSACTION{this}{mark}"
894
895        def commit_sql(self, expression: exp.Commit) -> str:
896            this = self.sql(expression, "this")
897            this = f" {this}" if this else ""
898            durability = expression.args.get("durability")
899            durability = (
900                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
901                if durability is not None
902                else ""
903            )
904            return f"COMMIT TRANSACTION{this}{durability}"
905
906        def rollback_sql(self, expression: exp.Rollback) -> str:
907            this = self.sql(expression, "this")
908            this = f" {this}" if this else ""
909            return f"ROLLBACK TRANSACTION{this}"
910
911        def identifier_sql(self, expression: exp.Identifier) -> str:
912            identifier = super().identifier_sql(expression)
913
914            if expression.args.get("global"):
915                identifier = f"##{identifier}"
916            elif expression.args.get("temporary"):
917                identifier = f"#{identifier}"
918
919            return identifier
920
921        def constraint_sql(self, expression: exp.Constraint) -> str:
922            this = self.sql(expression, "this")
923            expressions = self.expressions(expression, flat=True, sep=" ")
924            return f"CONSTRAINT {this} {expressions}"
NORMALIZATION_STRATEGY = <NormalizationStrategy.CASE_INSENSITIVE: 'CASE_INSENSITIVE'>

Specifies the strategy according to which identifiers should be normalized.

TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
SUPPORTS_SEMI_ANTI_JOIN = False

Determines whether or not SEMI or ANTI joins are supported.

LOG_BASE_FIRST = False

Determines whether the base comes first in the LOG function.

TYPED_DIVISION = True

Whether the behavior of a / b depends on the types of a and b. False means a / b is always float division. True means a / b is integer division if both a and b are integers.

CONCAT_COALESCE = True

A NULL arg in CONCAT yields NULL by default, but in some dialects it yields an empty string.

TIME_MAPPING: Dict[str, str] = {'year': '%Y', 'dayofyear': '%j', 'day': '%d', 'dy': '%d', 'y': '%Y', 'week': '%W', 'ww': '%W', 'wk': '%W', 'hour': '%h', 'hh': '%I', 'minute': '%M', 'mi': '%M', 'n': '%M', 'second': '%S', 'ss': '%S', 's': '%-S', 'millisecond': '%f', 'ms': '%f', 'weekday': '%W', 'dw': '%W', 'month': '%m', 'mm': '%M', 'm': '%-M', 'Y': '%Y', 'YYYY': '%Y', 'YY': '%y', 'MMMM': '%B', 'MMM': '%b', 'MM': '%m', 'M': '%-m', 'dddd': '%A', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}

Associates this dialect's time formats with their equivalent Python strftime format.

CONVERT_FORMAT_MAPPING = {'0': '%b %d %Y %-I:%M%p', '1': '%m/%d/%y', '2': '%y.%m.%d', '3': '%d/%m/%y', '4': '%d.%m.%y', '5': '%d-%m-%y', '6': '%d %b %y', '7': '%b %d, %y', '8': '%H:%M:%S', '9': '%b %d %Y %-I:%M:%S:%f%p', '10': 'mm-dd-yy', '11': 'yy/mm/dd', '12': 'yymmdd', '13': '%d %b %Y %H:%M:ss:%f', '14': '%H:%M:%S:%f', '20': '%Y-%m-%d %H:%M:%S', '21': '%Y-%m-%d %H:%M:%S.%f', '22': '%m/%d/%y %-I:%M:%S %p', '23': '%Y-%m-%d', '24': '%H:%M:%S', '25': '%Y-%m-%d %H:%M:%S.%f', '100': '%b %d %Y %-I:%M%p', '101': '%m/%d/%Y', '102': '%Y.%m.%d', '103': '%d/%m/%Y', '104': '%d.%m.%Y', '105': '%d-%m-%Y', '106': '%d %b %Y', '107': '%b %d, %Y', '108': '%H:%M:%S', '109': '%b %d %Y %-I:%M:%S:%f%p', '110': '%m-%d-%Y', '111': '%Y/%m/%d', '112': '%Y%m%d', '113': '%d %b %Y %H:%M:%S:%f', '114': '%H:%M:%S:%f', '120': '%Y-%m-%d %H:%M:%S', '121': '%Y-%m-%d %H:%M:%S.%f'}
FORMAT_TIME_MAPPING = {'y': '%B %Y', 'd': '%m/%d/%Y', 'H': '%-H', 'h': '%-I', 's': '%Y-%m-%d %H:%M:%S', 'D': '%A,%B,%Y', 'f': '%A,%B,%Y %-I:%M %p', 'F': '%A,%B,%Y %-I:%M:%S %p', 'g': '%m/%d/%Y %-I:%M %p', 'G': '%m/%d/%Y %-I:%M:%S %p', 'M': '%B %-d', 'm': '%B %-d', 'O': '%Y-%m-%dT%H:%M:%S', 'u': '%Y-%M-%D %H:%M:%S%z', 'U': '%A, %B %D, %Y %H:%M:%S%z', 'T': '%-I:%M:%S %p', 't': '%-I:%M', 'Y': '%a %Y'}
tokenizer_class = <class 'TSQL.Tokenizer'>
parser_class = <class 'TSQL.Parser'>
generator_class = <class 'TSQL.Generator'>
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
FORMAT_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
INVERSE_TIME_MAPPING: Dict[str, str] = {'%Y': 'yyyy', '%j': 'dayofyear', '%d': 'dd', '%W': 'dw', '%h': 'hour', '%I': 'hh', '%M': 'mm', '%S': 'ss', '%-S': 's', '%f': 'S', '%m': 'MM', '%-M': 'm', '%y': 'yy', '%B': 'MMMM', '%b': 'MMM', '%-m': 'M', '%A': 'dddd', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict = {'%': {'Y': {0: True}, 'j': {0: True}, 'd': {0: True}, 'W': {0: True}, 'h': {0: True}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, '-': {'S': {0: True}, 'M': {0: True}, 'm': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'f': {0: True}, 'm': {0: True}, 'y': {0: True}, 'B': {0: True}, 'b': {0: True}, 'A': {0: True}, 'H': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '['
IDENTIFIER_END = ']'
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
UNICODE_START: Optional[str] = None
UNICODE_END: Optional[str] = None
class TSQL.Tokenizer(sqlglot.tokens.Tokenizer):
380    class Tokenizer(tokens.Tokenizer):
381        IDENTIFIERS = [("[", "]"), '"']
382        QUOTES = ["'", '"']
383        HEX_STRINGS = [("0x", ""), ("0X", "")]
384        VAR_SINGLE_TOKENS = {"@", "$", "#"}
385
386        KEYWORDS = {
387            **tokens.Tokenizer.KEYWORDS,
388            "DATETIME2": TokenType.DATETIME,
389            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
390            "DECLARE": TokenType.COMMAND,
391            "EXEC": TokenType.COMMAND,
392            "IMAGE": TokenType.IMAGE,
393            "MONEY": TokenType.MONEY,
394            "NTEXT": TokenType.TEXT,
395            "NVARCHAR(MAX)": TokenType.TEXT,
396            "PRINT": TokenType.COMMAND,
397            "PROC": TokenType.PROCEDURE,
398            "REAL": TokenType.FLOAT,
399            "ROWVERSION": TokenType.ROWVERSION,
400            "SMALLDATETIME": TokenType.DATETIME,
401            "SMALLMONEY": TokenType.SMALLMONEY,
402            "SQL_VARIANT": TokenType.VARIANT,
403            "TOP": TokenType.TOP,
404            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
405            "UPDATE STATISTICS": TokenType.COMMAND,
406            "VARCHAR(MAX)": TokenType.TEXT,
407            "XML": TokenType.XML,
408            "OUTPUT": TokenType.RETURNING,
409            "SYSTEM_USER": TokenType.CURRENT_USER,
410            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
411        }
IDENTIFIERS = [('[', ']'), '"']
QUOTES = ["'", '"']
HEX_STRINGS = [('0x', ''), ('0X', '')]
VAR_SINGLE_TOKENS = {'#', '$', '@'}
KEYWORDS = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'EXEC': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, 'NVARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'PRINT': <TokenType.COMMAND: 'COMMAND'>, 'PROC': <TokenType.PROCEDURE: 'PROCEDURE'>, 'ROWVERSION': <TokenType.ROWVERSION: 'ROWVERSION'>, 'SMALLDATETIME': <TokenType.DATETIME: 'DATETIME'>, 'SMALLMONEY': <TokenType.SMALLMONEY: 'SMALLMONEY'>, 'SQL_VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'TOP': <TokenType.TOP: 'TOP'>, 'UNIQUEIDENTIFIER': <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, 'UPDATE STATISTICS': <TokenType.COMMAND: 'COMMAND'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'FOR SYSTEM_TIME': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}
class TSQL.Parser(sqlglot.parser.Parser):
413    class Parser(parser.Parser):
414        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
415
416        FUNCTIONS = {
417            **parser.Parser.FUNCTIONS,
418            "CHARINDEX": lambda args: exp.StrPosition(
419                this=seq_get(args, 1),
420                substr=seq_get(args, 0),
421                position=seq_get(args, 2),
422            ),
423            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
424            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
425            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
426            "DATEPART": _format_time_lambda(exp.TimeToStr),
427            "DATETIMEFROMPARTS": _parse_datetimefromparts,
428            "EOMONTH": _parse_eomonth,
429            "FORMAT": _parse_format,
430            "GETDATE": exp.CurrentTimestamp.from_arg_list,
431            "HASHBYTES": _parse_hashbytes,
432            "IIF": exp.If.from_arg_list,
433            "ISNULL": exp.Coalesce.from_arg_list,
434            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
435            "LEN": exp.Length.from_arg_list,
436            "REPLICATE": exp.Repeat.from_arg_list,
437            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
438            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
439            "SUSER_NAME": exp.CurrentUser.from_arg_list,
440            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
441            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
442            "TIMEFROMPARTS": _parse_timefromparts,
443        }
444
445        JOIN_HINTS = {
446            "LOOP",
447            "HASH",
448            "MERGE",
449            "REMOTE",
450        }
451
452        VAR_LENGTH_DATATYPES = {
453            DataType.Type.NVARCHAR,
454            DataType.Type.VARCHAR,
455            DataType.Type.CHAR,
456            DataType.Type.NCHAR,
457        }
458
459        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
460            TokenType.TABLE,
461            *parser.Parser.TYPE_TOKENS,
462        }
463
464        STATEMENT_PARSERS = {
465            **parser.Parser.STATEMENT_PARSERS,
466            TokenType.END: lambda self: self._parse_command(),
467        }
468
469        LOG_DEFAULTS_TO_LN = True
470
471        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
472        STRING_ALIASES = True
473
474        def _parse_projections(self) -> t.List[exp.Expression]:
475            """
476            T-SQL supports the syntax alias = expression in the SELECT's projection list,
477            so we transform all parsed Selects to convert their EQ projections into Aliases.
478
479            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
480            """
481            return [
482                exp.alias_(projection.expression, projection.this.this, copy=False)
483                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
484                else projection
485                for projection in super()._parse_projections()
486            ]
487
488        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
489            """Applies to SQL Server and Azure SQL Database
490            COMMIT [ { TRAN | TRANSACTION }
491                [ transaction_name | @tran_name_variable ] ]
492                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
493
494            ROLLBACK { TRAN | TRANSACTION }
495                [ transaction_name | @tran_name_variable
496                | savepoint_name | @savepoint_variable ]
497            """
498            rollback = self._prev.token_type == TokenType.ROLLBACK
499
500            self._match_texts(("TRAN", "TRANSACTION"))
501            this = self._parse_id_var()
502
503            if rollback:
504                return self.expression(exp.Rollback, this=this)
505
506            durability = None
507            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
508                self._match_text_seq("DELAYED_DURABILITY")
509                self._match(TokenType.EQ)
510
511                if self._match_text_seq("OFF"):
512                    durability = False
513                else:
514                    self._match(TokenType.ON)
515                    durability = True
516
517                self._match_r_paren()
518
519            return self.expression(exp.Commit, this=this, durability=durability)
520
521        def _parse_transaction(self) -> exp.Transaction | exp.Command:
522            """Applies to SQL Server and Azure SQL Database
523            BEGIN { TRAN | TRANSACTION }
524            [ { transaction_name | @tran_name_variable }
525            [ WITH MARK [ 'description' ] ]
526            ]
527            """
528            if self._match_texts(("TRAN", "TRANSACTION")):
529                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
530                if self._match_text_seq("WITH", "MARK"):
531                    transaction.set("mark", self._parse_string())
532
533                return transaction
534
535            return self._parse_as_command(self._prev)
536
537        def _parse_returns(self) -> exp.ReturnsProperty:
538            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
539            returns = super()._parse_returns()
540            returns.set("table", table)
541            return returns
542
543        def _parse_convert(
544            self, strict: bool, safe: t.Optional[bool] = None
545        ) -> t.Optional[exp.Expression]:
546            to = self._parse_types()
547            self._match(TokenType.COMMA)
548            this = self._parse_conjunction()
549
550            if not to or not this:
551                return None
552
553            # Retrieve length of datatype and override to default if not specified
554            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
555                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
556
557            # Check whether a conversion with format is applicable
558            if self._match(TokenType.COMMA):
559                format_val = self._parse_number()
560                format_val_name = format_val.name if format_val else ""
561
562                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
563                    raise ValueError(
564                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
565                    )
566
567                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
568
569                # Check whether the convert entails a string to date format
570                if to.this == DataType.Type.DATE:
571                    return self.expression(exp.StrToDate, this=this, format=format_norm)
572                # Check whether the convert entails a string to datetime format
573                elif to.this == DataType.Type.DATETIME:
574                    return self.expression(exp.StrToTime, this=this, format=format_norm)
575                # Check whether the convert entails a date to string format
576                elif to.this in self.VAR_LENGTH_DATATYPES:
577                    return self.expression(
578                        exp.Cast if strict else exp.TryCast,
579                        to=to,
580                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
581                        safe=safe,
582                    )
583                elif to.this == DataType.Type.TEXT:
584                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
585
586            # Entails a simple cast without any format requirement
587            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
588
589        def _parse_user_defined_function(
590            self, kind: t.Optional[TokenType] = None
591        ) -> t.Optional[exp.Expression]:
592            this = super()._parse_user_defined_function(kind=kind)
593
594            if (
595                kind == TokenType.FUNCTION
596                or isinstance(this, exp.UserDefinedFunction)
597                or self._match(TokenType.ALIAS, advance=False)
598            ):
599                return this
600
601            expressions = self._parse_csv(self._parse_function_parameter)
602            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
603
604        def _parse_id_var(
605            self,
606            any_token: bool = True,
607            tokens: t.Optional[t.Collection[TokenType]] = None,
608        ) -> t.Optional[exp.Expression]:
609            is_temporary = self._match(TokenType.HASH)
610            is_global = is_temporary and self._match(TokenType.HASH)
611
612            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
613            if this:
614                if is_global:
615                    this.set("global", True)
616                elif is_temporary:
617                    this.set("temporary", True)
618
619            return this
620
621        def _parse_create(self) -> exp.Create | exp.Command:
622            create = super()._parse_create()
623
624            if isinstance(create, exp.Create):
625                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
626                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
627                    if not create.args.get("properties"):
628                        create.set("properties", exp.Properties(expressions=[]))
629
630                    create.args["properties"].append("expressions", exp.TemporaryProperty())
631
632            return create
633
634        def _parse_if(self) -> t.Optional[exp.Expression]:
635            index = self._index
636
637            if self._match_text_seq("OBJECT_ID"):
638                self._parse_wrapped_csv(self._parse_string)
639                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
640                    return self._parse_drop(exists=True)
641                self._retreat(index)
642
643            return super()._parse_if()
644
645        def _parse_unique(self) -> exp.UniqueColumnConstraint:
646            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
647                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
648            else:
649                this = self._parse_schema(self._parse_id_var(any_token=False))
650
651            return self.expression(exp.UniqueColumnConstraint, this=this)

Parser consumes a list of tokens produced by the Tokenizer and produces a parsed syntax tree.

Arguments:
  • error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
  • error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
  • max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
SET_REQUIRES_ASSIGNMENT_DELIMITER = False
FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANONYMOUS_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnonymousAggFunc'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'ARRAY_UNIQUE_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUniqueAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'COMBINED_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedAggFunc'>>, 'COMBINED_PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedParameterizedAgg'>>, 'CONCAT': <function Parser.<lambda>>, 'CONCAT_WS': <function Parser.<lambda>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'COUNTIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GET_PATH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GetPath'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_INF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'ISINF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <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': <function parse_logarithm>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NULLIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nullif'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RAND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDOM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Randn'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeFromParts'>>, 'TIMEFROMPARTS': <function _parse_timefromparts>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMPFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToArray'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsDiff'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'TS_OR_DS_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToTime'>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixDate'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'DATETIMEFROMPARTS': <function _parse_datetimefromparts>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
JOIN_HINTS = {'LOOP', 'HASH', 'MERGE', 'REMOTE'}
VAR_LENGTH_DATATYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.MODEL: 'MODEL'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.ROWS: 'ROWS'>, <TokenType.ALL: 'ALL'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.DELETE: 'DELETE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ANY: 'ANY'>, <TokenType.NEXT: 'NEXT'>, <TokenType.LOAD: 'LOAD'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.CASE: 'CASE'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.FALSE: 'FALSE'>, <TokenType.KILL: 'KILL'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.SET: 'SET'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ROW: 'ROW'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.DIV: 'DIV'>, <TokenType.MERGE: 'MERGE'>, <TokenType.KEEP: 'KEEP'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.CACHE: 'CACHE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.FINAL: 'FINAL'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.VAR: 'VAR'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.ANTI: 'ANTI'>, <TokenType.USE: 'USE'>, <TokenType.SOME: 'SOME'>, <TokenType.SEMI: 'SEMI'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.FULL: 'FULL'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.FILTER: 'FILTER'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.ASC: 'ASC'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.APPLY: 'APPLY'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.IS: 'IS'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.END: 'END'>, <TokenType.TOP: 'TOP'>, <TokenType.VIEW: 'VIEW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.LEFT: 'LEFT'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.TRUE: 'TRUE'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.DESC: 'DESC'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.FORMAT: 'FORMAT'>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.REFRESH: 'REFRESH'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
LOG_DEFAULTS_TO_LN = True
ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
STRING_ALIASES = True
TABLE_ALIAS_TOKENS = {<TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.INT256: 'INT256'>, <TokenType.TEXT: 'TEXT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.MODEL: 'MODEL'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.ALL: 'ALL'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.BINARY: 'BINARY'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.DELETE: 'DELETE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.UINT128: 'UINT128'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.NESTED: 'NESTED'>, <TokenType.BIT: 'BIT'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ANY: 'ANY'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.NEXT: 'NEXT'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.JSONB: 'JSONB'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.CASE: 'CASE'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.FALSE: 'FALSE'>, <TokenType.KILL: 'KILL'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.UUID: 'UUID'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.SET: 'SET'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.INET: 'INET'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.INT: 'INT'>, <TokenType.ROW: 'ROW'>, <TokenType.DATE: 'DATE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.DIV: 'DIV'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.UINT: 'UINT'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.MERGE: 'MERGE'>, <TokenType.JSON: 'JSON'>, <TokenType.KEEP: 'KEEP'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.CACHE: 'CACHE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.FINAL: 'FINAL'>, <TokenType.XML: 'XML'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.ENUM: 'ENUM'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.VAR: 'VAR'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.ANTI: 'ANTI'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.USE: 'USE'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.SOME: 'SOME'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.TABLE: 'TABLE'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.FILTER: 'FILTER'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.ASC: 'ASC'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.MONEY: 'MONEY'>, <TokenType.INT128: 'INT128'>, <TokenType.UINT256: 'UINT256'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.IS: 'IS'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.END: 'END'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.NULL: 'NULL'>, <TokenType.MAP: 'MAP'>, <TokenType.TOP: 'TOP'>, <TokenType.VIEW: 'VIEW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.TRUE: 'TRUE'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.DESC: 'DESC'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.TIME: 'TIME'>, <TokenType.CHAR: 'CHAR'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.SUPER: 'SUPER'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>}
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
class TSQL.Generator(sqlglot.generator.Generator):
653    class Generator(generator.Generator):
654        LIMIT_IS_TOP = True
655        QUERY_HINTS = False
656        RETURNING_END = False
657        NVL2_SUPPORTED = False
658        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
659        LIMIT_FETCH = "FETCH"
660        COMPUTED_COLUMN_WITH_TYPE = False
661        CTE_RECURSIVE_KEYWORD_REQUIRED = False
662        ENSURE_BOOLS = True
663        NULL_ORDERING_SUPPORTED = False
664        SUPPORTS_SINGLE_ARG_CONCAT = False
665        TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
666
667        EXPRESSIONS_WITHOUT_NESTED_CTES = {
668            exp.Delete,
669            exp.Insert,
670            exp.Merge,
671            exp.Select,
672            exp.Subquery,
673            exp.Union,
674            exp.Update,
675        }
676
677        TYPE_MAPPING = {
678            **generator.Generator.TYPE_MAPPING,
679            exp.DataType.Type.BOOLEAN: "BIT",
680            exp.DataType.Type.DECIMAL: "NUMERIC",
681            exp.DataType.Type.DATETIME: "DATETIME2",
682            exp.DataType.Type.DOUBLE: "FLOAT",
683            exp.DataType.Type.INT: "INTEGER",
684            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
685            exp.DataType.Type.TIMESTAMP: "DATETIME2",
686            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
687            exp.DataType.Type.VARIANT: "SQL_VARIANT",
688        }
689
690        TRANSFORMS = {
691            **generator.Generator.TRANSFORMS,
692            exp.AnyValue: any_value_to_max_sql,
693            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
694            exp.DateAdd: date_delta_sql("DATEADD"),
695            exp.DateDiff: date_delta_sql("DATEDIFF"),
696            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
697            exp.CurrentDate: rename_func("GETDATE"),
698            exp.CurrentTimestamp: rename_func("GETDATE"),
699            exp.Extract: rename_func("DATEPART"),
700            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
701            exp.GetPath: path_to_jsonpath("JSON_VALUE"),
702            exp.GroupConcat: _string_agg_sql,
703            exp.If: rename_func("IIF"),
704            exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
705            exp.Length: rename_func("LEN"),
706            exp.Max: max_or_greatest,
707            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
708            exp.Min: min_or_least,
709            exp.NumberToStr: _format_sql,
710            exp.ParseJSON: lambda self, e: self.sql(e, "this"),
711            exp.Select: transforms.preprocess(
712                [
713                    transforms.eliminate_distinct_on,
714                    transforms.eliminate_semi_and_anti_joins,
715                    transforms.eliminate_qualify,
716                ]
717            ),
718            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
719            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
720            exp.SHA2: lambda self, e: self.func(
721                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
722            ),
723            exp.TemporaryProperty: lambda self, e: "",
724            exp.TimeStrToTime: timestrtotime_sql,
725            exp.TimeToStr: _format_sql,
726            exp.Trim: trim_sql,
727            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
728            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
729        }
730
731        TRANSFORMS.pop(exp.ReturnsProperty)
732
733        PROPERTIES_LOCATION = {
734            **generator.Generator.PROPERTIES_LOCATION,
735            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
736        }
737
738        def lateral_op(self, expression: exp.Lateral) -> str:
739            cross_apply = expression.args.get("cross_apply")
740            if cross_apply is True:
741                return "CROSS APPLY"
742            if cross_apply is False:
743                return "OUTER APPLY"
744
745            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
746            self.unsupported("LATERAL clause is not supported.")
747            return "LATERAL"
748
749        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
750            nano = expression.args.get("nano")
751            if nano is not None:
752                nano.pop()
753                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
754
755            if expression.args.get("fractions") is None:
756                expression.set("fractions", exp.Literal.number(0))
757            if expression.args.get("precision") is None:
758                expression.set("precision", exp.Literal.number(0))
759
760            return rename_func("TIMEFROMPARTS")(self, expression)
761
762        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
763            zone = expression.args.get("zone")
764            if zone is not None:
765                zone.pop()
766                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
767
768            nano = expression.args.get("nano")
769            if nano is not None:
770                nano.pop()
771                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
772
773            if expression.args.get("milli") is None:
774                expression.set("milli", exp.Literal.number(0))
775
776            return rename_func("DATETIMEFROMPARTS")(self, expression)
777
778        def set_operation(self, expression: exp.Union, op: str) -> str:
779            limit = expression.args.get("limit")
780            if limit:
781                return self.sql(expression.limit(limit.pop(), copy=False))
782
783            return super().set_operation(expression, op)
784
785        def setitem_sql(self, expression: exp.SetItem) -> str:
786            this = expression.this
787            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
788                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
789                return f"{self.sql(this.left)} {self.sql(this.right)}"
790
791            return super().setitem_sql(expression)
792
793        def boolean_sql(self, expression: exp.Boolean) -> str:
794            if type(expression.parent) in BIT_TYPES:
795                return "1" if expression.this else "0"
796
797            return "(1 = 1)" if expression.this else "(1 = 0)"
798
799        def is_sql(self, expression: exp.Is) -> str:
800            if isinstance(expression.expression, exp.Boolean):
801                return self.binary(expression, "=")
802            return self.binary(expression, "IS")
803
804        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
805            sql = self.sql(expression, "this")
806            properties = expression.args.get("properties")
807
808            if sql[:1] != "#" and any(
809                isinstance(prop, exp.TemporaryProperty)
810                for prop in (properties.expressions if properties else [])
811            ):
812                sql = f"#{sql}"
813
814            return sql
815
816        def create_sql(self, expression: exp.Create) -> str:
817            kind = self.sql(expression, "kind").upper()
818            exists = expression.args.pop("exists", None)
819            sql = super().create_sql(expression)
820
821            table = expression.find(exp.Table)
822
823            # Convert CTAS statement to SELECT .. INTO ..
824            if kind == "TABLE" and expression.expression:
825                ctas_with = expression.expression.args.get("with")
826                if ctas_with:
827                    ctas_with = ctas_with.pop()
828
829                subquery = expression.expression
830                if isinstance(subquery, exp.Subqueryable):
831                    subquery = subquery.subquery()
832
833                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
834                select_into.set("into", exp.Into(this=table))
835                select_into.set("with", ctas_with)
836
837                sql = self.sql(select_into)
838
839            if exists:
840                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
841                sql = self.sql(exp.Literal.string(sql))
842                if kind == "SCHEMA":
843                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
844                elif kind == "TABLE":
845                    assert table
846                    where = exp.and_(
847                        exp.column("table_name").eq(table.name),
848                        exp.column("table_schema").eq(table.db) if table.db else None,
849                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
850                    )
851                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
852                elif kind == "INDEX":
853                    index = self.sql(exp.Literal.string(expression.this.text("this")))
854                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
855            elif expression.args.get("replace"):
856                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
857
858            return self.prepend_ctes(expression, sql)
859
860        def offset_sql(self, expression: exp.Offset) -> str:
861            return f"{super().offset_sql(expression)} ROWS"
862
863        def version_sql(self, expression: exp.Version) -> str:
864            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
865            this = f"FOR {name}"
866            expr = expression.expression
867            kind = expression.text("kind")
868            if kind in ("FROM", "BETWEEN"):
869                args = expr.expressions
870                sep = "TO" if kind == "FROM" else "AND"
871                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
872            else:
873                expr_sql = self.sql(expr)
874
875            expr_sql = f" {expr_sql}" if expr_sql else ""
876            return f"{this} {kind}{expr_sql}"
877
878        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
879            table = expression.args.get("table")
880            table = f"{table} " if table else ""
881            return f"RETURNS {table}{self.sql(expression, 'this')}"
882
883        def returning_sql(self, expression: exp.Returning) -> str:
884            into = self.sql(expression, "into")
885            into = self.seg(f"INTO {into}") if into else ""
886            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
887
888        def transaction_sql(self, expression: exp.Transaction) -> str:
889            this = self.sql(expression, "this")
890            this = f" {this}" if this else ""
891            mark = self.sql(expression, "mark")
892            mark = f" WITH MARK {mark}" if mark else ""
893            return f"BEGIN TRANSACTION{this}{mark}"
894
895        def commit_sql(self, expression: exp.Commit) -> str:
896            this = self.sql(expression, "this")
897            this = f" {this}" if this else ""
898            durability = expression.args.get("durability")
899            durability = (
900                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
901                if durability is not None
902                else ""
903            )
904            return f"COMMIT TRANSACTION{this}{durability}"
905
906        def rollback_sql(self, expression: exp.Rollback) -> str:
907            this = self.sql(expression, "this")
908            this = f" {this}" if this else ""
909            return f"ROLLBACK TRANSACTION{this}"
910
911        def identifier_sql(self, expression: exp.Identifier) -> str:
912            identifier = super().identifier_sql(expression)
913
914            if expression.args.get("global"):
915                identifier = f"##{identifier}"
916            elif expression.args.get("temporary"):
917                identifier = f"#{identifier}"
918
919            return identifier
920
921        def constraint_sql(self, expression: exp.Constraint) -> str:
922            this = self.sql(expression, "this")
923            expressions = self.expressions(expression, flat=True, sep=" ")
924            return f"CONSTRAINT {this} {expressions}"

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
LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
LIMIT_FETCH = 'FETCH'
COMPUTED_COLUMN_WITH_TYPE = False
CTE_RECURSIVE_KEYWORD_REQUIRED = False
ENSURE_BOOLS = True
NULL_ORDERING_SUPPORTED = False
SUPPORTS_SINGLE_ARG_CONCAT = False
TABLESAMPLE_SEED_KEYWORD = 'REPEATABLE'
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.BOOLEAN: 'BOOLEAN'>: 'BIT', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.DOUBLE: 'DOUBLE'>: 'FLOAT', <Type.INT: 'INT'>: 'INTEGER', <Type.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.AutoIncrementColumnConstraint'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Extract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.GetPath'>: <function path_to_jsonpath.<locals>._transform>, <class 'sqlglot.expressions.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.LastDay'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Length'>: <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.ParseJSON'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.SHA'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.SHA2'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
def lateral_op(self, expression: sqlglot.expressions.Lateral) -> str:
738        def lateral_op(self, expression: exp.Lateral) -> str:
739            cross_apply = expression.args.get("cross_apply")
740            if cross_apply is True:
741                return "CROSS APPLY"
742            if cross_apply is False:
743                return "OUTER APPLY"
744
745            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
746            self.unsupported("LATERAL clause is not supported.")
747            return "LATERAL"
def timefromparts_sql(self, expression: sqlglot.expressions.TimeFromParts) -> str:
749        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
750            nano = expression.args.get("nano")
751            if nano is not None:
752                nano.pop()
753                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
754
755            if expression.args.get("fractions") is None:
756                expression.set("fractions", exp.Literal.number(0))
757            if expression.args.get("precision") is None:
758                expression.set("precision", exp.Literal.number(0))
759
760            return rename_func("TIMEFROMPARTS")(self, expression)
def timestampfromparts_sql(self, expression: sqlglot.expressions.TimestampFromParts) -> str:
762        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
763            zone = expression.args.get("zone")
764            if zone is not None:
765                zone.pop()
766                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
767
768            nano = expression.args.get("nano")
769            if nano is not None:
770                nano.pop()
771                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
772
773            if expression.args.get("milli") is None:
774                expression.set("milli", exp.Literal.number(0))
775
776            return rename_func("DATETIMEFROMPARTS")(self, expression)
def set_operation(self, expression: sqlglot.expressions.Union, op: str) -> str:
778        def set_operation(self, expression: exp.Union, op: str) -> str:
779            limit = expression.args.get("limit")
780            if limit:
781                return self.sql(expression.limit(limit.pop(), copy=False))
782
783            return super().set_operation(expression, op)
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
785        def setitem_sql(self, expression: exp.SetItem) -> str:
786            this = expression.this
787            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
788                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
789                return f"{self.sql(this.left)} {self.sql(this.right)}"
790
791            return super().setitem_sql(expression)
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
793        def boolean_sql(self, expression: exp.Boolean) -> str:
794            if type(expression.parent) in BIT_TYPES:
795                return "1" if expression.this else "0"
796
797            return "(1 = 1)" if expression.this else "(1 = 0)"
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
799        def is_sql(self, expression: exp.Is) -> str:
800            if isinstance(expression.expression, exp.Boolean):
801                return self.binary(expression, "=")
802            return self.binary(expression, "IS")
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
804        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
805            sql = self.sql(expression, "this")
806            properties = expression.args.get("properties")
807
808            if sql[:1] != "#" and any(
809                isinstance(prop, exp.TemporaryProperty)
810                for prop in (properties.expressions if properties else [])
811            ):
812                sql = f"#{sql}"
813
814            return sql
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
816        def create_sql(self, expression: exp.Create) -> str:
817            kind = self.sql(expression, "kind").upper()
818            exists = expression.args.pop("exists", None)
819            sql = super().create_sql(expression)
820
821            table = expression.find(exp.Table)
822
823            # Convert CTAS statement to SELECT .. INTO ..
824            if kind == "TABLE" and expression.expression:
825                ctas_with = expression.expression.args.get("with")
826                if ctas_with:
827                    ctas_with = ctas_with.pop()
828
829                subquery = expression.expression
830                if isinstance(subquery, exp.Subqueryable):
831                    subquery = subquery.subquery()
832
833                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
834                select_into.set("into", exp.Into(this=table))
835                select_into.set("with", ctas_with)
836
837                sql = self.sql(select_into)
838
839            if exists:
840                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
841                sql = self.sql(exp.Literal.string(sql))
842                if kind == "SCHEMA":
843                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
844                elif kind == "TABLE":
845                    assert table
846                    where = exp.and_(
847                        exp.column("table_name").eq(table.name),
848                        exp.column("table_schema").eq(table.db) if table.db else None,
849                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
850                    )
851                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
852                elif kind == "INDEX":
853                    index = self.sql(exp.Literal.string(expression.this.text("this")))
854                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
855            elif expression.args.get("replace"):
856                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
857
858            return self.prepend_ctes(expression, sql)
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
860        def offset_sql(self, expression: exp.Offset) -> str:
861            return f"{super().offset_sql(expression)} ROWS"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
863        def version_sql(self, expression: exp.Version) -> str:
864            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
865            this = f"FOR {name}"
866            expr = expression.expression
867            kind = expression.text("kind")
868            if kind in ("FROM", "BETWEEN"):
869                args = expr.expressions
870                sep = "TO" if kind == "FROM" else "AND"
871                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
872            else:
873                expr_sql = self.sql(expr)
874
875            expr_sql = f" {expr_sql}" if expr_sql else ""
876            return f"{this} {kind}{expr_sql}"
def returnsproperty_sql(self, expression: sqlglot.expressions.ReturnsProperty) -> str:
878        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
879            table = expression.args.get("table")
880            table = f"{table} " if table else ""
881            return f"RETURNS {table}{self.sql(expression, 'this')}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
883        def returning_sql(self, expression: exp.Returning) -> str:
884            into = self.sql(expression, "into")
885            into = self.seg(f"INTO {into}") if into else ""
886            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
888        def transaction_sql(self, expression: exp.Transaction) -> str:
889            this = self.sql(expression, "this")
890            this = f" {this}" if this else ""
891            mark = self.sql(expression, "mark")
892            mark = f" WITH MARK {mark}" if mark else ""
893            return f"BEGIN TRANSACTION{this}{mark}"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
895        def commit_sql(self, expression: exp.Commit) -> str:
896            this = self.sql(expression, "this")
897            this = f" {this}" if this else ""
898            durability = expression.args.get("durability")
899            durability = (
900                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
901                if durability is not None
902                else ""
903            )
904            return f"COMMIT TRANSACTION{this}{durability}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
906        def rollback_sql(self, expression: exp.Rollback) -> str:
907            this = self.sql(expression, "this")
908            this = f" {this}" if this else ""
909            return f"ROLLBACK TRANSACTION{this}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
911        def identifier_sql(self, expression: exp.Identifier) -> str:
912            identifier = super().identifier_sql(expression)
913
914            if expression.args.get("global"):
915                identifier = f"##{identifier}"
916            elif expression.args.get("temporary"):
917                identifier = f"#{identifier}"
918
919            return identifier
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
921        def constraint_sql(self, expression: exp.Constraint) -> str:
922            this = self.sql(expression, "this")
923            expressions = self.expressions(expression, flat=True, sep=" ")
924            return f"CONSTRAINT {this} {expressions}"
SELECT_KINDS: Tuple[str, ...] = ()
Inherited Members
sqlglot.generator.Generator
Generator
LOCKING_READS_SUPPORTED
EXPLICIT_UNION
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SINGLE_STRING_INTERVAL
INTERVAL_ALLOWS_PLURAL_FORM
LIMIT_ONLY_LITERALS
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
INDEX_ON
JOIN_HINTS
TABLE_HINTS
QUERY_HINT_SEP
IS_BOOL_ALLOWED
DUPLICATE_KEY_UPDATE_WITH_SET
COLUMN_JOIN_MARKS_SUPPORTED
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
VALUES_AS_TABLE
UNNEST_WITH_ORDINALITY
AGGREGATE_FILTER_SUPPORTED
SEMI_ANTI_JOIN_WITH_SIDE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
LAST_DAY_SUPPORTS_DATE_PART
SUPPORTS_TABLE_ALIAS_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
STAR_MAPPING
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
PARAMETER_TOKEN
RESERVED_KEYWORDS
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
KEY_VALUE_DEFINITIONS
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
pad_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_sql
columnposition_sql
columndef_sql
columnconstraint_sql
computedcolumnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
transformcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
clone_sql
describe_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_sql
directory_sql
delete_sql
drop_sql
except_sql
except_op
fetch_sql
filter_sql
hint_sql
index_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_name
property_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
intersect_sql
intersect_op
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
group_sql
having_sql
connect_sql
prior_sql
join_sql
lambda_sql
lateral_sql
limit_sql
set_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
order_sql
withfill_sql
cluster_sql
distribute_sql
sort_sql
ordered_sql
matchrecognize_sql
query_modifiers
offset_limit_modifiers
after_having_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
union_sql
union_op
unnest_sql
where_sql
window_sql
partition_by_sql
windowspec_sql
withingroup_sql
between_sql
bracket_sql
all_sql
any_sql
exists_sql
case_sql
nextvaluefor_sql
extract_sql
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
formatjson_sql
jsonobject_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
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
add_column_sql
droppartition_sql
addconstraint_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
intdiv_sql
dpipe_sql
div_sql
overlaps_sql
distance_sql
dot_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
ilike_sql
ilikeany_sql
like_sql
likeany_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
or_sql
slice_sql
sub_sql
trycast_sql
log_sql
use_sql
binary
function_fallback_sql
func
format_args
text_width
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
merge_sql
tochar_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
indexcolumnconstraint_sql
nvl2_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
forin_sql
refresh_sql
operator_sql
toarray_sql
tsordstotime_sql
tsordstodate_sql
unixdate_sql
lastday_sql