sqlglot.dialects.tsql API documentation

Edit on GitHub

# sqlglot.dialects.tsql

View Source

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

FULL_FORMAT_TIME_MAPPING = {'weekday': '%A', 'dw': '%A', 'w': '%A', 'month': '%B', 'mm': '%B', 'm': '%B'}
DATE_DELTA_INTERVAL = {'year': 'year', 'yyyy': 'year', 'yy': 'year', 'quarter': 'quarter', 'qq': 'quarter', 'q': 'quarter', 'month': 'month', 'mm': 'month', 'm': 'month', 'week': 'week', 'ww': 'week', 'wk': 'week', 'day': 'day', 'dd': 'day', 'd': 'day'}
DATE_FMT_RE = re.compile('([dD]{1,2})|([mM]{1,2})|([yY]{1,4})|([hH]{1,2})|([sS]{1,2})')
TRANSPILE_SAFE_NUMBER_FMT = {'N', 'C'}
DEFAULT_START_DATE = datetime.date(1900, 1, 1)
BIT_TYPES = {<class 'sqlglot.expressions.Alias'>, <class 'sqlglot.expressions.In'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.NEQ'>, <class 'sqlglot.expressions.Is'>, <class 'sqlglot.expressions.EQ'>}
def generate_date_delta_with_unit_sql( self: TSQL.Generator, expression: sqlglot.expressions.DateAdd | sqlglot.expressions.DateDiff) -> str: View Source

    139def generate_date_delta_with_unit_sql(
    140    self: TSQL.Generator, expression: exp.DateAdd | exp.DateDiff
    141) -> str:
    142    func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF"
    143    return self.func(func, expression.text("unit"), expression.expression, expression.this)

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

    206class TSQL(Dialect):
    207    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
    208    NULL_ORDERING = "nulls_are_small"
    209    TIME_FORMAT = "'yyyy-mm-dd hh:mm:ss'"
    210    SUPPORTS_SEMI_ANTI_JOIN = False
    211    LOG_BASE_FIRST = False
    212
    213    TIME_MAPPING = {
    214        "year": "%Y",
    215        "qq": "%q",
    216        "q": "%q",
    217        "quarter": "%q",
    218        "dayofyear": "%j",
    219        "day": "%d",
    220        "dy": "%d",
    221        "y": "%Y",
    222        "week": "%W",
    223        "ww": "%W",
    224        "wk": "%W",
    225        "hour": "%h",
    226        "hh": "%I",
    227        "minute": "%M",
    228        "mi": "%M",
    229        "n": "%M",
    230        "second": "%S",
    231        "ss": "%S",
    232        "s": "%-S",
    233        "millisecond": "%f",
    234        "ms": "%f",
    235        "weekday": "%W",
    236        "dw": "%W",
    237        "month": "%m",
    238        "mm": "%M",
    239        "m": "%-M",
    240        "Y": "%Y",
    241        "YYYY": "%Y",
    242        "YY": "%y",
    243        "MMMM": "%B",
    244        "MMM": "%b",
    245        "MM": "%m",
    246        "M": "%-m",
    247        "dddd": "%A",
    248        "dd": "%d",
    249        "d": "%-d",
    250        "HH": "%H",
    251        "H": "%-H",
    252        "h": "%-I",
    253        "S": "%f",
    254        "yyyy": "%Y",
    255        "yy": "%y",
    256    }
    257
    258    CONVERT_FORMAT_MAPPING = {
    259        "0": "%b %d %Y %-I:%M%p",
    260        "1": "%m/%d/%y",
    261        "2": "%y.%m.%d",
    262        "3": "%d/%m/%y",
    263        "4": "%d.%m.%y",
    264        "5": "%d-%m-%y",
    265        "6": "%d %b %y",
    266        "7": "%b %d, %y",
    267        "8": "%H:%M:%S",
    268        "9": "%b %d %Y %-I:%M:%S:%f%p",
    269        "10": "mm-dd-yy",
    270        "11": "yy/mm/dd",
    271        "12": "yymmdd",
    272        "13": "%d %b %Y %H:%M:ss:%f",
    273        "14": "%H:%M:%S:%f",
    274        "20": "%Y-%m-%d %H:%M:%S",
    275        "21": "%Y-%m-%d %H:%M:%S.%f",
    276        "22": "%m/%d/%y %-I:%M:%S %p",
    277        "23": "%Y-%m-%d",
    278        "24": "%H:%M:%S",
    279        "25": "%Y-%m-%d %H:%M:%S.%f",
    280        "100": "%b %d %Y %-I:%M%p",
    281        "101": "%m/%d/%Y",
    282        "102": "%Y.%m.%d",
    283        "103": "%d/%m/%Y",
    284        "104": "%d.%m.%Y",
    285        "105": "%d-%m-%Y",
    286        "106": "%d %b %Y",
    287        "107": "%b %d, %Y",
    288        "108": "%H:%M:%S",
    289        "109": "%b %d %Y %-I:%M:%S:%f%p",
    290        "110": "%m-%d-%Y",
    291        "111": "%Y/%m/%d",
    292        "112": "%Y%m%d",
    293        "113": "%d %b %Y %H:%M:%S:%f",
    294        "114": "%H:%M:%S:%f",
    295        "120": "%Y-%m-%d %H:%M:%S",
    296        "121": "%Y-%m-%d %H:%M:%S.%f",
    297    }
    298
    299    FORMAT_TIME_MAPPING = {
    300        "y": "%B %Y",
    301        "d": "%m/%d/%Y",
    302        "H": "%-H",
    303        "h": "%-I",
    304        "s": "%Y-%m-%d %H:%M:%S",
    305        "D": "%A,%B,%Y",
    306        "f": "%A,%B,%Y %-I:%M %p",
    307        "F": "%A,%B,%Y %-I:%M:%S %p",
    308        "g": "%m/%d/%Y %-I:%M %p",
    309        "G": "%m/%d/%Y %-I:%M:%S %p",
    310        "M": "%B %-d",
    311        "m": "%B %-d",
    312        "O": "%Y-%m-%dT%H:%M:%S",
    313        "u": "%Y-%M-%D %H:%M:%S%z",
    314        "U": "%A, %B %D, %Y %H:%M:%S%z",
    315        "T": "%-I:%M:%S %p",
    316        "t": "%-I:%M",
    317        "Y": "%a %Y",
    318    }
    319
    320    class Tokenizer(tokens.Tokenizer):
    321        IDENTIFIERS = ['"', ("[", "]")]
    322        QUOTES = ["'", '"']
    323        HEX_STRINGS = [("0x", ""), ("0X", "")]
    324
    325        KEYWORDS = {
    326            **tokens.Tokenizer.KEYWORDS,
    327            "DATETIME2": TokenType.DATETIME,
    328            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
    329            "DECLARE": TokenType.COMMAND,
    330            "IMAGE": TokenType.IMAGE,
    331            "MONEY": TokenType.MONEY,
    332            "NTEXT": TokenType.TEXT,
    333            "NVARCHAR(MAX)": TokenType.TEXT,
    334            "PRINT": TokenType.COMMAND,
    335            "PROC": TokenType.PROCEDURE,
    336            "REAL": TokenType.FLOAT,
    337            "ROWVERSION": TokenType.ROWVERSION,
    338            "SMALLDATETIME": TokenType.DATETIME,
    339            "SMALLMONEY": TokenType.SMALLMONEY,
    340            "SQL_VARIANT": TokenType.VARIANT,
    341            "TOP": TokenType.TOP,
    342            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
    343            "UPDATE STATISTICS": TokenType.COMMAND,
    344            "VARCHAR(MAX)": TokenType.TEXT,
    345            "XML": TokenType.XML,
    346            "OUTPUT": TokenType.RETURNING,
    347            "SYSTEM_USER": TokenType.CURRENT_USER,
    348            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
    349        }
    350
    351    class Parser(parser.Parser):
    352        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
    353
    354        FUNCTIONS = {
    355            **parser.Parser.FUNCTIONS,
    356            "CHARINDEX": lambda args: exp.StrPosition(
    357                this=seq_get(args, 1),
    358                substr=seq_get(args, 0),
    359                position=seq_get(args, 2),
    360            ),
    361            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
    362            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
    363            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
    364            "DATEPART": _format_time_lambda(exp.TimeToStr),
    365            "EOMONTH": _parse_eomonth,
    366            "FORMAT": _parse_format,
    367            "GETDATE": exp.CurrentTimestamp.from_arg_list,
    368            "HASHBYTES": _parse_hashbytes,
    369            "IIF": exp.If.from_arg_list,
    370            "ISNULL": exp.Coalesce.from_arg_list,
    371            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
    372            "LEN": exp.Length.from_arg_list,
    373            "REPLICATE": exp.Repeat.from_arg_list,
    374            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    375            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
    376            "SUSER_NAME": exp.CurrentUser.from_arg_list,
    377            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
    378            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
    379        }
    380
    381        JOIN_HINTS = {
    382            "LOOP",
    383            "HASH",
    384            "MERGE",
    385            "REMOTE",
    386        }
    387
    388        VAR_LENGTH_DATATYPES = {
    389            DataType.Type.NVARCHAR,
    390            DataType.Type.VARCHAR,
    391            DataType.Type.CHAR,
    392            DataType.Type.NCHAR,
    393        }
    394
    395        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
    396            TokenType.TABLE,
    397            *parser.Parser.TYPE_TOKENS,
    398        }
    399
    400        STATEMENT_PARSERS = {
    401            **parser.Parser.STATEMENT_PARSERS,
    402            TokenType.END: lambda self: self._parse_command(),
    403        }
    404
    405        LOG_DEFAULTS_TO_LN = True
    406
    407        CONCAT_NULL_OUTPUTS_STRING = True
    408
    409        ALTER_TABLE_ADD_COLUMN_KEYWORD = False
    410
    411        def _parse_projections(self) -> t.List[exp.Expression]:
    412            """
    413            T-SQL supports the syntax alias = expression in the SELECT's projection list,
    414            so we transform all parsed Selects to convert their EQ projections into Aliases.
    415
    416            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
    417            """
    418            return [
    419                exp.alias_(projection.expression, projection.this.this, copy=False)
    420                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
    421                else projection
    422                for projection in super()._parse_projections()
    423            ]
    424
    425        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
    426            """Applies to SQL Server and Azure SQL Database
    427            COMMIT [ { TRAN | TRANSACTION }
    428                [ transaction_name | @tran_name_variable ] ]
    429                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
    430
    431            ROLLBACK { TRAN | TRANSACTION }
    432                [ transaction_name | @tran_name_variable
    433                | savepoint_name | @savepoint_variable ]
    434            """
    435            rollback = self._prev.token_type == TokenType.ROLLBACK
    436
    437            self._match_texts({"TRAN", "TRANSACTION"})
    438            this = self._parse_id_var()
    439
    440            if rollback:
    441                return self.expression(exp.Rollback, this=this)
    442
    443            durability = None
    444            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
    445                self._match_text_seq("DELAYED_DURABILITY")
    446                self._match(TokenType.EQ)
    447
    448                if self._match_text_seq("OFF"):
    449                    durability = False
    450                else:
    451                    self._match(TokenType.ON)
    452                    durability = True
    453
    454                self._match_r_paren()
    455
    456            return self.expression(exp.Commit, this=this, durability=durability)
    457
    458        def _parse_transaction(self) -> exp.Transaction | exp.Command:
    459            """Applies to SQL Server and Azure SQL Database
    460            BEGIN { TRAN | TRANSACTION }
    461            [ { transaction_name | @tran_name_variable }
    462            [ WITH MARK [ 'description' ] ]
    463            ]
    464            """
    465            if self._match_texts(("TRAN", "TRANSACTION")):
    466                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
    467                if self._match_text_seq("WITH", "MARK"):
    468                    transaction.set("mark", self._parse_string())
    469
    470                return transaction
    471
    472            return self._parse_as_command(self._prev)
    473
    474        def _parse_returns(self) -> exp.ReturnsProperty:
    475            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
    476            returns = super()._parse_returns()
    477            returns.set("table", table)
    478            return returns
    479
    480        def _parse_convert(
    481            self, strict: bool, safe: t.Optional[bool] = None
    482        ) -> t.Optional[exp.Expression]:
    483            to = self._parse_types()
    484            self._match(TokenType.COMMA)
    485            this = self._parse_conjunction()
    486
    487            if not to or not this:
    488                return None
    489
    490            # Retrieve length of datatype and override to default if not specified
    491            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
    492                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    493
    494            # Check whether a conversion with format is applicable
    495            if self._match(TokenType.COMMA):
    496                format_val = self._parse_number()
    497                format_val_name = format_val.name if format_val else ""
    498
    499                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
    500                    raise ValueError(
    501                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
    502                    )
    503
    504                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
    505
    506                # Check whether the convert entails a string to date format
    507                if to.this == DataType.Type.DATE:
    508                    return self.expression(exp.StrToDate, this=this, format=format_norm)
    509                # Check whether the convert entails a string to datetime format
    510                elif to.this == DataType.Type.DATETIME:
    511                    return self.expression(exp.StrToTime, this=this, format=format_norm)
    512                # Check whether the convert entails a date to string format
    513                elif to.this in self.VAR_LENGTH_DATATYPES:
    514                    return self.expression(
    515                        exp.Cast if strict else exp.TryCast,
    516                        to=to,
    517                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
    518                        safe=safe,
    519                    )
    520                elif to.this == DataType.Type.TEXT:
    521                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
    522
    523            # Entails a simple cast without any format requirement
    524            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
    525
    526        def _parse_user_defined_function(
    527            self, kind: t.Optional[TokenType] = None
    528        ) -> t.Optional[exp.Expression]:
    529            this = super()._parse_user_defined_function(kind=kind)
    530
    531            if (
    532                kind == TokenType.FUNCTION
    533                or isinstance(this, exp.UserDefinedFunction)
    534                or self._match(TokenType.ALIAS, advance=False)
    535            ):
    536                return this
    537
    538            expressions = self._parse_csv(self._parse_function_parameter)
    539            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
    540
    541        def _parse_id_var(
    542            self,
    543            any_token: bool = True,
    544            tokens: t.Optional[t.Collection[TokenType]] = None,
    545        ) -> t.Optional[exp.Expression]:
    546            is_temporary = self._match(TokenType.HASH)
    547            is_global = is_temporary and self._match(TokenType.HASH)
    548
    549            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
    550            if this:
    551                if is_global:
    552                    this.set("global", True)
    553                elif is_temporary:
    554                    this.set("temporary", True)
    555
    556            return this
    557
    558        def _parse_create(self) -> exp.Create | exp.Command:
    559            create = super()._parse_create()
    560
    561            if isinstance(create, exp.Create):
    562                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
    563                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
    564                    if not create.args.get("properties"):
    565                        create.set("properties", exp.Properties(expressions=[]))
    566
    567                    create.args["properties"].append("expressions", exp.TemporaryProperty())
    568
    569            return create
    570
    571        def _parse_if(self) -> t.Optional[exp.Expression]:
    572            index = self._index
    573
    574            if self._match_text_seq("OBJECT_ID"):
    575                self._parse_wrapped_csv(self._parse_string)
    576                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
    577                    return self._parse_drop(exists=True)
    578                self._retreat(index)
    579
    580            return super()._parse_if()
    581
    582        def _parse_unique(self) -> exp.UniqueColumnConstraint:
    583            return self.expression(
    584                exp.UniqueColumnConstraint,
    585                this=None
    586                if self._curr and self._curr.text.upper() in {"CLUSTERED", "NONCLUSTERED"}
    587                else self._parse_schema(self._parse_id_var(any_token=False)),
    588            )
    589
    590    class Generator(generator.Generator):
    591        LIMIT_IS_TOP = True
    592        QUERY_HINTS = False
    593        RETURNING_END = False
    594        NVL2_SUPPORTED = False
    595        ALTER_TABLE_ADD_COLUMN_KEYWORD = False
    596        LIMIT_FETCH = "FETCH"
    597        COMPUTED_COLUMN_WITH_TYPE = False
    598        SUPPORTS_NESTED_CTES = False
    599        CTE_RECURSIVE_KEYWORD_REQUIRED = False
    600
    601        TYPE_MAPPING = {
    602            **generator.Generator.TYPE_MAPPING,
    603            exp.DataType.Type.BOOLEAN: "BIT",
    604            exp.DataType.Type.DECIMAL: "NUMERIC",
    605            exp.DataType.Type.DATETIME: "DATETIME2",
    606            exp.DataType.Type.DOUBLE: "FLOAT",
    607            exp.DataType.Type.INT: "INTEGER",
    608            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
    609            exp.DataType.Type.TIMESTAMP: "DATETIME2",
    610            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
    611            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    612        }
    613
    614        TRANSFORMS = {
    615            **generator.Generator.TRANSFORMS,
    616            exp.AnyValue: any_value_to_max_sql,
    617            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
    618            exp.DateAdd: generate_date_delta_with_unit_sql,
    619            exp.DateDiff: generate_date_delta_with_unit_sql,
    620            exp.CurrentDate: rename_func("GETDATE"),
    621            exp.CurrentTimestamp: rename_func("GETDATE"),
    622            exp.Extract: rename_func("DATEPART"),
    623            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
    624            exp.GroupConcat: _string_agg_sql,
    625            exp.If: rename_func("IIF"),
    626            exp.Max: max_or_greatest,
    627            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    628            exp.Min: min_or_least,
    629            exp.NumberToStr: _format_sql,
    630            exp.Select: transforms.preprocess(
    631                [
    632                    transforms.eliminate_distinct_on,
    633                    transforms.eliminate_semi_and_anti_joins,
    634                    transforms.eliminate_qualify,
    635                ]
    636            ),
    637            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    638            exp.SHA2: lambda self, e: self.func(
    639                "HASHBYTES",
    640                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
    641                e.this,
    642            ),
    643            exp.TemporaryProperty: lambda self, e: "",
    644            exp.TimeStrToTime: timestrtotime_sql,
    645            exp.TimeToStr: _format_sql,
    646            exp.TsOrDsToDate: ts_or_ds_to_date_sql("tsql"),
    647        }
    648
    649        TRANSFORMS.pop(exp.ReturnsProperty)
    650
    651        PROPERTIES_LOCATION = {
    652            **generator.Generator.PROPERTIES_LOCATION,
    653            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    654        }
    655
    656        def setitem_sql(self, expression: exp.SetItem) -> str:
    657            this = expression.this
    658            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
    659                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
    660                return f"{self.sql(this.left)} {self.sql(this.right)}"
    661
    662            return super().setitem_sql(expression)
    663
    664        def boolean_sql(self, expression: exp.Boolean) -> str:
    665            if type(expression.parent) in BIT_TYPES:
    666                return "1" if expression.this else "0"
    667
    668            return "(1 = 1)" if expression.this else "(1 = 0)"
    669
    670        def is_sql(self, expression: exp.Is) -> str:
    671            if isinstance(expression.expression, exp.Boolean):
    672                return self.binary(expression, "=")
    673            return self.binary(expression, "IS")
    674
    675        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    676            sql = self.sql(expression, "this")
    677            properties = expression.args.get("properties")
    678
    679            if sql[:1] != "#" and any(
    680                isinstance(prop, exp.TemporaryProperty)
    681                for prop in (properties.expressions if properties else [])
    682            ):
    683                sql = f"#{sql}"
    684
    685            return sql
    686
    687        def create_sql(self, expression: exp.Create) -> str:
    688            kind = self.sql(expression, "kind").upper()
    689            exists = expression.args.pop("exists", None)
    690            sql = super().create_sql(expression)
    691
    692            table = expression.find(exp.Table)
    693
    694            if kind == "TABLE" and expression.expression:
    695                sql = f"SELECT * INTO {self.sql(table)} FROM ({self.sql(expression.expression)}) AS temp"
    696
    697            if exists:
    698                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    699                sql = self.sql(exp.Literal.string(sql))
    700                if kind == "SCHEMA":
    701                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
    702                elif kind == "TABLE":
    703                    assert table
    704                    where = exp.and_(
    705                        exp.column("table_name").eq(table.name),
    706                        exp.column("table_schema").eq(table.db) if table.db else None,
    707                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
    708                    )
    709                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
    710                elif kind == "INDEX":
    711                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    712                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
    713            elif expression.args.get("replace"):
    714                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    715
    716            return self.prepend_ctes(expression, sql)
    717
    718        def offset_sql(self, expression: exp.Offset) -> str:
    719            return f"{super().offset_sql(expression)} ROWS"
    720
    721        def version_sql(self, expression: exp.Version) -> str:
    722            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    723            this = f"FOR {name}"
    724            expr = expression.expression
    725            kind = expression.text("kind")
    726            if kind in ("FROM", "BETWEEN"):
    727                args = expr.expressions
    728                sep = "TO" if kind == "FROM" else "AND"
    729                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    730            else:
    731                expr_sql = self.sql(expr)
    732
    733            expr_sql = f" {expr_sql}" if expr_sql else ""
    734            return f"{this} {kind}{expr_sql}"
    735
    736        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    737            table = expression.args.get("table")
    738            table = f"{table} " if table else ""
    739            return f"RETURNS {table}{self.sql(expression, 'this')}"
    740
    741        def returning_sql(self, expression: exp.Returning) -> str:
    742            into = self.sql(expression, "into")
    743            into = self.seg(f"INTO {into}") if into else ""
    744            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    745
    746        def transaction_sql(self, expression: exp.Transaction) -> str:
    747            this = self.sql(expression, "this")
    748            this = f" {this}" if this else ""
    749            mark = self.sql(expression, "mark")
    750            mark = f" WITH MARK {mark}" if mark else ""
    751            return f"BEGIN TRANSACTION{this}{mark}"
    752
    753        def commit_sql(self, expression: exp.Commit) -> str:
    754            this = self.sql(expression, "this")
    755            this = f" {this}" if this else ""
    756            durability = expression.args.get("durability")
    757            durability = (
    758                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    759                if durability is not None
    760                else ""
    761            )
    762            return f"COMMIT TRANSACTION{this}{durability}"
    763
    764        def rollback_sql(self, expression: exp.Rollback) -> str:
    765            this = self.sql(expression, "this")
    766            this = f" {this}" if this else ""
    767            return f"ROLLBACK TRANSACTION{this}"
    768
    769        def identifier_sql(self, expression: exp.Identifier) -> str:
    770            identifier = super().identifier_sql(expression)
    771
    772            if expression.args.get("global"):
    773                identifier = f"##{identifier}"
    774            elif expression.args.get("temporary"):
    775                identifier = f"#{identifier}"
    776
    777            return identifier
    778
    779        def constraint_sql(self, expression: exp.Constraint) -> str:
    780            this = self.sql(expression, "this")
    781            expressions = self.expressions(expression, flat=True, sep=" ")
    782            return f"CONSTRAINT {this} {expressions}"

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

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  DPIPE_IS_STRING_CONCAT
  STRICT_STRING_CONCAT
  SUPPORTS_USER_DEFINED_TYPES
  NORMALIZE_FUNCTIONS
  DATE_FORMAT
  DATEINT_FORMAT
  FORMAT_MAPPING
  ESCAPE_SEQUENCES
  PSEUDOCOLUMNS
  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

    320    class Tokenizer(tokens.Tokenizer):
    321        IDENTIFIERS = ['"', ("[", "]")]
    322        QUOTES = ["'", '"']
    323        HEX_STRINGS = [("0x", ""), ("0X", "")]
    324
    325        KEYWORDS = {
    326            **tokens.Tokenizer.KEYWORDS,
    327            "DATETIME2": TokenType.DATETIME,
    328            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
    329            "DECLARE": TokenType.COMMAND,
    330            "IMAGE": TokenType.IMAGE,
    331            "MONEY": TokenType.MONEY,
    332            "NTEXT": TokenType.TEXT,
    333            "NVARCHAR(MAX)": TokenType.TEXT,
    334            "PRINT": TokenType.COMMAND,
    335            "PROC": TokenType.PROCEDURE,
    336            "REAL": TokenType.FLOAT,
    337            "ROWVERSION": TokenType.ROWVERSION,
    338            "SMALLDATETIME": TokenType.DATETIME,
    339            "SMALLMONEY": TokenType.SMALLMONEY,
    340            "SQL_VARIANT": TokenType.VARIANT,
    341            "TOP": TokenType.TOP,
    342            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
    343            "UPDATE STATISTICS": TokenType.COMMAND,
    344            "VARCHAR(MAX)": TokenType.TEXT,
    345            "XML": TokenType.XML,
    346            "OUTPUT": TokenType.RETURNING,
    347            "SYSTEM_USER": TokenType.CURRENT_USER,
    348            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
    349        }

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'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, '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'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, 'NVARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'PRINT': <TokenType.COMMAND: 'COMMAND'>, 'PROC': <TokenType.PROCEDURE: 'PROCEDURE'>, 'ROWVERSION': <TokenType.ROWVERSION: 'ROWVERSION'>, 'SMALLDATETIME': <TokenType.DATETIME: 'DATETIME'>, 'SMALLMONEY': <TokenType.SMALLMONEY: 'SMALLMONEY'>, 'SQL_VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'TOP': <TokenType.TOP: 'TOP'>, 'UNIQUEIDENTIFIER': <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, 'UPDATE STATISTICS': <TokenType.COMMAND: 'COMMAND'>, 'VARCHAR(MAX)': <TokenType.TEXT: 'TEXT'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'FOR SYSTEM_TIME': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>}

