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

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

class TSQL(sqlglot.dialects.dialect.Dialect):
243class TSQL(Dialect):
244    NORMALIZATION_STRATEGY = NormalizationStrategy.CASE_INSENSITIVE
245    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
246    SUPPORTS_SEMI_ANTI_JOIN = False
247    LOG_BASE_FIRST = False
248    TYPED_DIVISION = True
249    CONCAT_COALESCE = True
250
251    TIME_MAPPING = {
252        "year": "%Y",
253        "dayofyear": "%j",
254        "day": "%d",
255        "dy": "%d",
256        "y": "%Y",
257        "week": "%W",
258        "ww": "%W",
259        "wk": "%W",
260        "hour": "%h",
261        "hh": "%I",
262        "minute": "%M",
263        "mi": "%M",
264        "n": "%M",
265        "second": "%S",
266        "ss": "%S",
267        "s": "%-S",
268        "millisecond": "%f",
269        "ms": "%f",
270        "weekday": "%W",
271        "dw": "%W",
272        "month": "%m",
273        "mm": "%M",
274        "m": "%-M",
275        "Y": "%Y",
276        "YYYY": "%Y",
277        "YY": "%y",
278        "MMMM": "%B",
279        "MMM": "%b",
280        "MM": "%m",
281        "M": "%-m",
282        "dddd": "%A",
283        "dd": "%d",
284        "d": "%-d",
285        "HH": "%H",
286        "H": "%-H",
287        "h": "%-I",
288        "S": "%f",
289        "yyyy": "%Y",
290        "yy": "%y",
291    }
292
293    CONVERT_FORMAT_MAPPING = {
294        "0": "%b %d %Y %-I:%M%p",
295        "1": "%m/%d/%y",
296        "2": "%y.%m.%d",
297        "3": "%d/%m/%y",
298        "4": "%d.%m.%y",
299        "5": "%d-%m-%y",
300        "6": "%d %b %y",
301        "7": "%b %d, %y",
302        "8": "%H:%M:%S",
303        "9": "%b %d %Y %-I:%M:%S:%f%p",
304        "10": "mm-dd-yy",
305        "11": "yy/mm/dd",
306        "12": "yymmdd",
307        "13": "%d %b %Y %H:%M:ss:%f",
308        "14": "%H:%M:%S:%f",
309        "20": "%Y-%m-%d %H:%M:%S",
310        "21": "%Y-%m-%d %H:%M:%S.%f",
311        "22": "%m/%d/%y %-I:%M:%S %p",
312        "23": "%Y-%m-%d",
313        "24": "%H:%M:%S",
314        "25": "%Y-%m-%d %H:%M:%S.%f",
315        "100": "%b %d %Y %-I:%M%p",
316        "101": "%m/%d/%Y",
317        "102": "%Y.%m.%d",
318        "103": "%d/%m/%Y",
319        "104": "%d.%m.%Y",
320        "105": "%d-%m-%Y",
321        "106": "%d %b %Y",
322        "107": "%b %d, %Y",
323        "108": "%H:%M:%S",
324        "109": "%b %d %Y %-I:%M:%S:%f%p",
325        "110": "%m-%d-%Y",
326        "111": "%Y/%m/%d",
327        "112": "%Y%m%d",
328        "113": "%d %b %Y %H:%M:%S:%f",
329        "114": "%H:%M:%S:%f",
330        "120": "%Y-%m-%d %H:%M:%S",
331        "121": "%Y-%m-%d %H:%M:%S.%f",
332    }
333
334    FORMAT_TIME_MAPPING = {
335        "y": "%B %Y",
336        "d": "%m/%d/%Y",
337        "H": "%-H",
338        "h": "%-I",
339        "s": "%Y-%m-%d %H:%M:%S",
340        "D": "%A,%B,%Y",
341        "f": "%A,%B,%Y %-I:%M %p",
342        "F": "%A,%B,%Y %-I:%M:%S %p",
343        "g": "%m/%d/%Y %-I:%M %p",
344        "G": "%m/%d/%Y %-I:%M:%S %p",
345        "M": "%B %-d",
346        "m": "%B %-d",
347        "O": "%Y-%m-%dT%H:%M:%S",
348        "u": "%Y-%M-%D %H:%M:%S%z",
349        "U": "%A, %B %D, %Y %H:%M:%S%z",
350        "T": "%-I:%M:%S %p",
351        "t": "%-I:%M",
352        "Y": "%a %Y",
353    }
354
355    class Tokenizer(tokens.Tokenizer):
356        IDENTIFIERS = ['"', ("[", "]")]
357        QUOTES = ["'", '"']
358        HEX_STRINGS = [("0x", ""), ("0X", "")]
359        VAR_SINGLE_TOKENS = {"@", "$", "#"}
360
361        KEYWORDS = {
362            **tokens.Tokenizer.KEYWORDS,
363            "DATETIME2": TokenType.DATETIME,
364            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
365            "DECLARE": TokenType.COMMAND,
366            "IMAGE": TokenType.IMAGE,
367            "MONEY": TokenType.MONEY,
368            "NTEXT": TokenType.TEXT,
369            "NVARCHAR(MAX)": TokenType.TEXT,
370            "PRINT": TokenType.COMMAND,
371            "PROC": TokenType.PROCEDURE,
372            "REAL": TokenType.FLOAT,
373            "ROWVERSION": TokenType.ROWVERSION,
374            "SMALLDATETIME": TokenType.DATETIME,
375            "SMALLMONEY": TokenType.SMALLMONEY,
376            "SQL_VARIANT": TokenType.VARIANT,
377            "TOP": TokenType.TOP,
378            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
379            "UPDATE STATISTICS": TokenType.COMMAND,
380            "VARCHAR(MAX)": TokenType.TEXT,
381            "XML": TokenType.XML,
382            "OUTPUT": TokenType.RETURNING,
383            "SYSTEM_USER": TokenType.CURRENT_USER,
384            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
385        }
386
387    class Parser(parser.Parser):
388        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
389
390        FUNCTIONS = {
391            **parser.Parser.FUNCTIONS,
392            "CHARINDEX": lambda args: exp.StrPosition(
393                this=seq_get(args, 1),
394                substr=seq_get(args, 0),
395                position=seq_get(args, 2),
396            ),
397            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
398            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
399            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
400            "DATEPART": _format_time_lambda(exp.TimeToStr),
401            "EOMONTH": _parse_eomonth,
402            "FORMAT": _parse_format,
403            "GETDATE": exp.CurrentTimestamp.from_arg_list,
404            "HASHBYTES": _parse_hashbytes,
405            "IIF": exp.If.from_arg_list,
406            "ISNULL": exp.Coalesce.from_arg_list,
407            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
408            "LEN": exp.Length.from_arg_list,
409            "REPLICATE": exp.Repeat.from_arg_list,
410            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
411            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
412            "SUSER_NAME": exp.CurrentUser.from_arg_list,
413            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
414            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
415        }
416
417        JOIN_HINTS = {
418            "LOOP",
419            "HASH",
420            "MERGE",
421            "REMOTE",
422        }
423
424        VAR_LENGTH_DATATYPES = {
425            DataType.Type.NVARCHAR,
426            DataType.Type.VARCHAR,
427            DataType.Type.CHAR,
428            DataType.Type.NCHAR,
429        }
430
431        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
432            TokenType.TABLE,
433            *parser.Parser.TYPE_TOKENS,
434        }
435
436        STATEMENT_PARSERS = {
437            **parser.Parser.STATEMENT_PARSERS,
438            TokenType.END: lambda self: self._parse_command(),
439        }
440
441        LOG_DEFAULTS_TO_LN = True
442
443        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
444
445        def _parse_projections(self) -> t.List[exp.Expression]:
446            """
447            T-SQL supports the syntax alias = expression in the SELECT's projection list,
448            so we transform all parsed Selects to convert their EQ projections into Aliases.
449
450            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
451            """
452            return [
453                exp.alias_(projection.expression, projection.this.this, copy=False)
454                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
455                else projection
456                for projection in super()._parse_projections()
457            ]
458
459        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
460            """Applies to SQL Server and Azure SQL Database
461            COMMIT [ { TRAN | TRANSACTION }
462                [ transaction_name | @tran_name_variable ] ]
463                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
464
465            ROLLBACK { TRAN | TRANSACTION }
466                [ transaction_name | @tran_name_variable
467                | savepoint_name | @savepoint_variable ]
468            """
469            rollback = self._prev.token_type == TokenType.ROLLBACK
470
471            self._match_texts(("TRAN", "TRANSACTION"))
472            this = self._parse_id_var()
473
474            if rollback:
475                return self.expression(exp.Rollback, this=this)
476
477            durability = None
478            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
479                self._match_text_seq("DELAYED_DURABILITY")
480                self._match(TokenType.EQ)
481
482                if self._match_text_seq("OFF"):
483                    durability = False
484                else:
485                    self._match(TokenType.ON)
486                    durability = True
487
488                self._match_r_paren()
489
490            return self.expression(exp.Commit, this=this, durability=durability)
491
492        def _parse_transaction(self) -> exp.Transaction | exp.Command:
493            """Applies to SQL Server and Azure SQL Database
494            BEGIN { TRAN | TRANSACTION }
495            [ { transaction_name | @tran_name_variable }
496            [ WITH MARK [ 'description' ] ]
497            ]
498            """
499            if self._match_texts(("TRAN", "TRANSACTION")):
500                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
501                if self._match_text_seq("WITH", "MARK"):
502                    transaction.set("mark", self._parse_string())
503
504                return transaction
505
506            return self._parse_as_command(self._prev)
507
508        def _parse_returns(self) -> exp.ReturnsProperty:
509            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
510            returns = super()._parse_returns()
511            returns.set("table", table)
512            return returns
513
514        def _parse_convert(
515            self, strict: bool, safe: t.Optional[bool] = None
516        ) -> t.Optional[exp.Expression]:
517            to = self._parse_types()
518            self._match(TokenType.COMMA)
519            this = self._parse_conjunction()
520
521            if not to or not this:
522                return None
523
524            # Retrieve length of datatype and override to default if not specified
525            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
526                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
527
528            # Check whether a conversion with format is applicable
529            if self._match(TokenType.COMMA):
530                format_val = self._parse_number()
531                format_val_name = format_val.name if format_val else ""
532
533                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
534                    raise ValueError(
535                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
536                    )
537
538                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
539
540                # Check whether the convert entails a string to date format
541                if to.this == DataType.Type.DATE:
542                    return self.expression(exp.StrToDate, this=this, format=format_norm)
543                # Check whether the convert entails a string to datetime format
544                elif to.this == DataType.Type.DATETIME:
545                    return self.expression(exp.StrToTime, this=this, format=format_norm)
546                # Check whether the convert entails a date to string format
547                elif to.this in self.VAR_LENGTH_DATATYPES:
548                    return self.expression(
549                        exp.Cast if strict else exp.TryCast,
550                        to=to,
551                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
552                        safe=safe,
553                    )
554                elif to.this == DataType.Type.TEXT:
555                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
556
557            # Entails a simple cast without any format requirement
558            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
559
560        def _parse_user_defined_function(
561            self, kind: t.Optional[TokenType] = None
562        ) -> t.Optional[exp.Expression]:
563            this = super()._parse_user_defined_function(kind=kind)
564
565            if (
566                kind == TokenType.FUNCTION
567                or isinstance(this, exp.UserDefinedFunction)
568                or self._match(TokenType.ALIAS, advance=False)
569            ):
570                return this
571
572            expressions = self._parse_csv(self._parse_function_parameter)
573            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
574
575        def _parse_id_var(
576            self,
577            any_token: bool = True,
578            tokens: t.Optional[t.Collection[TokenType]] = None,
579        ) -> t.Optional[exp.Expression]:
580            is_temporary = self._match(TokenType.HASH)
581            is_global = is_temporary and self._match(TokenType.HASH)
582
583            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
584            if this:
585                if is_global:
586                    this.set("global", True)
587                elif is_temporary:
588                    this.set("temporary", True)
589
590            return this
591
592        def _parse_create(self) -> exp.Create | exp.Command:
593            create = super()._parse_create()
594
595            if isinstance(create, exp.Create):
596                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
597                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
598                    if not create.args.get("properties"):
599                        create.set("properties", exp.Properties(expressions=[]))
600
601                    create.args["properties"].append("expressions", exp.TemporaryProperty())
602
603            return create
604
605        def _parse_if(self) -> t.Optional[exp.Expression]:
606            index = self._index
607
608            if self._match_text_seq("OBJECT_ID"):
609                self._parse_wrapped_csv(self._parse_string)
610                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
611                    return self._parse_drop(exists=True)
612                self._retreat(index)
613
614            return super()._parse_if()
615
616        def _parse_unique(self) -> exp.UniqueColumnConstraint:
617            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
618                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
619            else:
620                this = self._parse_schema(self._parse_id_var(any_token=False))
621
622            return self.expression(exp.UniqueColumnConstraint, this=this)
623
624    class Generator(generator.Generator):
625        LIMIT_IS_TOP = True
626        QUERY_HINTS = False
627        RETURNING_END = False
628        NVL2_SUPPORTED = False
629        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
630        LIMIT_FETCH = "FETCH"
631        COMPUTED_COLUMN_WITH_TYPE = False
632        CTE_RECURSIVE_KEYWORD_REQUIRED = False
633        ENSURE_BOOLS = True
634        NULL_ORDERING_SUPPORTED = False
635        SUPPORTS_SINGLE_ARG_CONCAT = False
636
637        EXPRESSIONS_WITHOUT_NESTED_CTES = {
638            exp.Delete,
639            exp.Insert,
640            exp.Merge,
641            exp.Select,
642            exp.Subquery,
643            exp.Union,
644            exp.Update,
645        }
646
647        TYPE_MAPPING = {
648            **generator.Generator.TYPE_MAPPING,
649            exp.DataType.Type.BOOLEAN: "BIT",
650            exp.DataType.Type.DECIMAL: "NUMERIC",
651            exp.DataType.Type.DATETIME: "DATETIME2",
652            exp.DataType.Type.DOUBLE: "FLOAT",
653            exp.DataType.Type.INT: "INTEGER",
654            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
655            exp.DataType.Type.TIMESTAMP: "DATETIME2",
656            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
657            exp.DataType.Type.VARIANT: "SQL_VARIANT",
658        }
659
660        TRANSFORMS = {
661            **generator.Generator.TRANSFORMS,
662            exp.AnyValue: any_value_to_max_sql,
663            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
664            exp.DateAdd: date_delta_sql("DATEADD"),
665            exp.DateDiff: date_delta_sql("DATEDIFF"),
666            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
667            exp.CurrentDate: rename_func("GETDATE"),
668            exp.CurrentTimestamp: rename_func("GETDATE"),
669            exp.Extract: rename_func("DATEPART"),
670            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
671            exp.GroupConcat: _string_agg_sql,
672            exp.If: rename_func("IIF"),
673            exp.Length: rename_func("LEN"),
674            exp.Max: max_or_greatest,
675            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
676            exp.Min: min_or_least,
677            exp.NumberToStr: _format_sql,
678            exp.Select: transforms.preprocess(
679                [
680                    transforms.eliminate_distinct_on,
681                    transforms.eliminate_semi_and_anti_joins,
682                    transforms.eliminate_qualify,
683                ]
684            ),
685            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
686            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
687            exp.SHA2: lambda self, e: self.func(
688                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
689            ),
690            exp.TemporaryProperty: lambda self, e: "",
691            exp.TimeStrToTime: timestrtotime_sql,
692            exp.TimeToStr: _format_sql,
693            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
694            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
695            exp.TsOrDsToDate: ts_or_ds_to_date_sql("tsql"),
696        }
697
698        TRANSFORMS.pop(exp.ReturnsProperty)
699
700        PROPERTIES_LOCATION = {
701            **generator.Generator.PROPERTIES_LOCATION,
702            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
703        }
704
705        def set_operation(self, expression: exp.Union, op: str) -> str:
706            limit = expression.args.get("limit")
707            if limit:
708                return self.sql(expression.limit(limit.pop(), copy=False))
709
710            return super().set_operation(expression, op)
711
712        def setitem_sql(self, expression: exp.SetItem) -> str:
713            this = expression.this
714            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
715                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
716                return f"{self.sql(this.left)} {self.sql(this.right)}"
717
718            return super().setitem_sql(expression)
719
720        def boolean_sql(self, expression: exp.Boolean) -> str:
721            if type(expression.parent) in BIT_TYPES:
722                return "1" if expression.this else "0"
723
724            return "(1 = 1)" if expression.this else "(1 = 0)"
725
726        def is_sql(self, expression: exp.Is) -> str:
727            if isinstance(expression.expression, exp.Boolean):
728                return self.binary(expression, "=")
729            return self.binary(expression, "IS")
730
731        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
732            sql = self.sql(expression, "this")
733            properties = expression.args.get("properties")
734
735            if sql[:1] != "#" and any(
736                isinstance(prop, exp.TemporaryProperty)
737                for prop in (properties.expressions if properties else [])
738            ):
739                sql = f"#{sql}"
740
741            return sql
742
743        def create_sql(self, expression: exp.Create) -> str:
744            kind = self.sql(expression, "kind").upper()
745            exists = expression.args.pop("exists", None)
746            sql = super().create_sql(expression)
747
748            table = expression.find(exp.Table)
749
750            # Convert CTAS statement to SELECT .. INTO ..
751            if kind == "TABLE" and expression.expression:
752                ctas_with = expression.expression.args.get("with")
753                if ctas_with:
754                    ctas_with = ctas_with.pop()
755
756                subquery = expression.expression
757                if isinstance(subquery, exp.Subqueryable):
758                    subquery = subquery.subquery()
759
760                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
761                select_into.set("into", exp.Into(this=table))
762                select_into.set("with", ctas_with)
763
764                sql = self.sql(select_into)
765
766            if exists:
767                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
768                sql = self.sql(exp.Literal.string(sql))
769                if kind == "SCHEMA":
770                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
771                elif kind == "TABLE":
772                    assert table
773                    where = exp.and_(
774                        exp.column("table_name").eq(table.name),
775                        exp.column("table_schema").eq(table.db) if table.db else None,
776                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
777                    )
778                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
779                elif kind == "INDEX":
780                    index = self.sql(exp.Literal.string(expression.this.text("this")))
781                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
782            elif expression.args.get("replace"):
783                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
784
785            return self.prepend_ctes(expression, sql)
786
787        def offset_sql(self, expression: exp.Offset) -> str:
788            return f"{super().offset_sql(expression)} ROWS"
789
790        def version_sql(self, expression: exp.Version) -> str:
791            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
792            this = f"FOR {name}"
793            expr = expression.expression
794            kind = expression.text("kind")
795            if kind in ("FROM", "BETWEEN"):
796                args = expr.expressions
797                sep = "TO" if kind == "FROM" else "AND"
798                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
799            else:
800                expr_sql = self.sql(expr)
801
802            expr_sql = f" {expr_sql}" if expr_sql else ""
803            return f"{this} {kind}{expr_sql}"
804
805        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
806            table = expression.args.get("table")
807            table = f"{table} " if table else ""
808            return f"RETURNS {table}{self.sql(expression, 'this')}"
809
810        def returning_sql(self, expression: exp.Returning) -> str:
811            into = self.sql(expression, "into")
812            into = self.seg(f"INTO {into}") if into else ""
813            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
814
815        def transaction_sql(self, expression: exp.Transaction) -> str:
816            this = self.sql(expression, "this")
817            this = f" {this}" if this else ""
818            mark = self.sql(expression, "mark")
819            mark = f" WITH MARK {mark}" if mark else ""
820            return f"BEGIN TRANSACTION{this}{mark}"
821
822        def commit_sql(self, expression: exp.Commit) -> str:
823            this = self.sql(expression, "this")
824            this = f" {this}" if this else ""
825            durability = expression.args.get("durability")
826            durability = (
827                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
828                if durability is not None
829                else ""
830            )
831            return f"COMMIT TRANSACTION{this}{durability}"
832
833        def rollback_sql(self, expression: exp.Rollback) -> str:
834            this = self.sql(expression, "this")
835            this = f" {this}" if this else ""
836            return f"ROLLBACK TRANSACTION{this}"
837
838        def identifier_sql(self, expression: exp.Identifier) -> str:
839            identifier = super().identifier_sql(expression)
840
841            if expression.args.get("global"):
842                identifier = f"##{identifier}"
843            elif expression.args.get("temporary"):
844                identifier = f"#{identifier}"
845
846            return identifier
847
848        def constraint_sql(self, expression: exp.Constraint) -> str:
849            this = self.sql(expression, "this")
850            expressions = self.expressions(expression, flat=True, sep=" ")
851            return f"CONSTRAINT {this} {expressions}"
NORMALIZATION_STRATEGY = <NormalizationStrategy.CASE_INSENSITIVE: 'CASE_INSENSITIVE'>
TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
SUPPORTS_SEMI_ANTI_JOIN = False
LOG_BASE_FIRST = False
TYPED_DIVISION = True
CONCAT_COALESCE = True
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'}
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
class TSQL.Tokenizer(sqlglot.tokens.Tokenizer):
355    class Tokenizer(tokens.Tokenizer):
356        IDENTIFIERS = ['"', ("[", "]")]
357        QUOTES = ["'", '"']
358        HEX_STRINGS = [("0x", ""), ("0X", "")]
359        VAR_SINGLE_TOKENS = {"@", "$", "#"}
360
361        KEYWORDS = {
362            **tokens.Tokenizer.KEYWORDS,
363            "DATETIME2": TokenType.DATETIME,
364            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
365            "DECLARE": TokenType.COMMAND,
366            "IMAGE": TokenType.IMAGE,
367            "MONEY": TokenType.MONEY,
368            "NTEXT": TokenType.TEXT,
369            "NVARCHAR(MAX)": TokenType.TEXT,
370            "PRINT": TokenType.COMMAND,
371            "PROC": TokenType.PROCEDURE,
372            "REAL": TokenType.FLOAT,
373            "ROWVERSION": TokenType.ROWVERSION,
374            "SMALLDATETIME": TokenType.DATETIME,
375            "SMALLMONEY": TokenType.SMALLMONEY,
376            "SQL_VARIANT": TokenType.VARIANT,
377            "TOP": TokenType.TOP,
378            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
379            "UPDATE STATISTICS": TokenType.COMMAND,
380            "VARCHAR(MAX)": TokenType.TEXT,
381            "XML": TokenType.XML,
382            "OUTPUT": TokenType.RETURNING,
383            "SYSTEM_USER": TokenType.CURRENT_USER,
384            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
385        }
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'>, '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):
387    class Parser(parser.Parser):
388        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
389
390        FUNCTIONS = {
391            **parser.Parser.FUNCTIONS,
392            "CHARINDEX": lambda args: exp.StrPosition(
393                this=seq_get(args, 1),
394                substr=seq_get(args, 0),
395                position=seq_get(args, 2),
396            ),
397            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
398            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
399            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
400            "DATEPART": _format_time_lambda(exp.TimeToStr),
401            "EOMONTH": _parse_eomonth,
402            "FORMAT": _parse_format,
403            "GETDATE": exp.CurrentTimestamp.from_arg_list,
404            "HASHBYTES": _parse_hashbytes,
405            "IIF": exp.If.from_arg_list,
406            "ISNULL": exp.Coalesce.from_arg_list,
407            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
408            "LEN": exp.Length.from_arg_list,
409            "REPLICATE": exp.Repeat.from_arg_list,
410            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
411            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
412            "SUSER_NAME": exp.CurrentUser.from_arg_list,
413            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
414            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
415        }
416
417        JOIN_HINTS = {
418            "LOOP",
419            "HASH",
420            "MERGE",
421            "REMOTE",
422        }
423
424        VAR_LENGTH_DATATYPES = {
425            DataType.Type.NVARCHAR,
426            DataType.Type.VARCHAR,
427            DataType.Type.CHAR,
428            DataType.Type.NCHAR,
429        }
430
431        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
432            TokenType.TABLE,
433            *parser.Parser.TYPE_TOKENS,
434        }
435
436        STATEMENT_PARSERS = {
437            **parser.Parser.STATEMENT_PARSERS,
438            TokenType.END: lambda self: self._parse_command(),
439        }
440
441        LOG_DEFAULTS_TO_LN = True
442
443        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
444
445        def _parse_projections(self) -> t.List[exp.Expression]:
446            """
447            T-SQL supports the syntax alias = expression in the SELECT's projection list,
448            so we transform all parsed Selects to convert their EQ projections into Aliases.
449
450            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
451            """
452            return [
453                exp.alias_(projection.expression, projection.this.this, copy=False)
454                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
455                else projection
456                for projection in super()._parse_projections()
457            ]
458
459        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
460            """Applies to SQL Server and Azure SQL Database
461            COMMIT [ { TRAN | TRANSACTION }
462                [ transaction_name | @tran_name_variable ] ]
463                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
464
465            ROLLBACK { TRAN | TRANSACTION }
466                [ transaction_name | @tran_name_variable
467                | savepoint_name | @savepoint_variable ]
468            """
469            rollback = self._prev.token_type == TokenType.ROLLBACK
470
471            self._match_texts(("TRAN", "TRANSACTION"))
472            this = self._parse_id_var()
473
474            if rollback:
475                return self.expression(exp.Rollback, this=this)
476
477            durability = None
478            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
479                self._match_text_seq("DELAYED_DURABILITY")
480                self._match(TokenType.EQ)
481
482                if self._match_text_seq("OFF"):
483                    durability = False
484                else:
485                    self._match(TokenType.ON)
486                    durability = True
487
488                self._match_r_paren()
489
490            return self.expression(exp.Commit, this=this, durability=durability)
491
492        def _parse_transaction(self) -> exp.Transaction | exp.Command:
493            """Applies to SQL Server and Azure SQL Database
494            BEGIN { TRAN | TRANSACTION }
495            [ { transaction_name | @tran_name_variable }
496            [ WITH MARK [ 'description' ] ]
497            ]
498            """
499            if self._match_texts(("TRAN", "TRANSACTION")):
500                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
501                if self._match_text_seq("WITH", "MARK"):
502                    transaction.set("mark", self._parse_string())
503
504                return transaction
505
506            return self._parse_as_command(self._prev)
507
508        def _parse_returns(self) -> exp.ReturnsProperty:
509            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
510            returns = super()._parse_returns()
511            returns.set("table", table)
512            return returns
513
514        def _parse_convert(
515            self, strict: bool, safe: t.Optional[bool] = None
516        ) -> t.Optional[exp.Expression]:
517            to = self._parse_types()
518            self._match(TokenType.COMMA)
519            this = self._parse_conjunction()
520
521            if not to or not this:
522                return None
523
524            # Retrieve length of datatype and override to default if not specified
525            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
526                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
527
528            # Check whether a conversion with format is applicable
529            if self._match(TokenType.COMMA):
530                format_val = self._parse_number()
531                format_val_name = format_val.name if format_val else ""
532
533                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
534                    raise ValueError(
535                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
536                    )
537
538                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
539
540                # Check whether the convert entails a string to date format
541                if to.this == DataType.Type.DATE:
542                    return self.expression(exp.StrToDate, this=this, format=format_norm)
543                # Check whether the convert entails a string to datetime format
544                elif to.this == DataType.Type.DATETIME:
545                    return self.expression(exp.StrToTime, this=this, format=format_norm)
546                # Check whether the convert entails a date to string format
547                elif to.this in self.VAR_LENGTH_DATATYPES:
548                    return self.expression(
549                        exp.Cast if strict else exp.TryCast,
550                        to=to,
551                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
552                        safe=safe,
553                    )
554                elif to.this == DataType.Type.TEXT:
555                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
556
557            # Entails a simple cast without any format requirement
558            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
559
560        def _parse_user_defined_function(
561            self, kind: t.Optional[TokenType] = None
562        ) -> t.Optional[exp.Expression]:
563            this = super()._parse_user_defined_function(kind=kind)
564
565            if (
566                kind == TokenType.FUNCTION
567                or isinstance(this, exp.UserDefinedFunction)
568                or self._match(TokenType.ALIAS, advance=False)
569            ):
570                return this
571
572            expressions = self._parse_csv(self._parse_function_parameter)
573            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
574
575        def _parse_id_var(
576            self,
577            any_token: bool = True,
578            tokens: t.Optional[t.Collection[TokenType]] = None,
579        ) -> t.Optional[exp.Expression]:
580            is_temporary = self._match(TokenType.HASH)
581            is_global = is_temporary and self._match(TokenType.HASH)
582
583            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
584            if this:
585                if is_global:
586                    this.set("global", True)
587                elif is_temporary:
588                    this.set("temporary", True)
589
590            return this
591
592        def _parse_create(self) -> exp.Create | exp.Command:
593            create = super()._parse_create()
594
595            if isinstance(create, exp.Create):
596                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
597                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
598                    if not create.args.get("properties"):
599                        create.set("properties", exp.Properties(expressions=[]))
600
601                    create.args["properties"].append("expressions", exp.TemporaryProperty())
602
603            return create
604
605        def _parse_if(self) -> t.Optional[exp.Expression]:
606            index = self._index
607
608            if self._match_text_seq("OBJECT_ID"):
609                self._parse_wrapped_csv(self._parse_string)
610                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
611                    return self._parse_drop(exists=True)
612                self._retreat(index)
613
614            return super()._parse_if()
615
616        def _parse_unique(self) -> exp.UniqueColumnConstraint:
617            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
618                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
619            else:
620                this = self._parse_schema(self._parse_id_var(any_token=False))
621
622            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'>>, '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'>>, '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'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, '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'>>, '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_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <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'>>, '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_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'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, '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>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
JOIN_HINTS = {'HASH', 'LOOP', 'MERGE', 'REMOTE'}
VAR_LENGTH_DATATYPES = {<Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.VAR: 'VAR'>, <TokenType.CASE: 'CASE'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.ROWS: 'ROWS'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.INDEX: 'INDEX'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ALL: 'ALL'>, <TokenType.SET: 'SET'>, <TokenType.CACHE: 'CACHE'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.ROW: 'ROW'>, <TokenType.FALSE: 'FALSE'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.NEXT: 'NEXT'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.SOME: 'SOME'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.ASC: 'ASC'>, <TokenType.LOAD: 'LOAD'>, <TokenType.MERGE: 'MERGE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.SHOW: 'SHOW'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.USE: 'USE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.MODEL: 'MODEL'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.DESC: 'DESC'>, <TokenType.ANY: 'ANY'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.KILL: 'KILL'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.DIV: 'DIV'>, <TokenType.IS: 'IS'>, <TokenType.KEEP: 'KEEP'>, <TokenType.FILTER: 'FILTER'>, <TokenType.LEFT: 'LEFT'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.APPLY: 'APPLY'>, <TokenType.FULL: 'FULL'>, <TokenType.ANTI: 'ANTI'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TRUE: 'TRUE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.END: 'END'>, <TokenType.TOP: 'TOP'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.DELETE: 'DELETE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.VIEW: 'VIEW'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>}
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
TABLE_ALIAS_TOKENS = {<TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.VAR: 'VAR'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.DATE: 'DATE'>, <TokenType.CASE: 'CASE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.TEXT: 'TEXT'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.UUID: 'UUID'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.FIRST: 'FIRST'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.ROWS: 'ROWS'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.INT128: 'INT128'>, <TokenType.ALL: 'ALL'>, <TokenType.SET: 'SET'>, <TokenType.JSONB: 'JSONB'>, <TokenType.CACHE: 'CACHE'>, <TokenType.NULL: 'NULL'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.ROW: 'ROW'>, <TokenType.BIT: 'BIT'>, <TokenType.ENUM: 'ENUM'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.FALSE: 'FALSE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SOME: 'SOME'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.ASC: 'ASC'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.XML: 'XML'>, <TokenType.LOAD: 'LOAD'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.BINARY: 'BINARY'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.JSON: 'JSON'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.NESTED: 'NESTED'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.UINT: 'UINT'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.USE: 'USE'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.MODEL: 'MODEL'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.UINT256: 'UINT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.DESC: 'DESC'>, <TokenType.ANY: 'ANY'>, <TokenType.INET: 'INET'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.MAP: 'MAP'>, <TokenType.KILL: 'KILL'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.TIME: 'TIME'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.DIV: 'DIV'>, <TokenType.IS: 'IS'>, <TokenType.KEEP: 'KEEP'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.FILTER: 'FILTER'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.YEAR: 'YEAR'>, <TokenType.CHAR: 'CHAR'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.INT256: 'INT256'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.ANTI: 'ANTI'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TRUE: 'TRUE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.END: 'END'>, <TokenType.TABLE: 'TABLE'>, <TokenType.UINT128: 'UINT128'>, <TokenType.TOP: 'TOP'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.DELETE: 'DELETE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.INT: 'INT'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.SUPER: 'SUPER'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.VIEW: 'VIEW'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.USMALLINT: 'USMALLINT'>}
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
class TSQL.Generator(sqlglot.generator.Generator):
624    class Generator(generator.Generator):
625        LIMIT_IS_TOP = True
626        QUERY_HINTS = False
627        RETURNING_END = False
628        NVL2_SUPPORTED = False
629        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
630        LIMIT_FETCH = "FETCH"
631        COMPUTED_COLUMN_WITH_TYPE = False
632        CTE_RECURSIVE_KEYWORD_REQUIRED = False
633        ENSURE_BOOLS = True
634        NULL_ORDERING_SUPPORTED = False
635        SUPPORTS_SINGLE_ARG_CONCAT = False
636
637        EXPRESSIONS_WITHOUT_NESTED_CTES = {
638            exp.Delete,
639            exp.Insert,
640            exp.Merge,
641            exp.Select,
642            exp.Subquery,
643            exp.Union,
644            exp.Update,
645        }
646
647        TYPE_MAPPING = {
648            **generator.Generator.TYPE_MAPPING,
649            exp.DataType.Type.BOOLEAN: "BIT",
650            exp.DataType.Type.DECIMAL: "NUMERIC",
651            exp.DataType.Type.DATETIME: "DATETIME2",
652            exp.DataType.Type.DOUBLE: "FLOAT",
653            exp.DataType.Type.INT: "INTEGER",
654            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
655            exp.DataType.Type.TIMESTAMP: "DATETIME2",
656            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
657            exp.DataType.Type.VARIANT: "SQL_VARIANT",
658        }
659
660        TRANSFORMS = {
661            **generator.Generator.TRANSFORMS,
662            exp.AnyValue: any_value_to_max_sql,
663            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
664            exp.DateAdd: date_delta_sql("DATEADD"),
665            exp.DateDiff: date_delta_sql("DATEDIFF"),
666            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
667            exp.CurrentDate: rename_func("GETDATE"),
668            exp.CurrentTimestamp: rename_func("GETDATE"),
669            exp.Extract: rename_func("DATEPART"),
670            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
671            exp.GroupConcat: _string_agg_sql,
672            exp.If: rename_func("IIF"),
673            exp.Length: rename_func("LEN"),
674            exp.Max: max_or_greatest,
675            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
676            exp.Min: min_or_least,
677            exp.NumberToStr: _format_sql,
678            exp.Select: transforms.preprocess(
679                [
680                    transforms.eliminate_distinct_on,
681                    transforms.eliminate_semi_and_anti_joins,
682                    transforms.eliminate_qualify,
683                ]
684            ),
685            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
686            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
687            exp.SHA2: lambda self, e: self.func(
688                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
689            ),
690            exp.TemporaryProperty: lambda self, e: "",
691            exp.TimeStrToTime: timestrtotime_sql,
692            exp.TimeToStr: _format_sql,
693            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
694            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
695            exp.TsOrDsToDate: ts_or_ds_to_date_sql("tsql"),
696        }
697
698        TRANSFORMS.pop(exp.ReturnsProperty)
699
700        PROPERTIES_LOCATION = {
701            **generator.Generator.PROPERTIES_LOCATION,
702            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
703        }
704
705        def set_operation(self, expression: exp.Union, op: str) -> str:
706            limit = expression.args.get("limit")
707            if limit:
708                return self.sql(expression.limit(limit.pop(), copy=False))
709
710            return super().set_operation(expression, op)
711
712        def setitem_sql(self, expression: exp.SetItem) -> str:
713            this = expression.this
714            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
715                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
716                return f"{self.sql(this.left)} {self.sql(this.right)}"
717
718            return super().setitem_sql(expression)
719
720        def boolean_sql(self, expression: exp.Boolean) -> str:
721            if type(expression.parent) in BIT_TYPES:
722                return "1" if expression.this else "0"
723
724            return "(1 = 1)" if expression.this else "(1 = 0)"
725
726        def is_sql(self, expression: exp.Is) -> str:
727            if isinstance(expression.expression, exp.Boolean):
728                return self.binary(expression, "=")
729            return self.binary(expression, "IS")
730
731        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
732            sql = self.sql(expression, "this")
733            properties = expression.args.get("properties")
734
735            if sql[:1] != "#" and any(
736                isinstance(prop, exp.TemporaryProperty)
737                for prop in (properties.expressions if properties else [])
738            ):
739                sql = f"#{sql}"
740
741            return sql
742
743        def create_sql(self, expression: exp.Create) -> str:
744            kind = self.sql(expression, "kind").upper()
745            exists = expression.args.pop("exists", None)
746            sql = super().create_sql(expression)
747
748            table = expression.find(exp.Table)
749
750            # Convert CTAS statement to SELECT .. INTO ..
751            if kind == "TABLE" and expression.expression:
752                ctas_with = expression.expression.args.get("with")
753                if ctas_with:
754                    ctas_with = ctas_with.pop()
755
756                subquery = expression.expression
757                if isinstance(subquery, exp.Subqueryable):
758                    subquery = subquery.subquery()
759
760                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
761                select_into.set("into", exp.Into(this=table))
762                select_into.set("with", ctas_with)
763
764                sql = self.sql(select_into)
765
766            if exists:
767                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
768                sql = self.sql(exp.Literal.string(sql))
769                if kind == "SCHEMA":
770                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
771                elif kind == "TABLE":
772                    assert table
773                    where = exp.and_(
774                        exp.column("table_name").eq(table.name),
775                        exp.column("table_schema").eq(table.db) if table.db else None,
776                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
777                    )
778                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
779                elif kind == "INDEX":
780                    index = self.sql(exp.Literal.string(expression.this.text("this")))
781                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
782            elif expression.args.get("replace"):
783                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
784
785            return self.prepend_ctes(expression, sql)
786
787        def offset_sql(self, expression: exp.Offset) -> str:
788            return f"{super().offset_sql(expression)} ROWS"
789
790        def version_sql(self, expression: exp.Version) -> str:
791            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
792            this = f"FOR {name}"
793            expr = expression.expression
794            kind = expression.text("kind")
795            if kind in ("FROM", "BETWEEN"):
796                args = expr.expressions
797                sep = "TO" if kind == "FROM" else "AND"
798                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
799            else:
800                expr_sql = self.sql(expr)
801
802            expr_sql = f" {expr_sql}" if expr_sql else ""
803            return f"{this} {kind}{expr_sql}"
804
805        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
806            table = expression.args.get("table")
807            table = f"{table} " if table else ""
808            return f"RETURNS {table}{self.sql(expression, 'this')}"
809
810        def returning_sql(self, expression: exp.Returning) -> str:
811            into = self.sql(expression, "into")
812            into = self.seg(f"INTO {into}") if into else ""
813            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
814
815        def transaction_sql(self, expression: exp.Transaction) -> str:
816            this = self.sql(expression, "this")
817            this = f" {this}" if this else ""
818            mark = self.sql(expression, "mark")
819            mark = f" WITH MARK {mark}" if mark else ""
820            return f"BEGIN TRANSACTION{this}{mark}"
821
822        def commit_sql(self, expression: exp.Commit) -> str:
823            this = self.sql(expression, "this")
824            this = f" {this}" if this else ""
825            durability = expression.args.get("durability")
826            durability = (
827                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
828                if durability is not None
829                else ""
830            )
831            return f"COMMIT TRANSACTION{this}{durability}"
832
833        def rollback_sql(self, expression: exp.Rollback) -> str:
834            this = self.sql(expression, "this")
835            this = f" {this}" if this else ""
836            return f"ROLLBACK TRANSACTION{this}"
837
838        def identifier_sql(self, expression: exp.Identifier) -> str:
839            identifier = super().identifier_sql(expression)
840
841            if expression.args.get("global"):
842                identifier = f"##{identifier}"
843            elif expression.args.get("temporary"):
844                identifier = f"#{identifier}"
845
846            return identifier
847
848        def constraint_sql(self, expression: exp.Constraint) -> str:
849            this = self.sql(expression, "this")
850            expressions = self.expressions(expression, flat=True, sep=" ")
851            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
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.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.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.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<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.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.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsToDate'>: <function ts_or_ds_to_date_sql.<locals>._ts_or_ds_to_date_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.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.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 set_operation(self, expression: sqlglot.expressions.Union, op: str) -> str:
705        def set_operation(self, expression: exp.Union, op: str) -> str:
706            limit = expression.args.get("limit")
707            if limit:
708                return self.sql(expression.limit(limit.pop(), copy=False))
709
710            return super().set_operation(expression, op)
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
712        def setitem_sql(self, expression: exp.SetItem) -> str:
713            this = expression.this
714            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
715                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
716                return f"{self.sql(this.left)} {self.sql(this.right)}"
717
718            return super().setitem_sql(expression)
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
720        def boolean_sql(self, expression: exp.Boolean) -> str:
721            if type(expression.parent) in BIT_TYPES:
722                return "1" if expression.this else "0"
723
724            return "(1 = 1)" if expression.this else "(1 = 0)"
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
726        def is_sql(self, expression: exp.Is) -> str:
727            if isinstance(expression.expression, exp.Boolean):
728                return self.binary(expression, "=")
729            return self.binary(expression, "IS")
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
731        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
732            sql = self.sql(expression, "this")
733            properties = expression.args.get("properties")
734
735            if sql[:1] != "#" and any(
736                isinstance(prop, exp.TemporaryProperty)
737                for prop in (properties.expressions if properties else [])
738            ):
739                sql = f"#{sql}"
740
741            return sql
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
743        def create_sql(self, expression: exp.Create) -> str:
744            kind = self.sql(expression, "kind").upper()
745            exists = expression.args.pop("exists", None)
746            sql = super().create_sql(expression)
747
748            table = expression.find(exp.Table)
749
750            # Convert CTAS statement to SELECT .. INTO ..
751            if kind == "TABLE" and expression.expression:
752                ctas_with = expression.expression.args.get("with")
753                if ctas_with:
754                    ctas_with = ctas_with.pop()
755
756                subquery = expression.expression
757                if isinstance(subquery, exp.Subqueryable):
758                    subquery = subquery.subquery()
759
760                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
761                select_into.set("into", exp.Into(this=table))
762                select_into.set("with", ctas_with)
763
764                sql = self.sql(select_into)
765
766            if exists:
767                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
768                sql = self.sql(exp.Literal.string(sql))
769                if kind == "SCHEMA":
770                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
771                elif kind == "TABLE":
772                    assert table
773                    where = exp.and_(
774                        exp.column("table_name").eq(table.name),
775                        exp.column("table_schema").eq(table.db) if table.db else None,
776                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
777                    )
778                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
779                elif kind == "INDEX":
780                    index = self.sql(exp.Literal.string(expression.this.text("this")))
781                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
782            elif expression.args.get("replace"):
783                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
784
785            return self.prepend_ctes(expression, sql)
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
787        def offset_sql(self, expression: exp.Offset) -> str:
788            return f"{super().offset_sql(expression)} ROWS"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
790        def version_sql(self, expression: exp.Version) -> str:
791            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
792            this = f"FOR {name}"
793            expr = expression.expression
794            kind = expression.text("kind")
795            if kind in ("FROM", "BETWEEN"):
796                args = expr.expressions
797                sep = "TO" if kind == "FROM" else "AND"
798                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
799            else:
800                expr_sql = self.sql(expr)
801
802            expr_sql = f" {expr_sql}" if expr_sql else ""
803            return f"{this} {kind}{expr_sql}"
def returnsproperty_sql(self, expression: sqlglot.expressions.ReturnsProperty) -> str:
805        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
806            table = expression.args.get("table")
807            table = f"{table} " if table else ""
808            return f"RETURNS {table}{self.sql(expression, 'this')}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
810        def returning_sql(self, expression: exp.Returning) -> str:
811            into = self.sql(expression, "into")
812            into = self.seg(f"INTO {into}") if into else ""
813            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
815        def transaction_sql(self, expression: exp.Transaction) -> str:
816            this = self.sql(expression, "this")
817            this = f" {this}" if this else ""
818            mark = self.sql(expression, "mark")
819            mark = f" WITH MARK {mark}" if mark else ""
820            return f"BEGIN TRANSACTION{this}{mark}"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
822        def commit_sql(self, expression: exp.Commit) -> str:
823            this = self.sql(expression, "this")
824            this = f" {this}" if this else ""
825            durability = expression.args.get("durability")
826            durability = (
827                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
828                if durability is not None
829                else ""
830            )
831            return f"COMMIT TRANSACTION{this}{durability}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
833        def rollback_sql(self, expression: exp.Rollback) -> str:
834            this = self.sql(expression, "this")
835            this = f" {this}" if this else ""
836            return f"ROLLBACK TRANSACTION{this}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
838        def identifier_sql(self, expression: exp.Identifier) -> str:
839            identifier = super().identifier_sql(expression)
840
841            if expression.args.get("global"):
842                identifier = f"##{identifier}"
843            elif expression.args.get("temporary"):
844                identifier = f"#{identifier}"
845
846            return identifier
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
848        def constraint_sql(self, expression: exp.Constraint) -> str:
849            this = self.sql(expression, "this")
850            expressions = self.expressions(expression, flat=True, sep=" ")
851            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
TABLESAMPLE_WITH_METHOD
TABLESAMPLE_SIZE_IS_PERCENT
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
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
STAR_MAPPING
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
PARAMETER_TOKEN
RESERVED_KEYWORDS
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
KEY_VALUE_DEFINITONS
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
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
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
aliases_sql
attimezone_sql
add_sql
and_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
currentdate_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
altercolumn_sql
renametable_sql
altertable_sql
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