Edit on GitHub

# sqlglot.dialects.tsql

View Source

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

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'}
def generate_date_delta_with_unit_sql( self: sqlglot.generator.Generator, expression: sqlglot.expressions.DateAdd | sqlglot.expressions.DateDiff) -> str: View Source

    129def generate_date_delta_with_unit_sql(
    130    self: generator.Generator, expression: exp.DateAdd | exp.DateDiff
    131) -> str:
    132    func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF"
    133    return self.func(func, expression.text("unit"), expression.expression, expression.this)

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

    170class TSQL(Dialect):
    171    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
    172    NULL_ORDERING = "nulls_are_small"
    173    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
    174
    175    TIME_MAPPING = {
    176        "year": "%Y",
    177        "qq": "%q",
    178        "q": "%q",
    179        "quarter": "%q",
    180        "dayofyear": "%j",
    181        "day": "%d",
    182        "dy": "%d",
    183        "y": "%Y",
    184        "week": "%W",
    185        "ww": "%W",
    186        "wk": "%W",
    187        "hour": "%h",
    188        "hh": "%I",
    189        "minute": "%M",
    190        "mi": "%M",
    191        "n": "%M",
    192        "second": "%S",
    193        "ss": "%S",
    194        "s": "%-S",
    195        "millisecond": "%f",
    196        "ms": "%f",
    197        "weekday": "%W",
    198        "dw": "%W",
    199        "month": "%m",
    200        "mm": "%M",
    201        "m": "%-M",
    202        "Y": "%Y",
    203        "YYYY": "%Y",
    204        "YY": "%y",
    205        "MMMM": "%B",
    206        "MMM": "%b",
    207        "MM": "%m",
    208        "M": "%-m",
    209        "dd": "%d",
    210        "d": "%-d",
    211        "HH": "%H",
    212        "H": "%-H",
    213        "h": "%-I",
    214        "S": "%f",
    215        "yyyy": "%Y",
    216        "yy": "%y",
    217    }
    218
    219    CONVERT_FORMAT_MAPPING = {
    220        "0": "%b %d %Y %-I:%M%p",
    221        "1": "%m/%d/%y",
    222        "2": "%y.%m.%d",
    223        "3": "%d/%m/%y",
    224        "4": "%d.%m.%y",
    225        "5": "%d-%m-%y",
    226        "6": "%d %b %y",
    227        "7": "%b %d, %y",
    228        "8": "%H:%M:%S",
    229        "9": "%b %d %Y %-I:%M:%S:%f%p",
    230        "10": "mm-dd-yy",
    231        "11": "yy/mm/dd",
    232        "12": "yymmdd",
    233        "13": "%d %b %Y %H:%M:ss:%f",
    234        "14": "%H:%M:%S:%f",
    235        "20": "%Y-%m-%d %H:%M:%S",
    236        "21": "%Y-%m-%d %H:%M:%S.%f",
    237        "22": "%m/%d/%y %-I:%M:%S %p",
    238        "23": "%Y-%m-%d",
    239        "24": "%H:%M:%S",
    240        "25": "%Y-%m-%d %H:%M:%S.%f",
    241        "100": "%b %d %Y %-I:%M%p",
    242        "101": "%m/%d/%Y",
    243        "102": "%Y.%m.%d",
    244        "103": "%d/%m/%Y",
    245        "104": "%d.%m.%Y",
    246        "105": "%d-%m-%Y",
    247        "106": "%d %b %Y",
    248        "107": "%b %d, %Y",
    249        "108": "%H:%M:%S",
    250        "109": "%b %d %Y %-I:%M:%S:%f%p",
    251        "110": "%m-%d-%Y",
    252        "111": "%Y/%m/%d",
    253        "112": "%Y%m%d",
    254        "113": "%d %b %Y %H:%M:%S:%f",
    255        "114": "%H:%M:%S:%f",
    256        "120": "%Y-%m-%d %H:%M:%S",
    257        "121": "%Y-%m-%d %H:%M:%S.%f",
    258    }
    259
    260    FORMAT_TIME_MAPPING = {
    261        "y": "%B %Y",
    262        "d": "%m/%d/%Y",
    263        "H": "%-H",
    264        "h": "%-I",
    265        "s": "%Y-%m-%d %H:%M:%S",
    266        "D": "%A,%B,%Y",
    267        "f": "%A,%B,%Y %-I:%M %p",
    268        "F": "%A,%B,%Y %-I:%M:%S %p",
    269        "g": "%m/%d/%Y %-I:%M %p",
    270        "G": "%m/%d/%Y %-I:%M:%S %p",
    271        "M": "%B %-d",
    272        "m": "%B %-d",
    273        "O": "%Y-%m-%dT%H:%M:%S",
    274        "u": "%Y-%M-%D %H:%M:%S%z",
    275        "U": "%A, %B %D, %Y %H:%M:%S%z",
    276        "T": "%-I:%M:%S %p",
    277        "t": "%-I:%M",
    278        "Y": "%a %Y",
    279    }
    280
    281    class Tokenizer(tokens.Tokenizer):
    282        IDENTIFIERS = ['"', ("[", "]")]
    283        QUOTES = ["'", '"']
    284        HEX_STRINGS = [("0x", ""), ("0X", "")]
    285
    286        KEYWORDS = {
    287            **tokens.Tokenizer.KEYWORDS,
    288            "DATETIME2": TokenType.DATETIME,
    289            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
    290            "DECLARE": TokenType.COMMAND,
    291            "IMAGE": TokenType.IMAGE,
    292            "MONEY": TokenType.MONEY,
    293            "NTEXT": TokenType.TEXT,
    294            "NVARCHAR(MAX)": TokenType.TEXT,
    295            "PRINT": TokenType.COMMAND,
    296            "PROC": TokenType.PROCEDURE,
    297            "REAL": TokenType.FLOAT,
    298            "ROWVERSION": TokenType.ROWVERSION,
    299            "SMALLDATETIME": TokenType.DATETIME,
    300            "SMALLMONEY": TokenType.SMALLMONEY,
    301            "SQL_VARIANT": TokenType.VARIANT,
    302            "TIME": TokenType.TIMESTAMP,
    303            "TOP": TokenType.TOP,
    304            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
    305            "VARCHAR(MAX)": TokenType.TEXT,
    306            "XML": TokenType.XML,
    307            "OUTPUT": TokenType.RETURNING,
    308            "SYSTEM_USER": TokenType.CURRENT_USER,
    309        }
    310
    311        # TSQL allows @, # to appear as a variable/identifier prefix
    312        SINGLE_TOKENS = tokens.Tokenizer.SINGLE_TOKENS.copy()
    313        SINGLE_TOKENS.pop("#")
    314
    315    class Parser(parser.Parser):
    316        FUNCTIONS = {
    317            **parser.Parser.FUNCTIONS,
    318            "CHARINDEX": lambda args: exp.StrPosition(
    319                this=seq_get(args, 1),
    320                substr=seq_get(args, 0),
    321                position=seq_get(args, 2),
    322            ),
    323            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
    324            "DATEDIFF": parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
    325            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
    326            "DATEPART": _format_time_lambda(exp.TimeToStr),
    327            "EOMONTH": _parse_eomonth,
    328            "FORMAT": _parse_format,
    329            "GETDATE": exp.CurrentTimestamp.from_arg_list,
    330            "HASHBYTES": _parse_hashbytes,
    331            "IIF": exp.If.from_arg_list,
    332            "ISNULL": exp.Coalesce.from_arg_list,
    333            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
    334            "LEN": exp.Length.from_arg_list,
    335            "REPLICATE": exp.Repeat.from_arg_list,
    336            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    337            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
    338            "SUSER_NAME": exp.CurrentUser.from_arg_list,
    339            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
    340            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
    341        }
    342
    343        JOIN_HINTS = {
    344            "LOOP",
    345            "HASH",
    346            "MERGE",
    347            "REMOTE",
    348        }
    349
    350        VAR_LENGTH_DATATYPES = {
    351            DataType.Type.NVARCHAR,
    352            DataType.Type.VARCHAR,
    353            DataType.Type.CHAR,
    354            DataType.Type.NCHAR,
    355        }
    356
    357        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
    358            TokenType.TABLE,
    359            *parser.Parser.TYPE_TOKENS,
    360        }
    361
    362        STATEMENT_PARSERS = {
    363            **parser.Parser.STATEMENT_PARSERS,
    364            TokenType.END: lambda self: self._parse_command(),
    365        }
    366
    367        LOG_BASE_FIRST = False
    368        LOG_DEFAULTS_TO_LN = True
    369
    370        CONCAT_NULL_OUTPUTS_STRING = True
    371
    372        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
    373            """Applies to SQL Server and Azure SQL Database
    374            COMMIT [ { TRAN | TRANSACTION }
    375                [ transaction_name | @tran_name_variable ] ]
    376                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
    377
    378            ROLLBACK { TRAN | TRANSACTION }
    379                [ transaction_name | @tran_name_variable
    380                | savepoint_name | @savepoint_variable ]
    381            """
    382            rollback = self._prev.token_type == TokenType.ROLLBACK
    383
    384            self._match_texts({"TRAN", "TRANSACTION"})
    385            this = self._parse_id_var()
    386
    387            if rollback:
    388                return self.expression(exp.Rollback, this=this)
    389
    390            durability = None
    391            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
    392                self._match_text_seq("DELAYED_DURABILITY")
    393                self._match(TokenType.EQ)
    394
    395                if self._match_text_seq("OFF"):
    396                    durability = False
    397                else:
    398                    self._match(TokenType.ON)
    399                    durability = True
    400
    401                self._match_r_paren()
    402
    403            return self.expression(exp.Commit, this=this, durability=durability)
    404
    405        def _parse_transaction(self) -> exp.Transaction | exp.Command:
    406            """Applies to SQL Server and Azure SQL Database
    407            BEGIN { TRAN | TRANSACTION }
    408            [ { transaction_name | @tran_name_variable }
    409            [ WITH MARK [ 'description' ] ]
    410            ]
    411            """
    412            if self._match_texts(("TRAN", "TRANSACTION")):
    413                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
    414                if self._match_text_seq("WITH", "MARK"):
    415                    transaction.set("mark", self._parse_string())
    416
    417                return transaction
    418
    419            return self._parse_as_command(self._prev)
    420
    421        def _parse_system_time(self) -> t.Optional[exp.Expression]:
    422            if not self._match_text_seq("FOR", "SYSTEM_TIME"):
    423                return None
    424
    425            if self._match_text_seq("AS", "OF"):
    426                system_time = self.expression(
    427                    exp.SystemTime, this=self._parse_bitwise(), kind="AS OF"
    428                )
    429            elif self._match_set((TokenType.FROM, TokenType.BETWEEN)):
    430                kind = self._prev.text
    431                this = self._parse_bitwise()
    432                self._match_texts(("TO", "AND"))
    433                expression = self._parse_bitwise()
    434                system_time = self.expression(
    435                    exp.SystemTime, this=this, expression=expression, kind=kind
    436                )
    437            elif self._match_text_seq("CONTAINED", "IN"):
    438                args = self._parse_wrapped_csv(self._parse_bitwise)
    439                system_time = self.expression(
    440                    exp.SystemTime,
    441                    this=seq_get(args, 0),
    442                    expression=seq_get(args, 1),
    443                    kind="CONTAINED IN",
    444                )
    445            elif self._match(TokenType.ALL):
    446                system_time = self.expression(exp.SystemTime, kind="ALL")
    447            else:
    448                system_time = None
    449                self.raise_error("Unable to parse FOR SYSTEM_TIME clause")
    450
    451            return system_time
    452
    453        def _parse_table_parts(self, schema: bool = False) -> exp.Table:
    454            table = super()._parse_table_parts(schema=schema)
    455            table.set("system_time", self._parse_system_time())
    456            return table
    457
    458        def _parse_returns(self) -> exp.ReturnsProperty:
    459            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
    460            returns = super()._parse_returns()
    461            returns.set("table", table)
    462            return returns
    463
    464        def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]:
    465            to = self._parse_types()
    466            self._match(TokenType.COMMA)
    467            this = self._parse_conjunction()
    468
    469            if not to or not this:
    470                return None
    471
    472            # Retrieve length of datatype and override to default if not specified
    473            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
    474                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    475
    476            # Check whether a conversion with format is applicable
    477            if self._match(TokenType.COMMA):
    478                format_val = self._parse_number()
    479                format_val_name = format_val.name if format_val else ""
    480
    481                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
    482                    raise ValueError(
    483                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
    484                    )
    485
    486                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
    487
    488                # Check whether the convert entails a string to date format
    489                if to.this == DataType.Type.DATE:
    490                    return self.expression(exp.StrToDate, this=this, format=format_norm)
    491                # Check whether the convert entails a string to datetime format
    492                elif to.this == DataType.Type.DATETIME:
    493                    return self.expression(exp.StrToTime, this=this, format=format_norm)
    494                # Check whether the convert entails a date to string format
    495                elif to.this in self.VAR_LENGTH_DATATYPES:
    496                    return self.expression(
    497                        exp.Cast if strict else exp.TryCast,
    498                        to=to,
    499                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
    500                    )
    501                elif to.this == DataType.Type.TEXT:
    502                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
    503
    504            # Entails a simple cast without any format requirement
    505            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to)
    506
    507        def _parse_user_defined_function(
    508            self, kind: t.Optional[TokenType] = None
    509        ) -> t.Optional[exp.Expression]:
    510            this = super()._parse_user_defined_function(kind=kind)
    511
    512            if (
    513                kind == TokenType.FUNCTION
    514                or isinstance(this, exp.UserDefinedFunction)
    515                or self._match(TokenType.ALIAS, advance=False)
    516            ):
    517                return this
    518
    519            expressions = self._parse_csv(self._parse_function_parameter)
    520            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
    521
    522    class Generator(generator.Generator):
    523        LOCKING_READS_SUPPORTED = True
    524        LIMIT_IS_TOP = True
    525        QUERY_HINTS = False
    526        RETURNING_END = False
    527
    528        TYPE_MAPPING = {
    529            **generator.Generator.TYPE_MAPPING,
    530            exp.DataType.Type.INT: "INTEGER",
    531            exp.DataType.Type.DECIMAL: "NUMERIC",
    532            exp.DataType.Type.DATETIME: "DATETIME2",
    533            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    534        }
    535
    536        TRANSFORMS = {
    537            **generator.Generator.TRANSFORMS,
    538            exp.DateAdd: generate_date_delta_with_unit_sql,
    539            exp.DateDiff: generate_date_delta_with_unit_sql,
    540            exp.CurrentDate: rename_func("GETDATE"),
    541            exp.CurrentTimestamp: rename_func("GETDATE"),
    542            exp.Extract: rename_func("DATEPART"),
    543            exp.GroupConcat: _string_agg_sql,
    544            exp.If: rename_func("IIF"),
    545            exp.Max: max_or_greatest,
    546            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    547            exp.Min: min_or_least,
    548            exp.NumberToStr: _format_sql,
    549            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    550            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    551            exp.SHA2: lambda self, e: self.func(
    552                "HASHBYTES",
    553                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
    554                e.this,
    555            ),
    556            exp.TimeToStr: _format_sql,
    557        }
    558
    559        TRANSFORMS.pop(exp.ReturnsProperty)
    560
    561        PROPERTIES_LOCATION = {
    562            **generator.Generator.PROPERTIES_LOCATION,
    563            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    564        }
    565
    566        LIMIT_FETCH = "FETCH"
    567
    568        def offset_sql(self, expression: exp.Offset) -> str:
    569            return f"{super().offset_sql(expression)} ROWS"
    570
    571        def systemtime_sql(self, expression: exp.SystemTime) -> str:
    572            kind = expression.args["kind"]
    573            if kind == "ALL":
    574                return "FOR SYSTEM_TIME ALL"
    575
    576            start = self.sql(expression, "this")
    577            if kind == "AS OF":
    578                return f"FOR SYSTEM_TIME AS OF {start}"
    579
    580            end = self.sql(expression, "expression")
    581            if kind == "FROM":
    582                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
    583            if kind == "BETWEEN":
    584                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
    585
    586            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
    587
    588        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    589            table = expression.args.get("table")
    590            table = f"{table} " if table else ""
    591            return f"RETURNS {table}{self.sql(expression, 'this')}"
    592
    593        def returning_sql(self, expression: exp.Returning) -> str:
    594            into = self.sql(expression, "into")
    595            into = self.seg(f"INTO {into}") if into else ""
    596            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    597
    598        def transaction_sql(self, expression: exp.Transaction) -> str:
    599            this = self.sql(expression, "this")
    600            this = f" {this}" if this else ""
    601            mark = self.sql(expression, "mark")
    602            mark = f" WITH MARK {mark}" if mark else ""
    603            return f"BEGIN TRANSACTION{this}{mark}"
    604
    605        def commit_sql(self, expression: exp.Commit) -> str:
    606            this = self.sql(expression, "this")
    607            this = f" {this}" if this else ""
    608            durability = expression.args.get("durability")
    609            durability = (
    610                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    611                if durability is not None
    612                else ""
    613            )
    614            return f"COMMIT TRANSACTION{this}{durability}"
    615
    616        def rollback_sql(self, expression: exp.Rollback) -> str:
    617            this = self.sql(expression, "this")
    618            this = f" {this}" if this else ""
    619            return f"ROLLBACK TRANSACTION{this}"

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

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  DATE_FORMAT
  DATEINT_FORMAT
  FORMAT_MAPPING
  get_or_raise
  format_time
  normalize_identifier
  case_sensitive
  can_identify
  quote_identifier
  parse
  parse_into
  generate
  transpile
  tokenize
  tokenizer
  parser
  generator

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

    281    class Tokenizer(tokens.Tokenizer):
    282        IDENTIFIERS = ['"', ("[", "]")]
    283        QUOTES = ["'", '"']
    284        HEX_STRINGS = [("0x", ""), ("0X", "")]
    285
    286        KEYWORDS = {
    287            **tokens.Tokenizer.KEYWORDS,
    288            "DATETIME2": TokenType.DATETIME,
    289            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
    290            "DECLARE": TokenType.COMMAND,
    291            "IMAGE": TokenType.IMAGE,
    292            "MONEY": TokenType.MONEY,
    293            "NTEXT": TokenType.TEXT,
    294            "NVARCHAR(MAX)": TokenType.TEXT,
    295            "PRINT": TokenType.COMMAND,
    296            "PROC": TokenType.PROCEDURE,
    297            "REAL": TokenType.FLOAT,
    298            "ROWVERSION": TokenType.ROWVERSION,
    299            "SMALLDATETIME": TokenType.DATETIME,
    300            "SMALLMONEY": TokenType.SMALLMONEY,
    301            "SQL_VARIANT": TokenType.VARIANT,
    302            "TIME": TokenType.TIMESTAMP,
    303            "TOP": TokenType.TOP,
    304            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
    305            "VARCHAR(MAX)": TokenType.TEXT,
    306            "XML": TokenType.XML,
    307            "OUTPUT": TokenType.RETURNING,
    308            "SYSTEM_USER": TokenType.CURRENT_USER,
    309        }
    310
    311        # TSQL allows @, # to appear as a variable/identifier prefix
    312        SINGLE_TOKENS = tokens.Tokenizer.SINGLE_TOKENS.copy()
    313        SINGLE_TOKENS.pop("#")