##### Inherited Members

sqlglot.tokens.Tokenizer
  SINGLE_TOKENS
  BIT_STRINGS
  BYTE_STRINGS
  RAW_STRINGS
  HEREDOC_STRINGS
  IDENTIFIER_ESCAPES
  STRING_ESCAPES
  VAR_SINGLE_TOKENS
  ESCAPE_SEQUENCES
  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

    351    class Parser(parser.Parser):
    352        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
    353
    354        FUNCTIONS = {
    355            **parser.Parser.FUNCTIONS,
    356            "CHARINDEX": lambda args: exp.StrPosition(
    357                this=seq_get(args, 1),
    358                substr=seq_get(args, 0),
    359                position=seq_get(args, 2),
    360            ),
    361            "DATEADD": parse_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
    362            "DATEDIFF": _parse_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
    363            "DATENAME": _format_time_lambda(exp.TimeToStr, full_format_mapping=True),
    364            "DATEPART": _format_time_lambda(exp.TimeToStr),
    365            "EOMONTH": _parse_eomonth,
    366            "FORMAT": _parse_format,
    367            "GETDATE": exp.CurrentTimestamp.from_arg_list,
    368            "HASHBYTES": _parse_hashbytes,
    369            "IIF": exp.If.from_arg_list,
    370            "ISNULL": exp.Coalesce.from_arg_list,
    371            "JSON_VALUE": exp.JSONExtractScalar.from_arg_list,
    372            "LEN": exp.Length.from_arg_list,
    373            "REPLICATE": exp.Repeat.from_arg_list,
    374            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
    375            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
    376            "SUSER_NAME": exp.CurrentUser.from_arg_list,
    377            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
    378            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
    379        }
    380
    381        JOIN_HINTS = {
    382            "LOOP",
    383            "HASH",
    384            "MERGE",
    385            "REMOTE",
    386        }
    387
    388        VAR_LENGTH_DATATYPES = {
    389            DataType.Type.NVARCHAR,
    390            DataType.Type.VARCHAR,
    391            DataType.Type.CHAR,
    392            DataType.Type.NCHAR,
    393        }
    394
    395        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
    396            TokenType.TABLE,
    397            *parser.Parser.TYPE_TOKENS,
    398        }
    399
    400        STATEMENT_PARSERS = {
    401            **parser.Parser.STATEMENT_PARSERS,
    402            TokenType.END: lambda self: self._parse_command(),
    403        }
    404
    405        LOG_DEFAULTS_TO_LN = True
    406
    407        CONCAT_NULL_OUTPUTS_STRING = True
    408
    409        ALTER_TABLE_ADD_COLUMN_KEYWORD = False
    410
    411        def _parse_projections(self) -> t.List[exp.Expression]:
    412            """
    413            T-SQL supports the syntax alias = expression in the SELECT's projection list,
    414            so we transform all parsed Selects to convert their EQ projections into Aliases.
    415
    416            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
    417            """
    418            return [
    419                exp.alias_(projection.expression, projection.this.this, copy=False)
    420                if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
    421                else projection
    422                for projection in super()._parse_projections()
    423            ]
    424
    425        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
    426            """Applies to SQL Server and Azure SQL Database
    427            COMMIT [ { TRAN | TRANSACTION }
    428                [ transaction_name | @tran_name_variable ] ]
    429                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
    430
    431            ROLLBACK { TRAN | TRANSACTION }
    432                [ transaction_name | @tran_name_variable
    433                | savepoint_name | @savepoint_variable ]
    434            """
    435            rollback = self._prev.token_type == TokenType.ROLLBACK
    436
    437            self._match_texts({"TRAN", "TRANSACTION"})
    438            this = self._parse_id_var()
    439
    440            if rollback:
    441                return self.expression(exp.Rollback, this=this)
    442
    443            durability = None
    444            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
    445                self._match_text_seq("DELAYED_DURABILITY")
    446                self._match(TokenType.EQ)
    447
    448                if self._match_text_seq("OFF"):
    449                    durability = False
    450                else:
    451                    self._match(TokenType.ON)
    452                    durability = True
    453
    454                self._match_r_paren()
    455
    456            return self.expression(exp.Commit, this=this, durability=durability)
    457
    458        def _parse_transaction(self) -> exp.Transaction | exp.Command:
    459            """Applies to SQL Server and Azure SQL Database
    460            BEGIN { TRAN | TRANSACTION }
    461            [ { transaction_name | @tran_name_variable }
    462            [ WITH MARK [ 'description' ] ]
    463            ]
    464            """
    465            if self._match_texts(("TRAN", "TRANSACTION")):
    466                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
    467                if self._match_text_seq("WITH", "MARK"):
    468                    transaction.set("mark", self._parse_string())
    469
    470                return transaction
    471
    472            return self._parse_as_command(self._prev)
    473
    474        def _parse_returns(self) -> exp.ReturnsProperty:
    475            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
    476            returns = super()._parse_returns()
    477            returns.set("table", table)
    478            return returns
    479
    480        def _parse_convert(
    481            self, strict: bool, safe: t.Optional[bool] = None
    482        ) -> t.Optional[exp.Expression]:
    483            to = self._parse_types()
    484            self._match(TokenType.COMMA)
    485            this = self._parse_conjunction()
    486
    487            if not to or not this:
    488                return None
    489
    490            # Retrieve length of datatype and override to default if not specified
    491            if seq_get(to.expressions, 0) is None and to.this in self.VAR_LENGTH_DATATYPES:
    492                to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    493
    494            # Check whether a conversion with format is applicable
    495            if self._match(TokenType.COMMA):
    496                format_val = self._parse_number()
    497                format_val_name = format_val.name if format_val else ""
    498
    499                if format_val_name not in TSQL.CONVERT_FORMAT_MAPPING:
    500                    raise ValueError(
    501                        f"CONVERT function at T-SQL does not support format style {format_val_name}"
    502                    )
    503
    504                format_norm = exp.Literal.string(TSQL.CONVERT_FORMAT_MAPPING[format_val_name])
    505
    506                # Check whether the convert entails a string to date format
    507                if to.this == DataType.Type.DATE:
    508                    return self.expression(exp.StrToDate, this=this, format=format_norm)
    509                # Check whether the convert entails a string to datetime format
    510                elif to.this == DataType.Type.DATETIME:
    511                    return self.expression(exp.StrToTime, this=this, format=format_norm)
    512                # Check whether the convert entails a date to string format
    513                elif to.this in self.VAR_LENGTH_DATATYPES:
    514                    return self.expression(
    515                        exp.Cast if strict else exp.TryCast,
    516                        to=to,
    517                        this=self.expression(exp.TimeToStr, this=this, format=format_norm),
    518                        safe=safe,
    519                    )
    520                elif to.this == DataType.Type.TEXT:
    521                    return self.expression(exp.TimeToStr, this=this, format=format_norm)
    522
    523            # Entails a simple cast without any format requirement
    524            return self.expression(exp.Cast if strict else exp.TryCast, this=this, to=to, safe=safe)
    525
    526        def _parse_user_defined_function(
    527            self, kind: t.Optional[TokenType] = None
    528        ) -> t.Optional[exp.Expression]:
    529            this = super()._parse_user_defined_function(kind=kind)
    530
    531            if (
    532                kind == TokenType.FUNCTION
    533                or isinstance(this, exp.UserDefinedFunction)
    534                or self._match(TokenType.ALIAS, advance=False)
    535            ):
    536                return this
    537
    538            expressions = self._parse_csv(self._parse_function_parameter)
    539            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
    540
    541        def _parse_id_var(
    542            self,
    543            any_token: bool = True,
    544            tokens: t.Optional[t.Collection[TokenType]] = None,
    545        ) -> t.Optional[exp.Expression]:
    546            is_temporary = self._match(TokenType.HASH)
    547            is_global = is_temporary and self._match(TokenType.HASH)
    548
    549            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
    550            if this:
    551                if is_global:
    552                    this.set("global", True)
    553                elif is_temporary:
    554                    this.set("temporary", True)
    555
    556            return this
    557
    558        def _parse_create(self) -> exp.Create | exp.Command:
    559            create = super()._parse_create()
    560
    561            if isinstance(create, exp.Create):
    562                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
    563                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
    564                    if not create.args.get("properties"):
    565                        create.set("properties", exp.Properties(expressions=[]))
    566
    567                    create.args["properties"].append("expressions", exp.TemporaryProperty())
    568
    569            return create
    570
    571        def _parse_if(self) -> t.Optional[exp.Expression]:
    572            index = self._index
    573
    574            if self._match_text_seq("OBJECT_ID"):
    575                self._parse_wrapped_csv(self._parse_string)
    576                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
    577                    return self._parse_drop(exists=True)
    578                self._retreat(index)
    579
    580            return super()._parse_if()
    581
    582        def _parse_unique(self) -> exp.UniqueColumnConstraint:
    583            return self.expression(
    584                exp.UniqueColumnConstraint,
    585                this=None
    586                if self._curr and self._curr.text.upper() in {"CLUSTERED", "NONCLUSTERED"}
    587                else self._parse_schema(self._parse_id_var(any_token=False)),
    588            )

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

