# sqlglot.dialects.tsql API documentation

Edit on GitHub

# sqlglot.dialects.tsql

View Source

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

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)
BIT_TYPES = {<class 'sqlglot.expressions.In'>, <class 'sqlglot.expressions.Alias'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.NEQ'>, <class 'sqlglot.expressions.Is'>, <class 'sqlglot.expressions.EQ'>}
DATEPART_ONLY_FORMATS = {'HOUR', 'QUARTER', 'DW'}
def qualify_derived_table_outputs( expression: sqlglot.expressions.Expression ) -> sqlglot.expressions.Expression: View Source

    211def qualify_derived_table_outputs(expression: exp.Expression) -> exp.Expression:
    212    """Ensures all (unnamed) output columns are aliased for CTEs and Subqueries."""
    213    alias = expression.args.get("alias")
    214
    215    if (
    216        isinstance(expression, (exp.CTE, exp.Subquery))
    217        and isinstance(alias, exp.TableAlias)
    218        and not alias.columns
    219    ):
    220        from sqlglot.optimizer.qualify_columns import qualify_outputs
    221
    222        # We keep track of the unaliased column projection indexes instead of the expressions
    223        # themselves, because the latter are going to be replaced by new nodes when the aliases
    224        # are added and hence we won't be able to reach these newly added Alias parents
    225        subqueryable = expression.this
    226        unaliased_column_indexes = (
    227            i
    228            for i, c in enumerate(subqueryable.selects)
    229            if isinstance(c, exp.Column) and not c.alias
    230        )
    231
    232        qualify_outputs(subqueryable)
    233
    234        # Preserve the quoting information of columns for newly added Alias nodes
    235        subqueryable_selects = subqueryable.selects
    236        for select_index in unaliased_column_indexes:
    237            alias = subqueryable_selects[select_index]
    238            column = alias.this
    239            if isinstance(column.this, exp.Identifier):
    240                alias.args["alias"].set("quoted", column.this.quoted)
    241
    242    return expression

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

class TSQL(sqlglot.dialects.dialect.Dialect): View Source

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

NORMALIZATION_STRATEGY = <NormalizationStrategy.CASE_INSENSITIVE: 'CASE_INSENSITIVE'>

Specifies the strategy according to which identifiers should be normalized.

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

Determines whether or not `SEMI` or `ANTI` joins are supported.

LOG_BASE_FIRST = False

Determines whether the base comes first in the `LOG` function.

TYPED_DIVISION = True

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

CONCAT_COALESCE = True

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

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

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

CONVERT_FORMAT_MAPPING = {'0': '%b %d %Y %-I:%M%p', '1': '%m/%d/%y', '2': '%y.%m.%d', '3': '%d/%m/%y', '4': '%d.%m.%y', '5': '%d-%m-%y', '6': '%d %b %y', '7': '%b %d, %y', '8': '%H:%M:%S', '9': '%b %d %Y %-I:%M:%S:%f%p', '10': 'mm-dd-yy', '11': 'yy/mm/dd', '12': 'yymmdd', '13': '%d %b %Y %H:%M:ss:%f', '14': '%H:%M:%S:%f', '20': '%Y-%m-%d %H:%M:%S', '21': '%Y-%m-%d %H:%M:%S.%f', '22': '%m/%d/%y %-I:%M:%S %p', '23': '%Y-%m-%d', '24': '%H:%M:%S', '25': '%Y-%m-%d %H:%M:%S.%f', '100': '%b %d %Y %-I:%M%p', '101': '%m/%d/%Y', '102': '%Y.%m.%d', '103': '%d/%m/%Y', '104': '%d.%m.%Y', '105': '%d-%m-%Y', '106': '%d %b %Y', '107': '%b %d, %Y', '108': '%H:%M:%S', '109': '%b %d %Y %-I:%M:%S:%f%p', '110': '%m-%d-%Y', '111': '%Y/%m/%d', '112': '%Y%m%d', '113': '%d %b %Y %H:%M:%S:%f', '114': '%H:%M:%S:%f', '120': '%Y-%m-%d %H:%M:%S', '121': '%Y-%m-%d %H:%M:%S.%f'}
FORMAT_TIME_MAPPING = {'y': '%B %Y', 'd': '%m/%d/%Y', 'H': '%-H', 'h': '%-I', 's': '%Y-%m-%d %H:%M:%S', 'D': '%A,%B,%Y', 'f': '%A,%B,%Y %-I:%M %p', 'F': '%A,%B,%Y %-I:%M:%S %p', 'g': '%m/%d/%Y %-I:%M %p', 'G': '%m/%d/%Y %-I:%M:%S %p', 'M': '%B %-d', 'm': '%B %-d', 'O': '%Y-%m-%dT%H:%M:%S', 'u': '%Y-%M-%D %H:%M:%S%z', 'U': '%A, %B %D, %Y %H:%M:%S%z', 'T': '%-I:%M:%S %p', 't': '%-I:%M', 'Y': '%a %Y'}
tokenizer_class = <class 'TSQL.Tokenizer'>
parser_class = <class 'TSQL.Parser'>
generator_class = <class 'TSQL.Generator'>
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
FORMAT_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
INVERSE_TIME_MAPPING: Dict[str, str] = {'%Y': 'yyyy', '%j': 'dayofyear', '%d': 'dd', '%W': 'dw', '%h': 'hour', '%I': 'hh', '%M': 'mm', '%S': 'ss', '%-S': 's', '%f': 'S', '%m': 'MM', '%-M': 'm', '%y': 'yy', '%B': 'MMMM', '%b': 'MMM', '%-m': 'M', '%A': 'dddd', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict = {'%': {'Y': {0: True}, 'j': {0: True}, 'd': {0: True}, 'W': {0: True}, 'h': {0: True}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, '-': {'S': {0: True}, 'M': {0: True}, 'm': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'f': {0: True}, 'm': {0: True}, 'y': {0: True}, 'B': {0: True}, 'b': {0: True}, 'A': {0: True}, 'H': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '['
IDENTIFIER_END = ']'
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
UNICODE_START: Optional[str] = None
UNICODE_END: Optional[str] = None

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  Dialect
  INDEX_OFFSET
  WEEK_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  TABLESAMPLE_SIZE_IS_PERCENT
  IDENTIFIERS_CAN_START_WITH_DIGIT
  DPIPE_IS_STRING_CONCAT
  STRICT_STRING_CONCAT
  SUPPORTS_USER_DEFINED_TYPES
  NORMALIZE_FUNCTIONS
  NULL_ORDERING
  SAFE_DIVISION
  DATE_FORMAT
  DATEINT_FORMAT
  FORMAT_MAPPING
  ESCAPE_SEQUENCES
  PSEUDOCOLUMNS
  PREFER_CTE_ALIAS_COLUMN
  get_or_raise
  format_time
  normalize_identifier
  case_sensitive
  can_identify
  quote_identifier
  to_json_path
  parse
  parse_into
  generate
  transpile
  tokenize
  tokenizer
  parser
  generator

class TSQL.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    409    class Tokenizer(tokens.Tokenizer):
    410        IDENTIFIERS = [("[", "]"), '"']
    411        QUOTES = ["'", '"']
    412        HEX_STRINGS = [("0x", ""), ("0X", "")]
    413        VAR_SINGLE_TOKENS = {"@", "$", "#"}
    414
    415        KEYWORDS = {
    416            **tokens.Tokenizer.KEYWORDS,
    417            "DATETIME2": TokenType.DATETIME,
    418            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
    419            "DECLARE": TokenType.COMMAND,
    420            "EXEC": TokenType.COMMAND,
    421            "IMAGE": TokenType.IMAGE,
    422            "MONEY": TokenType.MONEY,
    423            "NTEXT": TokenType.TEXT,
    424            "NVARCHAR(MAX)": TokenType.TEXT,
    425            "PRINT": TokenType.COMMAND,
    426            "PROC": TokenType.PROCEDURE,
    427            "REAL": TokenType.FLOAT,
    428            "ROWVERSION": TokenType.ROWVERSION,
    429            "SMALLDATETIME": TokenType.DATETIME,
    430            "SMALLMONEY": TokenType.SMALLMONEY,
    431            "SQL_VARIANT": TokenType.VARIANT,
    432            "TOP": TokenType.TOP,
    433            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
    434            "UPDATE STATISTICS": TokenType.COMMAND,
    435            "VARCHAR(MAX)": TokenType.TEXT,
    436            "XML": TokenType.XML,
    437            "OUTPUT": TokenType.RETURNING,
    438            "SYSTEM_USER": TokenType.CURRENT_USER,
    439            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
    440        }

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'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'EXEC': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, 'NVARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'PRINT': <TokenType.COMMAND: 'COMMAND'>, 'PROC': <TokenType.PROCEDURE: 'PROCEDURE'>, 'ROWVERSION': <TokenType.ROWVERSION: 'ROWVERSION'>, 'SMALLDATETIME': <TokenType.DATETIME: 'DATETIME'>, 'SMALLMONEY': <TokenType.SMALLMONEY: 'SMALLMONEY'>, 'SQL_VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'TOP': <TokenType.TOP: 'TOP'>, 'UNIQUEIDENTIFIER': <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, 'UPDATE STATISTICS': <TokenType.COMMAND: 'COMMAND'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'FOR SYSTEM_TIME': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}

##### Inherited Members

sqlglot.tokens.Tokenizer
  Tokenizer
  SINGLE_TOKENS
  BIT_STRINGS
  BYTE_STRINGS
  RAW_STRINGS
  HEREDOC_STRINGS
  UNICODE_STRINGS
  IDENTIFIER_ESCAPES
  STRING_ESCAPES
  WHITE_SPACE
  COMMANDS
  COMMAND_PREFIX_TOKENS
  NUMERIC_LITERALS
  COMMENTS
  dialect
  reset
  tokenize
  peek
  tokenize_rs
  size
  sql
  tokens

class TSQL.Parser(sqlglot.parser.Parser): View Source

    442    class Parser(parser.Parser):
    443        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
    444
    445        FUNCTIONS = {
    446            **parser.Parser.FUNCTIONS,
    447            "CHARINDEX": lambda args: exp.StrPosition(
    448                this=seq_get(args, 1),
    449                substr=seq_get(args, 0),
    450                position=seq_get(args, 2),
    451            ),
    452            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
    453            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
    454            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
    455            "DATEPART": _format_time_lambda(exp.TimeToStr),
    456            "DATETIMEFROMPARTS": _parse_datetimefromparts,
    457            "EOMONTH": _parse_eomonth,
    458            "FORMAT": _parse_format,
    459            "GETDATE": exp.CurrentTimestamp.from_arg_list,
    460            "HASHBYTES": _parse_hashbytes,
    461            "IIF": exp.If.from_arg_list,
    462            "ISNULL": exp.Coalesce.from_arg_list,
    463            "JSON_QUERY": parser.parse_extract_json_with_path(exp.JSONExtract),
    464            "JSON_VALUE": parser.parse_extract_json_with_path(exp.JSONExtractScalar),
    465            "LEN": _parse_as_text(exp.Length),
    466            "LEFT": _parse_as_text(exp.Left),
    467            "RIGHT": _parse_as_text(exp.Right),
    468            "REPLICATE": exp.Repeat.from_arg_list,
    469            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    470            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
    471            "SUSER_NAME": exp.CurrentUser.from_arg_list,
    472            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
    473            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
    474            "TIMEFROMPARTS": _parse_timefromparts,
    475        }
    476
    477        JOIN_HINTS = {
    478            "LOOP",
    479            "HASH",
    480            "MERGE",
    481            "REMOTE",
    482        }
    483
    484        VAR_LENGTH_DATATYPES = {
    485            DataType.Type.NVARCHAR,
    486            DataType.Type.VARCHAR,
    487            DataType.Type.CHAR,
    488            DataType.Type.NCHAR,
    489        }
    490
    491        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
    492            TokenType.TABLE,
    493            *parser.Parser.TYPE_TOKENS,
    494        }
    495
    496        STATEMENT_PARSERS = {
    497            **parser.Parser.STATEMENT_PARSERS,
    498            TokenType.END: lambda self: self._parse_command(),
    499        }
    500
    501        LOG_DEFAULTS_TO_LN = True
    502
    503        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
    504        STRING_ALIASES = True
    505        NO_PAREN_IF_COMMANDS = False
    506
    507        def _parse_projections(self) -> t.List[exp.Expression]:
    508            """
    509            T-SQL supports the syntax alias = expression in the SELECT's projection list,
    510            so we transform all parsed Selects to convert their EQ projections into Aliases.
    511
    512            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
    513            """
    514            return [
    515                (
    516                    exp.alias_(projection.expression, projection.this.this, copy=False)
    517                    if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
    518                    else projection
    519                )
    520                for projection in super()._parse_projections()
    521            ]
    522
    523        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
    524            """Applies to SQL Server and Azure SQL Database
    525            COMMIT [ { TRAN | TRANSACTION }
    526                [ transaction_name | @tran_name_variable ] ]
    527                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
    528
    529            ROLLBACK { TRAN | TRANSACTION }
    530                [ transaction_name | @tran_name_variable
    531                | savepoint_name | @savepoint_variable ]
    532            """
    533            rollback = self._prev.token_type == TokenType.ROLLBACK
    534
    535            self._match_texts(("TRAN", "TRANSACTION"))
    536            this = self._parse_id_var()
    537
    538            if rollback:
    539                return self.expression(exp.Rollback, this=this)
    540
    541            durability = None
    542            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
    543                self._match_text_seq("DELAYED_DURABILITY")
    544                self._match(TokenType.EQ)
    545
    546                if self._match_text_seq("OFF"):
    547                    durability = False
    548                else:
    549                    self._match(TokenType.ON)
    550                    durability = True
    551
    552                self._match_r_paren()
    553
    554            return self.expression(exp.Commit, this=this, durability=durability)
    555
    556        def _parse_transaction(self) -> exp.Transaction | exp.Command:
    557            """Applies to SQL Server and Azure SQL Database
    558            BEGIN { TRAN | TRANSACTION }
    559            [ { transaction_name | @tran_name_variable }
    560            [ WITH MARK [ 'description' ] ]
    561            ]
    562            """
    563            if self._match_texts(("TRAN", "TRANSACTION")):
    564                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
    565                if self._match_text_seq("WITH", "MARK"):
    566                    transaction.set("mark", self._parse_string())
    567
    568                return transaction
    569
    570            return self._parse_as_command(self._prev)
    571
    572        def _parse_returns(self) -> exp.ReturnsProperty:
    573            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
    574            returns = super()._parse_returns()
    575            returns.set("table", table)
    576            return returns
    577
    578        def _parse_convert(
    579            self, strict: bool, safe: t.Optional[bool] = None
    580        ) -> t.Optional[exp.Expression]:
    581            to = self._parse_types()
    582            self._match(TokenType.COMMA)
    583            this = self._parse_conjunction()
    584
    585            if not to or not this:
    586                return None
    587
    588            # Retrieve length of datatype and override to default if not specified
    589            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
    590                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    591
    592            # Check whether a conversion with format is applicable
    593            if self._match(TokenType.COMMA):
    594                format_val = self._parse_number()
    595                format_val_name = format_val.name if format_val else ""
    596
    597                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
    598                    raise ValueError(
    599                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
    600                    )
    601
    602                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
    603
    604                # Check whether the convert entails a string to date format
    605                if to.this == DataType.Type.DATE:
    606                    return self.expression(exp.StrToDate, this=this, format=format_norm)
    607                # Check whether the convert entails a string to datetime format
    608                elif to.this == DataType.Type.DATETIME:
    609                    return self.expression(exp.StrToTime, this=this, format=format_norm)
    610                # Check whether the convert entails a date to string format
    611                elif to.this in self.VAR_LENGTH_DATATYPES:
    612                    return self.expression(
    613                        exp.Cast if strict else exp.TryCast,
    614                        to=to,
    615                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
    616                        safe=safe,
    617                    )
    618                elif to.this == DataType.Type.TEXT:
    619                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
    620
    621            # Entails a simple cast without any format requirement
    622            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
    623
    624        def _parse_user_defined_function(
    625            self, kind: t.Optional[TokenType] = None
    626        ) -> t.Optional[exp.Expression]:
    627            this = super()._parse_user_defined_function(kind=kind)
    628
    629            if (
    630                kind == TokenType.FUNCTION
    631                or isinstance(this, exp.UserDefinedFunction)
    632                or self._match(TokenType.ALIAS, advance=False)
    633            ):
    634                return this
    635
    636            expressions = self._parse_csv(self._parse_function_parameter)
    637            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
    638
    639        def _parse_id_var(
    640            self,
    641            any_token: bool = True,
    642            tokens: t.Optional[t.Collection[TokenType]] = None,
    643        ) -> t.Optional[exp.Expression]:
    644            is_temporary = self._match(TokenType.HASH)
    645            is_global = is_temporary and self._match(TokenType.HASH)
    646
    647            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
    648            if this:
    649                if is_global:
    650                    this.set("global", True)
    651                elif is_temporary:
    652                    this.set("temporary", True)
    653
    654            return this
    655
    656        def _parse_create(self) -> exp.Create | exp.Command:
    657            create = super()._parse_create()
    658
    659            if isinstance(create, exp.Create):
    660                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
    661                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
    662                    if not create.args.get("properties"):
    663                        create.set("properties", exp.Properties(expressions=[]))
    664
    665                    create.args["properties"].append("expressions", exp.TemporaryProperty())
    666
    667            return create
    668
    669        def _parse_if(self) -> t.Optional[exp.Expression]:
    670            index = self._index
    671
    672            if self._match_text_seq("OBJECT_ID"):
    673                self._parse_wrapped_csv(self._parse_string)
    674                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
    675                    return self._parse_drop(exists=True)
    676                self._retreat(index)
    677
    678            return super()._parse_if()
    679
    680        def _parse_unique(self) -> exp.UniqueColumnConstraint:
    681            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
    682                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
    683            else:
    684                this = self._parse_schema(self._parse_id_var(any_token=False))
    685
    686            return self.expression(exp.UniqueColumnConstraint, this=this)

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

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3

SET_REQUIRES_ASSIGNMENT_DELIMITER = False
FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANONYMOUS_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnonymousAggFunc'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_OVERLAPS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayOverlaps'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'ARRAY_UNIQUE_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUniqueAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'COMBINED_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedAggFunc'>>, 'COMBINED_PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedParameterizedAgg'>>, 'CONCAT': <function Parser.<lambda>>, 'CONCAT_WS': <function Parser.<lambda>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'COUNTIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FIRST_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FirstValue'>>, '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': <function parse_extract_json_with_path.<locals>._parser>, 'JSON_EXTRACT_SCALAR': <function parse_extract_json_with_path.<locals>._parser>, '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_OBJECT_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObjectAgg'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lag'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastValue'>>, 'LEAD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lead'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <function _parse_as_text.<locals>._parse>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <function _parse_as_text.<locals>._parse>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <function parse_logarithm>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NTH_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NthValue'>>, 'NULLIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nullif'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RAND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDOM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Randn'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <function _parse_as_text.<locals>._parse>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeFromParts'>>, 'TIMEFROMPARTS': <function _parse_timefromparts>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMPDIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMPFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToArray'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsDiff'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'TS_OR_DS_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToTime'>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixDate'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'JSON_EXTRACT_PATH_TEXT': <function parse_extract_json_with_path.<locals>._parser>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'DATETIMEFROMPARTS': <function _parse_datetimefromparts>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_QUERY': <function parse_extract_json_with_path.<locals>._parser>, 'JSON_VALUE': <function parse_extract_json_with_path.<locals>._parser>, '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 = {'REMOTE', 'HASH', 'LOOP', 'MERGE'}
VAR_LENGTH_DATATYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.END: 'END'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.LEFT: 'LEFT'>, <TokenType.ROWS: 'ROWS'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SHOW: 'SHOW'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.MODEL: 'MODEL'>, <TokenType.FALSE: 'FALSE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.ANTI: 'ANTI'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.SET: 'SET'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.NEXT: 'NEXT'>, <TokenType.FILTER: 'FILTER'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.APPLY: 'APPLY'>, <TokenType.DESC: 'DESC'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.ALL: 'ALL'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.KEEP: 'KEEP'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.DELETE: 'DELETE'>, <TokenType.ROW: 'ROW'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.VAR: 'VAR'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.TRUE: 'TRUE'>, <TokenType.SOME: 'SOME'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.CASE: 'CASE'>, <TokenType.IS: 'IS'>, <TokenType.FULL: 'FULL'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.FINAL: 'FINAL'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.USE: 'USE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.ASC: 'ASC'>, <TokenType.KILL: 'KILL'>, <TokenType.CACHE: 'CACHE'>, <TokenType.ANY: 'ANY'>, <TokenType.VIEW: 'VIEW'>, <TokenType.FIRST: 'FIRST'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.DIV: 'DIV'>, <TokenType.TOP: 'TOP'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.FUNCTION: 'FUNCTION'>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.REFRESH: 'REFRESH'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
LOG_DEFAULTS_TO_LN = True
ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
STRING_ALIASES = True
NO_PAREN_IF_COMMANDS = False
TABLE_ALIAS_TOKENS = {<TokenType.NULL: 'NULL'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.XML: 'XML'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.END: 'END'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPV4: 'IPV4'>, <TokenType.ROWS: 'ROWS'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.SEMI: 'SEMI'>, <TokenType.INT128: 'INT128'>, <TokenType.SHOW: 'SHOW'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.FALSE: 'FALSE'>, <TokenType.MODEL: 'MODEL'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.ANTI: 'ANTI'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.MAP: 'MAP'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.TABLE: 'TABLE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.BINARY: 'BINARY'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.SET: 'SET'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.NEXT: 'NEXT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.FILTER: 'FILTER'>, <TokenType.TIME: 'TIME'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.UINT256: 'UINT256'>, <TokenType.DATE32: 'DATE32'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.INET: 'INET'>, <TokenType.DESC: 'DESC'>, <TokenType.NESTED: 'NESTED'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.BPCHAR: 'BPCHAR'>, <TokenType.ALL: 'ALL'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.UUID: 'UUID'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.IPV6: 'IPV6'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>, <TokenType.KEEP: 'KEEP'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.DELETE: 'DELETE'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.ROW: 'ROW'>, <TokenType.MONEY: 'MONEY'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.BIT: 'BIT'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.DATE: 'DATE'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.VAR: 'VAR'>, <TokenType.SUPER: 'SUPER'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.INT256: 'INT256'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.TRUE: 'TRUE'>, <TokenType.SOME: 'SOME'>, <TokenType.UINT: 'UINT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.CASE: 'CASE'>, <TokenType.IS: 'IS'>, <TokenType.INT: 'INT'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.FINAL: 'FINAL'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.JSON: 'JSON'>, <TokenType.JSONB: 'JSONB'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.INDEX: 'INDEX'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.USE: 'USE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.ASC: 'ASC'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.KILL: 'KILL'>, <TokenType.CACHE: 'CACHE'>, <TokenType.ANY: 'ANY'>, <TokenType.YEAR: 'YEAR'>, <TokenType.VIEW: 'VIEW'>, <TokenType.FIRST: 'FIRST'>, <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.DIV: 'DIV'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.ENUM: 'ENUM'>, <TokenType.TOP: 'TOP'>, <TokenType.CHAR: 'CHAR'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.FUNCTION: 'FUNCTION'>}
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  STRUCT_TYPE_TOKENS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  AGGREGATE_TYPE_TOKENS
  TYPE_TOKENS
  SIGNED_TO_UNSIGNED_TYPE_TOKEN
  SUBQUERY_PREDICATES
  RESERVED_TOKENS
  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
  HISTORICAL_DATA_KIND
  OPCLASS_FOLLOW_KEYWORDS
  OPTYPE_FOLLOW_TOKENS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  JSON_KEY_VALUE_SEPARATOR_TOKENS
  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
  MODIFIERS_ATTACHED_TO_UNION
  UNION_MODIFIERS
  error_level
  error_message_context
  max_errors
  dialect
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

class TSQL.Generator(sqlglot.generator.Generator): View Source

    688    class Generator(generator.Generator):
    689        LIMIT_IS_TOP = True
    690        QUERY_HINTS = False
    691        RETURNING_END = False
    692        NVL2_SUPPORTED = False
    693        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
    694        LIMIT_FETCH = "FETCH"
    695        COMPUTED_COLUMN_WITH_TYPE = False
    696        CTE_RECURSIVE_KEYWORD_REQUIRED = False
    697        ENSURE_BOOLS = True
    698        NULL_ORDERING_SUPPORTED = None
    699        SUPPORTS_SINGLE_ARG_CONCAT = False
    700        TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
    701        SUPPORTS_SELECT_INTO = True
    702        JSON_PATH_BRACKETED_KEY_SUPPORTED = False
    703
    704        EXPRESSIONS_WITHOUT_NESTED_CTES = {
    705            exp.Delete,
    706            exp.Insert,
    707            exp.Merge,
    708            exp.Select,
    709            exp.Subquery,
    710            exp.Union,
    711            exp.Update,
    712        }
    713
    714        SUPPORTED_JSON_PATH_PARTS = {
    715            exp.JSONPathKey,
    716            exp.JSONPathRoot,
    717            exp.JSONPathSubscript,
    718        }
    719
    720        TYPE_MAPPING = {
    721            **generator.Generator.TYPE_MAPPING,
    722            exp.DataType.Type.BOOLEAN: "BIT",
    723            exp.DataType.Type.DECIMAL: "NUMERIC",
    724            exp.DataType.Type.DATETIME: "DATETIME2",
    725            exp.DataType.Type.DOUBLE: "FLOAT",
    726            exp.DataType.Type.INT: "INTEGER",
    727            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
    728            exp.DataType.Type.TIMESTAMP: "DATETIME2",
    729            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
    730            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    731        }
    732
    733        TRANSFORMS = {
    734            **generator.Generator.TRANSFORMS,
    735            exp.AnyValue: any_value_to_max_sql,
    736            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
    737            exp.DateAdd: date_delta_sql("DATEADD"),
    738            exp.DateDiff: date_delta_sql("DATEDIFF"),
    739            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
    740            exp.CurrentDate: rename_func("GETDATE"),
    741            exp.CurrentTimestamp: rename_func("GETDATE"),
    742            exp.Extract: rename_func("DATEPART"),
    743            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
    744            exp.GroupConcat: _string_agg_sql,
    745            exp.If: rename_func("IIF"),
    746            exp.JSONExtract: _json_extract_sql,
    747            exp.JSONExtractScalar: _json_extract_sql,
    748            exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
    749            exp.Max: max_or_greatest,
    750            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    751            exp.Min: min_or_least,
    752            exp.NumberToStr: _format_sql,
    753            exp.ParseJSON: lambda self, e: self.sql(e, "this"),
    754            exp.Select: transforms.preprocess(
    755                [
    756                    transforms.eliminate_distinct_on,
    757                    transforms.eliminate_semi_and_anti_joins,
    758                    transforms.eliminate_qualify,
    759                ]
    760            ),
    761            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
    762            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    763            exp.SHA2: lambda self, e: self.func(
    764                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
    765            ),
    766            exp.TemporaryProperty: lambda self, e: "",
    767            exp.TimeStrToTime: timestrtotime_sql,
    768            exp.TimeToStr: _format_sql,
    769            exp.Trim: trim_sql,
    770            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
    771            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
    772        }
    773
    774        TRANSFORMS.pop(exp.ReturnsProperty)
    775
    776        PROPERTIES_LOCATION = {
    777            **generator.Generator.PROPERTIES_LOCATION,
    778            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    779        }
    780
    781        def lateral_op(self, expression: exp.Lateral) -> str:
    782            cross_apply = expression.args.get("cross_apply")
    783            if cross_apply is True:
    784                return "CROSS APPLY"
    785            if cross_apply is False:
    786                return "OUTER APPLY"
    787
    788            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
    789            self.unsupported("LATERAL clause is not supported.")
    790            return "LATERAL"
    791
    792        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
    793            nano = expression.args.get("nano")
    794            if nano is not None:
    795                nano.pop()
    796                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
    797
    798            if expression.args.get("fractions") is None:
    799                expression.set("fractions", exp.Literal.number(0))
    800            if expression.args.get("precision") is None:
    801                expression.set("precision", exp.Literal.number(0))
    802
    803            return rename_func("TIMEFROMPARTS")(self, expression)
    804
    805        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
    806            zone = expression.args.get("zone")
    807            if zone is not None:
    808                zone.pop()
    809                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
    810
    811            nano = expression.args.get("nano")
    812            if nano is not None:
    813                nano.pop()
    814                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
    815
    816            if expression.args.get("milli") is None:
    817                expression.set("milli", exp.Literal.number(0))
    818
    819            return rename_func("DATETIMEFROMPARTS")(self, expression)
    820
    821        def set_operation(self, expression: exp.Union, op: str) -> str:
    822            limit = expression.args.get("limit")
    823            if limit:
    824                return self.sql(expression.limit(limit.pop(), copy=False))
    825
    826            return super().set_operation(expression, op)
    827
    828        def setitem_sql(self, expression: exp.SetItem) -> str:
    829            this = expression.this
    830            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
    831                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
    832                return f"{self.sql(this.left)} {self.sql(this.right)}"
    833
    834            return super().setitem_sql(expression)
    835
    836        def boolean_sql(self, expression: exp.Boolean) -> str:
    837            if type(expression.parent) in BIT_TYPES:
    838                return "1" if expression.this else "0"
    839
    840            return "(1 = 1)" if expression.this else "(1 = 0)"
    841
    842        def is_sql(self, expression: exp.Is) -> str:
    843            if isinstance(expression.expression, exp.Boolean):
    844                return self.binary(expression, "=")
    845            return self.binary(expression, "IS")
    846
    847        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    848            sql = self.sql(expression, "this")
    849            properties = expression.args.get("properties")
    850
    851            if sql[:1] != "#" and any(
    852                isinstance(prop, exp.TemporaryProperty)
    853                for prop in (properties.expressions if properties else [])
    854            ):
    855                sql = f"#{sql}"
    856
    857            return sql
    858
    859        def create_sql(self, expression: exp.Create) -> str:
    860            kind = self.sql(expression, "kind").upper()
    861            exists = expression.args.pop("exists", None)
    862            sql = super().create_sql(expression)
    863
    864            like_property = expression.find(exp.LikeProperty)
    865            if like_property:
    866                ctas_expression = like_property.this
    867            else:
    868                ctas_expression = expression.expression
    869
    870            table = expression.find(exp.Table)
    871
    872            # Convert CTAS statement to SELECT .. INTO ..
    873            if kind == "TABLE" and ctas_expression:
    874                ctas_with = ctas_expression.args.get("with")
    875                if ctas_with:
    876                    ctas_with = ctas_with.pop()
    877
    878                subquery = ctas_expression
    879                if isinstance(subquery, exp.Subqueryable):
    880                    subquery = subquery.subquery()
    881
    882                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
    883                select_into.set("into", exp.Into(this=table))
    884                select_into.set("with", ctas_with)
    885
    886                if like_property:
    887                    select_into.limit(0, copy=False)
    888
    889                sql = self.sql(select_into)
    890
    891            if exists:
    892                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    893                sql = self.sql(exp.Literal.string(sql))
    894                if kind == "SCHEMA":
    895                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
    896                elif kind == "TABLE":
    897                    assert table
    898                    where = exp.and_(
    899                        exp.column("table_name").eq(table.name),
    900                        exp.column("table_schema").eq(table.db) if table.db else None,
    901                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
    902                    )
    903                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
    904                elif kind == "INDEX":
    905                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    906                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
    907            elif expression.args.get("replace"):
    908                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    909
    910            return self.prepend_ctes(expression, sql)
    911
    912        def offset_sql(self, expression: exp.Offset) -> str:
    913            return f"{super().offset_sql(expression)} ROWS"
    914
    915        def version_sql(self, expression: exp.Version) -> str:
    916            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    917            this = f"FOR {name}"
    918            expr = expression.expression
    919            kind = expression.text("kind")
    920            if kind in ("FROM", "BETWEEN"):
    921                args = expr.expressions
    922                sep = "TO" if kind == "FROM" else "AND"
    923                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    924            else:
    925                expr_sql = self.sql(expr)
    926
    927            expr_sql = f" {expr_sql}" if expr_sql else ""
    928            return f"{this} {kind}{expr_sql}"
    929
    930        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    931            table = expression.args.get("table")
    932            table = f"{table} " if table else ""
    933            return f"RETURNS {table}{self.sql(expression, 'this')}"
    934
    935        def returning_sql(self, expression: exp.Returning) -> str:
    936            into = self.sql(expression, "into")
    937            into = self.seg(f"INTO {into}") if into else ""
    938            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    939
    940        def transaction_sql(self, expression: exp.Transaction) -> str:
    941            this = self.sql(expression, "this")
    942            this = f" {this}" if this else ""
    943            mark = self.sql(expression, "mark")
    944            mark = f" WITH MARK {mark}" if mark else ""
    945            return f"BEGIN TRANSACTION{this}{mark}"
    946
    947        def commit_sql(self, expression: exp.Commit) -> str:
    948            this = self.sql(expression, "this")
    949            this = f" {this}" if this else ""
    950            durability = expression.args.get("durability")
    951            durability = (
    952                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    953                if durability is not None
    954                else ""
    955            )
    956            return f"COMMIT TRANSACTION{this}{durability}"
    957
    958        def rollback_sql(self, expression: exp.Rollback) -> str:
    959            this = self.sql(expression, "this")
    960            this = f" {this}" if this else ""
    961            return f"ROLLBACK TRANSACTION{this}"
    962
    963        def identifier_sql(self, expression: exp.Identifier) -> str:
    964            identifier = super().identifier_sql(expression)
    965
    966            if expression.args.get("global"):
    967                identifier = f"##{identifier}"
    968            elif expression.args.get("temporary"):
    969                identifier = f"#{identifier}"
    970
    971            return identifier
    972
    973        def constraint_sql(self, expression: exp.Constraint) -> str:
    974            this = self.sql(expression, "this")
    975            expressions = self.expressions(expression, flat=True, sep=" ")
    976            return f"CONSTRAINT {this} {expressions}"
    977
    978        def length_sql(self, expression: exp.Length) -> str:
    979            return self._uncast_text(expression, "LEN")
    980
    981        def right_sql(self, expression: exp.Right) -> str:
    982            return self._uncast_text(expression, "RIGHT")
    983
    984        def left_sql(self, expression: exp.Left) -> str:
    985            return self._uncast_text(expression, "LEFT")
    986
    987        def _uncast_text(self, expression: exp.Expression, name: str) -> str:
    988            this = expression.this
    989            if isinstance(this, exp.Cast) and this.is_type(exp.DataType.Type.TEXT):
    990                this_sql = self.sql(this, "this")
    991            else:
    992                this_sql = self.sql(this)
    993            expression_sql = self.sql(expression, "expression")
    994            return self.func(name, this_sql, expression_sql if expression_sql else None)

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether or not to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Determines whether or not the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True

LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
LIMIT_FETCH = 'FETCH'
COMPUTED_COLUMN_WITH_TYPE = False
CTE_RECURSIVE_KEYWORD_REQUIRED = False
ENSURE_BOOLS = True
NULL_ORDERING_SUPPORTED = None
SUPPORTS_SINGLE_ARG_CONCAT = False
TABLESAMPLE_SEED_KEYWORD = 'REPEATABLE'
SUPPORTS_SELECT_INTO = True
JSON_PATH_BRACKETED_KEY_SUPPORTED = False
EXPRESSIONS_WITHOUT_NESTED_CTES = {<class 'sqlglot.expressions.Union'>, <class 'sqlglot.expressions.Merge'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Subquery'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Delete'>}
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathKey'>}
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.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <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.InheritsProperty'>: <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.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <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.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <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.JSONExtract'>: <function _json_extract_sql>, <class 'sqlglot.expressions.JSONExtractScalar'>: <function _json_extract_sql>, <class 'sqlglot.expressions.LastDay'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.MD5'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Min'>: <function min_or_least>, <class 'sqlglot.expressions.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.ParseJSON'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.SHA'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.SHA2'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
def lateral_op(self, expression: sqlglot.expressions.Lateral ) -> str: View Source

    781        def lateral_op(self, expression: exp.Lateral) -> str:
    782            cross_apply = expression.args.get("cross_apply")
    783            if cross_apply is True:
    784                return "CROSS APPLY"
    785            if cross_apply is False:
    786                return "OUTER APPLY"
    787
    788            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
    789            self.unsupported("LATERAL clause is not supported.")
    790            return "LATERAL"

def timefromparts_sql(self, expression: sqlglot.expressions.TimeFromParts ) -> str: View Source

    792        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
    793            nano = expression.args.get("nano")
    794            if nano is not None:
    795                nano.pop()
    796                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
    797
    798            if expression.args.get("fractions") is None:
    799                expression.set("fractions", exp.Literal.number(0))
    800            if expression.args.get("precision") is None:
    801                expression.set("precision", exp.Literal.number(0))
    802
    803            return rename_func("TIMEFROMPARTS")(self, expression)

def timestampfromparts_sql(self, expression: sqlglot.expressions.TimestampFromParts ) -> str: View Source

    805        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
    806            zone = expression.args.get("zone")
    807            if zone is not None:
    808                zone.pop()
    809                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
    810
    811            nano = expression.args.get("nano")
    812            if nano is not None:
    813                nano.pop()
    814                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
    815
    816            if expression.args.get("milli") is None:
    817                expression.set("milli", exp.Literal.number(0))
    818
    819            return rename_func("DATETIMEFROMPARTS")(self, expression)

def set_operation(self, expression: sqlglot.expressions.Union, op: str) -> str: View Source

    821        def set_operation(self, expression: exp.Union, op: str) -> str:
    822            limit = expression.args.get("limit")
    823            if limit:
    824                return self.sql(expression.limit(limit.pop(), copy=False))
    825
    826            return super().set_operation(expression, op)

def setitem_sql(self, expression: sqlglot.expressions.SetItem ) -> str: View Source

    828        def setitem_sql(self, expression: exp.SetItem) -> str:
    829            this = expression.this
    830            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
    831                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
    832                return f"{self.sql(this.left)} {self.sql(this.right)}"
    833
    834            return super().setitem_sql(expression)

def boolean_sql(self, expression: sqlglot.expressions.Boolean ) -> str: View Source

    836        def boolean_sql(self, expression: exp.Boolean) -> str:
    837            if type(expression.parent) in BIT_TYPES:
    838                return "1" if expression.this else "0"
    839
    840            return "(1 = 1)" if expression.this else "(1 = 0)"

def is_sql(self, expression: sqlglot.expressions.Is ) -> str: View Source

    842        def is_sql(self, expression: exp.Is) -> str:
    843            if isinstance(expression.expression, exp.Boolean):
    844                return self.binary(expression, "=")
    845            return self.binary(expression, "IS")

def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str: View Source

    847        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    848            sql = self.sql(expression, "this")
    849            properties = expression.args.get("properties")
    850
    851            if sql[:1] != "#" and any(
    852                isinstance(prop, exp.TemporaryProperty)
    853                for prop in (properties.expressions if properties else [])
    854            ):
    855                sql = f"#{sql}"
    856
    857            return sql

def create_sql(self, expression: sqlglot.expressions.Create ) -> str: View Source

    859        def create_sql(self, expression: exp.Create) -> str:
    860            kind = self.sql(expression, "kind").upper()
    861            exists = expression.args.pop("exists", None)
    862            sql = super().create_sql(expression)
    863
    864            like_property = expression.find(exp.LikeProperty)
    865            if like_property:
    866                ctas_expression = like_property.this
    867            else:
    868                ctas_expression = expression.expression
    869
    870            table = expression.find(exp.Table)
    871
    872            # Convert CTAS statement to SELECT .. INTO ..
    873            if kind == "TABLE" and ctas_expression:
    874                ctas_with = ctas_expression.args.get("with")
    875                if ctas_with:
    876                    ctas_with = ctas_with.pop()
    877
    878                subquery = ctas_expression
    879                if isinstance(subquery, exp.Subqueryable):
    880                    subquery = subquery.subquery()
    881
    882                select_into = exp.select("*").from_(exp.alias_(subquery, "temp", table=True))
    883                select_into.set("into", exp.Into(this=table))
    884                select_into.set("with", ctas_with)
    885
    886                if like_property:
    887                    select_into.limit(0, copy=False)
    888
    889                sql = self.sql(select_into)
    890
    891            if exists:
    892                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    893                sql = self.sql(exp.Literal.string(sql))
    894                if kind == "SCHEMA":
    895                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
    896                elif kind == "TABLE":
    897                    assert table
    898                    where = exp.and_(
    899                        exp.column("table_name").eq(table.name),
    900                        exp.column("table_schema").eq(table.db) if table.db else None,
    901                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
    902                    )
    903                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
    904                elif kind == "INDEX":
    905                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    906                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
    907            elif expression.args.get("replace"):
    908                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    909
    910            return self.prepend_ctes(expression, sql)

def offset_sql(self, expression: sqlglot.expressions.Offset ) -> str: View Source

    912        def offset_sql(self, expression: exp.Offset) -> str:
    913            return f"{super().offset_sql(expression)} ROWS"

def version_sql(self, expression: sqlglot.expressions.Version ) -> str: View Source

    915        def version_sql(self, expression: exp.Version) -> str:
    916            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    917            this = f"FOR {name}"
    918            expr = expression.expression
    919            kind = expression.text("kind")
    920            if kind in ("FROM", "BETWEEN"):
    921                args = expr.expressions
    922                sep = "TO" if kind == "FROM" else "AND"
    923                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    924            else:
    925                expr_sql = self.sql(expr)
    926
    927            expr_sql = f" {expr_sql}" if expr_sql else ""
    928            return f"{this} {kind}{expr_sql}"

def returnsproperty_sql(self, expression: sqlglot.expressions.ReturnsProperty ) -> str: View Source

    930        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    931            table = expression.args.get("table")
    932            table = f"{table} " if table else ""
    933            return f"RETURNS {table}{self.sql(expression, 'this')}"

def returning_sql(self, expression: sqlglot.expressions.Returning ) -> str: View Source

    935        def returning_sql(self, expression: exp.Returning) -> str:
    936            into = self.sql(expression, "into")
    937            into = self.seg(f"INTO {into}") if into else ""
    938            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"

def transaction_sql(self, expression: sqlglot.expressions.Transaction ) -> str: View Source

    940        def transaction_sql(self, expression: exp.Transaction) -> str:
    941            this = self.sql(expression, "this")
    942            this = f" {this}" if this else ""
    943            mark = self.sql(expression, "mark")
    944            mark = f" WITH MARK {mark}" if mark else ""
    945            return f"BEGIN TRANSACTION{this}{mark}"

def commit_sql(self, expression: sqlglot.expressions.Commit ) -> str: View Source

    947        def commit_sql(self, expression: exp.Commit) -> str:
    948            this = self.sql(expression, "this")
    949            this = f" {this}" if this else ""
    950            durability = expression.args.get("durability")
    951            durability = (
    952                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    953                if durability is not None
    954                else ""
    955            )
    956            return f"COMMIT TRANSACTION{this}{durability}"

def rollback_sql(self, expression: sqlglot.expressions.Rollback ) -> str: View Source

    958        def rollback_sql(self, expression: exp.Rollback) -> str:
    959            this = self.sql(expression, "this")
    960            this = f" {this}" if this else ""
    961            return f"ROLLBACK TRANSACTION{this}"

def identifier_sql(self, expression: sqlglot.expressions.Identifier ) -> str: View Source

    963        def identifier_sql(self, expression: exp.Identifier) -> str:
    964            identifier = super().identifier_sql(expression)
    965
    966            if expression.args.get("global"):
    967                identifier = f"##{identifier}"
    968            elif expression.args.get("temporary"):
    969                identifier = f"#{identifier}"
    970
    971            return identifier

def constraint_sql(self, expression: sqlglot.expressions.Constraint ) -> str: View Source

    973        def constraint_sql(self, expression: exp.Constraint) -> str:
    974            this = self.sql(expression, "this")
    975            expressions = self.expressions(expression, flat=True, sep=" ")
    976            return f"CONSTRAINT {this} {expressions}"

def length_sql(self, expression: sqlglot.expressions.Length ) -> str: View Source

    978        def length_sql(self, expression: exp.Length) -> str:
    979            return self._uncast_text(expression, "LEN")

def right_sql(self, expression: sqlglot.expressions.Right ) -> str: View Source

    981        def right_sql(self, expression: exp.Right) -> str:
    982            return self._uncast_text(expression, "RIGHT")

def left_sql(self, expression: sqlglot.expressions.Left ) -> str: View Source

    984        def left_sql(self, expression: exp.Left) -> str:
    985            return self._uncast_text(expression, "LEFT")

SELECT_KINDS: Tuple[str, ...] = ()

##### Inherited Members

sqlglot.generator.Generator
  Generator
  IGNORE_NULLS_IN_FUNC
  LOCKING_READS_SUPPORTED
  EXPLICIT_UNION
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  LIMIT_ONLY_LITERALS
  RENAME_TABLE_WITH_DB
  GROUPINGS_SEP
  INDEX_ON
  JOIN_HINTS
  TABLE_HINTS
  QUERY_HINT_SEP
  IS_BOOL_ALLOWED
  DUPLICATE_KEY_UPDATE_WITH_SET
  COLUMN_JOIN_MARKS_SUPPORTED
  EXTRACT_ALLOWS_QUOTES
  TZ_TO_WITH_TIME_ZONE
  VALUES_AS_TABLE
  UNNEST_WITH_ORDINALITY
  AGGREGATE_FILTER_SUPPORTED
  SEMI_ANTI_JOIN_WITH_SIDE
  SUPPORTS_TABLE_COPY
  TABLESAMPLE_REQUIRES_PARENS
  TABLESAMPLE_SIZE_IS_ROWS
  TABLESAMPLE_KEYWORDS
  TABLESAMPLE_WITH_METHOD
  COLLATE_IS_FUNC
  DATA_TYPE_SPECIFIERS_ALLOWED
  LAST_DAY_SUPPORTS_DATE_PART
  SUPPORTS_TABLE_ALIAS_COLUMNS
  UNPIVOT_ALIASES_ARE_IDENTIFIERS
  JSON_KEY_VALUE_PAIR_SEP
  INSERT_OVERWRITE
  SUPPORTS_UNLOGGED_TABLES
  SUPPORTS_CREATE_TABLE_LIKE
  LIKE_PROPERTY_INSIDE_SCHEMA
  JSON_TYPE_REQUIRED_FOR_EXTRACTION
  JSON_PATH_SINGLE_QUOTE_ESCAPE
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  EXCLUDE_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  KEY_VALUE_DEFINITIONS
  SENTINEL_LINE_BREAK
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  dialect
  normalize_functions
  unsupported_messages
  generate
  preprocess
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  computedcolumnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  generatedasrowcolumnconstraint_sql
  periodforsystemtimeconstraint_sql
  notnullcolumnconstraint_sql
  transformcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  clone_sql
  describe_sql
  heredoc_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  unicodestring_sql
  rawstring_sql
  datatypeparam_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_name
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  partitionboundspec_sql
  partitionedofproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  withsystemversioningproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  kill_sql
  pseudotype_sql
  objectidentifier_sql
  onconflict_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  historicaldata_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  connect_sql
  prior_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  order_sql
  withfill_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  convert_concat_args
  concat_sql
  concatws_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonpath_sql
  json_path_part
  formatjson_sql
  jsonobject_sql
  jsonobjectagg_sql
  jsonarray_sql
  jsonarrayagg_sql
  jsoncolumndef_sql
  jsonschema_sql
  jsontable_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  pivotalias_sql
  aliases_sql
  atindex_sql
  attimezone_sql
  fromtimezone_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
  currenttimestamp_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  altercolumn_sql
  renametable_sql
  renamecolumn_sql
  altertable_sql
  add_column_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  propertyeq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  log_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql
  clusteredbyproperty_sql
  anyvalue_sql
  querytransform_sql
  indexconstraintoption_sql
  indexcolumnconstraint_sql
  nvl2_sql
  comprehension_sql
  columnprefix_sql
  opclass_sql
  predict_sql
  forin_sql
  refresh_sql
  operator_sql
  toarray_sql
  tsordstotime_sql
  tsordstodate_sql
  unixdate_sql
  lastday_sql