IDENTIFIERS = ['"', ('[', ']')]
QUOTES = ["'", '"']
HEX_STRINGS = [('0x', ''), ('0X', '')]
KEYWORDS = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'IF': <TokenType.IF: 'IF'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NEXT VALUE FOR': <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.BIGINT: 'BIGINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, 'NVARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'PRINT': <TokenType.COMMAND: 'COMMAND'>, 'PROC': <TokenType.PROCEDURE: 'PROCEDURE'>, 'ROWVERSION': <TokenType.ROWVERSION: 'ROWVERSION'>, 'SMALLDATETIME': <TokenType.DATETIME: 'DATETIME'>, 'SMALLMONEY': <TokenType.SMALLMONEY: 'SMALLMONEY'>, 'SQL_VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'TOP': <TokenType.TOP: 'TOP'>, 'UNIQUEIDENTIFIER': <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>}
SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>}

##### Inherited Members

sqlglot.tokens.Tokenizer
  BIT_STRINGS
  BYTE_STRINGS
  RAW_STRINGS
  IDENTIFIER_ESCAPES
  STRING_ESCAPES
  VAR_SINGLE_TOKENS
  IDENTIFIERS_CAN_START_WITH_DIGIT
  WHITE_SPACE
  COMMANDS
  COMMAND_PREFIX_TOKENS
  NUMERIC_LITERALS
  ENCODE
  COMMENTS
  reset
  tokenize
  peek
  size
  sql
  tokens

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

    315    class Parser(parser.Parser):
    316        FUNCTIONS = {
    317            **parser.Parser.FUNCTIONS,
    318            "CHARINDEX": lambda args: exp.StrPosition(
    319                this=seq_get(args, 1),
    320                substr=seq_get(args, 0),
    321                position=seq_get(args, 2),
    322            ),
    323            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
    324            "DATEDIFF": parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
    325            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
    326            "DATEPART": _format_time_lambda(exp.TimeToStr),
    327            "EOMONTH": _parse_eomonth,
    328            "FORMAT": _parse_format,
    329            "GETDATE": exp.CurrentTimestamp.from_arg_list,
    330            "HASHBYTES": _parse_hashbytes,
    331            "IIF": exp.If.from_arg_list,
    332            "ISNULL": exp.Coalesce.from_arg_list,
    333            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
    334            "LEN": exp.Length.from_arg_list,
    335            "REPLICATE": exp.Repeat.from_arg_list,
    336            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    337            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
    338            "SUSER_NAME": exp.CurrentUser.from_arg_list,
    339            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
    340            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
    341        }
    342
    343        JOIN_HINTS = {
    344            "LOOP",
    345            "HASH",
    346            "MERGE",
    347            "REMOTE",
    348        }
    349
    350        VAR_LENGTH_DATATYPES = {
    351            DataType.Type.NVARCHAR,
    352            DataType.Type.VARCHAR,
    353            DataType.Type.CHAR,
    354            DataType.Type.NCHAR,
    355        }
    356
    357        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
    358            TokenType.TABLE,
    359            *parser.Parser.TYPE_TOKENS,
    360        }
    361
    362        STATEMENT_PARSERS = {
    363            **parser.Parser.STATEMENT_PARSERS,
    364            TokenType.END: lambda self: self._parse_command(),
    365        }
    366
    367        LOG_BASE_FIRST = False
    368        LOG_DEFAULTS_TO_LN = True
    369
    370        CONCAT_NULL_OUTPUTS_STRING = True
    371
    372        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
    373            """Applies to SQL Server and Azure SQL Database
    374            COMMIT [ { TRAN | TRANSACTION }
    375                [ transaction_name | @tran_name_variable ] ]
    376                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
    377
    378            ROLLBACK { TRAN | TRANSACTION }
    379                [ transaction_name | @tran_name_variable
    380                | savepoint_name | @savepoint_variable ]
    381            """
    382            rollback = self._prev.token_type == TokenType.ROLLBACK
    383
    384            self._match_texts({"TRAN", "TRANSACTION"})
    385            this = self._parse_id_var()
    386
    387            if rollback:
    388                return self.expression(exp.Rollback, this=this)
    389
    390            durability = None
    391            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
    392                self._match_text_seq("DELAYED_DURABILITY")
    393                self._match(TokenType.EQ)
    394
    395                if self._match_text_seq("OFF"):
    396                    durability = False
    397                else:
    398                    self._match(TokenType.ON)
    399                    durability = True
    400
    401                self._match_r_paren()
    402
    403            return self.expression(exp.Commit, this=this, durability=durability)
    404
    405        def _parse_transaction(self) -> exp.Transaction | exp.Command:
    406            """Applies to SQL Server and Azure SQL Database
    407            BEGIN { TRAN | TRANSACTION }
    408            [ { transaction_name | @tran_name_variable }
    409            [ WITH MARK [ 'description' ] ]
    410            ]
    411            """
    412            if self._match_texts(("TRAN", "TRANSACTION")):
    413                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
    414                if self._match_text_seq("WITH", "MARK"):
    415                    transaction.set("mark", self._parse_string())
    416
    417                return transaction
    418
    419            return self._parse_as_command(self._prev)
    420
    421        def _parse_system_time(self) -> t.Optional[exp.Expression]:
    422            if not self._match_text_seq("FOR", "SYSTEM_TIME"):
    423                return None
    424
    425            if self._match_text_seq("AS", "OF"):
    426                system_time = self.expression(
    427                    exp.SystemTime, this=self._parse_bitwise(), kind="AS OF"
    428                )
    429            elif self._match_set((TokenType.FROM, TokenType.BETWEEN)):
    430                kind = self._prev.text
    431                this = self._parse_bitwise()
    432                self._match_texts(("TO", "AND"))
    433                expression = self._parse_bitwise()
    434                system_time = self.expression(
    435                    exp.SystemTime, this=this, expression=expression, kind=kind
    436                )
    437            elif self._match_text_seq("CONTAINED", "IN"):
    438                args = self._parse_wrapped_csv(self._parse_bitwise)
    439                system_time = self.expression(
    440                    exp.SystemTime,
    441                    this=seq_get(args, 0),
    442                    expression=seq_get(args, 1),
    443                    kind="CONTAINED IN",
    444                )
    445            elif self._match(TokenType.ALL):
    446                system_time = self.expression(exp.SystemTime, kind="ALL")
    447            else:
    448                system_time = None
    449                self.raise_error("Unable to parse FOR SYSTEM_TIME clause")
    450
    451            return system_time
    452
    453        def _parse_table_parts(self, schema: bool = False) -> exp.Table:
    454            table = super()._parse_table_parts(schema=schema)
    455            table.set("system_time", self._parse_system_time())
    456            return table
    457
    458        def _parse_returns(self) -> exp.ReturnsProperty:
    459            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
    460            returns = super()._parse_returns()
    461            returns.set("table", table)
    462            return returns
    463
    464        def _parse_convert(self, strict: bool) -> t.Optional[exp.Expression]:
    465            to = self._parse_types()
    466            self._match(TokenType.COMMA)
    467            this = self._parse_conjunction()
    468
    469            if not to or not this:
    470                return None
    471
    472            # Retrieve length of datatype and override to default if not specified
    473            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
    474                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    475
    476            # Check whether a conversion with format is applicable
    477            if self._match(TokenType.COMMA):
    478                format_val = self._parse_number()
    479                format_val_name = format_val.name if format_val else ""
    480
    481                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
    482                    raise ValueError(
    483                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
    484                    )
    485
    486                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
    487
    488                # Check whether the convert entails a string to date format
    489                if to.this == DataType.Type.DATE:
    490                    return self.expression(exp.StrToDate, this=this, format=format_norm)
    491                # Check whether the convert entails a string to datetime format
    492                elif to.this == DataType.Type.DATETIME:
    493                    return self.expression(exp.StrToTime, this=this, format=format_norm)
    494                # Check whether the convert entails a date to string format
    495                elif to.this in self.VAR_LENGTH_DATATYPES:
    496                    return self.expression(
    497                        exp.Cast if strict else exp.TryCast,
    498                        to=to,
    499                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
    500                    )
    501                elif to.this == DataType.Type.TEXT:
    502                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
    503
    504            # Entails a simple cast without any format requirement
    505            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to)
    506
    507        def _parse_user_defined_function(
    508            self, kind: t.Optional[TokenType] = None
    509        ) -> t.Optional[exp.Expression]:
    510            this = super()._parse_user_defined_function(kind=kind)
    511
    512            if (
    513                kind == TokenType.FUNCTION
    514                or isinstance(this, exp.UserDefinedFunction)
    515                or self._match(TokenType.ALIAS, advance=False)
    516            ):
    517                return this
    518
    519            expressions = self._parse_csv(self._parse_function_parameter)
    520            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)

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