###### Arguments:

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

SET_REQUIRES_ASSIGNMENT_DELIMITER = False
FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log'>>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, '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'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function parse_date_delta.<locals>.inner_func>, 'DATENAME': <function _format_time_lambda.<locals>._format_time>, 'DATEPART': <function _format_time_lambda.<locals>._format_time>, 'EOMONTH': <function _parse_eomonth>, 'FORMAT': <function _parse_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _parse_hashbytes>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
JOIN_HINTS = {'LOOP', 'HASH', 'REMOTE', 'MERGE'}
VAR_LENGTH_DATATYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.BEGIN: 'BEGIN'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.DIV: 'DIV'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.USE: 'USE'>, <TokenType.ALL: 'ALL'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.ROW: 'ROW'>, <TokenType.DELETE: 'DELETE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.SEMI: 'SEMI'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.ANTI: 'ANTI'>, <TokenType.FIRST: 'FIRST'>, <TokenType.RANGE: 'RANGE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.CACHE: 'CACHE'>, <TokenType.ANY: 'ANY'>, <TokenType.VAR: 'VAR'>, <TokenType.TOP: 'TOP'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.KILL: 'KILL'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.SOME: 'SOME'>, <TokenType.END: 'END'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.LEFT: 'LEFT'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.ROWS: 'ROWS'>, <TokenType.VIEW: 'VIEW'>, <TokenType.FILTER: 'FILTER'>, <TokenType.KEEP: 'KEEP'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.FALSE: 'FALSE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.SET: 'SET'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.MODEL: 'MODEL'>, <TokenType.CASE: 'CASE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.DESC: 'DESC'>, <TokenType.ASC: 'ASC'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.FULL: 'FULL'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.APPLY: 'APPLY'>, <TokenType.TRUE: 'TRUE'>, <TokenType.IS: 'IS'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.UNIQUE: 'UNIQUE'>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
LOG_DEFAULTS_TO_LN = True
CONCAT_NULL_OUTPUTS_STRING = True
ALTER_TABLE_ADD_COLUMN_KEYWORD = False
TABLE_ALIAS_TOKENS = {<TokenType.INT256: 'INT256'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.NEXT: 'NEXT'>, <TokenType.MAP: 'MAP'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.DIV: 'DIV'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.USE: 'USE'>, <TokenType.ALL: 'ALL'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.ROW: 'ROW'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.INT128: 'INT128'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.LOAD: 'LOAD'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.JSON: 'JSON'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.SEMI: 'SEMI'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ANTI: 'ANTI'>, <TokenType.BIT: 'BIT'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.JSONB: 'JSONB'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.MONEY: 'MONEY'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.ANY: 'ANY'>, <TokenType.CACHE: 'CACHE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.NESTED: 'NESTED'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.NULL: 'NULL'>, <TokenType.VAR: 'VAR'>, <TokenType.TOP: 'TOP'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.TABLE: 'TABLE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.KILL: 'KILL'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.INET: 'INET'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CHAR: 'CHAR'>, <TokenType.INDEX: 'INDEX'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.XML: 'XML'>, <TokenType.SOME: 'SOME'>, <TokenType.END: 'END'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.ENUM: 'ENUM'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.BINARY: 'BINARY'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.VIEW: 'VIEW'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.FILTER: 'FILTER'>, <TokenType.KEEP: 'KEEP'>, <TokenType.UINT128: 'UINT128'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.FALSE: 'FALSE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SET: 'SET'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.MODEL: 'MODEL'>, <TokenType.UUID: 'UUID'>, <TokenType.CASE: 'CASE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.DESC: 'DESC'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.ASC: 'ASC'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.UINT: 'UINT'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.SUPER: 'SUPER'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.IS: 'IS'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.DATE: 'DATE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.INT: 'INT'>, <TokenType.TIME: 'TIME'>, <TokenType.DATETIME64: 'DATETIME64'>}
LOG_BASE_FIRST = False
TOKENIZER_CLASS: Type[sqlglot.tokens.Tokenizer] = <class 'TSQL.Tokenizer'>
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': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
TIME_MAPPING: Dict[str, str] = {'year': '%Y', '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', 'dddd': '%A', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, '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': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  STRUCT_TYPE_TOKENS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  TYPE_TOKENS
  SIGNED_TO_UNSIGNED_TYPE_TOKEN
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  FUNC_TOKENS
  CONJUNCTION
  EQUALITY
  COMPARISON
  BITWISE
  TERM
  FACTOR
  TIMES
  TIMESTAMPS
  SET_OPERATIONS
  JOIN_METHODS
  JOIN_SIDES
  JOIN_KINDS
  LAMBDAS
  COLUMN_OPERATORS
  EXPRESSION_PARSERS
  UNARY_PARSERS
  PRIMARY_PARSERS
  PLACEHOLDER_PARSERS
  RANGE_PARSERS
  PROPERTY_PARSERS
  CONSTRAINT_PARSERS
  ALTER_PARSERS
  SCHEMA_UNNAMED_CONSTRAINTS
  NO_PAREN_FUNCTION_PARSERS
  INVALID_FUNC_NAME_TOKENS
  FUNCTIONS_WITH_ALIASED_ARGS
  FUNCTION_PARSERS
  QUERY_MODIFIER_PARSERS
  SET_PARSERS
  SHOW_PARSERS
  TYPE_LITERAL_PARSERS
  MODIFIABLES
  DDL_SELECT_TOKENS
  PRE_VOLATILE_TOKENS
  TRANSACTION_KIND
  TRANSACTION_CHARACTERISTICS
  INSERT_ALTERNATIVES
  CLONE_KEYWORDS
  CLONE_KINDS
  OPCLASS_FOLLOW_KEYWORDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  FETCH_TOKENS
  ADD_CONSTRAINT_TOKENS
  DISTINCT_TOKENS
  NULL_TOKENS
  UNNEST_OFFSET_ALIAS_TOKENS
  STRICT_CAST
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  TABLESAMPLE_CSV
  TRIM_PATTERN_FIRST
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  SUPPORTS_USER_DEFINED_TYPES
  NORMALIZE_FUNCTIONS
  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

    590    class Generator(generator.Generator):
    591        LIMIT_IS_TOP = True
    592        QUERY_HINTS = False
    593        RETURNING_END = False
    594        NVL2_SUPPORTED = False
    595        ALTER_TABLE_ADD_COLUMN_KEYWORD = False
    596        LIMIT_FETCH = "FETCH"
    597        COMPUTED_COLUMN_WITH_TYPE = False
    598        SUPPORTS_NESTED_CTES = False
    599        CTE_RECURSIVE_KEYWORD_REQUIRED = False
    600
    601        TYPE_MAPPING = {
    602            **generator.Generator.TYPE_MAPPING,
    603            exp.DataType.Type.BOOLEAN: "BIT",
    604            exp.DataType.Type.DECIMAL: "NUMERIC",
    605            exp.DataType.Type.DATETIME: "DATETIME2",
    606            exp.DataType.Type.DOUBLE: "FLOAT",
    607            exp.DataType.Type.INT: "INTEGER",
    608            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
    609            exp.DataType.Type.TIMESTAMP: "DATETIME2",
    610            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
    611            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    612        }
    613
    614        TRANSFORMS = {
    615            **generator.Generator.TRANSFORMS,
    616            exp.AnyValue: any_value_to_max_sql,
    617            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
    618            exp.DateAdd: generate_date_delta_with_unit_sql,
    619            exp.DateDiff: generate_date_delta_with_unit_sql,
    620            exp.CurrentDate: rename_func("GETDATE"),
    621            exp.CurrentTimestamp: rename_func("GETDATE"),
    622            exp.Extract: rename_func("DATEPART"),
    623            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
    624            exp.GroupConcat: _string_agg_sql,
    625            exp.If: rename_func("IIF"),
    626            exp.Max: max_or_greatest,
    627            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    628            exp.Min: min_or_least,
    629            exp.NumberToStr: _format_sql,
    630            exp.Select: transforms.preprocess(
    631                [
    632                    transforms.eliminate_distinct_on,
    633                    transforms.eliminate_semi_and_anti_joins,
    634                    transforms.eliminate_qualify,
    635                ]
    636            ),
    637            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    638            exp.SHA2: lambda self, e: self.func(
    639                "HASHBYTES",
    640                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
    641                e.this,
    642            ),
    643            exp.TemporaryProperty: lambda self, e: "",
    644            exp.TimeStrToTime: timestrtotime_sql,
    645            exp.TimeToStr: _format_sql,
    646            exp.TsOrDsToDate: ts_or_ds_to_date_sql("tsql"),
    647        }
    648
    649        TRANSFORMS.pop(exp.ReturnsProperty)
    650
    651        PROPERTIES_LOCATION = {
    652            **generator.Generator.PROPERTIES_LOCATION,
    653            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    654        }
    655
    656        def setitem_sql(self, expression: exp.SetItem) -> str:
    657            this = expression.this
    658            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
    659                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
    660                return f"{self.sql(this.left)} {self.sql(this.right)}"
    661
    662            return super().setitem_sql(expression)
    663
    664        def boolean_sql(self, expression: exp.Boolean) -> str:
    665            if type(expression.parent) in BIT_TYPES:
    666                return "1" if expression.this else "0"
    667
    668            return "(1 = 1)" if expression.this else "(1 = 0)"
    669
    670        def is_sql(self, expression: exp.Is) -> str:
    671            if isinstance(expression.expression, exp.Boolean):
    672                return self.binary(expression, "=")
    673            return self.binary(expression, "IS")
    674
    675        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    676            sql = self.sql(expression, "this")
    677            properties = expression.args.get("properties")
    678
    679            if sql[:1] != "#" and any(
    680                isinstance(prop, exp.TemporaryProperty)
    681                for prop in (properties.expressions if properties else [])
    682            ):
    683                sql = f"#{sql}"
    684
    685            return sql
    686
    687        def create_sql(self, expression: exp.Create) -> str:
    688            kind = self.sql(expression, "kind").upper()
    689            exists = expression.args.pop("exists", None)
    690            sql = super().create_sql(expression)
    691
    692            table = expression.find(exp.Table)
    693
    694            if kind == "TABLE" and expression.expression:
    695                sql = f"SELECT * INTO {self.sql(table)} FROM ({self.sql(expression.expression)}) AS temp"
    696
    697            if exists:
    698                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    699                sql = self.sql(exp.Literal.string(sql))
    700                if kind == "SCHEMA":
    701                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
    702                elif kind == "TABLE":
    703                    assert table
    704                    where = exp.and_(
    705                        exp.column("table_name").eq(table.name),
    706                        exp.column("table_schema").eq(table.db) if table.db else None,
    707                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
    708                    )
    709                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
    710                elif kind == "INDEX":
    711                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    712                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
    713            elif expression.args.get("replace"):
    714                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    715
    716            return self.prepend_ctes(expression, sql)
    717
    718        def offset_sql(self, expression: exp.Offset) -> str:
    719            return f"{super().offset_sql(expression)} ROWS"
    720
    721        def version_sql(self, expression: exp.Version) -> str:
    722            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    723            this = f"FOR {name}"
    724            expr = expression.expression
    725            kind = expression.text("kind")
    726            if kind in ("FROM", "BETWEEN"):
    727                args = expr.expressions
    728                sep = "TO" if kind == "FROM" else "AND"
    729                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    730            else:
    731                expr_sql = self.sql(expr)
    732
    733            expr_sql = f" {expr_sql}" if expr_sql else ""
    734            return f"{this} {kind}{expr_sql}"
    735
    736        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    737            table = expression.args.get("table")
    738            table = f"{table} " if table else ""
    739            return f"RETURNS {table}{self.sql(expression, 'this')}"
    740
    741        def returning_sql(self, expression: exp.Returning) -> str:
    742            into = self.sql(expression, "into")
    743            into = self.seg(f"INTO {into}") if into else ""
    744            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    745
    746        def transaction_sql(self, expression: exp.Transaction) -> str:
    747            this = self.sql(expression, "this")
    748            this = f" {this}" if this else ""
    749            mark = self.sql(expression, "mark")
    750            mark = f" WITH MARK {mark}" if mark else ""
    751            return f"BEGIN TRANSACTION{this}{mark}"
    752
    753        def commit_sql(self, expression: exp.Commit) -> str:
    754            this = self.sql(expression, "this")
    755            this = f" {this}" if this else ""
    756            durability = expression.args.get("durability")
    757            durability = (
    758                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    759                if durability is not None
    760                else ""
    761            )
    762            return f"COMMIT TRANSACTION{this}{durability}"
    763
    764        def rollback_sql(self, expression: exp.Rollback) -> str:
    765            this = self.sql(expression, "this")
    766            this = f" {this}" if this else ""
    767            return f"ROLLBACK TRANSACTION{this}"
    768
    769        def identifier_sql(self, expression: exp.Identifier) -> str:
    770            identifier = super().identifier_sql(expression)
    771
    772            if expression.args.get("global"):
    773                identifier = f"##{identifier}"
    774            elif expression.args.get("temporary"):
    775                identifier = f"#{identifier}"
    776
    777            return identifier
    778
    779        def constraint_sql(self, expression: exp.Constraint) -> str:
    780            this = self.sql(expression, "this")
    781            expressions = self.expressions(expression, flat=True, sep=" ")
    782            return f"CONSTRAINT {this} {expressions}"

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

###### Arguments:

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

LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_ADD_COLUMN_KEYWORD = False
LIMIT_FETCH = 'FETCH'
COMPUTED_COLUMN_WITH_TYPE = False
SUPPORTS_NESTED_CTES = False
CTE_RECURSIVE_KEYWORD_REQUIRED = False
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.BOOLEAN: 'BOOLEAN'>: 'BIT', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.DOUBLE: 'DOUBLE'>: 'FLOAT', <Type.INT: 'INT'>: 'INTEGER', <Type.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function 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.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.AutoIncrementColumnConstraint'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function 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.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <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.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.TsOrDsToDate'>: <function ts_or_ds_to_date_sql.<locals>._ts_or_ds_to_date_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str: View Source

    656        def setitem_sql(self, expression: exp.SetItem) -> str:
    657            this = expression.this
    658            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
    659                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
    660                return f"{self.sql(this.left)} {self.sql(this.right)}"
    661
    662            return super().setitem_sql(expression)

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

    664        def boolean_sql(self, expression: exp.Boolean) -> str:
    665            if type(expression.parent) in BIT_TYPES:
    666                return "1" if expression.this else "0"
    667
    668            return "(1 = 1)" if expression.this else "(1 = 0)"

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

    670        def is_sql(self, expression: exp.Is) -> str:
    671            if isinstance(expression.expression, exp.Boolean):
    672                return self.binary(expression, "=")
    673            return self.binary(expression, "IS")

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

    675        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    676            sql = self.sql(expression, "this")
    677            properties = expression.args.get("properties")
    678
    679            if sql[:1] != "#" and any(
    680                isinstance(prop, exp.TemporaryProperty)
    681                for prop in (properties.expressions if properties else [])
    682            ):
    683                sql = f"#{sql}"
    684
    685            return sql

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

    687        def create_sql(self, expression: exp.Create) -> str:
    688            kind = self.sql(expression, "kind").upper()
    689            exists = expression.args.pop("exists", None)
    690            sql = super().create_sql(expression)
    691
    692            table = expression.find(exp.Table)
    693
    694            if kind == "TABLE" and expression.expression:
    695                sql = f"SELECT * INTO {self.sql(table)} FROM ({self.sql(expression.expression)}) AS temp"
    696
    697            if exists:
    698                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    699                sql = self.sql(exp.Literal.string(sql))
    700                if kind == "SCHEMA":
    701                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
    702                elif kind == "TABLE":
    703                    assert table
    704                    where = exp.and_(
    705                        exp.column("table_name").eq(table.name),
    706                        exp.column("table_schema").eq(table.db) if table.db else None,
    707                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
    708                    )
    709                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
    710                elif kind == "INDEX":
    711                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    712                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
    713            elif expression.args.get("replace"):
    714                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    715
    716            return self.prepend_ctes(expression, sql)

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

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

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

    721        def version_sql(self, expression: exp.Version) -> str:
    722            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    723            this = f"FOR {name}"
    724            expr = expression.expression
    725            kind = expression.text("kind")
    726            if kind in ("FROM", "BETWEEN"):
    727                args = expr.expressions
    728                sep = "TO" if kind == "FROM" else "AND"
    729                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    730            else:
    731                expr_sql = self.sql(expr)
    732
    733            expr_sql = f" {expr_sql}" if expr_sql else ""
    734            return f"{this} {kind}{expr_sql}"

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

    736        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    737            table = expression.args.get("table")
    738            table = f"{table} " if table else ""
    739            return f"RETURNS {table}{self.sql(expression, 'this')}"

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

    741        def returning_sql(self, expression: exp.Returning) -> str:
    742            into = self.sql(expression, "into")
    743            into = self.seg(f"INTO {into}") if into else ""
    744            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"

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

    746        def transaction_sql(self, expression: exp.Transaction) -> str:
    747            this = self.sql(expression, "this")
    748            this = f" {this}" if this else ""
    749            mark = self.sql(expression, "mark")
    750            mark = f" WITH MARK {mark}" if mark else ""
    751            return f"BEGIN TRANSACTION{this}{mark}"

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

    753        def commit_sql(self, expression: exp.Commit) -> str:
    754            this = self.sql(expression, "this")
    755            this = f" {this}" if this else ""
    756            durability = expression.args.get("durability")
    757            durability = (
    758                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    759                if durability is not None
    760                else ""
    761            )
    762            return f"COMMIT TRANSACTION{this}{durability}"

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

    764        def rollback_sql(self, expression: exp.Rollback) -> str:
    765            this = self.sql(expression, "this")
    766            this = f" {this}" if this else ""
    767            return f"ROLLBACK TRANSACTION{this}"

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

    769        def identifier_sql(self, expression: exp.Identifier) -> str:
    770            identifier = super().identifier_sql(expression)
    771
    772            if expression.args.get("global"):
    773                identifier = f"##{identifier}"
    774            elif expression.args.get("temporary"):
    775                identifier = f"#{identifier}"
    776
    777            return identifier

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

    779        def constraint_sql(self, expression: exp.Constraint) -> str:
    780            this = self.sql(expression, "this")
    781            expressions = self.expressions(expression, flat=True, sep=" ")
    782            return f"CONSTRAINT {this} {expressions}"

LOG_BASE_FIRST = False
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', '%A': 'dddd', '%-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}, 'A': {0: True}, 'H': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
NULL_ORDERING = 'nulls_are_small'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    279    @classmethod
    280    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    281        """Checks if text can be identified given an identify option.
    282
    283        Args:
    284            text: The text to check.
    285            identify:
    286                "always" or `True`: Always returns true.
    287                "safe": True if the identifier is case-insensitive.
    288
    289        Returns:
    290            Whether or not the given text can be identified.
    291        """
    292        if identify is True or identify == "always":
    293            return True
    294
    295        if identify == "safe":
    296            return not cls.case_sensitive(text)
    297
    298        return False

Checks if text can be identified given an identify option.

###### Arguments:

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

###### Returns:

> Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
TOKENIZER_CLASS = <class 'TSQL.Tokenizer'>
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None

##### Inherited Members

sqlglot.generator.Generator
  Generator
  NULL_ORDERING_SUPPORTED
  LOCKING_READS_SUPPORTED
  EXPLICIT_UNION
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  TABLESAMPLE_WITH_METHOD
  TABLESAMPLE_SIZE_IS_PERCENT
  LIMIT_ONLY_LITERALS
  RENAME_TABLE_WITH_DB
  GROUPINGS_SEP
  INDEX_ON
  JOIN_HINTS
  TABLE_HINTS
  QUERY_HINT_SEP
  IS_BOOL_ALLOWED
  DUPLICATE_KEY_UPDATE_WITH_SET
  COLUMN_JOIN_MARKS_SUPPORTED
  EXTRACT_ALLOWS_QUOTES
  TZ_TO_WITH_TIME_ZONE
  VALUES_AS_TABLE
  UNNEST_WITH_ORDINALITY
  AGGREGATE_FILTER_SUPPORTED
  SEMI_ANTI_JOIN_WITH_SIDE
  SUPPORTS_PARAMETERS
  SUPPORTS_TABLE_COPY
  TABLESAMPLE_REQUIRES_PARENS
  COLLATE_IS_FUNC
  DATA_TYPE_SPECIFIERS_ALLOWED
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  EXCLUDE_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
  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
  computedcolumnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypeparam_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_name
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  partitionboundspec_sql
  partitionedofproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  kill_sql
  pseudotype_sql
  objectidentifier_sql
  onconflict_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  connect_sql
  prior_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  safebracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  formatjson_sql
  jsonobject_sql
  jsonarray_sql
  jsonarrayagg_sql
  jsoncolumndef_sql
  jsonschema_sql
  jsontable_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  xor_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  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
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  log_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql
  clusteredbyproperty_sql
  anyvalue_sql
  querytransform_sql
  indexconstraintoption_sql
  indexcolumnconstraint_sql
  nvl2_sql
  comprehension_sql
  columnprefix_sql
  opclass_sql
  predict_sql