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

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

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

Checks if text can be identified given an identify option.

Arguments:
  • text: The text to check.
  • identify: "always" or True: Always returns true. "safe": True if the identifier is case-insensitive.
Returns:

Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
TOKENIZER_CLASS = <class 'TSQL.Tokenizer'>
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
Inherited Members
sqlglot.generator.Generator
Generator
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_PARAMETERS
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
SAFE_DIVISION
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
INDEX_OFFSET
UNNEST_COLUMN_ONLY
ALIAS_POST_TABLESAMPLE
IDENTIFIERS_CAN_START_WITH_DIGIT
STRICT_STRING_CONCAT
NORMALIZE_FUNCTIONS
NULL_ORDERING
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
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
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
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
safebracket_sql
all_sql
any_sql
exists_sql
case_sql
nextvaluefor_sql
extract_sql
trim_sql
safeconcat_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
formatjson_sql
jsonobject_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
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
safedpipe_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
set_operation
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
merge_sql
tochar_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
indexcolumnconstraint_sql
nvl2_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
forin_sql
refresh_sql
operator_sql