###### Arguments:

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

FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'LAST_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log'>>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SET_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SetAgg'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
JOIN_HINTS = {'HASH', 'LOOP', 'MERGE', 'REMOTE'}
VAR_LENGTH_DATATYPES = {<Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.ANY: 'ANY'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.SET: 'SET'>, <TokenType.DELETE: 'DELETE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.ROWS: 'ROWS'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.FILTER: 'FILTER'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.IS: 'IS'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.FALSE: 'FALSE'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.MERGE: 'MERGE'>, <TokenType.FULL: 'FULL'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.VAR: 'VAR'>, <TokenType.KEEP: 'KEEP'>, <TokenType.END: 'END'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CACHE: 'CACHE'>, <TokenType.DIV: 'DIV'>, <TokenType.TRUE: 'TRUE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.VIEW: 'VIEW'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.SOME: 'SOME'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.SEMI: 'SEMI'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.DESC: 'DESC'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.ALL: 'ALL'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.IF: 'IF'>, <TokenType.APPLY: 'APPLY'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.ASC: 'ASC'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.LEFT: 'LEFT'>, <TokenType.CASE: 'CASE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.TOP: 'TOP'>, <TokenType.FIRST: 'FIRST'>, <TokenType.SHOW: 'SHOW'>, <TokenType.ANTI: 'ANTI'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.ROW: 'ROW'>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.FROM: 'FROM'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
LOG_BASE_FIRST = False
LOG_DEFAULTS_TO_LN = True
CONCAT_NULL_OUTPUTS_STRING = True
NULL_ORDERING: str = 'nulls_are_small'
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
FORMAT_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
TIME_MAPPING: Dict[str, str] = {'year': '%Y', 'qq': '%q', 'q': '%q', 'quarter': '%q', 'dayofyear': '%j', 'day': '%d', 'dy': '%d', 'y': '%Y', 'week': '%W', 'ww': '%W', 'wk': '%W', 'hour': '%h', 'hh': '%I', 'minute': '%M', 'mi': '%M', 'n': '%M', 'second': '%S', 'ss': '%S', 's': '%-S', 'millisecond': '%f', 'ms': '%f', 'weekday': '%W', 'dw': '%W', 'month': '%m', 'mm': '%M', 'm': '%-M', 'Y': '%Y', 'YYYY': '%Y', 'YY': '%y', 'MMMM': '%B', 'MMM': '%b', 'MM': '%m', 'M': '%-m', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  TYPE_TOKENS
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  TABLE_ALIAS_TOKENS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  FUNC_TOKENS
  CONJUNCTION
  EQUALITY
  COMPARISON
  BITWISE
  TERM
  FACTOR
  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
  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_KINDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  ADD_CONSTRAINT_TOKENS
  STRICT_CAST
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  FORMAT_MAPPING
  error_level
  error_message_context
  max_errors
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

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

    522    class Generator(generator.Generator):
    523        LOCKING_READS_SUPPORTED = True
    524        LIMIT_IS_TOP = True
    525        QUERY_HINTS = False
    526        RETURNING_END = False
    527
    528        TYPE_MAPPING = {
    529            **generator.Generator.TYPE_MAPPING,
    530            exp.DataType.Type.INT: "INTEGER",
    531            exp.DataType.Type.DECIMAL: "NUMERIC",
    532            exp.DataType.Type.DATETIME: "DATETIME2",
    533            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    534        }
    535
    536        TRANSFORMS = {
    537            **generator.Generator.TRANSFORMS,
    538            exp.DateAdd: generate_date_delta_with_unit_sql,
    539            exp.DateDiff: generate_date_delta_with_unit_sql,
    540            exp.CurrentDate: rename_func("GETDATE"),
    541            exp.CurrentTimestamp: rename_func("GETDATE"),
    542            exp.Extract: rename_func("DATEPART"),
    543            exp.GroupConcat: _string_agg_sql,
    544            exp.If: rename_func("IIF"),
    545            exp.Max: max_or_greatest,
    546            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    547            exp.Min: min_or_least,
    548            exp.NumberToStr: _format_sql,
    549            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    550            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    551            exp.SHA2: lambda self, e: self.func(
    552                "HASHBYTES",
    553                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
    554                e.this,
    555            ),
    556            exp.TimeToStr: _format_sql,
    557        }
    558
    559        TRANSFORMS.pop(exp.ReturnsProperty)
    560
    561        PROPERTIES_LOCATION = {
    562            **generator.Generator.PROPERTIES_LOCATION,
    563            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    564        }
    565
    566        LIMIT_FETCH = "FETCH"
    567
    568        def offset_sql(self, expression: exp.Offset) -> str:
    569            return f"{super().offset_sql(expression)} ROWS"
    570
    571        def systemtime_sql(self, expression: exp.SystemTime) -> str:
    572            kind = expression.args["kind"]
    573            if kind == "ALL":
    574                return "FOR SYSTEM_TIME ALL"
    575
    576            start = self.sql(expression, "this")
    577            if kind == "AS OF":
    578                return f"FOR SYSTEM_TIME AS OF {start}"
    579
    580            end = self.sql(expression, "expression")
    581            if kind == "FROM":
    582                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
    583            if kind == "BETWEEN":
    584                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
    585
    586            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"
    587
    588        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    589            table = expression.args.get("table")
    590            table = f"{table} " if table else ""
    591            return f"RETURNS {table}{self.sql(expression, 'this')}"
    592
    593        def returning_sql(self, expression: exp.Returning) -> str:
    594            into = self.sql(expression, "into")
    595            into = self.seg(f"INTO {into}") if into else ""
    596            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    597
    598        def transaction_sql(self, expression: exp.Transaction) -> str:
    599            this = self.sql(expression, "this")
    600            this = f" {this}" if this else ""
    601            mark = self.sql(expression, "mark")
    602            mark = f" WITH MARK {mark}" if mark else ""
    603            return f"BEGIN TRANSACTION{this}{mark}"
    604
    605        def commit_sql(self, expression: exp.Commit) -> str:
    606            this = self.sql(expression, "this")
    607            this = f" {this}" if this else ""
    608            durability = expression.args.get("durability")
    609            durability = (
    610                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    611                if durability is not None
    612                else ""
    613            )
    614            return f"COMMIT TRANSACTION{this}{durability}"
    615
    616        def rollback_sql(self, expression: exp.Rollback) -> str:
    617            this = self.sql(expression, "this")
    618            this = f" {this}" if this else ""
    619            return f"ROLLBACK TRANSACTION{this}"

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

###### Arguments:

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

LOCKING_READS_SUPPORTED = True
LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.INT: 'INT'>: 'INTEGER', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function generate_date_delta_with_unit_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function generate_date_delta_with_unit_sql>, <class 'sqlglot.expressions.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Extract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.MD5'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Min'>: <function min_or_least>, <class 'sqlglot.expressions.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.SHA'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.SHA2'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
LIMIT_FETCH = 'FETCH'
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str: View Source

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

def systemtime_sql(self, expression: sqlglot.expressions.SystemTime) -> str: View Source

    571        def systemtime_sql(self, expression: exp.SystemTime) -> str:
    572            kind = expression.args["kind"]
    573            if kind == "ALL":
    574                return "FOR SYSTEM_TIME ALL"
    575
    576            start = self.sql(expression, "this")
    577            if kind == "AS OF":
    578                return f"FOR SYSTEM_TIME AS OF {start}"
    579
    580            end = self.sql(expression, "expression")
    581            if kind == "FROM":
    582                return f"FOR SYSTEM_TIME FROM {start} TO {end}"
    583            if kind == "BETWEEN":
    584                return f"FOR SYSTEM_TIME BETWEEN {start} AND {end}"
    585
    586            return f"FOR SYSTEM_TIME CONTAINED IN ({start}, {end})"

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

    588        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    589            table = expression.args.get("table")
    590            table = f"{table} " if table else ""
    591            return f"RETURNS {table}{self.sql(expression, 'this')}"

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

    593        def returning_sql(self, expression: exp.Returning) -> str:
    594            into = self.sql(expression, "into")
    595            into = self.seg(f"INTO {into}") if into else ""
    596            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"

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

    598        def transaction_sql(self, expression: exp.Transaction) -> str:
    599            this = self.sql(expression, "this")
    600            this = f" {this}" if this else ""
    601            mark = self.sql(expression, "mark")
    602            mark = f" WITH MARK {mark}" if mark else ""
    603            return f"BEGIN TRANSACTION{this}{mark}"

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

    605        def commit_sql(self, expression: exp.Commit) -> str:
    606            this = self.sql(expression, "this")
    607            this = f" {this}" if this else ""
    608            durability = expression.args.get("durability")
    609            durability = (
    610                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    611                if durability is not None
    612                else ""
    613            )
    614            return f"COMMIT TRANSACTION{this}{durability}"

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

    616        def rollback_sql(self, expression: exp.Rollback) -> str:
    617            this = self.sql(expression, "this")
    618            this = f" {this}" if this else ""
    619            return f"ROLLBACK TRANSACTION{this}"

SELECT_KINDS: Tuple[str, ...] = ()
INVERSE_TIME_MAPPING: Dict[str, str] = {'%Y': 'yyyy', '%q': 'quarter', '%j': 'dayofyear', '%d': 'dd', '%W': 'dw', '%h': 'hour', '%I': 'hh', '%M': 'mm', '%S': 'ss', '%-S': 's', '%f': 'S', '%m': 'MM', '%-M': 'm', '%y': 'yy', '%B': 'MMMM', '%b': 'MMM', '%-m': 'M', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict = {'%': {'Y': {0: True}, 'q': {0: True}, 'j': {0: True}, 'd': {0: True}, 'W': {0: True}, 'h': {0: True}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, '-': {'S': {0: True}, 'M': {0: True}, 'm': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'f': {0: True}, 'm': {0: True}, 'y': {0: True}, 'B': {0: True}, 'b': {0: True}, 'H': {0: True}}}
NULL_ORDERING = 'nulls_are_small'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    246    @classmethod
    247    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    248        """Checks if text can be identified given an identify option.
    249
    250        Args:
    251            text: The text to check.
    252            identify:
    253                "always" or `True`: Always returns true.
    254                "safe": True if the identifier is case-insensitive.
    255
    256        Returns:
    257            Whether or not the given text can be identified.
    258        """
    259        if identify is True or identify == "always":
    260            return True
    261
    262        if identify == "safe":
    263            return not cls.case_sensitive(text)
    264
    265        return False

Checks if text can be identified given an identify option.

###### Arguments:

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

###### Returns:

> Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
STRING_ESCAPE = "'"
IDENTIFIER_ESCAPE = '"'
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None

##### Inherited Members

sqlglot.generator.Generator
  Generator
  NULL_ORDERING_SUPPORTED
  EXPLICIT_UNION
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  TABLESAMPLE_WITH_METHOD
  TABLESAMPLE_SIZE_IS_PERCENT
  RENAME_TABLE_WITH_DB
  GROUPINGS_SEP
  INDEX_ON
  JOIN_HINTS
  TABLE_HINTS
  QUERY_HINT_SEP
  IS_BOOL_ALLOWED
  DUPLICATE_KEY_UPDATE_WITH_SET
  COLUMN_JOIN_MARKS_SUPPORTED
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  SENTINEL_LINE_BREAK
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  ESCAPE_LINE_BREAK
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  normalize_functions
  unsupported_messages
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  createable_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  onconflict_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  safebracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  xor_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  safedpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql
  clusteredbyproperty_sql
  anyvalue_sql